-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathens.ts
74 lines (68 loc) · 2.6 KB
/
ens.ts
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
import { keccak_256 } from '@noble/hashes/sha3';
import { concatBytes } from '@noble/hashes/utils';
import { createContract } from '../abi/decoder.js';
import { IWeb3Provider, strip0x } from '../utils.js';
// No support for IDN names
export function namehash(address: string): Uint8Array {
let res = new Uint8Array(32);
if (!address) return res;
for (let label of address.split('.').reverse())
res = keccak_256(concatBytes(res, keccak_256(label)));
return res;
}
export default class ENS {
static ADDRESS_ZERO = '0x0000000000000000000000000000000000000000';
static REGISTRY = '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e';
static REGISTRY_CONTRACT = [
{
name: 'resolver',
type: 'function',
inputs: [{ name: 'node', type: 'bytes32' }],
outputs: [{ type: 'address' }],
},
] as const;
static RESOLVER_CONTRACT = [
{
name: 'addr',
type: 'function',
inputs: [{ name: 'node', type: 'bytes32' }],
outputs: [{ type: 'address' }],
},
{
name: 'name',
type: 'function',
inputs: [{ name: 'node', type: 'bytes32' }],
outputs: [{ type: 'string' }],
},
] as const;
constructor(readonly net: IWeb3Provider) {}
async getResolver(name: string): Promise<string | undefined> {
const contract = createContract(ENS.REGISTRY_CONTRACT, this.net, ENS.REGISTRY);
const res = await contract.resolver.call(namehash(name));
if (res === ENS.ADDRESS_ZERO) return;
return res;
}
async nameToAddress(name: string): Promise<string | undefined> {
const resolver = await this.getResolver(name);
if (!resolver) return;
const contract = createContract(ENS.RESOLVER_CONTRACT, this.net, resolver);
const addr = await contract.addr.call(namehash(name));
if (addr === ENS.ADDRESS_ZERO) return;
return addr;
}
async addressToName(address: string): Promise<string | undefined> {
const addrDomain = `${strip0x(address).toLowerCase()}.addr.reverse`;
const resolver = await this.getResolver(addrDomain);
if (!resolver) return;
const contract = createContract(ENS.RESOLVER_CONTRACT, this.net, resolver);
const name = await contract.name.call(namehash(addrDomain));
if (!name) return;
// From spec: ENS does not enforce accuracy of reverse records -
// anyone may claim that the name for their address is 'alice.eth'.
// To be certain the claim is accurate, you must always perform a forward
// resolution for the returned name and check whether it matches the original address.
const realAddr = await this.nameToAddress(name);
if (realAddr !== address) return;
return name;
}
}