-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathens-resolver.ts
More file actions
731 lines (598 loc) · 25.9 KB
/
Copy pathens-resolver.ts
File metadata and controls
731 lines (598 loc) · 25.9 KB
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
/**
* ENS is a service which allows easy-to-remember names to map to
* network addresses.
*
* @_section: api/providers/ens-resolver:ENS Resolver [about-ens-rsolver]
*/
import { getAddress } from "../address/index.js";
import { ZeroAddress } from "../constants/index.js";
import { Contract } from "../contract/index.js";
import {
dnsEncode, ensNormalize, isValidName, namehash
} from "../hash/index.js";
import {
getBigInt, hexlify, isHexString, toBeHex,
defineProperties, encodeBase58,
assert, assertArgument, isError,
FetchRequest
} from "../utils/index.js";
import type { FunctionFragment } from "../abi/index.js";
import type { BigNumberish, BytesLike } from "../utils/index.js";
import type { AbstractProvider, AbstractProviderPlugin } from "./abstract-provider.js";
import type { EnsPlugin } from "./plugins-network.js";
import type { Provider } from "./provider.js";
const BN_60 = BigInt(60);
// @TODO: This should use the fetch-data:ipfs gateway
// Trim off the ipfs:// prefix and return the default gateway URL
function getIpfsLink(link: string): string {
if (link.match(/^ipfs:\/\/ipfs\//i)) {
link = link.substring(12);
} else if (link.match(/^ipfs:\/\//i)) {
link = link.substring(7);
} else {
assertArgument(false, "unsupported IPFS format", "link", link);
}
return `https:/\/gateway.ipfs.io/ipfs/${ link }`;
}
/**
* The type of data found during a steip during avatar resolution.
*/
export type AvatarLinkageType = "name" | "avatar" | "!avatar" | "url" | "data" | "ipfs" |
"erc721" | "erc1155" | "!erc721-caip" | "!erc1155-caip" |
"!owner" | "owner" | "!balance" | "balance" |
"metadata-url-base" | "metadata-url-expanded" | "metadata-url" | "!metadata-url" |
"!metadata" | "metadata" |
"!imageUrl" | "imageUrl-ipfs" | "imageUrl" | "!imageUrl-ipfs";
/**
* An individual record for each step during avatar resolution.
*/
export interface AvatarLinkage {
/**
* The type of linkage.
*/
type: AvatarLinkageType;
/**
* The linkage value.
*/
value: string;
};
/**
* When resolving an avatar for an ENS name, there are many
* steps involved, fetching metadata, validating results, et cetera.
*
* Some applications may wish to analyse this data, or use this data
* to diagnose promblems, so an **AvatarResult** provides details of
* each completed step during avatar resolution.
*/
export interface AvatarResult {
/**
* How the [[url]] was arrived at, resolving the many steps required
* for an avatar URL.
*/
linkage: Array<AvatarLinkage>;
/**
* The avatar URL or null if the avatar was not set, or there was
* an issue during validation (such as the address not owning the
* avatar or a metadata error).
*/
url: null | string;
};
/**
* A provider plugin super-class for processing multicoin address types.
*/
export abstract class MulticoinProviderPlugin implements AbstractProviderPlugin {
/**
* The name.
*/
readonly name!: string;
/**
* Creates a new **MulticoinProviderPluing** for %%name%%.
*/
constructor(name: string) {
defineProperties<MulticoinProviderPlugin>(this, { name });
}
connect(provider: Provider): MulticoinProviderPlugin {
return this;
}
/**
* Returns ``true`` if %%coinType%% is supported by this plugin.
*/
supportsCoinType(coinType: number): boolean {
return false;
}
/**
* Resolves to the encoded %%address%% for %%coinType%%.
*/
async encodeAddress(coinType: number, address: string): Promise<string> {
throw new Error("unsupported coin");
}
/**
* Resolves to the decoded %%data%% for %%coinType%%.
*/
async decodeAddress(coinType: number, data: BytesLike): Promise<string> {
throw new Error("unsupported coin");
}
}
const BasicMulticoinPluginId = "org.ethers.plugins.provider.BasicMulticoin";
/**
* A **BasicMulticoinProviderPlugin** provides service for common
* coin types, which do not require additional libraries to encode or
* decode.
*/
export class BasicMulticoinProviderPlugin extends MulticoinProviderPlugin {
/**
* Creates a new **BasicMulticoinProviderPlugin**.
*/
constructor() {
super(BasicMulticoinPluginId);
}
}
const matcherIpfs = new RegExp("^(ipfs):/\/(.*)$", "i");
const matchers = [
new RegExp("^(https):/\/(.*)$", "i"),
new RegExp("^(data):(.*)$", "i"),
matcherIpfs,
new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i"),
];
function isEvmCoinType(coinType: bigint) {
return (coinType === BN_60) ||
(coinType >= 0x80000000 && coinType <= 0xffffffff);
}
/**
* A connected object to a resolved ENS name resolver, which can be
* used to query additional details.
*/
export class EnsResolver {
/**
* The connected provider.
*/
provider!: AbstractProvider;
/**
* The address of the resolver.
*/
address!: string;
/**
* The name this resolver was resolved against.
*/
name!: string;
// For EIP-2544 names, the ancestor that provided the resolver
#supports2544: null | Promise<boolean>;
readonly #resolver: Contract;
constructor(provider: AbstractProvider, address: string, name: string, supportsWildcard?: boolean) {
defineProperties<EnsResolver>(this, { provider, address, name });
this.#supports2544 = (supportsWildcard != null) ? Promise.resolve(supportsWildcard): null;
this.#resolver = new Contract(address, [
"function supportsInterface(bytes4) view returns (bool)",
"function resolve(bytes, bytes) view returns (bytes)",
"function addr(bytes32) view returns (address)",
"function addr(bytes32, uint) view returns (bytes)",
"function text(bytes32, string) view returns (string)",
"function contenthash(bytes32) view returns (bytes)",
"function name(bytes32) view returns (string)",
], provider);
}
/**
* Resolves to true if the resolver supports wildcard resolution.
*/
async supportsWildcard(): Promise<boolean> {
if (this.#supports2544 == null) {
this.#supports2544 = (async () => {
try {
return await this.#resolver.supportsInterface("0x9061b923");
} catch (error) {
// Wildcard resolvers must understand supportsInterface
// and return true.
if (isError(error, "CALL_EXCEPTION")) { return false; }
// Let future attempts try again...
this.#supports2544 = null;
throw error;
}
})();
}
return await this.#supports2544;
}
async #fetch(funcName: string, params?: Array<any>): Promise<null | any> {
params = (params || []).slice();
const iface = this.#resolver.interface;
// The first parameters is always the nodehash
params.unshift(namehash(this.name))
let fragment: null | FunctionFragment = null;
if (await this.supportsWildcard()) {
fragment = iface.getFunction(funcName);
assert(fragment, "missing fragment", "UNKNOWN_ERROR", {
info: { funcName }
});
params = [
dnsEncode(this.name, 255),
iface.encodeFunctionData(fragment, params)
];
funcName = "resolve(bytes,bytes)";
}
params.push({ enableCcipRead: true });
try {
const result = await this.#resolver[funcName](...params);
if (fragment) {
return iface.decodeFunctionResult(fragment, result)[0];
}
return result;
} catch (error: any) {
if (!isError(error, "CALL_EXCEPTION")) { throw error; }
}
return null;
}
/**
* Resolves to the address for %%coinType%% or null if the
* provided %%coinType%% has not been configured.
*/
async getAddress(_coinType?: BigNumberish): Promise<null | string> {
const coinType = (_coinType == null) ? BN_60: getBigInt(_coinType);
if (coinType === BN_60) {
try {
const result = await this.#fetch("addr(bytes32)");
// No address
if (result == null || result === ZeroAddress) { return null; }
return result;
} catch (error: any) {
if (isError(error, "CALL_EXCEPTION")) { return null; }
throw error;
}
}
if (isEvmCoinType(coinType)) {
const data = await this.#fetch("addr(bytes32,uint)", [ coinType ]);
if (isHexString(data, 20)) { return getAddress(data); }
return null;
}
// Try decoding its EVM canonical chain as an EVM chain address first
if (coinType >= 0 && coinType < 0x80000000) {
let ethCoinType = coinType + BigInt(0x80000000);
const data = await this.#fetch("addr(bytes32,uint)", [ ethCoinType ]);
if (isHexString(data, 20)) { return getAddress(data); }
}
// @TODO: add a new method to the MulticoinProviderPlugin and move
// this check above the auto-eth-decoding chunk above to give the
// plugin a chance to process the coinType and result
let coinPlugin: null | MulticoinProviderPlugin = null;
for (const plugin of this.provider.plugins) {
if (!(plugin instanceof MulticoinProviderPlugin)) { continue; }
if (coinType <= 0x80000000 && plugin.supportsCoinType(Number(coinType))) {
coinPlugin = plugin;
break;
}
}
if (coinPlugin == null) { return null; }
// keccak256("addr(bytes32,uint256")
const data = await this.#fetch("addr(bytes32,uint)", [ coinType ]);
// No address
if (data == null || data === "0x") { return null; }
if (coinType < 0x80000000) {
// Compute the address
const address = await coinPlugin.decodeAddress(Number(coinType), data);
if (address != null) { return address; }
}
assert(false, `invalid coin data`, "UNSUPPORTED_OPERATION", {
operation: `getAddress(${ coinType })`,
info: { coinType, data }
});
}
/**
* Resolves to the EIP-634 text record for %%key%%, or ``null``
* if unconfigured.
*/
async getText(key: string): Promise<null | string> {
const data = await this.#fetch("text(bytes32,string)", [ key ]);
if (data == null || data === "0x") { return null; }
return data;
}
/**
* Rsolves to the content-hash or ``null`` if unconfigured.
*/
async getContentHash(): Promise<null | string> {
// keccak256("contenthash()")
const data = await this.#fetch("contenthash(bytes32)");
// No contenthash
if (data == null || data === "0x") { return null; }
// IPFS (CID: 1, Type: 70=DAG-PB, 72=libp2p-key)
const ipfs = data.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);
if (ipfs) {
const scheme = (ipfs[1] === "e3010170") ? "ipfs": "ipns";
const length = parseInt(ipfs[4], 16);
if (ipfs[5].length === length * 2) {
return `${ scheme }:/\/${ encodeBase58("0x" + ipfs[2])}`;
}
}
// Swarm (CID: 1, Type: swarm-manifest; hash/length hard-coded to keccak256/32)
const swarm = data.match(/^0xe40101fa011b20([0-9a-f]*)$/)
if (swarm && swarm[1].length === 64) {
return `bzz:/\/${ swarm[1] }`;
}
assert(false, `invalid or unsupported content hash data`, "UNSUPPORTED_OPERATION", {
operation: "getContentHash()",
info: { data }
});
}
async getName(): Promise<null | string> {
return await this.#fetch("name(bytes32)");
}
/**
* Resolves to the avatar url or ``null`` if the avatar is either
* unconfigured or incorrectly configured (e.g. references an NFT
* not owned by the address).
*
* If diagnosing issues with configurations, the [[_getAvatar]]
* method may be useful.
*/
async getAvatar(): Promise<null | string> {
const avatar = await this._getAvatar();
return avatar.url;
}
/**
* When resolving an avatar, there are many steps involved, such
* fetching metadata and possibly validating ownership of an
* NFT.
*
* This method can be used to examine each step and the value it
* was working from.
*/
async _getAvatar(): Promise<AvatarResult> {
const linkage: Array<AvatarLinkage> = [ { type: "name", value: this.name } ];
try {
// test data for ricmoo.eth
//const avatar = "eip155:1/erc721:0x265385c7f4132228A0d54EB1A9e7460b91c0cC68/29233";
const avatar = await this.getText("avatar");
if (avatar == null) {
linkage.push({ type: "!avatar", value: "" });
return { url: null, linkage };
}
linkage.push({ type: "avatar", value: avatar });
for (let i = 0; i < matchers.length; i++) {
const match = avatar.match(matchers[i]);
if (match == null) { continue; }
const scheme = match[1].toLowerCase();
switch (scheme) {
case "https":
case "data":
linkage.push({ type: "url", value: avatar });
return { linkage, url: avatar };
case "ipfs": {
const url = getIpfsLink(avatar);
linkage.push({ type: "ipfs", value: avatar });
linkage.push({ type: "url", value: url });
return { linkage, url };
}
case "erc721":
case "erc1155": {
// Depending on the ERC type, use tokenURI(uint256) or url("https://github.com/ethers-io/ethers.js/blob/main/src.ts/providers/uint256")
const selector = (scheme === "erc721") ? "tokenURI(uint256)": "uri(uint256)";
linkage.push({ type: scheme, value: avatar });
// The owner of this name
const owner = await this.getAddress();
if (owner == null) {
linkage.push({ type: "!owner", value: "" });
return { url: null, linkage };
}
const comps = (match[2] || "").split("/");
if (comps.length !== 2) {
linkage.push({ type: <any>`!${ scheme }caip`, value: (match[2] || "") });
return { url: null, linkage };
}
const tokenId = comps[1];
const contract = new Contract(comps[0], [
// ERC-721
"function tokenURI(uint) view returns (string)",
"function ownerOf(uint) view returns (address)",
// ERC-1155
"function uri(uint) view returns (string)",
"function balanceOf(address, uint256) view returns (uint)"
], this.provider);
// Check that this account owns the token
if (scheme === "erc721") {
const tokenOwner = await contract.ownerOf(tokenId);
if (owner !== tokenOwner) {
linkage.push({ type: "!owner", value: tokenOwner });
return { url: null, linkage };
}
linkage.push({ type: "owner", value: tokenOwner });
} else if (scheme === "erc1155") {
const balance = await contract.balanceOf(owner, tokenId);
if (!balance) {
linkage.push({ type: "!balance", value: "0" });
return { url: null, linkage };
}
linkage.push({ type: "balance", value: balance.toString() });
}
// Call the token contract for the metadata URL
let metadataUrl = await contract[selector](tokenId);
if (metadataUrl == null || metadataUrl === "0x") {
linkage.push({ type: "!metadata-url", value: "" });
return { url: null, linkage };
}
linkage.push({ type: "metadata-url-base", value: metadataUrl });
// ERC-1155 allows a generic {id} in the URL
if (scheme === "erc1155") {
metadataUrl = metadataUrl.replace("{id}", toBeHex(tokenId, 32).substring(2));
linkage.push({ type: "metadata-url-expanded", value: metadataUrl });
}
// Transform IPFS metadata links
if (metadataUrl.match(/^ipfs:/i)) {
metadataUrl = getIpfsLink(metadataUrl);
}
linkage.push({ type: "metadata-url", value: metadataUrl });
// Get the token metadata
let metadata: any = { };
const response = await (new FetchRequest(metadataUrl)).send();
response.assertOk();
try {
metadata = response.bodyJson;
} catch (error) {
try {
linkage.push({ type: "!metadata", value: response.bodyText });
} catch (error) {
const bytes = response.body;
if (bytes) {
linkage.push({ type: "!metadata", value: hexlify(bytes) });
}
return { url: null, linkage };
}
return { url: null, linkage };
}
if (!metadata) {
linkage.push({ type: "!metadata", value: "" });
return { url: null, linkage };
}
linkage.push({ type: "metadata", value: JSON.stringify(metadata) });
// Pull the image URL out
let imageUrl = metadata.image;
if (typeof(imageUrl) !== "string") {
linkage.push({ type: "!imageUrl", value: "" });
return { url: null, linkage };
}
if (imageUrl.match(/^(https:\/\/|data:)/i)) {
// Allow
} else {
// Transform IPFS link to gateway
const ipfs = imageUrl.match(matcherIpfs);
if (ipfs == null) {
linkage.push({ type: "!imageUrl-ipfs", value: imageUrl });
return { url: null, linkage };
}
linkage.push({ type: "imageUrl-ipfs", value: imageUrl });
imageUrl = getIpfsLink(imageUrl);
}
linkage.push({ type: "url", value: imageUrl });
return { linkage, url: imageUrl };
}
}
}
} catch (error) { }
return { linkage, url: null };
}
static async getEnsAddress(provider: Provider): Promise<string> {
const network = await provider.getNetwork();
const ensPlugin = network.getPlugin<EnsPlugin>("org.ethers.plugins.network.Ens");
// No ENS...
assert(ensPlugin, "network does not support ENS", "UNSUPPORTED_OPERATION", {
operation: "getEnsAddress", info: { network } });
return ensPlugin.address;
}
static async getUniversalResolverAddress(provider: Provider): Promise<null | string> {
const network = await provider.getNetwork();
const ensPlugin = network.getPlugin<EnsPlugin>("org.ethers.plugins.network.Ens");
if (ensPlugin && ensPlugin.universalResolver) {
return ensPlugin.universalResolver;
}
return null;
}
static async #getResolver(provider: Provider, name: string): Promise<null | string> {
const ensAddr = await EnsResolver.getEnsAddress(provider);
try {
const contract = new Contract(ensAddr, [
"function resolver(bytes32) view returns (address)"
], provider);
const addr = await contract.resolver(namehash(name), {
enableCcipRead: true
});
if (addr === ZeroAddress) { return null; }
return addr;
} catch (error) {
// ENS registry cannot throw errors on resolver(bytes32),
// so probably a link error
throw error;
}
return null;
}
static async lookupAddress(provider: AbstractProvider, address: string, _coinType?: BigNumberish): Promise<null | string> {
const coinType = (_coinType == null) ? BN_60: getBigInt(_coinType);
if (isEvmCoinType(coinType)) { address = getAddress(address); }
// We have a Universal resolver, use it
const universal = await createUniversal(provider);
if (universal) {
try {
const result = await universal.reverse(address, coinType, {
enableCcipRead: true
});
const addr = result.primary;
if (!isValidName(addr)) { return null; }
return addr;
} catch (e) {
if (isError(e, "CALL_EXCEPTION") && e.reason === "ResolverNotFound(bytes)") {
return null;
}
throw e;
}
}
// Use legacy reverse lookup
assert(coinType === BN_60, "lookupAddress coinType requires ENS Universal Resolver", "UNSUPPORTED_OPERATION", {
operation: "lookupAddress"
});
try {
const resolver = await EnsResolver.fromName(provider,
`${ address.toLowerCase().substring(2) }.addr.reverse`);
if (!resolver) { return null; }
const name = await resolver.getName();
if (name == null || !isValidName(name)) { return null; }
// Failed forward resolution
const check = await provider.resolveName(name);
if (check !== address) { return null; }
return name;
} catch (error) {
// No data was returned from the resolver
if (isError(error, "BAD_DATA") && error.value === "0x") {
return null;
}
// Something reverted
if (isError(error, "CALL_EXCEPTION")) { return null; }
throw error;
}
}
/**
* Resolve to the ENS resolver for %%name%% using %%provider%% or
* ``null`` if unconfigured.
*/
static async fromName(provider: AbstractProvider, name: string): Promise<null | EnsResolver> {
// We have a Universal Resolver, use it
const universal = await createUniversal(provider);
if (universal) {
let dnsName: string;
try {
dnsName = dnsEncode(ensNormalize(name), 255);
} catch (error) {
// Should this emit an error in the provider debug event?
return null;
}
const result = await universal.requireResolver(dnsName);
return new EnsResolver(provider, result.resolver, name, result.extended);
}
let currentName = name;
while (true) {
if (currentName === "" || currentName === ".") { return null; }
// Optimization since the eth node cannot change and does
// not have a wildcard resolver
if (name !== "eth" && currentName === "eth") { return null; }
// Check the current node for a resolver
const addr = await EnsResolver.#getResolver(provider, currentName);
// Found a resolver!
if (addr != null) {
const resolver = new EnsResolver(provider, addr, name);
// Legacy resolver found, using EIP-2544 so it isn't safe to use
if (currentName !== name && !(await resolver.supportsWildcard())) { return null; }
return resolver;
}
// Get the parent node
currentName = currentName.split(".").slice(1).join(".");
}
}
}
async function createUniversal(provider: AbstractProvider): Promise<null | Contract> {
const address = await EnsResolver.getUniversalResolverAddress(provider);
if (!address) { return null; }
return new Contract(address, [
"function requireResolver(bytes) view returns ((bytes name, uint256 offset, bytes32 node, address resolver, bool extended))",
"function findResolver(bytes) view returns (address resolver, bytes32 node, uint offset)",
"function resolve(bytes name, bytes data) view returns (bytes result, address resolver)",
"function reverse(bytes name, uint coinType) view returns (string primary, address resolver, address reverseResolver)",
"error ResolverNotFound(bytes name)",
"error ResolverNotContract(bytes name, address resolver)",
"error ReverseAddressMismatch(string primary, bytes primaryAddress)",
"error HttpError(uint16 statusCode, string statusMessage)"
], provider);
}