provider.js 42 KB

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