UNPKG

132 kBJavaScriptView Raw
1"use strict";
2var __extends = (this && this.__extends) || (function () {
3 var extendStatics = function (d, b) {
4 extendStatics = Object.setPrototypeOf ||
5 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7 return extendStatics(d, b);
8 };
9 return function (d, b) {
10 if (typeof b !== "function" && b !== null)
11 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12 extendStatics(d, b);
13 function __() { this.constructor = d; }
14 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15 };
16})();
17var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
18 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
19 return new (P || (P = Promise))(function (resolve, reject) {
20 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
21 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
22 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
23 step((generator = generator.apply(thisArg, _arguments || [])).next());
24 });
25};
26var __generator = (this && this.__generator) || function (thisArg, body) {
27 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
28 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
29 function verb(n) { return function (v) { return step([n, v]); }; }
30 function step(op) {
31 if (f) throw new TypeError("Generator is already executing.");
32 while (_) try {
33 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
34 if (y = 0, t) op = [op[0] & 2, t.value];
35 switch (op[0]) {
36 case 0: case 1: t = op; break;
37 case 4: _.label++; return { value: op[1], done: false };
38 case 5: _.label++; y = op[1]; op = [0]; continue;
39 case 7: op = _.ops.pop(); _.trys.pop(); continue;
40 default:
41 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
42 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
43 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
44 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
45 if (t[2]) _.ops.pop();
46 _.trys.pop(); continue;
47 }
48 op = body.call(thisArg, _);
49 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
50 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
51 }
52};
53var __importDefault = (this && this.__importDefault) || function (mod) {
54 return (mod && mod.__esModule) ? mod : { "default": mod };
55};
56Object.defineProperty(exports, "__esModule", { value: true });
57exports.BaseProvider = exports.Resolver = exports.Event = void 0;
58var abstract_provider_1 = require("@ethersproject/abstract-provider");
59var base64_1 = require("@ethersproject/base64");
60var basex_1 = require("@ethersproject/basex");
61var bignumber_1 = require("@ethersproject/bignumber");
62var bytes_1 = require("@ethersproject/bytes");
63var constants_1 = require("@ethersproject/constants");
64var hash_1 = require("@ethersproject/hash");
65var networks_1 = require("@ethersproject/networks");
66var properties_1 = require("@ethersproject/properties");
67var sha2_1 = require("@ethersproject/sha2");
68var strings_1 = require("@ethersproject/strings");
69var web_1 = require("@ethersproject/web");
70var bech32_1 = __importDefault(require("bech32"));
71var logger_1 = require("@ethersproject/logger");
72var _version_1 = require("./_version");
73var logger = new logger_1.Logger(_version_1.version);
74var formatter_1 = require("./formatter");
75var MAX_CCIP_REDIRECTS = 10;
76//////////////////////////////
77// Event Serializeing
78function checkTopic(topic) {
79 if (topic == null) {
80 return "null";
81 }
82 if ((0, bytes_1.hexDataLength)(topic) !== 32) {
83 logger.throwArgumentError("invalid topic", "topic", topic);
84 }
85 return topic.toLowerCase();
86}
87function serializeTopics(topics) {
88 // Remove trailing null AND-topics; they are redundant
89 topics = topics.slice();
90 while (topics.length > 0 && topics[topics.length - 1] == null) {
91 topics.pop();
92 }
93 return topics.map(function (topic) {
94 if (Array.isArray(topic)) {
95 // Only track unique OR-topics
96 var unique_1 = {};
97 topic.forEach(function (topic) {
98 unique_1[checkTopic(topic)] = true;
99 });
100 // The order of OR-topics does not matter
101 var sorted = Object.keys(unique_1);
102 sorted.sort();
103 return sorted.join("|");
104 }
105 else {
106 return checkTopic(topic);
107 }
108 }).join("&");
109}
110function deserializeTopics(data) {
111 if (data === "") {
112 return [];
113 }
114 return data.split(/&/g).map(function (topic) {
115 if (topic === "") {
116 return [];
117 }
118 var comps = topic.split("|").map(function (topic) {
119 return ((topic === "null") ? null : topic);
120 });
121 return ((comps.length === 1) ? comps[0] : comps);
122 });
123}
124function getEventTag(eventName) {
125 if (typeof (eventName) === "string") {
126 eventName = eventName.toLowerCase();
127 if ((0, bytes_1.hexDataLength)(eventName) === 32) {
128 return "tx:" + eventName;
129 }
130 if (eventName.indexOf(":") === -1) {
131 return eventName;
132 }
133 }
134 else if (Array.isArray(eventName)) {
135 return "filter:*:" + serializeTopics(eventName);
136 }
137 else if (abstract_provider_1.ForkEvent.isForkEvent(eventName)) {
138 logger.warn("not implemented");
139 throw new Error("not implemented");
140 }
141 else if (eventName && typeof (eventName) === "object") {
142 return "filter:" + (eventName.address || "*") + ":" + serializeTopics(eventName.topics || []);
143 }
144 throw new Error("invalid event - " + eventName);
145}
146//////////////////////////////
147// Helper Object
148function getTime() {
149 return (new Date()).getTime();
150}
151function stall(duration) {
152 return new Promise(function (resolve) {
153 setTimeout(resolve, duration);
154 });
155}
156//////////////////////////////
157// Provider Object
158/**
159 * EventType
160 * - "block"
161 * - "poll"
162 * - "didPoll"
163 * - "pending"
164 * - "error"
165 * - "network"
166 * - filter
167 * - topics array
168 * - transaction hash
169 */
170var PollableEvents = ["block", "network", "pending", "poll"];
171var Event = /** @class */ (function () {
172 function Event(tag, listener, once) {
173 (0, properties_1.defineReadOnly)(this, "tag", tag);
174 (0, properties_1.defineReadOnly)(this, "listener", listener);
175 (0, properties_1.defineReadOnly)(this, "once", once);
176 this._lastBlockNumber = -2;
177 this._inflight = false;
178 }
179 Object.defineProperty(Event.prototype, "event", {
180 get: function () {
181 switch (this.type) {
182 case "tx":
183 return this.hash;
184 case "filter":
185 return this.filter;
186 }
187 return this.tag;
188 },
189 enumerable: false,
190 configurable: true
191 });
192 Object.defineProperty(Event.prototype, "type", {
193 get: function () {
194 return this.tag.split(":")[0];
195 },
196 enumerable: false,
197 configurable: true
198 });
199 Object.defineProperty(Event.prototype, "hash", {
200 get: function () {
201 var comps = this.tag.split(":");
202 if (comps[0] !== "tx") {
203 return null;
204 }
205 return comps[1];
206 },
207 enumerable: false,
208 configurable: true
209 });
210 Object.defineProperty(Event.prototype, "filter", {
211 get: function () {
212 var comps = this.tag.split(":");
213 if (comps[0] !== "filter") {
214 return null;
215 }
216 var address = comps[1];
217 var topics = deserializeTopics(comps[2]);
218 var filter = {};
219 if (topics.length > 0) {
220 filter.topics = topics;
221 }
222 if (address && address !== "*") {
223 filter.address = address;
224 }
225 return filter;
226 },
227 enumerable: false,
228 configurable: true
229 });
230 Event.prototype.pollable = function () {
231 return (this.tag.indexOf(":") >= 0 || PollableEvents.indexOf(this.tag) >= 0);
232 };
233 return Event;
234}());
235exports.Event = Event;
236;
237// https://github.com/satoshilabs/slips/blob/master/slip-0044.md
238var coinInfos = {
239 "0": { symbol: "btc", p2pkh: 0x00, p2sh: 0x05, prefix: "bc" },
240 "2": { symbol: "ltc", p2pkh: 0x30, p2sh: 0x32, prefix: "ltc" },
241 "3": { symbol: "doge", p2pkh: 0x1e, p2sh: 0x16 },
242 "60": { symbol: "eth", ilk: "eth" },
243 "61": { symbol: "etc", ilk: "eth" },
244 "700": { symbol: "xdai", ilk: "eth" },
245};
246function bytes32ify(value) {
247 return (0, bytes_1.hexZeroPad)(bignumber_1.BigNumber.from(value).toHexString(), 32);
248}
249// Compute the Base58Check encoded data (checksum is first 4 bytes of sha256d)
250function base58Encode(data) {
251 return basex_1.Base58.encode((0, bytes_1.concat)([data, (0, bytes_1.hexDataSlice)((0, sha2_1.sha256)((0, sha2_1.sha256)(data)), 0, 4)]));
252}
253var matcherIpfs = new RegExp("^(ipfs):/\/(.*)$", "i");
254var matchers = [
255 new RegExp("^(https):/\/(.*)$", "i"),
256 new RegExp("^(data):(.*)$", "i"),
257 matcherIpfs,
258 new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i"),
259];
260function _parseString(result, start) {
261 try {
262 return (0, strings_1.toUtf8String)(_parseBytes(result, start));
263 }
264 catch (error) { }
265 return null;
266}
267function _parseBytes(result, start) {
268 if (result === "0x") {
269 return null;
270 }
271 var offset = bignumber_1.BigNumber.from((0, bytes_1.hexDataSlice)(result, start, start + 32)).toNumber();
272 var length = bignumber_1.BigNumber.from((0, bytes_1.hexDataSlice)(result, offset, offset + 32)).toNumber();
273 return (0, bytes_1.hexDataSlice)(result, offset + 32, offset + 32 + length);
274}
275// Trim off the ipfs:// prefix and return the default gateway URL
276function getIpfsLink(link) {
277 if (link.match(/^ipfs:\/\/ipfs\//i)) {
278 link = link.substring(12);
279 }
280 else if (link.match(/^ipfs:\/\//i)) {
281 link = link.substring(7);
282 }
283 else {
284 logger.throwArgumentError("unsupported IPFS format", "link", link);
285 }
286 return "https://gateway.ipfs.io/ipfs/" + link;
287}
288function numPad(value) {
289 var result = (0, bytes_1.arrayify)(value);
290 if (result.length > 32) {
291 throw new Error("internal; should not happen");
292 }
293 var padded = new Uint8Array(32);
294 padded.set(result, 32 - result.length);
295 return padded;
296}
297function bytesPad(value) {
298 if ((value.length % 32) === 0) {
299 return value;
300 }
301 var result = new Uint8Array(Math.ceil(value.length / 32) * 32);
302 result.set(value);
303 return result;
304}
305// ABI Encodes a series of (bytes, bytes, ...)
306function encodeBytes(datas) {
307 var result = [];
308 var byteCount = 0;
309 // Add place-holders for pointers as we add items
310 for (var i = 0; i < datas.length; i++) {
311 result.push(null);
312 byteCount += 32;
313 }
314 for (var i = 0; i < datas.length; i++) {
315 var data = (0, bytes_1.arrayify)(datas[i]);
316 // Update the bytes offset
317 result[i] = numPad(byteCount);
318 // The length and padded value of data
319 result.push(numPad(data.length));
320 result.push(bytesPad(data));
321 byteCount += 32 + Math.ceil(data.length / 32) * 32;
322 }
323 return (0, bytes_1.hexConcat)(result);
324}
325var Resolver = /** @class */ (function () {
326 // The resolvedAddress is only for creating a ReverseLookup resolver
327 function Resolver(provider, address, name, resolvedAddress) {
328 (0, properties_1.defineReadOnly)(this, "provider", provider);
329 (0, properties_1.defineReadOnly)(this, "name", name);
330 (0, properties_1.defineReadOnly)(this, "address", provider.formatter.address(address));
331 (0, properties_1.defineReadOnly)(this, "_resolvedAddress", resolvedAddress);
332 }
333 Resolver.prototype.supportsWildcard = function () {
334 var _this = this;
335 if (!this._supportsEip2544) {
336 // supportsInterface(bytes4 = selector("resolve(bytes,bytes)"))
337 this._supportsEip2544 = this.provider.call({
338 to: this.address,
339 data: "0x01ffc9a79061b92300000000000000000000000000000000000000000000000000000000"
340 }).then(function (result) {
341 return bignumber_1.BigNumber.from(result).eq(1);
342 }).catch(function (error) {
343 if (error.code === logger_1.Logger.errors.CALL_EXCEPTION) {
344 return false;
345 }
346 // Rethrow the error: link is down, etc. Let future attempts retry.
347 _this._supportsEip2544 = null;
348 throw error;
349 });
350 }
351 return this._supportsEip2544;
352 };
353 Resolver.prototype._fetch = function (selector, parameters) {
354 return __awaiter(this, void 0, void 0, function () {
355 var tx, parseBytes, result, error_1;
356 return __generator(this, function (_a) {
357 switch (_a.label) {
358 case 0:
359 tx = {
360 to: this.address,
361 ccipReadEnabled: true,
362 data: (0, bytes_1.hexConcat)([selector, (0, hash_1.namehash)(this.name), (parameters || "0x")])
363 };
364 parseBytes = false;
365 return [4 /*yield*/, this.supportsWildcard()];
366 case 1:
367 if (_a.sent()) {
368 parseBytes = true;
369 // selector("resolve(bytes,bytes)")
370 tx.data = (0, bytes_1.hexConcat)(["0x9061b923", encodeBytes([(0, hash_1.dnsEncode)(this.name), tx.data])]);
371 }
372 _a.label = 2;
373 case 2:
374 _a.trys.push([2, 4, , 5]);
375 return [4 /*yield*/, this.provider.call(tx)];
376 case 3:
377 result = _a.sent();
378 if (((0, bytes_1.arrayify)(result).length % 32) === 4) {
379 logger.throwError("resolver threw error", logger_1.Logger.errors.CALL_EXCEPTION, {
380 transaction: tx, data: result
381 });
382 }
383 if (parseBytes) {
384 result = _parseBytes(result, 0);
385 }
386 return [2 /*return*/, result];
387 case 4:
388 error_1 = _a.sent();
389 if (error_1.code === logger_1.Logger.errors.CALL_EXCEPTION) {
390 return [2 /*return*/, null];
391 }
392 throw error_1;
393 case 5: return [2 /*return*/];
394 }
395 });
396 });
397 };
398 Resolver.prototype._fetchBytes = function (selector, parameters) {
399 return __awaiter(this, void 0, void 0, function () {
400 var result;
401 return __generator(this, function (_a) {
402 switch (_a.label) {
403 case 0: return [4 /*yield*/, this._fetch(selector, parameters)];
404 case 1:
405 result = _a.sent();
406 if (result != null) {
407 return [2 /*return*/, _parseBytes(result, 0)];
408 }
409 return [2 /*return*/, null];
410 }
411 });
412 });
413 };
414 Resolver.prototype._getAddress = function (coinType, hexBytes) {
415 var coinInfo = coinInfos[String(coinType)];
416 if (coinInfo == null) {
417 logger.throwError("unsupported coin type: " + coinType, logger_1.Logger.errors.UNSUPPORTED_OPERATION, {
418 operation: "getAddress(" + coinType + ")"
419 });
420 }
421 if (coinInfo.ilk === "eth") {
422 return this.provider.formatter.address(hexBytes);
423 }
424 var bytes = (0, bytes_1.arrayify)(hexBytes);
425 // P2PKH: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
426 if (coinInfo.p2pkh != null) {
427 var p2pkh = hexBytes.match(/^0x76a9([0-9a-f][0-9a-f])([0-9a-f]*)88ac$/);
428 if (p2pkh) {
429 var length_1 = parseInt(p2pkh[1], 16);
430 if (p2pkh[2].length === length_1 * 2 && length_1 >= 1 && length_1 <= 75) {
431 return base58Encode((0, bytes_1.concat)([[coinInfo.p2pkh], ("0x" + p2pkh[2])]));
432 }
433 }
434 }
435 // P2SH: OP_HASH160 <scriptHash> OP_EQUAL
436 if (coinInfo.p2sh != null) {
437 var p2sh = hexBytes.match(/^0xa9([0-9a-f][0-9a-f])([0-9a-f]*)87$/);
438 if (p2sh) {
439 var length_2 = parseInt(p2sh[1], 16);
440 if (p2sh[2].length === length_2 * 2 && length_2 >= 1 && length_2 <= 75) {
441 return base58Encode((0, bytes_1.concat)([[coinInfo.p2sh], ("0x" + p2sh[2])]));
442 }
443 }
444 }
445 // Bech32
446 if (coinInfo.prefix != null) {
447 var length_3 = bytes[1];
448 // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program
449 var version_1 = bytes[0];
450 if (version_1 === 0x00) {
451 if (length_3 !== 20 && length_3 !== 32) {
452 version_1 = -1;
453 }
454 }
455 else {
456 version_1 = -1;
457 }
458 if (version_1 >= 0 && bytes.length === 2 + length_3 && length_3 >= 1 && length_3 <= 75) {
459 var words = bech32_1.default.toWords(bytes.slice(2));
460 words.unshift(version_1);
461 return bech32_1.default.encode(coinInfo.prefix, words);
462 }
463 }
464 return null;
465 };
466 Resolver.prototype.getAddress = function (coinType) {
467 return __awaiter(this, void 0, void 0, function () {
468 var result, error_2, hexBytes, address;
469 return __generator(this, function (_a) {
470 switch (_a.label) {
471 case 0:
472 if (coinType == null) {
473 coinType = 60;
474 }
475 if (!(coinType === 60)) return [3 /*break*/, 4];
476 _a.label = 1;
477 case 1:
478 _a.trys.push([1, 3, , 4]);
479 return [4 /*yield*/, this._fetch("0x3b3b57de")];
480 case 2:
481 result = _a.sent();
482 // No address
483 if (result === "0x" || result === constants_1.HashZero) {
484 return [2 /*return*/, null];
485 }
486 return [2 /*return*/, this.provider.formatter.callAddress(result)];
487 case 3:
488 error_2 = _a.sent();
489 if (error_2.code === logger_1.Logger.errors.CALL_EXCEPTION) {
490 return [2 /*return*/, null];
491 }
492 throw error_2;
493 case 4: return [4 /*yield*/, this._fetchBytes("0xf1cb7e06", bytes32ify(coinType))];
494 case 5:
495 hexBytes = _a.sent();
496 // No address
497 if (hexBytes == null || hexBytes === "0x") {
498 return [2 /*return*/, null];
499 }
500 address = this._getAddress(coinType, hexBytes);
501 if (address == null) {
502 logger.throwError("invalid or unsupported coin data", logger_1.Logger.errors.UNSUPPORTED_OPERATION, {
503 operation: "getAddress(" + coinType + ")",
504 coinType: coinType,
505 data: hexBytes
506 });
507 }
508 return [2 /*return*/, address];
509 }
510 });
511 });
512 };
513 Resolver.prototype.getAvatar = function () {
514 return __awaiter(this, void 0, void 0, function () {
515 var linkage, avatar, i, match, scheme, _a, selector, owner, _b, comps, addr, tokenId, tokenOwner, _c, _d, balance, _e, _f, tx, metadataUrl, _g, metadata, imageUrl, ipfs, error_3;
516 return __generator(this, function (_h) {
517 switch (_h.label) {
518 case 0:
519 linkage = [{ type: "name", content: this.name }];
520 _h.label = 1;
521 case 1:
522 _h.trys.push([1, 19, , 20]);
523 return [4 /*yield*/, this.getText("avatar")];
524 case 2:
525 avatar = _h.sent();
526 if (avatar == null) {
527 return [2 /*return*/, null];
528 }
529 i = 0;
530 _h.label = 3;
531 case 3:
532 if (!(i < matchers.length)) return [3 /*break*/, 18];
533 match = avatar.match(matchers[i]);
534 if (match == null) {
535 return [3 /*break*/, 17];
536 }
537 scheme = match[1].toLowerCase();
538 _a = scheme;
539 switch (_a) {
540 case "https": return [3 /*break*/, 4];
541 case "data": return [3 /*break*/, 5];
542 case "ipfs": return [3 /*break*/, 6];
543 case "erc721": return [3 /*break*/, 7];
544 case "erc1155": return [3 /*break*/, 7];
545 }
546 return [3 /*break*/, 17];
547 case 4:
548 linkage.push({ type: "url", content: avatar });
549 return [2 /*return*/, { linkage: linkage, url: avatar }];
550 case 5:
551 linkage.push({ type: "data", content: avatar });
552 return [2 /*return*/, { linkage: linkage, url: avatar }];
553 case 6:
554 linkage.push({ type: "ipfs", content: avatar });
555 return [2 /*return*/, { linkage: linkage, url: getIpfsLink(avatar) }];
556 case 7:
557 selector = (scheme === "erc721") ? "0xc87b56dd" : "0x0e89341c";
558 linkage.push({ type: scheme, content: avatar });
559 _b = this._resolvedAddress;
560 if (_b) return [3 /*break*/, 9];
561 return [4 /*yield*/, this.getAddress()];
562 case 8:
563 _b = (_h.sent());
564 _h.label = 9;
565 case 9:
566 owner = (_b);
567 comps = (match[2] || "").split("/");
568 if (comps.length !== 2) {
569 return [2 /*return*/, null];
570 }
571 return [4 /*yield*/, this.provider.formatter.address(comps[0])];
572 case 10:
573 addr = _h.sent();
574 tokenId = (0, bytes_1.hexZeroPad)(bignumber_1.BigNumber.from(comps[1]).toHexString(), 32);
575 if (!(scheme === "erc721")) return [3 /*break*/, 12];
576 _d = (_c = this.provider.formatter).callAddress;
577 return [4 /*yield*/, this.provider.call({
578 to: addr, data: (0, bytes_1.hexConcat)(["0x6352211e", tokenId])
579 })];
580 case 11:
581 tokenOwner = _d.apply(_c, [_h.sent()]);
582 if (owner !== tokenOwner) {
583 return [2 /*return*/, null];
584 }
585 linkage.push({ type: "owner", content: tokenOwner });
586 return [3 /*break*/, 14];
587 case 12:
588 if (!(scheme === "erc1155")) return [3 /*break*/, 14];
589 _f = (_e = bignumber_1.BigNumber).from;
590 return [4 /*yield*/, this.provider.call({
591 to: addr, data: (0, bytes_1.hexConcat)(["0x00fdd58e", (0, bytes_1.hexZeroPad)(owner, 32), tokenId])
592 })];
593 case 13:
594 balance = _f.apply(_e, [_h.sent()]);
595 if (balance.isZero()) {
596 return [2 /*return*/, null];
597 }
598 linkage.push({ type: "balance", content: balance.toString() });
599 _h.label = 14;
600 case 14:
601 tx = {
602 to: this.provider.formatter.address(comps[0]),
603 data: (0, bytes_1.hexConcat)([selector, tokenId])
604 };
605 _g = _parseString;
606 return [4 /*yield*/, this.provider.call(tx)];
607 case 15:
608 metadataUrl = _g.apply(void 0, [_h.sent(), 0]);
609 if (metadataUrl == null) {
610 return [2 /*return*/, null];
611 }
612 linkage.push({ type: "metadata-url-base", content: metadataUrl });
613 // ERC-1155 allows a generic {id} in the URL
614 if (scheme === "erc1155") {
615 metadataUrl = metadataUrl.replace("{id}", tokenId.substring(2));
616 linkage.push({ type: "metadata-url-expanded", content: metadataUrl });
617 }
618 // Transform IPFS metadata links
619 if (metadataUrl.match(/^ipfs:/i)) {
620 metadataUrl = getIpfsLink(metadataUrl);
621 }
622 linkage.push({ type: "metadata-url", content: metadataUrl });
623 return [4 /*yield*/, (0, web_1.fetchJson)(metadataUrl)];
624 case 16:
625 metadata = _h.sent();
626 if (!metadata) {
627 return [2 /*return*/, null];
628 }
629 linkage.push({ type: "metadata", content: JSON.stringify(metadata) });
630 imageUrl = metadata.image;
631 if (typeof (imageUrl) !== "string") {
632 return [2 /*return*/, null];
633 }
634 if (imageUrl.match(/^(https:\/\/|data:)/i)) {
635 // Allow
636 }
637 else {
638 ipfs = imageUrl.match(matcherIpfs);
639 if (ipfs == null) {
640 return [2 /*return*/, null];
641 }
642 linkage.push({ type: "url-ipfs", content: imageUrl });
643 imageUrl = getIpfsLink(imageUrl);
644 }
645 linkage.push({ type: "url", content: imageUrl });
646 return [2 /*return*/, { linkage: linkage, url: imageUrl }];
647 case 17:
648 i++;
649 return [3 /*break*/, 3];
650 case 18: return [3 /*break*/, 20];
651 case 19:
652 error_3 = _h.sent();
653 return [3 /*break*/, 20];
654 case 20: return [2 /*return*/, null];
655 }
656 });
657 });
658 };
659 Resolver.prototype.getContentHash = function () {
660 return __awaiter(this, void 0, void 0, function () {
661 var hexBytes, ipfs, length_4, ipns, length_5, swarm, skynet, urlSafe_1, hash;
662 return __generator(this, function (_a) {
663 switch (_a.label) {
664 case 0: return [4 /*yield*/, this._fetchBytes("0xbc1c58d1")];
665 case 1:
666 hexBytes = _a.sent();
667 // No contenthash
668 if (hexBytes == null || hexBytes === "0x") {
669 return [2 /*return*/, null];
670 }
671 ipfs = hexBytes.match(/^0xe3010170(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);
672 if (ipfs) {
673 length_4 = parseInt(ipfs[3], 16);
674 if (ipfs[4].length === length_4 * 2) {
675 return [2 /*return*/, "ipfs:/\/" + basex_1.Base58.encode("0x" + ipfs[1])];
676 }
677 }
678 ipns = hexBytes.match(/^0xe5010172(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);
679 if (ipns) {
680 length_5 = parseInt(ipns[3], 16);
681 if (ipns[4].length === length_5 * 2) {
682 return [2 /*return*/, "ipns:/\/" + basex_1.Base58.encode("0x" + ipns[1])];
683 }
684 }
685 swarm = hexBytes.match(/^0xe40101fa011b20([0-9a-f]*)$/);
686 if (swarm) {
687 if (swarm[1].length === (32 * 2)) {
688 return [2 /*return*/, "bzz:/\/" + swarm[1]];
689 }
690 }
691 skynet = hexBytes.match(/^0x90b2c605([0-9a-f]*)$/);
692 if (skynet) {
693 if (skynet[1].length === (34 * 2)) {
694 urlSafe_1 = { "=": "", "+": "-", "/": "_" };
695 hash = (0, base64_1.encode)("0x" + skynet[1]).replace(/[=+\/]/g, function (a) { return (urlSafe_1[a]); });
696 return [2 /*return*/, "sia:/\/" + hash];
697 }
698 }
699 return [2 /*return*/, logger.throwError("invalid or unsupported content hash data", logger_1.Logger.errors.UNSUPPORTED_OPERATION, {
700 operation: "getContentHash()",
701 data: hexBytes
702 })];
703 }
704 });
705 });
706 };
707 Resolver.prototype.getText = function (key) {
708 return __awaiter(this, void 0, void 0, function () {
709 var keyBytes, hexBytes;
710 return __generator(this, function (_a) {
711 switch (_a.label) {
712 case 0:
713 keyBytes = (0, strings_1.toUtf8Bytes)(key);
714 // The nodehash consumes the first slot, so the string pointer targets
715 // offset 64, with the length at offset 64 and data starting at offset 96
716 keyBytes = (0, bytes_1.concat)([bytes32ify(64), bytes32ify(keyBytes.length), keyBytes]);
717 // Pad to word-size (32 bytes)
718 if ((keyBytes.length % 32) !== 0) {
719 keyBytes = (0, bytes_1.concat)([keyBytes, (0, bytes_1.hexZeroPad)("0x", 32 - (key.length % 32))]);
720 }
721 return [4 /*yield*/, this._fetchBytes("0x59d1d43c", (0, bytes_1.hexlify)(keyBytes))];
722 case 1:
723 hexBytes = _a.sent();
724 if (hexBytes == null || hexBytes === "0x") {
725 return [2 /*return*/, null];
726 }
727 return [2 /*return*/, (0, strings_1.toUtf8String)(hexBytes)];
728 }
729 });
730 });
731 };
732 return Resolver;
733}());
734exports.Resolver = Resolver;
735var defaultFormatter = null;
736var nextPollId = 1;
737var BaseProvider = /** @class */ (function (_super) {
738 __extends(BaseProvider, _super);
739 /**
740 * ready
741 *
742 * A Promise<Network> that resolves only once the provider is ready.
743 *
744 * Sub-classes that call the super with a network without a chainId
745 * MUST set this. Standard named networks have a known chainId.
746 *
747 */
748 function BaseProvider(network) {
749 var _newTarget = this.constructor;
750 var _this = _super.call(this) || this;
751 // Events being listened to
752 _this._events = [];
753 _this._emitted = { block: -2 };
754 _this.disableCcipRead = false;
755 _this.formatter = _newTarget.getFormatter();
756 // If network is any, this Provider allows the underlying
757 // network to change dynamically, and we auto-detect the
758 // current network
759 (0, properties_1.defineReadOnly)(_this, "anyNetwork", (network === "any"));
760 if (_this.anyNetwork) {
761 network = _this.detectNetwork();
762 }
763 if (network instanceof Promise) {
764 _this._networkPromise = network;
765 // Squash any "unhandled promise" errors; that do not need to be handled
766 network.catch(function (error) { });
767 // Trigger initial network setting (async)
768 _this._ready().catch(function (error) { });
769 }
770 else {
771 var knownNetwork = (0, properties_1.getStatic)(_newTarget, "getNetwork")(network);
772 if (knownNetwork) {
773 (0, properties_1.defineReadOnly)(_this, "_network", knownNetwork);
774 _this.emit("network", knownNetwork, null);
775 }
776 else {
777 logger.throwArgumentError("invalid network", "network", network);
778 }
779 }
780 _this._maxInternalBlockNumber = -1024;
781 _this._lastBlockNumber = -2;
782 _this._maxFilterBlockRange = 10;
783 _this._pollingInterval = 4000;
784 _this._fastQueryDate = 0;
785 return _this;
786 }
787 BaseProvider.prototype._ready = function () {
788 return __awaiter(this, void 0, void 0, function () {
789 var network, error_4;
790 return __generator(this, function (_a) {
791 switch (_a.label) {
792 case 0:
793 if (!(this._network == null)) return [3 /*break*/, 7];
794 network = null;
795 if (!this._networkPromise) return [3 /*break*/, 4];
796 _a.label = 1;
797 case 1:
798 _a.trys.push([1, 3, , 4]);
799 return [4 /*yield*/, this._networkPromise];
800 case 2:
801 network = _a.sent();
802 return [3 /*break*/, 4];
803 case 3:
804 error_4 = _a.sent();
805 return [3 /*break*/, 4];
806 case 4:
807 if (!(network == null)) return [3 /*break*/, 6];
808 return [4 /*yield*/, this.detectNetwork()];
809 case 5:
810 network = _a.sent();
811 _a.label = 6;
812 case 6:
813 // This should never happen; every Provider sub-class should have
814 // suggested a network by here (or have thrown).
815 if (!network) {
816 logger.throwError("no network detected", logger_1.Logger.errors.UNKNOWN_ERROR, {});
817 }
818 // Possible this call stacked so do not call defineReadOnly again
819 if (this._network == null) {
820 if (this.anyNetwork) {
821 this._network = network;
822 }
823 else {
824 (0, properties_1.defineReadOnly)(this, "_network", network);
825 }
826 this.emit("network", network, null);
827 }
828 _a.label = 7;
829 case 7: return [2 /*return*/, this._network];
830 }
831 });
832 });
833 };
834 Object.defineProperty(BaseProvider.prototype, "ready", {
835 // This will always return the most recently established network.
836 // For "any", this can change (a "network" event is emitted before
837 // any change is reflected); otherwise this cannot change
838 get: function () {
839 var _this = this;
840 return (0, web_1.poll)(function () {
841 return _this._ready().then(function (network) {
842 return network;
843 }, function (error) {
844 // If the network isn't running yet, we will wait
845 if (error.code === logger_1.Logger.errors.NETWORK_ERROR && error.event === "noNetwork") {
846 return undefined;
847 }
848 throw error;
849 });
850 });
851 },
852 enumerable: false,
853 configurable: true
854 });
855 // @TODO: Remove this and just create a singleton formatter
856 BaseProvider.getFormatter = function () {
857 if (defaultFormatter == null) {
858 defaultFormatter = new formatter_1.Formatter();
859 }
860 return defaultFormatter;
861 };
862 // @TODO: Remove this and just use getNetwork
863 BaseProvider.getNetwork = function (network) {
864 return (0, networks_1.getNetwork)((network == null) ? "homestead" : network);
865 };
866 BaseProvider.prototype.ccipReadFetch = function (tx, calldata, urls) {
867 return __awaiter(this, void 0, void 0, function () {
868 var sender, data, errorMessages, i, url, href, json, result, errorMessage;
869 return __generator(this, function (_a) {
870 switch (_a.label) {
871 case 0:
872 if (this.disableCcipRead || urls.length === 0) {
873 return [2 /*return*/, null];
874 }
875 sender = tx.to.toLowerCase();
876 data = calldata.toLowerCase();
877 errorMessages = [];
878 i = 0;
879 _a.label = 1;
880 case 1:
881 if (!(i < urls.length)) return [3 /*break*/, 4];
882 url = urls[i];
883 href = url.replace("{sender}", sender).replace("{data}", data);
884 json = (url.indexOf("{data}") >= 0) ? null : JSON.stringify({ data: data, sender: sender });
885 return [4 /*yield*/, (0, web_1.fetchJson)({ url: href, errorPassThrough: true }, json, function (value, response) {
886 value.status = response.statusCode;
887 return value;
888 })];
889 case 2:
890 result = _a.sent();
891 if (result.data) {
892 return [2 /*return*/, result.data];
893 }
894 errorMessage = (result.message || "unknown error");
895 // 4xx indicates the result is not present; stop
896 if (result.status >= 400 && result.status < 500) {
897 return [2 /*return*/, logger.throwError("response not found during CCIP fetch: " + errorMessage, logger_1.Logger.errors.SERVER_ERROR, { url: url, errorMessage: errorMessage })];
898 }
899 // 5xx indicates server issue; try the next url
900 errorMessages.push(errorMessage);
901 _a.label = 3;
902 case 3:
903 i++;
904 return [3 /*break*/, 1];
905 case 4: return [2 /*return*/, logger.throwError("error encountered during CCIP fetch: " + errorMessages.map(function (m) { return JSON.stringify(m); }).join(", "), logger_1.Logger.errors.SERVER_ERROR, {
906 urls: urls,
907 errorMessages: errorMessages
908 })];
909 }
910 });
911 });
912 };
913 // Fetches the blockNumber, but will reuse any result that is less
914 // than maxAge old or has been requested since the last request
915 BaseProvider.prototype._getInternalBlockNumber = function (maxAge) {
916 return __awaiter(this, void 0, void 0, function () {
917 var internalBlockNumber, result, error_5, reqTime, checkInternalBlockNumber;
918 var _this = this;
919 return __generator(this, function (_a) {
920 switch (_a.label) {
921 case 0: return [4 /*yield*/, this._ready()];
922 case 1:
923 _a.sent();
924 if (!(maxAge > 0)) return [3 /*break*/, 7];
925 _a.label = 2;
926 case 2:
927 if (!this._internalBlockNumber) return [3 /*break*/, 7];
928 internalBlockNumber = this._internalBlockNumber;
929 _a.label = 3;
930 case 3:
931 _a.trys.push([3, 5, , 6]);
932 return [4 /*yield*/, internalBlockNumber];
933 case 4:
934 result = _a.sent();
935 if ((getTime() - result.respTime) <= maxAge) {
936 return [2 /*return*/, result.blockNumber];
937 }
938 // Too old; fetch a new value
939 return [3 /*break*/, 7];
940 case 5:
941 error_5 = _a.sent();
942 // The fetch rejected; if we are the first to get the
943 // rejection, drop through so we replace it with a new
944 // fetch; all others blocked will then get that fetch
945 // which won't match the one they "remembered" and loop
946 if (this._internalBlockNumber === internalBlockNumber) {
947 return [3 /*break*/, 7];
948 }
949 return [3 /*break*/, 6];
950 case 6: return [3 /*break*/, 2];
951 case 7:
952 reqTime = getTime();
953 checkInternalBlockNumber = (0, properties_1.resolveProperties)({
954 blockNumber: this.perform("getBlockNumber", {}),
955 networkError: this.getNetwork().then(function (network) { return (null); }, function (error) { return (error); })
956 }).then(function (_a) {
957 var blockNumber = _a.blockNumber, networkError = _a.networkError;
958 if (networkError) {
959 // Unremember this bad internal block number
960 if (_this._internalBlockNumber === checkInternalBlockNumber) {
961 _this._internalBlockNumber = null;
962 }
963 throw networkError;
964 }
965 var respTime = getTime();
966 blockNumber = bignumber_1.BigNumber.from(blockNumber).toNumber();
967 if (blockNumber < _this._maxInternalBlockNumber) {
968 blockNumber = _this._maxInternalBlockNumber;
969 }
970 _this._maxInternalBlockNumber = blockNumber;
971 _this._setFastBlockNumber(blockNumber); // @TODO: Still need this?
972 return { blockNumber: blockNumber, reqTime: reqTime, respTime: respTime };
973 });
974 this._internalBlockNumber = checkInternalBlockNumber;
975 // Swallow unhandled exceptions; if needed they are handled else where
976 checkInternalBlockNumber.catch(function (error) {
977 // Don't null the dead (rejected) fetch, if it has already been updated
978 if (_this._internalBlockNumber === checkInternalBlockNumber) {
979 _this._internalBlockNumber = null;
980 }
981 });
982 return [4 /*yield*/, checkInternalBlockNumber];
983 case 8: return [2 /*return*/, (_a.sent()).blockNumber];
984 }
985 });
986 });
987 };
988 BaseProvider.prototype.poll = function () {
989 return __awaiter(this, void 0, void 0, function () {
990 var pollId, runners, blockNumber, error_6, i;
991 var _this = this;
992 return __generator(this, function (_a) {
993 switch (_a.label) {
994 case 0:
995 pollId = nextPollId++;
996 runners = [];
997 blockNumber = null;
998 _a.label = 1;
999 case 1:
1000 _a.trys.push([1, 3, , 4]);
1001 return [4 /*yield*/, this._getInternalBlockNumber(100 + this.pollingInterval / 2)];
1002 case 2:
1003 blockNumber = _a.sent();
1004 return [3 /*break*/, 4];
1005 case 3:
1006 error_6 = _a.sent();
1007 this.emit("error", error_6);
1008 return [2 /*return*/];
1009 case 4:
1010 this._setFastBlockNumber(blockNumber);
1011 // Emit a poll event after we have the latest (fast) block number
1012 this.emit("poll", pollId, blockNumber);
1013 // If the block has not changed, meh.
1014 if (blockNumber === this._lastBlockNumber) {
1015 this.emit("didPoll", pollId);
1016 return [2 /*return*/];
1017 }
1018 // First polling cycle, trigger a "block" events
1019 if (this._emitted.block === -2) {
1020 this._emitted.block = blockNumber - 1;
1021 }
1022 if (Math.abs((this._emitted.block) - blockNumber) > 1000) {
1023 logger.warn("network block skew detected; skipping block events (emitted=" + this._emitted.block + " blockNumber" + blockNumber + ")");
1024 this.emit("error", logger.makeError("network block skew detected", logger_1.Logger.errors.NETWORK_ERROR, {
1025 blockNumber: blockNumber,
1026 event: "blockSkew",
1027 previousBlockNumber: this._emitted.block
1028 }));
1029 this.emit("block", blockNumber);
1030 }
1031 else {
1032 // Notify all listener for each block that has passed
1033 for (i = this._emitted.block + 1; i <= blockNumber; i++) {
1034 this.emit("block", i);
1035 }
1036 }
1037 // The emitted block was updated, check for obsolete events
1038 if (this._emitted.block !== blockNumber) {
1039 this._emitted.block = blockNumber;
1040 Object.keys(this._emitted).forEach(function (key) {
1041 // The block event does not expire
1042 if (key === "block") {
1043 return;
1044 }
1045 // The block we were at when we emitted this event
1046 var eventBlockNumber = _this._emitted[key];
1047 // We cannot garbage collect pending transactions or blocks here
1048 // They should be garbage collected by the Provider when setting
1049 // "pending" events
1050 if (eventBlockNumber === "pending") {
1051 return;
1052 }
1053 // Evict any transaction hashes or block hashes over 12 blocks
1054 // old, since they should not return null anyways
1055 if (blockNumber - eventBlockNumber > 12) {
1056 delete _this._emitted[key];
1057 }
1058 });
1059 }
1060 // First polling cycle
1061 if (this._lastBlockNumber === -2) {
1062 this._lastBlockNumber = blockNumber - 1;
1063 }
1064 // Find all transaction hashes we are waiting on
1065 this._events.forEach(function (event) {
1066 switch (event.type) {
1067 case "tx": {
1068 var hash_2 = event.hash;
1069 var runner = _this.getTransactionReceipt(hash_2).then(function (receipt) {
1070 if (!receipt || receipt.blockNumber == null) {
1071 return null;
1072 }
1073 _this._emitted["t:" + hash_2] = receipt.blockNumber;
1074 _this.emit(hash_2, receipt);
1075 return null;
1076 }).catch(function (error) { _this.emit("error", error); });
1077 runners.push(runner);
1078 break;
1079 }
1080 case "filter": {
1081 // We only allow a single getLogs to be in-flight at a time
1082 if (!event._inflight) {
1083 event._inflight = true;
1084 // Filter from the last known event; due to load-balancing
1085 // and some nodes returning updated block numbers before
1086 // indexing events, a logs result with 0 entries cannot be
1087 // trusted and we must retry a range which includes it again
1088 var filter_1 = event.filter;
1089 filter_1.fromBlock = event._lastBlockNumber + 1;
1090 filter_1.toBlock = blockNumber;
1091 // Prevent fitler ranges from growing too wild
1092 if (filter_1.toBlock - _this._maxFilterBlockRange > filter_1.fromBlock) {
1093 filter_1.fromBlock = filter_1.toBlock - _this._maxFilterBlockRange;
1094 }
1095 var runner = _this.getLogs(filter_1).then(function (logs) {
1096 // Allow the next getLogs
1097 event._inflight = false;
1098 if (logs.length === 0) {
1099 return;
1100 }
1101 logs.forEach(function (log) {
1102 // Only when we get an event for a given block number
1103 // can we trust the events are indexed
1104 if (log.blockNumber > event._lastBlockNumber) {
1105 event._lastBlockNumber = log.blockNumber;
1106 }
1107 // Make sure we stall requests to fetch blocks and txs
1108 _this._emitted["b:" + log.blockHash] = log.blockNumber;
1109 _this._emitted["t:" + log.transactionHash] = log.blockNumber;
1110 _this.emit(filter_1, log);
1111 });
1112 }).catch(function (error) {
1113 _this.emit("error", error);
1114 // Allow another getLogs (the range was not updated)
1115 event._inflight = false;
1116 });
1117 runners.push(runner);
1118 }
1119 break;
1120 }
1121 }
1122 });
1123 this._lastBlockNumber = blockNumber;
1124 // Once all events for this loop have been processed, emit "didPoll"
1125 Promise.all(runners).then(function () {
1126 _this.emit("didPoll", pollId);
1127 }).catch(function (error) { _this.emit("error", error); });
1128 return [2 /*return*/];
1129 }
1130 });
1131 });
1132 };
1133 // Deprecated; do not use this
1134 BaseProvider.prototype.resetEventsBlock = function (blockNumber) {
1135 this._lastBlockNumber = blockNumber - 1;
1136 if (this.polling) {
1137 this.poll();
1138 }
1139 };
1140 Object.defineProperty(BaseProvider.prototype, "network", {
1141 get: function () {
1142 return this._network;
1143 },
1144 enumerable: false,
1145 configurable: true
1146 });
1147 // This method should query the network if the underlying network
1148 // can change, such as when connected to a JSON-RPC backend
1149 BaseProvider.prototype.detectNetwork = function () {
1150 return __awaiter(this, void 0, void 0, function () {
1151 return __generator(this, function (_a) {
1152 return [2 /*return*/, logger.throwError("provider does not support network detection", logger_1.Logger.errors.UNSUPPORTED_OPERATION, {
1153 operation: "provider.detectNetwork"
1154 })];
1155 });
1156 });
1157 };
1158 BaseProvider.prototype.getNetwork = function () {
1159 return __awaiter(this, void 0, void 0, function () {
1160 var network, currentNetwork, error;
1161 return __generator(this, function (_a) {
1162 switch (_a.label) {
1163 case 0: return [4 /*yield*/, this._ready()];
1164 case 1:
1165 network = _a.sent();
1166 return [4 /*yield*/, this.detectNetwork()];
1167 case 2:
1168 currentNetwork = _a.sent();
1169 if (!(network.chainId !== currentNetwork.chainId)) return [3 /*break*/, 5];
1170 if (!this.anyNetwork) return [3 /*break*/, 4];
1171 this._network = currentNetwork;
1172 // Reset all internal block number guards and caches
1173 this._lastBlockNumber = -2;
1174 this._fastBlockNumber = null;
1175 this._fastBlockNumberPromise = null;
1176 this._fastQueryDate = 0;
1177 this._emitted.block = -2;
1178 this._maxInternalBlockNumber = -1024;
1179 this._internalBlockNumber = null;
1180 // The "network" event MUST happen before this method resolves
1181 // so any events have a chance to unregister, so we stall an
1182 // additional event loop before returning from /this/ call
1183 this.emit("network", currentNetwork, network);
1184 return [4 /*yield*/, stall(0)];
1185 case 3:
1186 _a.sent();
1187 return [2 /*return*/, this._network];
1188 case 4:
1189 error = logger.makeError("underlying network changed", logger_1.Logger.errors.NETWORK_ERROR, {
1190 event: "changed",
1191 network: network,
1192 detectedNetwork: currentNetwork
1193 });
1194 this.emit("error", error);
1195 throw error;
1196 case 5: return [2 /*return*/, network];
1197 }
1198 });
1199 });
1200 };
1201 Object.defineProperty(BaseProvider.prototype, "blockNumber", {
1202 get: function () {
1203 var _this = this;
1204 this._getInternalBlockNumber(100 + this.pollingInterval / 2).then(function (blockNumber) {
1205 _this._setFastBlockNumber(blockNumber);
1206 }, function (error) { });
1207 return (this._fastBlockNumber != null) ? this._fastBlockNumber : -1;
1208 },
1209 enumerable: false,
1210 configurable: true
1211 });
1212 Object.defineProperty(BaseProvider.prototype, "polling", {
1213 get: function () {
1214 return (this._poller != null);
1215 },
1216 set: function (value) {
1217 var _this = this;
1218 if (value && !this._poller) {
1219 this._poller = setInterval(function () { _this.poll(); }, this.pollingInterval);
1220 if (!this._bootstrapPoll) {
1221 this._bootstrapPoll = setTimeout(function () {
1222 _this.poll();
1223 // We block additional polls until the polling interval
1224 // is done, to prevent overwhelming the poll function
1225 _this._bootstrapPoll = setTimeout(function () {
1226 // If polling was disabled, something may require a poke
1227 // since starting the bootstrap poll and it was disabled
1228 if (!_this._poller) {
1229 _this.poll();
1230 }
1231 // Clear out the bootstrap so we can do another
1232 _this._bootstrapPoll = null;
1233 }, _this.pollingInterval);
1234 }, 0);
1235 }
1236 }
1237 else if (!value && this._poller) {
1238 clearInterval(this._poller);
1239 this._poller = null;
1240 }
1241 },
1242 enumerable: false,
1243 configurable: true
1244 });
1245 Object.defineProperty(BaseProvider.prototype, "pollingInterval", {
1246 get: function () {
1247 return this._pollingInterval;
1248 },
1249 set: function (value) {
1250 var _this = this;
1251 if (typeof (value) !== "number" || value <= 0 || parseInt(String(value)) != value) {
1252 throw new Error("invalid polling interval");
1253 }
1254 this._pollingInterval = value;
1255 if (this._poller) {
1256 clearInterval(this._poller);
1257 this._poller = setInterval(function () { _this.poll(); }, this._pollingInterval);
1258 }
1259 },
1260 enumerable: false,
1261 configurable: true
1262 });
1263 BaseProvider.prototype._getFastBlockNumber = function () {
1264 var _this = this;
1265 var now = getTime();
1266 // Stale block number, request a newer value
1267 if ((now - this._fastQueryDate) > 2 * this._pollingInterval) {
1268 this._fastQueryDate = now;
1269 this._fastBlockNumberPromise = this.getBlockNumber().then(function (blockNumber) {
1270 if (_this._fastBlockNumber == null || blockNumber > _this._fastBlockNumber) {
1271 _this._fastBlockNumber = blockNumber;
1272 }
1273 return _this._fastBlockNumber;
1274 });
1275 }
1276 return this._fastBlockNumberPromise;
1277 };
1278 BaseProvider.prototype._setFastBlockNumber = function (blockNumber) {
1279 // Older block, maybe a stale request
1280 if (this._fastBlockNumber != null && blockNumber < this._fastBlockNumber) {
1281 return;
1282 }
1283 // Update the time we updated the blocknumber
1284 this._fastQueryDate = getTime();
1285 // Newer block number, use it
1286 if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) {
1287 this._fastBlockNumber = blockNumber;
1288 this._fastBlockNumberPromise = Promise.resolve(blockNumber);
1289 }
1290 };
1291 BaseProvider.prototype.waitForTransaction = function (transactionHash, confirmations, timeout) {
1292 return __awaiter(this, void 0, void 0, function () {
1293 return __generator(this, function (_a) {
1294 return [2 /*return*/, this._waitForTransaction(transactionHash, (confirmations == null) ? 1 : confirmations, timeout || 0, null)];
1295 });
1296 });
1297 };
1298 BaseProvider.prototype._waitForTransaction = function (transactionHash, confirmations, timeout, replaceable) {
1299 return __awaiter(this, void 0, void 0, function () {
1300 var receipt;
1301 var _this = this;
1302 return __generator(this, function (_a) {
1303 switch (_a.label) {
1304 case 0: return [4 /*yield*/, this.getTransactionReceipt(transactionHash)];
1305 case 1:
1306 receipt = _a.sent();
1307 // Receipt is already good
1308 if ((receipt ? receipt.confirmations : 0) >= confirmations) {
1309 return [2 /*return*/, receipt];
1310 }
1311 // Poll until the receipt is good...
1312 return [2 /*return*/, new Promise(function (resolve, reject) {
1313 var cancelFuncs = [];
1314 var done = false;
1315 var alreadyDone = function () {
1316 if (done) {
1317 return true;
1318 }
1319 done = true;
1320 cancelFuncs.forEach(function (func) { func(); });
1321 return false;
1322 };
1323 var minedHandler = function (receipt) {
1324 if (receipt.confirmations < confirmations) {
1325 return;
1326 }
1327 if (alreadyDone()) {
1328 return;
1329 }
1330 resolve(receipt);
1331 };
1332 _this.on(transactionHash, minedHandler);
1333 cancelFuncs.push(function () { _this.removeListener(transactionHash, minedHandler); });
1334 if (replaceable) {
1335 var lastBlockNumber_1 = replaceable.startBlock;
1336 var scannedBlock_1 = null;
1337 var replaceHandler_1 = function (blockNumber) { return __awaiter(_this, void 0, void 0, function () {
1338 var _this = this;
1339 return __generator(this, function (_a) {
1340 switch (_a.label) {
1341 case 0:
1342 if (done) {
1343 return [2 /*return*/];
1344 }
1345 // Wait 1 second; this is only used in the case of a fault, so
1346 // we will trade off a little bit of latency for more consistent
1347 // results and fewer JSON-RPC calls
1348 return [4 /*yield*/, stall(1000)];
1349 case 1:
1350 // Wait 1 second; this is only used in the case of a fault, so
1351 // we will trade off a little bit of latency for more consistent
1352 // results and fewer JSON-RPC calls
1353 _a.sent();
1354 this.getTransactionCount(replaceable.from).then(function (nonce) { return __awaiter(_this, void 0, void 0, function () {
1355 var mined, block, ti, tx, receipt_1, reason;
1356 return __generator(this, function (_a) {
1357 switch (_a.label) {
1358 case 0:
1359 if (done) {
1360 return [2 /*return*/];
1361 }
1362 if (!(nonce <= replaceable.nonce)) return [3 /*break*/, 1];
1363 lastBlockNumber_1 = blockNumber;
1364 return [3 /*break*/, 9];
1365 case 1: return [4 /*yield*/, this.getTransaction(transactionHash)];
1366 case 2:
1367 mined = _a.sent();
1368 if (mined && mined.blockNumber != null) {
1369 return [2 /*return*/];
1370 }
1371 // First time scanning. We start a little earlier for some
1372 // wiggle room here to handle the eventually consistent nature
1373 // of blockchain (e.g. the getTransactionCount was for a
1374 // different block)
1375 if (scannedBlock_1 == null) {
1376 scannedBlock_1 = lastBlockNumber_1 - 3;
1377 if (scannedBlock_1 < replaceable.startBlock) {
1378 scannedBlock_1 = replaceable.startBlock;
1379 }
1380 }
1381 _a.label = 3;
1382 case 3:
1383 if (!(scannedBlock_1 <= blockNumber)) return [3 /*break*/, 9];
1384 if (done) {
1385 return [2 /*return*/];
1386 }
1387 return [4 /*yield*/, this.getBlockWithTransactions(scannedBlock_1)];
1388 case 4:
1389 block = _a.sent();
1390 ti = 0;
1391 _a.label = 5;
1392 case 5:
1393 if (!(ti < block.transactions.length)) return [3 /*break*/, 8];
1394 tx = block.transactions[ti];
1395 // Successfully mined!
1396 if (tx.hash === transactionHash) {
1397 return [2 /*return*/];
1398 }
1399 if (!(tx.from === replaceable.from && tx.nonce === replaceable.nonce)) return [3 /*break*/, 7];
1400 if (done) {
1401 return [2 /*return*/];
1402 }
1403 return [4 /*yield*/, this.waitForTransaction(tx.hash, confirmations)];
1404 case 6:
1405 receipt_1 = _a.sent();
1406 // Already resolved or rejected (prolly a timeout)
1407 if (alreadyDone()) {
1408 return [2 /*return*/];
1409 }
1410 reason = "replaced";
1411 if (tx.data === replaceable.data && tx.to === replaceable.to && tx.value.eq(replaceable.value)) {
1412 reason = "repriced";
1413 }
1414 else if (tx.data === "0x" && tx.from === tx.to && tx.value.isZero()) {
1415 reason = "cancelled";
1416 }
1417 // Explain why we were replaced
1418 reject(logger.makeError("transaction was replaced", logger_1.Logger.errors.TRANSACTION_REPLACED, {
1419 cancelled: (reason === "replaced" || reason === "cancelled"),
1420 reason: reason,
1421 replacement: this._wrapTransaction(tx),
1422 hash: transactionHash,
1423 receipt: receipt_1
1424 }));
1425 return [2 /*return*/];
1426 case 7:
1427 ti++;
1428 return [3 /*break*/, 5];
1429 case 8:
1430 scannedBlock_1++;
1431 return [3 /*break*/, 3];
1432 case 9:
1433 if (done) {
1434 return [2 /*return*/];
1435 }
1436 this.once("block", replaceHandler_1);
1437 return [2 /*return*/];
1438 }
1439 });
1440 }); }, function (error) {
1441 if (done) {
1442 return;
1443 }
1444 _this.once("block", replaceHandler_1);
1445 });
1446 return [2 /*return*/];
1447 }
1448 });
1449 }); };
1450 if (done) {
1451 return;
1452 }
1453 _this.once("block", replaceHandler_1);
1454 cancelFuncs.push(function () {
1455 _this.removeListener("block", replaceHandler_1);
1456 });
1457 }
1458 if (typeof (timeout) === "number" && timeout > 0) {
1459 var timer_1 = setTimeout(function () {
1460 if (alreadyDone()) {
1461 return;
1462 }
1463 reject(logger.makeError("timeout exceeded", logger_1.Logger.errors.TIMEOUT, { timeout: timeout }));
1464 }, timeout);
1465 if (timer_1.unref) {
1466 timer_1.unref();
1467 }
1468 cancelFuncs.push(function () { clearTimeout(timer_1); });
1469 }
1470 })];
1471 }
1472 });
1473 });
1474 };
1475 BaseProvider.prototype.getBlockNumber = function () {
1476 return __awaiter(this, void 0, void 0, function () {
1477 return __generator(this, function (_a) {
1478 return [2 /*return*/, this._getInternalBlockNumber(0)];
1479 });
1480 });
1481 };
1482 BaseProvider.prototype.getGasPrice = function () {
1483 return __awaiter(this, void 0, void 0, function () {
1484 var result;
1485 return __generator(this, function (_a) {
1486 switch (_a.label) {
1487 case 0: return [4 /*yield*/, this.getNetwork()];
1488 case 1:
1489 _a.sent();
1490 return [4 /*yield*/, this.perform("getGasPrice", {})];
1491 case 2:
1492 result = _a.sent();
1493 try {
1494 return [2 /*return*/, bignumber_1.BigNumber.from(result)];
1495 }
1496 catch (error) {
1497 return [2 /*return*/, logger.throwError("bad result from backend", logger_1.Logger.errors.SERVER_ERROR, {
1498 method: "getGasPrice",
1499 result: result,
1500 error: error
1501 })];
1502 }
1503 return [2 /*return*/];
1504 }
1505 });
1506 });
1507 };
1508 BaseProvider.prototype.getBalance = function (addressOrName, blockTag) {
1509 return __awaiter(this, void 0, void 0, function () {
1510 var params, result;
1511 return __generator(this, function (_a) {
1512 switch (_a.label) {
1513 case 0: return [4 /*yield*/, this.getNetwork()];
1514 case 1:
1515 _a.sent();
1516 return [4 /*yield*/, (0, properties_1.resolveProperties)({
1517 address: this._getAddress(addressOrName),
1518 blockTag: this._getBlockTag(blockTag)
1519 })];
1520 case 2:
1521 params = _a.sent();
1522 return [4 /*yield*/, this.perform("getBalance", params)];
1523 case 3:
1524 result = _a.sent();
1525 try {
1526 return [2 /*return*/, bignumber_1.BigNumber.from(result)];
1527 }
1528 catch (error) {
1529 return [2 /*return*/, logger.throwError("bad result from backend", logger_1.Logger.errors.SERVER_ERROR, {
1530 method: "getBalance",
1531 params: params,
1532 result: result,
1533 error: error
1534 })];
1535 }
1536 return [2 /*return*/];
1537 }
1538 });
1539 });
1540 };
1541 BaseProvider.prototype.getTransactionCount = function (addressOrName, blockTag) {
1542 return __awaiter(this, void 0, void 0, function () {
1543 var params, result;
1544 return __generator(this, function (_a) {
1545 switch (_a.label) {
1546 case 0: return [4 /*yield*/, this.getNetwork()];
1547 case 1:
1548 _a.sent();
1549 return [4 /*yield*/, (0, properties_1.resolveProperties)({
1550 address: this._getAddress(addressOrName),
1551 blockTag: this._getBlockTag(blockTag)
1552 })];
1553 case 2:
1554 params = _a.sent();
1555 return [4 /*yield*/, this.perform("getTransactionCount", params)];
1556 case 3:
1557 result = _a.sent();
1558 try {
1559 return [2 /*return*/, bignumber_1.BigNumber.from(result).toNumber()];
1560 }
1561 catch (error) {
1562 return [2 /*return*/, logger.throwError("bad result from backend", logger_1.Logger.errors.SERVER_ERROR, {
1563 method: "getTransactionCount",
1564 params: params,
1565 result: result,
1566 error: error
1567 })];
1568 }
1569 return [2 /*return*/];
1570 }
1571 });
1572 });
1573 };
1574 BaseProvider.prototype.getCode = function (addressOrName, blockTag) {
1575 return __awaiter(this, void 0, void 0, function () {
1576 var params, result;
1577 return __generator(this, function (_a) {
1578 switch (_a.label) {
1579 case 0: return [4 /*yield*/, this.getNetwork()];
1580 case 1:
1581 _a.sent();
1582 return [4 /*yield*/, (0, properties_1.resolveProperties)({
1583 address: this._getAddress(addressOrName),
1584 blockTag: this._getBlockTag(blockTag)
1585 })];
1586 case 2:
1587 params = _a.sent();
1588 return [4 /*yield*/, this.perform("getCode", params)];
1589 case 3:
1590 result = _a.sent();
1591 try {
1592 return [2 /*return*/, (0, bytes_1.hexlify)(result)];
1593 }
1594 catch (error) {
1595 return [2 /*return*/, logger.throwError("bad result from backend", logger_1.Logger.errors.SERVER_ERROR, {
1596 method: "getCode",
1597 params: params,
1598 result: result,
1599 error: error
1600 })];
1601 }
1602 return [2 /*return*/];
1603 }
1604 });
1605 });
1606 };
1607 BaseProvider.prototype.getStorageAt = function (addressOrName, position, blockTag) {
1608 return __awaiter(this, void 0, void 0, function () {
1609 var params, result;
1610 return __generator(this, function (_a) {
1611 switch (_a.label) {
1612 case 0: return [4 /*yield*/, this.getNetwork()];
1613 case 1:
1614 _a.sent();
1615 return [4 /*yield*/, (0, properties_1.resolveProperties)({
1616 address: this._getAddress(addressOrName),
1617 blockTag: this._getBlockTag(blockTag),
1618 position: Promise.resolve(position).then(function (p) { return (0, bytes_1.hexValue)(p); })
1619 })];
1620 case 2:
1621 params = _a.sent();
1622 return [4 /*yield*/, this.perform("getStorageAt", params)];
1623 case 3:
1624 result = _a.sent();
1625 try {
1626 return [2 /*return*/, (0, bytes_1.hexlify)(result)];
1627 }
1628 catch (error) {
1629 return [2 /*return*/, logger.throwError("bad result from backend", logger_1.Logger.errors.SERVER_ERROR, {
1630 method: "getStorageAt",
1631 params: params,
1632 result: result,
1633 error: error
1634 })];
1635 }
1636 return [2 /*return*/];
1637 }
1638 });
1639 });
1640 };
1641 // This should be called by any subclass wrapping a TransactionResponse
1642 BaseProvider.prototype._wrapTransaction = function (tx, hash, startBlock) {
1643 var _this = this;
1644 if (hash != null && (0, bytes_1.hexDataLength)(hash) !== 32) {
1645 throw new Error("invalid response - sendTransaction");
1646 }
1647 var result = tx;
1648 // Check the hash we expect is the same as the hash the server reported
1649 if (hash != null && tx.hash !== hash) {
1650 logger.throwError("Transaction hash mismatch from Provider.sendTransaction.", logger_1.Logger.errors.UNKNOWN_ERROR, { expectedHash: tx.hash, returnedHash: hash });
1651 }
1652 result.wait = function (confirms, timeout) { return __awaiter(_this, void 0, void 0, function () {
1653 var replacement, receipt;
1654 return __generator(this, function (_a) {
1655 switch (_a.label) {
1656 case 0:
1657 if (confirms == null) {
1658 confirms = 1;
1659 }
1660 if (timeout == null) {
1661 timeout = 0;
1662 }
1663 replacement = undefined;
1664 if (confirms !== 0 && startBlock != null) {
1665 replacement = {
1666 data: tx.data,
1667 from: tx.from,
1668 nonce: tx.nonce,
1669 to: tx.to,
1670 value: tx.value,
1671 startBlock: startBlock
1672 };
1673 }
1674 return [4 /*yield*/, this._waitForTransaction(tx.hash, confirms, timeout, replacement)];
1675 case 1:
1676 receipt = _a.sent();
1677 if (receipt == null && confirms === 0) {
1678 return [2 /*return*/, null];
1679 }
1680 // No longer pending, allow the polling loop to garbage collect this
1681 this._emitted["t:" + tx.hash] = receipt.blockNumber;
1682 if (receipt.status === 0) {
1683 logger.throwError("transaction failed", logger_1.Logger.errors.CALL_EXCEPTION, {
1684 transactionHash: tx.hash,
1685 transaction: tx,
1686 receipt: receipt
1687 });
1688 }
1689 return [2 /*return*/, receipt];
1690 }
1691 });
1692 }); };
1693 return result;
1694 };
1695 BaseProvider.prototype.sendTransaction = function (signedTransaction) {
1696 return __awaiter(this, void 0, void 0, function () {
1697 var hexTx, tx, blockNumber, hash, error_7;
1698 return __generator(this, function (_a) {
1699 switch (_a.label) {
1700 case 0: return [4 /*yield*/, this.getNetwork()];
1701 case 1:
1702 _a.sent();
1703 return [4 /*yield*/, Promise.resolve(signedTransaction).then(function (t) { return (0, bytes_1.hexlify)(t); })];
1704 case 2:
1705 hexTx = _a.sent();
1706 tx = this.formatter.transaction(signedTransaction);
1707 if (tx.confirmations == null) {
1708 tx.confirmations = 0;
1709 }
1710 return [4 /*yield*/, this._getInternalBlockNumber(100 + 2 * this.pollingInterval)];
1711 case 3:
1712 blockNumber = _a.sent();
1713 _a.label = 4;
1714 case 4:
1715 _a.trys.push([4, 6, , 7]);
1716 return [4 /*yield*/, this.perform("sendTransaction", { signedTransaction: hexTx })];
1717 case 5:
1718 hash = _a.sent();
1719 return [2 /*return*/, this._wrapTransaction(tx, hash, blockNumber)];
1720 case 6:
1721 error_7 = _a.sent();
1722 error_7.transaction = tx;
1723 error_7.transactionHash = tx.hash;
1724 throw error_7;
1725 case 7: return [2 /*return*/];
1726 }
1727 });
1728 });
1729 };
1730 BaseProvider.prototype._getTransactionRequest = function (transaction) {
1731 return __awaiter(this, void 0, void 0, function () {
1732 var values, tx, _a, _b;
1733 var _this = this;
1734 return __generator(this, function (_c) {
1735 switch (_c.label) {
1736 case 0: return [4 /*yield*/, transaction];
1737 case 1:
1738 values = _c.sent();
1739 tx = {};
1740 ["from", "to"].forEach(function (key) {
1741 if (values[key] == null) {
1742 return;
1743 }
1744 tx[key] = Promise.resolve(values[key]).then(function (v) { return (v ? _this._getAddress(v) : null); });
1745 });
1746 ["gasLimit", "gasPrice", "maxFeePerGas", "maxPriorityFeePerGas", "value"].forEach(function (key) {
1747 if (values[key] == null) {
1748 return;
1749 }
1750 tx[key] = Promise.resolve(values[key]).then(function (v) { return (v ? bignumber_1.BigNumber.from(v) : null); });
1751 });
1752 ["type"].forEach(function (key) {
1753 if (values[key] == null) {
1754 return;
1755 }
1756 tx[key] = Promise.resolve(values[key]).then(function (v) { return ((v != null) ? v : null); });
1757 });
1758 if (values.accessList) {
1759 tx.accessList = this.formatter.accessList(values.accessList);
1760 }
1761 ["data"].forEach(function (key) {
1762 if (values[key] == null) {
1763 return;
1764 }
1765 tx[key] = Promise.resolve(values[key]).then(function (v) { return (v ? (0, bytes_1.hexlify)(v) : null); });
1766 });
1767 _b = (_a = this.formatter).transactionRequest;
1768 return [4 /*yield*/, (0, properties_1.resolveProperties)(tx)];
1769 case 2: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
1770 }
1771 });
1772 });
1773 };
1774 BaseProvider.prototype._getFilter = function (filter) {
1775 return __awaiter(this, void 0, void 0, function () {
1776 var result, _a, _b;
1777 var _this = this;
1778 return __generator(this, function (_c) {
1779 switch (_c.label) {
1780 case 0: return [4 /*yield*/, filter];
1781 case 1:
1782 filter = _c.sent();
1783 result = {};
1784 if (filter.address != null) {
1785 result.address = this._getAddress(filter.address);
1786 }
1787 ["blockHash", "topics"].forEach(function (key) {
1788 if (filter[key] == null) {
1789 return;
1790 }
1791 result[key] = filter[key];
1792 });
1793 ["fromBlock", "toBlock"].forEach(function (key) {
1794 if (filter[key] == null) {
1795 return;
1796 }
1797 result[key] = _this._getBlockTag(filter[key]);
1798 });
1799 _b = (_a = this.formatter).filter;
1800 return [4 /*yield*/, (0, properties_1.resolveProperties)(result)];
1801 case 2: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
1802 }
1803 });
1804 });
1805 };
1806 BaseProvider.prototype._call = function (transaction, blockTag, attempt) {
1807 return __awaiter(this, void 0, void 0, function () {
1808 var txSender, result, data, sender, urls, urlsOffset, urlsLength, urlsData, u, url, calldata, callbackSelector, extraData, ccipResult, tx, error_8;
1809 return __generator(this, function (_a) {
1810 switch (_a.label) {
1811 case 0:
1812 if (attempt >= MAX_CCIP_REDIRECTS) {
1813 logger.throwError("CCIP read exceeded maximum redirections", logger_1.Logger.errors.SERVER_ERROR, {
1814 redirects: attempt,
1815 transaction: transaction
1816 });
1817 }
1818 txSender = transaction.to;
1819 return [4 /*yield*/, this.perform("call", { transaction: transaction, blockTag: blockTag })];
1820 case 1:
1821 result = _a.sent();
1822 if (!(attempt >= 0 && blockTag === "latest" && txSender != null && result.substring(0, 10) === "0x556f1830" && ((0, bytes_1.hexDataLength)(result) % 32 === 4))) return [3 /*break*/, 5];
1823 _a.label = 2;
1824 case 2:
1825 _a.trys.push([2, 4, , 5]);
1826 data = (0, bytes_1.hexDataSlice)(result, 4);
1827 sender = (0, bytes_1.hexDataSlice)(data, 0, 32);
1828 if (!bignumber_1.BigNumber.from(sender).eq(txSender)) {
1829 logger.throwError("CCIP Read sender did not match", logger_1.Logger.errors.CALL_EXCEPTION, {
1830 name: "OffchainLookup",
1831 signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
1832 transaction: transaction,
1833 data: result
1834 });
1835 }
1836 urls = [];
1837 urlsOffset = bignumber_1.BigNumber.from((0, bytes_1.hexDataSlice)(data, 32, 64)).toNumber();
1838 urlsLength = bignumber_1.BigNumber.from((0, bytes_1.hexDataSlice)(data, urlsOffset, urlsOffset + 32)).toNumber();
1839 urlsData = (0, bytes_1.hexDataSlice)(data, urlsOffset + 32);
1840 for (u = 0; u < urlsLength; u++) {
1841 url = _parseString(urlsData, u * 32);
1842 if (url == null) {
1843 logger.throwError("CCIP Read contained corrupt URL string", logger_1.Logger.errors.CALL_EXCEPTION, {
1844 name: "OffchainLookup",
1845 signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
1846 transaction: transaction,
1847 data: result
1848 });
1849 }
1850 urls.push(url);
1851 }
1852 calldata = _parseBytes(data, 64);
1853 // Get the callbackSelector (bytes4)
1854 if (!bignumber_1.BigNumber.from((0, bytes_1.hexDataSlice)(data, 100, 128)).isZero()) {
1855 logger.throwError("CCIP Read callback selector included junk", logger_1.Logger.errors.CALL_EXCEPTION, {
1856 name: "OffchainLookup",
1857 signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
1858 transaction: transaction,
1859 data: result
1860 });
1861 }
1862 callbackSelector = (0, bytes_1.hexDataSlice)(data, 96, 100);
1863 extraData = _parseBytes(data, 128);
1864 return [4 /*yield*/, this.ccipReadFetch(transaction, calldata, urls)];
1865 case 3:
1866 ccipResult = _a.sent();
1867 if (ccipResult == null) {
1868 logger.throwError("CCIP Read disabled or provided no URLs", logger_1.Logger.errors.CALL_EXCEPTION, {
1869 name: "OffchainLookup",
1870 signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
1871 transaction: transaction,
1872 data: result
1873 });
1874 }
1875 tx = {
1876 to: txSender,
1877 data: (0, bytes_1.hexConcat)([callbackSelector, encodeBytes([ccipResult, extraData])])
1878 };
1879 return [2 /*return*/, this._call(tx, blockTag, attempt + 1)];
1880 case 4:
1881 error_8 = _a.sent();
1882 if (error_8.code === logger_1.Logger.errors.SERVER_ERROR) {
1883 throw error_8;
1884 }
1885 return [3 /*break*/, 5];
1886 case 5:
1887 try {
1888 return [2 /*return*/, (0, bytes_1.hexlify)(result)];
1889 }
1890 catch (error) {
1891 return [2 /*return*/, logger.throwError("bad result from backend", logger_1.Logger.errors.SERVER_ERROR, {
1892 method: "call",
1893 params: { transaction: transaction, blockTag: blockTag },
1894 result: result,
1895 error: error
1896 })];
1897 }
1898 return [2 /*return*/];
1899 }
1900 });
1901 });
1902 };
1903 BaseProvider.prototype.call = function (transaction, blockTag) {
1904 return __awaiter(this, void 0, void 0, function () {
1905 var resolved;
1906 return __generator(this, function (_a) {
1907 switch (_a.label) {
1908 case 0: return [4 /*yield*/, this.getNetwork()];
1909 case 1:
1910 _a.sent();
1911 return [4 /*yield*/, (0, properties_1.resolveProperties)({
1912 transaction: this._getTransactionRequest(transaction),
1913 blockTag: this._getBlockTag(blockTag),
1914 ccipReadEnabled: Promise.resolve(transaction.ccipReadEnabled)
1915 })];
1916 case 2:
1917 resolved = _a.sent();
1918 return [2 /*return*/, this._call(resolved.transaction, resolved.blockTag, resolved.ccipReadEnabled ? 0 : -1)];
1919 }
1920 });
1921 });
1922 };
1923 BaseProvider.prototype.estimateGas = function (transaction) {
1924 return __awaiter(this, void 0, void 0, function () {
1925 var params, result;
1926 return __generator(this, function (_a) {
1927 switch (_a.label) {
1928 case 0: return [4 /*yield*/, this.getNetwork()];
1929 case 1:
1930 _a.sent();
1931 return [4 /*yield*/, (0, properties_1.resolveProperties)({
1932 transaction: this._getTransactionRequest(transaction)
1933 })];
1934 case 2:
1935 params = _a.sent();
1936 return [4 /*yield*/, this.perform("estimateGas", params)];
1937 case 3:
1938 result = _a.sent();
1939 try {
1940 return [2 /*return*/, bignumber_1.BigNumber.from(result)];
1941 }
1942 catch (error) {
1943 return [2 /*return*/, logger.throwError("bad result from backend", logger_1.Logger.errors.SERVER_ERROR, {
1944 method: "estimateGas",
1945 params: params,
1946 result: result,
1947 error: error
1948 })];
1949 }
1950 return [2 /*return*/];
1951 }
1952 });
1953 });
1954 };
1955 BaseProvider.prototype._getAddress = function (addressOrName) {
1956 return __awaiter(this, void 0, void 0, function () {
1957 var address;
1958 return __generator(this, function (_a) {
1959 switch (_a.label) {
1960 case 0: return [4 /*yield*/, addressOrName];
1961 case 1:
1962 addressOrName = _a.sent();
1963 if (typeof (addressOrName) !== "string") {
1964 logger.throwArgumentError("invalid address or ENS name", "name", addressOrName);
1965 }
1966 return [4 /*yield*/, this.resolveName(addressOrName)];
1967 case 2:
1968 address = _a.sent();
1969 if (address == null) {
1970 logger.throwError("ENS name not configured", logger_1.Logger.errors.UNSUPPORTED_OPERATION, {
1971 operation: "resolveName(" + JSON.stringify(addressOrName) + ")"
1972 });
1973 }
1974 return [2 /*return*/, address];
1975 }
1976 });
1977 });
1978 };
1979 BaseProvider.prototype._getBlock = function (blockHashOrBlockTag, includeTransactions) {
1980 return __awaiter(this, void 0, void 0, function () {
1981 var blockNumber, params, _a, error_9;
1982 var _this = this;
1983 return __generator(this, function (_b) {
1984 switch (_b.label) {
1985 case 0: return [4 /*yield*/, this.getNetwork()];
1986 case 1:
1987 _b.sent();
1988 return [4 /*yield*/, blockHashOrBlockTag];
1989 case 2:
1990 blockHashOrBlockTag = _b.sent();
1991 blockNumber = -128;
1992 params = {
1993 includeTransactions: !!includeTransactions
1994 };
1995 if (!(0, bytes_1.isHexString)(blockHashOrBlockTag, 32)) return [3 /*break*/, 3];
1996 params.blockHash = blockHashOrBlockTag;
1997 return [3 /*break*/, 6];
1998 case 3:
1999 _b.trys.push([3, 5, , 6]);
2000 _a = params;
2001 return [4 /*yield*/, this._getBlockTag(blockHashOrBlockTag)];
2002 case 4:
2003 _a.blockTag = _b.sent();
2004 if ((0, bytes_1.isHexString)(params.blockTag)) {
2005 blockNumber = parseInt(params.blockTag.substring(2), 16);
2006 }
2007 return [3 /*break*/, 6];
2008 case 5:
2009 error_9 = _b.sent();
2010 logger.throwArgumentError("invalid block hash or block tag", "blockHashOrBlockTag", blockHashOrBlockTag);
2011 return [3 /*break*/, 6];
2012 case 6: return [2 /*return*/, (0, web_1.poll)(function () { return __awaiter(_this, void 0, void 0, function () {
2013 var block, blockNumber_1, i, tx, confirmations, blockWithTxs;
2014 var _this = this;
2015 return __generator(this, function (_a) {
2016 switch (_a.label) {
2017 case 0: return [4 /*yield*/, this.perform("getBlock", params)];
2018 case 1:
2019 block = _a.sent();
2020 // Block was not found
2021 if (block == null) {
2022 // For blockhashes, if we didn't say it existed, that blockhash may
2023 // not exist. If we did see it though, perhaps from a log, we know
2024 // it exists, and this node is just not caught up yet.
2025 if (params.blockHash != null) {
2026 if (this._emitted["b:" + params.blockHash] == null) {
2027 return [2 /*return*/, null];
2028 }
2029 }
2030 // For block tags, if we are asking for a future block, we return null
2031 if (params.blockTag != null) {
2032 if (blockNumber > this._emitted.block) {
2033 return [2 /*return*/, null];
2034 }
2035 }
2036 // Retry on the next block
2037 return [2 /*return*/, undefined];
2038 }
2039 if (!includeTransactions) return [3 /*break*/, 8];
2040 blockNumber_1 = null;
2041 i = 0;
2042 _a.label = 2;
2043 case 2:
2044 if (!(i < block.transactions.length)) return [3 /*break*/, 7];
2045 tx = block.transactions[i];
2046 if (!(tx.blockNumber == null)) return [3 /*break*/, 3];
2047 tx.confirmations = 0;
2048 return [3 /*break*/, 6];
2049 case 3:
2050 if (!(tx.confirmations == null)) return [3 /*break*/, 6];
2051 if (!(blockNumber_1 == null)) return [3 /*break*/, 5];
2052 return [4 /*yield*/, this._getInternalBlockNumber(100 + 2 * this.pollingInterval)];
2053 case 4:
2054 blockNumber_1 = _a.sent();
2055 _a.label = 5;
2056 case 5:
2057 confirmations = (blockNumber_1 - tx.blockNumber) + 1;
2058 if (confirmations <= 0) {
2059 confirmations = 1;
2060 }
2061 tx.confirmations = confirmations;
2062 _a.label = 6;
2063 case 6:
2064 i++;
2065 return [3 /*break*/, 2];
2066 case 7:
2067 blockWithTxs = this.formatter.blockWithTransactions(block);
2068 blockWithTxs.transactions = blockWithTxs.transactions.map(function (tx) { return _this._wrapTransaction(tx); });
2069 return [2 /*return*/, blockWithTxs];
2070 case 8: return [2 /*return*/, this.formatter.block(block)];
2071 }
2072 });
2073 }); }, { oncePoll: this })];
2074 }
2075 });
2076 });
2077 };
2078 BaseProvider.prototype.getBlock = function (blockHashOrBlockTag) {
2079 return (this._getBlock(blockHashOrBlockTag, false));
2080 };
2081 BaseProvider.prototype.getBlockWithTransactions = function (blockHashOrBlockTag) {
2082 return (this._getBlock(blockHashOrBlockTag, true));
2083 };
2084 BaseProvider.prototype.getTransaction = function (transactionHash) {
2085 return __awaiter(this, void 0, void 0, function () {
2086 var params;
2087 var _this = this;
2088 return __generator(this, function (_a) {
2089 switch (_a.label) {
2090 case 0: return [4 /*yield*/, this.getNetwork()];
2091 case 1:
2092 _a.sent();
2093 return [4 /*yield*/, transactionHash];
2094 case 2:
2095 transactionHash = _a.sent();
2096 params = { transactionHash: this.formatter.hash(transactionHash, true) };
2097 return [2 /*return*/, (0, web_1.poll)(function () { return __awaiter(_this, void 0, void 0, function () {
2098 var result, tx, blockNumber, confirmations;
2099 return __generator(this, function (_a) {
2100 switch (_a.label) {
2101 case 0: return [4 /*yield*/, this.perform("getTransaction", params)];
2102 case 1:
2103 result = _a.sent();
2104 if (result == null) {
2105 if (this._emitted["t:" + transactionHash] == null) {
2106 return [2 /*return*/, null];
2107 }
2108 return [2 /*return*/, undefined];
2109 }
2110 tx = this.formatter.transactionResponse(result);
2111 if (!(tx.blockNumber == null)) return [3 /*break*/, 2];
2112 tx.confirmations = 0;
2113 return [3 /*break*/, 4];
2114 case 2:
2115 if (!(tx.confirmations == null)) return [3 /*break*/, 4];
2116 return [4 /*yield*/, this._getInternalBlockNumber(100 + 2 * this.pollingInterval)];
2117 case 3:
2118 blockNumber = _a.sent();
2119 confirmations = (blockNumber - tx.blockNumber) + 1;
2120 if (confirmations <= 0) {
2121 confirmations = 1;
2122 }
2123 tx.confirmations = confirmations;
2124 _a.label = 4;
2125 case 4: return [2 /*return*/, this._wrapTransaction(tx)];
2126 }
2127 });
2128 }); }, { oncePoll: this })];
2129 }
2130 });
2131 });
2132 };
2133 BaseProvider.prototype.getTransactionReceipt = function (transactionHash) {
2134 return __awaiter(this, void 0, void 0, function () {
2135 var params;
2136 var _this = this;
2137 return __generator(this, function (_a) {
2138 switch (_a.label) {
2139 case 0: return [4 /*yield*/, this.getNetwork()];
2140 case 1:
2141 _a.sent();
2142 return [4 /*yield*/, transactionHash];
2143 case 2:
2144 transactionHash = _a.sent();
2145 params = { transactionHash: this.formatter.hash(transactionHash, true) };
2146 return [2 /*return*/, (0, web_1.poll)(function () { return __awaiter(_this, void 0, void 0, function () {
2147 var result, receipt, blockNumber, confirmations;
2148 return __generator(this, function (_a) {
2149 switch (_a.label) {
2150 case 0: return [4 /*yield*/, this.perform("getTransactionReceipt", params)];
2151 case 1:
2152 result = _a.sent();
2153 if (result == null) {
2154 if (this._emitted["t:" + transactionHash] == null) {
2155 return [2 /*return*/, null];
2156 }
2157 return [2 /*return*/, undefined];
2158 }
2159 // "geth-etc" returns receipts before they are ready
2160 if (result.blockHash == null) {
2161 return [2 /*return*/, undefined];
2162 }
2163 receipt = this.formatter.receipt(result);
2164 if (!(receipt.blockNumber == null)) return [3 /*break*/, 2];
2165 receipt.confirmations = 0;
2166 return [3 /*break*/, 4];
2167 case 2:
2168 if (!(receipt.confirmations == null)) return [3 /*break*/, 4];
2169 return [4 /*yield*/, this._getInternalBlockNumber(100 + 2 * this.pollingInterval)];
2170 case 3:
2171 blockNumber = _a.sent();
2172 confirmations = (blockNumber - receipt.blockNumber) + 1;
2173 if (confirmations <= 0) {
2174 confirmations = 1;
2175 }
2176 receipt.confirmations = confirmations;
2177 _a.label = 4;
2178 case 4: return [2 /*return*/, receipt];
2179 }
2180 });
2181 }); }, { oncePoll: this })];
2182 }
2183 });
2184 });
2185 };
2186 BaseProvider.prototype.getLogs = function (filter) {
2187 return __awaiter(this, void 0, void 0, function () {
2188 var params, logs;
2189 return __generator(this, function (_a) {
2190 switch (_a.label) {
2191 case 0: return [4 /*yield*/, this.getNetwork()];
2192 case 1:
2193 _a.sent();
2194 return [4 /*yield*/, (0, properties_1.resolveProperties)({ filter: this._getFilter(filter) })];
2195 case 2:
2196 params = _a.sent();
2197 return [4 /*yield*/, this.perform("getLogs", params)];
2198 case 3:
2199 logs = _a.sent();
2200 logs.forEach(function (log) {
2201 if (log.removed == null) {
2202 log.removed = false;
2203 }
2204 });
2205 return [2 /*return*/, formatter_1.Formatter.arrayOf(this.formatter.filterLog.bind(this.formatter))(logs)];
2206 }
2207 });
2208 });
2209 };
2210 BaseProvider.prototype.getEtherPrice = function () {
2211 return __awaiter(this, void 0, void 0, function () {
2212 return __generator(this, function (_a) {
2213 switch (_a.label) {
2214 case 0: return [4 /*yield*/, this.getNetwork()];
2215 case 1:
2216 _a.sent();
2217 return [2 /*return*/, this.perform("getEtherPrice", {})];
2218 }
2219 });
2220 });
2221 };
2222 BaseProvider.prototype._getBlockTag = function (blockTag) {
2223 return __awaiter(this, void 0, void 0, function () {
2224 var blockNumber;
2225 return __generator(this, function (_a) {
2226 switch (_a.label) {
2227 case 0: return [4 /*yield*/, blockTag];
2228 case 1:
2229 blockTag = _a.sent();
2230 if (!(typeof (blockTag) === "number" && blockTag < 0)) return [3 /*break*/, 3];
2231 if (blockTag % 1) {
2232 logger.throwArgumentError("invalid BlockTag", "blockTag", blockTag);
2233 }
2234 return [4 /*yield*/, this._getInternalBlockNumber(100 + 2 * this.pollingInterval)];
2235 case 2:
2236 blockNumber = _a.sent();
2237 blockNumber += blockTag;
2238 if (blockNumber < 0) {
2239 blockNumber = 0;
2240 }
2241 return [2 /*return*/, this.formatter.blockTag(blockNumber)];
2242 case 3: return [2 /*return*/, this.formatter.blockTag(blockTag)];
2243 }
2244 });
2245 });
2246 };
2247 BaseProvider.prototype.getResolver = function (name) {
2248 return __awaiter(this, void 0, void 0, function () {
2249 var currentName, addr, resolver, _a;
2250 return __generator(this, function (_b) {
2251 switch (_b.label) {
2252 case 0:
2253 currentName = name;
2254 _b.label = 1;
2255 case 1:
2256 if (!true) return [3 /*break*/, 6];
2257 if (currentName === "" || currentName === ".") {
2258 return [2 /*return*/, null];
2259 }
2260 // Optimization since the eth node cannot change and does
2261 // not have a wildcard resolver
2262 if (name !== "eth" && currentName === "eth") {
2263 return [2 /*return*/, null];
2264 }
2265 return [4 /*yield*/, this._getResolver(currentName, "getResolver")];
2266 case 2:
2267 addr = _b.sent();
2268 if (!(addr != null)) return [3 /*break*/, 5];
2269 resolver = new Resolver(this, addr, name);
2270 _a = currentName !== name;
2271 if (!_a) return [3 /*break*/, 4];
2272 return [4 /*yield*/, resolver.supportsWildcard()];
2273 case 3:
2274 _a = !(_b.sent());
2275 _b.label = 4;
2276 case 4:
2277 // Legacy resolver found, using EIP-2544 so it isn't safe to use
2278 if (_a) {
2279 return [2 /*return*/, null];
2280 }
2281 return [2 /*return*/, resolver];
2282 case 5:
2283 // Get the parent node
2284 currentName = currentName.split(".").slice(1).join(".");
2285 return [3 /*break*/, 1];
2286 case 6: return [2 /*return*/];
2287 }
2288 });
2289 });
2290 };
2291 BaseProvider.prototype._getResolver = function (name, operation) {
2292 return __awaiter(this, void 0, void 0, function () {
2293 var network, addrData, error_10;
2294 return __generator(this, function (_a) {
2295 switch (_a.label) {
2296 case 0:
2297 if (operation == null) {
2298 operation = "ENS";
2299 }
2300 return [4 /*yield*/, this.getNetwork()];
2301 case 1:
2302 network = _a.sent();
2303 // No ENS...
2304 if (!network.ensAddress) {
2305 logger.throwError("network does not support ENS", logger_1.Logger.errors.UNSUPPORTED_OPERATION, { operation: operation, network: network.name });
2306 }
2307 _a.label = 2;
2308 case 2:
2309 _a.trys.push([2, 4, , 5]);
2310 return [4 /*yield*/, this.call({
2311 to: network.ensAddress,
2312 data: ("0x0178b8bf" + (0, hash_1.namehash)(name).substring(2))
2313 })];
2314 case 3:
2315 addrData = _a.sent();
2316 return [2 /*return*/, this.formatter.callAddress(addrData)];
2317 case 4:
2318 error_10 = _a.sent();
2319 return [3 /*break*/, 5];
2320 case 5: return [2 /*return*/, null];
2321 }
2322 });
2323 });
2324 };
2325 BaseProvider.prototype.resolveName = function (name) {
2326 return __awaiter(this, void 0, void 0, function () {
2327 var resolver;
2328 return __generator(this, function (_a) {
2329 switch (_a.label) {
2330 case 0: return [4 /*yield*/, name];
2331 case 1:
2332 name = _a.sent();
2333 // If it is already an address, nothing to resolve
2334 try {
2335 return [2 /*return*/, Promise.resolve(this.formatter.address(name))];
2336 }
2337 catch (error) {
2338 // If is is a hexstring, the address is bad (See #694)
2339 if ((0, bytes_1.isHexString)(name)) {
2340 throw error;
2341 }
2342 }
2343 if (typeof (name) !== "string") {
2344 logger.throwArgumentError("invalid ENS name", "name", name);
2345 }
2346 return [4 /*yield*/, this.getResolver(name)];
2347 case 2:
2348 resolver = _a.sent();
2349 if (!resolver) {
2350 return [2 /*return*/, null];
2351 }
2352 return [4 /*yield*/, resolver.getAddress()];
2353 case 3: return [2 /*return*/, _a.sent()];
2354 }
2355 });
2356 });
2357 };
2358 BaseProvider.prototype.lookupAddress = function (address) {
2359 return __awaiter(this, void 0, void 0, function () {
2360 var node, resolverAddr, name, _a, addr;
2361 return __generator(this, function (_b) {
2362 switch (_b.label) {
2363 case 0: return [4 /*yield*/, address];
2364 case 1:
2365 address = _b.sent();
2366 address = this.formatter.address(address);
2367 node = address.substring(2).toLowerCase() + ".addr.reverse";
2368 return [4 /*yield*/, this._getResolver(node, "lookupAddress")];
2369 case 2:
2370 resolverAddr = _b.sent();
2371 if (resolverAddr == null) {
2372 return [2 /*return*/, null];
2373 }
2374 _a = _parseString;
2375 return [4 /*yield*/, this.call({
2376 to: resolverAddr,
2377 data: ("0x691f3431" + (0, hash_1.namehash)(node).substring(2))
2378 })];
2379 case 3:
2380 name = _a.apply(void 0, [_b.sent(), 0]);
2381 return [4 /*yield*/, this.resolveName(name)];
2382 case 4:
2383 addr = _b.sent();
2384 if (addr != address) {
2385 return [2 /*return*/, null];
2386 }
2387 return [2 /*return*/, name];
2388 }
2389 });
2390 });
2391 };
2392 BaseProvider.prototype.getAvatar = function (nameOrAddress) {
2393 return __awaiter(this, void 0, void 0, function () {
2394 var resolver, address, node, resolverAddress, avatar_1, error_11, name_1, _a, error_12, avatar;
2395 return __generator(this, function (_b) {
2396 switch (_b.label) {
2397 case 0:
2398 resolver = null;
2399 if (!(0, bytes_1.isHexString)(nameOrAddress)) return [3 /*break*/, 10];
2400 address = this.formatter.address(nameOrAddress);
2401 node = address.substring(2).toLowerCase() + ".addr.reverse";
2402 return [4 /*yield*/, this._getResolver(node, "getAvatar")];
2403 case 1:
2404 resolverAddress = _b.sent();
2405 if (!resolverAddress) {
2406 return [2 /*return*/, null];
2407 }
2408 // Try resolving the avatar against the addr.reverse resolver
2409 resolver = new Resolver(this, resolverAddress, node);
2410 _b.label = 2;
2411 case 2:
2412 _b.trys.push([2, 4, , 5]);
2413 return [4 /*yield*/, resolver.getAvatar()];
2414 case 3:
2415 avatar_1 = _b.sent();
2416 if (avatar_1) {
2417 return [2 /*return*/, avatar_1.url];
2418 }
2419 return [3 /*break*/, 5];
2420 case 4:
2421 error_11 = _b.sent();
2422 if (error_11.code !== logger_1.Logger.errors.CALL_EXCEPTION) {
2423 throw error_11;
2424 }
2425 return [3 /*break*/, 5];
2426 case 5:
2427 _b.trys.push([5, 8, , 9]);
2428 _a = _parseString;
2429 return [4 /*yield*/, this.call({
2430 to: resolverAddress,
2431 data: ("0x691f3431" + (0, hash_1.namehash)(node).substring(2))
2432 })];
2433 case 6:
2434 name_1 = _a.apply(void 0, [_b.sent(), 0]);
2435 return [4 /*yield*/, this.getResolver(name_1)];
2436 case 7:
2437 resolver = _b.sent();
2438 return [3 /*break*/, 9];
2439 case 8:
2440 error_12 = _b.sent();
2441 if (error_12.code !== logger_1.Logger.errors.CALL_EXCEPTION) {
2442 throw error_12;
2443 }
2444 return [2 /*return*/, null];
2445 case 9: return [3 /*break*/, 12];
2446 case 10: return [4 /*yield*/, this.getResolver(nameOrAddress)];
2447 case 11:
2448 // ENS name; forward lookup with wildcard
2449 resolver = _b.sent();
2450 if (!resolver) {
2451 return [2 /*return*/, null];
2452 }
2453 _b.label = 12;
2454 case 12: return [4 /*yield*/, resolver.getAvatar()];
2455 case 13:
2456 avatar = _b.sent();
2457 if (avatar == null) {
2458 return [2 /*return*/, null];
2459 }
2460 return [2 /*return*/, avatar.url];
2461 }
2462 });
2463 });
2464 };
2465 BaseProvider.prototype.perform = function (method, params) {
2466 return logger.throwError(method + " not implemented", logger_1.Logger.errors.NOT_IMPLEMENTED, { operation: method });
2467 };
2468 BaseProvider.prototype._startEvent = function (event) {
2469 this.polling = (this._events.filter(function (e) { return e.pollable(); }).length > 0);
2470 };
2471 BaseProvider.prototype._stopEvent = function (event) {
2472 this.polling = (this._events.filter(function (e) { return e.pollable(); }).length > 0);
2473 };
2474 BaseProvider.prototype._addEventListener = function (eventName, listener, once) {
2475 var event = new Event(getEventTag(eventName), listener, once);
2476 this._events.push(event);
2477 this._startEvent(event);
2478 return this;
2479 };
2480 BaseProvider.prototype.on = function (eventName, listener) {
2481 return this._addEventListener(eventName, listener, false);
2482 };
2483 BaseProvider.prototype.once = function (eventName, listener) {
2484 return this._addEventListener(eventName, listener, true);
2485 };
2486 BaseProvider.prototype.emit = function (eventName) {
2487 var _this = this;
2488 var args = [];
2489 for (var _i = 1; _i < arguments.length; _i++) {
2490 args[_i - 1] = arguments[_i];
2491 }
2492 var result = false;
2493 var stopped = [];
2494 var eventTag = getEventTag(eventName);
2495 this._events = this._events.filter(function (event) {
2496 if (event.tag !== eventTag) {
2497 return true;
2498 }
2499 setTimeout(function () {
2500 event.listener.apply(_this, args);
2501 }, 0);
2502 result = true;
2503 if (event.once) {
2504 stopped.push(event);
2505 return false;
2506 }
2507 return true;
2508 });
2509 stopped.forEach(function (event) { _this._stopEvent(event); });
2510 return result;
2511 };
2512 BaseProvider.prototype.listenerCount = function (eventName) {
2513 if (!eventName) {
2514 return this._events.length;
2515 }
2516 var eventTag = getEventTag(eventName);
2517 return this._events.filter(function (event) {
2518 return (event.tag === eventTag);
2519 }).length;
2520 };
2521 BaseProvider.prototype.listeners = function (eventName) {
2522 if (eventName == null) {
2523 return this._events.map(function (event) { return event.listener; });
2524 }
2525 var eventTag = getEventTag(eventName);
2526 return this._events
2527 .filter(function (event) { return (event.tag === eventTag); })
2528 .map(function (event) { return event.listener; });
2529 };
2530 BaseProvider.prototype.off = function (eventName, listener) {
2531 var _this = this;
2532 if (listener == null) {
2533 return this.removeAllListeners(eventName);
2534 }
2535 var stopped = [];
2536 var found = false;
2537 var eventTag = getEventTag(eventName);
2538 this._events = this._events.filter(function (event) {
2539 if (event.tag !== eventTag || event.listener != listener) {
2540 return true;
2541 }
2542 if (found) {
2543 return true;
2544 }
2545 found = true;
2546 stopped.push(event);
2547 return false;
2548 });
2549 stopped.forEach(function (event) { _this._stopEvent(event); });
2550 return this;
2551 };
2552 BaseProvider.prototype.removeAllListeners = function (eventName) {
2553 var _this = this;
2554 var stopped = [];
2555 if (eventName == null) {
2556 stopped = this._events;
2557 this._events = [];
2558 }
2559 else {
2560 var eventTag_1 = getEventTag(eventName);
2561 this._events = this._events.filter(function (event) {
2562 if (event.tag !== eventTag_1) {
2563 return true;
2564 }
2565 stopped.push(event);
2566 return false;
2567 });
2568 }
2569 stopped.forEach(function (event) { _this._stopEvent(event); });
2570 return this;
2571 };
2572 return BaseProvider;
2573}(abstract_provider_1.Provider));
2574exports.BaseProvider = BaseProvider;
2575//# sourceMappingURL=base-provider.js.map
\No newline at end of file