-
Notifications
You must be signed in to change notification settings - Fork 81
/
Resolution.ts
436 lines (402 loc) · 13.7 KB
/
Resolution.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
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
import Ens from './ens';
import Zns from './zns';
import Cns from './cns';
import Udapi from './unstoppableAPI';
import {
Blockchain,
UnclaimedDomainResponse,
ResolutionResponse,
DefaultAPI,
API,
nodeHash,
NamingServiceName,
Web3Version0Provider,
Web3Version1Provider,
Provider,
NamingServiceSource,
SourceDefinition,
EthersProvider,
} from './types';
import ResolutionError, { ResolutionErrorCode } from './errors/resolutionError';
import NamingService from './namingService';
import { signedInfuraLink } from './utils';
import { Eip1993Factories } from './utils/Eip1993Factories';
/**
* Blockchain domain Resolution library - Resolution.
* @example
* ```
* import Resolution from '@unstoppabledomains/resolution';
*
* let resolution = new Resolution({ blockchain: {
* ens: {
* url: "https://mainnet.infura.io/v3/12351245223",
* network: "mainnet"
* }
* }
* });
*
* let domain = "brad.zil";
* resolution.address(domain, "eth").then(addr => console.log(addr));;
* ```
*/
export default class Resolution {
/**
* @returns true if weather resolution library is configured to use blockchain for resolution.
*/
readonly blockchain: boolean;
/** @internal */
readonly ens?: Ens;
/** @internal */
readonly zns?: Zns;
/** @internal */
readonly cns?: Cns;
/** @internal */
readonly api?: Udapi;
constructor({
blockchain = true,
api = DefaultAPI,
}: { blockchain?: Blockchain | boolean; api?: API } = {}) {
this.blockchain = !!blockchain;
if (blockchain) {
if (blockchain === true) {
blockchain = {};
}
const web3provider = blockchain.web3Provider;
if (web3provider) {
console.warn(
'Usage of `web3Provider` option is deprecated. Use `provider` option instead for each individual blockchain',
);
}
const ens = this.normalizeSource(blockchain.ens, web3provider);
const zns = this.normalizeSource(blockchain.zns);
const cns = this.normalizeSource(blockchain.cns, web3provider);
if (ens) {
this.ens = new Ens(ens);
}
if (zns) {
this.zns = new Zns(zns);
}
if (cns) {
this.cns = new Cns(cns);
}
} else {
this.api = new Udapi(api);
}
}
/**
* Creates a resolution with configured infura id for ens and cns
* @param infura infura project id
* @param network ethereum network name
*/
static infura(infura: string, network: string = 'mainnet'): Resolution {
return new this({
blockchain: {
ens: { url: signedInfuraLink(infura, network), network },
cns: { url: signedInfuraLink(infura, network), network },
},
});
}
/**
* Creates a resolution instance with configured provider
* @param provider - any provider compatible with EIP-1193
* @see https://eips.ethereum.org/EIPS/eip-1193
*/
static fromEip1193Provider(provider: Provider): Resolution {
return new this({
blockchain: { zns: true, ens: { provider }, cns: { provider } },
});
}
/**
* Create a resolution instance from web3 0.x version provider
* @param provider - an 0.x version provider from web3 ( must implement sendAsync(payload, callback) )
* @see https://github.com/ethereum/web3.js/blob/0.20.7/lib/web3/httpprovider.js#L116
*/
static fromWeb3Version0Provider(provider: Web3Version0Provider): Resolution {
return this.fromEip1193Provider(Eip1993Factories.fromWeb3Version0Provider(provider));
}
/**
* Create a resolution instance from web3 1.x version provider
* @param provider - an 1.x version provider from web3 ( must implement send(payload, callback) )
* @see https://github.com/ethereum/web3.js/blob/1.x/packages/web3-core-helpers/types/index.d.ts#L165
* @see https://github.com/ethereum/web3.js/blob/1.x/packages/web3-providers-http/src/index.js#L95
*/
static fromWeb3Version1Provider(provider: Web3Version1Provider): Resolution {
return this.fromEip1193Provider(Eip1993Factories.fromWeb3Version1Provider(provider));
}
/**
* Creates instance of resolution from provider that implements Ethers Provider#call interface.
* This wrapper support only `eth_call` method for now, which is enough for all the current Resolution functionality
* @param provider - provider object
* @see https://github.com/ethers-io/ethers.js/blob/v4-legacy/providers/abstract-provider.d.ts#L91
* @see https://github.com/ethers-io/ethers.js/blob/v5.0.4/packages/abstract-provider/src.ts/index.ts#L224
* @see https://docs.ethers.io/ethers.js/v5-beta/api-providers.html#jsonrpcprovider-inherits-from-provider
* @see https://github.com/ethers-io/ethers.js/blob/master/packages/providers/src.ts/json-rpc-provider.ts
*/
static fromEthersProvider(provider: EthersProvider): Resolution {
return this.fromEip1193Provider(Eip1993Factories.fromEthersProvider(provider));
}
/**
* Resolves the given domain
* @async
* @param domain - domain name to be resolved
* @returns A promise that resolves in an object
*/
async resolve(domain: string): Promise<ResolutionResponse> {
domain = this.prepareDomain(domain);
const method = this.getNamingMethodOrThrow(domain);
const result = await method.resolve(domain);
return result || UnclaimedDomainResponse;
}
/**
* Resolves give domain name to a specific currency address if exists
* @async
* @param domain - domain name to be resolved
* @param currencyTicker - currency ticker like BTC, ETH, ZIL
* @returns A promise that resolves in an address or null
*/
async address(
domain: string,
currencyTicker: string,
): Promise<string | null> {
domain = this.prepareDomain(domain);
try {
return await this.addressOrThrow(domain, currencyTicker);
} catch (error) {
if (error instanceof ResolutionError) {
return null;
} else {
throw error;
}
}
}
/**
* Resolve a chat id from the domain record
* @param domain - domain name to be resolved
* @throws [[ResolutionError]]
* @returns A promise that resolves in chatId
*/
async chatId(domain: string): Promise<string> {
domain = this.prepareDomain(domain);
const method = this.getNamingMethodOrThrow(domain);
return await method.chatId(domain);
}
/**
* Resolve a gundb public key from the domain record
* @param domain - domain name to be resolved
* @throws [[ResolutionError]]
* @returns a promise that resolves in gundb public key
*/
async chatPk(domain: string): Promise<string> {
domain = this.prepareDomain(domain);
const method = this.getNamingMethodOrThrow(domain);
return await method.chatpk(domain);
}
/**
* Resolves the IPFS hash configured for domain records on ZNS
* @param domain - domain name
* @throws [[ResolutionError]]
*/
async ipfsHash(domain: string): Promise<string> {
domain = this.prepareDomain(domain);
return await this.getNamingMethodOrThrow(domain).ipfsHash(domain);
}
/**
* Resolves the httpUrl attached to domain
* @param domain - domain name
*/
async httpUrl(domain: string): Promise<string> {
domain = this.prepareDomain(domain);
return await this.getNamingMethodOrThrow(domain).httpUrl(domain);
}
/**
* Resolves the ipfs redirect url for a supported domain records
* @deprecated use Resolution#httpUrl instead
* @param domain - domain name
* @throws [[ResolutionError]]
* @returns A Promise that resolves in redirect url
*/
async ipfsRedirect(domain: string): Promise<string> {
console.warn(
'Resolution#ipfsRedirect is depricated since 1.0.15, use Resolution#httpUrl instead',
);
return await this.getNamingMethodOrThrow(domain).record(
domain,
'ipfs.redirect_domain.value',
);
}
/**
* Resolves the ipfs email field from whois configurations
* @param domain - domain name
* @throws [[ResolutionError]]
* @returns A Promise that resolves in an email address configured for this domain whois
*/
async email(domain: string): Promise<string> {
domain = this.prepareDomain(domain);
return await this.getNamingMethodOrThrow(domain).email(domain);
}
/**
* @returns A specific currency address or throws an error
* @param domain domain name
* @param currencyTicker currency ticker such as
* - ZIL
* - BTC
* - ETH
* @throws [[ResolutionError]] if address is not found
*/
async addressOrThrow(
domain: string,
currencyTicker: string,
): Promise<string> {
domain = this.prepareDomain(domain);
const method = this.getNamingMethodOrThrow(domain);
return await method.address(domain, currencyTicker);
}
/**
* @returns the resolver address for a specific domain
* @param domain - domain to look for
*/
async resolver(domain: string): Promise<string> {
domain = this.prepareDomain(domain);
return await this.getNamingMethodOrThrow(domain).resolver(domain);
}
/**
* @param domain - domain name
* @returns An owner address of the domain
*/
async owner(domain: string): Promise<string | null> {
domain = this.prepareDomain(domain);
const method = this.getNamingMethodOrThrow(domain);
return (await method.owner(domain)) || null;
}
/**
* @param domain - domain name
* @param recordKey - a name of a record to be resolved
* @returns A record value promise for a given record name
*/
async record(domain: string, recordKey: string): Promise<string> {
domain = this.prepareDomain(domain);
const method = this.getNamingMethodOrThrow(domain);
return await method.record(domain, recordKey);
}
/**
* This method is only for ens at the moment. Reverse the ens address to a ens registered domain name
* @async
* @param address - address you wish to reverse
* @param currencyTicker - currency ticker like BTC, ETH, ZIL
* @returns Domain name attached to this address
*/
async reverse(
address: string,
currencyTicker: string,
): Promise<string | null> {
return (this.findNamingService(NamingServiceName.ENS) as Ens).reverse(address, currencyTicker);
}
/**
* @returns Produces a namehash from supported naming service in hex format with 0x prefix.
* Corresponds to ERC721 token id in case of Ethereum based naming service like ENS or CNS.
* @param domain - domain name to be converted
* @throws [[ResolutionError]] with UnsupportedDomain error code if domain extension is unknown
*/
namehash(domain: string): string {
domain = this.prepareDomain(domain);
return this.getNamingMethodOrThrow(domain).namehash(domain);
}
/**
* returns a childhash for specific namingService
* @param parent hash for parent
* @param label hash for label
* @param method "ENS", "CNS" or "ZNS"
*/
childhash(
parent: nodeHash,
label: string,
method: NamingServiceName,
): nodeHash {
return this.findNamingService(method).childhash(parent, label);
}
/**
* Checks weather the domain name matches the hash
* @param domain - domain name to check againt
* @param hash - hash obtained from the blockchain
*/
isValidHash(domain: string, hash: string): boolean {
domain = this.prepareDomain(domain);
return this.namehash(domain) === hash;
}
/**
* Checks if the domain name is valid according to naming service rules
* for valid domain names.
* Example: ENS doesn't allow domains that start from '-' symbol.
* @param domain - domain name to be checked
*/
isSupportedDomain(domain: string): boolean {
domain = this.prepareDomain(domain);
return !!this.getNamingMethod(domain);
}
/**
* Checks if the domain is supported by the specified network as well as if it is in valid format
* @param domain - domain name to be checked
*/
isSupportedDomainInNetwork(domain: string): boolean {
domain = this.prepareDomain(domain);
const method = this.getNamingMethod(domain);
return !!method && method.isSupportedNetwork();
}
/**
* Returns the name of the service for a domain ENS | CNS | ZNS
* @param domain - domain name to look for
*/
serviceName(domain: string): NamingServiceName {
domain = this.prepareDomain(domain);
return this.getNamingMethodOrThrow(domain).serviceName(domain);
}
private getNamingMethod(domain: string): NamingService | undefined {
domain = this.prepareDomain(domain);
return this.getResolutionMethods().find(
method => method.isSupportedDomain(domain),
);
}
private getResolutionMethods(): NamingService[] {
return (this.blockchain
? [this.ens, this.zns, this.cns] as NamingService[]
: [this.api] as NamingService[]).filter(v => v);
}
private getNamingMethodOrThrow(domain: string): NamingService {
domain = this.prepareDomain(domain);
const method = this.getNamingMethod(domain);
if (!method)
throw new ResolutionError(ResolutionErrorCode.UnsupportedDomain, {
domain,
});
return method;
}
private findNamingService(name: NamingServiceName): NamingService {
const service = this.getResolutionMethods().find(m => m.name === name)
if (!service)
throw new ResolutionError(ResolutionErrorCode.NamingServiceDown, {
method: name,
});
return service;
}
private prepareDomain(domain: string): string {
return domain ? domain.trim().toLowerCase() : '';
}
private normalizeSource(source: NamingServiceSource | undefined, provider?: Provider): SourceDefinition | false {
switch (typeof source) {
case 'undefined': {
return {provider}
}
case 'boolean': {
return source ? {provider} : false;
}
case 'string': {
return { url: source };
}
case 'object': {
return {provider, ...source};
}
}
throw new Error('Unsupported configuration')
}
}
export { Resolution };