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

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 (195) hide show
  1. package/dest/account.d.ts +1 -1
  2. package/dest/chain.d.ts +1 -1
  3. package/dest/client.d.ts +2 -2
  4. package/dest/client.d.ts.map +1 -1
  5. package/dest/config.d.ts +16 -8
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +160 -62
  8. package/dest/constants.d.ts +1 -1
  9. package/dest/contracts/empire_base.d.ts +7 -6
  10. package/dest/contracts/empire_base.d.ts.map +1 -1
  11. package/dest/contracts/empire_base.js +1 -1
  12. package/dest/contracts/empire_slashing_proposer.d.ts +7 -6
  13. package/dest/contracts/empire_slashing_proposer.d.ts.map +1 -1
  14. package/dest/contracts/empire_slashing_proposer.js +9 -3
  15. package/dest/contracts/errors.d.ts +1 -1
  16. package/dest/contracts/errors.d.ts.map +1 -1
  17. package/dest/contracts/fee_asset_handler.d.ts +4 -4
  18. package/dest/contracts/fee_asset_handler.d.ts.map +1 -1
  19. package/dest/contracts/fee_juice.d.ts +1 -1
  20. package/dest/contracts/fee_juice.d.ts.map +1 -1
  21. package/dest/contracts/governance.d.ts +16 -16
  22. package/dest/contracts/governance.d.ts.map +1 -1
  23. package/dest/contracts/governance.js +7 -3
  24. package/dest/contracts/governance_proposer.d.ts +6 -6
  25. package/dest/contracts/governance_proposer.d.ts.map +1 -1
  26. package/dest/contracts/governance_proposer.js +9 -4
  27. package/dest/contracts/gse.d.ts +1 -1
  28. package/dest/contracts/gse.d.ts.map +1 -1
  29. package/dest/contracts/inbox.d.ts +1 -1
  30. package/dest/contracts/inbox.d.ts.map +1 -1
  31. package/dest/contracts/index.d.ts +1 -1
  32. package/dest/contracts/multicall.d.ts +5 -7
  33. package/dest/contracts/multicall.d.ts.map +1 -1
  34. package/dest/contracts/multicall.js +6 -4
  35. package/dest/contracts/registry.d.ts +1 -1
  36. package/dest/contracts/registry.d.ts.map +1 -1
  37. package/dest/contracts/rollup.d.ts +83 -72
  38. package/dest/contracts/rollup.d.ts.map +1 -1
  39. package/dest/contracts/rollup.js +144 -139
  40. package/dest/contracts/slasher_contract.d.ts +11 -1
  41. package/dest/contracts/slasher_contract.d.ts.map +1 -1
  42. package/dest/contracts/slasher_contract.js +18 -0
  43. package/dest/contracts/tally_slashing_proposer.d.ts +30 -9
  44. package/dest/contracts/tally_slashing_proposer.d.ts.map +1 -1
  45. package/dest/contracts/tally_slashing_proposer.js +58 -8
  46. package/dest/contracts/utils.d.ts +1 -1
  47. package/dest/deploy_l1_contracts.d.ts +477 -15
  48. package/dest/deploy_l1_contracts.d.ts.map +1 -1
  49. package/dest/deploy_l1_contracts.js +610 -386
  50. package/dest/eth-signer/eth-signer.d.ts +1 -1
  51. package/dest/eth-signer/index.d.ts +1 -1
  52. package/dest/forwarder_proxy.d.ts +32 -0
  53. package/dest/forwarder_proxy.d.ts.map +1 -0
  54. package/dest/forwarder_proxy.js +93 -0
  55. package/dest/l1_artifacts.d.ts +14258 -6015
  56. package/dest/l1_artifacts.d.ts.map +1 -1
  57. package/dest/l1_artifacts.js +10 -5
  58. package/dest/l1_contract_addresses.d.ts +8 -4
  59. package/dest/l1_contract_addresses.d.ts.map +1 -1
  60. package/dest/l1_contract_addresses.js +16 -26
  61. package/dest/l1_reader.d.ts +4 -2
  62. package/dest/l1_reader.d.ts.map +1 -1
  63. package/dest/l1_reader.js +14 -8
  64. package/dest/l1_tx_utils/config.d.ts +59 -0
  65. package/dest/l1_tx_utils/config.d.ts.map +1 -0
  66. package/dest/l1_tx_utils/config.js +96 -0
  67. package/dest/l1_tx_utils/constants.d.ts +6 -0
  68. package/dest/l1_tx_utils/constants.d.ts.map +1 -0
  69. package/dest/l1_tx_utils/constants.js +14 -0
  70. package/dest/l1_tx_utils/factory.d.ts +24 -0
  71. package/dest/l1_tx_utils/factory.d.ts.map +1 -0
  72. package/dest/l1_tx_utils/factory.js +12 -0
  73. package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts +41 -0
  74. package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts.map +1 -0
  75. package/dest/l1_tx_utils/forwarder_l1_tx_utils.js +48 -0
  76. package/dest/l1_tx_utils/index-blobs.d.ts +3 -0
  77. package/dest/l1_tx_utils/index-blobs.d.ts.map +1 -0
  78. package/dest/l1_tx_utils/index-blobs.js +2 -0
  79. package/dest/l1_tx_utils/index.d.ts +10 -0
  80. package/dest/l1_tx_utils/index.d.ts.map +1 -0
  81. package/dest/l1_tx_utils/index.js +10 -0
  82. package/dest/l1_tx_utils/interfaces.d.ts +76 -0
  83. package/dest/l1_tx_utils/interfaces.d.ts.map +1 -0
  84. package/dest/l1_tx_utils/interfaces.js +4 -0
  85. package/dest/l1_tx_utils/l1_tx_utils.d.ts +94 -0
  86. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -0
  87. package/dest/l1_tx_utils/l1_tx_utils.js +623 -0
  88. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts +26 -0
  89. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts.map +1 -0
  90. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.js +26 -0
  91. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +94 -0
  92. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -0
  93. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +431 -0
  94. package/dest/l1_tx_utils/signer.d.ts +4 -0
  95. package/dest/l1_tx_utils/signer.d.ts.map +1 -0
  96. package/dest/l1_tx_utils/signer.js +16 -0
  97. package/dest/l1_tx_utils/types.d.ts +67 -0
  98. package/dest/l1_tx_utils/types.d.ts.map +1 -0
  99. package/dest/l1_tx_utils/types.js +26 -0
  100. package/dest/l1_tx_utils/utils.d.ts +4 -0
  101. package/dest/l1_tx_utils/utils.d.ts.map +1 -0
  102. package/dest/l1_tx_utils/utils.js +14 -0
  103. package/dest/l1_types.d.ts +1 -1
  104. package/dest/publisher_manager.d.ts +8 -3
  105. package/dest/publisher_manager.d.ts.map +1 -1
  106. package/dest/publisher_manager.js +36 -8
  107. package/dest/queries.d.ts +1 -1
  108. package/dest/queries.d.ts.map +1 -1
  109. package/dest/queries.js +13 -12
  110. package/dest/test/chain_monitor.d.ts +33 -19
  111. package/dest/test/chain_monitor.d.ts.map +1 -1
  112. package/dest/test/chain_monitor.js +100 -33
  113. package/dest/test/delayed_tx_utils.d.ts +3 -3
  114. package/dest/test/delayed_tx_utils.d.ts.map +1 -1
  115. package/dest/test/delayed_tx_utils.js +2 -2
  116. package/dest/test/eth_cheat_codes.d.ts +36 -14
  117. package/dest/test/eth_cheat_codes.d.ts.map +1 -1
  118. package/dest/test/eth_cheat_codes.js +124 -31
  119. package/dest/test/eth_cheat_codes_with_state.d.ts +1 -1
  120. package/dest/test/eth_cheat_codes_with_state.d.ts.map +1 -1
  121. package/dest/test/index.d.ts +1 -1
  122. package/dest/test/rollup_cheat_codes.d.ts +23 -20
  123. package/dest/test/rollup_cheat_codes.d.ts.map +1 -1
  124. package/dest/test/rollup_cheat_codes.js +79 -42
  125. package/dest/test/start_anvil.d.ts +2 -1
  126. package/dest/test/start_anvil.d.ts.map +1 -1
  127. package/dest/test/start_anvil.js +2 -1
  128. package/dest/test/tx_delayer.d.ts +1 -1
  129. package/dest/test/tx_delayer.d.ts.map +1 -1
  130. package/dest/test/tx_delayer.js +3 -2
  131. package/dest/test/upgrade_utils.d.ts +1 -1
  132. package/dest/test/upgrade_utils.d.ts.map +1 -1
  133. package/dest/test/upgrade_utils.js +3 -2
  134. package/dest/types.d.ts +57 -2
  135. package/dest/types.d.ts.map +1 -1
  136. package/dest/utils.d.ts +2 -2
  137. package/dest/utils.d.ts.map +1 -1
  138. package/dest/utils.js +10 -161
  139. package/dest/zkPassportVerifierAddress.d.ts +1 -1
  140. package/dest/zkPassportVerifierAddress.js +1 -1
  141. package/package.json +27 -13
  142. package/src/client.ts +1 -1
  143. package/src/config.ts +177 -65
  144. package/src/contracts/empire_base.ts +7 -6
  145. package/src/contracts/empire_slashing_proposer.ts +18 -8
  146. package/src/contracts/fee_asset_handler.ts +1 -1
  147. package/src/contracts/governance.ts +3 -3
  148. package/src/contracts/governance_proposer.ts +14 -9
  149. package/src/contracts/multicall.ts +12 -10
  150. package/src/contracts/rollup.ts +170 -171
  151. package/src/contracts/slasher_contract.ts +22 -0
  152. package/src/contracts/tally_slashing_proposer.ts +63 -12
  153. package/src/deploy_l1_contracts.ts +610 -337
  154. package/src/forwarder_proxy.ts +108 -0
  155. package/src/l1_artifacts.ts +14 -6
  156. package/src/l1_contract_addresses.ts +17 -26
  157. package/src/l1_reader.ts +17 -9
  158. package/src/l1_tx_utils/README.md +177 -0
  159. package/src/l1_tx_utils/config.ts +161 -0
  160. package/src/l1_tx_utils/constants.ts +18 -0
  161. package/src/l1_tx_utils/factory.ts +64 -0
  162. package/src/l1_tx_utils/forwarder_l1_tx_utils.ts +119 -0
  163. package/src/l1_tx_utils/index-blobs.ts +2 -0
  164. package/src/l1_tx_utils/index.ts +12 -0
  165. package/src/l1_tx_utils/interfaces.ts +86 -0
  166. package/src/l1_tx_utils/l1_tx_utils.ts +738 -0
  167. package/src/l1_tx_utils/l1_tx_utils_with_blobs.ts +77 -0
  168. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +557 -0
  169. package/src/l1_tx_utils/signer.ts +28 -0
  170. package/src/l1_tx_utils/types.ts +85 -0
  171. package/src/l1_tx_utils/utils.ts +16 -0
  172. package/src/publisher_manager.ts +51 -9
  173. package/src/queries.ts +16 -8
  174. package/src/test/chain_monitor.ts +118 -36
  175. package/src/test/delayed_tx_utils.ts +2 -2
  176. package/src/test/eth_cheat_codes.ts +149 -30
  177. package/src/test/rollup_cheat_codes.ts +94 -52
  178. package/src/test/start_anvil.ts +2 -0
  179. package/src/test/tx_delayer.ts +4 -2
  180. package/src/test/upgrade_utils.ts +3 -2
  181. package/src/types.ts +62 -0
  182. package/src/utils.ts +12 -184
  183. package/src/zkPassportVerifierAddress.ts +1 -1
  184. package/dest/index.d.ts +0 -18
  185. package/dest/index.d.ts.map +0 -1
  186. package/dest/index.js +0 -17
  187. package/dest/l1_tx_utils.d.ts +0 -250
  188. package/dest/l1_tx_utils.d.ts.map +0 -1
  189. package/dest/l1_tx_utils.js +0 -826
  190. package/dest/l1_tx_utils_with_blobs.d.ts +0 -19
  191. package/dest/l1_tx_utils_with_blobs.d.ts.map +0 -1
  192. package/dest/l1_tx_utils_with_blobs.js +0 -85
  193. package/src/index.ts +0 -17
  194. package/src/l1_tx_utils.ts +0 -1105
  195. 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,557 @@
