1 | "use strict";
|
2 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
3 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
4 | return new (P || (P = Promise))(function (resolve, reject) {
|
5 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
6 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
7 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
8 | step((generator = generator.apply(thisArg, _arguments || [])).next());
|
9 | });
|
10 | };
|
11 | import { ForkEvent, Provider } from "@ethersproject/abstract-provider";
|
12 | import { encode as base64Encode } from "@ethersproject/base64";
|
13 | import { Base58 } from "@ethersproject/basex";
|
14 | import { BigNumber } from "@ethersproject/bignumber";
|
15 | import { arrayify, concat, hexConcat, hexDataLength, hexDataSlice, hexlify, hexValue, hexZeroPad, isHexString } from "@ethersproject/bytes";
|
16 | import { HashZero } from "@ethersproject/constants";
|
17 | import { dnsEncode, namehash } from "@ethersproject/hash";
|
18 | import { getNetwork } from "@ethersproject/networks";
|
19 | import { defineReadOnly, getStatic, resolveProperties } from "@ethersproject/properties";
|
20 | import { sha256 } from "@ethersproject/sha2";
|
21 | import { toUtf8Bytes, toUtf8String } from "@ethersproject/strings";
|
22 | import { fetchJson, poll } from "@ethersproject/web";
|
23 | import bech32 from "bech32";
|
24 | import { Logger } from "@ethersproject/logger";
|
25 | import { version } from "./_version";
|
26 | const logger = new Logger(version);
|
27 | import { Formatter } from "./formatter";
|
28 | const MAX_CCIP_REDIRECTS = 10;
|
29 |
|
30 |
|
31 | function checkTopic(topic) {
|
32 | if (topic == null) {
|
33 | return "null";
|
34 | }
|
35 | if (hexDataLength(topic) !== 32) {
|
36 | logger.throwArgumentError("invalid topic", "topic", topic);
|
37 | }
|
38 | return topic.toLowerCase();
|
39 | }
|
40 | function serializeTopics(topics) {
|
41 |
|
42 | topics = topics.slice();
|
43 | while (topics.length > 0 && topics[topics.length - 1] == null) {
|
44 | topics.pop();
|
45 | }
|
46 | return topics.map((topic) => {
|
47 | if (Array.isArray(topic)) {
|
48 |
|
49 | const unique = {};
|
50 | topic.forEach((topic) => {
|
51 | unique[checkTopic(topic)] = true;
|
52 | });
|
53 |
|
54 | const sorted = Object.keys(unique);
|
55 | sorted.sort();
|
56 | return sorted.join("|");
|
57 | }
|
58 | else {
|
59 | return checkTopic(topic);
|
60 | }
|
61 | }).join("&");
|
62 | }
|
63 | function deserializeTopics(data) {
|
64 | if (data === "") {
|
65 | return [];
|
66 | }
|
67 | return data.split(/&/g).map((topic) => {
|
68 | if (topic === "") {
|
69 | return [];
|
70 | }
|
71 | const comps = topic.split("|").map((topic) => {
|
72 | return ((topic === "null") ? null : topic);
|
73 | });
|
74 | return ((comps.length === 1) ? comps[0] : comps);
|
75 | });
|
76 | }
|
77 | function getEventTag(eventName) {
|
78 | if (typeof (eventName) === "string") {
|
79 | eventName = eventName.toLowerCase();
|
80 | if (hexDataLength(eventName) === 32) {
|
81 | return "tx:" + eventName;
|
82 | }
|
83 | if (eventName.indexOf(":") === -1) {
|
84 | return eventName;
|
85 | }
|
86 | }
|
87 | else if (Array.isArray(eventName)) {
|
88 | return "filter:*:" + serializeTopics(eventName);
|
89 | }
|
90 | else if (ForkEvent.isForkEvent(eventName)) {
|
91 | logger.warn("not implemented");
|
92 | throw new Error("not implemented");
|
93 | }
|
94 | else if (eventName && typeof (eventName) === "object") {
|
95 | return "filter:" + (eventName.address || "*") + ":" + serializeTopics(eventName.topics || []);
|
96 | }
|
97 | throw new Error("invalid event - " + eventName);
|
98 | }
|
99 |
|
100 |
|
101 | function getTime() {
|
102 | return (new Date()).getTime();
|
103 | }
|
104 | function stall(duration) {
|
105 | return new Promise((resolve) => {
|
106 | setTimeout(resolve, duration);
|
107 | });
|
108 | }
|
109 |
|
110 |
|
111 |
|
112 |
|
113 |
|
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 |
|
120 |
|
121 |
|
122 |
|
123 | const PollableEvents = ["block", "network", "pending", "poll"];
|
124 | export class Event {
|
125 | constructor(tag, listener, once) {
|
126 | defineReadOnly(this, "tag", tag);
|
127 | defineReadOnly(this, "listener", listener);
|
128 | defineReadOnly(this, "once", once);
|
129 | this._lastBlockNumber = -2;
|
130 | this._inflight = false;
|
131 | }
|
132 | get event() {
|
133 | switch (this.type) {
|
134 | case "tx":
|
135 | return this.hash;
|
136 | case "filter":
|
137 | return this.filter;
|
138 | }
|
139 | return this.tag;
|
140 | }
|
141 | get type() {
|
142 | return this.tag.split(":")[0];
|
143 | }
|
144 | get hash() {
|
145 | const comps = this.tag.split(":");
|
146 | if (comps[0] !== "tx") {
|
147 | return null;
|
148 | }
|
149 | return comps[1];
|
150 | }
|
151 | get filter() {
|
152 | const comps = this.tag.split(":");
|
153 | if (comps[0] !== "filter") {
|
154 | return null;
|
155 | }
|
156 | const address = comps[1];
|
157 | const topics = deserializeTopics(comps[2]);
|
158 | const filter = {};
|
159 | if (topics.length > 0) {
|
160 | filter.topics = topics;
|
161 | }
|
162 | if (address && address !== "*") {
|
163 | filter.address = address;
|
164 | }
|
165 | return filter;
|
166 | }
|
167 | pollable() {
|
168 | return (this.tag.indexOf(":") >= 0 || PollableEvents.indexOf(this.tag) >= 0);
|
169 | }
|
170 | }
|
171 | ;
|
172 |
|
173 | const coinInfos = {
|
174 | "0": { symbol: "btc", p2pkh: 0x00, p2sh: 0x05, prefix: "bc" },
|
175 | "2": { symbol: "ltc", p2pkh: 0x30, p2sh: 0x32, prefix: "ltc" },
|
176 | "3": { symbol: "doge", p2pkh: 0x1e, p2sh: 0x16 },
|
177 | "60": { symbol: "eth", ilk: "eth" },
|
178 | "61": { symbol: "etc", ilk: "eth" },
|
179 | "700": { symbol: "xdai", ilk: "eth" },
|
180 | };
|
181 | function bytes32ify(value) {
|
182 | return hexZeroPad(BigNumber.from(value).toHexString(), 32);
|
183 | }
|
184 |
|
185 | function base58Encode(data) {
|
186 | return Base58.encode(concat([data, hexDataSlice(sha256(sha256(data)), 0, 4)]));
|
187 | }
|
188 | const matcherIpfs = new RegExp("^(ipfs):/\/(.*)$", "i");
|
189 | const matchers = [
|
190 | new RegExp("^(https):/\/(.*)$", "i"),
|
191 | new RegExp("^(data):(.*)$", "i"),
|
192 | matcherIpfs,
|
193 | new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i"),
|
194 | ];
|
195 | function _parseString(result, start) {
|
196 | try {
|
197 | return toUtf8String(_parseBytes(result, start));
|
198 | }
|
199 | catch (error) { }
|
200 | return null;
|
201 | }
|
202 | function _parseBytes(result, start) {
|
203 | if (result === "0x") {
|
204 | return null;
|
205 | }
|
206 | const offset = BigNumber.from(hexDataSlice(result, start, start + 32)).toNumber();
|
207 | const length = BigNumber.from(hexDataSlice(result, offset, offset + 32)).toNumber();
|
208 | return hexDataSlice(result, offset + 32, offset + 32 + length);
|
209 | }
|
210 |
|
211 | function getIpfsLink(link) {
|
212 | if (link.match(/^ipfs:\/\/ipfs\//i)) {
|
213 | link = link.substring(12);
|
214 | }
|
215 | else if (link.match(/^ipfs:\/\//i)) {
|
216 | link = link.substring(7);
|
217 | }
|
218 | else {
|
219 | logger.throwArgumentError("unsupported IPFS format", "link", link);
|
220 | }
|
221 | return `https:/\/gateway.ipfs.io/ipfs/${link}`;
|
222 | }
|
223 | function numPad(value) {
|
224 | const result = arrayify(value);
|
225 | if (result.length > 32) {
|
226 | throw new Error("internal; should not happen");
|
227 | }
|
228 | const padded = new Uint8Array(32);
|
229 | padded.set(result, 32 - result.length);
|
230 | return padded;
|
231 | }
|
232 | function bytesPad(value) {
|
233 | if ((value.length % 32) === 0) {
|
234 | return value;
|
235 | }
|
236 | const result = new Uint8Array(Math.ceil(value.length / 32) * 32);
|
237 | result.set(value);
|
238 | return result;
|
239 | }
|
240 |
|
241 | function encodeBytes(datas) {
|
242 | const result = [];
|
243 | let byteCount = 0;
|
244 |
|
245 | for (let i = 0; i < datas.length; i++) {
|
246 | result.push(null);
|
247 | byteCount += 32;
|
248 | }
|
249 | for (let i = 0; i < datas.length; i++) {
|
250 | const data = arrayify(datas[i]);
|
251 |
|
252 | result[i] = numPad(byteCount);
|
253 |
|
254 | result.push(numPad(data.length));
|
255 | result.push(bytesPad(data));
|
256 | byteCount += 32 + Math.ceil(data.length / 32) * 32;
|
257 | }
|
258 | return hexConcat(result);
|
259 | }
|
260 | export class Resolver {
|
261 |
|
262 | constructor(provider, address, name, resolvedAddress) {
|
263 | defineReadOnly(this, "provider", provider);
|
264 | defineReadOnly(this, "name", name);
|
265 | defineReadOnly(this, "address", provider.formatter.address(address));
|
266 | defineReadOnly(this, "_resolvedAddress", resolvedAddress);
|
267 | }
|
268 | supportsWildcard() {
|
269 | if (!this._supportsEip2544) {
|
270 |
|
271 | this._supportsEip2544 = this.provider.call({
|
272 | to: this.address,
|
273 | data: "0x01ffc9a79061b92300000000000000000000000000000000000000000000000000000000"
|
274 | }).then((result) => {
|
275 | return BigNumber.from(result).eq(1);
|
276 | }).catch((error) => {
|
277 | if (error.code === Logger.errors.CALL_EXCEPTION) {
|
278 | return false;
|
279 | }
|
280 |
|
281 | this._supportsEip2544 = null;
|
282 | throw error;
|
283 | });
|
284 | }
|
285 | return this._supportsEip2544;
|
286 | }
|
287 | _fetch(selector, parameters) {
|
288 | return __awaiter(this, void 0, void 0, function* () {
|
289 |
|
290 | const tx = {
|
291 | to: this.address,
|
292 | ccipReadEnabled: true,
|
293 | data: hexConcat([selector, namehash(this.name), (parameters || "0x")])
|
294 | };
|
295 |
|
296 | let parseBytes = false;
|
297 | if (yield this.supportsWildcard()) {
|
298 | parseBytes = true;
|
299 |
|
300 | tx.data = hexConcat(["0x9061b923", encodeBytes([dnsEncode(this.name), tx.data])]);
|
301 | }
|
302 | try {
|
303 | let result = yield this.provider.call(tx);
|
304 | if ((arrayify(result).length % 32) === 4) {
|
305 | logger.throwError("resolver threw error", Logger.errors.CALL_EXCEPTION, {
|
306 | transaction: tx, data: result
|
307 | });
|
308 | }
|
309 | if (parseBytes) {
|
310 | result = _parseBytes(result, 0);
|
311 | }
|
312 | return result;
|
313 | }
|
314 | catch (error) {
|
315 | if (error.code === Logger.errors.CALL_EXCEPTION) {
|
316 | return null;
|
317 | }
|
318 | throw error;
|
319 | }
|
320 | });
|
321 | }
|
322 | _fetchBytes(selector, parameters) {
|
323 | return __awaiter(this, void 0, void 0, function* () {
|
324 | const result = yield this._fetch(selector, parameters);
|
325 | if (result != null) {
|
326 | return _parseBytes(result, 0);
|
327 | }
|
328 | return null;
|
329 | });
|
330 | }
|
331 | _getAddress(coinType, hexBytes) {
|
332 | const coinInfo = coinInfos[String(coinType)];
|
333 | if (coinInfo == null) {
|
334 | logger.throwError(`unsupported coin type: ${coinType}`, Logger.errors.UNSUPPORTED_OPERATION, {
|
335 | operation: `getAddress(${coinType})`
|
336 | });
|
337 | }
|
338 | if (coinInfo.ilk === "eth") {
|
339 | return this.provider.formatter.address(hexBytes);
|
340 | }
|
341 | const bytes = arrayify(hexBytes);
|
342 |
|
343 | if (coinInfo.p2pkh != null) {
|
344 | const p2pkh = hexBytes.match(/^0x76a9([0-9a-f][0-9a-f])([0-9a-f]*)88ac$/);
|
345 | if (p2pkh) {
|
346 | const length = parseInt(p2pkh[1], 16);
|
347 | if (p2pkh[2].length === length * 2 && length >= 1 && length <= 75) {
|
348 | return base58Encode(concat([[coinInfo.p2pkh], ("0x" + p2pkh[2])]));
|
349 | }
|
350 | }
|
351 | }
|
352 |
|
353 | if (coinInfo.p2sh != null) {
|
354 | const p2sh = hexBytes.match(/^0xa9([0-9a-f][0-9a-f])([0-9a-f]*)87$/);
|
355 | if (p2sh) {
|
356 | const length = parseInt(p2sh[1], 16);
|
357 | if (p2sh[2].length === length * 2 && length >= 1 && length <= 75) {
|
358 | return base58Encode(concat([[coinInfo.p2sh], ("0x" + p2sh[2])]));
|
359 | }
|
360 | }
|
361 | }
|
362 |
|
363 | if (coinInfo.prefix != null) {
|
364 | const length = bytes[1];
|
365 |
|
366 | let version = bytes[0];
|
367 | if (version === 0x00) {
|
368 | if (length !== 20 && length !== 32) {
|
369 | version = -1;
|
370 | }
|
371 | }
|
372 | else {
|
373 | version = -1;
|
374 | }
|
375 | if (version >= 0 && bytes.length === 2 + length && length >= 1 && length <= 75) {
|
376 | const words = bech32.toWords(bytes.slice(2));
|
377 | words.unshift(version);
|
378 | return bech32.encode(coinInfo.prefix, words);
|
379 | }
|
380 | }
|
381 | return null;
|
382 | }
|
383 | getAddress(coinType) {
|
384 | return __awaiter(this, void 0, void 0, function* () {
|
385 | if (coinType == null) {
|
386 | coinType = 60;
|
387 | }
|
388 |
|
389 | if (coinType === 60) {
|
390 | try {
|
391 |
|
392 | const result = yield this._fetch("0x3b3b57de");
|
393 |
|
394 | if (result === "0x" || result === HashZero) {
|
395 | return null;
|
396 | }
|
397 | return this.provider.formatter.callAddress(result);
|
398 | }
|
399 | catch (error) {
|
400 | if (error.code === Logger.errors.CALL_EXCEPTION) {
|
401 | return null;
|
402 | }
|
403 | throw error;
|
404 | }
|
405 | }
|
406 |
|
407 | const hexBytes = yield this._fetchBytes("0xf1cb7e06", bytes32ify(coinType));
|
408 |
|
409 | if (hexBytes == null || hexBytes === "0x") {
|
410 | return null;
|
411 | }
|
412 |
|
413 | const address = this._getAddress(coinType, hexBytes);
|
414 | if (address == null) {
|
415 | logger.throwError(`invalid or unsupported coin data`, Logger.errors.UNSUPPORTED_OPERATION, {
|
416 | operation: `getAddress(${coinType})`,
|
417 | coinType: coinType,
|
418 | data: hexBytes
|
419 | });
|
420 | }
|
421 | return address;
|
422 | });
|
423 | }
|
424 | getAvatar() {
|
425 | return __awaiter(this, void 0, void 0, function* () {
|
426 | const linkage = [{ type: "name", content: this.name }];
|
427 | try {
|
428 |
|
429 |
|
430 | const avatar = yield this.getText("avatar");
|
431 | if (avatar == null) {
|
432 | return null;
|
433 | }
|
434 | for (let i = 0; i < matchers.length; i++) {
|
435 | const match = avatar.match(matchers[i]);
|
436 | if (match == null) {
|
437 | continue;
|
438 | }
|
439 | const scheme = match[1].toLowerCase();
|
440 | switch (scheme) {
|
441 | case "https":
|
442 | linkage.push({ type: "url", content: avatar });
|
443 | return { linkage, url: avatar };
|
444 | case "data":
|
445 | linkage.push({ type: "data", content: avatar });
|
446 | return { linkage, url: avatar };
|
447 | case "ipfs":
|
448 | linkage.push({ type: "ipfs", content: avatar });
|
449 | return { linkage, url: getIpfsLink(avatar) };
|
450 | case "erc721":
|
451 | case "erc1155": {
|
452 |
|
453 | const selector = (scheme === "erc721") ? "0xc87b56dd" : "0x0e89341c";
|
454 | linkage.push({ type: scheme, content: avatar });
|
455 |
|
456 | const owner = (this._resolvedAddress || (yield this.getAddress()));
|
457 | const comps = (match[2] || "").split("/");
|
458 | if (comps.length !== 2) {
|
459 | return null;
|
460 | }
|
461 | const addr = yield this.provider.formatter.address(comps[0]);
|
462 | const tokenId = hexZeroPad(BigNumber.from(comps[1]).toHexString(), 32);
|
463 |
|
464 | if (scheme === "erc721") {
|
465 |
|
466 | const tokenOwner = this.provider.formatter.callAddress(yield this.provider.call({
|
467 | to: addr, data: hexConcat(["0x6352211e", tokenId])
|
468 | }));
|
469 | if (owner !== tokenOwner) {
|
470 | return null;
|
471 | }
|
472 | linkage.push({ type: "owner", content: tokenOwner });
|
473 | }
|
474 | else if (scheme === "erc1155") {
|
475 |
|
476 | const balance = BigNumber.from(yield this.provider.call({
|
477 | to: addr, data: hexConcat(["0x00fdd58e", hexZeroPad(owner, 32), tokenId])
|
478 | }));
|
479 | if (balance.isZero()) {
|
480 | return null;
|
481 | }
|
482 | linkage.push({ type: "balance", content: balance.toString() });
|
483 | }
|
484 |
|
485 | const tx = {
|
486 | to: this.provider.formatter.address(comps[0]),
|
487 | data: hexConcat([selector, tokenId])
|
488 | };
|
489 | let metadataUrl = _parseString(yield this.provider.call(tx), 0);
|
490 | if (metadataUrl == null) {
|
491 | return null;
|
492 | }
|
493 | linkage.push({ type: "metadata-url-base", content: metadataUrl });
|
494 |
|
495 | if (scheme === "erc1155") {
|
496 | metadataUrl = metadataUrl.replace("{id}", tokenId.substring(2));
|
497 | linkage.push({ type: "metadata-url-expanded", content: metadataUrl });
|
498 | }
|
499 |
|
500 | if (metadataUrl.match(/^ipfs:/i)) {
|
501 | metadataUrl = getIpfsLink(metadataUrl);
|
502 | }
|
503 | linkage.push({ type: "metadata-url", content: metadataUrl });
|
504 |
|
505 | const metadata = yield fetchJson(metadataUrl);
|
506 | if (!metadata) {
|
507 | return null;
|
508 | }
|
509 | linkage.push({ type: "metadata", content: JSON.stringify(metadata) });
|
510 |
|
511 | let imageUrl = metadata.image;
|
512 | if (typeof (imageUrl) !== "string") {
|
513 | return null;
|
514 | }
|
515 | if (imageUrl.match(/^(https:\/\/|data:)/i)) {
|
516 |
|
517 | }
|
518 | else {
|
519 |
|
520 | const ipfs = imageUrl.match(matcherIpfs);
|
521 | if (ipfs == null) {
|
522 | return null;
|
523 | }
|
524 | linkage.push({ type: "url-ipfs", content: imageUrl });
|
525 | imageUrl = getIpfsLink(imageUrl);
|
526 | }
|
527 | linkage.push({ type: "url", content: imageUrl });
|
528 | return { linkage, url: imageUrl };
|
529 | }
|
530 | }
|
531 | }
|
532 | }
|
533 | catch (error) { }
|
534 | return null;
|
535 | });
|
536 | }
|
537 | getContentHash() {
|
538 | return __awaiter(this, void 0, void 0, function* () {
|
539 |
|
540 | const hexBytes = yield this._fetchBytes("0xbc1c58d1");
|
541 |
|
542 | if (hexBytes == null || hexBytes === "0x") {
|
543 | return null;
|
544 | }
|
545 |
|
546 | const ipfs = hexBytes.match(/^0xe3010170(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);
|
547 | if (ipfs) {
|
548 | const length = parseInt(ipfs[3], 16);
|
549 | if (ipfs[4].length === length * 2) {
|
550 | return "ipfs:/\/" + Base58.encode("0x" + ipfs[1]);
|
551 | }
|
552 | }
|
553 |
|
554 | const ipns = hexBytes.match(/^0xe5010172(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);
|
555 | if (ipns) {
|
556 | const length = parseInt(ipns[3], 16);
|
557 | if (ipns[4].length === length * 2) {
|
558 | return "ipns:/\/" + Base58.encode("0x" + ipns[1]);
|
559 | }
|
560 | }
|
561 |
|
562 | const swarm = hexBytes.match(/^0xe40101fa011b20([0-9a-f]*)$/);
|
563 | if (swarm) {
|
564 | if (swarm[1].length === (32 * 2)) {
|
565 | return "bzz:/\/" + swarm[1];
|
566 | }
|
567 | }
|
568 | const skynet = hexBytes.match(/^0x90b2c605([0-9a-f]*)$/);
|
569 | if (skynet) {
|
570 | if (skynet[1].length === (34 * 2)) {
|
571 |
|
572 | const urlSafe = { "=": "", "+": "-", "/": "_" };
|
573 | const hash = base64Encode("0x" + skynet[1]).replace(/[=+\/]/g, (a) => (urlSafe[a]));
|
574 | return "sia:/\/" + hash;
|
575 | }
|
576 | }
|
577 | return logger.throwError(`invalid or unsupported content hash data`, Logger.errors.UNSUPPORTED_OPERATION, {
|
578 | operation: "getContentHash()",
|
579 | data: hexBytes
|
580 | });
|
581 | });
|
582 | }
|
583 | getText(key) {
|
584 | return __awaiter(this, void 0, void 0, function* () {
|
585 |
|
586 | let keyBytes = toUtf8Bytes(key);
|
587 |
|
588 |
|
589 | keyBytes = concat([bytes32ify(64), bytes32ify(keyBytes.length), keyBytes]);
|
590 |
|
591 | if ((keyBytes.length % 32) !== 0) {
|
592 | keyBytes = concat([keyBytes, hexZeroPad("0x", 32 - (key.length % 32))]);
|
593 | }
|
594 | const hexBytes = yield this._fetchBytes("0x59d1d43c", hexlify(keyBytes));
|
595 | if (hexBytes == null || hexBytes === "0x") {
|
596 | return null;
|
597 | }
|
598 | return toUtf8String(hexBytes);
|
599 | });
|
600 | }
|
601 | }
|
602 | let defaultFormatter = null;
|
603 | let nextPollId = 1;
|
604 | export class BaseProvider extends Provider {
|
605 | |
606 |
|
607 |
|
608 |
|
609 |
|
610 |
|
611 |
|
612 |
|
613 |
|
614 | constructor(network) {
|
615 | super();
|
616 |
|
617 | this._events = [];
|
618 | this._emitted = { block: -2 };
|
619 | this.disableCcipRead = false;
|
620 | this.formatter = new.target.getFormatter();
|
621 |
|
622 |
|
623 |
|
624 | defineReadOnly(this, "anyNetwork", (network === "any"));
|
625 | if (this.anyNetwork) {
|
626 | network = this.detectNetwork();
|
627 | }
|
628 | if (network instanceof Promise) {
|
629 | this._networkPromise = network;
|
630 |
|
631 | network.catch((error) => { });
|
632 |
|
633 | this._ready().catch((error) => { });
|
634 | }
|
635 | else {
|
636 | const knownNetwork = getStatic(new.target, "getNetwork")(network);
|
637 | if (knownNetwork) {
|
638 | defineReadOnly(this, "_network", knownNetwork);
|
639 | this.emit("network", knownNetwork, null);
|
640 | }
|
641 | else {
|
642 | logger.throwArgumentError("invalid network", "network", network);
|
643 | }
|
644 | }
|
645 | this._maxInternalBlockNumber = -1024;
|
646 | this._lastBlockNumber = -2;
|
647 | this._maxFilterBlockRange = 10;
|
648 | this._pollingInterval = 4000;
|
649 | this._fastQueryDate = 0;
|
650 | }
|
651 | _ready() {
|
652 | return __awaiter(this, void 0, void 0, function* () {
|
653 | if (this._network == null) {
|
654 | let network = null;
|
655 | if (this._networkPromise) {
|
656 | try {
|
657 | network = yield this._networkPromise;
|
658 | }
|
659 | catch (error) { }
|
660 | }
|
661 |
|
662 | if (network == null) {
|
663 | network = yield this.detectNetwork();
|
664 | }
|
665 |
|
666 |
|
667 | if (!network) {
|
668 | logger.throwError("no network detected", Logger.errors.UNKNOWN_ERROR, {});
|
669 | }
|
670 |
|
671 | if (this._network == null) {
|
672 | if (this.anyNetwork) {
|
673 | this._network = network;
|
674 | }
|
675 | else {
|
676 | defineReadOnly(this, "_network", network);
|
677 | }
|
678 | this.emit("network", network, null);
|
679 | }
|
680 | }
|
681 | return this._network;
|
682 | });
|
683 | }
|
684 |
|
685 |
|
686 |
|
687 | get ready() {
|
688 | return poll(() => {
|
689 | return this._ready().then((network) => {
|
690 | return network;
|
691 | }, (error) => {
|
692 |
|
693 | if (error.code === Logger.errors.NETWORK_ERROR && error.event === "noNetwork") {
|
694 | return undefined;
|
695 | }
|
696 | throw error;
|
697 | });
|
698 | });
|
699 | }
|
700 |
|
701 | static getFormatter() {
|
702 | if (defaultFormatter == null) {
|
703 | defaultFormatter = new Formatter();
|
704 | }
|
705 | return defaultFormatter;
|
706 | }
|
707 |
|
708 | static getNetwork(network) {
|
709 | return getNetwork((network == null) ? "homestead" : network);
|
710 | }
|
711 | ccipReadFetch(tx, calldata, urls) {
|
712 | return __awaiter(this, void 0, void 0, function* () {
|
713 | if (this.disableCcipRead || urls.length === 0) {
|
714 | return null;
|
715 | }
|
716 | const sender = tx.to.toLowerCase();
|
717 | const data = calldata.toLowerCase();
|
718 | const errorMessages = [];
|
719 | for (let i = 0; i < urls.length; i++) {
|
720 | const url = urls[i];
|
721 |
|
722 | const href = url.replace("{sender}", sender).replace("{data}", data);
|
723 |
|
724 | const json = (url.indexOf("{data}") >= 0) ? null : JSON.stringify({ data, sender });
|
725 | const result = yield fetchJson({ url: href, errorPassThrough: true }, json, (value, response) => {
|
726 | value.status = response.statusCode;
|
727 | return value;
|
728 | });
|
729 | if (result.data) {
|
730 | return result.data;
|
731 | }
|
732 | const errorMessage = (result.message || "unknown error");
|
733 |
|
734 | if (result.status >= 400 && result.status < 500) {
|
735 | return logger.throwError(`response not found during CCIP fetch: ${errorMessage}`, Logger.errors.SERVER_ERROR, { url, errorMessage });
|
736 | }
|
737 |
|
738 | errorMessages.push(errorMessage);
|
739 | }
|
740 | return logger.throwError(`error encountered during CCIP fetch: ${errorMessages.map((m) => JSON.stringify(m)).join(", ")}`, Logger.errors.SERVER_ERROR, {
|
741 | urls, errorMessages
|
742 | });
|
743 | });
|
744 | }
|
745 |
|
746 |
|
747 | _getInternalBlockNumber(maxAge) {
|
748 | return __awaiter(this, void 0, void 0, function* () {
|
749 | yield this._ready();
|
750 |
|
751 | if (maxAge > 0) {
|
752 |
|
753 | while (this._internalBlockNumber) {
|
754 |
|
755 | const internalBlockNumber = this._internalBlockNumber;
|
756 | try {
|
757 |
|
758 | const result = yield internalBlockNumber;
|
759 | if ((getTime() - result.respTime) <= maxAge) {
|
760 | return result.blockNumber;
|
761 | }
|
762 |
|
763 | break;
|
764 | }
|
765 | catch (error) {
|
766 |
|
767 |
|
768 |
|
769 |
|
770 | if (this._internalBlockNumber === internalBlockNumber) {
|
771 | break;
|
772 | }
|
773 | }
|
774 | }
|
775 | }
|
776 | const reqTime = getTime();
|
777 | const checkInternalBlockNumber = resolveProperties({
|
778 | blockNumber: this.perform("getBlockNumber", {}),
|
779 | networkError: this.getNetwork().then((network) => (null), (error) => (error))
|
780 | }).then(({ blockNumber, networkError }) => {
|
781 | if (networkError) {
|
782 |
|
783 | if (this._internalBlockNumber === checkInternalBlockNumber) {
|
784 | this._internalBlockNumber = null;
|
785 | }
|
786 | throw networkError;
|
787 | }
|
788 | const respTime = getTime();
|
789 | blockNumber = BigNumber.from(blockNumber).toNumber();
|
790 | if (blockNumber < this._maxInternalBlockNumber) {
|
791 | blockNumber = this._maxInternalBlockNumber;
|
792 | }
|
793 | this._maxInternalBlockNumber = blockNumber;
|
794 | this._setFastBlockNumber(blockNumber);
|
795 | return { blockNumber, reqTime, respTime };
|
796 | });
|
797 | this._internalBlockNumber = checkInternalBlockNumber;
|
798 |
|
799 | checkInternalBlockNumber.catch((error) => {
|
800 |
|
801 | if (this._internalBlockNumber === checkInternalBlockNumber) {
|
802 | this._internalBlockNumber = null;
|
803 | }
|
804 | });
|
805 | return (yield checkInternalBlockNumber).blockNumber;
|
806 | });
|
807 | }
|
808 | poll() {
|
809 | return __awaiter(this, void 0, void 0, function* () {
|
810 | const pollId = nextPollId++;
|
811 |
|
812 | const runners = [];
|
813 | let blockNumber = null;
|
814 | try {
|
815 | blockNumber = yield this._getInternalBlockNumber(100 + this.pollingInterval / 2);
|
816 | }
|
817 | catch (error) {
|
818 | this.emit("error", error);
|
819 | return;
|
820 | }
|
821 | this._setFastBlockNumber(blockNumber);
|
822 |
|
823 | this.emit("poll", pollId, blockNumber);
|
824 |
|
825 | if (blockNumber === this._lastBlockNumber) {
|
826 | this.emit("didPoll", pollId);
|
827 | return;
|
828 | }
|
829 |
|
830 | if (this._emitted.block === -2) {
|
831 | this._emitted.block = blockNumber - 1;
|
832 | }
|
833 | if (Math.abs((this._emitted.block) - blockNumber) > 1000) {
|
834 | logger.warn(`network block skew detected; skipping block events (emitted=${this._emitted.block} blockNumber${blockNumber})`);
|
835 | this.emit("error", logger.makeError("network block skew detected", Logger.errors.NETWORK_ERROR, {
|
836 | blockNumber: blockNumber,
|
837 | event: "blockSkew",
|
838 | previousBlockNumber: this._emitted.block
|
839 | }));
|
840 | this.emit("block", blockNumber);
|
841 | }
|
842 | else {
|
843 |
|
844 | for (let i = this._emitted.block + 1; i <= blockNumber; i++) {
|
845 | this.emit("block", i);
|
846 | }
|
847 | }
|
848 |
|
849 | if (this._emitted.block !== blockNumber) {
|
850 | this._emitted.block = blockNumber;
|
851 | Object.keys(this._emitted).forEach((key) => {
|
852 |
|
853 | if (key === "block") {
|
854 | return;
|
855 | }
|
856 |
|
857 | const eventBlockNumber = this._emitted[key];
|
858 |
|
859 |
|
860 |
|
861 | if (eventBlockNumber === "pending") {
|
862 | return;
|
863 | }
|
864 |
|
865 |
|
866 | if (blockNumber - eventBlockNumber > 12) {
|
867 | delete this._emitted[key];
|
868 | }
|
869 | });
|
870 | }
|
871 |
|
872 | if (this._lastBlockNumber === -2) {
|
873 | this._lastBlockNumber = blockNumber - 1;
|
874 | }
|
875 |
|
876 | this._events.forEach((event) => {
|
877 | switch (event.type) {
|
878 | case "tx": {
|
879 | const hash = event.hash;
|
880 | let runner = this.getTransactionReceipt(hash).then((receipt) => {
|
881 | if (!receipt || receipt.blockNumber == null) {
|
882 | return null;
|
883 | }
|
884 | this._emitted["t:" + hash] = receipt.blockNumber;
|
885 | this.emit(hash, receipt);
|
886 | return null;
|
887 | }).catch((error) => { this.emit("error", error); });
|
888 | runners.push(runner);
|
889 | break;
|
890 | }
|
891 | case "filter": {
|
892 |
|
893 | if (!event._inflight) {
|
894 | event._inflight = true;
|
895 |
|
896 |
|
897 |
|
898 |
|
899 | const filter = event.filter;
|
900 | filter.fromBlock = event._lastBlockNumber + 1;
|
901 | filter.toBlock = blockNumber;
|
902 |
|
903 | if (filter.toBlock - this._maxFilterBlockRange > filter.fromBlock) {
|
904 | filter.fromBlock = filter.toBlock - this._maxFilterBlockRange;
|
905 | }
|
906 | const runner = this.getLogs(filter).then((logs) => {
|
907 |
|
908 | event._inflight = false;
|
909 | if (logs.length === 0) {
|
910 | return;
|
911 | }
|
912 | logs.forEach((log) => {
|
913 |
|
914 |
|
915 | if (log.blockNumber > event._lastBlockNumber) {
|
916 | event._lastBlockNumber = log.blockNumber;
|
917 | }
|
918 |
|
919 | this._emitted["b:" + log.blockHash] = log.blockNumber;
|
920 | this._emitted["t:" + log.transactionHash] = log.blockNumber;
|
921 | this.emit(filter, log);
|
922 | });
|
923 | }).catch((error) => {
|
924 | this.emit("error", error);
|
925 |
|
926 | event._inflight = false;
|
927 | });
|
928 | runners.push(runner);
|
929 | }
|
930 | break;
|
931 | }
|
932 | }
|
933 | });
|
934 | this._lastBlockNumber = blockNumber;
|
935 |
|
936 | Promise.all(runners).then(() => {
|
937 | this.emit("didPoll", pollId);
|
938 | }).catch((error) => { this.emit("error", error); });
|
939 | return;
|
940 | });
|
941 | }
|
942 |
|
943 | resetEventsBlock(blockNumber) {
|
944 | this._lastBlockNumber = blockNumber - 1;
|
945 | if (this.polling) {
|
946 | this.poll();
|
947 | }
|
948 | }
|
949 | get network() {
|
950 | return this._network;
|
951 | }
|
952 |
|
953 |
|
954 | detectNetwork() {
|
955 | return __awaiter(this, void 0, void 0, function* () {
|
956 | return logger.throwError("provider does not support network detection", Logger.errors.UNSUPPORTED_OPERATION, {
|
957 | operation: "provider.detectNetwork"
|
958 | });
|
959 | });
|
960 | }
|
961 | getNetwork() {
|
962 | return __awaiter(this, void 0, void 0, function* () {
|
963 | const network = yield this._ready();
|
964 |
|
965 |
|
966 |
|
967 | const currentNetwork = yield this.detectNetwork();
|
968 | if (network.chainId !== currentNetwork.chainId) {
|
969 |
|
970 |
|
971 | if (this.anyNetwork) {
|
972 | this._network = currentNetwork;
|
973 |
|
974 | this._lastBlockNumber = -2;
|
975 | this._fastBlockNumber = null;
|
976 | this._fastBlockNumberPromise = null;
|
977 | this._fastQueryDate = 0;
|
978 | this._emitted.block = -2;
|
979 | this._maxInternalBlockNumber = -1024;
|
980 | this._internalBlockNumber = null;
|
981 |
|
982 |
|
983 |
|
984 | this.emit("network", currentNetwork, network);
|
985 | yield stall(0);
|
986 | return this._network;
|
987 | }
|
988 | const error = logger.makeError("underlying network changed", Logger.errors.NETWORK_ERROR, {
|
989 | event: "changed",
|
990 | network: network,
|
991 | detectedNetwork: currentNetwork
|
992 | });
|
993 | this.emit("error", error);
|
994 | throw error;
|
995 | }
|
996 | return network;
|
997 | });
|
998 | }
|
999 | get blockNumber() {
|
1000 | this._getInternalBlockNumber(100 + this.pollingInterval / 2).then((blockNumber) => {
|
1001 | this._setFastBlockNumber(blockNumber);
|
1002 | }, (error) => { });
|
1003 | return (this._fastBlockNumber != null) ? this._fastBlockNumber : -1;
|
1004 | }
|
1005 | get polling() {
|
1006 | return (this._poller != null);
|
1007 | }
|
1008 | set polling(value) {
|
1009 | if (value && !this._poller) {
|
1010 | this._poller = setInterval(() => { this.poll(); }, this.pollingInterval);
|
1011 | if (!this._bootstrapPoll) {
|
1012 | this._bootstrapPoll = setTimeout(() => {
|
1013 | this.poll();
|
1014 |
|
1015 |
|
1016 | this._bootstrapPoll = setTimeout(() => {
|
1017 |
|
1018 |
|
1019 | if (!this._poller) {
|
1020 | this.poll();
|
1021 | }
|
1022 |
|
1023 | this._bootstrapPoll = null;
|
1024 | }, this.pollingInterval);
|
1025 | }, 0);
|
1026 | }
|
1027 | }
|
1028 | else if (!value && this._poller) {
|
1029 | clearInterval(this._poller);
|
1030 | this._poller = null;
|
1031 | }
|
1032 | }
|
1033 | get pollingInterval() {
|
1034 | return this._pollingInterval;
|
1035 | }
|
1036 | set pollingInterval(value) {
|
1037 | if (typeof (value) !== "number" || value <= 0 || parseInt(String(value)) != value) {
|
1038 | throw new Error("invalid polling interval");
|
1039 | }
|
1040 | this._pollingInterval = value;
|
1041 | if (this._poller) {
|
1042 | clearInterval(this._poller);
|
1043 | this._poller = setInterval(() => { this.poll(); }, this._pollingInterval);
|
1044 | }
|
1045 | }
|
1046 | _getFastBlockNumber() {
|
1047 | const now = getTime();
|
1048 |
|
1049 | if ((now - this._fastQueryDate) > 2 * this._pollingInterval) {
|
1050 | this._fastQueryDate = now;
|
1051 | this._fastBlockNumberPromise = this.getBlockNumber().then((blockNumber) => {
|
1052 | if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) {
|
1053 | this._fastBlockNumber = blockNumber;
|
1054 | }
|
1055 | return this._fastBlockNumber;
|
1056 | });
|
1057 | }
|
1058 | return this._fastBlockNumberPromise;
|
1059 | }
|
1060 | _setFastBlockNumber(blockNumber) {
|
1061 |
|
1062 | if (this._fastBlockNumber != null && blockNumber < this._fastBlockNumber) {
|
1063 | return;
|
1064 | }
|
1065 |
|
1066 | this._fastQueryDate = getTime();
|
1067 |
|
1068 | if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) {
|
1069 | this._fastBlockNumber = blockNumber;
|
1070 | this._fastBlockNumberPromise = Promise.resolve(blockNumber);
|
1071 | }
|
1072 | }
|
1073 | waitForTransaction(transactionHash, confirmations, timeout) {
|
1074 | return __awaiter(this, void 0, void 0, function* () {
|
1075 | return this._waitForTransaction(transactionHash, (confirmations == null) ? 1 : confirmations, timeout || 0, null);
|
1076 | });
|
1077 | }
|
1078 | _waitForTransaction(transactionHash, confirmations, timeout, replaceable) {
|
1079 | return __awaiter(this, void 0, void 0, function* () {
|
1080 | const receipt = yield this.getTransactionReceipt(transactionHash);
|
1081 |
|
1082 | if ((receipt ? receipt.confirmations : 0) >= confirmations) {
|
1083 | return receipt;
|
1084 | }
|
1085 |
|
1086 | return new Promise((resolve, reject) => {
|
1087 | const cancelFuncs = [];
|
1088 | let done = false;
|
1089 | const alreadyDone = function () {
|
1090 | if (done) {
|
1091 | return true;
|
1092 | }
|
1093 | done = true;
|
1094 | cancelFuncs.forEach((func) => { func(); });
|
1095 | return false;
|
1096 | };
|
1097 | const minedHandler = (receipt) => {
|
1098 | if (receipt.confirmations < confirmations) {
|
1099 | return;
|
1100 | }
|
1101 | if (alreadyDone()) {
|
1102 | return;
|
1103 | }
|
1104 | resolve(receipt);
|
1105 | };
|
1106 | this.on(transactionHash, minedHandler);
|
1107 | cancelFuncs.push(() => { this.removeListener(transactionHash, minedHandler); });
|
1108 | if (replaceable) {
|
1109 | let lastBlockNumber = replaceable.startBlock;
|
1110 | let scannedBlock = null;
|
1111 | const replaceHandler = (blockNumber) => __awaiter(this, void 0, void 0, function* () {
|
1112 | if (done) {
|
1113 | return;
|
1114 | }
|
1115 |
|
1116 |
|
1117 |
|
1118 | yield stall(1000);
|
1119 | this.getTransactionCount(replaceable.from).then((nonce) => __awaiter(this, void 0, void 0, function* () {
|
1120 | if (done) {
|
1121 | return;
|
1122 | }
|
1123 | if (nonce <= replaceable.nonce) {
|
1124 | lastBlockNumber = blockNumber;
|
1125 | }
|
1126 | else {
|
1127 |
|
1128 | {
|
1129 | const mined = yield this.getTransaction(transactionHash);
|
1130 | if (mined && mined.blockNumber != null) {
|
1131 | return;
|
1132 | }
|
1133 | }
|
1134 |
|
1135 |
|
1136 |
|
1137 |
|
1138 | if (scannedBlock == null) {
|
1139 | scannedBlock = lastBlockNumber - 3;
|
1140 | if (scannedBlock < replaceable.startBlock) {
|
1141 | scannedBlock = replaceable.startBlock;
|
1142 | }
|
1143 | }
|
1144 | while (scannedBlock <= blockNumber) {
|
1145 | if (done) {
|
1146 | return;
|
1147 | }
|
1148 | const block = yield this.getBlockWithTransactions(scannedBlock);
|
1149 | for (let ti = 0; ti < block.transactions.length; ti++) {
|
1150 | const tx = block.transactions[ti];
|
1151 |
|
1152 | if (tx.hash === transactionHash) {
|
1153 | return;
|
1154 | }
|
1155 |
|
1156 | if (tx.from === replaceable.from && tx.nonce === replaceable.nonce) {
|
1157 | if (done) {
|
1158 | return;
|
1159 | }
|
1160 |
|
1161 | const receipt = yield this.waitForTransaction(tx.hash, confirmations);
|
1162 |
|
1163 | if (alreadyDone()) {
|
1164 | return;
|
1165 | }
|
1166 |
|
1167 | let reason = "replaced";
|
1168 | if (tx.data === replaceable.data && tx.to === replaceable.to && tx.value.eq(replaceable.value)) {
|
1169 | reason = "repriced";
|
1170 | }
|
1171 | else if (tx.data === "0x" && tx.from === tx.to && tx.value.isZero()) {
|
1172 | reason = "cancelled";
|
1173 | }
|
1174 |
|
1175 | reject(logger.makeError("transaction was replaced", Logger.errors.TRANSACTION_REPLACED, {
|
1176 | cancelled: (reason === "replaced" || reason === "cancelled"),
|
1177 | reason,
|
1178 | replacement: this._wrapTransaction(tx),
|
1179 | hash: transactionHash,
|
1180 | receipt
|
1181 | }));
|
1182 | return;
|
1183 | }
|
1184 | }
|
1185 | scannedBlock++;
|
1186 | }
|
1187 | }
|
1188 | if (done) {
|
1189 | return;
|
1190 | }
|
1191 | this.once("block", replaceHandler);
|
1192 | }), (error) => {
|
1193 | if (done) {
|
1194 | return;
|
1195 | }
|
1196 | this.once("block", replaceHandler);
|
1197 | });
|
1198 | });
|
1199 | if (done) {
|
1200 | return;
|
1201 | }
|
1202 | this.once("block", replaceHandler);
|
1203 | cancelFuncs.push(() => {
|
1204 | this.removeListener("block", replaceHandler);
|
1205 | });
|
1206 | }
|
1207 | if (typeof (timeout) === "number" && timeout > 0) {
|
1208 | const timer = setTimeout(() => {
|
1209 | if (alreadyDone()) {
|
1210 | return;
|
1211 | }
|
1212 | reject(logger.makeError("timeout exceeded", Logger.errors.TIMEOUT, { timeout: timeout }));
|
1213 | }, timeout);
|
1214 | if (timer.unref) {
|
1215 | timer.unref();
|
1216 | }
|
1217 | cancelFuncs.push(() => { clearTimeout(timer); });
|
1218 | }
|
1219 | });
|
1220 | });
|
1221 | }
|
1222 | getBlockNumber() {
|
1223 | return __awaiter(this, void 0, void 0, function* () {
|
1224 | return this._getInternalBlockNumber(0);
|
1225 | });
|
1226 | }
|
1227 | getGasPrice() {
|
1228 | return __awaiter(this, void 0, void 0, function* () {
|
1229 | yield this.getNetwork();
|
1230 | const result = yield this.perform("getGasPrice", {});
|
1231 | try {
|
1232 | return BigNumber.from(result);
|
1233 | }
|
1234 | catch (error) {
|
1235 | return logger.throwError("bad result from backend", Logger.errors.SERVER_ERROR, {
|
1236 | method: "getGasPrice",
|
1237 | result, error
|
1238 | });
|
1239 | }
|
1240 | });
|
1241 | }
|
1242 | getBalance(addressOrName, blockTag) {
|
1243 | return __awaiter(this, void 0, void 0, function* () {
|
1244 | yield this.getNetwork();
|
1245 | const params = yield resolveProperties({
|
1246 | address: this._getAddress(addressOrName),
|
1247 | blockTag: this._getBlockTag(blockTag)
|
1248 | });
|
1249 | const result = yield this.perform("getBalance", params);
|
1250 | try {
|
1251 | return BigNumber.from(result);
|
1252 | }
|
1253 | catch (error) {
|
1254 | return logger.throwError("bad result from backend", Logger.errors.SERVER_ERROR, {
|
1255 | method: "getBalance",
|
1256 | params, result, error
|
1257 | });
|
1258 | }
|
1259 | });
|
1260 | }
|
1261 | getTransactionCount(addressOrName, blockTag) {
|
1262 | return __awaiter(this, void 0, void 0, function* () {
|
1263 | yield this.getNetwork();
|
1264 | const params = yield resolveProperties({
|
1265 | address: this._getAddress(addressOrName),
|
1266 | blockTag: this._getBlockTag(blockTag)
|
1267 | });
|
1268 | const result = yield this.perform("getTransactionCount", params);
|
1269 | try {
|
1270 | return BigNumber.from(result).toNumber();
|
1271 | }
|
1272 | catch (error) {
|
1273 | return logger.throwError("bad result from backend", Logger.errors.SERVER_ERROR, {
|
1274 | method: "getTransactionCount",
|
1275 | params, result, error
|
1276 | });
|
1277 | }
|
1278 | });
|
1279 | }
|
1280 | getCode(addressOrName, blockTag) {
|
1281 | return __awaiter(this, void 0, void 0, function* () {
|
1282 | yield this.getNetwork();
|
1283 | const params = yield resolveProperties({
|
1284 | address: this._getAddress(addressOrName),
|
1285 | blockTag: this._getBlockTag(blockTag)
|
1286 | });
|
1287 | const result = yield this.perform("getCode", params);
|
1288 | try {
|
1289 | return hexlify(result);
|
1290 | }
|
1291 | catch (error) {
|
1292 | return logger.throwError("bad result from backend", Logger.errors.SERVER_ERROR, {
|
1293 | method: "getCode",
|
1294 | params, result, error
|
1295 | });
|
1296 | }
|
1297 | });
|
1298 | }
|
1299 | getStorageAt(addressOrName, position, blockTag) {
|
1300 | return __awaiter(this, void 0, void 0, function* () {
|
1301 | yield this.getNetwork();
|
1302 | const params = yield resolveProperties({
|
1303 | address: this._getAddress(addressOrName),
|
1304 | blockTag: this._getBlockTag(blockTag),
|
1305 | position: Promise.resolve(position).then((p) => hexValue(p))
|
1306 | });
|
1307 | const result = yield this.perform("getStorageAt", params);
|
1308 | try {
|
1309 | return hexlify(result);
|
1310 | }
|
1311 | catch (error) {
|
1312 | return logger.throwError("bad result from backend", Logger.errors.SERVER_ERROR, {
|
1313 | method: "getStorageAt",
|
1314 | params, result, error
|
1315 | });
|
1316 | }
|
1317 | });
|
1318 | }
|
1319 |
|
1320 | _wrapTransaction(tx, hash, startBlock) {
|
1321 | if (hash != null && hexDataLength(hash) !== 32) {
|
1322 | throw new Error("invalid response - sendTransaction");
|
1323 | }
|
1324 | const result = tx;
|
1325 |
|
1326 | if (hash != null && tx.hash !== hash) {
|
1327 | logger.throwError("Transaction hash mismatch from Provider.sendTransaction.", Logger.errors.UNKNOWN_ERROR, { expectedHash: tx.hash, returnedHash: hash });
|
1328 | }
|
1329 | result.wait = (confirms, timeout) => __awaiter(this, void 0, void 0, function* () {
|
1330 | if (confirms == null) {
|
1331 | confirms = 1;
|
1332 | }
|
1333 | if (timeout == null) {
|
1334 | timeout = 0;
|
1335 | }
|
1336 |
|
1337 | let replacement = undefined;
|
1338 | if (confirms !== 0 && startBlock != null) {
|
1339 | replacement = {
|
1340 | data: tx.data,
|
1341 | from: tx.from,
|
1342 | nonce: tx.nonce,
|
1343 | to: tx.to,
|
1344 | value: tx.value,
|
1345 | startBlock
|
1346 | };
|
1347 | }
|
1348 | const receipt = yield this._waitForTransaction(tx.hash, confirms, timeout, replacement);
|
1349 | if (receipt == null && confirms === 0) {
|
1350 | return null;
|
1351 | }
|
1352 |
|
1353 | this._emitted["t:" + tx.hash] = receipt.blockNumber;
|
1354 | if (receipt.status === 0) {
|
1355 | logger.throwError("transaction failed", Logger.errors.CALL_EXCEPTION, {
|
1356 | transactionHash: tx.hash,
|
1357 | transaction: tx,
|
1358 | receipt: receipt
|
1359 | });
|
1360 | }
|
1361 | return receipt;
|
1362 | });
|
1363 | return result;
|
1364 | }
|
1365 | sendTransaction(signedTransaction) {
|
1366 | return __awaiter(this, void 0, void 0, function* () {
|
1367 | yield this.getNetwork();
|
1368 | const hexTx = yield Promise.resolve(signedTransaction).then(t => hexlify(t));
|
1369 | const tx = this.formatter.transaction(signedTransaction);
|
1370 | if (tx.confirmations == null) {
|
1371 | tx.confirmations = 0;
|
1372 | }
|
1373 | const blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
|
1374 | try {
|
1375 | const hash = yield this.perform("sendTransaction", { signedTransaction: hexTx });
|
1376 | return this._wrapTransaction(tx, hash, blockNumber);
|
1377 | }
|
1378 | catch (error) {
|
1379 | error.transaction = tx;
|
1380 | error.transactionHash = tx.hash;
|
1381 | throw error;
|
1382 | }
|
1383 | });
|
1384 | }
|
1385 | _getTransactionRequest(transaction) {
|
1386 | return __awaiter(this, void 0, void 0, function* () {
|
1387 | const values = yield transaction;
|
1388 | const tx = {};
|
1389 | ["from", "to"].forEach((key) => {
|
1390 | if (values[key] == null) {
|
1391 | return;
|
1392 | }
|
1393 | tx[key] = Promise.resolve(values[key]).then((v) => (v ? this._getAddress(v) : null));
|
1394 | });
|
1395 | ["gasLimit", "gasPrice", "maxFeePerGas", "maxPriorityFeePerGas", "value"].forEach((key) => {
|
1396 | if (values[key] == null) {
|
1397 | return;
|
1398 | }
|
1399 | tx[key] = Promise.resolve(values[key]).then((v) => (v ? BigNumber.from(v) : null));
|
1400 | });
|
1401 | ["type"].forEach((key) => {
|
1402 | if (values[key] == null) {
|
1403 | return;
|
1404 | }
|
1405 | tx[key] = Promise.resolve(values[key]).then((v) => ((v != null) ? v : null));
|
1406 | });
|
1407 | if (values.accessList) {
|
1408 | tx.accessList = this.formatter.accessList(values.accessList);
|
1409 | }
|
1410 | ["data"].forEach((key) => {
|
1411 | if (values[key] == null) {
|
1412 | return;
|
1413 | }
|
1414 | tx[key] = Promise.resolve(values[key]).then((v) => (v ? hexlify(v) : null));
|
1415 | });
|
1416 | return this.formatter.transactionRequest(yield resolveProperties(tx));
|
1417 | });
|
1418 | }
|
1419 | _getFilter(filter) {
|
1420 | return __awaiter(this, void 0, void 0, function* () {
|
1421 | filter = yield filter;
|
1422 | const result = {};
|
1423 | if (filter.address != null) {
|
1424 | result.address = this._getAddress(filter.address);
|
1425 | }
|
1426 | ["blockHash", "topics"].forEach((key) => {
|
1427 | if (filter[key] == null) {
|
1428 | return;
|
1429 | }
|
1430 | result[key] = filter[key];
|
1431 | });
|
1432 | ["fromBlock", "toBlock"].forEach((key) => {
|
1433 | if (filter[key] == null) {
|
1434 | return;
|
1435 | }
|
1436 | result[key] = this._getBlockTag(filter[key]);
|
1437 | });
|
1438 | return this.formatter.filter(yield resolveProperties(result));
|
1439 | });
|
1440 | }
|
1441 | _call(transaction, blockTag, attempt) {
|
1442 | return __awaiter(this, void 0, void 0, function* () {
|
1443 | if (attempt >= MAX_CCIP_REDIRECTS) {
|
1444 | logger.throwError("CCIP read exceeded maximum redirections", Logger.errors.SERVER_ERROR, {
|
1445 | redirects: attempt, transaction
|
1446 | });
|
1447 | }
|
1448 | const txSender = transaction.to;
|
1449 | const result = yield this.perform("call", { transaction, blockTag });
|
1450 |
|
1451 | if (attempt >= 0 && blockTag === "latest" && txSender != null && result.substring(0, 10) === "0x556f1830" && (hexDataLength(result) % 32 === 4)) {
|
1452 | try {
|
1453 | const data = hexDataSlice(result, 4);
|
1454 |
|
1455 | const sender = hexDataSlice(data, 0, 32);
|
1456 | if (!BigNumber.from(sender).eq(txSender)) {
|
1457 | logger.throwError("CCIP Read sender did not match", Logger.errors.CALL_EXCEPTION, {
|
1458 | name: "OffchainLookup",
|
1459 | signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
|
1460 | transaction, data: result
|
1461 | });
|
1462 | }
|
1463 |
|
1464 | const urls = [];
|
1465 | const urlsOffset = BigNumber.from(hexDataSlice(data, 32, 64)).toNumber();
|
1466 | const urlsLength = BigNumber.from(hexDataSlice(data, urlsOffset, urlsOffset + 32)).toNumber();
|
1467 | const urlsData = hexDataSlice(data, urlsOffset + 32);
|
1468 | for (let u = 0; u < urlsLength; u++) {
|
1469 | const url = _parseString(urlsData, u * 32);
|
1470 | if (url == null) {
|
1471 | logger.throwError("CCIP Read contained corrupt URL string", Logger.errors.CALL_EXCEPTION, {
|
1472 | name: "OffchainLookup",
|
1473 | signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
|
1474 | transaction, data: result
|
1475 | });
|
1476 | }
|
1477 | urls.push(url);
|
1478 | }
|
1479 |
|
1480 | const calldata = _parseBytes(data, 64);
|
1481 |
|
1482 | if (!BigNumber.from(hexDataSlice(data, 100, 128)).isZero()) {
|
1483 | logger.throwError("CCIP Read callback selector included junk", Logger.errors.CALL_EXCEPTION, {
|
1484 | name: "OffchainLookup",
|
1485 | signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
|
1486 | transaction, data: result
|
1487 | });
|
1488 | }
|
1489 | const callbackSelector = hexDataSlice(data, 96, 100);
|
1490 |
|
1491 | const extraData = _parseBytes(data, 128);
|
1492 | const ccipResult = yield this.ccipReadFetch(transaction, calldata, urls);
|
1493 | if (ccipResult == null) {
|
1494 | logger.throwError("CCIP Read disabled or provided no URLs", Logger.errors.CALL_EXCEPTION, {
|
1495 | name: "OffchainLookup",
|
1496 | signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
|
1497 | transaction, data: result
|
1498 | });
|
1499 | }
|
1500 | const tx = {
|
1501 | to: txSender,
|
1502 | data: hexConcat([callbackSelector, encodeBytes([ccipResult, extraData])])
|
1503 | };
|
1504 | return this._call(tx, blockTag, attempt + 1);
|
1505 | }
|
1506 | catch (error) {
|
1507 | if (error.code === Logger.errors.SERVER_ERROR) {
|
1508 | throw error;
|
1509 | }
|
1510 | }
|
1511 | }
|
1512 | try {
|
1513 | return hexlify(result);
|
1514 | }
|
1515 | catch (error) {
|
1516 | return logger.throwError("bad result from backend", Logger.errors.SERVER_ERROR, {
|
1517 | method: "call",
|
1518 | params: { transaction, blockTag }, result, error
|
1519 | });
|
1520 | }
|
1521 | });
|
1522 | }
|
1523 | call(transaction, blockTag) {
|
1524 | return __awaiter(this, void 0, void 0, function* () {
|
1525 | yield this.getNetwork();
|
1526 | const resolved = yield resolveProperties({
|
1527 | transaction: this._getTransactionRequest(transaction),
|
1528 | blockTag: this._getBlockTag(blockTag),
|
1529 | ccipReadEnabled: Promise.resolve(transaction.ccipReadEnabled)
|
1530 | });
|
1531 | return this._call(resolved.transaction, resolved.blockTag, resolved.ccipReadEnabled ? 0 : -1);
|
1532 | });
|
1533 | }
|
1534 | estimateGas(transaction) {
|
1535 | return __awaiter(this, void 0, void 0, function* () {
|
1536 | yield this.getNetwork();
|
1537 | const params = yield resolveProperties({
|
1538 | transaction: this._getTransactionRequest(transaction)
|
1539 | });
|
1540 | const result = yield this.perform("estimateGas", params);
|
1541 | try {
|
1542 | return BigNumber.from(result);
|
1543 | }
|
1544 | catch (error) {
|
1545 | return logger.throwError("bad result from backend", Logger.errors.SERVER_ERROR, {
|
1546 | method: "estimateGas",
|
1547 | params, result, error
|
1548 | });
|
1549 | }
|
1550 | });
|
1551 | }
|
1552 | _getAddress(addressOrName) {
|
1553 | return __awaiter(this, void 0, void 0, function* () {
|
1554 | addressOrName = yield addressOrName;
|
1555 | if (typeof (addressOrName) !== "string") {
|
1556 | logger.throwArgumentError("invalid address or ENS name", "name", addressOrName);
|
1557 | }
|
1558 | const address = yield this.resolveName(addressOrName);
|
1559 | if (address == null) {
|
1560 | logger.throwError("ENS name not configured", Logger.errors.UNSUPPORTED_OPERATION, {
|
1561 | operation: `resolveName(${JSON.stringify(addressOrName)})`
|
1562 | });
|
1563 | }
|
1564 | return address;
|
1565 | });
|
1566 | }
|
1567 | _getBlock(blockHashOrBlockTag, includeTransactions) {
|
1568 | return __awaiter(this, void 0, void 0, function* () {
|
1569 | yield this.getNetwork();
|
1570 | blockHashOrBlockTag = yield blockHashOrBlockTag;
|
1571 |
|
1572 | let blockNumber = -128;
|
1573 | const params = {
|
1574 | includeTransactions: !!includeTransactions
|
1575 | };
|
1576 | if (isHexString(blockHashOrBlockTag, 32)) {
|
1577 | params.blockHash = blockHashOrBlockTag;
|
1578 | }
|
1579 | else {
|
1580 | try {
|
1581 | params.blockTag = yield this._getBlockTag(blockHashOrBlockTag);
|
1582 | if (isHexString(params.blockTag)) {
|
1583 | blockNumber = parseInt(params.blockTag.substring(2), 16);
|
1584 | }
|
1585 | }
|
1586 | catch (error) {
|
1587 | logger.throwArgumentError("invalid block hash or block tag", "blockHashOrBlockTag", blockHashOrBlockTag);
|
1588 | }
|
1589 | }
|
1590 | return poll(() => __awaiter(this, void 0, void 0, function* () {
|
1591 | const block = yield this.perform("getBlock", params);
|
1592 |
|
1593 | if (block == null) {
|
1594 |
|
1595 |
|
1596 |
|
1597 | if (params.blockHash != null) {
|
1598 | if (this._emitted["b:" + params.blockHash] == null) {
|
1599 | return null;
|
1600 | }
|
1601 | }
|
1602 |
|
1603 | if (params.blockTag != null) {
|
1604 | if (blockNumber > this._emitted.block) {
|
1605 | return null;
|
1606 | }
|
1607 | }
|
1608 |
|
1609 | return undefined;
|
1610 | }
|
1611 |
|
1612 | if (includeTransactions) {
|
1613 | let blockNumber = null;
|
1614 | for (let i = 0; i < block.transactions.length; i++) {
|
1615 | const tx = block.transactions[i];
|
1616 | if (tx.blockNumber == null) {
|
1617 | tx.confirmations = 0;
|
1618 | }
|
1619 | else if (tx.confirmations == null) {
|
1620 | if (blockNumber == null) {
|
1621 | blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
|
1622 | }
|
1623 |
|
1624 | let confirmations = (blockNumber - tx.blockNumber) + 1;
|
1625 | if (confirmations <= 0) {
|
1626 | confirmations = 1;
|
1627 | }
|
1628 | tx.confirmations = confirmations;
|
1629 | }
|
1630 | }
|
1631 | const blockWithTxs = this.formatter.blockWithTransactions(block);
|
1632 | blockWithTxs.transactions = blockWithTxs.transactions.map((tx) => this._wrapTransaction(tx));
|
1633 | return blockWithTxs;
|
1634 | }
|
1635 | return this.formatter.block(block);
|
1636 | }), { oncePoll: this });
|
1637 | });
|
1638 | }
|
1639 | getBlock(blockHashOrBlockTag) {
|
1640 | return (this._getBlock(blockHashOrBlockTag, false));
|
1641 | }
|
1642 | getBlockWithTransactions(blockHashOrBlockTag) {
|
1643 | return (this._getBlock(blockHashOrBlockTag, true));
|
1644 | }
|
1645 | getTransaction(transactionHash) {
|
1646 | return __awaiter(this, void 0, void 0, function* () {
|
1647 | yield this.getNetwork();
|
1648 | transactionHash = yield transactionHash;
|
1649 | const params = { transactionHash: this.formatter.hash(transactionHash, true) };
|
1650 | return poll(() => __awaiter(this, void 0, void 0, function* () {
|
1651 | const result = yield this.perform("getTransaction", params);
|
1652 | if (result == null) {
|
1653 | if (this._emitted["t:" + transactionHash] == null) {
|
1654 | return null;
|
1655 | }
|
1656 | return undefined;
|
1657 | }
|
1658 | const tx = this.formatter.transactionResponse(result);
|
1659 | if (tx.blockNumber == null) {
|
1660 | tx.confirmations = 0;
|
1661 | }
|
1662 | else if (tx.confirmations == null) {
|
1663 | const blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
|
1664 |
|
1665 | let confirmations = (blockNumber - tx.blockNumber) + 1;
|
1666 | if (confirmations <= 0) {
|
1667 | confirmations = 1;
|
1668 | }
|
1669 | tx.confirmations = confirmations;
|
1670 | }
|
1671 | return this._wrapTransaction(tx);
|
1672 | }), { oncePoll: this });
|
1673 | });
|
1674 | }
|
1675 | getTransactionReceipt(transactionHash) {
|
1676 | return __awaiter(this, void 0, void 0, function* () {
|
1677 | yield this.getNetwork();
|
1678 | transactionHash = yield transactionHash;
|
1679 | const params = { transactionHash: this.formatter.hash(transactionHash, true) };
|
1680 | return poll(() => __awaiter(this, void 0, void 0, function* () {
|
1681 | const result = yield this.perform("getTransactionReceipt", params);
|
1682 | if (result == null) {
|
1683 | if (this._emitted["t:" + transactionHash] == null) {
|
1684 | return null;
|
1685 | }
|
1686 | return undefined;
|
1687 | }
|
1688 |
|
1689 | if (result.blockHash == null) {
|
1690 | return undefined;
|
1691 | }
|
1692 | const receipt = this.formatter.receipt(result);
|
1693 | if (receipt.blockNumber == null) {
|
1694 | receipt.confirmations = 0;
|
1695 | }
|
1696 | else if (receipt.confirmations == null) {
|
1697 | const blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
|
1698 |
|
1699 | let confirmations = (blockNumber - receipt.blockNumber) + 1;
|
1700 | if (confirmations <= 0) {
|
1701 | confirmations = 1;
|
1702 | }
|
1703 | receipt.confirmations = confirmations;
|
1704 | }
|
1705 | return receipt;
|
1706 | }), { oncePoll: this });
|
1707 | });
|
1708 | }
|
1709 | getLogs(filter) {
|
1710 | return __awaiter(this, void 0, void 0, function* () {
|
1711 | yield this.getNetwork();
|
1712 | const params = yield resolveProperties({ filter: this._getFilter(filter) });
|
1713 | const logs = yield this.perform("getLogs", params);
|
1714 | logs.forEach((log) => {
|
1715 | if (log.removed == null) {
|
1716 | log.removed = false;
|
1717 | }
|
1718 | });
|
1719 | return Formatter.arrayOf(this.formatter.filterLog.bind(this.formatter))(logs);
|
1720 | });
|
1721 | }
|
1722 | getEtherPrice() {
|
1723 | return __awaiter(this, void 0, void 0, function* () {
|
1724 | yield this.getNetwork();
|
1725 | return this.perform("getEtherPrice", {});
|
1726 | });
|
1727 | }
|
1728 | _getBlockTag(blockTag) {
|
1729 | return __awaiter(this, void 0, void 0, function* () {
|
1730 | blockTag = yield blockTag;
|
1731 | if (typeof (blockTag) === "number" && blockTag < 0) {
|
1732 | if (blockTag % 1) {
|
1733 | logger.throwArgumentError("invalid BlockTag", "blockTag", blockTag);
|
1734 | }
|
1735 | let blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
|
1736 | blockNumber += blockTag;
|
1737 | if (blockNumber < 0) {
|
1738 | blockNumber = 0;
|
1739 | }
|
1740 | return this.formatter.blockTag(blockNumber);
|
1741 | }
|
1742 | return this.formatter.blockTag(blockTag);
|
1743 | });
|
1744 | }
|
1745 | getResolver(name) {
|
1746 | return __awaiter(this, void 0, void 0, function* () {
|
1747 | let currentName = name;
|
1748 | while (true) {
|
1749 | if (currentName === "" || currentName === ".") {
|
1750 | return null;
|
1751 | }
|
1752 |
|
1753 |
|
1754 | if (name !== "eth" && currentName === "eth") {
|
1755 | return null;
|
1756 | }
|
1757 |
|
1758 | const addr = yield this._getResolver(currentName, "getResolver");
|
1759 |
|
1760 | if (addr != null) {
|
1761 | const resolver = new Resolver(this, addr, name);
|
1762 |
|
1763 | if (currentName !== name && !(yield resolver.supportsWildcard())) {
|
1764 | return null;
|
1765 | }
|
1766 | return resolver;
|
1767 | }
|
1768 |
|
1769 | currentName = currentName.split(".").slice(1).join(".");
|
1770 | }
|
1771 | });
|
1772 | }
|
1773 | _getResolver(name, operation) {
|
1774 | return __awaiter(this, void 0, void 0, function* () {
|
1775 | if (operation == null) {
|
1776 | operation = "ENS";
|
1777 | }
|
1778 | const network = yield this.getNetwork();
|
1779 |
|
1780 | if (!network.ensAddress) {
|
1781 | logger.throwError("network does not support ENS", Logger.errors.UNSUPPORTED_OPERATION, { operation, network: network.name });
|
1782 | }
|
1783 | try {
|
1784 |
|
1785 | const addrData = yield this.call({
|
1786 | to: network.ensAddress,
|
1787 | data: ("0x0178b8bf" + namehash(name).substring(2))
|
1788 | });
|
1789 | return this.formatter.callAddress(addrData);
|
1790 | }
|
1791 | catch (error) {
|
1792 |
|
1793 | }
|
1794 | return null;
|
1795 | });
|
1796 | }
|
1797 | resolveName(name) {
|
1798 | return __awaiter(this, void 0, void 0, function* () {
|
1799 | name = yield name;
|
1800 |
|
1801 | try {
|
1802 | return Promise.resolve(this.formatter.address(name));
|
1803 | }
|
1804 | catch (error) {
|
1805 |
|
1806 | if (isHexString(name)) {
|
1807 | throw error;
|
1808 | }
|
1809 | }
|
1810 | if (typeof (name) !== "string") {
|
1811 | logger.throwArgumentError("invalid ENS name", "name", name);
|
1812 | }
|
1813 |
|
1814 | const resolver = yield this.getResolver(name);
|
1815 | if (!resolver) {
|
1816 | return null;
|
1817 | }
|
1818 | return yield resolver.getAddress();
|
1819 | });
|
1820 | }
|
1821 | lookupAddress(address) {
|
1822 | return __awaiter(this, void 0, void 0, function* () {
|
1823 | address = yield address;
|
1824 | address = this.formatter.address(address);
|
1825 | const node = address.substring(2).toLowerCase() + ".addr.reverse";
|
1826 | const resolverAddr = yield this._getResolver(node, "lookupAddress");
|
1827 | if (resolverAddr == null) {
|
1828 | return null;
|
1829 | }
|
1830 |
|
1831 | const name = _parseString(yield this.call({
|
1832 | to: resolverAddr,
|
1833 | data: ("0x691f3431" + namehash(node).substring(2))
|
1834 | }), 0);
|
1835 | const addr = yield this.resolveName(name);
|
1836 | if (addr != address) {
|
1837 | return null;
|
1838 | }
|
1839 | return name;
|
1840 | });
|
1841 | }
|
1842 | getAvatar(nameOrAddress) {
|
1843 | return __awaiter(this, void 0, void 0, function* () {
|
1844 | let resolver = null;
|
1845 | if (isHexString(nameOrAddress)) {
|
1846 |
|
1847 | const address = this.formatter.address(nameOrAddress);
|
1848 | const node = address.substring(2).toLowerCase() + ".addr.reverse";
|
1849 | const resolverAddress = yield this._getResolver(node, "getAvatar");
|
1850 | if (!resolverAddress) {
|
1851 | return null;
|
1852 | }
|
1853 |
|
1854 | resolver = new Resolver(this, resolverAddress, node);
|
1855 | try {
|
1856 | const avatar = yield resolver.getAvatar();
|
1857 | if (avatar) {
|
1858 | return avatar.url;
|
1859 | }
|
1860 | }
|
1861 | catch (error) {
|
1862 | if (error.code !== Logger.errors.CALL_EXCEPTION) {
|
1863 | throw error;
|
1864 | }
|
1865 | }
|
1866 |
|
1867 | try {
|
1868 |
|
1869 | const name = _parseString(yield this.call({
|
1870 | to: resolverAddress,
|
1871 | data: ("0x691f3431" + namehash(node).substring(2))
|
1872 | }), 0);
|
1873 | resolver = yield this.getResolver(name);
|
1874 | }
|
1875 | catch (error) {
|
1876 | if (error.code !== Logger.errors.CALL_EXCEPTION) {
|
1877 | throw error;
|
1878 | }
|
1879 | return null;
|
1880 | }
|
1881 | }
|
1882 | else {
|
1883 |
|
1884 | resolver = yield this.getResolver(nameOrAddress);
|
1885 | if (!resolver) {
|
1886 | return null;
|
1887 | }
|
1888 | }
|
1889 | const avatar = yield resolver.getAvatar();
|
1890 | if (avatar == null) {
|
1891 | return null;
|
1892 | }
|
1893 | return avatar.url;
|
1894 | });
|
1895 | }
|
1896 | perform(method, params) {
|
1897 | return logger.throwError(method + " not implemented", Logger.errors.NOT_IMPLEMENTED, { operation: method });
|
1898 | }
|
1899 | _startEvent(event) {
|
1900 | this.polling = (this._events.filter((e) => e.pollable()).length > 0);
|
1901 | }
|
1902 | _stopEvent(event) {
|
1903 | this.polling = (this._events.filter((e) => e.pollable()).length > 0);
|
1904 | }
|
1905 | _addEventListener(eventName, listener, once) {
|
1906 | const event = new Event(getEventTag(eventName), listener, once);
|
1907 | this._events.push(event);
|
1908 | this._startEvent(event);
|
1909 | return this;
|
1910 | }
|
1911 | on(eventName, listener) {
|
1912 | return this._addEventListener(eventName, listener, false);
|
1913 | }
|
1914 | once(eventName, listener) {
|
1915 | return this._addEventListener(eventName, listener, true);
|
1916 | }
|
1917 | emit(eventName, ...args) {
|
1918 | let result = false;
|
1919 | let stopped = [];
|
1920 | let eventTag = getEventTag(eventName);
|
1921 | this._events = this._events.filter((event) => {
|
1922 | if (event.tag !== eventTag) {
|
1923 | return true;
|
1924 | }
|
1925 | setTimeout(() => {
|
1926 | event.listener.apply(this, args);
|
1927 | }, 0);
|
1928 | result = true;
|
1929 | if (event.once) {
|
1930 | stopped.push(event);
|
1931 | return false;
|
1932 | }
|
1933 | return true;
|
1934 | });
|
1935 | stopped.forEach((event) => { this._stopEvent(event); });
|
1936 | return result;
|
1937 | }
|
1938 | listenerCount(eventName) {
|
1939 | if (!eventName) {
|
1940 | return this._events.length;
|
1941 | }
|
1942 | let eventTag = getEventTag(eventName);
|
1943 | return this._events.filter((event) => {
|
1944 | return (event.tag === eventTag);
|
1945 | }).length;
|
1946 | }
|
1947 | listeners(eventName) {
|
1948 | if (eventName == null) {
|
1949 | return this._events.map((event) => event.listener);
|
1950 | }
|
1951 | let eventTag = getEventTag(eventName);
|
1952 | return this._events
|
1953 | .filter((event) => (event.tag === eventTag))
|
1954 | .map((event) => event.listener);
|
1955 | }
|
1956 | off(eventName, listener) {
|
1957 | if (listener == null) {
|
1958 | return this.removeAllListeners(eventName);
|
1959 | }
|
1960 | const stopped = [];
|
1961 | let found = false;
|
1962 | let eventTag = getEventTag(eventName);
|
1963 | this._events = this._events.filter((event) => {
|
1964 | if (event.tag !== eventTag || event.listener != listener) {
|
1965 | return true;
|
1966 | }
|
1967 | if (found) {
|
1968 | return true;
|
1969 | }
|
1970 | found = true;
|
1971 | stopped.push(event);
|
1972 | return false;
|
1973 | });
|
1974 | stopped.forEach((event) => { this._stopEvent(event); });
|
1975 | return this;
|
1976 | }
|
1977 | removeAllListeners(eventName) {
|
1978 | let stopped = [];
|
1979 | if (eventName == null) {
|
1980 | stopped = this._events;
|
1981 | this._events = [];
|
1982 | }
|
1983 | else {
|
1984 | const eventTag = getEventTag(eventName);
|
1985 | this._events = this._events.filter((event) => {
|
1986 | if (event.tag !== eventTag) {
|
1987 | return true;
|
1988 | }
|
1989 | stopped.push(event);
|
1990 | return false;
|
1991 | });
|
1992 | }
|
1993 | stopped.forEach((event) => { this._stopEvent(event); });
|
1994 | return this;
|
1995 | }
|
1996 | }
|
1997 |
|
\ | No newline at end of file |