@aztec/ethereum 3.0.0-canary.a9708bd → 3.0.0-devnet.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/dest/client.d.ts +1 -1
  2. package/dest/client.d.ts.map +1 -1
  3. package/dest/config.d.ts +11 -6
  4. package/dest/config.d.ts.map +1 -1
  5. package/dest/config.js +124 -64
  6. package/dest/contracts/empire_base.d.ts +1 -1
  7. package/dest/contracts/empire_base.d.ts.map +1 -1
  8. package/dest/contracts/empire_slashing_proposer.d.ts +2 -2
  9. package/dest/contracts/empire_slashing_proposer.d.ts.map +1 -1
  10. package/dest/contracts/empire_slashing_proposer.js +1 -1
  11. package/dest/contracts/fee_asset_handler.d.ts +3 -3
  12. package/dest/contracts/fee_asset_handler.d.ts.map +1 -1
  13. package/dest/contracts/governance.js +7 -3
  14. package/dest/contracts/governance_proposer.d.ts +1 -2
  15. package/dest/contracts/governance_proposer.d.ts.map +1 -1
  16. package/dest/contracts/governance_proposer.js +1 -2
  17. package/dest/contracts/multicall.d.ts +3 -5
  18. package/dest/contracts/multicall.d.ts.map +1 -1
  19. package/dest/contracts/multicall.js +6 -4
  20. package/dest/contracts/rollup.d.ts +39 -19
  21. package/dest/contracts/rollup.d.ts.map +1 -1
  22. package/dest/contracts/rollup.js +84 -88
  23. package/dest/contracts/slasher_contract.d.ts +10 -0
  24. package/dest/contracts/slasher_contract.d.ts.map +1 -1
  25. package/dest/contracts/slasher_contract.js +18 -0
  26. package/dest/contracts/tally_slashing_proposer.d.ts +22 -3
  27. package/dest/contracts/tally_slashing_proposer.d.ts.map +1 -1
  28. package/dest/contracts/tally_slashing_proposer.js +55 -5
  29. package/dest/deploy_l1_contracts.d.ts +22 -7
  30. package/dest/deploy_l1_contracts.d.ts.map +1 -1
  31. package/dest/deploy_l1_contracts.js +555 -362
  32. package/dest/index.d.ts +1 -1
  33. package/dest/index.d.ts.map +1 -1
  34. package/dest/index.js +1 -1
  35. package/dest/l1_artifacts.d.ts +8729 -6014
  36. package/dest/l1_artifacts.d.ts.map +1 -1
  37. package/dest/l1_artifacts.js +10 -5
  38. package/dest/l1_contract_addresses.d.ts +5 -1
  39. package/dest/l1_contract_addresses.d.ts.map +1 -1
  40. package/dest/l1_contract_addresses.js +16 -26
  41. package/dest/l1_reader.d.ts +1 -1
  42. package/dest/l1_reader.d.ts.map +1 -1
  43. package/dest/l1_reader.js +8 -8
  44. package/dest/l1_tx_utils/config.d.ts +59 -0
  45. package/dest/l1_tx_utils/config.d.ts.map +1 -0
  46. package/dest/l1_tx_utils/config.js +73 -0
  47. package/dest/l1_tx_utils/constants.d.ts +6 -0
  48. package/dest/l1_tx_utils/constants.d.ts.map +1 -0
  49. package/dest/l1_tx_utils/constants.js +14 -0
  50. package/dest/l1_tx_utils/factory.d.ts +24 -0
  51. package/dest/l1_tx_utils/factory.d.ts.map +1 -0
  52. package/dest/l1_tx_utils/factory.js +12 -0
  53. package/dest/l1_tx_utils/index.d.ts +10 -0
  54. package/dest/l1_tx_utils/index.d.ts.map +1 -0
  55. package/dest/l1_tx_utils/index.js +10 -0
  56. package/dest/l1_tx_utils/interfaces.d.ts +76 -0
  57. package/dest/l1_tx_utils/interfaces.d.ts.map +1 -0
  58. package/dest/l1_tx_utils/interfaces.js +4 -0
  59. package/dest/l1_tx_utils/l1_tx_utils.d.ts +95 -0
  60. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -0
  61. package/dest/l1_tx_utils/l1_tx_utils.js +610 -0
  62. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts +26 -0
  63. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts.map +1 -0
  64. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.js +26 -0
  65. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +81 -0
  66. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -0
  67. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +294 -0
  68. package/dest/l1_tx_utils/signer.d.ts +4 -0
  69. package/dest/l1_tx_utils/signer.d.ts.map +1 -0
  70. package/dest/l1_tx_utils/signer.js +16 -0
  71. package/dest/l1_tx_utils/types.d.ts +67 -0
  72. package/dest/l1_tx_utils/types.d.ts.map +1 -0
  73. package/dest/l1_tx_utils/types.js +26 -0
  74. package/dest/l1_tx_utils/utils.d.ts +4 -0
  75. package/dest/l1_tx_utils/utils.d.ts.map +1 -0
  76. package/dest/l1_tx_utils/utils.js +14 -0
  77. package/dest/publisher_manager.d.ts +7 -2
  78. package/dest/publisher_manager.d.ts.map +1 -1
  79. package/dest/publisher_manager.js +36 -8
  80. package/dest/queries.d.ts.map +1 -1
  81. package/dest/queries.js +11 -12
  82. package/dest/test/chain_monitor.d.ts +11 -0
  83. package/dest/test/chain_monitor.d.ts.map +1 -1
  84. package/dest/test/chain_monitor.js +81 -12
  85. package/dest/test/delayed_tx_utils.d.ts +2 -2
  86. package/dest/test/delayed_tx_utils.d.ts.map +1 -1
  87. package/dest/test/delayed_tx_utils.js +2 -2
  88. package/dest/test/eth_cheat_codes.d.ts +32 -6
  89. package/dest/test/eth_cheat_codes.d.ts.map +1 -1
  90. package/dest/test/eth_cheat_codes.js +115 -28
  91. package/dest/test/rollup_cheat_codes.d.ts +11 -9
  92. package/dest/test/rollup_cheat_codes.d.ts.map +1 -1
  93. package/dest/test/rollup_cheat_codes.js +38 -6
  94. package/dest/test/upgrade_utils.d.ts.map +1 -1
  95. package/dest/test/upgrade_utils.js +3 -2
  96. package/dest/utils.d.ts.map +1 -1
  97. package/dest/utils.js +10 -161
  98. package/dest/zkPassportVerifierAddress.js +1 -1
  99. package/package.json +7 -7
  100. package/src/client.ts +1 -1
  101. package/src/config.ts +136 -68
  102. package/src/contracts/empire_base.ts +1 -1
  103. package/src/contracts/empire_slashing_proposer.ts +7 -3
  104. package/src/contracts/fee_asset_handler.ts +1 -1
  105. package/src/contracts/governance.ts +3 -3
  106. package/src/contracts/governance_proposer.ts +3 -4
  107. package/src/contracts/multicall.ts +12 -10
  108. package/src/contracts/rollup.ts +104 -106
  109. package/src/contracts/slasher_contract.ts +22 -0
  110. package/src/contracts/tally_slashing_proposer.ts +54 -6
  111. package/src/deploy_l1_contracts.ts +570 -328
  112. package/src/index.ts +1 -1
  113. package/src/l1_artifacts.ts +14 -6
  114. package/src/l1_contract_addresses.ts +17 -26
  115. package/src/l1_reader.ts +9 -9
  116. package/src/l1_tx_utils/README.md +177 -0
  117. package/src/l1_tx_utils/config.ts +140 -0
  118. package/src/l1_tx_utils/constants.ts +18 -0
  119. package/src/l1_tx_utils/factory.ts +64 -0
  120. package/src/l1_tx_utils/index.ts +12 -0
  121. package/src/l1_tx_utils/interfaces.ts +86 -0
  122. package/src/l1_tx_utils/l1_tx_utils.ts +718 -0
  123. package/src/l1_tx_utils/l1_tx_utils_with_blobs.ts +77 -0
  124. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +372 -0
  125. package/src/l1_tx_utils/signer.ts +28 -0
  126. package/src/l1_tx_utils/types.ts +85 -0
  127. package/src/l1_tx_utils/utils.ts +16 -0
  128. package/src/publisher_manager.ts +51 -9
  129. package/src/queries.ts +13 -8
  130. package/src/test/chain_monitor.ts +89 -9
  131. package/src/test/delayed_tx_utils.ts +2 -2
  132. package/src/test/eth_cheat_codes.ts +142 -29
  133. package/src/test/rollup_cheat_codes.ts +54 -14
  134. package/src/test/upgrade_utils.ts +3 -2
  135. package/src/utils.ts +13 -185
  136. package/src/zkPassportVerifierAddress.ts +1 -1
  137. package/dest/l1_tx_utils.d.ts +0 -250
  138. package/dest/l1_tx_utils.d.ts.map +0 -1
  139. package/dest/l1_tx_utils.js +0 -826
  140. package/dest/l1_tx_utils_with_blobs.d.ts +0 -19
  141. package/dest/l1_tx_utils_with_blobs.d.ts.map +0 -1
  142. package/dest/l1_tx_utils_with_blobs.js +0 -85
  143. package/src/l1_tx_utils.ts +0 -1105
  144. package/src/l1_tx_utils_with_blobs.ts +0 -144
