alloy-ens 2.0.0

Ethereum Name Service utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
#![doc = include_str!("../README.md")]
#![doc(
    html_logo_url = "https://raw.githubusercontent.com/alloy-rs/core/main/assets/alloy.jpg",
    html_favicon_url = "https://raw.githubusercontent.com/alloy-rs/core/main/assets/favicon.ico"
)]
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
#![cfg_attr(docsrs, feature(doc_cfg))]

//! ENS Name resolving utilities.

use alloy_primitives::{address, Address, Keccak256, B256};
use std::{borrow::Cow, str::FromStr};

/// ENS registry address (`0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e`)
pub const ENS_ADDRESS: Address = address!("0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e");

/// ENS Universal Resolver address on Ethereum Mainnet
/// (`0xeeeeeeee14d718c2b47d9923deab1335e144eeee`)
///
/// The Universal Resolver is the canonical entry point for all ENS resolution.
pub const UNIVERSAL_RESOLVER_ADDRESS: Address =
    address!("0xeeeeeeee14d718c2b47d9923deab1335e144eeee");

/// ENS const for registrar domain
pub const ENS_REVERSE_REGISTRAR_DOMAIN: &str = "addr.reverse";

#[cfg(feature = "contract")]
pub use contract::*;

#[cfg(feature = "provider")]
pub use provider::*;

/// ENS name or Ethereum Address.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NameOrAddress {
    /// An ENS Name (format does not get checked)
    Name(String),
    /// An Ethereum Address
    Address(Address),
}

impl NameOrAddress {
    /// Resolves the name to an Ethereum Address.
    #[cfg(feature = "provider")]
    pub async fn resolve<N: alloy_provider::Network, P: alloy_provider::Provider<N>>(
        &self,
        provider: &P,
    ) -> Result<Address, EnsError> {
        match self {
            Self::Name(name) => provider.resolve_name(name).await,
            Self::Address(addr) => Ok(*addr),
        }
    }
}

impl From<String> for NameOrAddress {
    fn from(name: String) -> Self {
        Self::Name(name)
    }
}

impl From<&String> for NameOrAddress {
    fn from(name: &String) -> Self {
        Self::Name(name.clone())
    }
}

impl From<Address> for NameOrAddress {
    fn from(addr: Address) -> Self {
        Self::Address(addr)
    }
}

impl FromStr for NameOrAddress {
    type Err = <Address as FromStr>::Err;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match Address::from_str(s) {
            Ok(addr) => Ok(Self::Address(addr)),
            Err(err) => {
                if s.contains('.') {
                    Ok(Self::Name(s.to_string()))
                } else {
                    Err(err)
                }
            }
        }
    }
}

#[cfg(feature = "contract")]
mod contract {
    use alloy_sol_types::sol;

    // ENS Registry and Resolver contracts.
    sol! {
        /// ENS Registry contract.
        #[sol(rpc)]
        contract EnsRegistry {
            /// Returns the resolver for the specified node.
            function resolver(bytes32 node) view returns (address);

            /// returns the owner of this node
            function owner(bytes32 node) view returns (address);
        }

        /// ENS Resolver interface.
        #[sol(rpc)]
        contract EnsResolver {
            /// Returns the address associated with the specified node.
            function addr(bytes32 node) view returns (address);

            /// Returns the name associated with an ENS node, for reverse records.
            function name(bytes32 node) view returns (string);

            /// Returns the txt associated with an ENS node
            function text(bytes32 node,string calldata key) view virtual returns (string memory);
        }

        /// ENS Universal Resolver contract.
        ///
        /// The Universal Resolver is the canonical entry point for ENS resolution.
        /// It handles CCIP-Read (EIP-3668) for offchain/cross-chain names and
        /// supports all name types including DNS names.
        #[sol(rpc)]
        contract UniversalResolver {
            /// Resolves an ENS name with the given encoded resolver call data.
            function resolve(bytes calldata name, bytes calldata data) external view returns (bytes memory, address);

            /// Performs reverse resolution for an address.
            function reverse(bytes calldata reverseName) external view returns (string memory, address, address, address);
        }

        /// ENS Reverse Registrar contract
        #[sol(rpc)]
        contract ReverseRegistrar {}
    }

