/
index.ts
137 lines (116 loc) · 2.82 KB
/
index.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
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
import { namehash } from './namehash'
import { ABI } from './abi'
import { Contract } from '@ethersproject/contracts'
import { BaseProvider, getDefaultProvider } from '@ethersproject/providers'
import assert from 'assert'
export type ENSRecords = {
[key: string]: string
} & Partial<{
avatar: string
github: string
reddit: string
instagram: string
twitter: string
email: string
url: string
description: string
}>
export interface ResolvedENS {
/**
* Owner address
*/
owner: string | null
/**
* Resolved address
*/
address: string | null
/**
* ENS text records
*/
records: ENSRecords
/**
* Reverse lookup domain
*/
domain: string
}
const ENDPOINT = 'https://api.thegraph.com/subgraphs/name/ensdomains/ens'
const QUERY = `
query($domain: String!) {
domains(where:{name: $domain}) {
resolvedAddress {
id
}
resolver {
texts
}
owner {
id
}
}
}
`
const request = async (
endpoint: string,
query: string,
variables: Record<string, any>,
fetchOptions: RequestInit = {}
) => {
const res = await fetch(endpoint, {
...fetchOptions,
body: JSON.stringify({ query, variables }),
method: 'POST'
})
assert.strictEqual(200, res.status)
const json = await res.json()
return json.data
}
/**
*
* @param provider Ethereum provider
* @param contractAddress ENS resolver contract address
* @returns
*/
export const getENS = (
provider: BaseProvider = getDefaultProvider(),
contractAddress: string = '0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41'
) => {
const contract = new Contract(contractAddress, ABI, provider)
const getRecord = async (node: string, record: string) => await contract.text(node, record)
return async function getENS(_domain: string, fetchOptions?: RequestInit): Promise<ResolvedENS> {
const domain = /^0x[a-fA-F0-9]{40}$/.test(_domain) ? await provider.lookupAddress(_domain) : _domain
const node = namehash(domain)
const { domains } = await request(
ENDPOINT,
QUERY,
{
domain
},
fetchOptions
)
const records: ENSRecords = {}
if (domains?.[0]) {
const { resolvedAddress: address, resolver, owner } = domains?.[0]
let data = {
owner: null,
address: null,
domain,
records: {}
}
if (owner) data.owner = owner.id
if (address) data.address = address.id
if (!resolver?.texts) {
return data
} else {
for (const record of resolver.texts) {
if (record.startsWith('com.') || record.startsWith('vnd.')) {
records[record.slice(record.indexOf('.') + 1)] = await getRecord(node, record)
} else {
records[record] = await getRecord(node, record)
}
}
data.records = records
return data
}
}
}
}