@@ -0,0 +1,77 @@
1
+ import { Blob } from '@aztec/blob-lib';
2
+ import { EthAddress } from '@aztec/foundation/eth-address';
3
+ import type { Logger } from '@aztec/foundation/log';
4
+ import { DateProvider } from '@aztec/foundation/timer';
5
+
6
+ import type { TransactionSerializable } from 'viem';
7
+
8
+ import type { EthSigner } from '../eth-signer/eth-signer.js';
9
+ import type { ExtendedViemWalletClient, ViemClient } from '../types.js';
10
+ import type { L1TxUtilsConfig } from './config.js';
11
+ import type { IL1TxMetrics, IL1TxStore } from './interfaces.js';
12
+ import { L1TxUtils } from './l1_tx_utils.js';
13
+ import { createViemSigner } from './signer.js';
14
+ import type { L1BlobInputs, SigningCallback } from './types.js';
15
+
16
+ /** Extends L1TxUtils with the capability to cancel blobs. This needs to be a separate class so we don't require a dependency on blob-lib unnecessarily. */
17
+ export class L1TxUtilsWithBlobs extends L1TxUtils {
18
+ /** Makes empty blob inputs for the cancellation tx. */
19
+ protected override makeEmptyBlobInputs(maxFeePerBlobGas: bigint): Required<L1BlobInputs> {
20
+ const blobData = new Uint8Array(131072).fill(0);
21
+ const kzg = Blob.getViemKzgInstance();
22
+ return { blobs: [blobData], kzg, maxFeePerBlobGas };
23
+ }
24
+ }
25
+
26
+ export function createL1TxUtilsWithBlobsFromViemWallet(
27
+ client: ExtendedViemWalletClient,
28
+ deps: {
29
+ logger?: Logger;
30
+ dateProvider?: DateProvider;
31
+ store?: IL1TxStore;
32
+ metrics?: IL1TxMetrics;
33
+ } = {},
34
+ config: Partial<L1TxUtilsConfig> = {},
35
+ debugMaxGasLimit: boolean = false,
36
+ ) {
37
+ return new L1TxUtilsWithBlobs(
38
+ client,
39
+ EthAddress.fromString(client.account.address),
40
+ createViemSigner(client),
41
+ deps.logger,
42
+ deps.dateProvider,
43
+ config,
44
+ debugMaxGasLimit,
45
+ deps.store,
46
+ deps.metrics,
47
+ );
48
+ }
49
+
50
+ export function createL1TxUtilsWithBlobsFromEthSigner(
51
+ client: ViemClient,
52
+ signer: EthSigner,
53
+ deps: {
54
+ logger?: Logger;
55
+ dateProvider?: DateProvider;
56
+ store?: IL1TxStore;
57
+ metrics?: IL1TxMetrics;
58
+ } = {},
59
+ config: Partial<L1TxUtilsConfig> = {},
60
+ debugMaxGasLimit: boolean = false,
61
+ ) {
62
+ const callback: SigningCallback = async (transaction: TransactionSerializable, _signingAddress) => {
63
+ return (await signer.signTransaction(transaction)).toViemTransactionSignature();
64
+ };
65
+
66
+ return new L1TxUtilsWithBlobs(
67
+ client,
68
+ signer.address,
69
+ callback,
70
+ deps.logger,
71
+ deps.dateProvider,
72
+ config,
73
+ debugMaxGasLimit,
74
+ deps.store,
75
+ deps.metrics,
76
+ );
77
+ }
@@ -0,0 +1,372 @@
1
+ import { getKeys, merge, pick, times } from '@aztec/foundation/collection';
2
+ import { type Logger, createLogger } from '@aztec/foundation/log';
3
+ import { makeBackoff, retry } from '@aztec/foundation/retry';
4
+ import { DateProvider } from '@aztec/foundation/timer';
5
+ import { RollupAbi } from '@aztec/l1-artifacts/RollupAbi';
6
+
7
+ import pickBy from 'lodash.pickby';
8
+ import {
9
+ type Abi,
10
+ type Account,
11
+ type BaseError,
12
+ type BlockOverrides,
13
+ type ContractFunctionExecutionError,
14
+ type Hex,
15
+ MethodNotFoundRpcError,
16
+ MethodNotSupportedRpcError,
17
+ type StateOverride,
18
+ decodeErrorResult,
19
+ formatGwei,
20
+ getContractError,
21
+ hexToBytes,
22
+ } from 'viem';
23
+
24
+ import type { ViemClient } from '../types.js';
25
+ import { type L1TxUtilsConfig, defaultL1TxUtilsConfig, l1TxUtilsConfigMappings } from './config.js';
26
+ import {
27
+ BLOCK_TIME_MS,
28
+ LARGE_GAS_LIMIT,
29
+ MIN_BLOB_REPLACEMENT_BUMP_PERCENTAGE,
30
+ MIN_REPLACEMENT_BUMP_PERCENTAGE,
31
+ WEI_CONST,
32
+ } from './constants.js';
33
+ import type { GasPrice, L1BlobInputs, L1TxRequest, TransactionStats } from './types.js';
34
+ import { getCalldataGasUsage, tryGetCustomErrorNameContractFunction } from './utils.js';
35
+
36
+ export class ReadOnlyL1TxUtils {
37
+ public config: Required<L1TxUtilsConfig>;
38
+ protected interrupted = false;
39
+
40
+ constructor(
41
+ public client: ViemClient,
42
+ protected logger: Logger = createLogger('ethereum:readonly-l1-utils'),
43
+ public readonly dateProvider: DateProvider,
44
+ config?: Partial<L1TxUtilsConfig>,
45
+ protected debugMaxGasLimit: boolean = false,
46
+ ) {
47
+ this.config = merge(defaultL1TxUtilsConfig, pick(config || {}, ...getKeys(l1TxUtilsConfigMappings)));
48
+ }
49
+
50
+ public interrupt() {
51
+ this.interrupted = true;
52
+ }
53
+
54
+ public restart() {
55
+ this.interrupted = false;
56
+ }
57
+
58
+ public getBlock() {
59
+ return this.client.getBlock();
60
+ }
61
+
62
+ public getBlockNumber() {
63
+ return this.client.getBlockNumber();
64
+ }
65
+
66
+ /**
67
+ * Gets the current gas price with bounds checking
68
+ */
69
+ public async getGasPrice(
70
+ gasConfigOverrides?: L1TxUtilsConfig,
71
+ isBlobTx: boolean = false,
72
+ attempt: number = 0,
73
+ previousGasPrice?: typeof attempt extends 0 ? never : GasPrice,
74
+ ): Promise<GasPrice> {
75
+ const gasConfig = merge(this.config, gasConfigOverrides);
76
+ const block = await this.client.getBlock({ blockTag: 'latest' });
77
+ const baseFee = block.baseFeePerGas ?? 0n;
78
+
79
+ // Get blob base fee if available
80
+ let blobBaseFee = 0n;
81
+ if (isBlobTx) {
82
+ try {
83
+ blobBaseFee = await retry<bigint>(
84
+ () => this.client.getBlobBaseFee(),
85
+ 'Getting L1 blob base fee',
86
+ makeBackoff(times(2, () => 1)),
87
+ this.logger,
88
+ true,
89
+ );
90
+ } catch {
91
+ this.logger?.warn('Failed to get L1 blob base fee', attempt);
92
+ }
93
+ }
94
+
95
+ let priorityFee: bigint;
96
+ if (gasConfig.fixedPriorityFeePerGas) {
97
+ this.logger?.debug('Using fixed priority fee per L1 gas', {
98
+ fixedPriorityFeePerGas: gasConfig.fixedPriorityFeePerGas,
99
+ });
100
+ // try to maintain precision up to 1000000 wei
101
+ priorityFee = BigInt(gasConfig.fixedPriorityFeePerGas * 1_000_000) * (WEI_CONST / 1_000_000n);
102
+ } else {
103
+ // Get initial priority fee from the network
104
+ priorityFee = await this.client.estimateMaxPriorityFeePerGas();
105
+ }
106
+ let maxFeePerGas = baseFee;
107
+
108
+ let maxFeePerBlobGas = blobBaseFee;
109
+
110
+ // Bump base fee so it's valid for next blocks if it stalls
111
+ const numBlocks = Math.ceil(gasConfig.stallTimeMs! / BLOCK_TIME_MS);
112
+ for (let i = 0; i < numBlocks; i++) {
113
+ // each block can go up 12.5% from previous baseFee
114
+ maxFeePerGas = (maxFeePerGas * (1_000n + 125n)) / 1_000n;
115
+ // same for blob gas fee
116
+ maxFeePerBlobGas = (maxFeePerBlobGas * (1_000n + 125n)) / 1_000n;
117
+ }
118
+ if (attempt > 0) {
119
+ const configBump =
120
+ gasConfig.priorityFeeRetryBumpPercentage ?? defaultL1TxUtilsConfig.priorityFeeRetryBumpPercentage!;
121
+
122
+ // if this is a blob tx, we have to use the blob bump percentage
123
+ const minBumpPercentage = isBlobTx ? MIN_BLOB_REPLACEMENT_BUMP_PERCENTAGE : MIN_REPLACEMENT_BUMP_PERCENTAGE;
124
+
125
+ const bumpPercentage = configBump > minBumpPercentage ? configBump : minBumpPercentage;
126
+ // Calculate minimum required fees based on previous attempt
127
+ // multiply by 100 & divide by 100 to maintain some precision
128
+ const minPriorityFee =
129
+ (previousGasPrice!.maxPriorityFeePerGas * (100_00n + BigInt(bumpPercentage * 1_00))) / 100_00n;
130
+ const minMaxFee = (previousGasPrice!.maxFeePerGas * (100_00n + BigInt(bumpPercentage * 1_00))) / 100_00n;
131
+
132
+ // Add priority fee to maxFeePerGas
133
+ maxFeePerGas += priorityFee;
134
+
135
+ // Use maximum between current network values and minimum required values
136
+ priorityFee = priorityFee > minPriorityFee ? priorityFee : minPriorityFee;
137
+ maxFeePerGas = maxFeePerGas > minMaxFee ? maxFeePerGas : minMaxFee;
138
+ } else {
139
+ // first attempt, just bump priority fee, unless it's a fixed config
140
+ // multiply by 100 & divide by 100 to maintain some precision
141
+ if (!gasConfig.fixedPriorityFeePerGas) {
142
+ priorityFee = (priorityFee * (100_00n + BigInt((gasConfig.priorityFeeBumpPercentage || 0) * 1_00))) / 100_00n;
143
+ }
144
+ maxFeePerGas += priorityFee;
145
+ }
146
+
147
+ // Ensure we don't exceed maxGwei
148
+ const maxGweiInWei = gasConfig.maxGwei! * WEI_CONST;
149
+ maxFeePerGas = maxFeePerGas > maxGweiInWei ? maxGweiInWei : maxFeePerGas;
150
+
151
+ // Ensure we don't exceed maxBlobGwei
152
+ if (maxFeePerBlobGas) {
153
+ const maxBlobGweiInWei = gasConfig.maxBlobGwei! * WEI_CONST;
154
+ maxFeePerBlobGas = maxFeePerBlobGas > maxBlobGweiInWei ? maxBlobGweiInWei : maxFeePerBlobGas;
155
+ }
156
+
157
+ // Ensure priority fee doesn't exceed max fee
158
+ const maxPriorityFeePerGas = priorityFee > maxFeePerGas ? maxFeePerGas : priorityFee;
159
+
160
+ if (attempt > 0 && previousGasPrice?.maxFeePerBlobGas) {
161
+ const bumpPercentage =
162
+ gasConfig.priorityFeeRetryBumpPercentage! > MIN_BLOB_REPLACEMENT_BUMP_PERCENTAGE
163
+ ? gasConfig.priorityFeeRetryBumpPercentage!
164
+ : MIN_BLOB_REPLACEMENT_BUMP_PERCENTAGE;
165
+
166
+ // calculate min blob fee based on previous attempt
167
+ const minBlobFee = (previousGasPrice.maxFeePerBlobGas * (100_00n + BigInt(bumpPercentage * 1_00))) / 100_00n;
168
+
169
+ // use max between current network values and min required values
170
+ maxFeePerBlobGas = maxFeePerBlobGas > minBlobFee ? maxFeePerBlobGas : minBlobFee;
171
+ }
172
+
173
+ this.logger?.trace(
174
+ `Computed L1 gas price max fee ${formatGwei(maxFeePerGas)} and max priority fee ${formatGwei(maxPriorityFeePerGas)}`,
175
+ {
176
+ attempt,
177
+ baseFee: formatGwei(baseFee),
178
+ maxFeePerGas: formatGwei(maxFeePerGas),
179
+ maxPriorityFeePerGas: formatGwei(maxPriorityFeePerGas),
180
+ blobBaseFee: formatGwei(blobBaseFee),
181
+ maxFeePerBlobGas: formatGwei(maxFeePerBlobGas),
182
+ },
183
+ );
184
+
185
+ return {
186
+ maxFeePerGas,
187
+ maxPriorityFeePerGas,
188
+ ...(maxFeePerBlobGas && { maxFeePerBlobGas: maxFeePerBlobGas }),
189
+ };
190
+ }
191
+
192
+ /**
193
+ * Estimates gas and adds buffer
194
+ */
195
+ public async estimateGas(
196
+ account: Account | Hex,
197
+ request: L1TxRequest,
198
+ _gasConfig?: L1TxUtilsConfig,
199
+ _blobInputs?: L1BlobInputs,
200
+ ): Promise<bigint> {
201
+ const gasConfig = { ...this.config, ..._gasConfig };
202
+ let initialEstimate = 0n;
203
+ if (_blobInputs) {
204
+ // @note requests with blobs also require maxFeePerBlobGas to be set
205
+ const gasPrice = await this.getGasPrice(gasConfig, true, 0);
206
+ initialEstimate = await this.client.estimateGas({
207
+ account,
208
+ ...request,
209
+ ..._blobInputs,
210
+ maxFeePerBlobGas: gasPrice.maxFeePerBlobGas!,
211
+ gas: LARGE_GAS_LIMIT,
212
+ });
213
+
214
+ this.logger?.trace(`Estimated gas for blob tx: ${initialEstimate}`);
215
+ } else {
216
+ initialEstimate = await this.client.estimateGas({ account, ...request, gas: LARGE_GAS_LIMIT });
217
+ this.logger?.trace(`Estimated gas for non-blob tx: ${initialEstimate}`);
218
+ }
219
+
220
+ // Add buffer based on either fixed amount or percentage
221
+ const withBuffer = this.bumpGasLimit(initialEstimate, gasConfig);
222
+
223
+ return withBuffer;
224
+ }
225
+
226
+ async getTransactionStats(txHash: string): Promise<TransactionStats | undefined> {
227
+ const tx = await this.client.getTransaction({ hash: txHash as Hex });
228
+ if (!tx) {
229
+ return undefined;
230
+ }
231
+ const calldata = hexToBytes(tx.input);
232
+ return {
233
+ sender: tx.from.toString(),
234
+ transactionHash: tx.hash,
235
+ calldataSize: calldata.length,
236
+ calldataGas: getCalldataGasUsage(calldata),
237
+ };
238
+ }
239
+
240
+ public async tryGetErrorFromRevertedTx(
241
+ data: Hex,
242
+ args: {
243
+ args: readonly any[];
244
+ functionName: string;
245
+ abi: Abi;
246
+ address: Hex;
247
+ },
248
+ blobInputs: (L1BlobInputs & { maxFeePerBlobGas: bigint }) | undefined,
249
+ stateOverride: StateOverride = [],
250
+ ) {
251
+ try {
252
+ await this.client.simulateContract({
253
+ ...args,
254
+ account: this.client.account,
255
+ stateOverride,
256
+ });
257
+ this.logger?.trace('Simulated blob tx', { blobInputs });
258
+ // If the above passes, we have a blob error. We cannot simulate blob txs, and failed txs no longer throw errors.
259
+ // Strangely, the only way to throw the revert reason as an error and provide blobs is prepareTransactionRequest.
260
+ // See: https://github.com/wevm/viem/issues/2075
261
+ // This throws a EstimateGasExecutionError with the custom error information:
262
+ const request = blobInputs
263
+ ? {
264
+ account: this.client.account,
265
+ to: args.address,
266
+ data,
267
+ blobs: blobInputs.blobs,
268
+ kzg: blobInputs.kzg,
269
+ maxFeePerBlobGas: blobInputs.maxFeePerBlobGas,
270
+ }
271
+ : {
272
+ account: this.client.account,
273
+ to: args.address,
274
+ data,
275
+ };
276
+ this.logger?.trace('Preparing tx', { request });
277
+ await this.client.prepareTransactionRequest(request);
278
+ this.logger?.trace('Prepared tx');
279
+ return undefined;
280
+ } catch (simulationErr: any) {
281
+ // If we don't have a ContractFunctionExecutionError, we have a blob related error => use getContractError to get the error msg.
282
+ const contractErr =
283
+ simulationErr.name === 'ContractFunctionExecutionError'
284
+ ? simulationErr
285
+ : getContractError(simulationErr as BaseError, {
286
+ args: [],
287
+ abi: args.abi,
288
+ functionName: args.functionName,
289
+ address: args.address,
290
+ });
291
+ if (contractErr.name === 'ContractFunctionExecutionError') {
292
+ const execErr = contractErr as ContractFunctionExecutionError;
293
+ return tryGetCustomErrorNameContractFunction(execErr);
294
+ }
295
+ this.logger?.error(`Error getting error from simulation`, simulationErr);
296
+ }
297
+ }
298
+
299
+ public async simulate(
300
+ request: L1TxRequest & { gas?: bigint; from?: Hex },
301
+ blockOverrides: BlockOverrides<bigint, number> = {},
302
+ stateOverrides: StateOverride = [],
303
+ abi: Abi = RollupAbi,
304
+ _gasConfig?: L1TxUtilsConfig & { fallbackGasEstimate?: bigint },
305
+ ): Promise<{ gasUsed: bigint; result: `0x${string}` }> {
306
+ const gasConfig = { ...this.config, ..._gasConfig };
307
+
308
+ const call: any = {
309
+ to: request.to!,
310
+ data: request.data,
311
+ ...(request.from && { from: request.from }),
312
+ };
313
+
314
+ return await this._simulate(call, blockOverrides, stateOverrides, gasConfig, abi);
315
+ }
316
+
317
+ protected async _simulate(
318
+ call: any,
319
+ blockOverrides: BlockOverrides<bigint, number> = {},
320
+ stateOverrides: StateOverride = [],
321
+ gasConfig: L1TxUtilsConfig & { fallbackGasEstimate?: bigint },
322
+ abi: Abi,
323
+ ) {
324
+ try {
325
+ const result = await this.client.simulateBlocks({
326
+ validation: false,
327
+ blocks: [
328
+ {
329
+ blockOverrides,
330
+ stateOverrides,
331
+ calls: [call],
332
+ },
333
+ ],
334
+ });
335
+
336
+ if (result[0].calls[0].status === 'failure') {
337
+ this.logger?.error('L1 transaction simulation failed', result[0].calls[0].error);
338
+ const decodedError = decodeErrorResult({ abi, data: result[0].calls[0].data });
339
+
340
+ throw new Error(
341
+ `L1 transaction simulation failed with error ${decodedError.errorName}(${decodedError.args?.join(',')})`,
342
+ );
343
+ }
344
+ this.logger?.debug(`L1 transaction simulation succeeded`, { ...result[0].calls[0] });
345
+ return { gasUsed: result[0].gasUsed, result: result[0].calls[0].data as `0x${string}` };
346
+ } catch (err) {
347
+ if (err instanceof MethodNotFoundRpcError || err instanceof MethodNotSupportedRpcError) {
348
+ if (gasConfig.fallbackGasEstimate) {
349
+ this.logger?.warn(
350
+ `Node does not support eth_simulateV1 API. Using fallback gas estimate: ${gasConfig.fallbackGasEstimate}`,
351
+ );
352
+ return { gasUsed: gasConfig.fallbackGasEstimate, result: '0x' as `0x${string}` };
353
+ }
354
+ this.logger?.error('Node does not support eth_simulateV1 API');
355
+ }
356
+ throw err;
357
+ }
358
+ }
359
+
360
+ public bumpGasLimit(gasLimit: bigint, _gasConfig?: L1TxUtilsConfig): bigint {
361
+ const gasConfig = { ...this.config, ..._gasConfig };
362
+ const bumpedGasLimit = gasLimit + (gasLimit * BigInt((gasConfig?.gasLimitBufferPercentage || 0) * 1_00)) / 100_00n;
363
+
364
+ const cleanGasConfig = pickBy(gasConfig, (_, key) => key in l1TxUtilsConfigMappings);
365
+ this.logger?.trace(`Bumping gas limit from ${gasLimit} to ${bumpedGasLimit}`, {
366
+ gasLimit,
367
+ gasConfig: cleanGasConfig,
368
+ bumpedGasLimit,
369
+ });
370
+ return bumpedGasLimit;
371
+ }
372
+ }
@@ -0,0 +1,28 @@
1
+ import { EthAddress } from '@aztec/foundation/eth-address';
2
+ import type { ViemTransactionSignature } from '@aztec/foundation/eth-signature';
3
+
4
+ import { type TransactionSerializable, type WalletClient, parseTransaction } from 'viem';
5
+
6
+ import type { SigningCallback } from './types.js';
7
+
8
+ export function createViemSigner(client: WalletClient) {
9
+ const signer: SigningCallback = async (
10
+ tx: TransactionSerializable,
11
+ _address: EthAddress,
12
+ ): Promise<ViemTransactionSignature> => {
13
+ const signedTx = await client.signTransaction(tx as any);
14
+
15
+ const parsed = parseTransaction(signedTx);
16
+
17
+ if (!parsed.r || !parsed.s || (parsed.yParity !== 0 && parsed.yParity !== 1)) {
18
+ throw new Error('Failed to extract signature from viem signed transaction');
19
+ }
20
+
21
+ return {
22
+ r: parsed.r,
23
+ s: parsed.s,
24
+ yParity: parsed.yParity,
25
+ };
26
+ };
27
+ return signer;
28
+ }
@@ -0,0 +1,85 @@
1
+ import type { BlobKzgInstance } from '@aztec/blob-lib/types';
2
+ import { EthAddress } from '@aztec/foundation/eth-address';
3
+ import type { ViemTransactionSignature } from '@aztec/foundation/eth-signature';
4
+
5
+ import type { Abi, Address, Hex, TransactionReceipt, TransactionSerializable } from 'viem';
6
+
7
+ import type { L1TxUtilsConfig } from './config.js';
8
+
9
+ export interface L1TxRequest {
10
+ to: Address | null;
11
+ data?: Hex;
12
+ value?: bigint;
13
+ abi?: Abi;
14
+ }
15
+
16
+ export type L1TxConfig = Partial<L1TxUtilsConfig> & { gasLimit?: bigint; txTimeoutAt?: Date };
17
+
18
+ export interface L1BlobInputs {
19
+ blobs: Uint8Array[];
20
+ kzg: BlobKzgInstance;
21
+ maxFeePerBlobGas?: bigint;
22
+ }
23
+
24
+ export interface GasPrice {
25
+ maxFeePerGas: bigint;
26
+ maxPriorityFeePerGas: bigint;
27
+ maxFeePerBlobGas?: bigint;
28
+ }
29
+
30
+ export type TransactionStats = {
31
+ /** Address of the sender. */
32
+ sender: string;
33
+ /** Hash of the transaction. */
34
+ transactionHash: string;
35
+ /** Size in bytes of the tx calldata */
36
+ calldataSize: number;
37
+ /** Gas required to pay for the calldata inclusion (depends on size and number of zeros) */
38
+ calldataGas: number;
39
+ };
40
+
41
+ export enum TxUtilsState {
42
+ IDLE,
43
+ SENT,
44
+ SPEED_UP,
45
+ CANCELLED,
46
+ NOT_MINED,
47
+ MINED,
48
+ }
49
+
50
+ export const TerminalTxUtilsState = [TxUtilsState.IDLE, TxUtilsState.MINED, TxUtilsState.NOT_MINED];
51
+
52
+ export type L1TxState = {
53
+ id: number;
54
+ txHashes: Hex[];
55
+ cancelTxHashes: Hex[];
56
+ gasLimit: bigint;
57
+ gasPrice: GasPrice;
58
+ txConfigOverrides: L1TxConfig;
59
+ request: L1TxRequest;
60
+ status: TxUtilsState;
61
+ nonce: number;
62
+ sentAtL1Ts: Date;
63
+ lastSentAtL1Ts: Date;
64
+ receipt?: TransactionReceipt;
65
+ blobInputs: L1BlobInputs | undefined;
66
+ };
67
+
68
+ export type SigningCallback = (
69
+ transaction: TransactionSerializable,
70
+ signingAddress: EthAddress,
71
+ ) => Promise<ViemTransactionSignature>;
72
+
73
+ export class UnknownMinedTxError extends Error {
74
+ constructor(nonce: number, account: string) {
75
+ super(`Nonce ${nonce} from account ${account} is MINED but not by one of our expected transactions`);
76
+ this.name = 'UnknownMinedTxError';
77
+ }
78
+ }
79
+
80
+ export class DroppedTransactionError extends Error {
81
+ constructor(nonce: number, account: string) {
82
+ super(`Transaction with nonce ${nonce} from account ${account} was dropped from the mempool`);
83
+ this.name = 'DroppedTransactionError';
84
+ }
85
+ }
@@ -0,0 +1,16 @@
1
+ import { compactArray } from '@aztec/foundation/collection';
2
+
3
+ import type { ContractFunctionExecutionError } from 'viem';
4
+
5
+ export function tryGetCustomErrorNameContractFunction(err: ContractFunctionExecutionError) {
6
+ return compactArray([err.shortMessage, ...(err.metaMessages ?? []).slice(0, 2).map(s => s.trim())]).join(' ');
7
+ }
8
+
9
+ /*
10
+ * Returns cost of calldata usage in Ethereum.
11
+ * @param data - Calldata.
12
+ * @returns 4 for each zero byte, 16 for each nonzero.
13
+ */
14
+ export function getCalldataGasUsage(data: Uint8Array) {
15
+ return data.filter(byte => byte === 0).length * 4 + data.filter(byte => byte !== 0).length * 16;
16
+ }
@@ -1,31 +1,73 @@
1
+ import { pick } from '@aztec/foundation/collection';
1
2
  import { createLogger } from '@aztec/foundation/log';
