base-provider.ts 80 KB

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