UNPKG

133 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 // This is the first filter for this event, so we want to
1085 // restrict events to events that happened no earlier than now
1086 if (event._lastBlockNumber === -2) {
1087 event._lastBlockNumber = blockNumber - 1;
1088 }
1089 // Filter from the last *known* event; due to load-balancing
1090 // and some nodes returning updated block numbers before
1091 // indexing events, a logs result with 0 entries cannot be
1092 // trusted and we must retry a range which includes it again
1093 var filter_1 = event.filter;
1094 filter_1.fromBlock = event._lastBlockNumber + 1;
1095 filter_1.toBlock = blockNumber;
1096 // Prevent fitler ranges from growing too wild, since it is quite
1097 // likely there just haven't been any events to move the lastBlockNumber.
1098 var minFromBlock = filter_1.toBlock - _this._maxFilterBlockRange;
1099 if (minFromBlock > filter_1.fromBlock) {
1100 filter_1.fromBlock = minFromBlock;
1101 }
1102 if (filter_1.fromBlock < 0) {
1103 filter_1.fromBlock = 0;
1104 }
1105 var runner = _this.getLogs(filter_1).then(function (logs) {
1106 // Allow the next getLogs
1107 event._inflight = false;
1108 if (logs.length === 0) {
1109 return;
1110 }
1111 logs.forEach(function (log) {
1112 // Only when we get an event for a given block number
1113 // can we trust the events are indexed
1114 if (log.blockNumber > event._lastBlockNumber) {
1115 event._lastBlockNumber = log.blockNumber;
1116 }
1117 // Make sure we stall requests to fetch blocks and txs
1118 _this._emitted["b:" + log.blockHash] = log.blockNumber;
1119 _this._emitted["t:" + log.transactionHash] = log.blockNumber;
1120 _this.emit(filter_1, log);
1121 });
1122 }).catch(function (error) {
1123 _this.emit("error", error);
1124 // Allow another getLogs (the range was not updated)
1125 event._inflight = false;
1126 });
1127 runners.push(runner);
1128 }
1129 break;
1130 }
1131 }
1132 });
1133 this._lastBlockNumber = blockNumber;
1134 // Once all events for this loop have been processed, emit "didPoll"
1135 Promise.all(runners).then(function () {
1136 _this.emit("didPoll", pollId);
1137 }).catch(function (error) { _this.emit("error", error); });
1138 return [2 /*return*/];
1139 }
1140 });
1141 });
1142 };
1143 // Deprecated; do not use this
1144 BaseProvider.prototype.resetEventsBlock = function (blockNumber) {
1145 this._lastBlockNumber = blockNumber - 1;
1146 if (this.polling) {
1147 this.poll();
1148 }
1149 };
1150 Object.defineProperty(BaseProvider.prototype, "network", {
1151 get: function () {
1152 return this._network;
1153 },
1154 enumerable: false,
1155 configurable: true
1156 });
1157 // This method should query the network if the underlying network
1158 // can change, such as when connected to a JSON-RPC backend
1159 BaseProvider.prototype.detectNetwork = function () {
1160 return __awaiter(this, void 0, void 0, function () {
1161 return __generator(this, function (_a) {
1162 return [2 /*return*/, logger.throwError("provider does not support network detection", logger_1.Logger.errors.UNSUPPORTED_OPERATION, {
1163 operation: "provider.detectNetwork"
1164 })];
1165 });
1166 });
1167 };
1168 BaseProvider.prototype.getNetwork = function () {
1169 return __awaiter(this, void 0, void 0, function () {
1170 var network, currentNetwork, error;
1171 return __generator(this, function (_a) {
1172 switch (_a.label) {
1173 case 0: return [4 /*yield*/, this._ready()];
1174 case 1:
1175 network = _a.sent();
1176 return [4 /*yield*/, this.detectNetwork()];
1177 case 2:
1178 currentNetwork = _a.sent();
1179 if (!(network.chainId !== currentNetwork.chainId)) return [3 /*break*/, 5];
1180 if (!this.anyNetwork) return [3 /*break*/, 4];
1181 this._network = currentNetwork;
1182 // Reset all internal block number guards and caches
1183 this._lastBlockNumber = -2;
1184 this._fastBlockNumber = null;
1185 this._fastBlockNumberPromise = null;
1186 this._fastQueryDate = 0;
1187 this._emitted.block = -2;
1188 this._maxInternalBlockNumber = -1024;
1189 this._internalBlockNumber = null;
1190 // The "network" event MUST happen before this method resolves
1191 // so any events have a chance to unregister, so we stall an
1192 // additional event loop before returning from /this/ call
1193 this.emit("network", currentNetwork, network);
1194 return [4 /*yield*/, stall(0)];
1195 case 3:
1196 _a.sent();
1197 return [2 /*return*/, this._network];
1198 case 4:
1199 error = logger.makeError("underlying network changed", logger_1.Logger.errors.NETWORK_ERROR, {
1200 event: "changed",
1201 network: network,
1202 detectedNetwork: currentNetwork
1203 });
1204 this.emit("error", error);
1205 throw error;
1206 case 5: return [2 /*return*/, network];
1207 }
1208 });
1209 });
1210 };
1211 Object.defineProperty(BaseProvider.prototype, "blockNumber", {
1212 get: function () {
1213 var _this = this;
1214 this._getInternalBlockNumber(100 + this.pollingInterval / 2).then(function (blockNumber) {
1215 _this._setFastBlockNumber(blockNumber);
1216 }, function (error) { });
1217 return (this._fastBlockNumber != null) ? this._fastBlockNumber : -1;
1218 },
1219 enumerable: false,
1220 configurable: true
1221 });
1222 Object.defineProperty(BaseProvider.prototype, "polling", {
1223 get: function () {
1224 return (this._poller != null);
1225 },
1226 set: function (value) {
1227 var _this = this;
1228 if (value && !this._poller) {
1229 this._poller = setInterval(function () { _this.poll(); }, this.pollingInterval);
1230 if (!this._bootstrapPoll) {
1231 this._bootstrapPoll = setTimeout(function () {
1232 _this.poll();
1233 // We block additional polls until the polling interval
1234 // is done, to prevent overwhelming the poll function
1235 _this._bootstrapPoll = setTimeout(function () {
1236 // If polling was disabled, something may require a poke
1237 // since starting the bootstrap poll and it was disabled
1238 if (!_this._poller) {
1239 _this.poll();
1240 }
1241 // Clear out the bootstrap so we can do another
1242 _this._bootstrapPoll = null;
1243 }, _this.pollingInterval);
1244 }, 0);
1245 }
1246 }
1247 else if (!value && this._poller) {
1248 clearInterval(this._poller);
1249 this._poller = null;
1250 }
1251 },
1252 enumerable: false,
1253 configurable: true
1254 });
1255 Object.defineProperty(BaseProvider.prototype, "pollingInterval", {
1256 get: function () {
1257 return this._pollingInterval;
1258 },
1259 set: function (value) {
1260 var _this = this;
1261 if (typeof (value) !== "number" || value <= 0 || parseInt(String(value)) != value) {
1262 throw new Error("invalid polling interval");
1263 }
1264 this._pollingInterval = value;
1265 if (this._poller) {
1266 clearInterval(this._poller);
1267 this._poller = setInterval(function () { _this.poll(); }, this._pollingInterval);
1268 }
1269 },
1270 enumerable: false,
1271 configurable: true
1272 });
1273 BaseProvider.prototype._getFastBlockNumber = function () {
1274 var _this = this;
1275 var now = getTime();
1276 // Stale block number, request a newer value
1277 if ((now - this._fastQueryDate) > 2 * this._pollingInterval) {
1278 this._fastQueryDate = now;
1279 this._fastBlockNumberPromise = this.getBlockNumber().then(function (blockNumber) {
1280 if (_this._fastBlockNumber == null || blockNumber > _this._fastBlockNumber) {
1281 _this._fastBlockNumber = blockNumber;
1282 }
1283 return _this._fastBlockNumber;
1284 });
1285 }
1286 return this._fastBlockNumberPromise;
1287 };
1288 BaseProvider.prototype._setFastBlockNumber = function (blockNumber) {
1289 // Older block, maybe a stale request
1290 if (this._fastBlockNumber != null && blockNumber < this._fastBlockNumber) {
1291 return;
1292 }
1293 // Update the time we updated the blocknumber
1294 this._fastQueryDate = getTime();
1295 // Newer block number, use it
1296 if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) {
1297 this._fastBlockNumber = blockNumber;
1298 this._fastBlockNumberPromise = Promise.resolve(blockNumber);
1299 }
1300 };
1301 BaseProvider.prototype.waitForTransaction = function (transactionHash, confirmations, timeout) {
1302 return __awaiter(this, void 0, void 0, function () {
1303 return __generator(this, function (_a) {
1304 return [2 /*return*/, this._waitForTransaction(transactionHash, (confirmations == null) ? 1 : confirmations, timeout || 0, null)];
1305 });
1306 });
1307 };
1308 BaseProvider.prototype._waitForTransaction = function (transactionHash, confirmations, timeout, replaceable) {
1309 return __awaiter(this, void 0, void 0, function () {
1310 var receipt;
1311 var _this = this;
1312 return __generator(this, function (_a) {
1313 switch (_a.label) {
1314 case 0: return [4 /*yield*/, this.getTransactionReceipt(transactionHash)];
1315 case 1:
1316 receipt = _a.sent();
1317 // Receipt is already good
1318 if ((receipt ? receipt.confirmations : 0) >= confirmations) {
1319 return [2 /*return*/, receipt];
1320 }
1321 // Poll until the receipt is good...
1322 return [2 /*return*/, new Promise(function (resolve, reject) {
1323 var cancelFuncs = [];
1324 var done = false;
1325 var alreadyDone = function () {
1326 if (done) {
1327 return true;
1328 }
1329 done = true;
1330 cancelFuncs.forEach(function (func) { func(); });
1331 return false;
1332 };
1333 var minedHandler = function (receipt) {
1334 if (receipt.confirmations < confirmations) {
1335 return;
1336 }
1337 if (alreadyDone()) {
1338 return;
1339 }
1340 resolve(receipt);
1341 };
1342 _this.on(transactionHash, minedHandler);
1343 cancelFuncs.push(function () { _this.removeListener(transactionHash, minedHandler); });
1344 if (replaceable) {
1345 var lastBlockNumber_1 = replaceable.startBlock;
1346 var scannedBlock_1 = null;
1347 var replaceHandler_1 = function (blockNumber) { return __awaiter(_this, void 0, void 0, function () {
1348 var _this = this;
1349 return __generator(this, function (_a) {
1350 switch (_a.label) {
1351 case 0:
1352 if (done) {
1353 return [2 /*return*/];
1354 }
1355 // Wait 1 second; this is only used in the case of a fault, so
1356 // we will trade off a little bit of latency for more consistent
1357 // results and fewer JSON-RPC calls
1358 return [4 /*yield*/, stall(1000)];
1359 case 1:
1360 // Wait 1 second; this is only used in the case of a fault, so
1361 // we will trade off a little bit of latency for more consistent
1362 // results and fewer JSON-RPC calls
1363 _a.sent();
1364 this.getTransactionCount(replaceable.from).then(function (nonce) { return __awaiter(_this, void 0, void 0, function () {
1365 var mined, block, ti, tx, receipt_1, reason;
1366 return __generator(this, function (_a) {
1367 switch (_a.label) {
1368 case 0:
1369 if (done) {
1370 return [2 /*return*/];
1371 }
1372 if (!(nonce <= replaceable.nonce)) return [3 /*break*/, 1];
1373 lastBlockNumber_1 = blockNumber;
1374 return [3 /*break*/, 9];
1375 case 1: return [4 /*yield*/, this.getTransaction(transactionHash)];
1376 case 2:
1377 mined = _a.sent();
1378 if (mined && mined.blockNumber != null) {
1379 return [2 /*return*/];
1380 }
1381 // First time scanning. We start a little earlier for some
1382 // wiggle room here to handle the eventually consistent nature
1383 // of blockchain (e.g. the getTransactionCount was for a
1384 // different block)
1385 if (scannedBlock_1 == null) {
1386 scannedBlock_1 = lastBlockNumber_1 - 3;
1387 if (scannedBlock_1 < replaceable.startBlock) {
1388 scannedBlock_1 = replaceable.startBlock;
1389 }
1390 }
1391 _a.label = 3;
1392 case 3:
1393 if (!(scannedBlock_1 <= blockNumber)) return [3 /*break*/, 9];
1394 if (done) {
1395 return [2 /*return*/];
1396 }
1397 return [4 /*yield*/, this.getBlockWithTransactions(scannedBlock_1)];
1398 case 4:
1399 block = _a.sent();
1400 ti = 0;
1401 _a.label = 5;
1402 case 5:
1403 if (!(ti < block.transactions.length)) return [3 /*break*/, 8];
1404 tx = block.transactions[ti];
1405 // Successfully mined!
1406 if (tx.hash === transactionHash) {
1407 return [2 /*return*/];
1408 }
1409 if (!(tx.from === replaceable.from && tx.nonce === replaceable.nonce)) return [3 /*break*/, 7];
1410 if (done) {
1411 return [2 /*return*/];
1412 }
1413 return [4 /*yield*/, this.waitForTransaction(tx.hash, confirmations)];
1414 case 6:
1415 receipt_1 = _a.sent();
1416 // Already resolved or rejected (prolly a timeout)
1417 if (alreadyDone()) {
1418 return [2 /*return*/];
1419 }
1420 reason = "replaced";
1421 if (tx.data === replaceable.data && tx.to === replaceable.to && tx.value.eq(replaceable.value)) {
1422 reason = "repriced";
1423 }
1424 else if (tx.data === "0x" && tx.from === tx.to && tx.value.isZero()) {
1425 reason = "cancelled";
1426 }
1427 // Explain why we were replaced
1428 reject(logger.makeError("transaction was replaced", logger_1.Logger.errors.TRANSACTION_REPLACED, {
1429 cancelled: (reason === "replaced" || reason === "cancelled"),
1430 reason: reason,
1431 replacement: this._wrapTransaction(tx),
1432 hash: transactionHash,
1433 receipt: receipt_1
1434 }));
1435 return [2 /*return*/];
1436 case 7:
1437 ti++;
1438 return [3 /*break*/, 5];
1439 case 8:
1440 scannedBlock_1++;
1441 return [3 /*break*/, 3];
1442 case 9:
1443 if (done) {
1444 return [2 /*return*/];
1445 }
1446 this.once("block", replaceHandler_1);
1447 return [2 /*return*/];
1448 }
1449 });
1450 }); }, function (error) {
1451 if (done) {
1452 return;
1453 }
1454 _this.once("block", replaceHandler_1);
1455 });
1456 return [2 /*return*/];
1457 }
1458 });
1459 }); };
1460 if (done) {
1461 return;
1462 }
1463 _this.once("block", replaceHandler_1);
1464 cancelFuncs.push(function () {
1465 _this.removeListener("block", replaceHandler_1);
1466 });
1467 }
1468 if (typeof (timeout) === "number" && timeout > 0) {
1469 var timer_1 = setTimeout(function () {
1470 if (alreadyDone()) {
1471 return;
1472 }
1473 reject(logger.makeError("timeout exceeded", logger_1.Logger.errors.TIMEOUT, { timeout: timeout }));
1474 }, timeout);
1475 if (timer_1.unref) {
1476 timer_1.unref();
1477 }
1478 cancelFuncs.push(function () { clearTimeout(timer_1); });
1479 }
1480 })];
1481 }
1482 });
1483 });
1484 };
1485 BaseProvider.prototype.getBlockNumber = function () {
1486 return __awaiter(this, void 0, void 0, function () {
1487 return __generator(this, function (_a) {
1488 return [2 /*return*/, this._getInternalBlockNumber(0)];
1489 });
1490 });
1491 };
1492 BaseProvider.prototype.getGasPrice = function () {
1493 return __awaiter(this, void 0, void 0, function () {
1494 var result;
1495 return __generator(this, function (_a) {
1496 switch (_a.label) {
1497 case 0: return [4 /*yield*/, this.getNetwork()];
1498 case 1:
1499 _a.sent();
1500 return [4 /*yield*/, this.perform("getGasPrice", {})];
1501 case 2:
1502 result = _a.sent();
1503 try {
1504 return [2 /*return*/, bignumber_1.BigNumber.from(result)];
1505 }
1506 catch (error) {
1507 return [2 /*return*/, logger.throwError("bad result from backend", logger_1.Logger.errors.SERVER_ERROR, {
1508 method: "getGasPrice",
1509 result: result,
1510 error: error
1511 })];
1512 }
1513 return [2 /*return*/];
1514 }
1515 });
1516 });
1517 };
1518 BaseProvider.prototype.getBalance = function (addressOrName, blockTag) {
1519 return __awaiter(this, void 0, void 0, function () {
1520 var params, result;
1521 return __generator(this, function (_a) {
1522 switch (_a.label) {
1523 case 0: return [4 /*yield*/, this.getNetwork()];
1524 case 1:
1525 _a.sent();
1526 return [4 /*yield*/, (0, properties_1.resolveProperties)({
1527 address: this._getAddress(addressOrName),
1528 blockTag: this._getBlockTag(blockTag)
1529 })];
1530 case 2:
1531 params = _a.sent();
1532 return [4 /*yield*/, this.perform("getBalance", params)];
1533 case 3:
1534 result = _a.sent();
1535 try {
1536 return [2 /*return*/, bignumber_1.BigNumber.from(result)];
1537 }
1538 catch (error) {
1539 return [2 /*return*/, logger.throwError("bad result from backend", logger_1.Logger.errors.SERVER_ERROR, {
1540 method: "getBalance",
1541 params: params,
1542 result: result,
1543 error: error
1544 })];
1545 }
1546 return [2 /*return*/];
1547 }
1548 });
1549 });
1550 };
1551 BaseProvider.prototype.getTransactionCount = function (addressOrName, blockTag) {
1552 return __awaiter(this, void 0, void 0, function () {
1553 var params, result;
1554 return __generator(this, function (_a) {
1555 switch (_a.label) {
1556 case 0: return [4 /*yield*/, this.getNetwork()];
1557 case 1:
1558 _a.sent();
1559 return [4 /*yield*/, (0, properties_1.resolveProperties)({
1560 address: this._getAddress(addressOrName),
1561 blockTag: this._getBlockTag(blockTag)
1562 })];
1563 case 2:
1564 params = _a.sent();
1565 return [4 /*yield*/, this.perform("getTransactionCount", params)];
1566 case 3:
1567 result = _a.sent();
1568 try {
1569 return [2 /*return*/, bignumber_1.BigNumber.from(result).toNumber()];
1570 }
1571 catch (error) {
1572 return [2 /*return*/, logger.throwError("bad result from backend", logger_1.Logger.errors.SERVER_ERROR, {
1573 method: "getTransactionCount",
1574 params: params,
1575 result: result,
1576 error: error
1577 })];
1578 }
1579 return [2 /*return*/];
1580 }
1581 });
1582 });
1583 };
1584 BaseProvider.prototype.getCode = function (addressOrName, blockTag) {
1585 return __awaiter(this, void 0, void 0, function () {
1586 var params, result;
1587 return __generator(this, function (_a) {
1588 switch (_a.label) {
1589 case 0: return [4 /*yield*/, this.getNetwork()];
1590 case 1:
1591 _a.sent();
1592 return [4 /*yield*/, (0, properties_1.resolveProperties)({
1593 address: this._getAddress(addressOrName),
1594 blockTag: this._getBlockTag(blockTag)
1595 })];
1596 case 2:
1597 params = _a.sent();
1598 return [4 /*yield*/, this.perform("getCode", params)];
1599 case 3:
1600 result = _a.sent();
1601 try {
1602 return [2 /*return*/, (0, bytes_1.hexlify)(result)];
1603 }
1604 catch (error) {
1605 return [2 /*return*/, logger.throwError("bad result from backend", logger_1.Logger.errors.SERVER_ERROR, {
1606 method: "getCode",
1607 params: params,
1608 result: result,
1609 error: error
1610 })];
1611 }
1612 return [2 /*return*/];
1613 }
1614 });
1615 });
1616 };
1617 BaseProvider.prototype.getStorageAt = function (addressOrName, position, blockTag) {
1618 return __awaiter(this, void 0, void 0, function () {
1619 var params, result;
1620 return __generator(this, function (_a) {
1621 switch (_a.label) {
1622 case 0: return [4 /*yield*/, this.getNetwork()];
1623 case 1:
1624 _a.sent();
1625 return [4 /*yield*/, (0, properties_1.resolveProperties)({
1626 address: this._getAddress(addressOrName),
1627 blockTag: this._getBlockTag(blockTag),
1628 position: Promise.resolve(position).then(function (p) { return (0, bytes_1.hexValue)(p); })
1629 })];
1630 case 2:
1631 params = _a.sent();
1632 return [4 /*yield*/, this.perform("getStorageAt", params)];
1633 case 3:
1634 result = _a.sent();
1635 try {
1636 return [2 /*return*/, (0, bytes_1.hexlify)(result)];
1637 }
1638 catch (error) {
1639 return [2 /*return*/, logger.throwError("bad result from backend", logger_1.Logger.errors.SERVER_ERROR, {
1640 method: "getStorageAt",
1641 params: params,
1642 result: result,
1643 error: error
1644 })];
1645 }
1646 return [2 /*return*/];
1647 }
1648 });
1649 });
1650 };
1651 // This should be called by any subclass wrapping a TransactionResponse
1652 BaseProvider.prototype._wrapTransaction = function (tx, hash, startBlock) {
1653 var _this = this;
1654 if (hash != null && (0, bytes_1.hexDataLength)(hash) !== 32) {
1655 throw new Error("invalid response - sendTransaction");
1656 }
1657 var result = tx;
1658 // Check the hash we expect is the same as the hash the server reported
1659 if (hash != null && tx.hash !== hash) {
1660 logger.throwError("Transaction hash mismatch from Provider.sendTransaction.", logger_1.Logger.errors.UNKNOWN_ERROR, { expectedHash: tx.hash, returnedHash: hash });
1661 }
1662 result.wait = function (confirms, timeout) { return __awaiter(_this, void 0, void 0, function () {
1663 var replacement, receipt;
1664 return __generator(this, function (_a) {
1665 switch (_a.label) {
1666 case 0:
1667 if (confirms == null) {
1668 confirms = 1;
1669 }
1670 if (timeout == null) {
1671 timeout = 0;
1672 }
1673 replacement = undefined;
1674 if (confirms !== 0 && startBlock != null) {
1675 replacement = {
1676 data: tx.data,
1677 from: tx.from,
1678 nonce: tx.nonce,
1679 to: tx.to,
1680 value: tx.value,
1681 startBlock: startBlock
1682 };
1683 }
1684 return [4 /*yield*/, this._waitForTransaction(tx.hash, confirms, timeout, replacement)];
1685 case 1:
1686 receipt = _a.sent();
1687 if (receipt == null && confirms === 0) {
1688 return [2 /*return*/, null];
1689 }
1690 // No longer pending, allow the polling loop to garbage collect this
1691 this._emitted["t:" + tx.hash] = receipt.blockNumber;
1692 if (receipt.status === 0) {
1693 logger.throwError("transaction failed", logger_1.Logger.errors.CALL_EXCEPTION, {
1694 transactionHash: tx.hash,
1695 transaction: tx,
1696 receipt: receipt
1697 });
1698 }
1699 return [2 /*return*/, receipt];
1700 }
1701 });
1702 }); };
1703 return result;
1704 };
1705 BaseProvider.prototype.sendTransaction = function (signedTransaction) {
1706 return __awaiter(this, void 0, void 0, function () {
1707 var hexTx, tx, blockNumber, hash, error_7;
1708 return __generator(this, function (_a) {
1709 switch (_a.label) {
1710 case 0: return [4 /*yield*/, this.getNetwork()];
1711 case 1:
1712 _a.sent();
1713 return [4 /*yield*/, Promise.resolve(signedTransaction).then(function (t) { return (0, bytes_1.hexlify)(t); })];
1714 case 2:
1715 hexTx = _a.sent();
1716 tx = this.formatter.transaction(signedTransaction);
1717 if (tx.confirmations == null) {
1718 tx.confirmations = 0;
1719 }
1720 return [4 /*yield*/, this._getInternalBlockNumber(100 + 2 * this.pollingInterval)];
1721 case 3:
1722 blockNumber = _a.sent();
1723 _a.label = 4;
1724 case 4:
1725 _a.trys.push([4, 6, , 7]);
1726 return [4 /*yield*/, this.perform("sendTransaction", { signedTransaction: hexTx })];
1727 case 5:
1728 hash = _a.sent();
1729 return [2 /*return*/, this._wrapTransaction(tx, hash, blockNumber)];
1730 case 6:
1731 error_7 = _a.sent();
1732 error_7.transaction = tx;
1733 error_7.transactionHash = tx.hash;
1734 throw error_7;
1735 case 7: return [2 /*return*/];
1736 }
1737 });
1738 });
1739 };
1740 BaseProvider.prototype._getTransactionRequest = function (transaction) {
1741 return __awaiter(this, void 0, void 0, function () {
1742 var values, tx, _a, _b;
1743 var _this = this;
1744 return __generator(this, function (_c) {
1745 switch (_c.label) {
1746 case 0: return [4 /*yield*/, transaction];
1747 case 1:
1748 values = _c.sent();
1749 tx = {};
1750 ["from", "to"].forEach(function (key) {
1751 if (values[key] == null) {
1752 return;
1753 }
1754 tx[key] = Promise.resolve(values[key]).then(function (v) { return (v ? _this._getAddress(v) : null); });
1755 });
1756 ["gasLimit", "gasPrice", "maxFeePerGas", "maxPriorityFeePerGas", "value"].forEach(function (key) {
1757 if (values[key] == null) {
1758 return;
1759 }
1760 tx[key] = Promise.resolve(values[key]).then(function (v) { return (v ? bignumber_1.BigNumber.from(v) : null); });
1761 });
1762 ["type"].forEach(function (key) {
1763 if (values[key] == null) {
1764 return;
1765 }
1766 tx[key] = Promise.resolve(values[key]).then(function (v) { return ((v != null) ? v : null); });
1767 });
1768 if (values.accessList) {
1769 tx.accessList = this.formatter.accessList(values.accessList);
1770 }
1771 ["data"].forEach(function (key) {
1772 if (values[key] == null) {
1773 return;
1774 }
1775 tx[key] = Promise.resolve(values[key]).then(function (v) { return (v ? (0, bytes_1.hexlify)(v) : null); });
1776 });
1777 _b = (_a = this.formatter).transactionRequest;
1778 return [4 /*yield*/, (0, properties_1.resolveProperties)(tx)];
1779 case 2: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
1780 }
1781 });
1782 });
1783 };
1784 BaseProvider.prototype._getFilter = function (filter) {
1785 return __awaiter(this, void 0, void 0, function () {
1786 var result, _a, _b;
1787 var _this = this;
1788 return __generator(this, function (_c) {
1789 switch (_c.label) {
1790 case 0: return [4 /*yield*/, filter];
1791 case 1:
1792 filter = _c.sent();
1793 result = {};
1794 if (filter.address != null) {
1795 result.address = this._getAddress(filter.address);
1796 }
1797 ["blockHash", "topics"].forEach(function (key) {
1798 if (filter[key] == null) {
1799 return;
1800 }
1801 result[key] = filter[key];
1802 });
1803 ["fromBlock", "toBlock"].forEach(function (key) {
1804 if (filter[key] == null) {
1805 return;
1806 }
1807 result[key] = _this._getBlockTag(filter[key]);
1808 });
1809 _b = (_a = this.formatter).filter;
1810 return [4 /*yield*/, (0, properties_1.resolveProperties)(result)];
1811 case 2: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
1812 }
1813 });
1814 });
1815 };
1816 BaseProvider.prototype._call = function (transaction, blockTag, attempt) {
1817 return __awaiter(this, void 0, void 0, function () {
1818 var txSender, result, data, sender, urls, urlsOffset, urlsLength, urlsData, u, url, calldata, callbackSelector, extraData, ccipResult, tx, error_8;
1819 return __generator(this, function (_a) {
1820 switch (_a.label) {
1821 case 0:
1822 if (attempt >= MAX_CCIP_REDIRECTS) {
1823 logger.throwError("CCIP read exceeded maximum redirections", logger_1.Logger.errors.SERVER_ERROR, {
1824 redirects: attempt,
1825 transaction: transaction
1826 });
1827 }
1828 txSender = transaction.to;
1829 return [4 /*yield*/, this.perform("call", { transaction: transaction, blockTag: blockTag })];
1830 case 1:
1831 result = _a.sent();
1832 if (!(attempt >= 0 && blockTag === "latest" && txSender != null && result.substring(0, 10) === "0x556f1830" && ((0, bytes_1.hexDataLength)(result) % 32 === 4))) return [3 /*break*/, 5];
1833 _a.label = 2;
1834 case 2:
1835 _a.trys.push([2, 4, , 5]);
1836 data = (0, bytes_1.hexDataSlice)(result, 4);
1837 sender = (0, bytes_1.hexDataSlice)(data, 0, 32);
1838 if (!bignumber_1.BigNumber.from(sender).eq(txSender)) {
1839 logger.throwError("CCIP Read sender did not match", logger_1.Logger.errors.CALL_EXCEPTION, {
1840 name: "OffchainLookup",
1841 signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
1842 transaction: transaction,
1843 data: result
1844 });
1845 }
1846 urls = [];
1847 urlsOffset = bignumber_1.BigNumber.from((0, bytes_1.hexDataSlice)(data, 32, 64)).toNumber();
1848 urlsLength = bignumber_1.BigNumber.from((0, bytes_1.hexDataSlice)(data, urlsOffset, urlsOffset + 32)).toNumber();
1849 urlsData = (0, bytes_1.hexDataSlice)(data, urlsOffset + 32);
1850 for (u = 0; u < urlsLength; u++) {
1851 url = _parseString(urlsData, u * 32);
1852 if (url == null) {
1853 logger.throwError("CCIP Read contained corrupt URL string", logger_1.Logger.errors.CALL_EXCEPTION, {
1854 name: "OffchainLookup",
1855 signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
1856 transaction: transaction,
1857 data: result
1858 });
1859 }
1860 urls.push(url);
1861 }
1862 calldata = _parseBytes(data, 64);
1863 // Get the callbackSelector (bytes4)
1864 if (!bignumber_1.BigNumber.from((0, bytes_1.hexDataSlice)(data, 100, 128)).isZero()) {
1865 logger.throwError("CCIP Read callback selector included junk", logger_1.Logger.errors.CALL_EXCEPTION, {
1866 name: "OffchainLookup",
1867 signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
1868 transaction: transaction,
1869 data: result
1870 });
1871 }
1872 callbackSelector = (0, bytes_1.hexDataSlice)(data, 96, 100);
1873 extraData = _parseBytes(data, 128);
1874 return [4 /*yield*/, this.ccipReadFetch(transaction, calldata, urls)];
1875 case 3:
1876 ccipResult = _a.sent();
1877 if (ccipResult == null) {
1878 logger.throwError("CCIP Read disabled or provided no URLs", logger_1.Logger.errors.CALL_EXCEPTION, {
1879 name: "OffchainLookup",
1880 signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
1881 transaction: transaction,
1882 data: result
1883 });
1884 }
1885 tx = {
1886 to: txSender,
1887 data: (0, bytes_1.hexConcat)([callbackSelector, encodeBytes([ccipResult, extraData])])
1888 };
1889 return [2 /*return*/, this._call(tx, blockTag, attempt + 1)];
1890 case 4:
1891 error_8 = _a.sent();
1892 if (error_8.code === logger_1.Logger.errors.SERVER_ERROR) {
1893 throw error_8;
1894 }
1895 return [3 /*break*/, 5];
1896 case 5:
1897 try {
1898 return [2 /*return*/, (0, bytes_1.hexlify)(result)];
1899 }
1900 catch (error) {
1901 return [2 /*return*/, logger.throwError("bad result from backend", logger_1.Logger.errors.SERVER_ERROR, {
1902 method: "call",
1903 params: { transaction: transaction, blockTag: blockTag },
1904 result: result,
1905 error: error
1906 })];
1907 }
1908 return [2 /*return*/];
1909 }
1910 });
1911 });
1912 };
1913 BaseProvider.prototype.call = function (transaction, blockTag) {
1914 return __awaiter(this, void 0, void 0, function () {
1915 var resolved;
1916 return __generator(this, function (_a) {
1917 switch (_a.label) {
1918 case 0: return [4 /*yield*/, this.getNetwork()];
1919 case 1:
1920 _a.sent();
1921 return [4 /*yield*/, (0, properties_1.resolveProperties)({
1922 transaction: this._getTransactionRequest(transaction),
1923 blockTag: this._getBlockTag(blockTag),
1924 ccipReadEnabled: Promise.resolve(transaction.ccipReadEnabled)
1925 })];
1926 case 2:
1927 resolved = _a.sent();
1928 return [2 /*return*/, this._call(resolved.transaction, resolved.blockTag, resolved.ccipReadEnabled ? 0 : -1)];
1929 }
1930 });
1931 });
1932 };
1933 BaseProvider.prototype.estimateGas = function (transaction) {
1934 return __awaiter(this, void 0, void 0, function () {
1935 var params, result;
1936 return __generator(this, function (_a) {
1937 switch (_a.label) {
1938 case 0: return [4 /*yield*/, this.getNetwork()];
1939 case 1:
1940 _a.sent();
1941 return [4 /*yield*/, (0, properties_1.resolveProperties)({
1942 transaction: this._getTransactionRequest(transaction)
1943 })];
1944 case 2:
1945 params = _a.sent();
1946 return [4 /*yield*/, this.perform("estimateGas", params)];
1947 case 3:
1948 result = _a.sent();
1949 try {
1950 return [2 /*return*/, bignumber_1.BigNumber.from(result)];
1951 }
1952 catch (error) {
1953 return [2 /*return*/, logger.throwError("bad result from backend", logger_1.Logger.errors.SERVER_ERROR, {
1954 method: "estimateGas",
1955 params: params,
1956 result: result,
1957 error: error
1958 })];
1959 }
1960 return [2 /*return*/];
1961 }
1962 });
1963 });
1964 };
1965 BaseProvider.prototype._getAddress = function (addressOrName) {
1966 return __awaiter(this, void 0, void 0, function () {
1967 var address;
1968 return __generator(this, function (_a) {
1969 switch (_a.label) {
1970 case 0: return [4 /*yield*/, addressOrName];
1971 case 1:
1972 addressOrName = _a.sent();
1973 if (typeof (addressOrName) !== "string") {
1974 logger.throwArgumentError("invalid address or ENS name", "name", addressOrName);
1975 }
1976 return [4 /*yield*/, this.resolveName(addressOrName)];
1977 case 2:
1978 address = _a.sent();
1979 if (address == null) {
1980 logger.throwError("ENS name not configured", logger_1.Logger.errors.UNSUPPORTED_OPERATION, {
1981 operation: "resolveName(" + JSON.stringify(addressOrName) + ")"
1982 });
1983 }
1984 return [2 /*return*/, address];
1985 }
1986 });
1987 });
1988 };
1989 BaseProvider.prototype._getBlock = function (blockHashOrBlockTag, includeTransactions) {
1990 return __awaiter(this, void 0, void 0, function () {
1991 var blockNumber, params, _a, error_9;
1992 var _this = this;
1993 return __generator(this, function (_b) {
1994 switch (_b.label) {
1995 case 0: return [4 /*yield*/, this.getNetwork()];
1996 case 1:
1997 _b.sent();
1998 return [4 /*yield*/, blockHashOrBlockTag];
1999 case 2:
2000 blockHashOrBlockTag = _b.sent();
2001 blockNumber = -128;
2002 params = {
2003 includeTransactions: !!includeTransactions
2004 };
2005 if (!(0, bytes_1.isHexString)(blockHashOrBlockTag, 32)) return [3 /*break*/, 3];
2006 params.blockHash = blockHashOrBlockTag;
2007 return [3 /*break*/, 6];
2008 case 3:
2009 _b.trys.push([3, 5, , 6]);
2010 _a = params;
2011 return [4 /*yield*/, this._getBlockTag(blockHashOrBlockTag)];
2012 case 4:
2013 _a.blockTag = _b.sent();
2014 if ((0, bytes_1.isHexString)(params.blockTag)) {
2015 blockNumber = parseInt(params.blockTag.substring(2), 16);
2016 }
2017 return [3 /*break*/, 6];
2018 case 5:
2019 error_9 = _b.sent();
2020 logger.throwArgumentError("invalid block hash or block tag", "blockHashOrBlockTag", blockHashOrBlockTag);
2021 return [3 /*break*/, 6];
2022 case 6: return [2 /*return*/, (0, web_1.poll)(function () { return __awaiter(_this, void 0, void 0, function () {
2023 var block, blockNumber_1, i, tx, confirmations, blockWithTxs;
2024 var _this = this;
2025 return __generator(this, function (_a) {
2026 switch (_a.label) {
2027 case 0: return [4 /*yield*/, this.perform("getBlock", params)];
2028 case 1:
2029 block = _a.sent();
2030 // Block was not found
2031 if (block == null) {
2032 // For blockhashes, if we didn't say it existed, that blockhash may
2033 // not exist. If we did see it though, perhaps from a log, we know
2034 // it exists, and this node is just not caught up yet.
2035 if (params.blockHash != null) {
2036 if (this._emitted["b:" + params.blockHash] == null) {
2037 return [2 /*return*/, null];
2038 }
2039 }
2040 // For block tags, if we are asking for a future block, we return null
2041 if (params.blockTag != null) {
2042 if (blockNumber > this._emitted.block) {
2043 return [2 /*return*/, null];
2044 }
2045 }
2046 // Retry on the next block
2047 return [2 /*return*/, undefined];
2048 }
2049 if (!includeTransactions) return [3 /*break*/, 8];
2050 blockNumber_1 = null;
2051 i = 0;
2052 _a.label = 2;
2053 case 2:
2054 if (!(i < block.transactions.length)) return [3 /*break*/, 7];
2055 tx = block.transactions[i];
2056 if (!(tx.blockNumber == null)) return [3 /*break*/, 3];
2057 tx.confirmations = 0;
2058 return [3 /*break*/, 6];
2059 case 3:
2060 if (!(tx.confirmations == null)) return [3 /*break*/, 6];
2061 if (!(blockNumber_1 == null)) return [3 /*break*/, 5];
2062 return [4 /*yield*/, this._getInternalBlockNumber(100 + 2 * this.pollingInterval)];
2063 case 4:
2064 blockNumber_1 = _a.sent();
2065 _a.label = 5;
2066 case 5:
2067 confirmations = (blockNumber_1 - tx.blockNumber) + 1;
2068 if (confirmations <= 0) {
2069 confirmations = 1;
2070 }
2071 tx.confirmations = confirmations;
2072 _a.label = 6;
2073 case 6:
2074 i++;
2075 return [3 /*break*/, 2];
2076 case 7:
2077 blockWithTxs = this.formatter.blockWithTransactions(block);
2078 blockWithTxs.transactions = blockWithTxs.transactions.map(function (tx) { return _this._wrapTransaction(tx); });
2079 return [2 /*return*/, blockWithTxs];
2080 case 8: return [2 /*return*/, this.formatter.block(block)];
2081 }
2082 });
2083 }); }, { oncePoll: this })];
2084 }
2085 });
2086 });
2087 };
2088 BaseProvider.prototype.getBlock = function (blockHashOrBlockTag) {
2089 return (this._getBlock(blockHashOrBlockTag, false));
2090 };
2091 BaseProvider.prototype.getBlockWithTransactions = function (blockHashOrBlockTag) {
2092 return (this._getBlock(blockHashOrBlockTag, true));
2093 };
2094 BaseProvider.prototype.getTransaction = function (transactionHash) {
2095 return __awaiter(this, void 0, void 0, function () {
2096 var params;
2097 var _this = this;
2098 return __generator(this, function (_a) {
2099 switch (_a.label) {
2100 case 0: return [4 /*yield*/, this.getNetwork()];
2101 case 1:
2102 _a.sent();
2103 return [4 /*yield*/, transactionHash];
2104 case 2:
2105 transactionHash = _a.sent();
2106 params = { transactionHash: this.formatter.hash(transactionHash, true) };
2107 return [2 /*return*/, (0, web_1.poll)(function () { return __awaiter(_this, void 0, void 0, function () {
2108 var result, tx, blockNumber, confirmations;
2109 return __generator(this, function (_a) {
2110 switch (_a.label) {
2111 case 0: return [4 /*yield*/, this.perform("getTransaction", params)];
2112 case 1:
2113 result = _a.sent();
2114 if (result == null) {
2115 if (this._emitted["t:" + transactionHash] == null) {
2116 return [2 /*return*/, null];
2117 }
2118 return [2 /*return*/, undefined];
2119 }
2120 tx = this.formatter.transactionResponse(result);
2121 if (!(tx.blockNumber == null)) return [3 /*break*/, 2];
2122 tx.confirmations = 0;
2123 return [3 /*break*/, 4];
2124 case 2:
2125 if (!(tx.confirmations == null)) return [3 /*break*/, 4];
2126 return [4 /*yield*/, this._getInternalBlockNumber(100 + 2 * this.pollingInterval)];
2127 case 3:
2128 blockNumber = _a.sent();
2129 confirmations = (blockNumber - tx.blockNumber) + 1;
2130 if (confirmations <= 0) {
2131 confirmations = 1;
2132 }
2133 tx.confirmations = confirmations;
2134 _a.label = 4;
2135 case 4: return [2 /*return*/, this._wrapTransaction(tx)];
2136 }
2137 });
2138 }); }, { oncePoll: this })];
2139 }
2140 });
2141 });
2142 };
2143 BaseProvider.prototype.getTransactionReceipt = function (transactionHash) {
2144 return __awaiter(this, void 0, void 0, function () {
2145 var params;
2146 var _this = this;
2147 return __generator(this, function (_a) {
2148 switch (_a.label) {
2149 case 0: return [4 /*yield*/, this.getNetwork()];
2150 case 1:
2151 _a.sent();
2152 return [4 /*yield*/, transactionHash];
2153 case 2:
2154 transactionHash = _a.sent();
2155 params = { transactionHash: this.formatter.hash(transactionHash, true) };
2156 return [2 /*return*/, (0, web_1.poll)(function () { return __awaiter(_this, void 0, void 0, function () {
2157 var result, receipt, blockNumber, confirmations;
2158 return __generator(this, function (_a) {
2159 switch (_a.label) {
2160 case 0: return [4 /*yield*/, this.perform("getTransactionReceipt", params)];
2161 case 1:
2162 result = _a.sent();
2163 if (result == null) {
2164 if (this._emitted["t:" + transactionHash] == null) {
2165 return [2 /*return*/, null];
2166 }
2167 return [2 /*return*/, undefined];
2168 }
2169 // "geth-etc" returns receipts before they are ready
2170 if (result.blockHash == null) {
2171 return [2 /*return*/, undefined];
2172 }
2173 receipt = this.formatter.receipt(result);
2174 if (!(receipt.blockNumber == null)) return [3 /*break*/, 2];
2175 receipt.confirmations = 0;
2176 return [3 /*break*/, 4];
2177 case 2:
2178 if (!(receipt.confirmations == null)) return [3 /*break*/, 4];
2179 return [4 /*yield*/, this._getInternalBlockNumber(100 + 2 * this.pollingInterval)];
2180 case 3:
2181 blockNumber = _a.sent();
2182 confirmations = (blockNumber - receipt.blockNumber) + 1;
2183 if (confirmations <= 0) {
2184 confirmations = 1;
2185 }
2186 receipt.confirmations = confirmations;
2187 _a.label = 4;
2188 case 4: return [2 /*return*/, receipt];
2189 }
2190 });
2191 }); }, { oncePoll: this })];
2192 }
2193 });
2194 });
2195 };
2196 BaseProvider.prototype.getLogs = function (filter) {
2197 return __awaiter(this, void 0, void 0, function () {
2198 var params, logs;
2199 return __generator(this, function (_a) {
2200 switch (_a.label) {
2201 case 0: return [4 /*yield*/, this.getNetwork()];
2202 case 1:
2203 _a.sent();
2204 return [4 /*yield*/, (0, properties_1.resolveProperties)({ filter: this._getFilter(filter) })];
2205 case 2:
2206 params = _a.sent();
2207 return [4 /*yield*/, this.perform("getLogs", params)];
2208 case 3:
2209 logs = _a.sent();
2210 logs.forEach(function (log) {
2211 if (log.removed == null) {
2212 log.removed = false;
2213 }
2214 });
2215 return [2 /*return*/, formatter_1.Formatter.arrayOf(this.formatter.filterLog.bind(this.formatter))(logs)];
2216 }
2217 });
2218 });
2219 };
2220 BaseProvider.prototype.getEtherPrice = function () {
2221 return __awaiter(this, void 0, void 0, function () {
2222 return __generator(this, function (_a) {
2223 switch (_a.label) {
2224 case 0: return [4 /*yield*/, this.getNetwork()];
2225 case 1:
2226 _a.sent();
2227 return [2 /*return*/, this.perform("getEtherPrice", {})];
2228 }
2229 });
2230 });
2231 };
2232 BaseProvider.prototype._getBlockTag = function (blockTag) {
2233 return __awaiter(this, void 0, void 0, function () {
2234 var blockNumber;
2235 return __generator(this, function (_a) {
2236 switch (_a.label) {
2237 case 0: return [4 /*yield*/, blockTag];
2238 case 1:
2239 blockTag = _a.sent();
2240 if (!(typeof (blockTag) === "number" && blockTag < 0)) return [3 /*break*/, 3];
2241 if (blockTag % 1) {
2242 logger.throwArgumentError("invalid BlockTag", "blockTag", blockTag);
2243 }
2244 return [4 /*yield*/, this._getInternalBlockNumber(100 + 2 * this.pollingInterval)];
2245 case 2:
2246 blockNumber = _a.sent();
2247 blockNumber += blockTag;
2248 if (blockNumber < 0) {
2249 blockNumber = 0;
2250 }
2251 return [2 /*return*/, this.formatter.blockTag(blockNumber)];
2252 case 3: return [2 /*return*/, this.formatter.blockTag(blockTag)];
2253 }
2254 });
2255 });
2256 };
2257 BaseProvider.prototype.getResolver = function (name) {
2258 return __awaiter(this, void 0, void 0, function () {
2259 var currentName, addr, resolver, _a;
2260 return __generator(this, function (_b) {
2261 switch (_b.label) {
2262 case 0:
2263 currentName = name;
2264 _b.label = 1;
2265 case 1:
2266 if (!true) return [3 /*break*/, 6];
2267 if (currentName === "" || currentName === ".") {
2268 return [2 /*return*/, null];
2269 }
2270 // Optimization since the eth node cannot change and does
2271 // not have a wildcard resolver
2272 if (name !== "eth" && currentName === "eth") {
2273 return [2 /*return*/, null];
2274 }
2275 return [4 /*yield*/, this._getResolver(currentName, "getResolver")];
2276 case 2:
2277 addr = _b.sent();
2278 if (!(addr != null)) return [3 /*break*/, 5];
2279 resolver = new Resolver(this, addr, name);
2280 _a = currentName !== name;
2281 if (!_a) return [3 /*break*/, 4];
2282 return [4 /*yield*/, resolver.supportsWildcard()];
2283 case 3:
2284 _a = !(_b.sent());
2285 _b.label = 4;
2286 case 4:
2287 // Legacy resolver found, using EIP-2544 so it isn't safe to use
2288 if (_a) {
2289 return [2 /*return*/, null];
2290 }
2291 return [2 /*return*/, resolver];
2292 case 5:
2293 // Get the parent node
2294 currentName = currentName.split(".").slice(1).join(".");
2295 return [3 /*break*/, 1];
2296 case 6: return [2 /*return*/];
2297 }
2298 });
2299 });
2300 };
2301 BaseProvider.prototype._getResolver = function (name, operation) {
2302 return __awaiter(this, void 0, void 0, function () {
2303 var network, addrData, error_10;
2304 return __generator(this, function (_a) {
2305 switch (_a.label) {
2306 case 0:
2307 if (operation == null) {
2308 operation = "ENS";
2309 }
2310 return [4 /*yield*/, this.getNetwork()];
2311 case 1:
2312 network = _a.sent();
2313 // No ENS...
2314 if (!network.ensAddress) {
2315 logger.throwError("network does not support ENS", logger_1.Logger.errors.UNSUPPORTED_OPERATION, { operation: operation, network: network.name });
2316 }
2317 _a.label = 2;
2318 case 2:
2319 _a.trys.push([2, 4, , 5]);
2320 return [4 /*yield*/, this.call({
2321 to: network.ensAddress,
2322 data: ("0x0178b8bf" + (0, hash_1.namehash)(name).substring(2))
2323 })];
2324 case 3:
2325 addrData = _a.sent();
2326 return [2 /*return*/, this.formatter.callAddress(addrData)];
2327 case 4:
2328 error_10 = _a.sent();
2329 return [3 /*break*/, 5];
2330 case 5: return [2 /*return*/, null];
2331 }
2332 });
2333 });
2334 };
2335 BaseProvider.prototype.resolveName = function (name) {
2336 return __awaiter(this, void 0, void 0, function () {
2337 var resolver;
2338 return __generator(this, function (_a) {
2339 switch (_a.label) {
2340 case 0: return [4 /*yield*/, name];
2341 case 1:
2342 name = _a.sent();
2343 // If it is already an address, nothing to resolve
2344 try {
2345 return [2 /*return*/, Promise.resolve(this.formatter.address(name))];
2346 }
2347 catch (error) {
2348 // If is is a hexstring, the address is bad (See #694)
2349 if ((0, bytes_1.isHexString)(name)) {
2350 throw error;
2351 }
2352 }
2353 if (typeof (name) !== "string") {
2354 logger.throwArgumentError("invalid ENS name", "name", name);
2355 }
2356 return [4 /*yield*/, this.getResolver(name)];
2357 case 2:
2358 resolver = _a.sent();
2359 if (!resolver) {
2360 return [2 /*return*/, null];
2361 }
2362 return [4 /*yield*/, resolver.getAddress()];
2363 case 3: return [2 /*return*/, _a.sent()];
2364 }
2365 });
2366 });
2367 };
2368 BaseProvider.prototype.lookupAddress = function (address) {
2369 return __awaiter(this, void 0, void 0, function () {
2370 var node, resolverAddr, name, _a, addr;
2371 return __generator(this, function (_b) {
2372 switch (_b.label) {
2373 case 0: return [4 /*yield*/, address];
2374 case 1:
2375 address = _b.sent();
2376 address = this.formatter.address(address);
2377 node = address.substring(2).toLowerCase() + ".addr.reverse";
2378 return [4 /*yield*/, this._getResolver(node, "lookupAddress")];
2379 case 2:
2380 resolverAddr = _b.sent();
2381 if (resolverAddr == null) {
2382 return [2 /*return*/, null];
2383 }
2384 _a = _parseString;
2385 return [4 /*yield*/, this.call({
2386 to: resolverAddr,
2387 data: ("0x691f3431" + (0, hash_1.namehash)(node).substring(2))
2388 })];
2389 case 3:
2390 name = _a.apply(void 0, [_b.sent(), 0]);
2391 return [4 /*yield*/, this.resolveName(name)];
2392 case 4:
2393 addr = _b.sent();
2394 if (addr != address) {
2395 return [2 /*return*/, null];
2396 }
2397 return [2 /*return*/, name];
2398 }
2399 });
2400 });
2401 };
2402 BaseProvider.prototype.getAvatar = function (nameOrAddress) {
2403 return __awaiter(this, void 0, void 0, function () {
2404 var resolver, address, node, resolverAddress, avatar_1, error_11, name_1, _a, error_12, avatar;
2405 return __generator(this, function (_b) {
2406 switch (_b.label) {
2407 case 0:
2408 resolver = null;
2409 if (!(0, bytes_1.isHexString)(nameOrAddress)) return [3 /*break*/, 10];
2410 address = this.formatter.address(nameOrAddress);
2411 node = address.substring(2).toLowerCase() + ".addr.reverse";
2412 return [4 /*yield*/, this._getResolver(node, "getAvatar")];
2413 case 1:
2414 resolverAddress = _b.sent();
2415 if (!resolverAddress) {
2416 return [2 /*return*/, null];
2417 }
2418 // Try resolving the avatar against the addr.reverse resolver
2419 resolver = new Resolver(this, resolverAddress, node);
2420 _b.label = 2;
2421 case 2:
2422 _b.trys.push([2, 4, , 5]);
2423 return [4 /*yield*/, resolver.getAvatar()];
2424 case 3:
2425 avatar_1 = _b.sent();
2426 if (avatar_1) {
2427 return [2 /*return*/, avatar_1.url];
2428 }
2429 return [3 /*break*/, 5];
2430 case 4:
2431 error_11 = _b.sent();
2432 if (error_11.code !== logger_1.Logger.errors.CALL_EXCEPTION) {
2433 throw error_11;
2434 }
2435 return [3 /*break*/, 5];
2436 case 5:
2437 _b.trys.push([5, 8, , 9]);
2438 _a = _parseString;
2439 return [4 /*yield*/, this.call({
2440 to: resolverAddress,
2441 data: ("0x691f3431" + (0, hash_1.namehash)(node).substring(2))
2442 })];
2443 case 6:
2444 name_1 = _a.apply(void 0, [_b.sent(), 0]);
2445 return [4 /*yield*/, this.getResolver(name_1)];
2446 case 7:
2447 resolver = _b.sent();
2448 return [3 /*break*/, 9];
2449 case 8:
2450 error_12 = _b.sent();
2451 if (error_12.code !== logger_1.Logger.errors.CALL_EXCEPTION) {
2452 throw error_12;
2453 }
2454 return [2 /*return*/, null];
2455 case 9: return [3 /*break*/, 12];
2456 case 10: return [4 /*yield*/, this.getResolver(nameOrAddress)];
2457 case 11:
2458 // ENS name; forward lookup with wildcard
2459 resolver = _b.sent();
2460 if (!resolver) {
2461 return [2 /*return*/, null];
2462 }
2463 _b.label = 12;
2464 case 12: return [4 /*yield*/, resolver.getAvatar()];
2465 case 13:
2466 avatar = _b.sent();
2467 if (avatar == null) {
2468 return [2 /*return*/, null];
2469 }
2470 return [2 /*return*/, avatar.url];
2471 }
2472 });
2473 });
2474 };
2475 BaseProvider.prototype.perform = function (method, params) {
2476 return logger.throwError(method + " not implemented", logger_1.Logger.errors.NOT_IMPLEMENTED, { operation: method });
2477 };
2478 BaseProvider.prototype._startEvent = function (event) {
2479 this.polling = (this._events.filter(function (e) { return e.pollable(); }).length > 0);
2480 };
2481 BaseProvider.prototype._stopEvent = function (event) {
2482 this.polling = (this._events.filter(function (e) { return e.pollable(); }).length > 0);
2483 };
2484 BaseProvider.prototype._addEventListener = function (eventName, listener, once) {
2485 var event = new Event(getEventTag(eventName), listener, once);
2486 this._events.push(event);
2487 this._startEvent(event);
2488 return this;
2489 };
2490 BaseProvider.prototype.on = function (eventName, listener) {
2491 return this._addEventListener(eventName, listener, false);
2492 };
2493 BaseProvider.prototype.once = function (eventName, listener) {
2494 return this._addEventListener(eventName, listener, true);
2495 };
2496 BaseProvider.prototype.emit = function (eventName) {
2497 var _this = this;
2498 var args = [];
2499 for (var _i = 1; _i < arguments.length; _i++) {
2500 args[_i - 1] = arguments[_i];
2501 }
2502 var result = false;
2503 var stopped = [];
2504 var eventTag = getEventTag(eventName);
2505 this._events = this._events.filter(function (event) {
2506 if (event.tag !== eventTag) {
2507 return true;
2508 }
2509 setTimeout(function () {
2510 event.listener.apply(_this, args);
2511 }, 0);
2512 result = true;
2513 if (event.once) {
2514 stopped.push(event);
2515 return false;
2516 }
2517 return true;
2518 });
2519 stopped.forEach(function (event) { _this._stopEvent(event); });
2520 return result;
2521 };
2522 BaseProvider.prototype.listenerCount = function (eventName) {
2523 if (!eventName) {
2524 return this._events.length;
2525 }
2526 var eventTag = getEventTag(eventName);
2527 return this._events.filter(function (event) {
2528 return (event.tag === eventTag);
2529 }).length;
2530 };
2531 BaseProvider.prototype.listeners = function (eventName) {
2532 if (eventName == null) {
2533 return this._events.map(function (event) { return event.listener; });
2534 }
2535 var eventTag = getEventTag(eventName);
2536 return this._events
2537 .filter(function (event) { return (event.tag === eventTag); })
2538 .map(function (event) { return event.listener; });
2539 };
2540 BaseProvider.prototype.off = function (eventName, listener) {
2541 var _this = this;
2542 if (listener == null) {
2543 return this.removeAllListeners(eventName);
2544 }
2545 var stopped = [];
2546 var found = false;
2547 var eventTag = getEventTag(eventName);
2548 this._events = this._events.filter(function (event) {
2549 if (event.tag !== eventTag || event.listener != listener) {
2550 return true;
2551 }
2552 if (found) {
2553 return true;
2554 }
2555 found = true;
2556 stopped.push(event);
2557 return false;
2558 });
2559 stopped.forEach(function (event) { _this._stopEvent(event); });
2560 return this;
2561 };
2562 BaseProvider.prototype.removeAllListeners = function (eventName) {
2563 var _this = this;
2564 var stopped = [];
2565 if (eventName == null) {
2566 stopped = this._events;
2567 this._events = [];
2568 }
2569 else {
2570 var eventTag_1 = getEventTag(eventName);
2571 this._events = this._events.filter(function (event) {
2572 if (event.tag !== eventTag_1) {
2573 return true;
2574 }
2575 stopped.push(event);
2576 return false;
2577 });
2578 }
2579 stopped.forEach(function (event) { _this._stopEvent(event); });
2580 return this;
2581 };
2582 return BaseProvider;
2583}(abstract_provider_1.Provider));
2584exports.BaseProvider = BaseProvider;
2585//# sourceMappingURL=base-provider.js.map
\No newline at end of file