    /// Error type for ENS resolution.
    #[derive(Debug, thiserror::Error)]
    pub enum EnsError {
        /// Failed to get resolver from the ENS registry.
        #[error("Failed to get resolver from the ENS registry: {0}")]
        Resolver(alloy_contract::Error),
        /// Failed to get resolver from the ENS registry.
        #[error("ENS resolver not found for name {0:?}")]
        ResolverNotFound(String),
        /// Failed to get reverse registrar from the ENS registry.
        #[error("Failed to get reverse registrar from the ENS registry: {0}")]
        RevRegistrar(alloy_contract::Error),
        /// Failed to get reverse registrar from the ENS registry.
        #[error("ENS reverse registrar not found for addr.reverse")]
        ReverseRegistrarNotFound,
        /// Failed to lookup ENS name from an address.
        #[error("Failed to lookup ENS name from an address: {0}")]
        Lookup(alloy_contract::Error),
        /// Failed to resolve ENS name to an address.
        #[error("Failed to resolve ENS name to an address: {0}")]
        Resolve(alloy_contract::Error),
        /// Failed to get txt records of ENS name.
        #[error("Failed to resolve txt record: {0}")]
        ResolveTxtRecord(alloy_contract::Error),
    }
}

#[cfg(feature = "provider")]
mod provider {
    use crate::{
        dns_encode, namehash, reverse_address, EnsError, EnsRegistry, EnsResolver,
        EnsResolver::EnsResolverInstance, ReverseRegistrar::ReverseRegistrarInstance,
        UniversalResolver, ENS_ADDRESS, ENS_REVERSE_REGISTRAR_DOMAIN, UNIVERSAL_RESOLVER_ADDRESS,
    };
    use alloy_primitives::{Address, Bytes, B256};
    use alloy_provider::{Network, Provider};
    use alloy_sol_types::SolCall;

    /// Extension trait for ENS contract calls.
    #[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]
    #[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]
    pub trait ProviderEnsExt<N: alloy_provider::Network, P: Provider<N>> {
        /// Returns the resolver for the specified node. The `&str` is only used for error messages.
        async fn get_resolver(
            &self,
            node: B256,
            error_name: &str,
        ) -> Result<EnsResolverInstance<&P, N>, EnsError>;

        /// Returns the reverse registrar for the specified node.
        async fn get_reverse_registrar(&self) -> Result<ReverseRegistrarInstance<&P, N>, EnsError>;

        /// Performs a forward lookup of an ENS name to an address using the Universal Resolver.
        async fn resolve_name(&self, name: &str) -> Result<Address, EnsError>;

        /// Performs a reverse lookup of an address to an ENS name.
        async fn lookup_address(&self, address: &Address) -> Result<String, EnsError>;

        /// Performs a txt lookup of an ENS name.
        async fn lookup_txt(&self, name: &str, key: &str) -> Result<String, EnsError>;
    }

    #[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]
    #[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]
    impl<N, P> ProviderEnsExt<N, P> for P
    where
        P: Provider<N>,
        N: Network,
    {
        async fn get_resolver(
            &self,
            node: B256,
            error_name: &str,
        ) -> Result<EnsResolverInstance<&P, N>, EnsError> {
            let registry = EnsRegistry::new(ENS_ADDRESS, self);
            let address = registry.resolver(node).call().await.map_err(EnsError::Resolver)?;
            if address == Address::ZERO {
                return Err(EnsError::ResolverNotFound(error_name.to_string()));
            }
            Ok(EnsResolverInstance::new(address, self))
        }

        async fn get_reverse_registrar(&self) -> Result<ReverseRegistrarInstance<&P, N>, EnsError> {
            let registry = EnsRegistry::new(ENS_ADDRESS, self);
            let address = registry
                .owner(namehash(ENS_REVERSE_REGISTRAR_DOMAIN))
                .call()
                .await
                .map_err(EnsError::RevRegistrar)?;
            if address == Address::ZERO {
                return Err(EnsError::ReverseRegistrarNotFound);
            }
            Ok(ReverseRegistrarInstance::new(address, self))
        }

        async fn resolve_name(&self, name: &str) -> Result<Address, EnsError> {
            let dns_name = dns_encode(name);
            let node = namehash(name);
            let addr_call = EnsResolver::addrCall { node };
            let call_data = Bytes::from(EnsResolver::addrCall::abi_encode(&addr_call));

            let ur = UniversalResolver::new(UNIVERSAL_RESOLVER_ADDRESS, self);
            let result = ur
                .resolve(Bytes::from(dns_name), call_data)
                .call()
                .await
                .map_err(EnsError::Resolve)?;

            let result_bytes = result._0;
            if result_bytes.len() < 32 {
                return Err(EnsError::ResolverNotFound(name.to_string()));
            }
            let addr = Address::from_slice(&result_bytes[result_bytes.len() - 20..]);
            Ok(addr)
        }

        async fn lookup_address(&self, address: &Address) -> Result<String, EnsError> {
            let name = reverse_address(address);
            let node = namehash(&name);
            let resolver = self.get_resolver(node, &name).await?;
            let name = resolver.name(node).call().await.map_err(EnsError::Lookup)?;
            Ok(name)
        }

        async fn lookup_txt(&self, name: &str, key: &str) -> Result<String, EnsError> {
            let node = namehash(name);
            let resolver = self.get_resolver(node, name).await?;
            let txt_value = resolver
                .text(node, key.to_string())
                .call()
                .await
                .map_err(EnsError::ResolveTxtRecord)?;
            Ok(txt_value)
        }
    }
}

