0
# ENS Operations
1
2
Ethereum Name Service integration for human-readable address resolution, reverse lookups, domain management, and decentralized naming system interactions.
3
4
## Capabilities
5
6
### ENS Resolution
7
8
Core ENS functionality for resolving names to addresses and vice versa.
9
10
```python { .api }
11
class ENS:
12
def __init__(self, provider: BaseProvider = None):
13
"""
14
Initialize ENS instance.
15
16
Parameters:
17
- provider: Web3 provider for blockchain access
18
"""
19
20
def address(self, name: str) -> ChecksumAddress:
21
"""
22
Resolve ENS name to Ethereum address.
23
24
Parameters:
25
- name: ENS name (e.g., 'ethereum.eth')
26
27
Returns:
28
Ethereum address
29
30
Raises:
31
InvalidName: If name format is invalid
32
UnownedName: If name is not owned
33
"""
34
35
def name(self, address: AnyAddress) -> str:
36
"""
37
Reverse resolve Ethereum address to ENS name.
38
39
Parameters:
40
- address: Ethereum address
41
42
Returns:
43
ENS name if configured, empty string otherwise
44
"""
45
46
def resolver(self, name: str) -> ChecksumAddress:
47
"""
48
Get resolver contract address for ENS name.
49
50
Parameters:
51
- name: ENS name
52
53
Returns:
54
Resolver contract address
55
"""
56
57
def owner(self, name: str) -> ChecksumAddress:
58
"""
59
Get owner address for ENS name.
60
61
Parameters:
62
- name: ENS name
63
64
Returns:
65
Owner address
66
"""
67
```
68
69
### Async ENS Operations
70
71
Async version of ENS operations with the same interface.
72
73
```python { .api }
74
class AsyncENS:
75
def __init__(self, provider: AsyncBaseProvider = None):
76
"""
77
Initialize async ENS instance.
78
79
Parameters:
80
- provider: Async Web3 provider
81
"""
82
83
async def address(self, name: str) -> ChecksumAddress:
84
"""
85
Async resolve ENS name to address.
86
87
Parameters:
88
- name: ENS name
89
90
Returns:
91
Ethereum address
92
"""
93
94
async def name(self, address: AnyAddress) -> str:
95
"""
96
Async reverse resolve address to ENS name.
97
98
Parameters:
99
- address: Ethereum address
100
101
Returns:
102
ENS name
103
"""
104
105
async def resolver(self, name: str) -> ChecksumAddress:
106
"""
107
Async get resolver contract address.
108
109
Parameters:
110
- name: ENS name
111
112
Returns:
113
Resolver contract address
114
"""
115
116
async def owner(self, name: str) -> ChecksumAddress:
117
"""
118
Async get owner address.
119
120
Parameters:
121
- name: ENS name
122
123
Returns:
124
Owner address
125
"""
126
```
127
128
### Base ENS
129
130
Base class providing common ENS functionality.
131
132
```python { .api }
133
class BaseENS:
134
def is_valid_name(self, name: str) -> bool:
135
"""
136
Check if ENS name format is valid.
137
138
Parameters:
139
- name: ENS name to validate
140
141
Returns:
142
True if valid format
143
"""
144
145
def namehash(self, name: str) -> HexBytes:
146
"""
147
Calculate namehash for ENS name.
148
149
Parameters:
150
- name: ENS name
151
152
Returns:
153
Namehash as bytes
154
"""
155
156
def label_to_hash(self, label: str) -> HexBytes:
157
"""
158
Convert label to hash for ENS operations.
159
160
Parameters:
161
- label: ENS label
162
163
Returns:
164
Label hash
165
"""
166
```
167
168
## ENS Exceptions
169
170
ENS-specific exception classes for error handling.
171
172
```python { .api }
173
class AddressMismatch(ValueError):
174
"""Address does not match expected value."""
175
176
class BidTooLow(ValueError):
177
"""Bid amount is too low for auction."""
178
179
class InvalidLabel(ValueError):
180
"""ENS label format is invalid."""
181
182
class InvalidName(ValueError):
183
"""ENS name format is invalid."""
184
185
class UnauthorizedError(ValueError):
186
"""Unauthorized operation on ENS name."""
187
188
class UnderfundedBid(ValueError):
189
"""Insufficient funds for bid."""
190
191
class UnownedName(ValueError):
192
"""ENS name is not owned/registered."""
193
```
194
195
## Usage Examples
196
197
### Basic ENS Resolution
198
199
```python
200
from web3 import Web3
201
from ens import ENS
202
203
# Initialize Web3 and ENS
204
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'))
205
ens = ENS.from_web3(w3)
206
207
# Resolve ENS name to address
208
address = ens.address('ethereum.eth')
209
print(f"ethereum.eth resolves to: {address}")
210
211
# Reverse resolve address to ENS name
212
name = ens.name('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045')
213
print(f"Address resolves to: {name}")
214
215
# Check if name is valid
216
if ens.is_valid_name('test.eth'):
217
print("Valid ENS name format")
218
```
219
220
### ENS with Web3 Integration
221
222
```python
223
from web3 import Web3
224
225
# ENS middleware is included by default
226
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'))
227
228
# Use ENS names directly in Web3 operations
229
balance = w3.eth.get_balance('ethereum.eth')
230
print(f"Balance for ethereum.eth: {w3.from_wei(balance, 'ether')} ETH")
231
232
# Send transaction to ENS name
233
transaction = {
234
'from': w3.eth.accounts[0],
235
'to': 'recipient.eth', # ENS name resolved automatically
236
'value': w3.to_wei(1, 'ether'),
237
'gas': 21000,
238
'gasPrice': w3.to_wei(20, 'gwei')
239
}
240
241
tx_hash = w3.eth.send_transaction(transaction)
242
```
243
244
### Advanced ENS Operations
245
246
```python
247
from web3 import Web3
248
from ens import ENS
249
250
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'))
251
ens = ENS.from_web3(w3)
252
253
# Get ENS name owner
254
owner = ens.owner('example.eth')
255
print(f"Owner of example.eth: {owner}")
256
257
# Get resolver contract
258
resolver_address = ens.resolver('example.eth')
259
print(f"Resolver for example.eth: {resolver_address}")
260
261
# Calculate namehash
262
namehash = ens.namehash('subdomain.example.eth')
263
print(f"Namehash: {namehash.hex()}")
264
265
# Validate name format
266
names_to_check = ['valid.eth', 'invalid..eth', 'toolong.eth']
267
for name in names_to_check:
268
if ens.is_valid_name(name):
269
print(f"{name} is valid")
270
else:
271
print(f"{name} is invalid")
272
```
273
274
### Error Handling
275
276
```python
277
from web3 import Web3
278
from ens import ENS
279
from ens.exceptions import InvalidName, UnownedName
280
281
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'))
282
ens = ENS.from_web3(w3)
283
284
try:
285
# Try to resolve unregistered name
286
address = ens.address('nonexistent-name-12345.eth')
287
print(f"Address: {address}")
288
except UnownedName:
289
print("ENS name is not registered")
290
except InvalidName:
291
print("Invalid ENS name format")
292
293
try:
294
# Try invalid name format
295
address = ens.address('invalid..name.eth')
296
except InvalidName as e:
297
print(f"Invalid name: {e}")
298
```
299
300
### Async ENS Operations
301
302
```python
303
import asyncio
304
from web3 import AsyncWeb3
305
from ens import AsyncENS
306
307
async def main():
308
w3 = AsyncWeb3(AsyncWeb3.AsyncHTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'))
309
ens = AsyncENS.from_web3(w3)
310
311
# Async ENS resolution
312
address = await ens.address('ethereum.eth')
313
print(f"ethereum.eth resolves to: {address}")
314
315
# Async reverse resolution
316
name = await ens.name('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045')
317
print(f"Address resolves to: {name}")
318
319
# Get owner asynchronously
320
owner = await ens.owner('ethereum.eth')
321
print(f"Owner: {owner}")
322
323
asyncio.run(main())
324
```
325
326
### Custom ENS Resolver
327
328
```python
329
from web3 import Web3
330
from ens import ENS
331
332
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'))
333
334
# Connect to specific ENS registry
335
custom_ens = ENS(
336
provider=w3.provider,
337
addr='0x314159265dd8dbb310642f98f50c066173c1259b' # Custom ENS registry
338
)
339
340
# Use custom ENS instance
341
try:
342
address = custom_ens.address('example.eth')
343
print(f"Resolved via custom ENS: {address}")
344
except Exception as e:
345
print(f"Resolution failed: {e}")
346
```
347
348
### Batch ENS Operations
349
350
```python
351
from web3 import Web3
352
from ens import ENS
353
from ens.exceptions import UnownedName
354
355
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'))
356
ens = ENS.from_web3(w3)
357
358
# Batch resolve multiple names
359
names = ['ethereum.eth', 'ens.eth', 'example.eth']
360
addresses = {}
361
362
for name in names:
363
try:
364
address = ens.address(name)
365
addresses[name] = address
366
print(f"{name} -> {address}")
367
except UnownedName:
368
print(f"{name} is not registered")
369
except Exception as e:
370
print(f"Error resolving {name}: {e}")
371
372
print(f"Successfully resolved {len(addresses)} names")
373
```