-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
base-provider.ts
2217 lines (1758 loc) · 81.4 KB
/
base-provider.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
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
import {
Block, BlockTag, BlockWithTransactions, EventType, Filter, FilterByBlockHash, ForkEvent,
Listener, Log, Provider, TransactionReceipt, TransactionRequest, TransactionResponse
} from "@ethersproject/abstract-provider";
import { encode as base64Encode } from "@ethersproject/base64";
import { Base58 } from "@ethersproject/basex";
import { BigNumber, BigNumberish } from "@ethersproject/bignumber";
import { arrayify, BytesLike, concat, hexConcat, hexDataLength, hexDataSlice, hexlify, hexValue, hexZeroPad, isHexString } from "@ethersproject/bytes";
import { HashZero } from "@ethersproject/constants";
import { dnsEncode, namehash } from "@ethersproject/hash";
import { getNetwork, Network, Networkish } from "@ethersproject/networks";
import { Deferrable, defineReadOnly, getStatic, resolveProperties } from "@ethersproject/properties";
import { Transaction } from "@ethersproject/transactions";
import { sha256 } from "@ethersproject/sha2";
import { toUtf8Bytes, toUtf8String } from "@ethersproject/strings";
import { fetchJson, poll } from "@ethersproject/web";
import bech32 from "bech32";
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
import { Formatter } from "./formatter";
const MAX_CCIP_REDIRECTS = 10;
//////////////////////////////
// Event Serializeing
function checkTopic(topic: string): string {
if (topic == null) { return "null"; }
if (hexDataLength(topic) !== 32) {
logger.throwArgumentError("invalid topic", "topic", topic);
}
return topic.toLowerCase();
}
function serializeTopics(topics: Array<string | Array<string>>): string {
// Remove trailing null AND-topics; they are redundant
topics = topics.slice();
while (topics.length > 0 && topics[topics.length - 1] == null) { topics.pop(); }
return topics.map((topic) => {
if (Array.isArray(topic)) {
// Only track unique OR-topics
const unique: { [ topic: string ]: boolean } = { }
topic.forEach((topic) => {
unique[checkTopic(topic)] = true;
});
// The order of OR-topics does not matter
const sorted = Object.keys(unique);
sorted.sort();
return sorted.join("|");
} else {
return checkTopic(topic);
}
}).join("&");
}
function deserializeTopics(data: string): Array<string | Array<string>> {
if (data === "") { return [ ]; }
return data.split(/&/g).map((topic) => {
if (topic === "") { return [ ]; }
const comps = topic.split("|").map((topic) => {
return ((topic === "null") ? null: topic);
});
return ((comps.length === 1) ? comps[0]: comps);
});
}
function getEventTag(eventName: EventType): string {
if (typeof(eventName) === "string") {
eventName = eventName.toLowerCase();
if (hexDataLength(eventName) === 32) {
return "tx:" + eventName;
}
if (eventName.indexOf(":") === -1) {
return eventName;
}
} else if (Array.isArray(eventName)) {
return "filter:*:" + serializeTopics(eventName);
} else if (ForkEvent.isForkEvent(eventName)) {
logger.warn("not implemented");
throw new Error("not implemented");
} else if (eventName && typeof(eventName) === "object") {
return "filter:" + (eventName.address || "*") + ":" + serializeTopics(eventName.topics || []);
}
throw new Error("invalid event - " + eventName);
}
//////////////////////////////
// Helper Object
function getTime() {
return (new Date()).getTime();
}
function stall(duration: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, duration);
});
}
//////////////////////////////
// Provider Object
/**
* EventType
* - "block"
* - "poll"
* - "didPoll"
* - "pending"
* - "error"
* - "network"
* - filter
* - topics array
* - transaction hash
*/
const PollableEvents = [ "block", "network", "pending", "poll" ];
export class Event {
readonly listener: Listener;
readonly once: boolean;
readonly tag: string;
_lastBlockNumber: number
_inflight: boolean;
constructor(tag: string, listener: Listener, once: boolean) {
defineReadOnly(this, "tag", tag);
defineReadOnly(this, "listener", listener);
defineReadOnly(this, "once", once);
this._lastBlockNumber = -2;
this._inflight = false;
}
get event(): EventType {
switch (this.type) {
case "tx":
return this.hash;
case "filter":
return this.filter;
}
return this.tag;
}
get type(): string {
return this.tag.split(":")[0]
}
get hash(): string {
const comps = this.tag.split(":");
if (comps[0] !== "tx") { return null; }
return comps[1];
}
get filter(): Filter {
const comps = this.tag.split(":");
if (comps[0] !== "filter") { return null; }
const address = comps[1];
const topics = deserializeTopics(comps[2]);
const filter: Filter = { };
if (topics.length > 0) { filter.topics = topics; }
if (address && address !== "*") { filter.address = address; }
return filter;
}
pollable(): boolean {
return (this.tag.indexOf(":") >= 0 || PollableEvents.indexOf(this.tag) >= 0);
}
}
export interface EnsResolver {
// Name this Resolver is associated with
readonly name: string;
// The address of the resolver
readonly address: string;
// Multichain address resolution (also normal address resolution)
// See: https://eips.ethereum.org/EIPS/eip-2304
getAddress(coinType?: 60): Promise<null | string>
// Contenthash field
// See: https://eips.ethereum.org/EIPS/eip-1577
getContentHash(): Promise<null | string>;
// Storage of text records
// See: https://eips.ethereum.org/EIPS/eip-634
getText(key: string): Promise<null | string>;
};
export interface EnsProvider {
resolveName(name: string): Promise<null | string>;
lookupAddress(address: string): Promise<null | string>;
getResolver(name: string): Promise<null | EnsResolver>;
}
type CoinInfo = {
symbol: string,
ilk?: string, // General family
prefix?: string, // Bech32 prefix
p2pkh?: number, // Pay-to-Public-Key-Hash Version
p2sh?: number, // Pay-to-Script-Hash Version
};
// https://github.com/satoshilabs/slips/blob/master/slip-0044.md
const coinInfos: { [ coinType: string ]: CoinInfo } = {
"0": { symbol: "btc", p2pkh: 0x00, p2sh: 0x05, prefix: "bc" },
"2": { symbol: "ltc", p2pkh: 0x30, p2sh: 0x32, prefix: "ltc" },
"3": { symbol: "doge", p2pkh: 0x1e, p2sh: 0x16 },
"60": { symbol: "eth", ilk: "eth" },
"61": { symbol: "etc", ilk: "eth" },
"700": { symbol: "xdai", ilk: "eth" },
};
function bytes32ify(value: number): string {
return hexZeroPad(BigNumber.from(value).toHexString(), 32);
}
// Compute the Base58Check encoded data (checksum is first 4 bytes of sha256d)
function base58Encode(data: Uint8Array): string {
return Base58.encode(concat([ data, hexDataSlice(sha256(sha256(data)), 0, 4) ]));
}
export interface Avatar {
url: string;
linkage: Array<{ type: string, content: string }>;
}
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 _parseString(result: string, start: number): null | string {
try {
return toUtf8String(_parseBytes(result, start));
} catch(error) { }
return null;
}
function _parseBytes(result: string, start: number): null | string {
if (result === "0x") { return null; }
const offset = BigNumber.from(hexDataSlice(result, start, start + 32)).toNumber();
const length = BigNumber.from(hexDataSlice(result, offset, offset + 32)).toNumber();
return hexDataSlice(result, offset + 32, offset + 32 + length);
}
// 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 {
logger.throwArgumentError("unsupported IPFS format", "link", link);
}
return `https:/\/gateway.ipfs.io/ipfs/${ link }`;
}
function numPad(value: number): Uint8Array {
const result = arrayify(value);
if (result.length > 32) { throw new Error("internal; should not happen"); }
const padded = new Uint8Array(32);
padded.set(result, 32 - result.length);
return padded;
}
function bytesPad(value: Uint8Array): Uint8Array {
if ((value.length % 32) === 0) { return value; }
const result = new Uint8Array(Math.ceil(value.length / 32) * 32);
result.set(value);
return result;
}
// ABI Encodes a series of (bytes, bytes, ...)
function encodeBytes(datas: Array<BytesLike>) {
const result: Array<Uint8Array> = [ ];
let byteCount = 0;
// Add place-holders for pointers as we add items
for (let i = 0; i < datas.length; i++) {
result.push(null);
byteCount += 32;
}
for (let i = 0; i < datas.length; i++) {
const data = arrayify(datas[i]);
// Update the bytes offset
result[i] = numPad(byteCount);
// The length and padded value of data
result.push(numPad(data.length));
result.push(bytesPad(data));
byteCount += 32 + Math.ceil(data.length / 32) * 32;
}
return hexConcat(result);
}
export class Resolver implements EnsResolver {
readonly provider: BaseProvider;
readonly name: string;
readonly address: string;
readonly _resolvedAddress: null | string;
// For EIP-2544 names, the ancestor that provided the resolver
_supportsEip2544: null | Promise<boolean>;
// The resolvedAddress is only for creating a ReverseLookup resolver
constructor(provider: BaseProvider, address: string, name: string, resolvedAddress?: string) {
defineReadOnly(this, "provider", provider);
defineReadOnly(this, "name", name);
defineReadOnly(this, "address", provider.formatter.address(address));
defineReadOnly(this, "_resolvedAddress", resolvedAddress);
}
supportsWildcard(): Promise<boolean> {
if (!this._supportsEip2544) {
// supportsInterface(bytes4 = selector("resolve(bytes,bytes)"))
this._supportsEip2544 = this.provider.call({
to: this.address,
data: "0x01ffc9a79061b92300000000000000000000000000000000000000000000000000000000"
}).then((result) => {
return BigNumber.from(result).eq(1);
}).catch((error) => {
if (error.code === Logger.errors.CALL_EXCEPTION) { return false; }
// Rethrow the error: link is down, etc. Let future attempts retry.
this._supportsEip2544 = null;
throw error;
});
}
return this._supportsEip2544;
}
async _fetch(selector: string, parameters?: string): Promise<null | string> {
// e.g. keccak256("addr(bytes32,uint256)")
const tx = {
to: this.address,
ccipReadEnabled: true,
data: hexConcat([ selector, namehash(this.name), (parameters || "0x") ])
};
// Wildcard support; use EIP-2544 to resolve the request
let parseBytes = false;
if (await this.supportsWildcard()) {
parseBytes = true;
// selector("resolve(bytes,bytes)")
tx.data = hexConcat([ "0x9061b923", encodeBytes([ dnsEncode(this.name), tx.data ]) ]);
}
try {
let result = await this.provider.call(tx);
if ((arrayify(result).length % 32) === 4) {
logger.throwError("resolver threw error", Logger.errors.CALL_EXCEPTION, {
transaction: tx, data: result
});
}
if (parseBytes) { result = _parseBytes(result, 0); }
return result;
} catch (error) {
if (error.code === Logger.errors.CALL_EXCEPTION) { return null; }
throw error;
}
}
async _fetchBytes(selector: string, parameters?: string): Promise<null | string> {
const result = await this._fetch(selector, parameters);
if (result != null) { return _parseBytes(result, 0); }
return null;
}
_getAddress(coinType: number, hexBytes: string): string {
const coinInfo = coinInfos[String(coinType)];
if (coinInfo == null) {
logger.throwError(`unsupported coin type: ${ coinType }`, Logger.errors.UNSUPPORTED_OPERATION, {
operation: `getAddress(${ coinType })`
});
}
if (coinInfo.ilk === "eth") {
return this.provider.formatter.address(hexBytes);
}
const bytes = arrayify(hexBytes);
// P2PKH: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
if (coinInfo.p2pkh != null) {
const p2pkh = hexBytes.match(/^0x76a9([0-9a-f][0-9a-f])([0-9a-f]*)88ac$/);
if (p2pkh) {
const length = parseInt(p2pkh[1], 16);
if (p2pkh[2].length === length * 2 && length >= 1 && length <= 75) {
return base58Encode(concat([ [ coinInfo.p2pkh ], ("0x" + p2pkh[2]) ]));
}
}
}
// P2SH: OP_HASH160 <scriptHash> OP_EQUAL
if (coinInfo.p2sh != null) {
const p2sh = hexBytes.match(/^0xa9([0-9a-f][0-9a-f])([0-9a-f]*)87$/);
if (p2sh) {
const length = parseInt(p2sh[1], 16);
if (p2sh[2].length === length * 2 && length >= 1 && length <= 75) {
return base58Encode(concat([ [ coinInfo.p2sh ], ("0x" + p2sh[2]) ]));
}
}
}
// Bech32
if (coinInfo.prefix != null) {
const length = bytes[1];
// https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program
let version = bytes[0];
if (version === 0x00) {
if (length !== 20 && length !== 32) {
version = -1;
}
} else {
version = -1;
}
if (version >= 0 && bytes.length === 2 + length && length >= 1 && length <= 75) {
const words = bech32.toWords(bytes.slice(2));
words.unshift(version);
return bech32.encode(coinInfo.prefix, words);
}
}
return null;
}
async getAddress(coinType?: number): Promise<string> {
if (coinType == null) { coinType = 60; }
// If Ethereum, use the standard `addr(bytes32)`
if (coinType === 60) {
try {
// keccak256("addr(bytes32)")
const result = await this._fetch("0x3b3b57de");
// No address
if (result === "0x" || result === HashZero) { return null; }
return this.provider.formatter.callAddress(result);
} catch (error) {
if (error.code === Logger.errors.CALL_EXCEPTION) { return null; }
throw error;
}
}
// keccak256("addr(bytes32,uint256")
const hexBytes = await this._fetchBytes("0xf1cb7e06", bytes32ify(coinType));
// No address
if (hexBytes == null || hexBytes === "0x") { return null; }
// Compute the address
const address = this._getAddress(coinType, hexBytes);
if (address == null) {
logger.throwError(`invalid or unsupported coin data`, Logger.errors.UNSUPPORTED_OPERATION, {
operation: `getAddress(${ coinType })`,
coinType: coinType,
data: hexBytes
});
}
return address;
}
async getAvatar(): Promise<null | Avatar> {
const linkage: Array<{ type: string, content: string }> = [ { type: "name", content: this.name } ];
try {
// test data for ricmoo.eth
//const avatar = "eip155:1/erc721:0x265385c7f4132228A0d54EB1A9e7460b91c0cC68/29233";
const avatar = await this.getText("avatar");
if (avatar == null) { return null; }
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":
linkage.push({ type: "url", content: avatar });
return { linkage, url: avatar };
case "data":
linkage.push({ type: "data", content: avatar });
return { linkage, url: avatar };
case "ipfs":
linkage.push({ type: "ipfs", content: avatar });
return { linkage, url: getIpfsLink(avatar) };
case "erc721":
case "erc1155": {
// Depending on the ERC type, use tokenURI(uint256) or url(uint256)
const selector = (scheme === "erc721") ? "0xc87b56dd": "0x0e89341c";
linkage.push({ type: scheme, content: avatar });
// The owner of this name
const owner = (this._resolvedAddress || await this.getAddress());
const comps = (match[2] || "").split("/");
if (comps.length !== 2) { return null; }
const addr = await this.provider.formatter.address(comps[0]);
const tokenId = hexZeroPad(BigNumber.from(comps[1]).toHexString(), 32);
// Check that this account owns the token
if (scheme === "erc721") {
// ownerOf(uint256 tokenId)
const tokenOwner = this.provider.formatter.callAddress(await this.provider.call({
to: addr, data: hexConcat([ "0x6352211e", tokenId ])
}));
if (owner !== tokenOwner) { return null; }
linkage.push({ type: "owner", content: tokenOwner });
} else if (scheme === "erc1155") {
// balanceOf(address owner, uint256 tokenId)
const balance = BigNumber.from(await this.provider.call({
to: addr, data: hexConcat([ "0x00fdd58e", hexZeroPad(owner, 32), tokenId ])
}));
if (balance.isZero()) { return null; }
linkage.push({ type: "balance", content: balance.toString() });
}
// Call the token contract for the metadata URL
const tx = {
to: this.provider.formatter.address(comps[0]),
data: hexConcat([ selector, tokenId ])
};
let metadataUrl = _parseString(await this.provider.call(tx), 0);
if (metadataUrl == null) { return null; }
linkage.push({ type: "metadata-url-base", content: metadataUrl });
// ERC-1155 allows a generic {id} in the URL
if (scheme === "erc1155") {
metadataUrl = metadataUrl.replace("{id}", tokenId.substring(2));
linkage.push({ type: "metadata-url-expanded", content: metadataUrl });
}
// Transform IPFS metadata links
if (metadataUrl.match(/^ipfs:/i)) {
metadataUrl = getIpfsLink(metadataUrl);
}
linkage.push({ type: "metadata-url", content: metadataUrl });
// Get the token metadata
const metadata = await fetchJson(metadataUrl);
if (!metadata) { return null; }
linkage.push({ type: "metadata", content: JSON.stringify(metadata) });
// Pull the image URL out
let imageUrl = metadata.image;
if (typeof(imageUrl) !== "string") { return null; }
if (imageUrl.match(/^(https:\/\/|data:)/i)) {
// Allow
} else {
// Transform IPFS link to gateway
const ipfs = imageUrl.match(matcherIpfs);
if (ipfs == null) { return null; }
linkage.push({ type: "url-ipfs", content: imageUrl });
imageUrl = getIpfsLink(imageUrl);
}
linkage.push({ type: "url", content: imageUrl });
return { linkage, url: imageUrl };
}
}
}
} catch (error) { }
return null;
}
async getContentHash(): Promise<string> {
// keccak256("contenthash()")
const hexBytes = await this._fetchBytes("0xbc1c58d1");
// No contenthash
if (hexBytes == null || hexBytes === "0x") { return null; }
// IPFS (CID: 1, Type: DAG-PB)
const ipfs = hexBytes.match(/^0xe3010170(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);
if (ipfs) {
const length = parseInt(ipfs[3], 16);
if (ipfs[4].length === length * 2) {
return "ipfs:/\/" + Base58.encode("0x" + ipfs[1]);
}
}
// IPNS (CID: 1, Type: libp2p-key)
const ipns = hexBytes.match(/^0xe5010172(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);
if (ipns) {
const length = parseInt(ipns[3], 16);
if (ipns[4].length === length * 2) {
return "ipns:/\/" + Base58.encode("0x" + ipns[1]);
}
}
// Swarm (CID: 1, Type: swarm-manifest; hash/length hard-coded to keccak256/32)
const swarm = hexBytes.match(/^0xe40101fa011b20([0-9a-f]*)$/)
if (swarm) {
if (swarm[1].length === (32 * 2)) {
return "bzz:/\/" + swarm[1]
}
}
const skynet = hexBytes.match(/^0x90b2c605([0-9a-f]*)$/);
if (skynet) {
if (skynet[1].length === (34 * 2)) {
// URL Safe base64; https://datatracker.ietf.org/doc/html/rfc4648#section-5
const urlSafe: Record<string, string> = { "=": "", "+": "-", "/": "_" };
const hash = base64Encode("0x" + skynet[1]).replace(/[=+\/]/g, (a) => (urlSafe[a]));
return "sia:/\/" + hash;
}
}
return logger.throwError(`invalid or unsupported content hash data`, Logger.errors.UNSUPPORTED_OPERATION, {
operation: "getContentHash()",
data: hexBytes
});
}
async getText(key: string): Promise<string> {
// The key encoded as parameter to fetchBytes
let keyBytes = toUtf8Bytes(key);
// The nodehash consumes the first slot, so the string pointer targets
// offset 64, with the length at offset 64 and data starting at offset 96
keyBytes = concat([ bytes32ify(64), bytes32ify(keyBytes.length), keyBytes ]);
// Pad to word-size (32 bytes)
if ((keyBytes.length % 32) !== 0) {
keyBytes = concat([ keyBytes, hexZeroPad("0x", 32 - (key.length % 32)) ])
}
const hexBytes = await this._fetchBytes("0x59d1d43c", hexlify(keyBytes));
if (hexBytes == null || hexBytes === "0x") { return null; }
return toUtf8String(hexBytes);
}
}
let defaultFormatter: Formatter = null;
let nextPollId = 1;
export class BaseProvider extends Provider implements EnsProvider {
_networkPromise: Promise<Network>;
_network: Network;
_events: Array<Event>;
formatter: Formatter;
// To help mitigate the eventually consistent nature of the blockchain
// we keep a mapping of events we emit. If we emit an event X, we expect
// that a user should be able to query for that event in the callback,
// if the node returns null, we stall the response until we get back a
// meaningful value, since we may be hitting a re-org, or a node that
// has not indexed the event yet.
// Events:
// - t:{hash} - Transaction hash
// - b:{hash} - BlockHash
// - block - The most recent emitted block
_emitted: { [ eventName: string ]: number | "pending" };
_pollingInterval: number;
_poller: NodeJS.Timer;
_bootstrapPoll: NodeJS.Timer;
_lastBlockNumber: number;
_maxFilterBlockRange: number;
_fastBlockNumber: number;
_fastBlockNumberPromise: Promise<number>;
_fastQueryDate: number;
_maxInternalBlockNumber: number;
_internalBlockNumber: Promise<{ blockNumber: number, reqTime: number, respTime: number }>;
readonly anyNetwork: boolean;
disableCcipRead: boolean;
/**
* ready
*
* A Promise<Network> that resolves only once the provider is ready.
*
* Sub-classes that call the super with a network without a chainId
* MUST set this. Standard named networks have a known chainId.
*
*/
constructor(network: Networkish | Promise<Network>) {
super();
// Events being listened to
this._events = [];
this._emitted = { block: -2 };
this.disableCcipRead = false;
this.formatter = new.target.getFormatter();
// If network is any, this Provider allows the underlying
// network to change dynamically, and we auto-detect the
// current network
defineReadOnly(this, "anyNetwork", (network === "any"));
if (this.anyNetwork) { network = this.detectNetwork(); }
if (network instanceof Promise) {
this._networkPromise = network;
// Squash any "unhandled promise" errors; that do not need to be handled
network.catch((error) => { });
// Trigger initial network setting (async)
this._ready().catch((error) => { });
} else {
const knownNetwork = getStatic<(network: Networkish) => Network>(new.target, "getNetwork")(network);
if (knownNetwork) {
defineReadOnly(this, "_network", knownNetwork);
this.emit("network", knownNetwork, null);
} else {
logger.throwArgumentError("invalid network", "network", network);
}
}
this._maxInternalBlockNumber = -1024;
this._lastBlockNumber = -2;
this._maxFilterBlockRange = 10;
this._pollingInterval = 4000;
this._fastQueryDate = 0;
}
async _ready(): Promise<Network> {
if (this._network == null) {
let network: Network = null;
if (this._networkPromise) {
try {
network = await this._networkPromise;
} catch (error) { }
}
// Try the Provider's network detection (this MUST throw if it cannot)
if (network == null) {
network = await this.detectNetwork();
}
// This should never happen; every Provider sub-class should have
// suggested a network by here (or have thrown).
if (!network) {
logger.throwError("no network detected", Logger.errors.UNKNOWN_ERROR, { });
}
// Possible this call stacked so do not call defineReadOnly again
if (this._network == null) {
if (this.anyNetwork) {
this._network = network;
} else {
defineReadOnly(this, "_network", network);
}
this.emit("network", network, null);
}
}
return this._network;
}
// This will always return the most recently established network.
// For "any", this can change (a "network" event is emitted before
// any change is reflected); otherwise this cannot change
get ready(): Promise<Network> {
return poll(() => {
return this._ready().then((network) => {
return network;
}, (error) => {
// If the network isn't running yet, we will wait
if (error.code === Logger.errors.NETWORK_ERROR && error.event === "noNetwork") {
return undefined;
}
throw error;
});
});
}
// @TODO: Remove this and just create a singleton formatter
static getFormatter(): Formatter {
if (defaultFormatter == null) {
defaultFormatter = new Formatter();
}
return defaultFormatter;
}
// @TODO: Remove this and just use getNetwork
static getNetwork(network: Networkish): Network {
return getNetwork((network == null) ? "homestead": network);
}
async ccipReadFetch(tx: Transaction, calldata: string, urls: Array<string>): Promise<null | string> {
if (this.disableCcipRead || urls.length === 0) { return null; }
const sender = tx.to.toLowerCase();
const data = calldata.toLowerCase();
const errorMessages: Array<string> = [ ];
for (let i = 0; i < urls.length; i++) {
const url = urls[i];
// URL expansion
const href = url.replace("{sender}", sender).replace("{data}", data);
// If no {data} is present, use POST; otherwise GET
const json: string | null = (url.indexOf("{data}") >= 0) ? null: JSON.stringify({ data, sender });
const result = await fetchJson({ url: href, errorPassThrough: true }, json, (value, response) => {
value.status = response.statusCode;
return value;
});
if (result.data) { return result.data; }
const errorMessage = (result.message || "unknown error");
// 4xx indicates the result is not present; stop
if (result.status >= 400 && result.status < 500) {
return logger.throwError(`response not found during CCIP fetch: ${ errorMessage }`, Logger.errors.SERVER_ERROR, { url, errorMessage });
}
// 5xx indicates server issue; try the next url
errorMessages.push(errorMessage);
}
return logger.throwError(`error encountered during CCIP fetch: ${ errorMessages.map((m) => JSON.stringify(m)).join(", ") }`, Logger.errors.SERVER_ERROR, {
urls, errorMessages
});
}
// Fetches the blockNumber, but will reuse any result that is less
// than maxAge old or has been requested since the last request
async _getInternalBlockNumber(maxAge: number): Promise<number> {
await this._ready();
// Allowing stale data up to maxAge old
if (maxAge > 0) {
// While there are pending internal block requests...
while (this._internalBlockNumber) {
// ..."remember" which fetch we started with
const internalBlockNumber = this._internalBlockNumber;
try {
// Check the result is not too stale
const result = await internalBlockNumber;
if ((getTime() - result.respTime) <= maxAge) {
return result.blockNumber;
}
// Too old; fetch a new value
break;
} catch(error) {
// The fetch rejected; if we are the first to get the
// rejection, drop through so we replace it with a new
// fetch; all others blocked will then get that fetch
// which won't match the one they "remembered" and loop
if (this._internalBlockNumber === internalBlockNumber) {
break;
}
}
}
}
const reqTime = getTime();
const checkInternalBlockNumber = resolveProperties({
blockNumber: this.perform("getBlockNumber", { }),
networkError: this.getNetwork().then((network) => (null), (error) => (error))
}).then(({ blockNumber, networkError }) => {
if (networkError) {
// Unremember this bad internal block number
if (this._internalBlockNumber === checkInternalBlockNumber) {
this._internalBlockNumber = null;
}
throw networkError;
}
const respTime = getTime();
blockNumber = BigNumber.from(blockNumber).toNumber();
if (blockNumber < this._maxInternalBlockNumber) { blockNumber = this._maxInternalBlockNumber; }
this._maxInternalBlockNumber = blockNumber;
this._setFastBlockNumber(blockNumber); // @TODO: Still need this?
return { blockNumber, reqTime, respTime };
});
this._internalBlockNumber = checkInternalBlockNumber;
// Swallow unhandled exceptions; if needed they are handled else where
checkInternalBlockNumber.catch((error) => {
// Don't null the dead (rejected) fetch, if it has already been updated
if (this._internalBlockNumber === checkInternalBlockNumber) {
this._internalBlockNumber = null;
}
});
return (await checkInternalBlockNumber).blockNumber;
}
async poll(): Promise<void> {
const pollId = nextPollId++;
// Track all running promises, so we can trigger a post-poll once they are complete
const runners: Array<Promise<void>> = [];
let blockNumber: number = null;
try {
blockNumber = await this._getInternalBlockNumber(100 + this.pollingInterval / 2);
} catch (error) {
this.emit("error", error);
return;
}
this._setFastBlockNumber(blockNumber);
// Emit a poll event after we have the latest (fast) block number
this.emit("poll", pollId, blockNumber);
// If the block has not changed, meh.
if (blockNumber === this._lastBlockNumber) {
this.emit("didPoll", pollId);
return;
}