2
3
 
3
- import { L1TxUtils, TxUtilsState } from './l1_tx_utils.js';
4
+ import { L1TxUtils, TxUtilsState } from './l1_tx_utils/index.js';
4
5
 
5
- const sortOrder = [TxUtilsState.IDLE, TxUtilsState.MINED];
6
- const invalidStates = [TxUtilsState.SENT, TxUtilsState.SPEED_UP, TxUtilsState.CANCELLED, TxUtilsState.NOT_MINED]; // Cancelled and not mined are states that can be handled by a later iteration
6
+ // Defines the order in which we prioritise publishers based on their state (first is better)
7
+ const sortOrder = [
8
+ // Always prefer sending from idle publishers
9
+ TxUtilsState.IDLE,
10
+ // Then from publishers that have sent a tx and it got mined
11
+ TxUtilsState.MINED,
12
+ // Then from publishers that have sent a tx but it's in-flight
13
+ TxUtilsState.SPEED_UP,
14
+ TxUtilsState.SENT,
15
+ // We leave cancelled and not-mined states for last, since these represent failures to mines and could be problematic
16
+ TxUtilsState.CANCELLED,
17
+ TxUtilsState.NOT_MINED,
18
+ ];
19
+
20
+ // Which states represent a busy publisher that we should avoid if possible
21
+ const busyStates: TxUtilsState[] = [
22
+ TxUtilsState.SENT,
23
+ TxUtilsState.SPEED_UP,
24
+ TxUtilsState.CANCELLED,
25
+ TxUtilsState.NOT_MINED,
26
+ ];
7
27
 
