UNPKG

63 kBPlain TextView Raw
1"use strict";
2
3import {
4 Block, BlockTag, BlockWithTransactions, EventType, Filter, FilterByBlockHash, ForkEvent,
5 Listener, Log, Provider, TransactionReceipt, TransactionRequest, TransactionResponse
6} from "@ethersproject/abstract-provider";
7import { Base58 } from "@ethersproject/basex";
8import { BigNumber, BigNumberish } from "@ethersproject/bignumber";
9import { arrayify, concat, hexConcat, hexDataLength, hexDataSlice, hexlify, hexValue, hexZeroPad, isHexString } from "@ethersproject/bytes";
10import { HashZero } from "@ethersproject/constants";
11import { namehash } from "@ethersproject/hash";
12import { getNetwork, Network, Networkish } from "@ethersproject/networks";
13import { Deferrable, defineReadOnly, getStatic, resolveProperties } from "@ethersproject/properties";
14import { Transaction } from "@ethersproject/transactions";
15import { sha256 } from "@ethersproject/sha2";
16import { toUtf8Bytes, toUtf8String } from "@ethersproject/strings";
17import { poll } from "@ethersproject/web";
18
19import bech32 from "bech32";
20
21import { Logger } from "@ethersproject/logger";
22import { version } from "./_version";
23const logger = new Logger(version);
24
25import { Formatter } from "./formatter";
26
27//////////////////////////////
28// Event Serializeing
29
30function checkTopic(topic: string): string {
31 if (topic == null) { return "null"; }
32 if (hexDataLength(topic) !== 32) {
33 logger.throwArgumentError("invalid topic", "topic", topic);
34 }
35 return topic.toLowerCase();
36}
37
38function serializeTopics(topics: Array<string | Array<string>>): string {
39 // Remove trailing null AND-topics; they are redundant
40 topics = topics.slice();
41 while (topics.length > 0 && topics[topics.length - 1] == null) { topics.pop(); }
42
43 return topics.map((topic) => {
44 if (Array.isArray(topic)) {
45
46 // Only track unique OR-topics
47 const unique: { [ topic: string ]: boolean } = { }
48 topic.forEach((topic) => {
49 unique[checkTopic(topic)] = true;
50 });
51
52 // The order of OR-topics does not matter
53 const sorted = Object.keys(unique);
54 sorted.sort();
55
56 return sorted.join("|");
57
58 } else {
59 return checkTopic(topic);
60 }
61 }).join("&");
62}
63
64function deserializeTopics(data: string): Array<string | Array<string>> {
65 if (data === "") { return [ ]; }
66
67 return data.split(/&/g).map((topic) => {
68 if (topic === "") { return [ ]; }
69
70 const comps = topic.split("|").map((topic) => {
71 return ((topic === "null") ? null: topic);
72 });
73
74 return ((comps.length === 1) ? comps[0]: comps);
75 });
76}
77
78function getEventTag(eventName: EventType): string {
79 if (typeof(eventName) === "string") {
80 eventName = eventName.toLowerCase();
81
82 if (hexDataLength(eventName) === 32) {
83 return "tx:" + eventName;
84 }
85
86 if (eventName.indexOf(":") === -1) {
87 return eventName;
88 }
89
90 } else if (Array.isArray(eventName)) {
91 return "filter:*:" + serializeTopics(eventName);
92
93 } else if (ForkEvent.isForkEvent(eventName)) {
94 logger.warn("not implemented");
95 throw new Error("not implemented");
96
97 } else if (eventName && typeof(eventName) === "object") {
98 return "filter:" + (eventName.address || "*") + ":" + serializeTopics(eventName.topics || []);
99 }
100
101 throw new Error("invalid event - " + eventName);
102}
103
104//////////////////////////////
105// Helper Object
106
107function getTime() {
108 return (new Date()).getTime();
109}
110
111function stall(duration: number): Promise<void> {
112 return new Promise((resolve) => {
113 setTimeout(resolve, duration);
114 });
115}
116
117//////////////////////////////
118// Provider Object
119
120
121/**
122 * EventType
123 * - "block"
124 * - "poll"
125 * - "didPoll"
126 * - "pending"
127 * - "error"
128 * - "network"
129 * - filter
130 * - topics array
131 * - transaction hash
132 */
133
134const PollableEvents = [ "block", "network", "pending", "poll" ];
135
136export class Event {
137 readonly listener: Listener;
138 readonly once: boolean;
139 readonly tag: string;
140
141 constructor(tag: string, listener: Listener, once: boolean) {
142 defineReadOnly(this, "tag", tag);
143 defineReadOnly(this, "listener", listener);
144 defineReadOnly(this, "once", once);
145 }
146
147 get event(): EventType {
148 switch (this.type) {
149 case "tx":
150 return this.hash;
151 case "filter":
152 return this.filter;
153 }
154 return this.tag;
155 }
156
157 get type(): string {
158 return this.tag.split(":")[0]
159 }
160
161 get hash(): string {
162 const comps = this.tag.split(":");
163 if (comps[0] !== "tx") { return null; }
164 return comps[1];
165 }
166
167 get filter(): Filter {
168 const comps = this.tag.split(":");
169 if (comps[0] !== "filter") { return null; }
170 const address = comps[1];
171
172 const topics = deserializeTopics(comps[2]);
173 const filter: Filter = { };
174
175 if (topics.length > 0) { filter.topics = topics; }
176 if (address && address !== "*") { filter.address = address; }
177
178 return filter;
179 }
180
181 pollable(): boolean {
182 return (this.tag.indexOf(":") >= 0 || PollableEvents.indexOf(this.tag) >= 0);
183 }
184}
185
186export interface EnsResolver {
187
188 // Name this Resolver is associated with
189 readonly name: string;
190
191 // The address of the resolver
192 readonly address: string;
193
194 // Multichain address resolution (also normal address resolution)
195 // See: https://eips.ethereum.org/EIPS/eip-2304
196 getAddress(coinType?: 60): Promise<string>
197
198 // Contenthash field
199 // See: https://eips.ethereum.org/EIPS/eip-1577
200 getContentHash(): Promise<string>;
201
202 // Storage of text records
203 // See: https://eips.ethereum.org/EIPS/eip-634
204 getText(key: string): Promise<string>;
205};
206
207export interface EnsProvider {
208 resolveName(name: string): Promise<string>;
209 lookupAddress(address: string): Promise<string>;
210 getResolver(name: string): Promise<EnsResolver>;
211}
212
213type CoinInfo = {
214 symbol: string,
215 ilk?: string, // General family
216 prefix?: string, // Bech32 prefix
217 p2pkh?: number, // Pay-to-Public-Key-Hash Version
218 p2sh?: number, // Pay-to-Script-Hash Version
219};
220
221// https://github.com/satoshilabs/slips/blob/master/slip-0044.md
222const coinInfos: { [ coinType: string ]: CoinInfo } = {
223 "0": { symbol: "btc", p2pkh: 0x00, p2sh: 0x05, prefix: "bc" },
224 "2": { symbol: "ltc", p2pkh: 0x30, p2sh: 0x32, prefix: "ltc" },
225 "3": { symbol: "doge", p2pkh: 0x1e, p2sh: 0x16 },
226 "60": { symbol: "eth", ilk: "eth" },
227 "61": { symbol: "etc", ilk: "eth" },
228 "700": { symbol: "xdai", ilk: "eth" },
229};
230
231function bytes32ify(value: number): string {
232 return hexZeroPad(BigNumber.from(value).toHexString(), 32);
233}
234
235// Compute the Base58Check encoded data (checksum is first 4 bytes of sha256d)
236function base58Encode(data: Uint8Array): string {
237 return Base58.encode(concat([ data, hexDataSlice(sha256(sha256(data)), 0, 4) ]));
238}
239
240export class Resolver implements EnsResolver {
241 readonly provider: BaseProvider;
242
243 readonly name: string;
244 readonly address: string;
245
246 constructor(provider: BaseProvider, address: string, name: string) {
247 defineReadOnly(this, "provider", provider);
248 defineReadOnly(this, "name", name);
249 defineReadOnly(this, "address", provider.formatter.address(address));
250 }
251
252 async _fetchBytes(selector: string, parameters?: string): Promise<string> {
253 // keccak256("addr(bytes32,uint256)")
254 const transaction = {
255 to: this.address,
256 data: hexConcat([ selector, namehash(this.name), (parameters || "0x") ])
257 };
258
259 try {
260 const result = await this.provider.call(transaction);
261 if (result === "0x") { return null; }
262
263 const offset = BigNumber.from(hexDataSlice(result, 0, 32)).toNumber();
264 const length = BigNumber.from(hexDataSlice(result, offset, offset + 32)).toNumber();
265 return hexDataSlice(result, offset + 32, offset + 32 + length);
266 } catch (error) {
267 if (error.code === Logger.errors.CALL_EXCEPTION) { return null; }
268 return null;
269 }
270 }
271
272 _getAddress(coinType: number, hexBytes: string): string {
273 const coinInfo = coinInfos[String(coinType)];
274
275 if (coinInfo == null) {
276 logger.throwError(`unsupported coin type: ${ coinType }`, Logger.errors.UNSUPPORTED_OPERATION, {
277 operation: `getAddress(${ coinType })`
278 });
279 }
280
281 if (coinInfo.ilk === "eth") {
282 return this.provider.formatter.address(hexBytes);
283 }
284
285 const bytes = arrayify(hexBytes);
286
287 // P2PKH: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
288 if (coinInfo.p2pkh != null) {
289 const p2pkh = hexBytes.match(/^0x76a9([0-9a-f][0-9a-f])([0-9a-f]*)88ac$/);
290 if (p2pkh) {
291 const length = parseInt(p2pkh[1], 16);
292 if (p2pkh[2].length === length * 2 && length >= 1 && length <= 75) {
293 return base58Encode(concat([ [ coinInfo.p2pkh ], ("0x" + p2pkh[2]) ]));
294 }
295 }
296 }
297
298 // P2SH: OP_HASH160 <scriptHash> OP_EQUAL
299 if (coinInfo.p2sh != null) {
300 const p2sh = hexBytes.match(/^0xa9([0-9a-f][0-9a-f])([0-9a-f]*)87$/);
301 if (p2sh) {
302 const length = parseInt(p2sh[1], 16);
303 if (p2sh[2].length === length * 2 && length >= 1 && length <= 75) {
304 return base58Encode(concat([ [ coinInfo.p2sh ], ("0x" + p2sh[2]) ]));
305 }
306 }
307 }
308
309 // Bech32
310 if (coinInfo.prefix != null) {
311 const length = bytes[1];
312
313 // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program
314 let version = bytes[0];
315 if (version === 0x00) {
316 if (length !== 20 && length !== 32) {
317 version = -1;
318 }
319 } else {
320 version = -1;
321 }
322
323 if (version >= 0 && bytes.length === 2 + length && length >= 1 && length <= 75) {
324 const words = bech32.toWords(bytes.slice(2));
325 words.unshift(version);
326 return bech32.encode(coinInfo.prefix, words);
327 }
328 }
329
330 return null;
331 }
332
333
334 async getAddress(coinType?: number): Promise<string> {
335 if (coinType == null) { coinType = 60; }
336
337 // If Ethereum, use the standard `addr(bytes32)`
338 if (coinType === 60) {
339 try {
340 // keccak256("addr(bytes32)")
341 const transaction = {
342 to: this.address,
343 data: ("0x3b3b57de" + namehash(this.name).substring(2))
344 };
345 const hexBytes = await this.provider.call(transaction);
346
347 // No address
348 if (hexBytes === "0x" || hexBytes === HashZero) { return null; }
349
350 return this.provider.formatter.callAddress(hexBytes);
351 } catch (error) {
352 if (error.code === Logger.errors.CALL_EXCEPTION) { return null; }
353 throw error;
354 }
355 }
356
357 // keccak256("addr(bytes32,uint256")
358 const hexBytes = await this._fetchBytes("0xf1cb7e06", bytes32ify(coinType));
359
360 // No address
361 if (hexBytes == null || hexBytes === "0x") { return null; }
362
363 // Compute the address
364 const address = this._getAddress(coinType, hexBytes);
365
366 if (address == null) {
367 logger.throwError(`invalid or unsupported coin data`, Logger.errors.UNSUPPORTED_OPERATION, {
368 operation: `getAddress(${ coinType })`,
369 coinType: coinType,
370 data: hexBytes
371 });
372 }
373
374 return address;
375 }
376
377 async getContentHash(): Promise<string> {
378
379 // keccak256("contenthash()")
380 const hexBytes = await this._fetchBytes("0xbc1c58d1");
381
382 // No contenthash
383 if (hexBytes == null || hexBytes === "0x") { return null; }
384
385 // IPFS (CID: 1, Type: DAG-PB)
386 const ipfs = hexBytes.match(/^0xe3010170(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);
387 if (ipfs) {
388 const length = parseInt(ipfs[3], 16);
389 if (ipfs[4].length === length * 2) {
390 return "ipfs:/\/" + Base58.encode("0x" + ipfs[1]);
391 }
392 }
393
394 // Swarm (CID: 1, Type: swarm-manifest; hash/length hard-coded to keccak256/32)
395 const swarm = hexBytes.match(/^0xe40101fa011b20([0-9a-f]*)$/)
396 if (swarm) {
397 if (swarm[1].length === (32 * 2)) {
398 return "bzz:/\/" + swarm[1]
399 }
400 }
401
402 return logger.throwError(`invalid or unsupported content hash data`, Logger.errors.UNSUPPORTED_OPERATION, {
403 operation: "getContentHash()",
404 data: hexBytes
405 });
406 }
407
408 async getText(key: string): Promise<string> {
409
410 // The key encoded as parameter to fetchBytes
411 let keyBytes = toUtf8Bytes(key);
412
413 // The nodehash consumes the first slot, so the string pointer targets
414 // offset 64, with the length at offset 64 and data starting at offset 96
415 keyBytes = concat([ bytes32ify(64), bytes32ify(keyBytes.length), keyBytes ]);
416
417 // Pad to word-size (32 bytes)
418 if ((keyBytes.length % 32) !== 0) {
419 keyBytes = concat([ keyBytes, hexZeroPad("0x", 32 - (key.length % 32)) ])
420 }
421
422 const hexBytes = await this._fetchBytes("0x59d1d43c", hexlify(keyBytes));
423 if (hexBytes == null || hexBytes === "0x") { return null; }
424
425 return toUtf8String(hexBytes);
426 }
427}
428
429let defaultFormatter: Formatter = null;
430
431let nextPollId = 1;
432
433export class BaseProvider extends Provider implements EnsProvider {
434 _networkPromise: Promise<Network>;
435 _network: Network;
436
437 _events: Array<Event>;
438
439 formatter: Formatter;
440
441 // To help mitigate the eventually consistent nature of the blockchain
442 // we keep a mapping of events we emit. If we emit an event X, we expect
443 // that a user should be able to query for that event in the callback,
444 // if the node returns null, we stall the response until we get back a
445 // meaningful value, since we may be hitting a re-org, or a node that
446 // has not indexed the event yet.
447 // Events:
448 // - t:{hash} - Transaction hash
449 // - b:{hash} - BlockHash
450 // - block - The most recent emitted block
451 _emitted: { [ eventName: string ]: number | "pending" };
452
453 _pollingInterval: number;
454 _poller: NodeJS.Timer;
455 _bootstrapPoll: NodeJS.Timer;
456
457 _lastBlockNumber: number;
458
459 _fastBlockNumber: number;
460 _fastBlockNumberPromise: Promise<number>;
461 _fastQueryDate: number;
462
463 _maxInternalBlockNumber: number;
464 _internalBlockNumber: Promise<{ blockNumber: number, reqTime: number, respTime: number }>;
465
466 readonly anyNetwork: boolean;
467
468
469 /**
470 * ready
471 *
472 * A Promise<Network> that resolves only once the provider is ready.
473 *
474 * Sub-classes that call the super with a network without a chainId
475 * MUST set this. Standard named networks have a known chainId.
476 *
477 */
478
479 constructor(network: Networkish | Promise<Network>) {
480 logger.checkNew(new.target, Provider);
481
482 super();
483
484 // Events being listened to
485 this._events = [];
486
487 this._emitted = { block: -2 };
488
489 this.formatter = new.target.getFormatter();
490
491 // If network is any, this Provider allows the underlying
492 // network to change dynamically, and we auto-detect the
493 // current network
494 defineReadOnly(this, "anyNetwork", (network === "any"));
495 if (this.anyNetwork) { network = this.detectNetwork(); }
496
497 if (network instanceof Promise) {
498 this._networkPromise = network;
499
500 // Squash any "unhandled promise" errors; that do not need to be handled
501 network.catch((error) => { });
502
503 // Trigger initial network setting (async)
504 this._ready().catch((error) => { });
505
506 } else {
507 const knownNetwork = getStatic<(network: Networkish) => Network>(new.target, "getNetwork")(network);
508 if (knownNetwork) {
509 defineReadOnly(this, "_network", knownNetwork);
510 this.emit("network", knownNetwork, null);
511
512 } else {
513 logger.throwArgumentError("invalid network", "network", network);
514 }
515 }
516
517 this._maxInternalBlockNumber = -1024;
518
519 this._lastBlockNumber = -2;
520
521 this._pollingInterval = 4000;
522
523 this._fastQueryDate = 0;
524 }
525
526 async _ready(): Promise<Network> {
527 if (this._network == null) {
528 let network: Network = null;
529 if (this._networkPromise) {
530 try {
531 network = await this._networkPromise;
532 } catch (error) { }
533 }
534
535 // Try the Provider's network detection (this MUST throw if it cannot)
536 if (network == null) {
537 network = await this.detectNetwork();
538 }
539
540 // This should never happen; every Provider sub-class should have
541 // suggested a network by here (or have thrown).
542 if (!network) {
543 logger.throwError("no network detected", Logger.errors.UNKNOWN_ERROR, { });
544 }
545
546 // Possible this call stacked so do not call defineReadOnly again
547 if (this._network == null) {
548 if (this.anyNetwork) {
549 this._network = network;
550 } else {
551 defineReadOnly(this, "_network", network);
552 }
553 this.emit("network", network, null);
554 }
555 }
556
557 return this._network;
558 }
559
560 // This will always return the most recently established network.
561 // For "any", this can change (a "network" event is emitted before
562 // any change is refelcted); otherwise this cannot change
563 get ready(): Promise<Network> {
564 return poll(() => {
565 return this._ready().then((network) => {
566 return network;
567 }, (error) => {
568 // If the network isn't running yet, we will wait
569 if (error.code === Logger.errors.NETWORK_ERROR && error.event === "noNetwork") {
570 return undefined;
571 }
572 throw error;
573 });
574 });
575 }
576
577 // @TODO: Remove this and just create a singleton formatter
578 static getFormatter(): Formatter {
579 if (defaultFormatter == null) {
580 defaultFormatter = new Formatter();
581 }
582 return defaultFormatter;
583 }
584
585 // @TODO: Remove this and just use getNetwork
586 static getNetwork(network: Networkish): Network {
587 return getNetwork((network == null) ? "homestead": network);
588 }
589
590 // Fetches the blockNumber, but will reuse any result that is less
591 // than maxAge old or has been requested since the last request
592 async _getInternalBlockNumber(maxAge: number): Promise<number> {
593 await this._ready();
594
595 // Allowing stale data up to maxAge old
596 if (maxAge > 0) {
597
598 // While there are pending internal block requests...
599 while (this._internalBlockNumber) {
600
601 // ..."remember" which fetch we started with
602 const internalBlockNumber = this._internalBlockNumber;
603
604 try {
605 // Check the result is not too stale
606 const result = await internalBlockNumber;
607 if ((getTime() - result.respTime) <= maxAge) {
608 return result.blockNumber;
609 }
610
611 // Too old; fetch a new value
612 break;
613
614 } catch(error) {
615
616 // The fetch rejected; if we are the first to get the
617 // rejection, drop through so we replace it with a new
618 // fetch; all others blocked will then get that fetch
619 // which won't match the one they "remembered" and loop
620 if (this._internalBlockNumber === internalBlockNumber) {
621 break;
622 }
623 }
624 }
625 }
626
627 const reqTime = getTime();
628
629 const checkInternalBlockNumber = resolveProperties({
630 blockNumber: this.perform("getBlockNumber", { }),
631 networkError: this.getNetwork().then((network) => (null), (error) => (error))
632 }).then(({ blockNumber, networkError }) => {
633 if (networkError) {
634 // Unremember this bad internal block number
635 if (this._internalBlockNumber === checkInternalBlockNumber) {
636 this._internalBlockNumber = null;
637 }
638 throw networkError;
639 }
640
641 const respTime = getTime();
642
643 blockNumber = BigNumber.from(blockNumber).toNumber();
644 if (blockNumber < this._maxInternalBlockNumber) { blockNumber = this._maxInternalBlockNumber; }
645
646 this._maxInternalBlockNumber = blockNumber;
647 this._setFastBlockNumber(blockNumber); // @TODO: Still need this?
648 return { blockNumber, reqTime, respTime };
649 });
650
651 this._internalBlockNumber = checkInternalBlockNumber;
652
653 // Swallow unhandled exceptions; if needed they are handled else where
654 checkInternalBlockNumber.catch((error) => {
655 // Don't null the dead (rejected) fetch, if it has already been updated
656 if (this._internalBlockNumber === checkInternalBlockNumber) {
657 this._internalBlockNumber = null;
658 }
659 });
660
661 return (await checkInternalBlockNumber).blockNumber;
662 }
663
664 async poll(): Promise<void> {
665 const pollId = nextPollId++;
666
667 // Track all running promises, so we can trigger a post-poll once they are complete
668 const runners: Array<Promise<void>> = [];
669
670 let blockNumber: number = null;
671 try {
672 blockNumber = await this._getInternalBlockNumber(100 + this.pollingInterval / 2);
673 } catch (error) {
674 this.emit("error", error);
675 return;
676 }
677 this._setFastBlockNumber(blockNumber);
678
679 // Emit a poll event after we have the latest (fast) block number
680 this.emit("poll", pollId, blockNumber);
681
682 // If the block has not changed, meh.
683 if (blockNumber === this._lastBlockNumber) {
684 this.emit("didPoll", pollId);
685 return;
686 }
687
688 // First polling cycle, trigger a "block" events
689 if (this._emitted.block === -2) {
690 this._emitted.block = blockNumber - 1;
691 }
692
693 if (Math.abs((<number>(this._emitted.block)) - blockNumber) > 1000) {
694 logger.warn(`network block skew detected; skipping block events (emitted=${ this._emitted.block } blockNumber${ blockNumber })`);
695 this.emit("error", logger.makeError("network block skew detected", Logger.errors.NETWORK_ERROR, {
696 blockNumber: blockNumber,
697 event: "blockSkew",
698 previousBlockNumber: this._emitted.block
699 }));
700 this.emit("block", blockNumber);
701
702 } else {
703 // Notify all listener for each block that has passed
704 for (let i = (<number>this._emitted.block) + 1; i <= blockNumber; i++) {
705 this.emit("block", i);
706 }
707 }
708
709 // The emitted block was updated, check for obsolete events
710 if ((<number>this._emitted.block) !== blockNumber) {
711 this._emitted.block = blockNumber;
712
713 Object.keys(this._emitted).forEach((key) => {
714 // The block event does not expire
715 if (key === "block") { return; }
716
717 // The block we were at when we emitted this event
718 const eventBlockNumber = this._emitted[key];
719
720 // We cannot garbage collect pending transactions or blocks here
721 // They should be garbage collected by the Provider when setting
722 // "pending" events
723 if (eventBlockNumber === "pending") { return; }
724
725 // Evict any transaction hashes or block hashes over 12 blocks
726 // old, since they should not return null anyways
727 if (blockNumber - eventBlockNumber > 12) {
728 delete this._emitted[key];
729 }
730 });
731 }
732
733 // First polling cycle
734 if (this._lastBlockNumber === -2) {
735 this._lastBlockNumber = blockNumber - 1;
736 }
737
738 // Find all transaction hashes we are waiting on
739 this._events.forEach((event) => {
740 switch (event.type) {
741 case "tx": {
742 const hash = event.hash;
743 let runner = this.getTransactionReceipt(hash).then((receipt) => {
744 if (!receipt || receipt.blockNumber == null) { return null; }
745 this._emitted["t:" + hash] = receipt.blockNumber;
746 this.emit(hash, receipt);
747 return null;
748 }).catch((error: Error) => { this.emit("error", error); });
749
750 runners.push(runner);
751
752 break;
753 }
754
755 case "filter": {
756 const filter = event.filter;
757 filter.fromBlock = this._lastBlockNumber + 1;
758 filter.toBlock = blockNumber;
759
760 const runner = this.getLogs(filter).then((logs) => {
761 if (logs.length === 0) { return; }
762 logs.forEach((log: Log) => {
763 this._emitted["b:" + log.blockHash] = log.blockNumber;
764 this._emitted["t:" + log.transactionHash] = log.blockNumber;
765 this.emit(filter, log);
766 });
767 }).catch((error: Error) => { this.emit("error", error); });
768 runners.push(runner);
769
770 break;
771 }
772 }
773 });
774
775 this._lastBlockNumber = blockNumber;
776
777 // Once all events for this loop have been processed, emit "didPoll"
778 Promise.all(runners).then(() => {
779 this.emit("didPoll", pollId);
780 }).catch((error) => { this.emit("error", error); });
781
782 return;
783 }
784
785 // Deprecated; do not use this
786 resetEventsBlock(blockNumber: number): void {
787 this._lastBlockNumber = blockNumber - 1;
788 if (this.polling) { this.poll(); }
789 }
790
791 get network(): Network {
792 return this._network;
793 }
794
795 // This method should query the network if the underlying network
796 // can change, such as when connected to a JSON-RPC backend
797 async detectNetwork(): Promise<Network> {
798 return logger.throwError("provider does not support network detection", Logger.errors.UNSUPPORTED_OPERATION, {
799 operation: "provider.detectNetwork"
800 });
801 }
802
803 async getNetwork(): Promise<Network> {
804 const network = await this._ready();
805
806 // Make sure we are still connected to the same network; this is
807 // only an external call for backends which can have the underlying
808 // network change spontaneously
809 const currentNetwork = await this.detectNetwork();
810 if (network.chainId !== currentNetwork.chainId) {
811
812 // We are allowing network changes, things can get complex fast;
813 // make sure you know what you are doing if you use "any"
814 if (this.anyNetwork) {
815 this._network = currentNetwork;
816
817 // Reset all internal block number guards and caches
818 this._lastBlockNumber = -2;
819 this._fastBlockNumber = null;
820 this._fastBlockNumberPromise = null;
821 this._fastQueryDate = 0;
822 this._emitted.block = -2;
823 this._maxInternalBlockNumber = -1024;
824 this._internalBlockNumber = null;
825
826 // The "network" event MUST happen before this method resolves
827 // so any events have a chance to unregister, so we stall an
828 // additional event loop before returning from /this/ call
829 this.emit("network", currentNetwork, network);
830 await stall(0);
831
832 return this._network;
833 }
834
835 const error = logger.makeError("underlying network changed", Logger.errors.NETWORK_ERROR, {
836 event: "changed",
837 network: network,
838 detectedNetwork: currentNetwork
839 });
840
841 this.emit("error", error);
842 throw error;
843 }
844
845 return network;
846 }
847
848 get blockNumber(): number {
849 this._getInternalBlockNumber(100 + this.pollingInterval / 2).then((blockNumber) => {
850 this._setFastBlockNumber(blockNumber);
851 }, (error) => { });
852
853 return (this._fastBlockNumber != null) ? this._fastBlockNumber: -1;
854 }
855
856 get polling(): boolean {
857 return (this._poller != null);
858 }
859
860 set polling(value: boolean) {
861 if (value && !this._poller) {
862 this._poller = setInterval(() => { this.poll(); }, this.pollingInterval);
863
864 if (!this._bootstrapPoll) {
865 this._bootstrapPoll = setTimeout(() => {
866 this.poll();
867
868 // We block additional polls until the polling interval
869 // is done, to prevent overwhelming the poll function
870 this._bootstrapPoll = setTimeout(() => {
871 // If polling was disabled, something may require a poke
872 // since starting the bootstrap poll and it was disabled
873 if (!this._poller) { this.poll(); }
874
875 // Clear out the bootstrap so we can do another
876 this._bootstrapPoll = null;
877 }, this.pollingInterval);
878 }, 0);
879 }
880
881 } else if (!value && this._poller) {
882 clearInterval(this._poller);
883 this._poller = null;
884 }
885 }
886
887 get pollingInterval(): number {
888 return this._pollingInterval;
889 }
890
891 set pollingInterval(value: number) {
892 if (typeof(value) !== "number" || value <= 0 || parseInt(String(value)) != value) {
893 throw new Error("invalid polling interval");
894 }
895
896 this._pollingInterval = value;
897
898 if (this._poller) {
899 clearInterval(this._poller);
900 this._poller = setInterval(() => { this.poll(); }, this._pollingInterval);
901 }
902 }
903
904 _getFastBlockNumber(): Promise<number> {
905 const now = getTime();
906
907 // Stale block number, request a newer value
908 if ((now - this._fastQueryDate) > 2 * this._pollingInterval) {
909 this._fastQueryDate = now;
910 this._fastBlockNumberPromise = this.getBlockNumber().then((blockNumber) => {
911 if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) {
912 this._fastBlockNumber = blockNumber;
913 }
914 return this._fastBlockNumber;
915 });
916 }
917
918 return this._fastBlockNumberPromise;
919 }
920
921 _setFastBlockNumber(blockNumber: number): void {
922 // Older block, maybe a stale request
923 if (this._fastBlockNumber != null && blockNumber < this._fastBlockNumber) { return; }
924
925 // Update the time we updated the blocknumber
926 this._fastQueryDate = getTime();
927
928 // Newer block number, use it
929 if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) {
930 this._fastBlockNumber = blockNumber;
931 this._fastBlockNumberPromise = Promise.resolve(blockNumber);
932 }
933 }
934
935 async waitForTransaction(transactionHash: string, confirmations?: number, timeout?: number): Promise<TransactionReceipt> {
936 return this._waitForTransaction(transactionHash, (confirmations == null) ? 1: confirmations, timeout || 0, null);
937 }
938
939 async _waitForTransaction(transactionHash: string, confirmations: number, timeout: number, replaceable: { data: string, from: string, nonce: number, to: string, value: BigNumber, startBlock: number }): Promise<TransactionReceipt> {
940 const receipt = await this.getTransactionReceipt(transactionHash);
941
942 // Receipt is already good
943 if ((receipt ? receipt.confirmations: 0) >= confirmations) { return receipt; }
944
945 // Poll until the receipt is good...
946 return new Promise((resolve, reject) => {
947 const cancelFuncs: Array<() => void> = [];
948
949 let done = false;
950 const alreadyDone = function() {
951 if (done) { return true; }
952 done = true;
953 cancelFuncs.forEach((func) => { func(); });
954 return false;
955 };
956
957 const minedHandler = (receipt: TransactionReceipt) => {
958 if (receipt.confirmations < confirmations) { return; }
959 if (alreadyDone()) { return; }
960 resolve(receipt);
961 }
962 this.on(transactionHash, minedHandler);
963 cancelFuncs.push(() => { this.removeListener(transactionHash, minedHandler); });
964
965 if (replaceable) {
966 let lastBlockNumber = replaceable.startBlock;
967 let scannedBlock: number = null;
968 const replaceHandler = async (blockNumber: number) => {
969 if (done) { return; }
970
971 // Wait 1 second; this is only used in the case of a fault, so
972 // we will trade off a little bit of latency for more consistent
973 // results and fewer JSON-RPC calls
974 await stall(1000);
975
976 this.getTransactionCount(replaceable.from).then(async (nonce) => {
977 if (done) { return; }
978
979 if (nonce <= replaceable.nonce) {
980 lastBlockNumber = blockNumber;
981
982 } else {
983 // First check if the transaction was mined
984 {
985 const mined = await this.getTransaction(transactionHash);
986 if (mined && mined.blockNumber != null) { return; }
987 }
988
989 // First time scanning. We start a little earlier for some
990 // wiggle room here to handle the eventually consistent nature
991 // of blockchain (e.g. the getTransactionCount was for a
992 // different block)
993 if (scannedBlock == null) {
994 scannedBlock = lastBlockNumber - 3;
995 if (scannedBlock < replaceable.startBlock) {
996 scannedBlock = replaceable.startBlock;
997 }
998 }
999
1000 while (scannedBlock <= blockNumber) {
1001 if (done) { return; }
1002
1003 const block = await this.getBlockWithTransactions(scannedBlock);
1004 for (let ti = 0; ti < block.transactions.length; ti++) {
1005 const tx = block.transactions[ti];
1006
1007 // Successfully mined!
1008 if (tx.hash === transactionHash) { return; }
1009
1010 // Matches our transaction from and nonce; its a replacement
1011 if (tx.from === replaceable.from && tx.nonce === replaceable.nonce) {
1012 if (done) { return; }
1013
1014 // Get the receipt of the replacement
1015 const receipt = await this.waitForTransaction(tx.hash, confirmations);
1016
1017 // Already resolved or rejected (prolly a timeout)
1018 if (alreadyDone()) { return; }
1019
1020 // The reason we were replaced
1021 let reason = "replaced";
1022 if (tx.data === replaceable.data && tx.to === replaceable.to && tx.value.eq(replaceable.value)) {
1023 reason = "repriced";
1024 } else if (tx.data === "0x" && tx.from === tx.to && tx.value.isZero()) {
1025 reason = "cancelled"
1026 }
1027
1028 // Explain why we were replaced
1029 reject(logger.makeError("transaction was replaced", Logger.errors.TRANSACTION_REPLACED, {
1030 cancelled: (reason === "replaced" || reason === "cancelled"),
1031 reason,
1032 replacement: this._wrapTransaction(tx),
1033 hash: transactionHash,
1034 receipt
1035 }));
1036
1037 return;
1038 }
1039 }
1040 scannedBlock++;
1041 }
1042 }
1043
1044 if (done) { return; }
1045 this.once("block", replaceHandler);
1046
1047 }, (error) => {
1048 if (done) { return; }
1049 this.once("block", replaceHandler);
1050 });
1051 };
1052
1053 if (done) { return; }
1054 this.once("block", replaceHandler);
1055
1056 cancelFuncs.push(() => {
1057 this.removeListener("block", replaceHandler);
1058 });
1059 }
1060
1061 if (typeof(timeout) === "number" && timeout > 0) {
1062 const timer = setTimeout(() => {
1063 if (alreadyDone()) { return; }
1064 reject(logger.makeError("timeout exceeded", Logger.errors.TIMEOUT, { timeout: timeout }));
1065 }, timeout);
1066 if (timer.unref) { timer.unref(); }
1067
1068 cancelFuncs.push(() => { clearTimeout(timer); });
1069 }
1070 });
1071 }
1072
1073 async getBlockNumber(): Promise<number> {
1074 return this._getInternalBlockNumber(0);
1075 }
1076
1077 async getGasPrice(): Promise<BigNumber> {
1078 await this.getNetwork();
1079
1080 const result = await this.perform("getGasPrice", { });
1081 try {
1082 return BigNumber.from(result);
1083 } catch (error) {
1084 return logger.throwError("bad result from backend", Logger.errors.SERVER_ERROR, {
1085 method: "getGasPrice",
1086 result, error
1087 });
1088 }
1089 }
1090
1091 async getBalance(addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag>): Promise<BigNumber> {
1092 await this.getNetwork();
1093 const params = await resolveProperties({
1094 address: this._getAddress(addressOrName),
1095 blockTag: this._getBlockTag(blockTag)
1096 });
1097
1098 const result = await this.perform("getBalance", params);
1099 try {
1100 return BigNumber.from(result);
1101 } catch (error) {
1102 return logger.throwError("bad result from backend", Logger.errors.SERVER_ERROR, {
1103 method: "getBalance",
1104 params, result, error
1105 });
1106 }
1107 }
1108
1109 async getTransactionCount(addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag>): Promise<number> {
1110 await this.getNetwork();
1111 const params = await resolveProperties({
1112 address: this._getAddress(addressOrName),
1113 blockTag: this._getBlockTag(blockTag)
1114 });
1115
1116 const result = await this.perform("getTransactionCount", params);
1117 try {
1118 return BigNumber.from(result).toNumber();
1119 } catch (error) {
1120 return logger.throwError("bad result from backend", Logger.errors.SERVER_ERROR, {
1121 method: "getTransactionCount",
1122 params, result, error
1123 });
1124 }
1125 }
1126
1127 async getCode(addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag>): Promise<string> {
1128 await this.getNetwork();
1129 const params = await resolveProperties({
1130 address: this._getAddress(addressOrName),
1131 blockTag: this._getBlockTag(blockTag)
1132 });
1133
1134 const result = await this.perform("getCode", params);
1135 try {
1136 return hexlify(result);
1137 } catch (error) {
1138 return logger.throwError("bad result from backend", Logger.errors.SERVER_ERROR, {
1139 method: "getCode",
1140 params, result, error
1141 });
1142 }
1143 }
1144
1145 async getStorageAt(addressOrName: string | Promise<string>, position: BigNumberish | Promise<BigNumberish>, blockTag?: BlockTag | Promise<BlockTag>): Promise<string> {
1146 await this.getNetwork();
1147 const params = await resolveProperties({
1148 address: this._getAddress(addressOrName),
1149 blockTag: this._getBlockTag(blockTag),
1150 position: Promise.resolve(position).then((p) => hexValue(p))
1151 });
1152 const result = await this.perform("getStorageAt", params);
1153 try {
1154 return hexlify(result);
1155 } catch (error) {
1156 return logger.throwError("bad result from backend", Logger.errors.SERVER_ERROR, {
1157 method: "getStorageAt",
1158 params, result, error
1159 });
1160 }
1161 }
1162
1163 // This should be called by any subclass wrapping a TransactionResponse
1164 _wrapTransaction(tx: Transaction, hash?: string, startBlock?: number): TransactionResponse {
1165 if (hash != null && hexDataLength(hash) !== 32) { throw new Error("invalid response - sendTransaction"); }
1166
1167 const result = <TransactionResponse>tx;
1168
1169 // Check the hash we expect is the same as the hash the server reported
1170 if (hash != null && tx.hash !== hash) {
1171 logger.throwError("Transaction hash mismatch from Provider.sendTransaction.", Logger.errors.UNKNOWN_ERROR, { expectedHash: tx.hash, returnedHash: hash });
1172 }
1173
1174 result.wait = async (confirms?: number, timeout?: number) => {
1175 if (confirms == null) { confirms = 1; }
1176 if (timeout == null) { timeout = 0; }
1177
1178 // Get the details to detect replacement
1179 let replacement = undefined;
1180 if (confirms !== 0 && startBlock != null) {
1181 replacement = {
1182 data: tx.data,
1183 from: tx.from,
1184 nonce: tx.nonce,
1185 to: tx.to,
1186 value: tx.value,
1187 startBlock
1188 };
1189 }
1190
1191 const receipt = await this._waitForTransaction(tx.hash, confirms, timeout, replacement);
1192 if (receipt == null && confirms === 0) { return null; }
1193
1194 // No longer pending, allow the polling loop to garbage collect this
1195 this._emitted["t:" + tx.hash] = receipt.blockNumber;
1196
1197 if (receipt.status === 0) {
1198 logger.throwError("transaction failed", Logger.errors.CALL_EXCEPTION, {
1199 transactionHash: tx.hash,
1200 transaction: tx,
1201 receipt: receipt
1202 });
1203 }
1204 return receipt;
1205 };
1206
1207 return result;
1208 }
1209
1210 async sendTransaction(signedTransaction: string | Promise<string>): Promise<TransactionResponse> {
1211 await this.getNetwork();
1212 const hexTx = await Promise.resolve(signedTransaction).then(t => hexlify(t));
1213 const tx = this.formatter.transaction(signedTransaction);
1214 if (tx.confirmations == null) { tx.confirmations = 0; }
1215 const blockNumber = await this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
1216 try {
1217 const hash = await this.perform("sendTransaction", { signedTransaction: hexTx });
1218 return this._wrapTransaction(tx, hash, blockNumber);
1219 } catch (error) {
1220 (<any>error).transaction = tx;
1221 (<any>error).transactionHash = tx.hash;
1222 throw error;
1223 }
1224 }
1225
1226 async _getTransactionRequest(transaction: Deferrable<TransactionRequest>): Promise<Transaction> {
1227 const values: any = await transaction;
1228
1229 const tx: any = { };
1230
1231 ["from", "to"].forEach((key) => {
1232 if (values[key] == null) { return; }
1233 tx[key] = Promise.resolve(values[key]).then((v) => (v ? this._getAddress(v): null))
1234 });
1235
1236 ["gasLimit", "gasPrice", "maxFeePerGas", "maxPriorityFeePerGas", "value"].forEach((key) => {
1237 if (values[key] == null) { return; }
1238 tx[key] = Promise.resolve(values[key]).then((v) => (v ? BigNumber.from(v): null));
1239 });
1240
1241 ["type"].forEach((key) => {
1242 if (values[key] == null) { return; }
1243 tx[key] = Promise.resolve(values[key]).then((v) => ((v != null) ? v: null));
1244 });
1245
1246 if (values.accessList) {
1247 tx.accessList = this.formatter.accessList(values.accessList);
1248 }
1249
1250 ["data"].forEach((key) => {
1251 if (values[key] == null) { return; }
1252 tx[key] = Promise.resolve(values[key]).then((v) => (v ? hexlify(v): null));
1253 });
1254
1255 return this.formatter.transactionRequest(await resolveProperties(tx));
1256 }
1257
1258 async _getFilter(filter: Filter | FilterByBlockHash | Promise<Filter | FilterByBlockHash>): Promise<Filter | FilterByBlockHash> {
1259 filter = await filter;
1260
1261 const result: any = { };
1262
1263 if (filter.address != null) {
1264 result.address = this._getAddress(filter.address);
1265 }
1266
1267 ["blockHash", "topics"].forEach((key) => {
1268 if ((<any>filter)[key] == null) { return; }
1269 result[key] = (<any>filter)[key];
1270 });
1271
1272 ["fromBlock", "toBlock"].forEach((key) => {
1273 if ((<any>filter)[key] == null) { return; }
1274 result[key] = this._getBlockTag((<any>filter)[key]);
1275 });
1276
1277 return this.formatter.filter(await resolveProperties(result));
1278 }
1279
1280 async call(transaction: Deferrable<TransactionRequest>, blockTag?: BlockTag | Promise<BlockTag>): Promise<string> {
1281 await this.getNetwork();
1282 const params = await resolveProperties({
1283 transaction: this._getTransactionRequest(transaction),
1284 blockTag: this._getBlockTag(blockTag)
1285 });
1286
1287 const result = await this.perform("call", params);
1288 try {
1289 return hexlify(result);
1290 } catch (error) {
1291 return logger.throwError("bad result from backend", Logger.errors.SERVER_ERROR, {
1292 method: "call",
1293 params, result, error
1294 });
1295 }
1296 }
1297
1298 async estimateGas(transaction: Deferrable<TransactionRequest>): Promise<BigNumber> {
1299 await this.getNetwork();
1300 const params = await resolveProperties({
1301 transaction: this._getTransactionRequest(transaction)
1302 });
1303
1304 const result = await this.perform("estimateGas", params);
1305 try {
1306 return BigNumber.from(result);
1307 } catch (error) {
1308 return logger.throwError("bad result from backend", Logger.errors.SERVER_ERROR, {
1309 method: "estimateGas",
1310 params, result, error
1311 });
1312 }
1313 }
1314
1315 async _getAddress(addressOrName: string | Promise<string>): Promise<string> {
1316 const address = await this.resolveName(addressOrName);
1317 if (address == null) {
1318 logger.throwError("ENS name not configured", Logger.errors.UNSUPPORTED_OPERATION, {
1319 operation: `resolveName(${ JSON.stringify(addressOrName) })`
1320 });
1321 }
1322 return address;
1323 }
1324
1325 async _getBlock(blockHashOrBlockTag: BlockTag | string | Promise<BlockTag | string>, includeTransactions?: boolean): Promise<Block | BlockWithTransactions> {
1326 await this.getNetwork();
1327
1328 blockHashOrBlockTag = await blockHashOrBlockTag;
1329
1330 // If blockTag is a number (not "latest", etc), this is the block number
1331 let blockNumber = -128;
1332
1333 const params: { [key: string]: any } = {
1334 includeTransactions: !!includeTransactions
1335 };
1336
1337 if (isHexString(blockHashOrBlockTag, 32)) {
1338 params.blockHash = blockHashOrBlockTag;
1339 } else {
1340 try {
1341 params.blockTag = this.formatter.blockTag(await this._getBlockTag(blockHashOrBlockTag));
1342 if (isHexString(params.blockTag)) {
1343 blockNumber = parseInt(params.blockTag.substring(2), 16);
1344 }
1345 } catch (error) {
1346 logger.throwArgumentError("invalid block hash or block tag", "blockHashOrBlockTag", blockHashOrBlockTag);
1347 }
1348 }
1349
1350 return poll(async () => {
1351 const block = await this.perform("getBlock", params);
1352
1353 // Block was not found
1354 if (block == null) {
1355
1356 // For blockhashes, if we didn't say it existed, that blockhash may
1357 // not exist. If we did see it though, perhaps from a log, we know
1358 // it exists, and this node is just not caught up yet.
1359 if (params.blockHash != null) {
1360 if (this._emitted["b:" + params.blockHash] == null) { return null; }
1361 }
1362
1363 // For block tags, if we are asking for a future block, we return null
1364 if (params.blockTag != null) {
1365 if (blockNumber > this._emitted.block) { return null; }
1366 }
1367
1368 // Retry on the next block
1369 return undefined;
1370 }
1371
1372 // Add transactions
1373 if (includeTransactions) {
1374 let blockNumber: number = null;
1375 for (let i = 0; i < block.transactions.length; i++) {
1376 const tx = block.transactions[i];
1377 if (tx.blockNumber == null) {
1378 tx.confirmations = 0;
1379
1380 } else if (tx.confirmations == null) {
1381 if (blockNumber == null) {
1382 blockNumber = await this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
1383 }
1384
1385 // Add the confirmations using the fast block number (pessimistic)
1386 let confirmations = (blockNumber - tx.blockNumber) + 1;
1387 if (confirmations <= 0) { confirmations = 1; }
1388 tx.confirmations = confirmations;
1389 }
1390 }
1391
1392 const blockWithTxs: any = this.formatter.blockWithTransactions(block);
1393 blockWithTxs.transactions = blockWithTxs.transactions.map((tx: TransactionResponse) => this._wrapTransaction(tx));
1394 return blockWithTxs;
1395 }
1396
1397 return this.formatter.block(block);
1398
1399 }, { oncePoll: this });
1400 }
1401
1402 getBlock(blockHashOrBlockTag: BlockTag | string | Promise<BlockTag | string>): Promise<Block> {
1403 return <Promise<Block>>(this._getBlock(blockHashOrBlockTag, false));
1404 }
1405
1406 getBlockWithTransactions(blockHashOrBlockTag: BlockTag | string | Promise<BlockTag | string>): Promise<BlockWithTransactions> {
1407 return <Promise<BlockWithTransactions>>(this._getBlock(blockHashOrBlockTag, true));
1408 }
1409
1410 async getTransaction(transactionHash: string | Promise<string>): Promise<TransactionResponse> {
1411 await this.getNetwork();
1412 transactionHash = await transactionHash;
1413
1414 const params = { transactionHash: this.formatter.hash(transactionHash, true) };
1415
1416 return poll(async () => {
1417 const result = await this.perform("getTransaction", params);
1418
1419 if (result == null) {
1420 if (this._emitted["t:" + transactionHash] == null) {
1421 return null;
1422 }
1423 return undefined;
1424 }
1425
1426 const tx = this.formatter.transactionResponse(result);
1427
1428 if (tx.blockNumber == null) {
1429 tx.confirmations = 0;
1430
1431 } else if (tx.confirmations == null) {
1432 const blockNumber = await this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
1433
1434 // Add the confirmations using the fast block number (pessimistic)
1435 let confirmations = (blockNumber - tx.blockNumber) + 1;
1436 if (confirmations <= 0) { confirmations = 1; }
1437 tx.confirmations = confirmations;
1438 }
1439
1440 return this._wrapTransaction(tx);
1441 }, { oncePoll: this });
1442 }
1443
1444 async getTransactionReceipt(transactionHash: string | Promise<string>): Promise<TransactionReceipt> {
1445 await this.getNetwork();
1446
1447 transactionHash = await transactionHash;
1448
1449 const params = { transactionHash: this.formatter.hash(transactionHash, true) };
1450
1451 return poll(async () => {
1452 const result = await this.perform("getTransactionReceipt", params);
1453
1454 if (result == null) {
1455 if (this._emitted["t:" + transactionHash] == null) {
1456 return null;
1457 }
1458 return undefined;
1459 }
1460
1461 // "geth-etc" returns receipts before they are ready
1462 if (result.blockHash == null) { return undefined; }
1463
1464 const receipt = this.formatter.receipt(result);
1465
1466 if (receipt.blockNumber == null) {
1467 receipt.confirmations = 0;
1468
1469 } else if (receipt.confirmations == null) {
1470 const blockNumber = await this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
1471
1472 // Add the confirmations using the fast block number (pessimistic)
1473 let confirmations = (blockNumber - receipt.blockNumber) + 1;
1474 if (confirmations <= 0) { confirmations = 1; }
1475 receipt.confirmations = confirmations;
1476 }
1477
1478 return receipt;
1479 }, { oncePoll: this });
1480 }
1481
1482 async getLogs(filter: Filter | FilterByBlockHash | Promise<Filter | FilterByBlockHash>): Promise<Array<Log>> {
1483 await this.getNetwork();
1484 const params = await resolveProperties({ filter: this._getFilter(filter) });
1485 const logs: Array<Log> = await this.perform("getLogs", params);
1486 logs.forEach((log) => {
1487 if (log.removed == null) { log.removed = false; }
1488 });
1489 return Formatter.arrayOf(this.formatter.filterLog.bind(this.formatter))(logs);
1490 }
1491
1492 async getEtherPrice(): Promise<number> {
1493 await this.getNetwork();
1494 return this.perform("getEtherPrice", { });
1495 }
1496
1497 async _getBlockTag(blockTag: BlockTag | Promise<BlockTag>): Promise<BlockTag> {
1498 blockTag = await blockTag;
1499
1500 if (typeof(blockTag) === "number" && blockTag < 0) {
1501 if (blockTag % 1) {
1502 logger.throwArgumentError("invalid BlockTag", "blockTag", blockTag);
1503 }
1504
1505 let blockNumber = await this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
1506 blockNumber += blockTag;
1507 if (blockNumber < 0) { blockNumber = 0; }
1508 return this.formatter.blockTag(blockNumber)
1509 }
1510
1511 return this.formatter.blockTag(blockTag);
1512 }
1513
1514
1515 async getResolver(name: string): Promise<Resolver> {
1516 try {
1517 const address = await this._getResolver(name);
1518 if (address == null) { return null; }
1519 return new Resolver(this, address, name);
1520 } catch (error) {
1521 if (error.code === Logger.errors.CALL_EXCEPTION) { return null; }
1522 return null;
1523 }
1524 }
1525
1526 async _getResolver(name: string): Promise<string> {
1527 // Get the resolver from the blockchain
1528 const network = await this.getNetwork();
1529
1530 // No ENS...
1531 if (!network.ensAddress) {
1532 logger.throwError(
1533 "network does not support ENS",
1534 Logger.errors.UNSUPPORTED_OPERATION,
1535 { operation: "ENS", network: network.name }
1536 );
1537 }
1538
1539 // keccak256("resolver(bytes32)")
1540 const transaction = {
1541 to: network.ensAddress,
1542 data: ("0x0178b8bf" + namehash(name).substring(2))
1543 };
1544
1545 try {
1546 return this.formatter.callAddress(await this.call(transaction));
1547 } catch (error) {
1548 if (error.code === Logger.errors.CALL_EXCEPTION) { return null; }
1549 throw error;
1550 }
1551 }
1552
1553 async resolveName(name: string | Promise<string>): Promise<string> {
1554 name = await name;
1555
1556 // If it is already an address, nothing to resolve
1557 try {
1558 return Promise.resolve(this.formatter.address(name));
1559 } catch (error) {
1560 // If is is a hexstring, the address is bad (See #694)
1561 if (isHexString(name)) { throw error; }
1562 }
1563
1564 if (typeof(name) !== "string") {
1565 logger.throwArgumentError("invalid ENS name", "name", name);
1566 }
1567
1568 // Get the addr from the resovler
1569 const resolver = await this.getResolver(name);
1570 if (!resolver) { return null; }
1571
1572 return await resolver.getAddress();
1573 }
1574
1575 async lookupAddress(address: string | Promise<string>): Promise<string> {
1576 address = await address;
1577 address = this.formatter.address(address);
1578
1579 const reverseName = address.substring(2).toLowerCase() + ".addr.reverse";
1580
1581 const resolverAddress = await this._getResolver(reverseName);
1582 if (!resolverAddress) { return null; }
1583
1584 // keccak("name(bytes32)")
1585 let bytes = arrayify(await this.call({
1586 to: resolverAddress,
1587 data: ("0x691f3431" + namehash(reverseName).substring(2))
1588 }));
1589
1590 // Strip off the dynamic string pointer (0x20)
1591 if (bytes.length < 32 || !BigNumber.from(bytes.slice(0, 32)).eq(32)) { return null; }
1592 bytes = bytes.slice(32);
1593
1594 // Not a length-prefixed string
1595 if (bytes.length < 32) { return null; }
1596
1597 // Get the length of the string (from the length-prefix)
1598 const length = BigNumber.from(bytes.slice(0, 32)).toNumber();
1599 bytes = bytes.slice(32);
1600
1601 // Length longer than available data
1602 if (length > bytes.length) { return null; }
1603
1604 const name = toUtf8String(bytes.slice(0, length));
1605
1606 // Make sure the reverse record matches the foward record
1607 const addr = await this.resolveName(name);
1608 if (addr != address) { return null; }
1609
1610 return name;
1611 }
1612
1613 perform(method: string, params: any): Promise<any> {
1614 return logger.throwError(method + " not implemented", Logger.errors.NOT_IMPLEMENTED, { operation: method });
1615 }
1616
1617 _startEvent(event: Event): void {
1618 this.polling = (this._events.filter((e) => e.pollable()).length > 0);
1619 }
1620
1621 _stopEvent(event: Event): void {
1622 this.polling = (this._events.filter((e) => e.pollable()).length > 0);
1623 }
1624
1625 _addEventListener(eventName: EventType, listener: Listener, once: boolean): this {
1626 const event = new Event(getEventTag(eventName), listener, once)
1627 this._events.push(event);
1628 this._startEvent(event);
1629
1630 return this;
1631 }
1632
1633 on(eventName: EventType, listener: Listener): this {
1634 return this._addEventListener(eventName, listener, false);
1635 }
1636
1637 once(eventName: EventType, listener: Listener): this {
1638 return this._addEventListener(eventName, listener, true);
1639 }
1640
1641
1642 emit(eventName: EventType, ...args: Array<any>): boolean {
1643 let result = false;
1644
1645 let stopped: Array<Event> = [ ];
1646
1647 let eventTag = getEventTag(eventName);
1648 this._events = this._events.filter((event) => {
1649 if (event.tag !== eventTag) { return true; }
1650
1651 setTimeout(() => {
1652 event.listener.apply(this, args);
1653 }, 0);
1654
1655 result = true;
1656
1657 if (event.once) {
1658 stopped.push(event);
1659 return false;
1660 }
1661
1662 return true;
1663 });
1664
1665 stopped.forEach((event) => { this._stopEvent(event); });
1666
1667 return result;
1668 }
1669
1670 listenerCount(eventName?: EventType): number {
1671 if (!eventName) { return this._events.length; }
1672
1673 let eventTag = getEventTag(eventName);
1674 return this._events.filter((event) => {
1675 return (event.tag === eventTag);
1676 }).length;
1677 }
1678
1679 listeners(eventName?: EventType): Array<Listener> {
1680 if (eventName == null) {
1681 return this._events.map((event) => event.listener);
1682 }
1683
1684 let eventTag = getEventTag(eventName);
1685 return this._events
1686 .filter((event) => (event.tag === eventTag))
1687 .map((event) => event.listener);
1688 }
1689
1690 off(eventName: EventType, listener?: Listener): this {
1691 if (listener == null) {
1692 return this.removeAllListeners(eventName);
1693 }
1694
1695 const stopped: Array<Event> = [ ];
1696
1697 let found = false;
1698
1699 let eventTag = getEventTag(eventName);
1700 this._events = this._events.filter((event) => {
1701 if (event.tag !== eventTag || event.listener != listener) { return true; }
1702 if (found) { return true; }
1703 found = true;
1704 stopped.push(event);
1705 return false;
1706 });
1707
1708 stopped.forEach((event) => { this._stopEvent(event); });
1709
1710 return this;
1711 }
1712
1713 removeAllListeners(eventName?: EventType): this {
1714 let stopped: Array<Event> = [ ];
1715 if (eventName == null) {
1716 stopped = this._events;
1717
1718 this._events = [ ];
1719 } else {
1720 const eventTag = getEventTag(eventName);
1721 this._events = this._events.filter((event) => {
1722 if (event.tag !== eventTag) { return true; }
1723 stopped.push(event);
1724 return false;
1725 });
1726 }
1727
1728 stopped.forEach((event) => { this._stopEvent(event); });
1729
1730 return this;
1731 }
1732}
1733
\No newline at end of file