provider.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.TransactionResponse = exports.TransactionReceipt = exports.Log = exports.Block = exports.copyRequest = exports.FeeData = void 0;
  4. //import { resolveAddress } from "@ethersproject/address";
  5. const index_js_1 = require("../utils/index.js");
  6. const index_js_2 = require("../transaction/index.js");
  7. const BN_0 = BigInt(0);
  8. // -----------------------
  9. function getValue(value) {
  10. if (value == null) {
  11. return null;
  12. }
  13. return value;
  14. }
  15. function toJson(value) {
  16. if (value == null) {
  17. return null;
  18. }
  19. return value.toString();
  20. }
  21. // @TODO? <T extends FeeData = { }> implements Required<T>
  22. /**
  23. * A **FeeData** wraps all the fee-related values associated with
  24. * the network.
  25. */
  26. class FeeData {
  27. /**
  28. * The gas price for legacy networks.
  29. */
  30. gasPrice;
  31. /**
  32. * The maximum fee to pay per gas.
  33. *
  34. * The base fee per gas is defined by the network and based on
  35. * congestion, increasing the cost during times of heavy load
  36. * and lowering when less busy.
  37. *
  38. * The actual fee per gas will be the base fee for the block
  39. * and the priority fee, up to the max fee per gas.
  40. *
  41. * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559))
  42. */
  43. maxFeePerGas;
  44. /**
  45. * The additional amout to pay per gas to encourage a validator
  46. * to include the transaction.
  47. *
  48. * The purpose of this is to compensate the validator for the
  49. * adjusted risk for including a given transaction.
  50. *
  51. * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559))
  52. */
  53. maxPriorityFeePerGas;
  54. /**
  55. * Creates a new FeeData for %%gasPrice%%, %%maxFeePerGas%% and
  56. * %%maxPriorityFeePerGas%%.
  57. */
  58. constructor(gasPrice, maxFeePerGas, maxPriorityFeePerGas) {
  59. (0, index_js_1.defineProperties)(this, {
  60. gasPrice: getValue(gasPrice),
  61. maxFeePerGas: getValue(maxFeePerGas),
  62. maxPriorityFeePerGas: getValue(maxPriorityFeePerGas)
  63. });
  64. }
  65. /**
  66. * Returns a JSON-friendly value.
  67. */
  68. toJSON() {
  69. const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = this;
  70. return {
  71. _type: "FeeData",
  72. gasPrice: toJson(gasPrice),
  73. maxFeePerGas: toJson(maxFeePerGas),
  74. maxPriorityFeePerGas: toJson(maxPriorityFeePerGas),
  75. };
  76. }
  77. }
  78. exports.FeeData = FeeData;
  79. ;
  80. /**
  81. * Returns a copy of %%req%% with all properties coerced to their strict
  82. * types.
  83. */
  84. function copyRequest(req) {
  85. const result = {};
  86. // These could be addresses, ENS names or Addressables
  87. if (req.to) {
  88. result.to = req.to;
  89. }
  90. if (req.from) {
  91. result.from = req.from;
  92. }
  93. if (req.data) {
  94. result.data = (0, index_js_1.hexlify)(req.data);
  95. }
  96. const bigIntKeys = "chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);
  97. for (const key of bigIntKeys) {
  98. if (!(key in req) || req[key] == null) {
  99. continue;
  100. }
  101. result[key] = (0, index_js_1.getBigInt)(req[key], `request.${key}`);
  102. }
  103. const numberKeys = "type,nonce".split(/,/);
  104. for (const key of numberKeys) {
  105. if (!(key in req) || req[key] == null) {
  106. continue;
  107. }
  108. result[key] = (0, index_js_1.getNumber)(req[key], `request.${key}`);
  109. }
  110. if (req.accessList) {
  111. result.accessList = (0, index_js_2.accessListify)(req.accessList);
  112. }
  113. if ("blockTag" in req) {
  114. result.blockTag = req.blockTag;
  115. }
  116. if ("enableCcipRead" in req) {
  117. result.enableCcipRead = !!req.enableCcipRead;
  118. }
  119. if ("customData" in req) {
  120. result.customData = req.customData;
  121. }
  122. if ("blobVersionedHashes" in req && req.blobVersionedHashes) {
  123. result.blobVersionedHashes = req.blobVersionedHashes.slice();
  124. }
  125. if ("kzg" in req) {
  126. result.kzg = req.kzg;
  127. }
  128. if ("blobs" in req && req.blobs) {
  129. result.blobs = req.blobs.map((b) => {
  130. if ((0, index_js_1.isBytesLike)(b)) {
  131. return (0, index_js_1.hexlify)(b);
  132. }
  133. return Object.assign({}, b);
  134. });
  135. }
  136. return result;
  137. }
  138. exports.copyRequest = copyRequest;
  139. /**
  140. * A **Block** represents the data associated with a full block on
  141. * Ethereum.
  142. */
  143. class Block {
  144. /**
  145. * The provider connected to the block used to fetch additional details
  146. * if necessary.
  147. */
  148. provider;
  149. /**
  150. * The block number, sometimes called the block height. This is a
  151. * sequential number that is one higher than the parent block.
  152. */
  153. number;
  154. /**
  155. * The block hash.
  156. *
  157. * This hash includes all properties, so can be safely used to identify
  158. * an exact set of block properties.
  159. */
  160. hash;
  161. /**
  162. * The timestamp for this block, which is the number of seconds since
  163. * epoch that this block was included.
  164. */
  165. timestamp;
  166. /**
  167. * The block hash of the parent block.
  168. */
  169. parentHash;
  170. /**
  171. * The hash tree root of the parent beacon block for the given
  172. * execution block. See [[link-eip-4788]].
  173. */
  174. parentBeaconBlockRoot;
  175. /**
  176. * The nonce.
  177. *
  178. * On legacy networks, this is the random number inserted which
  179. * permitted the difficulty target to be reached.
  180. */
  181. nonce;
  182. /**
  183. * The difficulty target.
  184. *
  185. * On legacy networks, this is the proof-of-work target required
  186. * for a block to meet the protocol rules to be included.
  187. *
  188. * On modern networks, this is a random number arrived at using
  189. * randao. @TODO: Find links?
  190. */
  191. difficulty;
  192. /**
  193. * The total gas limit for this block.
  194. */
  195. gasLimit;
  196. /**
  197. * The total gas used in this block.
  198. */
  199. gasUsed;
  200. /**
  201. * The root hash for the global state after applying changes
  202. * in this block.
  203. */
  204. stateRoot;
  205. /**
  206. * The hash of the transaction receipts trie.
  207. */
  208. receiptsRoot;
  209. /**
  210. * The total amount of blob gas consumed by the transactions
  211. * within the block. See [[link-eip-4844]].
  212. */
  213. blobGasUsed;
  214. /**
  215. * The running total of blob gas consumed in excess of the
  216. * target, prior to the block. See [[link-eip-4844]].
  217. */
  218. excessBlobGas;
  219. /**
  220. * The miner coinbase address, wihch receives any subsidies for
  221. * including this block.
  222. */
  223. miner;
  224. /**
  225. * The latest RANDAO mix of the post beacon state of
  226. * the previous block.
  227. */
  228. prevRandao;
  229. /**
  230. * Any extra data the validator wished to include.
  231. */
  232. extraData;
  233. /**
  234. * The base fee per gas that all transactions in this block were
  235. * charged.
  236. *
  237. * This adjusts after each block, depending on how congested the network
  238. * is.
  239. */
  240. baseFeePerGas;
  241. #transactions;
  242. /**
  243. * Create a new **Block** object.
  244. *
  245. * This should generally not be necessary as the unless implementing a
  246. * low-level library.
  247. */
  248. constructor(block, provider) {
  249. this.#transactions = block.transactions.map((tx) => {
  250. if (typeof (tx) !== "string") {
  251. return new TransactionResponse(tx, provider);
  252. }
  253. return tx;
  254. });
  255. (0, index_js_1.defineProperties)(this, {
  256. provider,
  257. hash: getValue(block.hash),
  258. number: block.number,
  259. timestamp: block.timestamp,
  260. parentHash: block.parentHash,
  261. parentBeaconBlockRoot: block.parentBeaconBlockRoot,
  262. nonce: block.nonce,
  263. difficulty: block.difficulty,
  264. gasLimit: block.gasLimit,
  265. gasUsed: block.gasUsed,
  266. blobGasUsed: block.blobGasUsed,
  267. excessBlobGas: block.excessBlobGas,
  268. miner: block.miner,
  269. prevRandao: getValue(block.prevRandao),
  270. extraData: block.extraData,
  271. baseFeePerGas: getValue(block.baseFeePerGas),
  272. stateRoot: block.stateRoot,
  273. receiptsRoot: block.receiptsRoot,
  274. });
  275. }
  276. /**
  277. * Returns the list of transaction hashes, in the order
  278. * they were executed within the block.
  279. */
  280. get transactions() {
  281. return this.#transactions.map((tx) => {
  282. if (typeof (tx) === "string") {
  283. return tx;
  284. }
  285. return tx.hash;
  286. });
  287. }
  288. /**
  289. * Returns the complete transactions, in the order they
  290. * were executed within the block.
  291. *
  292. * This is only available for blocks which prefetched
  293. * transactions, by passing ``true`` to %%prefetchTxs%%
  294. * into [[Provider-getBlock]].
  295. */
  296. get prefetchedTransactions() {
  297. const txs = this.#transactions.slice();
  298. // Doesn't matter...
  299. if (txs.length === 0) {
  300. return [];
  301. }
  302. // Make sure we prefetched the transactions
  303. (0, index_js_1.assert)(typeof (txs[0]) === "object", "transactions were not prefetched with block request", "UNSUPPORTED_OPERATION", {
  304. operation: "transactionResponses()"
  305. });
  306. return txs;
  307. }
  308. /**
  309. * Returns a JSON-friendly value.
  310. */
  311. toJSON() {
  312. const { baseFeePerGas, difficulty, extraData, gasLimit, gasUsed, hash, miner, prevRandao, nonce, number, parentHash, parentBeaconBlockRoot, stateRoot, receiptsRoot, timestamp, transactions } = this;
  313. return {
  314. _type: "Block",
  315. baseFeePerGas: toJson(baseFeePerGas),
  316. difficulty: toJson(difficulty),
  317. extraData,
  318. gasLimit: toJson(gasLimit),
  319. gasUsed: toJson(gasUsed),
  320. blobGasUsed: toJson(this.blobGasUsed),
  321. excessBlobGas: toJson(this.excessBlobGas),
  322. hash, miner, prevRandao, nonce, number, parentHash, timestamp,
  323. parentBeaconBlockRoot, stateRoot, receiptsRoot,
  324. transactions,
  325. };
  326. }
  327. [Symbol.iterator]() {
  328. let index = 0;
  329. const txs = this.transactions;
  330. return {
  331. next: () => {
  332. if (index < this.length) {
  333. return {
  334. value: txs[index++], done: false
  335. };
  336. }
  337. return { value: undefined, done: true };
  338. }
  339. };
  340. }
  341. /**
  342. * The number of transactions in this block.
  343. */
  344. get length() { return this.#transactions.length; }
  345. /**
  346. * The [[link-js-date]] this block was included at.
  347. */
  348. get date() {
  349. if (this.timestamp == null) {
  350. return null;
  351. }
  352. return new Date(this.timestamp * 1000);
  353. }
  354. /**
  355. * Get the transaction at %%indexe%% within this block.
  356. */
  357. async getTransaction(indexOrHash) {
  358. // Find the internal value by its index or hash
  359. let tx = undefined;
  360. if (typeof (indexOrHash) === "number") {
  361. tx = this.#transactions[indexOrHash];
  362. }
  363. else {
  364. const hash = indexOrHash.toLowerCase();
  365. for (const v of this.#transactions) {
  366. if (typeof (v) === "string") {
  367. if (v !== hash) {
  368. continue;
  369. }
  370. tx = v;
  371. break;
  372. }
  373. else {
  374. if (v.hash !== hash) {
  375. continue;
  376. }
  377. tx = v;
  378. break;
  379. }
  380. }
  381. }
  382. if (tx == null) {
  383. throw new Error("no such tx");
  384. }
  385. if (typeof (tx) === "string") {
  386. return (await this.provider.getTransaction(tx));
  387. }
  388. else {
  389. return tx;
  390. }
  391. }
  392. /**
  393. * If a **Block** was fetched with a request to include the transactions
  394. * this will allow synchronous access to those transactions.
  395. *
  396. * If the transactions were not prefetched, this will throw.
  397. */
  398. getPrefetchedTransaction(indexOrHash) {
  399. const txs = this.prefetchedTransactions;
  400. if (typeof (indexOrHash) === "number") {
  401. return txs[indexOrHash];
  402. }
  403. indexOrHash = indexOrHash.toLowerCase();
  404. for (const tx of txs) {
  405. if (tx.hash === indexOrHash) {
  406. return tx;
  407. }
  408. }
  409. (0, index_js_1.assertArgument)(false, "no matching transaction", "indexOrHash", indexOrHash);
  410. }
  411. /**
  412. * Returns true if this block been mined. This provides a type guard
  413. * for all properties on a [[MinedBlock]].
  414. */
  415. isMined() { return !!this.hash; }
  416. /**
  417. * Returns true if this block is an [[link-eip-2930]] block.
  418. */
  419. isLondon() {
  420. return !!this.baseFeePerGas;
  421. }
  422. /**
  423. * @_ignore:
  424. */
  425. orphanedEvent() {
  426. if (!this.isMined()) {
  427. throw new Error("");
  428. }
  429. return createOrphanedBlockFilter(this);
  430. }
  431. }
  432. exports.Block = Block;
  433. //////////////////////
  434. // Log
  435. /**
  436. * A **Log** in Ethereum represents an event that has been included in a
  437. * transaction using the ``LOG*`` opcodes, which are most commonly used by
  438. * Solidity's emit for announcing events.
  439. */
  440. class Log {
  441. /**
  442. * The provider connected to the log used to fetch additional details
  443. * if necessary.
  444. */
  445. provider;
  446. /**
  447. * The transaction hash of the transaction this log occurred in. Use the
  448. * [[Log-getTransaction]] to get the [[TransactionResponse]].
  449. */
  450. transactionHash;
  451. /**
  452. * The block hash of the block this log occurred in. Use the
  453. * [[Log-getBlock]] to get the [[Block]].
  454. */
  455. blockHash;
  456. /**
  457. * The block number of the block this log occurred in. It is preferred
  458. * to use the [[Block-hash]] when fetching the related [[Block]],
  459. * since in the case of an orphaned block, the block at that height may
  460. * have changed.
  461. */
  462. blockNumber;
  463. /**
  464. * If the **Log** represents a block that was removed due to an orphaned
  465. * block, this will be true.
  466. *
  467. * This can only happen within an orphan event listener.
  468. */
  469. removed;
  470. /**
  471. * The address of the contract that emitted this log.
  472. */
  473. address;
  474. /**
  475. * The data included in this log when it was emitted.
  476. */
  477. data;
  478. /**
  479. * The indexed topics included in this log when it was emitted.
  480. *
  481. * All topics are included in the bloom filters, so they can be
  482. * efficiently filtered using the [[Provider-getLogs]] method.
  483. */
  484. topics;
  485. /**
  486. * The index within the block this log occurred at. This is generally
  487. * not useful to developers, but can be used with the various roots
  488. * to proof inclusion within a block.
  489. */
  490. index;
  491. /**
  492. * The index within the transaction of this log.
  493. */
  494. transactionIndex;
  495. /**
  496. * @_ignore:
  497. */
  498. constructor(log, provider) {
  499. this.provider = provider;
  500. const topics = Object.freeze(log.topics.slice());
  501. (0, index_js_1.defineProperties)(this, {
  502. transactionHash: log.transactionHash,
  503. blockHash: log.blockHash,
  504. blockNumber: log.blockNumber,
  505. removed: log.removed,
  506. address: log.address,
  507. data: log.data,
  508. topics,
  509. index: log.index,
  510. transactionIndex: log.transactionIndex,
  511. });
  512. }
  513. /**
  514. * Returns a JSON-compatible object.
  515. */
  516. toJSON() {
  517. const { address, blockHash, blockNumber, data, index, removed, topics, transactionHash, transactionIndex } = this;
  518. return {
  519. _type: "log",
  520. address, blockHash, blockNumber, data, index,
  521. removed, topics, transactionHash, transactionIndex
  522. };
  523. }
  524. /**
  525. * Returns the block that this log occurred in.
  526. */
  527. async getBlock() {
  528. const block = await this.provider.getBlock(this.blockHash);
  529. (0, index_js_1.assert)(!!block, "failed to find transaction", "UNKNOWN_ERROR", {});
  530. return block;
  531. }
  532. /**
  533. * Returns the transaction that this log occurred in.
  534. */
  535. async getTransaction() {
  536. const tx = await this.provider.getTransaction(this.transactionHash);
  537. (0, index_js_1.assert)(!!tx, "failed to find transaction", "UNKNOWN_ERROR", {});
  538. return tx;
  539. }
  540. /**
  541. * Returns the transaction receipt fot the transaction that this
  542. * log occurred in.
  543. */
  544. async getTransactionReceipt() {
  545. const receipt = await this.provider.getTransactionReceipt(this.transactionHash);
  546. (0, index_js_1.assert)(!!receipt, "failed to find transaction receipt", "UNKNOWN_ERROR", {});
  547. return receipt;
  548. }
  549. /**
  550. * @_ignore:
  551. */
  552. removedEvent() {
  553. return createRemovedLogFilter(this);
  554. }
  555. }
  556. exports.Log = Log;
  557. //////////////////////
  558. // Transaction Receipt
  559. /*
  560. export interface LegacyTransactionReceipt {
  561. byzantium: false;
  562. status: null;
  563. root: string;
  564. }
  565. export interface ByzantiumTransactionReceipt {
  566. byzantium: true;
  567. status: number;
  568. root: null;
  569. }
  570. */
  571. /**
  572. * A **TransactionReceipt** includes additional information about a
  573. * transaction that is only available after it has been mined.
  574. */
  575. class TransactionReceipt {
  576. /**
  577. * The provider connected to the log used to fetch additional details
  578. * if necessary.
  579. */
  580. provider;
  581. /**
  582. * The address the transaction was sent to.
  583. */
  584. to;
  585. /**
  586. * The sender of the transaction.
  587. */
  588. from;
  589. /**
  590. * The address of the contract if the transaction was directly
  591. * responsible for deploying one.
  592. *
  593. * This is non-null **only** if the ``to`` is empty and the ``data``
  594. * was successfully executed as initcode.
  595. */
  596. contractAddress;
  597. /**
  598. * The transaction hash.
  599. */
  600. hash;
  601. /**
  602. * The index of this transaction within the block transactions.
  603. */
  604. index;
  605. /**
  606. * The block hash of the [[Block]] this transaction was included in.
  607. */
  608. blockHash;
  609. /**
  610. * The block number of the [[Block]] this transaction was included in.
  611. */
  612. blockNumber;
  613. /**
  614. * The bloom filter bytes that represent all logs that occurred within
  615. * this transaction. This is generally not useful for most developers,
  616. * but can be used to validate the included logs.
  617. */
  618. logsBloom;
  619. /**
  620. * The actual amount of gas used by this transaction.
  621. *
  622. * When creating a transaction, the amount of gas that will be used can
  623. * only be approximated, but the sender must pay the gas fee for the
  624. * entire gas limit. After the transaction, the difference is refunded.
  625. */
  626. gasUsed;
  627. /**
  628. * The gas used for BLObs. See [[link-eip-4844]].
  629. */
  630. blobGasUsed;
  631. /**
  632. * The amount of gas used by all transactions within the block for this
  633. * and all transactions with a lower ``index``.
  634. *
  635. * This is generally not useful for developers but can be used to
  636. * validate certain aspects of execution.
  637. */
  638. cumulativeGasUsed;
  639. /**
  640. * The actual gas price used during execution.
  641. *
  642. * Due to the complexity of [[link-eip-1559]] this value can only
  643. * be caluclated after the transaction has been mined, snce the base
  644. * fee is protocol-enforced.
  645. */
  646. gasPrice;
  647. /**
  648. * The price paid per BLOB in gas. See [[link-eip-4844]].
  649. */
  650. blobGasPrice;
  651. /**
  652. * The [[link-eip-2718]] transaction type.
  653. */
  654. type;
  655. //readonly byzantium!: boolean;
  656. /**
  657. * The status of this transaction, indicating success (i.e. ``1``) or
  658. * a revert (i.e. ``0``).
  659. *
  660. * This is available in post-byzantium blocks, but some backends may
  661. * backfill this value.
  662. */
  663. status;
  664. /**
  665. * The root hash of this transaction.
  666. *
  667. * This is no present and was only included in pre-byzantium blocks, but
  668. * could be used to validate certain parts of the receipt.
  669. */
  670. root;
  671. #logs;
  672. /**
  673. * @_ignore:
  674. */
  675. constructor(tx, provider) {
  676. this.#logs = Object.freeze(tx.logs.map((log) => {
  677. return new Log(log, provider);
  678. }));
  679. let gasPrice = BN_0;
  680. if (tx.effectiveGasPrice != null) {
  681. gasPrice = tx.effectiveGasPrice;
  682. }
  683. else if (tx.gasPrice != null) {
  684. gasPrice = tx.gasPrice;
  685. }
  686. (0, index_js_1.defineProperties)(this, {
  687. provider,
  688. to: tx.to,
  689. from: tx.from,
  690. contractAddress: tx.contractAddress,
  691. hash: tx.hash,
  692. index: tx.index,
  693. blockHash: tx.blockHash,
  694. blockNumber: tx.blockNumber,
  695. logsBloom: tx.logsBloom,
  696. gasUsed: tx.gasUsed,
  697. cumulativeGasUsed: tx.cumulativeGasUsed,
  698. blobGasUsed: tx.blobGasUsed,
  699. gasPrice,
  700. blobGasPrice: tx.blobGasPrice,
  701. type: tx.type,
  702. //byzantium: tx.byzantium,
  703. status: tx.status,
  704. root: tx.root
  705. });
  706. }
  707. /**
  708. * The logs for this transaction.
  709. */
  710. get logs() { return this.#logs; }
  711. /**
  712. * Returns a JSON-compatible representation.
  713. */
  714. toJSON() {
  715. const { to, from, contractAddress, hash, index, blockHash, blockNumber, logsBloom, logs, //byzantium,
  716. status, root } = this;
  717. return {
  718. _type: "TransactionReceipt",
  719. blockHash, blockNumber,
  720. //byzantium,
  721. contractAddress,
  722. cumulativeGasUsed: toJson(this.cumulativeGasUsed),
  723. from,
  724. gasPrice: toJson(this.gasPrice),
  725. blobGasUsed: toJson(this.blobGasUsed),
  726. blobGasPrice: toJson(this.blobGasPrice),
  727. gasUsed: toJson(this.gasUsed),
  728. hash, index, logs, logsBloom, root, status, to
  729. };
  730. }
  731. /**
  732. * @_ignore:
  733. */
  734. get length() { return this.logs.length; }
  735. [Symbol.iterator]() {
  736. let index = 0;
  737. return {
  738. next: () => {
  739. if (index < this.length) {
  740. return { value: this.logs[index++], done: false };
  741. }
  742. return { value: undefined, done: true };
  743. }
  744. };
  745. }
  746. /**
  747. * The total fee for this transaction, in wei.
  748. */
  749. get fee() {
  750. return this.gasUsed * this.gasPrice;
  751. }
  752. /**
  753. * Resolves to the block this transaction occurred in.
  754. */
  755. async getBlock() {
  756. const block = await this.provider.getBlock(this.blockHash);
  757. if (block == null) {
  758. throw new Error("TODO");
  759. }
  760. return block;
  761. }
  762. /**
  763. * Resolves to the transaction this transaction occurred in.
  764. */
  765. async getTransaction() {
  766. const tx = await this.provider.getTransaction(this.hash);
  767. if (tx == null) {
  768. throw new Error("TODO");
  769. }
  770. return tx;
  771. }
  772. /**
  773. * Resolves to the return value of the execution of this transaction.
  774. *
  775. * Support for this feature is limited, as it requires an archive node
  776. * with the ``debug_`` or ``trace_`` API enabled.
  777. */
  778. async getResult() {
  779. return (await this.provider.getTransactionResult(this.hash));
  780. }
  781. /**
  782. * Resolves to the number of confirmations this transaction has.
  783. */
  784. async confirmations() {
  785. return (await this.provider.getBlockNumber()) - this.blockNumber + 1;
  786. }
  787. /**
  788. * @_ignore:
  789. */
  790. removedEvent() {
  791. return createRemovedTransactionFilter(this);
  792. }
  793. /**
  794. * @_ignore:
  795. */
  796. reorderedEvent(other) {
  797. (0, index_js_1.assert)(!other || other.isMined(), "unmined 'other' transction cannot be orphaned", "UNSUPPORTED_OPERATION", { operation: "reorderedEvent(other)" });
  798. return createReorderedTransactionFilter(this, other);
  799. }
  800. }
  801. exports.TransactionReceipt = TransactionReceipt;
  802. /**
  803. * A **TransactionResponse** includes all properties about a transaction
  804. * that was sent to the network, which may or may not be included in a
  805. * block.
  806. *
  807. * The [[TransactionResponse-isMined]] can be used to check if the
  808. * transaction has been mined as well as type guard that the otherwise
  809. * possibly ``null`` properties are defined.
  810. */
  811. class TransactionResponse {
  812. /**
  813. * The provider this is connected to, which will influence how its
  814. * methods will resolve its async inspection methods.
  815. */
  816. provider;
  817. /**
  818. * The block number of the block that this transaction was included in.
  819. *
  820. * This is ``null`` for pending transactions.
  821. */
  822. blockNumber;
  823. /**
  824. * The blockHash of the block that this transaction was included in.
  825. *
  826. * This is ``null`` for pending transactions.
  827. */
  828. blockHash;
  829. /**
  830. * The index within the block that this transaction resides at.
  831. */
  832. index;
  833. /**
  834. * The transaction hash.
  835. */
  836. hash;
  837. /**
  838. * The [[link-eip-2718]] transaction envelope type. This is
  839. * ``0`` for legacy transactions types.
  840. */
  841. type;
  842. /**
  843. * The receiver of this transaction.
  844. *
  845. * If ``null``, then the transaction is an initcode transaction.
  846. * This means the result of executing the [[data]] will be deployed
  847. * as a new contract on chain (assuming it does not revert) and the
  848. * address may be computed using [[getCreateAddress]].
  849. */
  850. to;
  851. /**
  852. * The sender of this transaction. It is implicitly computed
  853. * from the transaction pre-image hash (as the digest) and the
  854. * [[signature]] using ecrecover.
  855. */
  856. from;
  857. /**
  858. * The nonce, which is used to prevent replay attacks and offer
  859. * a method to ensure transactions from a given sender are explicitly
  860. * ordered.
  861. *
  862. * When sending a transaction, this must be equal to the number of
  863. * transactions ever sent by [[from]].
  864. */
  865. nonce;
  866. /**
  867. * The maximum units of gas this transaction can consume. If execution
  868. * exceeds this, the entries transaction is reverted and the sender
  869. * is charged for the full amount, despite not state changes being made.
  870. */
  871. gasLimit;
  872. /**
  873. * The gas price can have various values, depending on the network.
  874. *
  875. * In modern networks, for transactions that are included this is
  876. * the //effective gas price// (the fee per gas that was actually
  877. * charged), while for transactions that have not been included yet
  878. * is the [[maxFeePerGas]].
  879. *
  880. * For legacy transactions, or transactions on legacy networks, this
  881. * is the fee that will be charged per unit of gas the transaction
  882. * consumes.
  883. */
  884. gasPrice;
  885. /**
  886. * The maximum priority fee (per unit of gas) to allow a
  887. * validator to charge the sender. This is inclusive of the
  888. * [[maxFeeFeePerGas]].
  889. */
  890. maxPriorityFeePerGas;
  891. /**
  892. * The maximum fee (per unit of gas) to allow this transaction
  893. * to charge the sender.
  894. */
  895. maxFeePerGas;
  896. /**
  897. * The [[link-eip-4844]] max fee per BLOb gas.
  898. */
  899. maxFeePerBlobGas;
  900. /**
  901. * The data.
  902. */
  903. data;
  904. /**
  905. * The value, in wei. Use [[formatEther]] to format this value
  906. * as ether.
  907. */
  908. value;
  909. /**
  910. * The chain ID.
  911. */
  912. chainId;
  913. /**
  914. * The signature.
  915. */
  916. signature;
  917. /**
  918. * The [[link-eip-2930]] access list for transaction types that
  919. * support it, otherwise ``null``.
  920. */
  921. accessList;
  922. /**
  923. * The [[link-eip-4844]] BLOb versioned hashes.
  924. */
  925. blobVersionedHashes;
  926. #startBlock;
  927. /**
  928. * @_ignore:
  929. */
  930. constructor(tx, provider) {
  931. this.provider = provider;
  932. this.blockNumber = (tx.blockNumber != null) ? tx.blockNumber : null;
  933. this.blockHash = (tx.blockHash != null) ? tx.blockHash : null;
  934. this.hash = tx.hash;
  935. this.index = tx.index;
  936. this.type = tx.type;
  937. this.from = tx.from;
  938. this.to = tx.to || null;
  939. this.gasLimit = tx.gasLimit;
  940. this.nonce = tx.nonce;
  941. this.data = tx.data;
  942. this.value = tx.value;
  943. this.gasPrice = tx.gasPrice;
  944. this.maxPriorityFeePerGas = (tx.maxPriorityFeePerGas != null) ? tx.maxPriorityFeePerGas : null;
  945. this.maxFeePerGas = (tx.maxFeePerGas != null) ? tx.maxFeePerGas : null;
  946. this.maxFeePerBlobGas = (tx.maxFeePerBlobGas != null) ? tx.maxFeePerBlobGas : null;
  947. this.chainId = tx.chainId;
  948. this.signature = tx.signature;
  949. this.accessList = (tx.accessList != null) ? tx.accessList : null;
  950. this.blobVersionedHashes = (tx.blobVersionedHashes != null) ? tx.blobVersionedHashes : null;
  951. this.#startBlock = -1;
  952. }
  953. /**
  954. * Returns a JSON-compatible representation of this transaction.
  955. */
  956. toJSON() {
  957. const { blockNumber, blockHash, index, hash, type, to, from, nonce, data, signature, accessList, blobVersionedHashes } = this;
  958. return {
  959. _type: "TransactionResponse",
  960. accessList, blockNumber, blockHash,
  961. blobVersionedHashes,
  962. chainId: toJson(this.chainId),
  963. data, from,
  964. gasLimit: toJson(this.gasLimit),
  965. gasPrice: toJson(this.gasPrice),
  966. hash,
  967. maxFeePerGas: toJson(this.maxFeePerGas),
  968. maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas),
  969. maxFeePerBlobGas: toJson(this.maxFeePerBlobGas),
  970. nonce, signature, to, index, type,
  971. value: toJson(this.value),
  972. };
  973. }
  974. /**
  975. * Resolves to the Block that this transaction was included in.
  976. *
  977. * This will return null if the transaction has not been included yet.
  978. */
  979. async getBlock() {
  980. let blockNumber = this.blockNumber;
  981. if (blockNumber == null) {
  982. const tx = await this.getTransaction();
  983. if (tx) {
  984. blockNumber = tx.blockNumber;
  985. }
  986. }
  987. if (blockNumber == null) {
  988. return null;
  989. }
  990. const block = this.provider.getBlock(blockNumber);
  991. if (block == null) {
  992. throw new Error("TODO");
  993. }
  994. return block;
  995. }
  996. /**
  997. * Resolves to this transaction being re-requested from the
  998. * provider. This can be used if you have an unmined transaction
  999. * and wish to get an up-to-date populated instance.
  1000. */
  1001. async getTransaction() {
  1002. return this.provider.getTransaction(this.hash);
  1003. }
  1004. /**
  1005. * Resolve to the number of confirmations this transaction has.
  1006. */
  1007. async confirmations() {
  1008. if (this.blockNumber == null) {
  1009. const { tx, blockNumber } = await (0, index_js_1.resolveProperties)({
  1010. tx: this.getTransaction(),
  1011. blockNumber: this.provider.getBlockNumber()
  1012. });
  1013. // Not mined yet...
  1014. if (tx == null || tx.blockNumber == null) {
  1015. return 0;
  1016. }
  1017. return blockNumber - tx.blockNumber + 1;
  1018. }
  1019. const blockNumber = await this.provider.getBlockNumber();
  1020. return blockNumber - this.blockNumber + 1;
  1021. }
  1022. /**
  1023. * Resolves once this transaction has been mined and has
  1024. * %%confirms%% blocks including it (default: ``1``) with an
  1025. * optional %%timeout%%.
  1026. *
  1027. * This can resolve to ``null`` only if %%confirms%% is ``0``
  1028. * and the transaction has not been mined, otherwise this will
  1029. * wait until enough confirmations have completed.
  1030. */
  1031. async wait(_confirms, _timeout) {
  1032. const confirms = (_confirms == null) ? 1 : _confirms;
  1033. const timeout = (_timeout == null) ? 0 : _timeout;
  1034. let startBlock = this.#startBlock;
  1035. let nextScan = -1;
  1036. let stopScanning = (startBlock === -1) ? true : false;
  1037. const checkReplacement = async () => {
  1038. // Get the current transaction count for this sender
  1039. if (stopScanning) {
  1040. return null;
  1041. }
  1042. const { blockNumber, nonce } = await (0, index_js_1.resolveProperties)({
  1043. blockNumber: this.provider.getBlockNumber(),
  1044. nonce: this.provider.getTransactionCount(this.from)
  1045. });
  1046. // No transaction or our nonce has not been mined yet; but we
  1047. // can start scanning later when we do start
  1048. if (nonce < this.nonce) {
  1049. startBlock = blockNumber;
  1050. return;
  1051. }
  1052. // We were mined; no replacement
  1053. if (stopScanning) {
  1054. return null;
  1055. }
  1056. const mined = await this.getTransaction();
  1057. if (mined && mined.blockNumber != null) {
  1058. return;
  1059. }
  1060. // We were replaced; start scanning for that transaction
  1061. // Starting to scan; look back a few extra blocks for safety
  1062. if (nextScan === -1) {
  1063. nextScan = startBlock - 3;
  1064. if (nextScan < this.#startBlock) {
  1065. nextScan = this.#startBlock;
  1066. }
  1067. }
  1068. while (nextScan <= blockNumber) {
  1069. // Get the next block to scan
  1070. if (stopScanning) {
  1071. return null;
  1072. }
  1073. const block = await this.provider.getBlock(nextScan, true);
  1074. // This should not happen; but we'll try again shortly
  1075. if (block == null) {
  1076. return;
  1077. }
  1078. // We were mined; no replacement
  1079. for (const hash of block) {
  1080. if (hash === this.hash) {
  1081. return;
  1082. }
  1083. }
  1084. // Search for the transaction that replaced us
  1085. for (let i = 0; i < block.length; i++) {
  1086. const tx = await block.getTransaction(i);
  1087. if (tx.from === this.from && tx.nonce === this.nonce) {
  1088. // Get the receipt
  1089. if (stopScanning) {
  1090. return null;
  1091. }
  1092. const receipt = await this.provider.getTransactionReceipt(tx.hash);
  1093. // This should not happen; but we'll try again shortly
  1094. if (receipt == null) {
  1095. return;
  1096. }
  1097. // We will retry this on the next block (this case could be optimized)
  1098. if ((blockNumber - receipt.blockNumber + 1) < confirms) {
  1099. return;
  1100. }
  1101. // The reason we were replaced
  1102. let reason = "replaced";
  1103. if (tx.data === this.data && tx.to === this.to && tx.value === this.value) {
  1104. reason = "repriced";
  1105. }
  1106. else if (tx.data === "0x" && tx.from === tx.to && tx.value === BN_0) {
  1107. reason = "cancelled";
  1108. }
  1109. (0, index_js_1.assert)(false, "transaction was replaced", "TRANSACTION_REPLACED", {
  1110. cancelled: (reason === "replaced" || reason === "cancelled"),
  1111. reason,
  1112. replacement: tx.replaceableTransaction(startBlock),
  1113. hash: tx.hash,
  1114. receipt
  1115. });
  1116. }
  1117. }
  1118. nextScan++;
  1119. }
  1120. return;
  1121. };
  1122. const checkReceipt = (receipt) => {
  1123. if (receipt == null || receipt.status !== 0) {
  1124. return receipt;
  1125. }
  1126. (0, index_js_1.assert)(false, "transaction execution reverted", "CALL_EXCEPTION", {
  1127. action: "sendTransaction",
  1128. data: null, reason: null, invocation: null, revert: null,
  1129. transaction: {
  1130. to: receipt.to,
  1131. from: receipt.from,
  1132. data: "" // @TODO: in v7, split out sendTransaction properties
  1133. }, receipt
  1134. });
  1135. };
  1136. const receipt = await this.provider.getTransactionReceipt(this.hash);
  1137. if (confirms === 0) {
  1138. return checkReceipt(receipt);
  1139. }
  1140. if (receipt) {
  1141. if ((await receipt.confirmations()) >= confirms) {
  1142. return checkReceipt(receipt);
  1143. }
  1144. }
  1145. else {
  1146. // Check for a replacement; throws if a replacement was found
  1147. await checkReplacement();
  1148. // Allow null only when the confirms is 0
  1149. if (confirms === 0) {
  1150. return null;
  1151. }
  1152. }
  1153. const waiter = new Promise((resolve, reject) => {
  1154. // List of things to cancel when we have a result (one way or the other)
  1155. const cancellers = [];
  1156. const cancel = () => { cancellers.forEach((c) => c()); };
  1157. // On cancel, stop scanning for replacements
  1158. cancellers.push(() => { stopScanning = true; });
  1159. // Set up any timeout requested
  1160. if (timeout > 0) {
  1161. const timer = setTimeout(() => {
  1162. cancel();
  1163. reject((0, index_js_1.makeError)("wait for transaction timeout", "TIMEOUT"));
  1164. }, timeout);
  1165. cancellers.push(() => { clearTimeout(timer); });
  1166. }
  1167. const txListener = async (receipt) => {
  1168. // Done; return it!
  1169. if ((await receipt.confirmations()) >= confirms) {
  1170. cancel();
  1171. try {
  1172. resolve(checkReceipt(receipt));
  1173. }
  1174. catch (error) {
  1175. reject(error);
  1176. }
  1177. }
  1178. };
  1179. cancellers.push(() => { this.provider.off(this.hash, txListener); });
  1180. this.provider.on(this.hash, txListener);
  1181. // We support replacement detection; start checking
  1182. if (startBlock >= 0) {
  1183. const replaceListener = async () => {
  1184. try {
  1185. // Check for a replacement; this throws only if one is found
  1186. await checkReplacement();
  1187. }
  1188. catch (error) {
  1189. // We were replaced (with enough confirms); re-throw the error
  1190. if ((0, index_js_1.isError)(error, "TRANSACTION_REPLACED")) {
  1191. cancel();
  1192. reject(error);
  1193. return;
  1194. }
  1195. }
  1196. // Rescheudle a check on the next block
  1197. if (!stopScanning) {
  1198. this.provider.once("block", replaceListener);
  1199. }
  1200. };
  1201. cancellers.push(() => { this.provider.off("block", replaceListener); });
  1202. this.provider.once("block", replaceListener);
  1203. }
  1204. });
  1205. return await waiter;
  1206. }
  1207. /**
  1208. * Returns ``true`` if this transaction has been included.
  1209. *
  1210. * This is effective only as of the time the TransactionResponse
  1211. * was instantiated. To get up-to-date information, use
  1212. * [[getTransaction]].
  1213. *
  1214. * This provides a Type Guard that this transaction will have
  1215. * non-null property values for properties that are null for
  1216. * unmined transactions.
  1217. */
  1218. isMined() {
  1219. return (this.blockHash != null);
  1220. }
  1221. /**
  1222. * Returns true if the transaction is a legacy (i.e. ``type == 0``)
  1223. * transaction.
  1224. *
  1225. * This provides a Type Guard that this transaction will have
  1226. * the ``null``-ness for hardfork-specific properties set correctly.
  1227. */
  1228. isLegacy() {
  1229. return (this.type === 0);
  1230. }
  1231. /**
  1232. * Returns true if the transaction is a Berlin (i.e. ``type == 1``)
  1233. * transaction. See [[link-eip-2070]].
  1234. *
  1235. * This provides a Type Guard that this transaction will have
  1236. * the ``null``-ness for hardfork-specific properties set correctly.
  1237. */
  1238. isBerlin() {
  1239. return (this.type === 1);
  1240. }
  1241. /**
  1242. * Returns true if the transaction is a London (i.e. ``type == 2``)
  1243. * transaction. See [[link-eip-1559]].
  1244. *
  1245. * This provides a Type Guard that this transaction will have
  1246. * the ``null``-ness for hardfork-specific properties set correctly.
  1247. */
  1248. isLondon() {
  1249. return (this.type === 2);
  1250. }
  1251. /**
  1252. * Returns true if hte transaction is a Cancun (i.e. ``type == 3``)
  1253. * transaction. See [[link-eip-4844]].
  1254. */
  1255. isCancun() {
  1256. return (this.type === 3);
  1257. }
  1258. /**
  1259. * Returns a filter which can be used to listen for orphan events
  1260. * that evict this transaction.
  1261. */
  1262. removedEvent() {
  1263. (0, index_js_1.assert)(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" });
  1264. return createRemovedTransactionFilter(this);
  1265. }
  1266. /**
  1267. * Returns a filter which can be used to listen for orphan events
  1268. * that re-order this event against %%other%%.
  1269. */
  1270. reorderedEvent(other) {
  1271. (0, index_js_1.assert)(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" });
  1272. (0, index_js_1.assert)(!other || other.isMined(), "unmined 'other' transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" });
  1273. return createReorderedTransactionFilter(this, other);
  1274. }
  1275. /**
  1276. * Returns a new TransactionResponse instance which has the ability to
  1277. * detect (and throw an error) if the transaction is replaced, which
  1278. * will begin scanning at %%startBlock%%.
  1279. *
  1280. * This should generally not be used by developers and is intended
  1281. * primarily for internal use. Setting an incorrect %%startBlock%% can
  1282. * have devastating performance consequences if used incorrectly.
  1283. */
  1284. replaceableTransaction(startBlock) {
  1285. (0, index_js_1.assertArgument)(Number.isInteger(startBlock) && startBlock >= 0, "invalid startBlock", "startBlock", startBlock);
  1286. const tx = new TransactionResponse(this, this.provider);
  1287. tx.#startBlock = startBlock;
  1288. return tx;
  1289. }
  1290. }
  1291. exports.TransactionResponse = TransactionResponse;
  1292. function createOrphanedBlockFilter(block) {
  1293. return { orphan: "drop-block", hash: block.hash, number: block.number };
  1294. }
  1295. function createReorderedTransactionFilter(tx, other) {
  1296. return { orphan: "reorder-transaction", tx, other };
  1297. }
  1298. function createRemovedTransactionFilter(tx) {
  1299. return { orphan: "drop-transaction", tx };
  1300. }
  1301. function createRemovedLogFilter(log) {
  1302. return { orphan: "drop-log", log: {
  1303. transactionHash: log.transactionHash,
  1304. blockHash: log.blockHash,
  1305. blockNumber: log.blockNumber,
  1306. address: log.address,
  1307. data: log.data,
  1308. topics: Object.freeze(log.topics.slice()),
  1309. index: log.index
  1310. } };
  1311. }
  1312. //# sourceMappingURL=provider.js.map