transaction.ts 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  1. import { getAddress } from "../address/index.js";
  2. import { ZeroAddress } from "../constants/addresses.js";
  3. import {
  4. keccak256, sha256, Signature, SigningKey
  5. } from "../crypto/index.js";
  6. import {
  7. concat, decodeRlp, encodeRlp, getBytes, getBigInt, getNumber, hexlify,
  8. assert, assertArgument, isBytesLike, isHexString, toBeArray, zeroPadValue
  9. } from "../utils/index.js";
  10. import { accessListify } from "./accesslist.js";
  11. import { recoverAddress } from "./address.js";
  12. import type { BigNumberish, BytesLike } from "../utils/index.js";
  13. import type { SignatureLike } from "../crypto/index.js";
  14. import type { AccessList, AccessListish } from "./index.js";
  15. const BN_0 = BigInt(0);
  16. const BN_2 = BigInt(2);
  17. const BN_27 = BigInt(27)
  18. const BN_28 = BigInt(28)
  19. const BN_35 = BigInt(35);
  20. const BN_MAX_UINT = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
  21. const BLOB_SIZE = 4096 * 32;
  22. // The BLS Modulo; each field within a BLOb must be less than this
  23. //const BLOB_BLS_MODULO = BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001");
  24. /**
  25. * A **TransactionLike** is an object which is appropriate as a loose
  26. * input for many operations which will populate missing properties of
  27. * a transaction.
  28. */
  29. export interface TransactionLike<A = string> {
  30. /**
  31. * The type.
  32. */
  33. type?: null | number;
  34. /**
  35. * The recipient address or ``null`` for an ``init`` transaction.
  36. */
  37. to?: null | A;
  38. /**
  39. * The sender.
  40. */
  41. from?: null | A;
  42. /**
  43. * The nonce.
  44. */
  45. nonce?: null | number;
  46. /**
  47. * The maximum amount of gas that can be used.
  48. */
  49. gasLimit?: null | BigNumberish;
  50. /**
  51. * The gas price for legacy and berlin transactions.
  52. */
  53. gasPrice?: null | BigNumberish;
  54. /**
  55. * The maximum priority fee per gas for london transactions.
  56. */
  57. maxPriorityFeePerGas?: null | BigNumberish;
  58. /**
  59. * The maximum total fee per gas for london transactions.
  60. */
  61. maxFeePerGas?: null | BigNumberish;
  62. /**
  63. * The data.
  64. */
  65. data?: null | string;
  66. /**
  67. * The value (in wei) to send.
  68. */
  69. value?: null | BigNumberish;
  70. /**
  71. * The chain ID the transaction is valid on.
  72. */
  73. chainId?: null | BigNumberish;
  74. /**
  75. * The transaction hash.
  76. */
  77. hash?: null | string;
  78. /**
  79. * The signature provided by the sender.
  80. */
  81. signature?: null | SignatureLike;
  82. /**
  83. * The access list for berlin and london transactions.
  84. */
  85. accessList?: null | AccessListish;
  86. /**
  87. * The maximum fee per blob gas (see [[link-eip-4844]]).
  88. */
  89. maxFeePerBlobGas?: null | BigNumberish;
  90. /**
  91. * The versioned hashes (see [[link-eip-4844]]).
  92. */
  93. blobVersionedHashes?: null | Array<string>;
  94. /**
  95. * The blobs (if any) attached to this transaction (see [[link-eip-4844]]).
  96. */
  97. blobs?: null | Array<BlobLike>
  98. /**
  99. * An external library for computing the KZG commitments and
  100. * proofs necessary for EIP-4844 transactions (see [[link-eip-4844]]).
  101. *
  102. * This is generally ``null``, unless you are creating BLOb
  103. * transactions.
  104. */
  105. kzg?: null | KzgLibrary;
  106. }
  107. /**
  108. * A full-valid BLOb object for [[link-eip-4844]] transactions.
  109. *
  110. * The commitment and proof should have been computed using a
  111. * KZG library.
  112. */
  113. export interface Blob {
  114. data: string;
  115. proof: string;
  116. commitment: string;
  117. }
  118. /**
  119. * A BLOb object that can be passed for [[link-eip-4844]]
  120. * transactions.
  121. *
  122. * It may have had its commitment and proof already provided
  123. * or rely on an attached [[KzgLibrary]] to compute them.
  124. */
  125. export type BlobLike = BytesLike | {
  126. data: BytesLike;
  127. proof: BytesLike;
  128. commitment: BytesLike;
  129. };
  130. /**
  131. * A KZG Library with the necessary functions to compute
  132. * BLOb commitments and proofs.
  133. */
  134. export interface KzgLibrary {
  135. blobToKzgCommitment: (blob: Uint8Array) => Uint8Array;
  136. computeBlobKzgProof: (blob: Uint8Array, commitment: Uint8Array) => Uint8Array;
  137. }
  138. function getVersionedHash(version: number, hash: BytesLike): string {
  139. let versioned = version.toString(16);
  140. while (versioned.length < 2) { versioned = "0" + versioned; }
  141. versioned += sha256(hash).substring(4);
  142. return "0x" + versioned;
  143. }
  144. function handleAddress(value: string): null | string {
  145. if (value === "0x") { return null; }
  146. return getAddress(value);
  147. }
  148. function handleAccessList(value: any, param: string): AccessList {
  149. try {
  150. return accessListify(value);
  151. } catch (error: any) {
  152. assertArgument(false, error.message, param, value);
  153. }
  154. }
  155. function handleNumber(_value: string, param: string): number {
  156. if (_value === "0x") { return 0; }
  157. return getNumber(_value, param);
  158. }
  159. function handleUint(_value: string, param: string): bigint {
  160. if (_value === "0x") { return BN_0; }
  161. const value = getBigInt(_value, param);
  162. assertArgument(value <= BN_MAX_UINT, "value exceeds uint size", param, value);
  163. return value;
  164. }
  165. function formatNumber(_value: BigNumberish, name: string): Uint8Array {
  166. const value = getBigInt(_value, "value");
  167. const result = toBeArray(value);
  168. assertArgument(result.length <= 32, `value too large`, `tx.${ name }`, value);
  169. return result;
  170. }
  171. function formatAccessList(value: AccessListish): Array<[ string, Array<string> ]> {
  172. return accessListify(value).map((set) => [ set.address, set.storageKeys ]);
  173. }
  174. function formatHashes(value: Array<string>, param: string): Array<string> {
  175. assertArgument(Array.isArray(value), `invalid ${ param }`, "value", value);
  176. for (let i = 0; i < value.length; i++) {
  177. assertArgument(isHexString(value[i], 32), "invalid ${ param } hash", `value[${ i }]`, value[i]);
  178. }
  179. return value;
  180. }
  181. function _parseLegacy(data: Uint8Array): TransactionLike {
  182. const fields: any = decodeRlp(data);
  183. assertArgument(Array.isArray(fields) && (fields.length === 9 || fields.length === 6),
  184. "invalid field count for legacy transaction", "data", data);
  185. const tx: TransactionLike = {
  186. type: 0,
  187. nonce: handleNumber(fields[0], "nonce"),
  188. gasPrice: handleUint(fields[1], "gasPrice"),
  189. gasLimit: handleUint(fields[2], "gasLimit"),
  190. to: handleAddress(fields[3]),
  191. value: handleUint(fields[4], "value"),
  192. data: hexlify(fields[5]),
  193. chainId: BN_0
  194. };
  195. // Legacy unsigned transaction
  196. if (fields.length === 6) { return tx; }
  197. const v = handleUint(fields[6], "v");
  198. const r = handleUint(fields[7], "r");
  199. const s = handleUint(fields[8], "s");
  200. if (r === BN_0 && s === BN_0) {
  201. // EIP-155 unsigned transaction
  202. tx.chainId = v;
  203. } else {
  204. // Compute the EIP-155 chain ID (or 0 for legacy)
  205. let chainId = (v - BN_35) / BN_2;
  206. if (chainId < BN_0) { chainId = BN_0; }
  207. tx.chainId = chainId
  208. // Signed Legacy Transaction
  209. assertArgument(chainId !== BN_0 || (v === BN_27 || v === BN_28), "non-canonical legacy v", "v", fields[6]);
  210. tx.signature = Signature.from({
  211. r: zeroPadValue(fields[7], 32),
  212. s: zeroPadValue(fields[8], 32),
  213. v
  214. });
  215. //tx.hash = keccak256(data);
  216. }
  217. return tx;
  218. }
  219. function _serializeLegacy(tx: Transaction, sig: null | Signature): string {
  220. const fields: Array<any> = [
  221. formatNumber(tx.nonce, "nonce"),
  222. formatNumber(tx.gasPrice || 0, "gasPrice"),
  223. formatNumber(tx.gasLimit, "gasLimit"),
  224. (tx.to || "0x"),
  225. formatNumber(tx.value, "value"),
  226. tx.data,
  227. ];
  228. let chainId = BN_0;
  229. if (tx.chainId != BN_0) {
  230. // A chainId was provided; if non-zero we'll use EIP-155
  231. chainId = getBigInt(tx.chainId, "tx.chainId");
  232. // We have a chainId in the tx and an EIP-155 v in the signature,
  233. // make sure they agree with each other
  234. assertArgument(!sig || sig.networkV == null || sig.legacyChainId === chainId,
  235. "tx.chainId/sig.v mismatch", "sig", sig);
  236. } else if (tx.signature) {
  237. // No explicit chainId, but EIP-155 have a derived implicit chainId
  238. const legacy = tx.signature.legacyChainId;
  239. if (legacy != null) { chainId = legacy; }
  240. }
  241. // Requesting an unsigned transaction
  242. if (!sig) {
  243. // We have an EIP-155 transaction (chainId was specified and non-zero)
  244. if (chainId !== BN_0) {
  245. fields.push(toBeArray(chainId));
  246. fields.push("0x");
  247. fields.push("0x");
  248. }
  249. return encodeRlp(fields);
  250. }
  251. // @TODO: We should probably check that tx.signature, chainId, and sig
  252. // match but that logic could break existing code, so schedule
  253. // this for the next major bump.
  254. // Compute the EIP-155 v
  255. let v = BigInt(27 + sig.yParity);
  256. if (chainId !== BN_0) {
  257. v = Signature.getChainIdV(chainId, sig.v);
  258. } else if (BigInt(sig.v) !== v) {
  259. assertArgument(false, "tx.chainId/sig.v mismatch", "sig", sig);
  260. }
  261. // Add the signature
  262. fields.push(toBeArray(v));
  263. fields.push(toBeArray(sig.r));
  264. fields.push(toBeArray(sig.s));
  265. return encodeRlp(fields);
  266. }
  267. function _parseEipSignature(tx: TransactionLike, fields: Array<string>): void {
  268. let yParity: number;
  269. try {
  270. yParity = handleNumber(fields[0], "yParity");
  271. if (yParity !== 0 && yParity !== 1) { throw new Error("bad yParity"); }
  272. } catch (error) {
  273. assertArgument(false, "invalid yParity", "yParity", fields[0]);
  274. }
  275. const r = zeroPadValue(fields[1], 32);
  276. const s = zeroPadValue(fields[2], 32);
  277. const signature = Signature.from({ r, s, yParity });
  278. tx.signature = signature;
  279. }
  280. function _parseEip1559(data: Uint8Array): TransactionLike {
  281. const fields: any = decodeRlp(getBytes(data).slice(1));
  282. assertArgument(Array.isArray(fields) && (fields.length === 9 || fields.length === 12),
  283. "invalid field count for transaction type: 2", "data", hexlify(data));
  284. const tx: TransactionLike = {
  285. type: 2,
  286. chainId: handleUint(fields[0], "chainId"),
  287. nonce: handleNumber(fields[1], "nonce"),
  288. maxPriorityFeePerGas: handleUint(fields[2], "maxPriorityFeePerGas"),
  289. maxFeePerGas: handleUint(fields[3], "maxFeePerGas"),
  290. gasPrice: null,
  291. gasLimit: handleUint(fields[4], "gasLimit"),
  292. to: handleAddress(fields[5]),
  293. value: handleUint(fields[6], "value"),
  294. data: hexlify(fields[7]),
  295. accessList: handleAccessList(fields[8], "accessList"),
  296. };
  297. // Unsigned EIP-1559 Transaction
  298. if (fields.length === 9) { return tx; }
  299. //tx.hash = keccak256(data);
  300. _parseEipSignature(tx, fields.slice(9));
  301. return tx;
  302. }
  303. function _serializeEip1559(tx: Transaction, sig: null | Signature): string {
  304. const fields: Array<any> = [
  305. formatNumber(tx.chainId, "chainId"),
  306. formatNumber(tx.nonce, "nonce"),
  307. formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"),
  308. formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"),
  309. formatNumber(tx.gasLimit, "gasLimit"),
  310. (tx.to || "0x"),
  311. formatNumber(tx.value, "value"),
  312. tx.data,
  313. formatAccessList(tx.accessList || [ ])
  314. ];
  315. if (sig) {
  316. fields.push(formatNumber(sig.yParity, "yParity"));
  317. fields.push(toBeArray(sig.r));
  318. fields.push(toBeArray(sig.s));
  319. }
  320. return concat([ "0x02", encodeRlp(fields)]);
  321. }
  322. function _parseEip2930(data: Uint8Array): TransactionLike {
  323. const fields: any = decodeRlp(getBytes(data).slice(1));
  324. assertArgument(Array.isArray(fields) && (fields.length === 8 || fields.length === 11),
  325. "invalid field count for transaction type: 1", "data", hexlify(data));
  326. const tx: TransactionLike = {
  327. type: 1,
  328. chainId: handleUint(fields[0], "chainId"),
  329. nonce: handleNumber(fields[1], "nonce"),
  330. gasPrice: handleUint(fields[2], "gasPrice"),
  331. gasLimit: handleUint(fields[3], "gasLimit"),
  332. to: handleAddress(fields[4]),
  333. value: handleUint(fields[5], "value"),
  334. data: hexlify(fields[6]),
  335. accessList: handleAccessList(fields[7], "accessList")
  336. };
  337. // Unsigned EIP-2930 Transaction
  338. if (fields.length === 8) { return tx; }
  339. //tx.hash = keccak256(data);
  340. _parseEipSignature(tx, fields.slice(8));
  341. return tx;
  342. }
  343. function _serializeEip2930(tx: Transaction, sig: null | Signature): string {
  344. const fields: any = [
  345. formatNumber(tx.chainId, "chainId"),
  346. formatNumber(tx.nonce, "nonce"),
  347. formatNumber(tx.gasPrice || 0, "gasPrice"),
  348. formatNumber(tx.gasLimit, "gasLimit"),
  349. (tx.to || "0x"),
  350. formatNumber(tx.value, "value"),
  351. tx.data,
  352. formatAccessList(tx.accessList || [ ])
  353. ];
  354. if (sig) {
  355. fields.push(formatNumber(sig.yParity, "recoveryParam"));
  356. fields.push(toBeArray(sig.r));
  357. fields.push(toBeArray(sig.s));
  358. }
  359. return concat([ "0x01", encodeRlp(fields)]);
  360. }
  361. function _parseEip4844(data: Uint8Array): TransactionLike {
  362. let fields: any = decodeRlp(getBytes(data).slice(1));
  363. let typeName = "3";
  364. let blobs: null | Array<Blob> = null;
  365. // Parse the network format
  366. if (fields.length === 4 && Array.isArray(fields[0])) {
  367. typeName = "3 (network format)";
  368. const fBlobs = fields[1], fCommits = fields[2], fProofs = fields[3];
  369. assertArgument(Array.isArray(fBlobs), "invalid network format: blobs not an array", "fields[1]", fBlobs);
  370. assertArgument(Array.isArray(fCommits), "invalid network format: commitments not an array", "fields[2]", fCommits);
  371. assertArgument(Array.isArray(fProofs), "invalid network format: proofs not an array", "fields[3]", fProofs);
  372. assertArgument(fBlobs.length === fCommits.length, "invalid network format: blobs/commitments length mismatch", "fields", fields);
  373. assertArgument(fBlobs.length === fProofs.length, "invalid network format: blobs/proofs length mismatch", "fields", fields);
  374. blobs = [ ];
  375. for (let i = 0; i < fields[1].length; i++) {
  376. blobs.push({
  377. data: fBlobs[i],
  378. commitment: fCommits[i],
  379. proof: fProofs[i],
  380. });
  381. }
  382. fields = fields[0];
  383. }
  384. assertArgument(Array.isArray(fields) && (fields.length === 11 || fields.length === 14),
  385. `invalid field count for transaction type: ${ typeName }`, "data", hexlify(data));
  386. const tx: TransactionLike = {
  387. type: 3,
  388. chainId: handleUint(fields[0], "chainId"),
  389. nonce: handleNumber(fields[1], "nonce"),
  390. maxPriorityFeePerGas: handleUint(fields[2], "maxPriorityFeePerGas"),
  391. maxFeePerGas: handleUint(fields[3], "maxFeePerGas"),
  392. gasPrice: null,
  393. gasLimit: handleUint(fields[4], "gasLimit"),
  394. to: handleAddress(fields[5]),
  395. value: handleUint(fields[6], "value"),
  396. data: hexlify(fields[7]),
  397. accessList: handleAccessList(fields[8], "accessList"),
  398. maxFeePerBlobGas: handleUint(fields[9], "maxFeePerBlobGas"),
  399. blobVersionedHashes: fields[10]
  400. };
  401. if (blobs) { tx.blobs = blobs; }
  402. assertArgument(tx.to != null, `invalid address for transaction type: ${ typeName }`, "data", data);
  403. assertArgument(Array.isArray(tx.blobVersionedHashes), "invalid blobVersionedHashes: must be an array", "data", data);
  404. for (let i = 0; i < tx.blobVersionedHashes.length; i++) {
  405. assertArgument(isHexString(tx.blobVersionedHashes[i], 32), `invalid blobVersionedHash at index ${ i }: must be length 32`, "data", data);
  406. }
  407. // Unsigned EIP-4844 Transaction
  408. if (fields.length === 11) { return tx; }
  409. // @TODO: Do we need to do this? This is only called internally
  410. // and used to verify hashes; it might save time to not do this
  411. //tx.hash = keccak256(concat([ "0x03", encodeRlp(fields) ]));
  412. _parseEipSignature(tx, fields.slice(11));
  413. return tx;
  414. }
  415. function _serializeEip4844(tx: Transaction, sig: null | Signature, blobs: null | Array<Blob>): string {
  416. const fields: Array<any> = [
  417. formatNumber(tx.chainId, "chainId"),
  418. formatNumber(tx.nonce, "nonce"),
  419. formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"),
  420. formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"),
  421. formatNumber(tx.gasLimit, "gasLimit"),
  422. (tx.to || ZeroAddress),
  423. formatNumber(tx.value, "value"),
  424. tx.data,
  425. formatAccessList(tx.accessList || [ ]),
  426. formatNumber(tx.maxFeePerBlobGas || 0, "maxFeePerBlobGas"),
  427. formatHashes(tx.blobVersionedHashes || [ ], "blobVersionedHashes")
  428. ];
  429. if (sig) {
  430. fields.push(formatNumber(sig.yParity, "yParity"));
  431. fields.push(toBeArray(sig.r));
  432. fields.push(toBeArray(sig.s));
  433. // We have blobs; return the network wrapped format
  434. if (blobs) {
  435. return concat([
  436. "0x03",
  437. encodeRlp([
  438. fields,
  439. blobs.map((b) => b.data),
  440. blobs.map((b) => b.commitment),
  441. blobs.map((b) => b.proof),
  442. ])
  443. ]);
  444. }
  445. }
  446. return concat([ "0x03", encodeRlp(fields)]);
  447. }
  448. /**
  449. * A **Transaction** describes an operation to be executed on
  450. * Ethereum by an Externally Owned Account (EOA). It includes
  451. * who (the [[to]] address), what (the [[data]]) and how much (the
  452. * [[value]] in ether) the operation should entail.
  453. *
  454. * @example:
  455. * tx = new Transaction()
  456. * //_result:
  457. *
  458. * tx.data = "0x1234";
  459. * //_result:
  460. */
  461. export class Transaction implements TransactionLike<string> {
  462. #type: null | number;
  463. #to: null | string;
  464. #data: string;
  465. #nonce: number;
  466. #gasLimit: bigint;
  467. #gasPrice: null | bigint;
  468. #maxPriorityFeePerGas: null | bigint;
  469. #maxFeePerGas: null | bigint;
  470. #value: bigint;
  471. #chainId: bigint;
  472. #sig: null | Signature;
  473. #accessList: null | AccessList;
  474. #maxFeePerBlobGas: null | bigint;
  475. #blobVersionedHashes: null | Array<string>;
  476. #kzg: null | KzgLibrary;
  477. #blobs: null | Array<Blob>;
  478. /**
  479. * The transaction type.
  480. *
  481. * If null, the type will be automatically inferred based on
  482. * explicit properties.
  483. */
  484. get type(): null | number { return this.#type; }
  485. set type(value: null | number | string) {
  486. switch (value) {
  487. case null:
  488. this.#type = null;
  489. break;
  490. case 0: case "legacy":
  491. this.#type = 0;
  492. break;
  493. case 1: case "berlin": case "eip-2930":
  494. this.#type = 1;
  495. break;
  496. case 2: case "london": case "eip-1559":
  497. this.#type = 2;
  498. break;
  499. case 3: case "cancun": case "eip-4844":
  500. this.#type = 3;
  501. break;
  502. default:
  503. assertArgument(false, "unsupported transaction type", "type", value);
  504. }
  505. }
  506. /**
  507. * The name of the transaction type.
  508. */
  509. get typeName(): null | string {
  510. switch (this.type) {
  511. case 0: return "legacy";
  512. case 1: return "eip-2930";
  513. case 2: return "eip-1559";
  514. case 3: return "eip-4844";
  515. }
  516. return null;
  517. }
  518. /**
  519. * The ``to`` address for the transaction or ``null`` if the
  520. * transaction is an ``init`` transaction.
  521. */
  522. get to(): null | string {
  523. const value = this.#to;
  524. if (value == null && this.type === 3) { return ZeroAddress; }
  525. return value;
  526. }
  527. set to(value: null | string) {
  528. this.#to = (value == null) ? null: getAddress(value);
  529. }
  530. /**
  531. * The transaction nonce.
  532. */
  533. get nonce(): number { return this.#nonce; }
  534. set nonce(value: BigNumberish) { this.#nonce = getNumber(value, "value"); }
  535. /**
  536. * The gas limit.
  537. */
  538. get gasLimit(): bigint { return this.#gasLimit; }
  539. set gasLimit(value: BigNumberish) { this.#gasLimit = getBigInt(value); }
  540. /**
  541. * The gas price.
  542. *
  543. * On legacy networks this defines the fee that will be paid. On
  544. * EIP-1559 networks, this should be ``null``.
  545. */
  546. get gasPrice(): null | bigint {
  547. const value = this.#gasPrice;
  548. if (value == null && (this.type === 0 || this.type === 1)) { return BN_0; }
  549. return value;
  550. }
  551. set gasPrice(value: null | BigNumberish) {
  552. this.#gasPrice = (value == null) ? null: getBigInt(value, "gasPrice");
  553. }
  554. /**
  555. * The maximum priority fee per unit of gas to pay. On legacy
  556. * networks this should be ``null``.
  557. */
  558. get maxPriorityFeePerGas(): null | bigint {
  559. const value = this.#maxPriorityFeePerGas;
  560. if (value == null) {
  561. if (this.type === 2 || this.type === 3) { return BN_0; }
  562. return null;
  563. }
  564. return value;
  565. }
  566. set maxPriorityFeePerGas(value: null | BigNumberish) {
  567. this.#maxPriorityFeePerGas = (value == null) ? null: getBigInt(value, "maxPriorityFeePerGas");
  568. }
  569. /**
  570. * The maximum total fee per unit of gas to pay. On legacy
  571. * networks this should be ``null``.
  572. */
  573. get maxFeePerGas(): null | bigint {
  574. const value = this.#maxFeePerGas;
  575. if (value == null) {
  576. if (this.type === 2 || this.type === 3) { return BN_0; }
  577. return null;
  578. }
  579. return value;
  580. }
  581. set maxFeePerGas(value: null | BigNumberish) {
  582. this.#maxFeePerGas = (value == null) ? null: getBigInt(value, "maxFeePerGas");
  583. }
  584. /**
  585. * The transaction data. For ``init`` transactions this is the
  586. * deployment code.
  587. */
  588. get data(): string { return this.#data; }
  589. set data(value: BytesLike) { this.#data = hexlify(value); }
  590. /**
  591. * The amount of ether (in wei) to send in this transactions.
  592. */
  593. get value(): bigint { return this.#value; }
  594. set value(value: BigNumberish) {
  595. this.#value = getBigInt(value, "value");
  596. }
  597. /**
  598. * The chain ID this transaction is valid on.
  599. */
  600. get chainId(): bigint { return this.#chainId; }
  601. set chainId(value: BigNumberish) { this.#chainId = getBigInt(value); }
  602. /**
  603. * If signed, the signature for this transaction.
  604. */
  605. get signature(): null | Signature { return this.#sig || null; }
  606. set signature(value: null | SignatureLike) {
  607. this.#sig = (value == null) ? null: Signature.from(value);
  608. }
  609. /**
  610. * The access list.
  611. *
  612. * An access list permits discounted (but pre-paid) access to
  613. * bytecode and state variable access within contract execution.
  614. */
  615. get accessList(): null | AccessList {
  616. const value = this.#accessList || null;
  617. if (value == null) {
  618. if (this.type === 1 || this.type === 2 || this.type === 3) {
  619. // @TODO: in v7, this should assign the value or become
  620. // a live object itself, otherwise mutation is inconsistent
  621. return [ ];
  622. }
  623. return null;
  624. }
  625. return value;
  626. }
  627. set accessList(value: null | AccessListish) {
  628. this.#accessList = (value == null) ? null: accessListify(value);
  629. }
  630. /**
  631. * The max fee per blob gas for Cancun transactions.
  632. */
  633. get maxFeePerBlobGas(): null | bigint {
  634. const value = this.#maxFeePerBlobGas;
  635. if (value == null && this.type === 3) { return BN_0; }
  636. return value;
  637. }
  638. set maxFeePerBlobGas(value: null | BigNumberish) {
  639. this.#maxFeePerBlobGas = (value == null) ? null: getBigInt(value, "maxFeePerBlobGas");
  640. }
  641. /**
  642. * The BLOb versioned hashes for Cancun transactions.
  643. */
  644. get blobVersionedHashes(): null | Array<string> {
  645. // @TODO: Mutation is inconsistent; if unset, the returned value
  646. // cannot mutate the object, if set it can
  647. let value = this.#blobVersionedHashes;
  648. if (value == null && this.type === 3) { return [ ]; }
  649. return value;
  650. }
  651. set blobVersionedHashes(value: null | Array<string>) {
  652. if (value != null) {
  653. assertArgument(Array.isArray(value), "blobVersionedHashes must be an Array", "value", value);
  654. value = value.slice();
  655. for (let i = 0; i < value.length; i++) {
  656. assertArgument(isHexString(value[i], 32), "invalid blobVersionedHash", `value[${ i }]`, value[i]);
  657. }
  658. }
  659. this.#blobVersionedHashes = value;
  660. }
  661. /**
  662. * The BLObs for the Transaction, if any.
  663. *
  664. * If ``blobs`` is non-``null``, then the [[seriailized]]
  665. * will return the network formatted sidecar, otherwise it
  666. * will return the standard [[link-eip-2718]] payload. The
  667. * [[unsignedSerialized]] is unaffected regardless.
  668. *
  669. * When setting ``blobs``, either fully valid [[Blob]] objects
  670. * may be specified (i.e. correctly padded, with correct
  671. * committments and proofs) or a raw [[BytesLike]] may
  672. * be provided.
  673. *
  674. * If raw [[BytesLike]] are provided, the [[kzg]] property **must**
  675. * be already set. The blob will be correctly padded and the
  676. * [[KzgLibrary]] will be used to compute the committment and
  677. * proof for the blob.
  678. *
  679. * A BLOb is a sequence of field elements, each of which must
  680. * be within the BLS field modulo, so some additional processing
  681. * may be required to encode arbitrary data to ensure each 32 byte
  682. * field is within the valid range.
  683. *
  684. * Setting this automatically populates [[blobVersionedHashes]],
  685. * overwriting any existing values. Setting this to ``null``
  686. * does **not** remove the [[blobVersionedHashes]], leaving them
  687. * present.
  688. */
  689. get blobs(): null | Array<Blob> {
  690. if (this.#blobs == null) { return null; }
  691. return this.#blobs.map((b) => Object.assign({ }, b));
  692. }
  693. set blobs(_blobs: null | Array<BlobLike>) {
  694. if (_blobs == null) {
  695. this.#blobs = null;
  696. return;
  697. }
  698. const blobs: Array<Blob> = [ ];
  699. const versionedHashes: Array<string> = [ ];
  700. for (let i = 0; i < _blobs.length; i++) {
  701. const blob = _blobs[i];
  702. if (isBytesLike(blob)) {
  703. assert(this.#kzg, "adding a raw blob requires a KZG library", "UNSUPPORTED_OPERATION", {
  704. operation: "set blobs()"
  705. });
  706. let data = getBytes(blob);
  707. assertArgument(data.length <= BLOB_SIZE, "blob is too large", `blobs[${ i }]`, blob);
  708. // Pad blob if necessary
  709. if (data.length !== BLOB_SIZE) {
  710. const padded = new Uint8Array(BLOB_SIZE);
  711. padded.set(data);
  712. data = padded;
  713. }
  714. const commit = this.#kzg.blobToKzgCommitment(data);
  715. const proof = hexlify(this.#kzg.computeBlobKzgProof(data, commit));
  716. blobs.push({
  717. data: hexlify(data),
  718. commitment: hexlify(commit),
  719. proof
  720. });
  721. versionedHashes.push(getVersionedHash(1, commit));
  722. } else {
  723. const commit = hexlify(blob.commitment);
  724. blobs.push({
  725. data: hexlify(blob.data),
  726. commitment: commit,
  727. proof: hexlify(blob.proof)
  728. });
  729. versionedHashes.push(getVersionedHash(1, commit));
  730. }
  731. }
  732. this.#blobs = blobs;
  733. this.#blobVersionedHashes = versionedHashes;
  734. }
  735. get kzg(): null | KzgLibrary { return this.#kzg; }
  736. set kzg(kzg: null | KzgLibrary) {
  737. this.#kzg = kzg;
  738. }
  739. /**
  740. * Creates a new Transaction with default values.
  741. */
  742. constructor() {
  743. this.#type = null;
  744. this.#to = null;
  745. this.#nonce = 0;
  746. this.#gasLimit = BN_0;
  747. this.#gasPrice = null;
  748. this.#maxPriorityFeePerGas = null;
  749. this.#maxFeePerGas = null;
  750. this.#data = "0x";
  751. this.#value = BN_0;
  752. this.#chainId = BN_0;
  753. this.#sig = null;
  754. this.#accessList = null;
  755. this.#maxFeePerBlobGas = null;
  756. this.#blobVersionedHashes = null;
  757. this.#blobs = null;
  758. this.#kzg = null;
  759. }
  760. /**
  761. * The transaction hash, if signed. Otherwise, ``null``.
  762. */
  763. get hash(): null | string {
  764. if (this.signature == null) { return null; }
  765. return keccak256(this.#getSerialized(true, false));
  766. }
  767. /**
  768. * The pre-image hash of this transaction.
  769. *
  770. * This is the digest that a [[Signer]] must sign to authorize
  771. * this transaction.
  772. */
  773. get unsignedHash(): string {
  774. return keccak256(this.unsignedSerialized);
  775. }
  776. /**
  777. * The sending address, if signed. Otherwise, ``null``.
  778. */
  779. get from(): null | string {
  780. if (this.signature == null) { return null; }
  781. return recoverAddress(this.unsignedHash, this.signature);
  782. }
  783. /**
  784. * The public key of the sender, if signed. Otherwise, ``null``.
  785. */
  786. get fromPublicKey(): null | string {
  787. if (this.signature == null) { return null; }
  788. return SigningKey.recoverPublicKey(this.unsignedHash, this.signature);
  789. }
  790. /**
  791. * Returns true if signed.
  792. *
  793. * This provides a Type Guard that properties requiring a signed
  794. * transaction are non-null.
  795. */
  796. isSigned(): this is (Transaction & { type: number, typeName: string, from: string, signature: Signature }) {
  797. return this.signature != null;
  798. }
  799. #getSerialized(signed: boolean, sidecar: boolean): string {
  800. assert(!signed || this.signature != null, "cannot serialize unsigned transaction; maybe you meant .unsignedSerialized", "UNSUPPORTED_OPERATION", { operation: ".serialized"});
  801. const sig = signed ? this.signature: null;
  802. switch (this.inferType()) {
  803. case 0:
  804. return _serializeLegacy(this, sig);
  805. case 1:
  806. return _serializeEip2930(this, sig);
  807. case 2:
  808. return _serializeEip1559(this, sig);
  809. case 3:
  810. return _serializeEip4844(this, sig, sidecar ? this.blobs: null);
  811. }
  812. assert(false, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: ".serialized" });
  813. }
  814. /**
  815. * The serialized transaction.
  816. *
  817. * This throws if the transaction is unsigned. For the pre-image,
  818. * use [[unsignedSerialized]].
  819. */
  820. get serialized(): string {
  821. return this.#getSerialized(true, true);
  822. }
  823. /**
  824. * The transaction pre-image.
  825. *
  826. * The hash of this is the digest which needs to be signed to
  827. * authorize this transaction.
  828. */
  829. get unsignedSerialized(): string {
  830. return this.#getSerialized(false, false);
  831. }
  832. /**
  833. * Return the most "likely" type; currently the highest
  834. * supported transaction type.
  835. */
  836. inferType(): number {
  837. const types = this.inferTypes();
  838. // Prefer London (EIP-1559) over Cancun (BLOb)
  839. if (types.indexOf(2) >= 0) { return 2; }
  840. // Return the highest inferred type
  841. return <number>(types.pop());
  842. }
  843. /**
  844. * Validates the explicit properties and returns a list of compatible
  845. * transaction types.
  846. */
  847. inferTypes(): Array<number> {
  848. // Checks that there are no conflicting properties set
  849. const hasGasPrice = this.gasPrice != null;
  850. const hasFee = (this.maxFeePerGas != null || this.maxPriorityFeePerGas != null);
  851. const hasAccessList = (this.accessList != null);
  852. const hasBlob = (this.#maxFeePerBlobGas != null || this.#blobVersionedHashes);
  853. //if (hasGasPrice && hasFee) {
  854. // throw new Error("transaction cannot have gasPrice and maxFeePerGas");
  855. //}
  856. if (this.maxFeePerGas != null && this.maxPriorityFeePerGas != null) {
  857. assert(this.maxFeePerGas >= this.maxPriorityFeePerGas, "priorityFee cannot be more than maxFee", "BAD_DATA", { value: this });
  858. }
  859. //if (this.type === 2 && hasGasPrice) {
  860. // throw new Error("eip-1559 transaction cannot have gasPrice");
  861. //}
  862. assert(!hasFee || (this.type !== 0 && this.type !== 1), "transaction type cannot have maxFeePerGas or maxPriorityFeePerGas", "BAD_DATA", { value: this });
  863. assert(this.type !== 0 || !hasAccessList, "legacy transaction cannot have accessList", "BAD_DATA", { value: this })
  864. const types: Array<number> = [ ];
  865. // Explicit type
  866. if (this.type != null) {
  867. types.push(this.type);
  868. } else {
  869. if (hasFee) {
  870. types.push(2);
  871. } else if (hasGasPrice) {
  872. types.push(1);
  873. if (!hasAccessList) { types.push(0); }
  874. } else if (hasAccessList) {
  875. types.push(1);
  876. types.push(2);
  877. } else if (hasBlob && this.to) {
  878. types.push(3);
  879. } else {
  880. types.push(0);
  881. types.push(1);
  882. types.push(2);
  883. types.push(3);
  884. }
  885. }
  886. types.sort();
  887. return types;
  888. }
  889. /**
  890. * Returns true if this transaction is a legacy transaction (i.e.
  891. * ``type === 0``).
  892. *
  893. * This provides a Type Guard that the related properties are
  894. * non-null.
  895. */
  896. isLegacy(): this is (Transaction & { type: 0, gasPrice: bigint }) {
  897. return (this.type === 0);
  898. }
  899. /**
  900. * Returns true if this transaction is berlin hardform transaction (i.e.
  901. * ``type === 1``).
  902. *
  903. * This provides a Type Guard that the related properties are
  904. * non-null.
  905. */
  906. isBerlin(): this is (Transaction & { type: 1, gasPrice: bigint, accessList: AccessList }) {
  907. return (this.type === 1);
  908. }
  909. /**
  910. * Returns true if this transaction is london hardform transaction (i.e.
  911. * ``type === 2``).
  912. *
  913. * This provides a Type Guard that the related properties are
  914. * non-null.
  915. */
  916. isLondon(): this is (Transaction & { type: 2, accessList: AccessList, maxFeePerGas: bigint, maxPriorityFeePerGas: bigint }) {
  917. return (this.type === 2);
  918. }
  919. /**
  920. * Returns true if this transaction is an [[link-eip-4844]] BLOB
  921. * transaction.
  922. *
  923. * This provides a Type Guard that the related properties are
  924. * non-null.
  925. */
  926. isCancun(): this is (Transaction & { type: 3, to: string, accessList: AccessList, maxFeePerGas: bigint, maxPriorityFeePerGas: bigint, maxFeePerBlobGas: bigint, blobVersionedHashes: Array<string> }) {
  927. return (this.type === 3);
  928. }
  929. /**
  930. * Create a copy of this transaciton.
  931. */
  932. clone(): Transaction {
  933. return Transaction.from(this);
  934. }
  935. /**
  936. * Return a JSON-friendly object.
  937. */
  938. toJSON(): any {
  939. const s = (v: null | bigint) => {
  940. if (v == null) { return null; }
  941. return v.toString();
  942. };
  943. return {
  944. type: this.type,
  945. to: this.to,
  946. // from: this.from,
  947. data: this.data,
  948. nonce: this.nonce,
  949. gasLimit: s(this.gasLimit),
  950. gasPrice: s(this.gasPrice),
  951. maxPriorityFeePerGas: s(this.maxPriorityFeePerGas),
  952. maxFeePerGas: s(this.maxFeePerGas),
  953. value: s(this.value),
  954. chainId: s(this.chainId),
  955. sig: this.signature ? this.signature.toJSON(): null,
  956. accessList: this.accessList
  957. };
  958. }
  959. /**
  960. * Create a **Transaction** from a serialized transaction or a
  961. * Transaction-like object.
  962. */
  963. static from(tx?: string | TransactionLike<string>): Transaction {
  964. if (tx == null) { return new Transaction(); }
  965. if (typeof(tx) === "string") {
  966. const payload = getBytes(tx);
  967. if (payload[0] >= 0x7f) { // @TODO: > vs >= ??
  968. return Transaction.from(_parseLegacy(payload));
  969. }
  970. switch(payload[0]) {
  971. case 1: return Transaction.from(_parseEip2930(payload));
  972. case 2: return Transaction.from(_parseEip1559(payload));
  973. case 3: return Transaction.from(_parseEip4844(payload));
  974. }
  975. assert(false, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: "from" });
  976. }
  977. const result = new Transaction();
  978. if (tx.type != null) { result.type = tx.type; }
  979. if (tx.to != null) { result.to = tx.to; }
  980. if (tx.nonce != null) { result.nonce = tx.nonce; }
  981. if (tx.gasLimit != null) { result.gasLimit = tx.gasLimit; }
  982. if (tx.gasPrice != null) { result.gasPrice = tx.gasPrice; }
  983. if (tx.maxPriorityFeePerGas != null) { result.maxPriorityFeePerGas = tx.maxPriorityFeePerGas; }
  984. if (tx.maxFeePerGas != null) { result.maxFeePerGas = tx.maxFeePerGas; }
  985. if (tx.maxFeePerBlobGas != null) { result.maxFeePerBlobGas = tx.maxFeePerBlobGas; }
  986. if (tx.data != null) { result.data = tx.data; }
  987. if (tx.value != null) { result.value = tx.value; }
  988. if (tx.chainId != null) { result.chainId = tx.chainId; }
  989. if (tx.signature != null) { result.signature = Signature.from(tx.signature); }
  990. if (tx.accessList != null) { result.accessList = tx.accessList; }
  991. // This will get overwritten by blobs, if present
  992. if (tx.blobVersionedHashes != null) { result.blobVersionedHashes = tx.blobVersionedHashes; }
  993. // Make sure we assign the kzg before assigning blobs, which
  994. // require the library in the event raw blob data is provided.
  995. if (tx.kzg != null) { result.kzg = tx.kzg; }
  996. if (tx.blobs != null) { result.blobs = tx.blobs; }
  997. if (tx.hash != null) {
  998. assertArgument(result.isSigned(), "unsigned transaction cannot define '.hash'", "tx", tx);
  999. assertArgument(result.hash === tx.hash, "hash mismatch", "tx", tx);
  1000. }
  1001. if (tx.from != null) {
  1002. assertArgument(result.isSigned(), "unsigned transaction cannot define '.from'", "tx", tx);
  1003. assertArgument(result.from.toLowerCase() === (tx.from || "").toLowerCase(), "from mismatch", "tx", tx);
  1004. }
  1005. return result;
  1006. }
  1007. }