/// Returns the ENS namehash as specified in [EIP-137](https://eips.ethereum.org/EIPS/eip-137)
pub fn namehash(name: &str) -> B256 {
    if name.is_empty() {
        return B256::ZERO;
    }

    // Remove the variation selector `U+FE0F` if present.
    const VARIATION_SELECTOR: char = '\u{fe0f}';
    let name = if name.contains(VARIATION_SELECTOR) {
        Cow::Owned(name.replace(VARIATION_SELECTOR, ""))
    } else {
        Cow::Borrowed(name)
    };

    // Generate the node starting from the right.
    // This buffer is `[node @ [u8; 32], label_hash @ [u8; 32]]`.
    let mut buffer = [0u8; 64];
    for label in name.rsplit('.') {
        // node = keccak256([node, keccak256(label)])

        // Hash the label.
        let mut label_hasher = Keccak256::new();
        label_hasher.update(label.as_bytes());
        label_hasher.finalize_into(&mut buffer[32..]);

        // Hash both the node and the label hash, writing into the node.
        let mut buffer_hasher = Keccak256::new();
        buffer_hasher.update(buffer.as_slice());
        buffer_hasher.finalize_into(&mut buffer[..32]);
    }
    buffer[..32].try_into().unwrap()
}

/// Encodes a domain name into DNS wire format as specified in
/// [RFC 1035](https://datatracker.ietf.org/doc/html/rfc1035).
///
/// Each label is prefixed with its length byte, and the name is terminated with a
/// zero-length label (null byte).
///
/// # Examples
///
/// ```
/// use alloy_ens::dns_encode;
/// assert_eq!(dns_encode("eth"), vec![3, b'e', b't', b'h', 0]);
/// assert_eq!(
///     dns_encode("vitalik.eth"),
///     vec![7, b'v', b'i', b't', b'a', b'l', b'i', b'k', 3, b'e', b't', b'h', 0]
/// );
/// ```
pub fn dns_encode(name: &str) -> Vec<u8> {
    let mut result = Vec::with_capacity(name.len() + 2);
    for label in name.split('.') {
        result.push(label.len() as u8);
        result.extend_from_slice(label.as_bytes());
    }
    result.push(0);
    result
}

/// Returns the reverse-registrar name of an address.
pub fn reverse_address(addr: &Address) -> String {
    format!("{addr:x}.{ENS_REVERSE_REGISTRAR_DOMAIN}")
}

#[cfg(test)]
mod test {
    use super::*;
    use alloy_primitives::hex;

    fn assert_hex(hash: B256, val: &str) {
        assert_eq!(hash.0[..], hex::decode(val).unwrap()[..]);
    }

    #[test]
    fn test_namehash() {
        for (name, expected) in &[
            ("", "0x0000000000000000000000000000000000000000000000000000000000000000"),
            ("eth", "0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae"),
            ("foo.eth", "0xde9b09fd7c5f901e23a3f19fecc54828e9c848539801e86591bd9801b019f84f"),
            ("alice.eth", "0x787192fc5378cc32aa956ddfdedbf26b24e8d78e40109add0eea2c1a012c3dec"),
            ("ret↩️rn.eth", "0x3de5f4c02db61b221e7de7f1c40e29b6e2f07eb48d65bf7e304715cd9ed33b24"),
        ] {
            assert_hex(namehash(name), expected);
        }
    }

