provider.ts 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114
  1. //import { resolveAddress } from "@ethersproject/address";
  2. import {
  3. defineProperties, getBigInt, getNumber, hexlify, isBytesLike,
  4. resolveProperties,
  5. assert, assertArgument, isError, makeError
  6. } from "../utils/index.js";
  7. import { accessListify } from "../transaction/index.js";
  8. import type { AddressLike, NameResolver } from "../address/index.js";
  9. import type { BigNumberish, EventEmitterable } from "../utils/index.js";
  10. import type { Signature } from "../crypto/index.js";
  11. import type {
  12. AccessList, AccessListish, BlobLike, KzgLibrary, TransactionLike
  13. } from "../transaction/index.js";
  14. import type { ContractRunner } from "./contracts.js";
  15. import type { Network } from "./network.js";
  16. const BN_0 = BigInt(0);
  17. /**
  18. * A **BlockTag** specifies a specific block.
  19. *
  20. * **numeric value** - specifies the block height, where
  21. * the genesis block is block 0; many operations accept a negative
  22. * value which indicates the block number should be deducted from
  23. * the most recent block. A numeric value may be a ``number``, ``bigint``,
  24. * or a decimal of hex string.
  25. *
  26. * **blockhash** - specifies a specific block by its blockhash; this allows
  27. * potentially orphaned blocks to be specifed, without ambiguity, but many
  28. * backends do not support this for some operations.
  29. */
  30. export type BlockTag = BigNumberish | string;
  31. import {
  32. BlockParams, LogParams, TransactionReceiptParams,
  33. TransactionResponseParams
  34. } from "./formatting.js";
  35. // -----------------------
  36. function getValue<T>(value: undefined | null | T): null | T {
  37. if (value == null) { return null; }
  38. return value;
  39. }
  40. function toJson(value: null | bigint): null | string {
  41. if (value == null) { return null; }
  42. return value.toString();
  43. }
  44. // @TODO? <T extends FeeData = { }> implements Required<T>
  45. /**
  46. * A **FeeData** wraps all the fee-related values associated with
  47. * the network.
  48. */
  49. export class FeeData {
  50. /**
  51. * The gas price for legacy networks.
  52. */
  53. readonly gasPrice!: null | bigint;
  54. /**
  55. * The maximum fee to pay per gas.
  56. *
  57. * The base fee per gas is defined by the network and based on
  58. * congestion, increasing the cost during times of heavy load
  59. * and lowering when less busy.
  60. *
  61. * The actual fee per gas will be the base fee for the block
  62. * and the priority fee, up to the max fee per gas.
  63. *
  64. * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559))
  65. */
  66. readonly maxFeePerGas!: null | bigint;
  67. /**
  68. * The additional amout to pay per gas to encourage a validator
  69. * to include the transaction.
  70. *
  71. * The purpose of this is to compensate the validator for the
  72. * adjusted risk for including a given transaction.
  73. *
  74. * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559))
  75. */
  76. readonly maxPriorityFeePerGas!: null | bigint;
  77. /**
  78. * Creates a new FeeData for %%gasPrice%%, %%maxFeePerGas%% and
  79. * %%maxPriorityFeePerGas%%.
  80. */
  81. constructor(gasPrice?: null | bigint, maxFeePerGas?: null | bigint, maxPriorityFeePerGas?: null | bigint) {
  82. defineProperties<FeeData>(this, {
  83. gasPrice: getValue(gasPrice),
  84. maxFeePerGas: getValue(maxFeePerGas),
  85. maxPriorityFeePerGas: getValue(maxPriorityFeePerGas)
  86. });
  87. }
  88. /**
  89. * Returns a JSON-friendly value.
  90. */
  91. toJSON(): any {
  92. const {
  93. gasPrice, maxFeePerGas, maxPriorityFeePerGas
  94. } = this;
  95. return {
  96. _type: "FeeData",
  97. gasPrice: toJson(gasPrice),
  98. maxFeePerGas: toJson(maxFeePerGas),
  99. maxPriorityFeePerGas: toJson(maxPriorityFeePerGas),
  100. };
  101. }
  102. }
  103. /**
  104. * A **TransactionRequest** is a transactions with potentially various
  105. * properties not defined, or with less strict types for its values.
  106. *
  107. * This is used to pass to various operations, which will internally
  108. * coerce any types and populate any necessary values.
  109. */
  110. export interface TransactionRequest {
  111. /**
  112. * The transaction type.
  113. */
  114. type?: null | number;
  115. /**
  116. * The target of the transaction.
  117. */
  118. to?: null | AddressLike;
  119. /**
  120. * The sender of the transaction.
  121. */
  122. from?: null | AddressLike;
  123. /**
  124. * The nonce of the transaction, used to prevent replay attacks.
  125. */
  126. nonce?: null | number;
  127. /**
  128. * The maximum amount of gas to allow this transaction to consume.
  129. */
  130. gasLimit?: null | BigNumberish;
  131. /**
  132. * The gas price to use for legacy transactions or transactions on
  133. * legacy networks.
  134. *
  135. * Most of the time the ``max*FeePerGas`` is preferred.
  136. */
  137. gasPrice?: null | BigNumberish;
  138. /**
  139. * The [[link-eip-1559]] maximum priority fee to pay per gas.
  140. */
  141. maxPriorityFeePerGas?: null | BigNumberish;
  142. /**
  143. * The [[link-eip-1559]] maximum total fee to pay per gas. The actual
  144. * value used is protocol enforced to be the block's base fee.
  145. */
  146. maxFeePerGas?: null | BigNumberish;
  147. /**
  148. * The transaction data.
  149. */
  150. data?: null | string;
  151. /**
  152. * The transaction value (in wei).
  153. */
  154. value?: null | BigNumberish;
  155. /**
  156. * The chain ID for the network this transaction is valid on.
  157. */
  158. chainId?: null | BigNumberish;
  159. /**
  160. * The [[link-eip-2930]] access list. Storage slots included in the access
  161. * list are //warmed// by pre-loading them, so their initial cost to
  162. * fetch is guaranteed, but then each additional access is cheaper.
  163. */
  164. accessList?: null | AccessListish;
  165. /**
  166. * A custom object, which can be passed along for network-specific
  167. * values.
  168. */
  169. customData?: any;
  170. // Only meaningful when used for call
  171. /**
  172. * When using ``call`` or ``estimateGas``, this allows a specific
  173. * block to be queried. Many backends do not support this and when
  174. * unsupported errors are silently squelched and ``"latest"`` is used.
  175. */
  176. blockTag?: BlockTag;
  177. /**
  178. * When using ``call``, this enables CCIP-read, which permits the
  179. * provider to be redirected to web-based content during execution,
  180. * which is then further validated by the contract.
  181. *
  182. * There are potential security implications allowing CCIP-read, as
  183. * it could be used to expose the IP address or user activity during
  184. * the fetch to unexpected parties.
  185. */
  186. enableCcipRead?: boolean;
  187. /**
  188. * The blob versioned hashes (see [[link-eip-4844]]).
  189. */
  190. blobVersionedHashes?: null | Array<string>
  191. /**
  192. * The maximum fee per blob gas (see [[link-eip-4844]]).
  193. */
  194. maxFeePerBlobGas?: null | BigNumberish;
  195. /**
  196. * Any blobs to include in the transaction (see [[link-eip-4844]]).
  197. */
  198. blobs?: null | Array<BlobLike>;
  199. /**
  200. * An external library for computing the KZG commitments and
  201. * proofs necessary for EIP-4844 transactions (see [[link-eip-4844]]).
  202. *
  203. * This is generally ``null``, unless you are creating BLOb
  204. * transactions.
  205. */
  206. kzg?: null | KzgLibrary;
  207. // Todo?
  208. //gasMultiplier?: number;
  209. };
  210. /**
  211. * A **PreparedTransactionRequest** is identical to a [[TransactionRequest]]
  212. * except all the property types are strictly enforced.
  213. */
  214. export interface PreparedTransactionRequest {
  215. /**
  216. * The transaction type.
  217. */
  218. type?: number;
  219. /**
  220. * The target of the transaction.
  221. */
  222. to?: AddressLike;
  223. /**
  224. * The sender of the transaction.
  225. */
  226. from?: AddressLike;
  227. /**
  228. * The nonce of the transaction, used to prevent replay attacks.
  229. */
  230. nonce?: number;
  231. /**
  232. * The maximum amount of gas to allow this transaction to consime.
  233. */
  234. gasLimit?: bigint;
  235. /**
  236. * The gas price to use for legacy transactions or transactions on
  237. * legacy networks.
  238. *
  239. * Most of the time the ``max*FeePerGas`` is preferred.
  240. */
  241. gasPrice?: bigint;
  242. /**
  243. * The [[link-eip-1559]] maximum priority fee to pay per gas.
  244. */
  245. maxPriorityFeePerGas?: bigint;
  246. /**
  247. * The [[link-eip-1559]] maximum total fee to pay per gas. The actual
  248. * value used is protocol enforced to be the block's base fee.
  249. */
  250. maxFeePerGas?: bigint;
  251. /**
  252. * The transaction data.
  253. */
  254. data?: string;
  255. /**
  256. * The transaction value (in wei).
  257. */
  258. value?: bigint;
  259. /**
  260. * The chain ID for the network this transaction is valid on.
  261. */
  262. chainId?: bigint;
  263. /**
  264. * The [[link-eip-2930]] access list. Storage slots included in the access
  265. * list are //warmed// by pre-loading them, so their initial cost to
  266. * fetch is guaranteed, but then each additional access is cheaper.
  267. */
  268. accessList?: AccessList;
  269. /**
  270. * A custom object, which can be passed along for network-specific
  271. * values.
  272. */
  273. customData?: any;
  274. /**
  275. * When using ``call`` or ``estimateGas``, this allows a specific
  276. * block to be queried. Many backends do not support this and when
  277. * unsupported errors are silently squelched and ``"latest"`` is used.
  278. */
  279. blockTag?: BlockTag;
  280. /**
  281. * When using ``call``, this enables CCIP-read, which permits the
  282. * provider to be redirected to web-based content during execution,
  283. * which is then further validated by the contract.
  284. *
  285. * There are potential security implications allowing CCIP-read, as
  286. * it could be used to expose the IP address or user activity during
  287. * the fetch to unexpected parties.
  288. */
  289. enableCcipRead?: boolean;
  290. }
  291. /**
  292. * Returns a copy of %%req%% with all properties coerced to their strict
  293. * types.
  294. */
  295. export function copyRequest(req: TransactionRequest): PreparedTransactionRequest {
  296. const result: any = { };
  297. // These could be addresses, ENS names or Addressables
  298. if (req.to) { result.to = req.to; }
  299. if (req.from) { result.from = req.from; }
  300. if (req.data) { result.data = hexlify(req.data); }
  301. const bigIntKeys = "chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);
  302. for (const key of bigIntKeys) {
  303. if (!(key in req) || (<any>req)[key] == null) { continue; }
  304. result[key] = getBigInt((<any>req)[key], `request.${ key }`);
  305. }
  306. const numberKeys = "type,nonce".split(/,/);
  307. for (const key of numberKeys) {
  308. if (!(key in req) || (<any>req)[key] == null) { continue; }
  309. result[key] = getNumber((<any>req)[key], `request.${ key }`);
  310. }
  311. if (req.accessList) {
  312. result.accessList = accessListify(req.accessList);
  313. }
  314. if ("blockTag" in req) { result.blockTag = req.blockTag; }
  315. if ("enableCcipRead" in req) {
  316. result.enableCcipRead = !!req.enableCcipRead
  317. }
  318. if ("customData" in req) {
  319. result.customData = req.customData;
  320. }
  321. if ("blobVersionedHashes" in req && req.blobVersionedHashes) {
  322. result.blobVersionedHashes = req.blobVersionedHashes.slice();
  323. }
  324. if ("kzg" in req) { result.kzg = req.kzg; }
  325. if ("blobs" in req && req.blobs) {
  326. result.blobs = req.blobs.map((b) => {
  327. if (isBytesLike(b)) { return hexlify(b); }
  328. return Object.assign({ }, b);
  329. });
  330. }
  331. return result;
  332. }
  333. //////////////////////
  334. // Block
  335. /**
  336. * An Interface to indicate a [[Block]] has been included in the
  337. * blockchain. This asserts a Type Guard that necessary properties
  338. * are non-null.
  339. *
  340. * Before a block is included, it is a //pending// block.
  341. */
  342. export interface MinedBlock extends Block {
  343. /**
  344. * The block number also known as the block height.
  345. */
  346. readonly number: number;
  347. /**
  348. * The block hash.
  349. */
  350. readonly hash: string;
  351. /**
  352. * The block timestamp, in seconds from epoch.
  353. */
  354. readonly timestamp: number;
  355. /**
  356. * The block date, created from the [[timestamp]].
  357. */
  358. readonly date: Date;
  359. /**
  360. * The miner of the block, also known as the ``author`` or
  361. * block ``producer``.
  362. */
  363. readonly miner: string;
  364. }
  365. /**
  366. * A **Block** represents the data associated with a full block on
  367. * Ethereum.
  368. */
  369. export class Block implements BlockParams, Iterable<string> {
  370. /**
  371. * The provider connected to the block used to fetch additional details
  372. * if necessary.
  373. */
  374. readonly provider!: Provider;
  375. /**
  376. * The block number, sometimes called the block height. This is a
  377. * sequential number that is one higher than the parent block.
  378. */
  379. readonly number!: number;
  380. /**
  381. * The block hash.
  382. *
  383. * This hash includes all properties, so can be safely used to identify
  384. * an exact set of block properties.
  385. */
  386. readonly hash!: null | string;
  387. /**
  388. * The timestamp for this block, which is the number of seconds since
  389. * epoch that this block was included.
  390. */
  391. readonly timestamp!: number;
  392. /**
  393. * The block hash of the parent block.
  394. */
  395. readonly parentHash!: string;
  396. /**
  397. * The hash tree root of the parent beacon block for the given
  398. * execution block. See [[link-eip-4788]].
  399. */
  400. parentBeaconBlockRoot!: null | string;
  401. /**
  402. * The nonce.
  403. *
  404. * On legacy networks, this is the random number inserted which
  405. * permitted the difficulty target to be reached.
  406. */
  407. readonly nonce!: string;
  408. /**
  409. * The difficulty target.
  410. *
  411. * On legacy networks, this is the proof-of-work target required
  412. * for a block to meet the protocol rules to be included.
  413. *
  414. * On modern networks, this is a random number arrived at using
  415. * randao. @TODO: Find links?
  416. */
  417. readonly difficulty!: bigint;
  418. /**
  419. * The total gas limit for this block.
  420. */
  421. readonly gasLimit!: bigint;
  422. /**
  423. * The total gas used in this block.
  424. */
  425. readonly gasUsed!: bigint;
  426. /**
  427. * The root hash for the global state after applying changes
  428. * in this block.
  429. */
  430. readonly stateRoot!: null | string;
  431. /**
  432. * The hash of the transaction receipts trie.
  433. */
  434. readonly receiptsRoot!: null | string;
  435. /**
  436. * The total amount of blob gas consumed by the transactions
  437. * within the block. See [[link-eip-4844]].
  438. */
  439. readonly blobGasUsed!: null | bigint;
  440. /**
  441. * The running total of blob gas consumed in excess of the
  442. * target, prior to the block. See [[link-eip-4844]].
  443. */
  444. readonly excessBlobGas!: null | bigint;
  445. /**
  446. * The miner coinbase address, wihch receives any subsidies for
  447. * including this block.
  448. */
  449. readonly miner!: string;
  450. /**
  451. * The latest RANDAO mix of the post beacon state of
  452. * the previous block.
  453. */
  454. readonly prevRandao!: null | string;
  455. /**
  456. * Any extra data the validator wished to include.
  457. */
  458. readonly extraData!: string;
  459. /**
  460. * The base fee per gas that all transactions in this block were
  461. * charged.
  462. *
  463. * This adjusts after each block, depending on how congested the network
  464. * is.
  465. */
  466. readonly baseFeePerGas!: null | bigint;
  467. readonly #transactions: Array<string | TransactionResponse>;
  468. /**
  469. * Create a new **Block** object.
  470. *
  471. * This should generally not be necessary as the unless implementing a
  472. * low-level library.
  473. */
  474. constructor(block: BlockParams, provider: Provider) {
  475. this.#transactions = block.transactions.map((tx) => {
  476. if (typeof(tx) !== "string") {
  477. return new TransactionResponse(tx, provider);
  478. }
  479. return tx;
  480. });
  481. defineProperties<Block>(this, {
  482. provider,
  483. hash: getValue(block.hash),
  484. number: block.number,
  485. timestamp: block.timestamp,
  486. parentHash: block.parentHash,
  487. parentBeaconBlockRoot: block.parentBeaconBlockRoot,
  488. nonce: block.nonce,
  489. difficulty: block.difficulty,
  490. gasLimit: block.gasLimit,
  491. gasUsed: block.gasUsed,
  492. blobGasUsed: block.blobGasUsed,
  493. excessBlobGas: block.excessBlobGas,
  494. miner: block.miner,
  495. prevRandao: getValue(block.prevRandao),
  496. extraData: block.extraData,
  497. baseFeePerGas: getValue(block.baseFeePerGas),
  498. stateRoot: block.stateRoot,
  499. receiptsRoot: block.receiptsRoot,
  500. });
  501. }
  502. /**
  503. * Returns the list of transaction hashes, in the order
  504. * they were executed within the block.
  505. */
  506. get transactions(): ReadonlyArray<string> {
  507. return this.#transactions.map((tx) => {
  508. if (typeof(tx) === "string") { return tx; }
  509. return tx.hash;
  510. });
  511. }
  512. /**
  513. * Returns the complete transactions, in the order they
  514. * were executed within the block.
  515. *
  516. * This is only available for blocks which prefetched
  517. * transactions, by passing ``true`` to %%prefetchTxs%%
  518. * into [[Provider-getBlock]].
  519. */
  520. get prefetchedTransactions(): Array<TransactionResponse> {
  521. const txs = this.#transactions.slice();
  522. // Doesn't matter...
  523. if (txs.length === 0) { return [ ]; }
  524. // Make sure we prefetched the transactions
  525. assert(typeof(txs[0]) === "object", "transactions were not prefetched with block request", "UNSUPPORTED_OPERATION", {
  526. operation: "transactionResponses()"
  527. });
  528. return <Array<TransactionResponse>>txs;
  529. }
  530. /**
  531. * Returns a JSON-friendly value.
  532. */
  533. toJSON(): any {
  534. const {
  535. baseFeePerGas, difficulty, extraData, gasLimit, gasUsed, hash,
  536. miner, prevRandao, nonce, number, parentHash, parentBeaconBlockRoot,
  537. stateRoot, receiptsRoot, timestamp, transactions
  538. } = this;
  539. return {
  540. _type: "Block",
  541. baseFeePerGas: toJson(baseFeePerGas),
  542. difficulty: toJson(difficulty),
  543. extraData,
  544. gasLimit: toJson(gasLimit),
  545. gasUsed: toJson(gasUsed),
  546. blobGasUsed: toJson(this.blobGasUsed),
  547. excessBlobGas: toJson(this.excessBlobGas),
  548. hash, miner, prevRandao, nonce, number, parentHash, timestamp,
  549. parentBeaconBlockRoot, stateRoot, receiptsRoot,
  550. transactions,
  551. };
  552. }
  553. [Symbol.iterator](): Iterator<string> {
  554. let index = 0;
  555. const txs = this.transactions;
  556. return {
  557. next: () => {
  558. if (index < this.length) {
  559. return {
  560. value: txs[index++], done: false
  561. }
  562. }
  563. return { value: undefined, done: true };
  564. }
  565. };
  566. }
  567. /**
  568. * The number of transactions in this block.
  569. */
  570. get length(): number { return this.#transactions.length; }
  571. /**
  572. * The [[link-js-date]] this block was included at.
  573. */
  574. get date(): null | Date {
  575. if (this.timestamp == null) { return null; }
  576. return new Date(this.timestamp * 1000);
  577. }
  578. /**
  579. * Get the transaction at %%indexe%% within this block.
  580. */
  581. async getTransaction(indexOrHash: number | string): Promise<TransactionResponse> {
  582. // Find the internal value by its index or hash
  583. let tx: string | TransactionResponse | undefined = undefined;
  584. if (typeof(indexOrHash) === "number") {
  585. tx = this.#transactions[indexOrHash];
  586. } else {
  587. const hash = indexOrHash.toLowerCase();
  588. for (const v of this.#transactions) {
  589. if (typeof(v) === "string") {
  590. if (v !== hash) { continue; }
  591. tx = v;
  592. break;
  593. } else {
  594. if (v.hash !== hash) { continue; }
  595. tx = v;
  596. break;
  597. }
  598. }
  599. }
  600. if (tx == null) { throw new Error("no such tx"); }
  601. if (typeof(tx) === "string") {
  602. return <TransactionResponse>(await this.provider.getTransaction(tx));
  603. } else {
  604. return tx;
  605. }
  606. }
  607. /**
  608. * If a **Block** was fetched with a request to include the transactions
  609. * this will allow synchronous access to those transactions.
  610. *
  611. * If the transactions were not prefetched, this will throw.
  612. */
  613. getPrefetchedTransaction(indexOrHash: number | string): TransactionResponse {
  614. const txs = this.prefetchedTransactions;
  615. if (typeof(indexOrHash) === "number") {
  616. return txs[indexOrHash];
  617. }
  618. indexOrHash = indexOrHash.toLowerCase();
  619. for (const tx of txs) {
  620. if (tx.hash === indexOrHash) { return tx; }
  621. }
  622. assertArgument(false, "no matching transaction", "indexOrHash", indexOrHash);
  623. }
  624. /**
  625. * Returns true if this block been mined. This provides a type guard
  626. * for all properties on a [[MinedBlock]].
  627. */
  628. isMined(): this is MinedBlock { return !!this.hash; }
  629. /**
  630. * Returns true if this block is an [[link-eip-2930]] block.
  631. */
  632. isLondon(): this is (Block & { baseFeePerGas: bigint }) {
  633. return !!this.baseFeePerGas;
  634. }
  635. /**
  636. * @_ignore:
  637. */
  638. orphanedEvent(): OrphanFilter {
  639. if (!this.isMined()) { throw new Error(""); }
  640. return createOrphanedBlockFilter(this);
  641. }
  642. }
  643. //////////////////////
  644. // Log
  645. /**
  646. * A **Log** in Ethereum represents an event that has been included in a
  647. * transaction using the ``LOG*`` opcodes, which are most commonly used by
  648. * Solidity's emit for announcing events.
  649. */
  650. export class Log implements LogParams {
  651. /**
  652. * The provider connected to the log used to fetch additional details
  653. * if necessary.
  654. */
  655. readonly provider: Provider;
  656. /**
  657. * The transaction hash of the transaction this log occurred in. Use the
  658. * [[Log-getTransaction]] to get the [[TransactionResponse]].
  659. */
  660. readonly transactionHash!: string;
  661. /**
  662. * The block hash of the block this log occurred in. Use the
  663. * [[Log-getBlock]] to get the [[Block]].
  664. */
  665. readonly blockHash!: string;
  666. /**
  667. * The block number of the block this log occurred in. It is preferred
  668. * to use the [[Block-hash]] when fetching the related [[Block]],
  669. * since in the case of an orphaned block, the block at that height may
  670. * have changed.
  671. */
  672. readonly blockNumber!: number;
  673. /**
  674. * If the **Log** represents a block that was removed due to an orphaned
  675. * block, this will be true.
  676. *
  677. * This can only happen within an orphan event listener.
  678. */
  679. readonly removed!: boolean;
  680. /**
  681. * The address of the contract that emitted this log.
  682. */
  683. readonly address!: string;
  684. /**
  685. * The data included in this log when it was emitted.
  686. */
  687. readonly data!: string;
  688. /**
  689. * The indexed topics included in this log when it was emitted.
  690. *
  691. * All topics are included in the bloom filters, so they can be
  692. * efficiently filtered using the [[Provider-getLogs]] method.
  693. */
  694. readonly topics!: ReadonlyArray<string>;
  695. /**
  696. * The index within the block this log occurred at. This is generally
  697. * not useful to developers, but can be used with the various roots
  698. * to proof inclusion within a block.
  699. */
  700. readonly index!: number;
  701. /**
  702. * The index within the transaction of this log.
  703. */
  704. readonly transactionIndex!: number;
  705. /**
  706. * @_ignore:
  707. */
  708. constructor(log: LogParams, provider: Provider) {
  709. this.provider = provider;
  710. const topics = Object.freeze(log.topics.slice());
  711. defineProperties<Log>(this, {
  712. transactionHash: log.transactionHash,
  713. blockHash: log.blockHash,
  714. blockNumber: log.blockNumber,
  715. removed: log.removed,
  716. address: log.address,
  717. data: log.data,
  718. topics,
  719. index: log.index,
  720. transactionIndex: log.transactionIndex,
  721. });
  722. }
  723. /**
  724. * Returns a JSON-compatible object.
  725. */
  726. toJSON(): any {
  727. const {
  728. address, blockHash, blockNumber, data, index,
  729. removed, topics, transactionHash, transactionIndex
  730. } = this;
  731. return {
  732. _type: "log",
  733. address, blockHash, blockNumber, data, index,
  734. removed, topics, transactionHash, transactionIndex
  735. };
  736. }
  737. /**
  738. * Returns the block that this log occurred in.
  739. */
  740. async getBlock(): Promise<Block> {
  741. const block = await this.provider.getBlock(this.blockHash);
  742. assert(!!block, "failed to find transaction", "UNKNOWN_ERROR", { });
  743. return block;
  744. }
  745. /**
  746. * Returns the transaction that this log occurred in.
  747. */
  748. async getTransaction(): Promise<TransactionResponse> {
  749. const tx = await this.provider.getTransaction(this.transactionHash);
  750. assert(!!tx, "failed to find transaction", "UNKNOWN_ERROR", { });
  751. return tx;
  752. }
  753. /**
  754. * Returns the transaction receipt fot the transaction that this
  755. * log occurred in.
  756. */
  757. async getTransactionReceipt(): Promise<TransactionReceipt> {
  758. const receipt = await this.provider.getTransactionReceipt(this.transactionHash);
  759. assert(!!receipt, "failed to find transaction receipt", "UNKNOWN_ERROR", { });
  760. return receipt;
  761. }
  762. /**
  763. * @_ignore:
  764. */
  765. removedEvent(): OrphanFilter {
  766. return createRemovedLogFilter(this);
  767. }
  768. }
  769. //////////////////////
  770. // Transaction Receipt
  771. /*
  772. export interface LegacyTransactionReceipt {
  773. byzantium: false;
  774. status: null;
  775. root: string;
  776. }
  777. export interface ByzantiumTransactionReceipt {
  778. byzantium: true;
  779. status: number;
  780. root: null;
  781. }
  782. */
  783. /**
  784. * A **TransactionReceipt** includes additional information about a
  785. * transaction that is only available after it has been mined.
  786. */
  787. export class TransactionReceipt implements TransactionReceiptParams, Iterable<Log> {
  788. /**
  789. * The provider connected to the log used to fetch additional details
  790. * if necessary.
  791. */
  792. readonly provider!: Provider;
  793. /**
  794. * The address the transaction was sent to.
  795. */
  796. readonly to!: null | string;
  797. /**
  798. * The sender of the transaction.
  799. */
  800. readonly from!: string;
  801. /**
  802. * The address of the contract if the transaction was directly
  803. * responsible for deploying one.
  804. *
  805. * This is non-null **only** if the ``to`` is empty and the ``data``
  806. * was successfully executed as initcode.
  807. */
  808. readonly contractAddress!: null | string;
  809. /**
  810. * The transaction hash.
  811. */
  812. readonly hash!: string;
  813. /**
  814. * The index of this transaction within the block transactions.
  815. */
  816. readonly index!: number;
  817. /**
  818. * The block hash of the [[Block]] this transaction was included in.
  819. */
  820. readonly blockHash!: string;
  821. /**
  822. * The block number of the [[Block]] this transaction was included in.
  823. */
  824. readonly blockNumber!: number;
  825. /**
  826. * The bloom filter bytes that represent all logs that occurred within
  827. * this transaction. This is generally not useful for most developers,
  828. * but can be used to validate the included logs.
  829. */
  830. readonly logsBloom!: string;
  831. /**
  832. * The actual amount of gas used by this transaction.
  833. *
  834. * When creating a transaction, the amount of gas that will be used can
  835. * only be approximated, but the sender must pay the gas fee for the
  836. * entire gas limit. After the transaction, the difference is refunded.
  837. */
  838. readonly gasUsed!: bigint;
  839. /**
  840. * The gas used for BLObs. See [[link-eip-4844]].
  841. */
  842. readonly blobGasUsed!: null | bigint;
  843. /**
  844. * The amount of gas used by all transactions within the block for this
  845. * and all transactions with a lower ``index``.
  846. *
  847. * This is generally not useful for developers but can be used to
  848. * validate certain aspects of execution.
  849. */
  850. readonly cumulativeGasUsed!: bigint;
  851. /**
  852. * The actual gas price used during execution.
  853. *
  854. * Due to the complexity of [[link-eip-1559]] this value can only
  855. * be caluclated after the transaction has been mined, snce the base
  856. * fee is protocol-enforced.
  857. */
  858. readonly gasPrice!: bigint;
  859. /**
  860. * The price paid per BLOB in gas. See [[link-eip-4844]].
  861. */
  862. readonly blobGasPrice!: null | bigint;
  863. /**
  864. * The [[link-eip-2718]] transaction type.
  865. */
  866. readonly type!: number;
  867. //readonly byzantium!: boolean;
  868. /**
  869. * The status of this transaction, indicating success (i.e. ``1``) or
  870. * a revert (i.e. ``0``).
  871. *
  872. * This is available in post-byzantium blocks, but some backends may
  873. * backfill this value.
  874. */
  875. readonly status!: null | number;
  876. /**
  877. * The root hash of this transaction.
  878. *
  879. * This is no present and was only included in pre-byzantium blocks, but
  880. * could be used to validate certain parts of the receipt.
  881. */
  882. readonly root!: null | string;
  883. readonly #logs: ReadonlyArray<Log>;
  884. /**
  885. * @_ignore:
  886. */
  887. constructor(tx: TransactionReceiptParams, provider: Provider) {
  888. this.#logs = Object.freeze(tx.logs.map((log) => {
  889. return new Log(log, provider);
  890. }));
  891. let gasPrice = BN_0;
  892. if (tx.effectiveGasPrice != null) {
  893. gasPrice = tx.effectiveGasPrice;
  894. } else if (tx.gasPrice != null) {
  895. gasPrice = tx.gasPrice;
  896. }
  897. defineProperties<TransactionReceipt>(this, {
  898. provider,
  899. to: tx.to,
  900. from: tx.from,
  901. contractAddress: tx.contractAddress,
  902. hash: tx.hash,
  903. index: tx.index,
  904. blockHash: tx.blockHash,
  905. blockNumber: tx.blockNumber,
  906. logsBloom: tx.logsBloom,
  907. gasUsed: tx.gasUsed,
  908. cumulativeGasUsed: tx.cumulativeGasUsed,
  909. blobGasUsed: tx.blobGasUsed,
  910. gasPrice,
  911. blobGasPrice: tx.blobGasPrice,
  912. type: tx.type,
  913. //byzantium: tx.byzantium,
  914. status: tx.status,
  915. root: tx.root
  916. });
  917. }
  918. /**
  919. * The logs for this transaction.
  920. */
  921. get logs(): ReadonlyArray<Log> { return this.#logs; }
  922. /**
  923. * Returns a JSON-compatible representation.
  924. */
  925. toJSON(): any {
  926. const {
  927. to, from, contractAddress, hash, index,
  928. blockHash, blockNumber, logsBloom,
  929. logs, //byzantium,
  930. status, root
  931. } = this;
  932. return {
  933. _type: "TransactionReceipt",
  934. blockHash, blockNumber,
  935. //byzantium,
  936. contractAddress,
  937. cumulativeGasUsed: toJson(this.cumulativeGasUsed),
  938. from,
  939. gasPrice: toJson(this.gasPrice),
  940. blobGasUsed: toJson(this.blobGasUsed),
  941. blobGasPrice: toJson(this.blobGasPrice),
  942. gasUsed: toJson(this.gasUsed),
  943. hash, index, logs, logsBloom, root, status, to
  944. };
  945. }
  946. /**
  947. * @_ignore:
  948. */
  949. get length(): number { return this.logs.length; }
  950. [Symbol.iterator](): Iterator<Log> {
  951. let index = 0;
  952. return {
  953. next: () => {
  954. if (index < this.length) {
  955. return { value: this.logs[index++], done: false }
  956. }
  957. return { value: undefined, done: true };
  958. }
  959. };
  960. }
  961. /**
  962. * The total fee for this transaction, in wei.
  963. */
  964. get fee(): bigint {
  965. return this.gasUsed * this.gasPrice;
  966. }
  967. /**
  968. * Resolves to the block this transaction occurred in.
  969. */
  970. async getBlock(): Promise<Block> {
  971. const block = await this.provider.getBlock(this.blockHash);
  972. if (block == null) { throw new Error("TODO"); }
  973. return block;
  974. }
  975. /**
  976. * Resolves to the transaction this transaction occurred in.
  977. */
  978. async getTransaction(): Promise<TransactionResponse> {
  979. const tx = await this.provider.getTransaction(this.hash);
  980. if (tx == null) { throw new Error("TODO"); }
  981. return tx;
  982. }
  983. /**
  984. * Resolves to the return value of the execution of this transaction.
  985. *
  986. * Support for this feature is limited, as it requires an archive node
  987. * with the ``debug_`` or ``trace_`` API enabled.
  988. */
  989. async getResult(): Promise<string> {
  990. return <string>(await this.provider.getTransactionResult(this.hash));
  991. }
  992. /**
  993. * Resolves to the number of confirmations this transaction has.
  994. */
  995. async confirmations(): Promise<number> {
  996. return (await this.provider.getBlockNumber()) - this.blockNumber + 1;
  997. }
  998. /**
  999. * @_ignore:
  1000. */
  1001. removedEvent(): OrphanFilter {
  1002. return createRemovedTransactionFilter(this);
  1003. }
  1004. /**
  1005. * @_ignore:
  1006. */
  1007. reorderedEvent(other?: TransactionResponse): OrphanFilter {
  1008. assert(!other || other.isMined(), "unmined 'other' transction cannot be orphaned",
  1009. "UNSUPPORTED_OPERATION", { operation: "reorderedEvent(other)" });
  1010. return createReorderedTransactionFilter(this, other);
  1011. }
  1012. }
  1013. //////////////////////
  1014. // Transaction Response
  1015. /**
  1016. * A **MinedTransactionResponse** is an interface representing a
  1017. * transaction which has been mined and allows for a type guard for its
  1018. * property values being defined.
  1019. */
  1020. export interface MinedTransactionResponse extends TransactionResponse {
  1021. /**
  1022. * The block number this transaction occurred in.
  1023. */
  1024. blockNumber: number;
  1025. /**
  1026. * The block hash this transaction occurred in.
  1027. */
  1028. blockHash: string;
  1029. /**
  1030. * The date this transaction occurred on.
  1031. */
  1032. date: Date;
  1033. }
  1034. /**
  1035. * A **TransactionResponse** includes all properties about a transaction
  1036. * that was sent to the network, which may or may not be included in a
  1037. * block.
  1038. *
  1039. * The [[TransactionResponse-isMined]] can be used to check if the
  1040. * transaction has been mined as well as type guard that the otherwise
  1041. * possibly ``null`` properties are defined.
  1042. */
  1043. export class TransactionResponse implements TransactionLike<string>, TransactionResponseParams {
  1044. /**
  1045. * The provider this is connected to, which will influence how its
  1046. * methods will resolve its async inspection methods.
  1047. */
  1048. readonly provider: Provider;
  1049. /**
  1050. * The block number of the block that this transaction was included in.
  1051. *
  1052. * This is ``null`` for pending transactions.
  1053. */
  1054. readonly blockNumber: null | number;
  1055. /**
  1056. * The blockHash of the block that this transaction was included in.
  1057. *
  1058. * This is ``null`` for pending transactions.
  1059. */
  1060. readonly blockHash: null | string;
  1061. /**
  1062. * The index within the block that this transaction resides at.
  1063. */
  1064. readonly index!: number;
  1065. /**
  1066. * The transaction hash.
  1067. */
  1068. readonly hash!: string;
  1069. /**
  1070. * The [[link-eip-2718]] transaction envelope type. This is
  1071. * ``0`` for legacy transactions types.
  1072. */
  1073. readonly type!: number;
  1074. /**
  1075. * The receiver of this transaction.
  1076. *
  1077. * If ``null``, then the transaction is an initcode transaction.
  1078. * This means the result of executing the [[data]] will be deployed
  1079. * as a new contract on chain (assuming it does not revert) and the
  1080. * address may be computed using [[getCreateAddress]].
  1081. */
  1082. readonly to!: null | string;
  1083. /**
  1084. * The sender of this transaction. It is implicitly computed
  1085. * from the transaction pre-image hash (as the digest) and the
  1086. * [[signature]] using ecrecover.
  1087. */
  1088. readonly from!: string;
  1089. /**
  1090. * The nonce, which is used to prevent replay attacks and offer
  1091. * a method to ensure transactions from a given sender are explicitly
  1092. * ordered.
  1093. *
  1094. * When sending a transaction, this must be equal to the number of
  1095. * transactions ever sent by [[from]].
  1096. */
  1097. readonly nonce!: number;
  1098. /**
  1099. * The maximum units of gas this transaction can consume. If execution
  1100. * exceeds this, the entries transaction is reverted and the sender
  1101. * is charged for the full amount, despite not state changes being made.
  1102. */
  1103. readonly gasLimit!: bigint;
  1104. /**
  1105. * The gas price can have various values, depending on the network.
  1106. *
  1107. * In modern networks, for transactions that are included this is
  1108. * the //effective gas price// (the fee per gas that was actually
  1109. * charged), while for transactions that have not been included yet
  1110. * is the [[maxFeePerGas]].
  1111. *
  1112. * For legacy transactions, or transactions on legacy networks, this
  1113. * is the fee that will be charged per unit of gas the transaction
  1114. * consumes.
  1115. */
  1116. readonly gasPrice!: bigint;
  1117. /**
  1118. * The maximum priority fee (per unit of gas) to allow a
  1119. * validator to charge the sender. This is inclusive of the
  1120. * [[maxFeeFeePerGas]].
  1121. */
  1122. readonly maxPriorityFeePerGas!: null | bigint;
  1123. /**
  1124. * The maximum fee (per unit of gas) to allow this transaction
  1125. * to charge the sender.
  1126. */
  1127. readonly maxFeePerGas!: null | bigint;
  1128. /**
  1129. * The [[link-eip-4844]] max fee per BLOb gas.
  1130. */
  1131. readonly maxFeePerBlobGas!: null | bigint;
  1132. /**
  1133. * The data.
  1134. */
  1135. readonly data!: string;
  1136. /**
  1137. * The value, in wei. Use [[formatEther]] to format this value
  1138. * as ether.
  1139. */
  1140. readonly value!: bigint;
  1141. /**
  1142. * The chain ID.
  1143. */
  1144. readonly chainId!: bigint;
  1145. /**
  1146. * The signature.
  1147. */
  1148. readonly signature!: Signature;
  1149. /**
  1150. * The [[link-eip-2930]] access list for transaction types that
  1151. * support it, otherwise ``null``.
  1152. */
  1153. readonly accessList!: null | AccessList;
  1154. /**
  1155. * The [[link-eip-4844]] BLOb versioned hashes.
  1156. */
  1157. readonly blobVersionedHashes!: null | Array<string>;
  1158. #startBlock: number;
  1159. /**
  1160. * @_ignore:
  1161. */
  1162. constructor(tx: TransactionResponseParams, provider: Provider) {
  1163. this.provider = provider;
  1164. this.blockNumber = (tx.blockNumber != null) ? tx.blockNumber: null;
  1165. this.blockHash = (tx.blockHash != null) ? tx.blockHash: null;
  1166. this.hash = tx.hash;
  1167. this.index = tx.index;
  1168. this.type = tx.type;
  1169. this.from = tx.from;
  1170. this.to = tx.to || null;
  1171. this.gasLimit = tx.gasLimit;
  1172. this.nonce = tx.nonce;
  1173. this.data = tx.data;
  1174. this.value = tx.value;
  1175. this.gasPrice = tx.gasPrice;
  1176. this.maxPriorityFeePerGas = (tx.maxPriorityFeePerGas != null) ? tx.maxPriorityFeePerGas: null;
  1177. this.maxFeePerGas = (tx.maxFeePerGas != null) ? tx.maxFeePerGas: null;
  1178. this.maxFeePerBlobGas = (tx.maxFeePerBlobGas != null) ? tx.maxFeePerBlobGas: null;
  1179. this.chainId = tx.chainId;
  1180. this.signature = tx.signature;
  1181. this.accessList = (tx.accessList != null) ? tx.accessList: null;
  1182. this.blobVersionedHashes = (tx.blobVersionedHashes != null) ? tx.blobVersionedHashes: null;
  1183. this.#startBlock = -1;
  1184. }
  1185. /**
  1186. * Returns a JSON-compatible representation of this transaction.
  1187. */
  1188. toJSON(): any {
  1189. const {
  1190. blockNumber, blockHash, index, hash, type, to, from, nonce,
  1191. data, signature, accessList, blobVersionedHashes
  1192. } = this;
  1193. return {
  1194. _type: "TransactionResponse",
  1195. accessList, blockNumber, blockHash,
  1196. blobVersionedHashes,
  1197. chainId: toJson(this.chainId),
  1198. data, from,
  1199. gasLimit: toJson(this.gasLimit),
  1200. gasPrice: toJson(this.gasPrice),
  1201. hash,
  1202. maxFeePerGas: toJson(this.maxFeePerGas),
  1203. maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas),
  1204. maxFeePerBlobGas: toJson(this.maxFeePerBlobGas),
  1205. nonce, signature, to, index, type,
  1206. value: toJson(this.value),
  1207. };
  1208. }
  1209. /**
  1210. * Resolves to the Block that this transaction was included in.
  1211. *
  1212. * This will return null if the transaction has not been included yet.
  1213. */
  1214. async getBlock(): Promise<null | Block> {
  1215. let blockNumber = this.blockNumber;
  1216. if (blockNumber == null) {
  1217. const tx = await this.getTransaction();
  1218. if (tx) { blockNumber = tx.blockNumber; }
  1219. }
  1220. if (blockNumber == null) { return null; }
  1221. const block = this.provider.getBlock(blockNumber);
  1222. if (block == null) { throw new Error("TODO"); }
  1223. return block;
  1224. }
  1225. /**
  1226. * Resolves to this transaction being re-requested from the
  1227. * provider. This can be used if you have an unmined transaction
  1228. * and wish to get an up-to-date populated instance.
  1229. */
  1230. async getTransaction(): Promise<null | TransactionResponse> {
  1231. return this.provider.getTransaction(this.hash);
  1232. }
  1233. /**
  1234. * Resolve to the number of confirmations this transaction has.
  1235. */
  1236. async confirmations(): Promise<number> {
  1237. if (this.blockNumber == null) {
  1238. const { tx, blockNumber } = await resolveProperties({
  1239. tx: this.getTransaction(),
  1240. blockNumber: this.provider.getBlockNumber()
  1241. });
  1242. // Not mined yet...
  1243. if (tx == null || tx.blockNumber == null) { return 0; }
  1244. return blockNumber - tx.blockNumber + 1;
  1245. }
  1246. const blockNumber = await this.provider.getBlockNumber();
  1247. return blockNumber - this.blockNumber + 1;
  1248. }
  1249. /**
  1250. * Resolves once this transaction has been mined and has
  1251. * %%confirms%% blocks including it (default: ``1``) with an
  1252. * optional %%timeout%%.
  1253. *
  1254. * This can resolve to ``null`` only if %%confirms%% is ``0``
  1255. * and the transaction has not been mined, otherwise this will
  1256. * wait until enough confirmations have completed.
  1257. */
  1258. async wait(_confirms?: number, _timeout?: number): Promise<null | TransactionReceipt> {
  1259. const confirms = (_confirms == null) ? 1: _confirms;
  1260. const timeout = (_timeout == null) ? 0: _timeout;
  1261. let startBlock = this.#startBlock
  1262. let nextScan = -1;
  1263. let stopScanning = (startBlock === -1) ? true: false;
  1264. const checkReplacement = async () => {
  1265. // Get the current transaction count for this sender
  1266. if (stopScanning) { return null; }
  1267. const { blockNumber, nonce } = await resolveProperties({
  1268. blockNumber: this.provider.getBlockNumber(),
  1269. nonce: this.provider.getTransactionCount(this.from)
  1270. });
  1271. // No transaction or our nonce has not been mined yet; but we
  1272. // can start scanning later when we do start
  1273. if (nonce < this.nonce) {
  1274. startBlock = blockNumber;
  1275. return;
  1276. }
  1277. // We were mined; no replacement
  1278. if (stopScanning) { return null; }
  1279. const mined = await this.getTransaction();
  1280. if (mined && mined.blockNumber != null) { return; }
  1281. // We were replaced; start scanning for that transaction
  1282. // Starting to scan; look back a few extra blocks for safety
  1283. if (nextScan === -1) {
  1284. nextScan = startBlock - 3;
  1285. if (nextScan < this.#startBlock) { nextScan = this.#startBlock; }
  1286. }
  1287. while (nextScan <= blockNumber) {
  1288. // Get the next block to scan
  1289. if (stopScanning) { return null; }
  1290. const block = await this.provider.getBlock(nextScan, true);
  1291. // This should not happen; but we'll try again shortly
  1292. if (block == null) { return; }
  1293. // We were mined; no replacement
  1294. for (const hash of block) {
  1295. if (hash === this.hash) { return; }
  1296. }
  1297. // Search for the transaction that replaced us
  1298. for (let i = 0; i < block.length; i++) {
  1299. const tx: TransactionResponse = await block.getTransaction(i);
  1300. if (tx.from === this.from && tx.nonce === this.nonce) {
  1301. // Get the receipt
  1302. if (stopScanning) { return null; }
  1303. const receipt = await this.provider.getTransactionReceipt(tx.hash);
  1304. // This should not happen; but we'll try again shortly
  1305. if (receipt == null) { return; }
  1306. // We will retry this on the next block (this case could be optimized)
  1307. if ((blockNumber - receipt.blockNumber + 1) < confirms) { return; }
  1308. // The reason we were replaced
  1309. let reason: "replaced" | "repriced" | "cancelled" = "replaced";
  1310. if (tx.data === this.data && tx.to === this.to && tx.value === this.value) {
  1311. reason = "repriced";
  1312. } else if (tx.data === "0x" && tx.from === tx.to && tx.value === BN_0) {
  1313. reason = "cancelled"
  1314. }
  1315. assert(false, "transaction was replaced", "TRANSACTION_REPLACED", {
  1316. cancelled: (reason === "replaced" || reason === "cancelled"),
  1317. reason,
  1318. replacement: tx.replaceableTransaction(startBlock),
  1319. hash: tx.hash,
  1320. receipt
  1321. });
  1322. }
  1323. }
  1324. nextScan++;
  1325. }
  1326. return;
  1327. };
  1328. const checkReceipt = (receipt: null | TransactionReceipt) => {
  1329. if (receipt == null || receipt.status !== 0) { return receipt; }
  1330. assert(false, "transaction execution reverted", "CALL_EXCEPTION", {
  1331. action: "sendTransaction",
  1332. data: null, reason: null, invocation: null, revert: null,
  1333. transaction: {
  1334. to: receipt.to,
  1335. from: receipt.from,
  1336. data: "" // @TODO: in v7, split out sendTransaction properties
  1337. }, receipt
  1338. });
  1339. };
  1340. const receipt = await this.provider.getTransactionReceipt(this.hash);
  1341. if (confirms === 0) { return checkReceipt(receipt); }
  1342. if (receipt) {
  1343. if ((await receipt.confirmations()) >= confirms) {
  1344. return checkReceipt(receipt);
  1345. }
  1346. } else {
  1347. // Check for a replacement; throws if a replacement was found
  1348. await checkReplacement();
  1349. // Allow null only when the confirms is 0
  1350. if (confirms === 0) { return null; }
  1351. }
  1352. const waiter = new Promise((resolve, reject) => {
  1353. // List of things to cancel when we have a result (one way or the other)
  1354. const cancellers: Array<() => void> = [ ];
  1355. const cancel = () => { cancellers.forEach((c) => c()); };
  1356. // On cancel, stop scanning for replacements
  1357. cancellers.push(() => { stopScanning = true; });
  1358. // Set up any timeout requested
  1359. if (timeout > 0) {
  1360. const timer = setTimeout(() => {
  1361. cancel();
  1362. reject(makeError("wait for transaction timeout", "TIMEOUT"));
  1363. }, timeout);
  1364. cancellers.push(() => { clearTimeout(timer); });
  1365. }
  1366. const txListener = async (receipt: TransactionReceipt) => {
  1367. // Done; return it!
  1368. if ((await receipt.confirmations()) >= confirms) {
  1369. cancel();
  1370. try {
  1371. resolve(checkReceipt(receipt));
  1372. } catch (error) { reject(error); }
  1373. }
  1374. };
  1375. cancellers.push(() => { this.provider.off(this.hash, txListener); });
  1376. this.provider.on(this.hash, txListener);
  1377. // We support replacement detection; start checking
  1378. if (startBlock >= 0) {
  1379. const replaceListener = async () => {
  1380. try {
  1381. // Check for a replacement; this throws only if one is found
  1382. await checkReplacement();
  1383. } catch (error) {
  1384. // We were replaced (with enough confirms); re-throw the error
  1385. if (isError(error, "TRANSACTION_REPLACED")) {
  1386. cancel();
  1387. reject(error);
  1388. return;
  1389. }
  1390. }
  1391. // Rescheudle a check on the next block
  1392. if (!stopScanning) {
  1393. this.provider.once("block", replaceListener);
  1394. }
  1395. };
  1396. cancellers.push(() => { this.provider.off("block", replaceListener); });
  1397. this.provider.once("block", replaceListener);
  1398. }
  1399. });
  1400. return await <Promise<TransactionReceipt>>waiter;
  1401. }
  1402. /**
  1403. * Returns ``true`` if this transaction has been included.
  1404. *
  1405. * This is effective only as of the time the TransactionResponse
  1406. * was instantiated. To get up-to-date information, use
  1407. * [[getTransaction]].
  1408. *
  1409. * This provides a Type Guard that this transaction will have
  1410. * non-null property values for properties that are null for
  1411. * unmined transactions.
  1412. */
  1413. isMined(): this is MinedTransactionResponse {
  1414. return (this.blockHash != null);
  1415. }
  1416. /**
  1417. * Returns true if the transaction is a legacy (i.e. ``type == 0``)
  1418. * transaction.
  1419. *
  1420. * This provides a Type Guard that this transaction will have
  1421. * the ``null``-ness for hardfork-specific properties set correctly.
  1422. */
  1423. isLegacy(): this is (TransactionResponse & { accessList: null, maxFeePerGas: null, maxPriorityFeePerGas: null }) {
  1424. return (this.type === 0)
  1425. }
  1426. /**
  1427. * Returns true if the transaction is a Berlin (i.e. ``type == 1``)
  1428. * transaction. See [[link-eip-2070]].
  1429. *
  1430. * This provides a Type Guard that this transaction will have
  1431. * the ``null``-ness for hardfork-specific properties set correctly.
  1432. */
  1433. isBerlin(): this is (TransactionResponse & { accessList: AccessList, maxFeePerGas: null, maxPriorityFeePerGas: null }) {
  1434. return (this.type === 1);
  1435. }
  1436. /**
  1437. * Returns true if the transaction is a London (i.e. ``type == 2``)
  1438. * transaction. See [[link-eip-1559]].
  1439. *
  1440. * This provides a Type Guard that this transaction will have
  1441. * the ``null``-ness for hardfork-specific properties set correctly.
  1442. */
  1443. isLondon(): this is (TransactionResponse & { accessList: AccessList, maxFeePerGas: bigint, maxPriorityFeePerGas: bigint }){
  1444. return (this.type === 2);
  1445. }
  1446. /**
  1447. * Returns true if hte transaction is a Cancun (i.e. ``type == 3``)
  1448. * transaction. See [[link-eip-4844]].
  1449. */
  1450. isCancun(): this is (TransactionResponse & { accessList: AccessList, maxFeePerGas: bigint, maxPriorityFeePerGas: bigint, maxFeePerBlobGas: bigint, blobVersionedHashes: Array<string> }){
  1451. return (this.type === 3);
  1452. }
  1453. /**
  1454. * Returns a filter which can be used to listen for orphan events
  1455. * that evict this transaction.
  1456. */
  1457. removedEvent(): OrphanFilter {
  1458. assert(this.isMined(), "unmined transaction canot be orphaned",
  1459. "UNSUPPORTED_OPERATION", { operation: "removeEvent()" });
  1460. return createRemovedTransactionFilter(this);
  1461. }
  1462. /**
  1463. * Returns a filter which can be used to listen for orphan events
  1464. * that re-order this event against %%other%%.
  1465. */
  1466. reorderedEvent(other?: TransactionResponse): OrphanFilter {
  1467. assert(this.isMined(), "unmined transaction canot be orphaned",
  1468. "UNSUPPORTED_OPERATION", { operation: "removeEvent()" });
  1469. assert(!other || other.isMined(), "unmined 'other' transaction canot be orphaned",
  1470. "UNSUPPORTED_OPERATION", { operation: "removeEvent()" });
  1471. return createReorderedTransactionFilter(this, other);
  1472. }
  1473. /**
  1474. * Returns a new TransactionResponse instance which has the ability to
  1475. * detect (and throw an error) if the transaction is replaced, which
  1476. * will begin scanning at %%startBlock%%.
  1477. *
  1478. * This should generally not be used by developers and is intended
  1479. * primarily for internal use. Setting an incorrect %%startBlock%% can
  1480. * have devastating performance consequences if used incorrectly.
  1481. */
  1482. replaceableTransaction(startBlock: number): TransactionResponse {
  1483. assertArgument(Number.isInteger(startBlock) && startBlock >= 0, "invalid startBlock", "startBlock", startBlock);
  1484. const tx = new TransactionResponse(this, this.provider);
  1485. tx.#startBlock = startBlock;
  1486. return tx;
  1487. }
  1488. }
  1489. //////////////////////
  1490. // OrphanFilter
  1491. /**
  1492. * An Orphan Filter allows detecting when an orphan block has
  1493. * resulted in dropping a block or transaction or has resulted
  1494. * in transactions changing order.
  1495. *
  1496. * Not currently fully supported.
  1497. */
  1498. export type OrphanFilter = {
  1499. orphan: "drop-block",
  1500. hash: string,
  1501. number: number
  1502. } | {
  1503. orphan: "drop-transaction",
  1504. tx: { hash: string, blockHash: string, blockNumber: number },
  1505. other?: { hash: string, blockHash: string, blockNumber: number }
  1506. } | {
  1507. orphan: "reorder-transaction",
  1508. tx: { hash: string, blockHash: string, blockNumber: number },
  1509. other?: { hash: string, blockHash: string, blockNumber: number }
  1510. } | {
  1511. orphan: "drop-log",
  1512. log: {
  1513. transactionHash: string,
  1514. blockHash: string,
  1515. blockNumber: number,
  1516. address: string,
  1517. data: string,
  1518. topics: ReadonlyArray<string>,
  1519. index: number
  1520. }
  1521. };
  1522. function createOrphanedBlockFilter(block: { hash: string, number: number }): OrphanFilter {
  1523. return { orphan: "drop-block", hash: block.hash, number: block.number };
  1524. }
  1525. function createReorderedTransactionFilter(tx: { hash: string, blockHash: string, blockNumber: number }, other?: { hash: string, blockHash: string, blockNumber: number }): OrphanFilter {
  1526. return { orphan: "reorder-transaction", tx, other };
  1527. }
  1528. function createRemovedTransactionFilter(tx: { hash: string, blockHash: string, blockNumber: number }): OrphanFilter {
  1529. return { orphan: "drop-transaction", tx };
  1530. }
  1531. function createRemovedLogFilter(log: { blockHash: string, transactionHash: string, blockNumber: number, address: string, data: string, topics: ReadonlyArray<string>, index: number }): OrphanFilter {
  1532. return { orphan: "drop-log", log: {
  1533. transactionHash: log.transactionHash,
  1534. blockHash: log.blockHash,
  1535. blockNumber: log.blockNumber,
  1536. address: log.address,
  1537. data: log.data,
  1538. topics: Object.freeze(log.topics.slice()),
  1539. index: log.index
  1540. } };
  1541. }
  1542. //////////////////////
  1543. // EventFilter
  1544. /**
  1545. * A **TopicFilter** provides a struture to define bloom-filter
  1546. * queries.
  1547. *
  1548. * Each field that is ``null`` matches **any** value, a field that is
  1549. * a ``string`` must match exactly that value and ``array`` is
  1550. * effectively an ``OR``-ed set, where any one of those values must
  1551. * match.
  1552. */
  1553. export type TopicFilter = Array<null | string | Array<string>>;
  1554. // @TODO:
  1555. //export type DeferableTopicFilter = Array<null | string | Promise<string> | Array<string | Promise<string>>>;
  1556. /**
  1557. * An **EventFilter** allows efficiently filtering logs (also known as
  1558. * events) using bloom filters included within blocks.
  1559. */
  1560. export interface EventFilter {
  1561. address?: AddressLike | Array<AddressLike>;
  1562. topics?: TopicFilter;
  1563. }
  1564. /**
  1565. * A **Filter** allows searching a specific range of blocks for mathcing
  1566. * logs.
  1567. */
  1568. export interface Filter extends EventFilter {
  1569. /**
  1570. * The start block for the filter (inclusive).
  1571. */
  1572. fromBlock?: BlockTag;
  1573. /**
  1574. * The end block for the filter (inclusive).
  1575. */
  1576. toBlock?: BlockTag;
  1577. }
  1578. /**
  1579. * A **FilterByBlockHash** allows searching a specific block for mathcing
  1580. * logs.
  1581. */
  1582. export interface FilterByBlockHash extends EventFilter {
  1583. /**
  1584. * The blockhash of the specific block for the filter.
  1585. */
  1586. blockHash?: string;
  1587. }
  1588. //////////////////////
  1589. // ProviderEvent
  1590. /**
  1591. * A **ProviderEvent** provides the types of events that can be subscribed
  1592. * to on a [[Provider]].
  1593. *
  1594. * Each provider may include additional possible events it supports, but
  1595. * the most commonly supported are:
  1596. *
  1597. * **``"block"``** - calls the listener with the current block number on each
  1598. * new block.
  1599. *
  1600. * **``"error"``** - calls the listener on each async error that occurs during
  1601. * the event loop, with the error.
  1602. *
  1603. * **``"debug"``** - calls the listener on debug events, which can be used to
  1604. * troubleshoot network errors, provider problems, etc.
  1605. *
  1606. * **``transaction hash``** - calls the listener on each block after the
  1607. * transaction has been mined; generally ``.once`` is more appropriate for
  1608. * this event.
  1609. *
  1610. * **``Array``** - calls the listener on each log that matches the filter.
  1611. *
  1612. * [[EventFilter]] - calls the listener with each matching log
  1613. */
  1614. export type ProviderEvent = string | Array<string | Array<string>> | EventFilter | OrphanFilter;
  1615. //////////////////////
  1616. // Provider
  1617. /**
  1618. * A **Provider** is the primary method to interact with the read-only
  1619. * content on Ethereum.
  1620. *
  1621. * It allows access to details about accounts, blocks and transactions
  1622. * and the ability to query event logs and simulate contract execution.
  1623. *
  1624. * Account data includes the [balance](getBalance),
  1625. * [transaction count](getTransactionCount), [code](getCode) and
  1626. * [state trie storage](getStorage).
  1627. *
  1628. * Simulating execution can be used to [call](call),
  1629. * [estimate gas](estimateGas) and
  1630. * [get transaction results](getTransactionResult).
  1631. *
  1632. * The [[broadcastTransaction]] is the only method which allows updating
  1633. * the blockchain, but it is usually accessed by a [[Signer]], since a
  1634. * private key must be used to sign the transaction before it can be
  1635. * broadcast.
  1636. */
  1637. export interface Provider extends ContractRunner, EventEmitterable<ProviderEvent>, NameResolver {
  1638. /**
  1639. * The provider iteself.
  1640. *
  1641. * This is part of the necessary API for executing a contract, as
  1642. * it provides a common property on any [[ContractRunner]] that
  1643. * can be used to access the read-only portion of the runner.
  1644. */
  1645. provider: this;
  1646. /**
  1647. * Shutdown any resources this provider is using. No additional
  1648. * calls should be made to this provider after calling this.
  1649. */
  1650. destroy(): void;
  1651. ////////////////////
  1652. // State
  1653. /**
  1654. * Get the current block number.
  1655. */
  1656. getBlockNumber(): Promise<number>;
  1657. /**
  1658. * Get the connected [[Network]].
  1659. */
  1660. getNetwork(): Promise<Network>;
  1661. /**
  1662. * Get the best guess at the recommended [[FeeData]].
  1663. */
  1664. getFeeData(): Promise<FeeData>;
  1665. ////////////////////
  1666. // Account
  1667. /**
  1668. * Get the account balance (in wei) of %%address%%. If %%blockTag%%
  1669. * is specified and the node supports archive access for that
  1670. * %%blockTag%%, the balance is as of that [[BlockTag]].
  1671. *
  1672. * @note On nodes without archive access enabled, the %%blockTag%% may be
  1673. * **silently ignored** by the node, which may cause issues if relied on.
  1674. */
  1675. getBalance(address: AddressLike, blockTag?: BlockTag): Promise<bigint>;
  1676. /**
  1677. * Get the number of transactions ever sent for %%address%%, which
  1678. * is used as the ``nonce`` when sending a transaction. If
  1679. * %%blockTag%% is specified and the node supports archive access
  1680. * for that %%blockTag%%, the transaction count is as of that
  1681. * [[BlockTag]].
  1682. *
  1683. * @note On nodes without archive access enabled, the %%blockTag%% may be
  1684. * **silently ignored** by the node, which may cause issues if relied on.
  1685. */
  1686. getTransactionCount(address: AddressLike, blockTag?: BlockTag): Promise<number>;
  1687. /**
  1688. * Get the bytecode for %%address%%.
  1689. *
  1690. * @note On nodes without archive access enabled, the %%blockTag%% may be
  1691. * **silently ignored** by the node, which may cause issues if relied on.
  1692. */
  1693. getCode(address: AddressLike, blockTag?: BlockTag): Promise<string>
  1694. /**
  1695. * Get the storage slot value for %%address%% at slot %%position%%.
  1696. *
  1697. * @note On nodes without archive access enabled, the %%blockTag%% may be
  1698. * **silently ignored** by the node, which may cause issues if relied on.
  1699. */
  1700. getStorage(address: AddressLike, position: BigNumberish, blockTag?: BlockTag): Promise<string>
  1701. ////////////////////
  1702. // Execution
  1703. /**
  1704. * Estimates the amount of gas required to execute %%tx%%.
  1705. */
  1706. estimateGas(tx: TransactionRequest): Promise<bigint>;
  1707. /**
  1708. * Simulate the execution of %%tx%%. If the call reverts, it will
  1709. * throw a [[CallExceptionError]] which includes the revert data.
  1710. */
  1711. call(tx: TransactionRequest): Promise<string>
  1712. /**
  1713. * Broadcasts the %%signedTx%% to the network, adding it to the
  1714. * memory pool of any node for which the transaction meets the
  1715. * rebroadcast requirements.
  1716. */
  1717. broadcastTransaction(signedTx: string): Promise<TransactionResponse>;
  1718. ////////////////////
  1719. // Queries
  1720. /**
  1721. * Resolves to the block for %%blockHashOrBlockTag%%.
  1722. *
  1723. * If %%prefetchTxs%%, and the backend supports including transactions
  1724. * with block requests, all transactions will be included and the
  1725. * [[Block]] object will not need to make remote calls for getting
  1726. * transactions.
  1727. */
  1728. getBlock(blockHashOrBlockTag: BlockTag | string, prefetchTxs?: boolean): Promise<null | Block>;
  1729. /**
  1730. * Resolves to the transaction for %%hash%%.
  1731. *
  1732. * If the transaction is unknown or on pruning nodes which
  1733. * discard old transactions this resolves to ``null``.
  1734. */
  1735. getTransaction(hash: string): Promise<null | TransactionResponse>;
  1736. /**
  1737. * Resolves to the transaction receipt for %%hash%%, if mined.
  1738. *
  1739. * If the transaction has not been mined, is unknown or on
  1740. * pruning nodes which discard old transactions this resolves to
  1741. * ``null``.
  1742. */
  1743. getTransactionReceipt(hash: string): Promise<null | TransactionReceipt>;
  1744. /**
  1745. * Resolves to the result returned by the executions of %%hash%%.
  1746. *
  1747. * This is only supported on nodes with archive access and with
  1748. * the necessary debug APIs enabled.
  1749. */
  1750. getTransactionResult(hash: string): Promise<null | string>;
  1751. ////////////////////
  1752. // Bloom-filter Queries
  1753. /**
  1754. * Resolves to the list of Logs that match %%filter%%
  1755. */
  1756. getLogs(filter: Filter | FilterByBlockHash): Promise<Array<Log>>;
  1757. ////////////////////
  1758. // ENS
  1759. /**
  1760. * Resolves to the address configured for the %%ensName%% or
  1761. * ``null`` if unconfigured.
  1762. */
  1763. resolveName(ensName: string): Promise<null | string>;
  1764. /**
  1765. * Resolves to the ENS name associated for the %%address%% or
  1766. * ``null`` if the //primary name// is not configured.
  1767. *
  1768. * Users must perform additional steps to configure a //primary name//,
  1769. * which is not currently common.
  1770. */
  1771. lookupAddress(address: string): Promise<null | string>;
  1772. /**
  1773. * Waits until the transaction %%hash%% is mined and has %%confirms%%
  1774. * confirmations.
  1775. */
  1776. waitForTransaction(hash: string, confirms?: number, timeout?: number): Promise<null | TransactionReceipt>;
  1777. /**
  1778. * Resolves to the block at %%blockTag%% once it has been mined.
  1779. *
  1780. * This can be useful for waiting some number of blocks by using
  1781. * the ``currentBlockNumber + N``.
  1782. */
  1783. waitForBlock(blockTag?: BlockTag): Promise<Block>;
  1784. }