1
+ import { getKeys, median, 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
+ const HISTORICAL_BLOCK_COUNT = 5;
37
+
38
+ export class ReadOnlyL1TxUtils {
39
+ public config: Required<L1TxUtilsConfig>;
40
+ protected interrupted = false;
41
+
42
+ constructor(
43
+ public client: ViemClient,
44
+ protected logger: Logger = createLogger('ethereum:readonly-l1-utils'),
45
+ public readonly dateProvider: DateProvider,
46
+ config?: Partial<L1TxUtilsConfig>,
47
+ protected debugMaxGasLimit: boolean = false,
48
+ ) {
49
+ this.config = merge(defaultL1TxUtilsConfig, pick(config || {}, ...getKeys(l1TxUtilsConfigMappings)));
50
+ }
51
+
52
+ public interrupt() {
53
+ this.interrupted = true;
54
+ }
55
+
56
+ public restart() {
57
+ this.interrupted = false;
58
+ }
59
+
60
+ public getBlock() {
61
+ return this.client.getBlock();
62
+ }
63
+
64
+ public getBlockNumber() {
65
+ return this.client.getBlockNumber();
66
+ }
67
+
68
+ /**
69
+ * Analyzes pending transactions and recent fee history to determine a competitive priority fee.
70
+ * Falls back to network estimate if data is unavailable or fails.
71
+ * @param networkEstimateResult - Result from estimateMaxPriorityFeePerGas RPC call
72
+ * @param pendingBlockResult - Result from getBlock with pending tag RPC call
73
+ * @param feeHistoryResult - Result from getFeeHistory RPC call
74
+ * @returns A competitive priority fee based on pending txs and recent block history
75
+ */
76
+ protected getCompetitivePriorityFee(
77
+ networkEstimateResult: PromiseSettledResult<bigint | null>,
78
+ pendingBlockResult: PromiseSettledResult<Awaited<ReturnType<ViemClient['getBlock']>> | null>,
79
+ feeHistoryResult: PromiseSettledResult<Awaited<ReturnType<ViemClient['getFeeHistory']>> | null>,
80
+ ): bigint {
81
+ const networkEstimate =
82
+ networkEstimateResult.status === 'fulfilled' && typeof networkEstimateResult.value === 'bigint'
83
+ ? networkEstimateResult.value
84
+ : 0n;
85
+ let competitiveFee = networkEstimate;
86
+
87
+ if (
88
+ pendingBlockResult.status === 'fulfilled' &&
89
+ pendingBlockResult.value !== null &&
90
+ pendingBlockResult.value.transactions &&
91
+ pendingBlockResult.value.transactions.length > 0
92
+ ) {
93
+ const pendingBlock = pendingBlockResult.value;
94
+ // Extract priority fees from pending transactions
95
+ const pendingFees = pendingBlock.transactions
96
+ .map(tx => {
97
+ // Transaction can be just a hash string, so we need to check if it's an object
98
+ if (typeof tx === 'string') {
99
+ return 0n;
100
+ }
101
+ const fee = tx.maxPriorityFeePerGas || 0n;
102
+ // Debug: Log suspicious fees
103
+ if (fee > 100n * WEI_CONST) {
104
+ this.logger?.warn('Suspicious high priority fee in pending tx', {
105
+ txHash: tx.hash,
106
+ maxPriorityFeePerGas: formatGwei(fee),
107
+ maxFeePerGas: formatGwei(tx.maxFeePerGas || 0n),
108
+ maxFeePerBlobGas: tx.maxFeePerBlobGas ? formatGwei(tx.maxFeePerBlobGas) : 'N/A',
109
+ });
110
+ }
111
+ return fee;
112
+ })
113
+ .filter((fee: bigint) => fee > 0n);
114
+
115
+ if (pendingFees.length > 0) {
116
+ // Use 75th percentile of pending fees to be competitive
117
+ const sortedPendingFees = [...pendingFees].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
118
+ const percentile75Index = Math.floor((sortedPendingFees.length - 1) * 0.75);
119
+ const pendingCompetitiveFee = sortedPendingFees[percentile75Index];
120
+
121
+ if (pendingCompetitiveFee > competitiveFee) {
122
+ competitiveFee = pendingCompetitiveFee;
123
+ }
124
+
125
+ this.logger?.debug('Analyzed pending transactions for competitive pricing', {
126
+ pendingTxCount: pendingFees.length,
127
+ pendingP75: formatGwei(pendingCompetitiveFee),
128
+ });
129
+ }
130
+ }
131
+ if (
132
+ feeHistoryResult.status === 'fulfilled' &&
133
+ feeHistoryResult.value !== null &&
134
+ feeHistoryResult.value.reward &&
135
+ feeHistoryResult.value.reward.length > 0
136
+ ) {
137
+ const feeHistory = feeHistoryResult.value;
138
+ // Extract 75th percentile fees from each block
139
+ const percentile75Fees = feeHistory.reward!.map(rewards => rewards[0] || 0n).filter(fee => fee > 0n);
140
+
141
+ if (percentile75Fees.length > 0) {
142
+ // Calculate median of the 75th percentile fees across blocks
143
+ const medianHistoricalFee = median(percentile75Fees) ?? 0n;
144
+
145
+ // Debug: Log suspicious fees from history
146
+ if (medianHistoricalFee > 100n * WEI_CONST) {
147
+ this.logger?.warn('Suspicious high fee in history', {
148
+ historicalMedian: formatGwei(medianHistoricalFee),
149
+ allP75Fees: percentile75Fees.map(f => formatGwei(f)),
150
+ });
151
+ }
152
+
153
+ if (medianHistoricalFee > competitiveFee) {
154
+ competitiveFee = medianHistoricalFee;
155
+ }
156
+
157
+ this.logger?.debug('Analyzed fee history for competitive pricing', {
158
+ historicalMedian: formatGwei(medianHistoricalFee),
159
+ });
160
+ }
161
+ }
162
+
163
+ // Sanity check: cap competitive fee at 100x network estimate to avoid using unrealistic fees
164
+ // (e.g., Anvil returns inflated historical fees that don't reflect actual network conditions)
165
+ const maxReasonableFee = networkEstimate * 100n;
166
+ if (competitiveFee > maxReasonableFee) {
167
+ this.logger?.warn('Competitive fee exceeds sanity cap, using capped value', {
168
+ competitiveFee: formatGwei(competitiveFee),
169
+ networkEstimate: formatGwei(networkEstimate),
170
+ cappedTo: formatGwei(maxReasonableFee),
171
+ });
172
+ competitiveFee = maxReasonableFee;
173
+ }
174
+
175
+ // Log final decision
176
+ if (competitiveFee > networkEstimate) {
177
+ this.logger?.debug('Using competitive fee from market analysis', {
178
+ networkEstimate: formatGwei(networkEstimate),
179
+ competitive: formatGwei(competitiveFee),
180
+ });
181
+ }
182
+
183
+ return competitiveFee;
184
+ }
185
+
186
+ /**
187
+ * Gets the current gas price with bounds checking
188
+ */
189
+ public async getGasPrice(
190
+ gasConfigOverrides?: L1TxUtilsConfig,
191
+ isBlobTx: boolean = false,
192
+ attempt: number = 0,
193
+ previousGasPrice?: typeof attempt extends 0 ? never : GasPrice,
194
+ ): Promise<GasPrice> {
195
+ const gasConfig = merge(this.config, gasConfigOverrides);
196
+
197
+ // Make all RPC calls in parallel upfront with retry logic
198
+ const latestBlockPromise = this.tryTwice(
199
+ () => this.client.getBlock({ blockTag: 'latest' }),
200
+ 'Getting latest block',
201
+ );
202
+ const networkEstimatePromise = this.tryTwice(
203
+ () => this.client.estimateMaxPriorityFeePerGas(),
204
+ 'Estimating max priority fee per gas',
205
+ );
206
+ const pendingBlockPromise = this.tryTwice(
207
+ () => this.client.getBlock({ blockTag: 'pending', includeTransactions: true }),
208
+ 'Getting pending block',
209
+ );
210
+ const feeHistoryPromise = this.tryTwice(
211
+ () => this.client.getFeeHistory({ blockCount: HISTORICAL_BLOCK_COUNT, rewardPercentiles: [75] }),
212
+ 'Getting fee history',
213
+ );
214
+ const blobBaseFeePromise = isBlobTx
215
+ ? this.tryTwice(() => this.client.getBlobBaseFee(), 'Getting blob base fee')
216
+ : null;
217
+
218
+ const [latestBlockResult, networkEstimateResult, pendingBlockResult, feeHistoryResult, blobBaseFeeResult] =
219
+ await Promise.allSettled([
220
+ latestBlockPromise,
221
+ networkEstimatePromise,
222
+ pendingBlockPromise,
223
+ feeHistoryPromise,
224
+ blobBaseFeePromise ?? Promise.resolve(0n),
225
+ ]);
226
+
227
+ // Extract results
228
+ const baseFee =
229
+ latestBlockResult.status === 'fulfilled' &&
230
+ typeof latestBlockResult.value === 'object' &&
231
+ latestBlockResult.value.baseFeePerGas
232
+ ? latestBlockResult.value.baseFeePerGas
233
+ : 0n;
234
+
235
+ // Get blob base fee if available
236
+ let blobBaseFee = 0n;
237
+ if (isBlobTx && blobBaseFeeResult.status === 'fulfilled' && typeof blobBaseFeeResult.value === 'bigint') {
238
+ blobBaseFee = blobBaseFeeResult.value;
239
+ } else if (isBlobTx) {
240
+ this.logger?.warn('Failed to get L1 blob base fee', attempt);
241
+ }
242
+
243
+ // Get competitive priority fee
244
+ let priorityFee = this.getCompetitivePriorityFee(networkEstimateResult, pendingBlockResult, feeHistoryResult);
245
+
246
+ // Apply minimum priority fee as a floor if configured
247
+ if (gasConfig.minimumPriorityFeePerGas) {
248
+ const minimumFee = BigInt(Math.trunc(gasConfig.minimumPriorityFeePerGas * Number(WEI_CONST)));
249
+ if (minimumFee > priorityFee) {
250
+ this.logger?.debug('Using minimum priority fee as floor', {
251
+ minimumPriorityFeePerGas: formatGwei(minimumFee),
252
+ competitiveFee: formatGwei(priorityFee),
253
+ });
254
+ priorityFee = minimumFee;
255
+ } else {
256
+ this.logger?.debug('Competitive fee exceeds minimum, using competitive fee', {
257
+ minimumPriorityFeePerGas: formatGwei(minimumFee),
258
+ competitiveFee: formatGwei(priorityFee),
259
+ });
260
+ }
261
+ }
262
+ let maxFeePerGas = baseFee;
263
+
264
+ let maxFeePerBlobGas = blobBaseFee;
265
+
266
+ // Bump base fee so it's valid for next blocks if it stalls
267
+ const numBlocks = Math.ceil(gasConfig.stallTimeMs! / BLOCK_TIME_MS);
268
+ for (let i = 0; i < numBlocks; i++) {
269
+ // each block can go up 12.5% from previous baseFee
270
+ maxFeePerGas = (maxFeePerGas * (1_000n + 125n)) / 1_000n;
271
+ // same for blob gas fee
272
+ maxFeePerBlobGas = (maxFeePerBlobGas * (1_000n + 125n)) / 1_000n;
273
+ }
274
+
275
+ if (attempt > 0) {
276
+ const configBump =
277
+ gasConfig.priorityFeeRetryBumpPercentage ?? defaultL1TxUtilsConfig.priorityFeeRetryBumpPercentage!;
278
+
279
+ // if this is a blob tx, we have to use the blob bump percentage
280
+ const minBumpPercentage = isBlobTx ? MIN_BLOB_REPLACEMENT_BUMP_PERCENTAGE : MIN_REPLACEMENT_BUMP_PERCENTAGE;
281
+
282
+ const bumpPercentage = configBump > minBumpPercentage ? configBump : minBumpPercentage;
283
+ // Calculate minimum required fees based on previous attempt
284
+ // multiply by 100 & divide by 100 to maintain some precision
285
+ const minPriorityFee =
286
+ (previousGasPrice!.maxPriorityFeePerGas * (100_00n + BigInt(bumpPercentage * 1_00))) / 100_00n;
287
+ const minMaxFee = (previousGasPrice!.maxFeePerGas * (100_00n + BigInt(bumpPercentage * 1_00))) / 100_00n;
288
+
289
+ // Apply bump percentage to competitive fee
290
+ const competitivePriorityFee = (priorityFee * (100_00n + BigInt(configBump * 1_00))) / 100_00n;
291
+
292
+ this.logger?.debug(`Speed-up attempt ${attempt}: using competitive fee strategy`, {
293
+ networkEstimate: formatGwei(priorityFee),
294
+ competitiveFee: formatGwei(competitivePriorityFee),
295
+ minRequired: formatGwei(minPriorityFee),
296
+ bumpPercentage: configBump,
297
+ });
298
+
299
+ // Use maximum between competitive fee and minimum required bump
300
+ const finalPriorityFee = competitivePriorityFee > minPriorityFee ? competitivePriorityFee : minPriorityFee;
301
+ const feeSource = finalPriorityFee === competitivePriorityFee ? 'competitive' : 'minimum-bump';
302
+
303
+ priorityFee = finalPriorityFee;
304
+ // Add the final priority fee to maxFeePerGas
305
+ maxFeePerGas += finalPriorityFee;
306
+ maxFeePerGas = maxFeePerGas > minMaxFee ? maxFeePerGas : minMaxFee;
307
+
308
+ this.logger?.debug(`Speed-up fee decision: using ${feeSource} fee`, {
309
+ finalPriorityFee: formatGwei(finalPriorityFee),
310
+ });
311
+ } else {
312
+ // First attempt: apply configured bump percentage to competitive fee
313
+ // multiply by 100 & divide by 100 to maintain some precision
314
+ priorityFee = (priorityFee * (100_00n + BigInt((gasConfig.priorityFeeBumpPercentage || 0) * 1_00))) / 100_00n;
315
+ this.logger?.debug('Initial transaction: using competitive fee from market analysis', {
316
+ networkEstimate: formatGwei(priorityFee),
317
+ });
318
+ maxFeePerGas += priorityFee;
319
+ }
320
+
321
+ // maxGwei and maxBlobGwei are hard limits
322
+ const effectiveMaxGwei = BigInt(Math.trunc(gasConfig.maxGwei! * Number(WEI_CONST)));
323
+ const effectiveMaxBlobGwei = BigInt(Math.trunc(gasConfig.maxBlobGwei! * Number(WEI_CONST)));
324
+
325
+ // Ensure we don't exceed maxGwei
326
+ if (effectiveMaxGwei > 0n) {
327
+ maxFeePerGas = maxFeePerGas > effectiveMaxGwei ? effectiveMaxGwei : maxFeePerGas;
328
+ }
329
+
330
+ // Ensure we don't exceed maxBlobGwei
331
+ if (maxFeePerBlobGas && effectiveMaxBlobGwei > 0n) {
332
+ maxFeePerBlobGas = maxFeePerBlobGas > effectiveMaxBlobGwei ? effectiveMaxBlobGwei : maxFeePerBlobGas;
333
+ }
334
+
335
+ // Ensure priority fee doesn't exceed max fee
336
+ const maxPriorityFeePerGas = priorityFee > maxFeePerGas ? maxFeePerGas : priorityFee;
337
+
338
+ if (attempt > 0 && previousGasPrice?.maxFeePerBlobGas) {
339
+ const bumpPercentage =
340
+ gasConfig.priorityFeeRetryBumpPercentage! > MIN_BLOB_REPLACEMENT_BUMP_PERCENTAGE
341
+ ? gasConfig.priorityFeeRetryBumpPercentage!
342
+ : MIN_BLOB_REPLACEMENT_BUMP_PERCENTAGE;
343
+
344
+ // calculate min blob fee based on previous attempt
345
+ const minBlobFee = (previousGasPrice.maxFeePerBlobGas * (100_00n + BigInt(bumpPercentage * 1_00))) / 100_00n;
346
+
347
+ // use max between current network values and min required values
348
+ maxFeePerBlobGas = maxFeePerBlobGas > minBlobFee ? maxFeePerBlobGas : minBlobFee;
349
+ }
350
+
351
+ this.logger?.trace(
352
+ `Computed L1 gas price max fee ${formatGwei(maxFeePerGas)} and max priority fee ${formatGwei(maxPriorityFeePerGas)}`,
353
+ {
354
+ attempt,
355
+ baseFee: formatGwei(baseFee),
356
+ maxFeePerGas: formatGwei(maxFeePerGas),
357
+ maxPriorityFeePerGas: formatGwei(maxPriorityFeePerGas),
358
+ blobBaseFee: formatGwei(blobBaseFee),
359
+ maxFeePerBlobGas: formatGwei(maxFeePerBlobGas),
360
+ },
361
+ );
362
+
363
+ return {
364
+ maxFeePerGas,
365
+ maxPriorityFeePerGas,
366
+ ...(maxFeePerBlobGas && { maxFeePerBlobGas: maxFeePerBlobGas }),
367
+ };
368
+ }
369
+
370
+ /**
371
+ * Estimates gas and adds buffer
372
+ */
373
+ public async estimateGas(
374
+ account: Account | Hex,
375
+ request: L1TxRequest,
376
+ _gasConfig?: L1TxUtilsConfig,
377
+ _blobInputs?: L1BlobInputs,
378
+ ): Promise<bigint> {
379
+ const gasConfig = { ...this.config, ..._gasConfig };
380
+ let initialEstimate = 0n;
381
+ if (_blobInputs) {
382
+ // @note requests with blobs also require maxFeePerBlobGas to be set
383
+ const gasPrice = await this.getGasPrice(gasConfig, true, 0);
384
+ initialEstimate = await this.client.estimateGas({
385
+ account,
386
+ ...request,
387
+ ..._blobInputs,
388
+ maxFeePerBlobGas: gasPrice.maxFeePerBlobGas!,
389
+ gas: LARGE_GAS_LIMIT,
390
+ });
391
+
392
+ this.logger?.trace(`Estimated gas for blob tx: ${initialEstimate}`);
393
+ } else {
394
+ initialEstimate = await this.client.estimateGas({ account, ...request, gas: LARGE_GAS_LIMIT });
395
+ this.logger?.trace(`Estimated gas for non-blob tx: ${initialEstimate}`);
396
+ }
397
+
398
+ // Add buffer based on either fixed amount or percentage
399
+ const withBuffer = this.bumpGasLimit(initialEstimate, gasConfig);
400
+
401
+ return withBuffer;
402
+ }
403
+
404
+ async getTransactionStats(txHash: string): Promise<TransactionStats | undefined> {
405
+ const tx = await this.client.getTransaction({ hash: txHash as Hex });
406
+ if (!tx) {
407
+ return undefined;
408
+ }
409
+ const calldata = hexToBytes(tx.input);
410
+ return {
411
+ sender: tx.from.toString(),
412
+ transactionHash: tx.hash,
413
+ calldataSize: calldata.length,
414
+ calldataGas: getCalldataGasUsage(calldata),
415
+ };
416
+ }
417
+
418
+ public async tryGetErrorFromRevertedTx(
419
+ data: Hex,
420
+ args: {
421
+ args: readonly any[];
422
+ functionName: string;
423
+ abi: Abi;
424
+ address: Hex;
425
+ },
426
+ blobInputs: (L1BlobInputs & { maxFeePerBlobGas: bigint }) | undefined,
427
+ stateOverride: StateOverride = [],
428
+ ) {
429
+ try {
430
+ await this.client.simulateContract({
431
+ ...args,
432
+ account: this.client.account,
433
+ stateOverride,
434
+ });
435
+ this.logger?.trace('Simulated blob tx', { blobInputs });
436
+ // If the above passes, we have a blob error. We cannot simulate blob txs, and failed txs no longer throw errors.
437
+ // Strangely, the only way to throw the revert reason as an error and provide blobs is prepareTransactionRequest.
438
+ // See: https://github.com/wevm/viem/issues/2075
439
+ // This throws a EstimateGasExecutionError with the custom error information:
440
+ const request = blobInputs
441
+ ? {
442
+ account: this.client.account,
443
+ to: args.address,
444
+ data,
445
+ blobs: blobInputs.blobs,
446
+ kzg: blobInputs.kzg,
447
+ maxFeePerBlobGas: blobInputs.maxFeePerBlobGas,
448
+ }
449
+ : {
450
+ account: this.client.account,
451
+ to: args.address,
452
+ data,
453
+ };
454
+ this.logger?.trace('Preparing tx', { request });
455
+ await this.client.prepareTransactionRequest(request);
456
+ this.logger?.trace('Prepared tx');
457
+ return undefined;
458
+ } catch (simulationErr: any) {
459
+ // If we don't have a ContractFunctionExecutionError, we have a blob related error => use getContractError to get the error msg.
460
+ const contractErr =
461
+ simulationErr.name === 'ContractFunctionExecutionError'
462
+ ? simulationErr
463
+ : getContractError(simulationErr as BaseError, {
464
+ args: [],
465
+ abi: args.abi,
466
+ functionName: args.functionName,
467
+ address: args.address,
468
+ });
469
+ if (contractErr.name === 'ContractFunctionExecutionError') {
470
+ const execErr = contractErr as ContractFunctionExecutionError;
471
+ return tryGetCustomErrorNameContractFunction(execErr);
472
+ }
473
+ this.logger?.error(`Error getting error from simulation`, simulationErr);
474
+ }
475
+ }
476
+
477
+ public async simulate(
478
+ request: L1TxRequest & { gas?: bigint; from?: Hex },
479
+ blockOverrides: BlockOverrides<bigint, number> = {},
480
+ stateOverrides: StateOverride = [],
481
+ abi: Abi = RollupAbi,
482
+ _gasConfig?: L1TxUtilsConfig & { fallbackGasEstimate?: bigint },
483
+ ): Promise<{ gasUsed: bigint; result: `0x${string}` }> {
484
+ const gasConfig = { ...this.config, ..._gasConfig };
485
+
486
+ const call: any = {
487
+ to: request.to!,
488
+ data: request.data,
489
+ ...(request.from && { from: request.from }),
490
+ };
491
+
492
+ return await this._simulate(call, blockOverrides, stateOverrides, gasConfig, abi);
493
+ }
494
+
495
+ protected async _simulate(
496
+ call: any,
497
+ blockOverrides: BlockOverrides<bigint, number> = {},
498
+ stateOverrides: StateOverride = [],
499
+ gasConfig: L1TxUtilsConfig & { fallbackGasEstimate?: bigint },
500
+ abi: Abi,
501
+ ) {
502
+ try {
503
+ const result = await this.client.simulateBlocks({
504
+ validation: false,
505
+ blocks: [
506
+ {
507
+ blockOverrides,
508
+ stateOverrides,
509
+ calls: [call],
510
+ },
511
+ ],
512
+ });
513
+
514
+ if (result[0].calls[0].status === 'failure') {
515
+ this.logger?.error('L1 transaction simulation failed', result[0].calls[0].error);
516
+ const decodedError = decodeErrorResult({ abi, data: result[0].calls[0].data });
517
+
518
+ throw new Error(
519
+ `L1 transaction simulation failed with error ${decodedError.errorName}(${decodedError.args?.join(',')})`,
520
+ );
521
+ }
522
+ this.logger?.debug(`L1 transaction simulation succeeded`, { ...result[0].calls[0] });
523
+ return { gasUsed: result[0].gasUsed, result: result[0].calls[0].data as `0x${string}` };
524
+ } catch (err) {
525
+ if (err instanceof MethodNotFoundRpcError || err instanceof MethodNotSupportedRpcError) {
526
+ if (gasConfig.fallbackGasEstimate) {
527
+ this.logger?.warn(
528
+ `Node does not support eth_simulateV1 API. Using fallback gas estimate: ${gasConfig.fallbackGasEstimate}`,
529
+ );
530
+ return { gasUsed: gasConfig.fallbackGasEstimate, result: '0x' as `0x${string}` };
531
+ }
532
+ this.logger?.error('Node does not support eth_simulateV1 API');
533
+ }
534
+ throw err;
535
+ }
536
+ }
537
+
538
+ public bumpGasLimit(gasLimit: bigint, _gasConfig?: L1TxUtilsConfig): bigint {
539
+ const gasConfig = { ...this.config, ..._gasConfig };
540
+ const bumpedGasLimit = gasLimit + (gasLimit * BigInt((gasConfig?.gasLimitBufferPercentage || 0) * 1_00)) / 100_00n;
541
+
542
+ const cleanGasConfig = pickBy(gasConfig, (_, key) => key in l1TxUtilsConfigMappings);
543
+ this.logger?.trace(`Bumping gas limit from ${gasLimit} to ${bumpedGasLimit}`, {
544
+ gasLimit,
545
+ gasConfig: cleanGasConfig,
546
+ bumpedGasLimit,
547
+ });
548
+ return bumpedGasLimit;
549
+ }
550
+
551
+ /**
552
+ * Helper function to retry RPC calls twice
553
+ */
554
+ private tryTwice<T>(fn: () => Promise<T>, description: string): Promise<T> {
555
+ return retry<T>(fn, description, makeBackoff(times(2, () => 0)), this.logger, true);
556
+ }
557
+ }
@@ -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
+ }