    #[test]
    fn test_dns_encode() {
        assert_eq!(dns_encode("eth"), vec![3, b'e', b't', b'h', 0]);
        assert_eq!(
            dns_encode("vitalik.eth"),
            vec![7, b'v', b'i', b't', b'a', b'l', b'i', b'k', 3, b'e', b't', b'h', 0]
        );
    }

    #[test]
    fn test_reverse_address() {
        for (addr, expected) in [
            (
                "0x314159265dd8dbb310642f98f50c066173c1259b",
                "314159265dd8dbb310642f98f50c066173c1259b.addr.reverse",
            ),
            (
                "0x28679A1a632125fbBf7A68d850E50623194A709E",
                "28679a1a632125fbbf7a68d850e50623194a709e.addr.reverse",
            ),
        ] {
            assert_eq!(reverse_address(&addr.parse().unwrap()), expected, "{addr}");
        }
    }

    #[test]
    fn test_invalid_address() {
        for addr in [
            "0x314618",
            "0x000000000000000000000000000000000000000", // 41
            "0x00000000000000000000000000000000000000000", // 43
            "0x28679A1a632125fbBf7A68d850E50623194A709E123", // 44
        ] {
            assert!(NameOrAddress::from_str(addr).is_err());
        }
    }
}

#[cfg(all(test, feature = "provider"))]
mod tests {
    use super::*;
    use alloy_primitives::address;
    use alloy_provider::ProviderBuilder;

    #[tokio::test]
    async fn test_reverse_registrar_fetching_mainnet() {
        let provider = ProviderBuilder::new()
            .connect_http("https://reth-ethereum.ithaca.xyz/rpc".parse().unwrap());

        let res = provider.get_reverse_registrar().await;
        assert_eq!(*res.unwrap().address(), address!("0xa58E81fe9b61B5c3fE2AFD33CF304c454AbFc7Cb"));
    }

    #[tokio::test]
    async fn test_pub_resolver_fetching_mainnet() {
        let provider = ProviderBuilder::new()
            .connect_http("https://reth-ethereum.ithaca.xyz/rpc".parse().unwrap());

        let name = "vitalik.eth";
        let node = namehash(name);
        let res = provider.get_resolver(node, name).await;
        assert_eq!(*res.unwrap().address(), address!("0x231b0Ee14048e9dCcD1d247744d114a4EB5E8E63"));
    }

    #[tokio::test]
    async fn test_resolve_name_via_universal_resolver() {
        let provider = ProviderBuilder::new()
            .connect_http("https://reth-ethereum.ithaca.xyz/rpc".parse().unwrap());

        let addr = provider.resolve_name("ur.integration-tests.eth").await.unwrap();
        assert_eq!(addr, address!("0x2222222222222222222222222222222222222222"));
    }

    #[tokio::test]
    async fn test_lookup_address_via_universal_resolver() {
        let provider = ProviderBuilder::new()
            .connect_http("https://reth-ethereum.ithaca.xyz/rpc".parse().unwrap());

        let name = provider
            .lookup_address(&address!("0xeE9eeaAB0Bb7D9B969D701f6f8212609EDeA252E"))
            .await
            .unwrap();
        assert_eq!(name, "devrel.enslabs.eth");
    }

    #[tokio::test]
    async fn test_lookup_txt_via_universal_resolver() {
        let provider = ProviderBuilder::new()
            .connect_http("https://reth-ethereum.ithaca.xyz/rpc".parse().unwrap());

        let avatar = provider.lookup_txt("integration-tests.eth", "avatar").await.unwrap();
        assert_eq!(
            avatar,
            "https://raw.githubusercontent.com/ensdomains/resolution-tests/refs/heads/main/assets/avatar.svg"
        );
    }

    #[tokio::test]
    async fn test_pub_resolver_text() {
        let provider = ProviderBuilder::new()
            .connect_http("http://reth-ethereum.ithaca.xyz/rpc".parse().unwrap());

        let name = "vitalik.eth";
        let node = namehash(name);
        let res = provider.get_resolver(node, name).await.unwrap();
        let txt = res.text(node, "avatar".to_string()).call().await.unwrap();
        assert_eq!(txt, "https://euc.li/vitalik.eth")
    }

    #[tokio::test]
    async fn test_pub_resolver_fetching_txt() {
        let provider = ProviderBuilder::new()
            .connect_http("http://reth-ethereum.ithaca.xyz/rpc".parse().unwrap());

        let name = "vitalik.eth";
        let res = provider.lookup_txt(name, "avatar").await.unwrap();
        assert_eq!(res, "https://euc.li/vitalik.eth")
    }
}