base-provider.js 128 KB

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