8
28
  export type PublisherFilter<UtilsType extends L1TxUtils> = (utils: UtilsType) => boolean;
9
29
 
10
30
  export class PublisherManager<UtilsType extends L1TxUtils = L1TxUtils> {
11
- private log = createLogger('PublisherManager');
31
+ private log = createLogger('publisher:manager');
32
+ private config: { publisherAllowInvalidStates?: boolean };
12
33
 
13
- constructor(private publishers: UtilsType[]) {
34
+ constructor(
35
+ private publishers: UtilsType[],
36
+ config: { publisherAllowInvalidStates?: boolean },
37
+ ) {
14
38
  this.log.info(`PublisherManager initialized with ${publishers.length} publishers.`);
15
39
  this.publishers = publishers;
40
+ this.config = pick(config, 'publisherAllowInvalidStates');
41
+ }
42
+
43
+ /** Loads the state of all publishers and resumes monitoring any pending txs */
44
+ public async loadState(): Promise<void> {
45
+ await Promise.all(this.publishers.map(pub => pub.loadStateAndResumeMonitoring()));
16
46
  }
17
47
 
18
48
  // Finds and prioritises available publishers based on
19
49
  // 1. Validity as per the provided filter function
20
50
  // 2. Validity based on the state the publisher is in
21
- // 3. Priority based on state as defined bu sortOrder
51
+ // 3. Priority based on state as defined by sortOrder
22
52
  // 4. Then priority based on highest balance
23
53
  // 5. Then priority based on least recently used
24
54
  public async getAvailablePublisher(filter: PublisherFilter<UtilsType> = () => true): Promise<UtilsType> {
55
+ this.log.debug(`Getting available publisher`, {
56
+ publishers: this.publishers.map(p => ({
57
+ address: p.getSenderAddress(),
58
+ state: p.state,
59
+ lastMined: p.lastMinedAtBlockNumber,
60
+ })),
61
+ });
62
+
25
63
  // Extract the valid publishers
26
- const validPublishers = this.publishers.filter(
27
- (pub: UtilsType) => !invalidStates.includes(pub.state) && filter(pub),
28
- );
64
+ let validPublishers = this.publishers.filter((pub: UtilsType) => !busyStates.includes(pub.state) && filter(pub));
65
+
66
+ // If none found but we allow invalid (busy) states, try again including them
67
+ if (validPublishers.length === 0 && this.config.publisherAllowInvalidStates) {
68
+ this.log.warn(`No valid publishers found. Trying again including invalid states.`);
69
+ validPublishers = this.publishers.filter(pub => filter(pub));
70
+ }
29
71
 
30
72
  // Error if none found
31
73
  if (validPublishers.length === 0) {