/
zns.ts
383 lines (352 loc) · 11 KB
/
zns.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
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
import {
fromBech32Address,
toBech32Address,
toChecksumAddress,
} from './zns/utils';
import namehash, { childhash } from './zns/namehash';
import { invert, set } from './utils';
import {
Dictionary,
ResolutionResponse,
SourceDefinition,
UnclaimedDomainResponse,
ZnsResolution,
NamingServiceSource,
NamingServiceName,
isNullAddress,
nodeHash,
} from './types';
import { ResolutionError, ResolutionErrorCode } from './index';
import NamingService from './namingService';
const DefaultSource = 'https://api.zilliqa.com';
const NetworkIdMap = {
1: 'mainnet',
333: 'testnet',
111: 'localnet',
};
const RegistryMap = {
mainnet: 'zil1jcgu2wlx6xejqk9jw3aaankw6lsjzeunx2j0jz',
};
const UrlMap = {
mainnet: 'https://api.zilliqa.com',
testnet: 'https://dev-api.zilliqa.com',
localnet: 'http://localhost:4201',
};
const UrlNetworkMap = (url: string) => invert(UrlMap)[url];
/**
* Class to support connection with Zilliqa naming service
* @param network - network string such as
* - mainnet
* - ropsten
* @param url - main api url such as
* - https://mainnet.infura.io
* @param registryAddress - address for a registry contract
*/
export default class Zns extends NamingService {
readonly name = NamingServiceName.ZNS;
readonly network: string;
readonly url: string;
readonly registryAddress?: string;
/**
* Source object describing the network naming service operates on
* @param source - if specified as a string will be used as main url, if omitted then defaults are used
* @throws ConfigurationError - when either network or url is setup incorrectly
*/
constructor(source: string | boolean | SourceDefinition = true) {
super();
source = this.normalizeSource(source);
this.network = source.network as string;
this.url = source.url;
if (!this.network) {
throw new Error('Unspecified network in Resolution ZNS configuration');
}
if (!this.url) {
throw new Error('Unspecified url in Resolution ZNS configuration');
}
this.registryAddress = source.registry
? source.registry
: RegistryMap[this.network];
if (this.registryAddress) {
this.registryAddress = this.registryAddress.startsWith('0x')
? toBech32Address(this.registryAddress)
: this.registryAddress;
}
}
/**
* Resolves the domain name
* @param domain - domain name to be resolved
* @returns A promise that resolves in a detailed crypto Resolution
*/
async resolve(domain: string): Promise<ResolutionResponse | null> {
const recordAddresses = await this.getRecordsAddresses(domain);
if (!recordAddresses) return UnclaimedDomainResponse;
const [ownerAddress, resolverAddress] = recordAddresses;
const Resolution = this.structureResolverRecords(
await this.getResolverRecords(resolverAddress),
);
const addresses = {};
Object.entries(Resolution.crypto).map(
([key, v]) => (addresses[key] = v.address),
);
return {
addresses,
meta: {
owner: ownerAddress || null,
type: this.name,
ttl: parseInt(Resolution.ttl as string) || 0,
},
};
}
/**
* Resolves domain name to a particular crypto address associated with it
* @param domain - domain name to be resolved
* @param currencyTicker - specific currency ticker such as
* - ZIL
* - BTC
* - ETH
* @returns A promise that resolves in a string
* @throws ResolutionError
*/
async address(domain: string, currencyTicker: string): Promise<string> {
const data = await this.resolve(domain);
if (!data.meta.owner || isNullAddress(data.meta.owner))
throw new ResolutionError(ResolutionErrorCode.UnregisteredDomain, {
domain,
});
const address = data.addresses[currencyTicker.toUpperCase()];
if (!address)
throw new ResolutionError(ResolutionErrorCode.UnspecifiedCurrency, {
domain,
currencyTicker,
});
return address;
}
/**
* Owner of the domain
* @param domain - domain name
* @returns An owner address of the domain
*/
async owner(domain: string): Promise<string | null> {
return (await this.resolve(domain)).meta.owner;
}
/**
* Resolves a domain
* @param domain - domain name to be resolved
* @returns Everything what is stored on specified domain
*/
async Resolution(domain: string): Promise<ZnsResolution> {
return this.structureResolverRecords(await this.records(domain));
}
async ipfsHash(domain: string): Promise<string> {
return await this.getRecordOrThrow(domain, 'ipfs.html.value');
}
async httpUrl(domain: string): Promise<string> {
return await this.getRecordOrThrow(domain, 'ipfs.redirect_domain.value');
}
async email(domain: string): Promise<string> {
return await this.getRecordOrThrow(domain, 'whois.email.value');
}
/**
* Resolves a specific field from domain's record
* @param domain - domain name
* @param field - resolver record name to be queried
* @returns Record field associated with the domain
*/
async record(domain: string, field: string) {
return await this.getRecordOrThrow(domain, field);
}
/**
* Resolver Records
* @param domain - domain name to be resolved
* @returns ZNS resolver records in an plain key-value format
*/
async records(domain: string): Promise<Dictionary<string>> {
return await this.getResolverRecords(await this.resolverAddress(domain));
}
/**
* Checks if domain is supported by zns
*/
isSupportedDomain(domain: string): boolean {
const tokens = domain.split('.');
return tokens.length && tokens[tokens.length - 1] === 'zil';
}
/**
* Checks if zns is supported by current Resolution instance
*/
isSupportedNetwork(): boolean {
return this.registryAddress != null;
}
/**
* Produces ZNS namehash of a domain
* @param domain - domain name to be hashed
* @returns ZNS namehash
*/
namehash(domain: string): string {
this.ensureSupportedDomain(domain);
return namehash(domain);
}
/**
* Returns the childhash
* @param parent - nodehash of a parent
* @param label - child
*/
childhash(parent: nodeHash, label: string): string {
return childhash(parent, label);
}
/**
* get the resolver address from domain
* @param domain - domain name
* @throws ResolutionError with codes
* - UnregisteredDomain if there is no owner for such a domain
* - UnspecifiedResolver if there is no resolver for such a domain
*/
async resolver(domain: string): Promise<string> {
const recordsAddresses = await this.getRecordsAddresses(domain);
if (!recordsAddresses || !recordsAddresses[0])
throw new ResolutionError(ResolutionErrorCode.UnregisteredDomain, {
domain: domain,
});
const [_, resolverAddress] = recordsAddresses;
if (!resolverAddress || isNullAddress(resolverAddress))
throw new ResolutionError(ResolutionErrorCode.UnspecifiedResolver, {
domain: domain,
});
return resolverAddress;
}
/** @internal */
protected normalizeSource(source: NamingServiceSource): SourceDefinition {
switch (typeof source) {
case 'boolean': {
return { url: DefaultSource, network: 'mainnet' };
}
case 'string': {
return {
url: source as string,
network: UrlNetworkMap(source),
};
}
case 'object': {
source = { ...source };
if (typeof source.network == 'number') {
source.network = NetworkIdMap[source.network];
}
if (source.registry) {
source.network = source.network ? source.network : 'mainnet';
source.url = source.url ? source.url : DefaultSource;
}
if (source.network && !source.url) {
source.url = UrlMap[source.network];
}
if (source.url && !source.network) {
source.network = UrlNetworkMap(source.url);
}
return source;
}
}
}
private async getRecordOrThrow(
domain: string,
field: string,
): Promise<string> {
const records = await this.records(domain);
return this.getRecordFieldOrThrow(domain, records, field);
}
private getRecordFieldOrThrow(
domain: string,
records: Dictionary<string>,
field: string,
): string {
if (!records || !records[field])
throw new ResolutionError(ResolutionErrorCode.RecordNotFound, {
domain,
recordName: field,
});
return records[field];
}
private async getRecordsAddresses(
domain: string,
): Promise<[string, string] | undefined> {
if (!this.isSupportedDomain(domain) || !this.isSupportedNetwork())
return undefined;
const registryRecord = await this.getContractMapValue(
this.registryAddress,
'records',
namehash(domain),
);
if (!registryRecord) return undefined;
let [ownerAddress, resolverAddress] = registryRecord.arguments as [
string,
string,
];
if (ownerAddress.startsWith('0x')) {
ownerAddress = toBech32Address(ownerAddress);
}
return [ownerAddress, resolverAddress];
}
private async getResolverRecords(
resolverAddress: string,
): Promise<ZnsResolution> {
if (!resolverAddress || isNullAddress(resolverAddress)) {
return {};
}
const resolver = toChecksumAddress(resolverAddress);
return ((await this.getContractField(resolver, 'records')) ||
{}) as Dictionary<string>;
}
private structureResolverRecords(records: Dictionary<string>): ZnsResolution {
const result = {};
for (const [key, value] of Object.entries(records)) {
set(result, key, value);
}
return result;
}
private async resolverAddress(domain: string): Promise<string | undefined> {
return ((await this.getRecordsAddresses(domain)) || [])[1];
}
private async fetchSubState(
contractAddress: string,
field: string,
keys: string[] = [],
): Promise<any> {
const response = await this.fetch(this.url, {
method: 'POST',
body: JSON.stringify({
id: '1',
jsonrpc: '2.0',
method: 'GetSmartContractSubState',
params: [contractAddress.replace('0x', ''), field, keys],
}),
headers: {
'Content-Type': 'application/json',
},
}).then(res => res.json());
return response.result;
}
private async getContractField(
contractAddress: string,
field: string,
keys: string[] = [],
): Promise<any> {
try {
const contractAddr = contractAddress.startsWith('zil1')
? fromBech32Address(contractAddress)
: contractAddress;
let result = (await this.fetchSubState(contractAddr, field, keys)) || {};
return result[field];
} catch (err) {
if (err.name == 'FetchError')
throw new ResolutionError(ResolutionErrorCode.NamingServiceDown, {
method: NamingServiceName.ZNS,
});
else throw err;
}
}
private async getContractMapValue(
contractAddress: string,
field: string,
key: string,
): Promise<any> {
const record = await this.getContractField(contractAddress, field, [key]);
return (record && record[key]) || null;
}
}