@aztec/ethereum 3.0.3 → 4.0.0-devnet.1-patch.0

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 (129) hide show
  1. package/dest/client.js +6 -2
  2. package/dest/config.d.ts +17 -27
  3. package/dest/config.d.ts.map +1 -1
  4. package/dest/config.js +51 -54
  5. package/dest/contracts/empire_base.d.ts +2 -1
  6. package/dest/contracts/empire_base.d.ts.map +1 -1
  7. package/dest/contracts/empire_slashing_proposer.d.ts +2 -1
  8. package/dest/contracts/empire_slashing_proposer.d.ts.map +1 -1
  9. package/dest/contracts/empire_slashing_proposer.js +22 -15
  10. package/dest/contracts/fee_asset_handler.d.ts +6 -5
  11. package/dest/contracts/fee_asset_handler.d.ts.map +1 -1
  12. package/dest/contracts/fee_asset_handler.js +11 -9
  13. package/dest/contracts/governance.d.ts +3 -1
  14. package/dest/contracts/governance.d.ts.map +1 -1
  15. package/dest/contracts/governance.js +11 -1
  16. package/dest/contracts/governance_proposer.d.ts +2 -1
  17. package/dest/contracts/governance_proposer.d.ts.map +1 -1
  18. package/dest/contracts/governance_proposer.js +395 -9
  19. package/dest/contracts/inbox.d.ts +22 -1
  20. package/dest/contracts/inbox.d.ts.map +1 -1
  21. package/dest/contracts/inbox.js +36 -1
  22. package/dest/contracts/index.d.ts +3 -1
  23. package/dest/contracts/index.d.ts.map +1 -1
  24. package/dest/contracts/index.js +2 -0
  25. package/dest/contracts/log.d.ts +13 -0
  26. package/dest/contracts/log.d.ts.map +1 -0
  27. package/dest/contracts/log.js +1 -0
  28. package/dest/contracts/multicall.d.ts +1 -1
  29. package/dest/contracts/multicall.d.ts.map +1 -1
  30. package/dest/contracts/multicall.js +2 -1
  31. package/dest/contracts/outbox.d.ts +41 -0
  32. package/dest/contracts/outbox.d.ts.map +1 -0
  33. package/dest/contracts/outbox.js +86 -0
  34. package/dest/contracts/rollup.d.ts +162 -81
  35. package/dest/contracts/rollup.d.ts.map +1 -1
  36. package/dest/contracts/rollup.js +691 -132
  37. package/dest/contracts/tally_slashing_proposer.d.ts +1 -1
  38. package/dest/contracts/tally_slashing_proposer.d.ts.map +1 -1
  39. package/dest/contracts/tally_slashing_proposer.js +8 -1
  40. package/dest/deploy_aztec_l1_contracts.d.ts +17 -2
  41. package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -1
  42. package/dest/deploy_aztec_l1_contracts.js +87 -19
  43. package/dest/generated/l1-contracts-defaults.d.ts +30 -0
  44. package/dest/generated/l1-contracts-defaults.d.ts.map +1 -0
  45. package/dest/generated/l1-contracts-defaults.js +30 -0
  46. package/dest/l1_artifacts.d.ts +4964 -1573
  47. package/dest/l1_artifacts.d.ts.map +1 -1
  48. package/dest/l1_contract_addresses.d.ts +1 -1
  49. package/dest/l1_contract_addresses.d.ts.map +1 -1
  50. package/dest/l1_contract_addresses.js +3 -3
  51. package/dest/l1_tx_utils/constants.d.ts +8 -2
  52. package/dest/l1_tx_utils/constants.d.ts.map +1 -1
  53. package/dest/l1_tx_utils/constants.js +27 -2
  54. package/dest/l1_tx_utils/fee-strategies/index.d.ts +10 -0
  55. package/dest/l1_tx_utils/fee-strategies/index.d.ts.map +1 -0
  56. package/dest/l1_tx_utils/fee-strategies/index.js +12 -0
  57. package/dest/l1_tx_utils/fee-strategies/p75_competitive.d.ts +8 -0
  58. package/dest/l1_tx_utils/fee-strategies/p75_competitive.d.ts.map +1 -0
  59. package/dest/l1_tx_utils/fee-strategies/p75_competitive.js +129 -0
  60. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.d.ts +23 -0
  61. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.d.ts.map +1 -0
  62. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.js +191 -0
  63. package/dest/l1_tx_utils/fee-strategies/types.d.ts +51 -0
  64. package/dest/l1_tx_utils/fee-strategies/types.d.ts.map +1 -0
  65. package/dest/l1_tx_utils/fee-strategies/types.js +3 -0
  66. package/dest/l1_tx_utils/index.d.ts +3 -1
  67. package/dest/l1_tx_utils/index.d.ts.map +1 -1
  68. package/dest/l1_tx_utils/index.js +2 -0
  69. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts +233 -0
  70. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts.map +1 -0
  71. package/dest/l1_tx_utils/l1_fee_analyzer.js +506 -0
  72. package/dest/l1_tx_utils/l1_tx_utils.js +6 -6
  73. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +4 -15
  74. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -1
  75. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +35 -143
  76. package/dest/publisher_manager.d.ts +3 -2
  77. package/dest/publisher_manager.d.ts.map +1 -1
  78. package/dest/publisher_manager.js +2 -2
  79. package/dest/queries.d.ts +2 -2
  80. package/dest/queries.d.ts.map +1 -1
  81. package/dest/queries.js +12 -4
  82. package/dest/test/chain_monitor.js +1 -2
  83. package/dest/test/eth_cheat_codes.d.ts +13 -1
  84. package/dest/test/eth_cheat_codes.d.ts.map +1 -1
  85. package/dest/test/eth_cheat_codes.js +3 -1
  86. package/dest/test/rollup_cheat_codes.d.ts +5 -2
  87. package/dest/test/rollup_cheat_codes.d.ts.map +1 -1
  88. package/dest/test/rollup_cheat_codes.js +22 -3
  89. package/dest/test/start_anvil.js +1 -1
  90. package/dest/test/tx_delayer.js +1 -1
  91. package/dest/utils.d.ts +15 -2
  92. package/dest/utils.d.ts.map +1 -1
  93. package/dest/utils.js +64 -0
  94. package/package.json +9 -7
  95. package/src/client.ts +2 -2
  96. package/src/config.ts +62 -53
  97. package/src/contracts/README.md +157 -0
  98. package/src/contracts/empire_base.ts +1 -1
  99. package/src/contracts/empire_slashing_proposer.ts +22 -28
  100. package/src/contracts/fee_asset_handler.ts +10 -7
  101. package/src/contracts/governance.ts +10 -1
  102. package/src/contracts/governance_proposer.ts +10 -2
  103. package/src/contracts/inbox.ts +53 -1
  104. package/src/contracts/index.ts +2 -0
  105. package/src/contracts/log.ts +13 -0
  106. package/src/contracts/multicall.ts +5 -2
  107. package/src/contracts/outbox.ts +98 -0
  108. package/src/contracts/rollup.ts +364 -100
  109. package/src/contracts/tally_slashing_proposer.ts +5 -1
  110. package/src/deploy_aztec_l1_contracts.ts +94 -18
  111. package/src/generated/l1-contracts-defaults.ts +32 -0
  112. package/src/l1_contract_addresses.ts +22 -20
  113. package/src/l1_tx_utils/constants.ts +13 -2
  114. package/src/l1_tx_utils/fee-strategies/index.ts +22 -0
  115. package/src/l1_tx_utils/fee-strategies/p75_competitive.ts +163 -0
  116. package/src/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.ts +245 -0
  117. package/src/l1_tx_utils/fee-strategies/types.ts +56 -0
  118. package/src/l1_tx_utils/index.ts +2 -0
  119. package/src/l1_tx_utils/l1_fee_analyzer.ts +803 -0
  120. package/src/l1_tx_utils/l1_tx_utils.ts +6 -6
  121. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +48 -186
  122. package/src/publisher_manager.ts +4 -2
  123. package/src/queries.ts +11 -3
  124. package/src/test/chain_monitor.ts +1 -1
  125. package/src/test/eth_cheat_codes.ts +1 -1
  126. package/src/test/rollup_cheat_codes.ts +22 -4
  127. package/src/test/start_anvil.ts +1 -1
  128. package/src/test/tx_delayer.ts +1 -1
  129. package/src/utils.ts +82 -0
@@ -27,7 +27,7 @@ import { jsonRpc } from 'viem/nonce';
27
27
  import type { ViemClient } from '../types.js';
28
28
  import { formatViemError } from '../utils.js';
29
29
  import { type L1TxUtilsConfig, l1TxUtilsConfigMappings } from './config.js';
30
- import { LARGE_GAS_LIMIT } from './constants.js';
30
+ import { MAX_L1_TX_LIMIT } from './constants.js';
31
31
  import type { IL1TxMetrics, IL1TxStore } from './interfaces.js';
32
32
  import { ReadOnlyL1TxUtils } from './readonly_l1_tx_utils.js';
33
33
  import {
@@ -207,7 +207,7 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
207
207
 
208
208
  let gasLimit: bigint;
209
209
  if (this.debugMaxGasLimit) {
210
- gasLimit = LARGE_GAS_LIMIT;
210
+ gasLimit = MAX_L1_TX_LIMIT;
211
211
  } else if (gasConfig.gasLimit) {
212
212
  gasLimit = gasConfig.gasLimit;
213
213
  } else {
@@ -283,7 +283,7 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
283
283
  return { txHash, state: l1TxState };
284
284
  } catch (err: any) {
285
285
  const viemError = formatViemError(err, request.abi);
286
- this.logger.error(`Failed to send L1 transaction`, viemError, {
286
+ this.logger.error(`Failed to send L1 transaction: ${viemError.message}`, viemError, {
287
287
  request: pick(request, 'to', 'value'),
288
288
  });
289
289
  throw viemError;
@@ -631,12 +631,12 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
631
631
  from: request.from ?? this.getSenderAddress().toString(),
632
632
  maxFeePerGas: gasPrice.maxFeePerGas,
633
633
  maxPriorityFeePerGas: gasPrice.maxPriorityFeePerGas,
634
- gas: request.gas ?? LARGE_GAS_LIMIT,
634
+ gas: request.gas ?? MAX_L1_TX_LIMIT,
635
635
  };
636
636
 
637
637
  if (!request.gas && !gasConfig.ignoreBlockGasLimit) {
638
- // LARGE_GAS_LIMIT is set as call.gas, increase block gasLimit
639
- blockOverrides.gasLimit = LARGE_GAS_LIMIT * 2n;
638
+ // MAX_L1_TX_LIMIT is set as call.gas, ensure block gasLimit is sufficient
639
+ blockOverrides.gasLimit = MAX_L1_TX_LIMIT;
640
640
  }
641
641
 
642
642
  return this._simulate(call, blockOverrides, stateOverrides, gasConfig, abi);
@@ -1,4 +1,5 @@
1
- import { getKeys, median, merge, pick, times } from '@aztec/foundation/collection';
1
+ import { getKeys, merge, pick, times } from '@aztec/foundation/collection';
2
+ import type { EthAddress } from '@aztec/foundation/eth-address';
2
3
  import { type Logger, createLogger } from '@aztec/foundation/log';
3
4
  import { makeBackoff, retry } from '@aztec/foundation/retry';
4
5
  import { DateProvider } from '@aztec/foundation/timer';
@@ -11,6 +12,7 @@ import {
11
12
  type BaseError,
12
13
  type BlockOverrides,
13
14
  type ContractFunctionExecutionError,
15
+ type GetCodeReturnType,
14
16
  type Hex,
15
17
  MethodNotFoundRpcError,
16
18
  MethodNotSupportedRpcError,
@@ -25,15 +27,17 @@ import type { ViemClient } from '../types.js';
25
27
  import { type L1TxUtilsConfig, defaultL1TxUtilsConfig, l1TxUtilsConfigMappings } from './config.js';
26
28
  import {
27
29
  BLOCK_TIME_MS,
28
- LARGE_GAS_LIMIT,
30
+ MAX_L1_TX_LIMIT,
29
31
  MIN_BLOB_REPLACEMENT_BUMP_PERCENTAGE,
30
32
  MIN_REPLACEMENT_BUMP_PERCENTAGE,
31
33
  WEI_CONST,
32
34
  } from './constants.js';
35
+ import { P75AllTxsPriorityFeeStrategy, type PriorityFeeStrategy } from './fee-strategies/index.js';
33
36
  import type { GasPrice, L1BlobInputs, L1TxRequest, TransactionStats } from './types.js';
34
37
  import { getCalldataGasUsage, tryGetCustomErrorNameContractFunction } from './utils.js';
35
38
 
36
- const HISTORICAL_BLOCK_COUNT = 5;
39
+ // Change this to the current strategy we want to use
40
+ const CurrentStrategy: PriorityFeeStrategy = P75AllTxsPriorityFeeStrategy;
37
41
 
38
42
  export class ReadOnlyL1TxUtils {
39
43
  public config: Required<L1TxUtilsConfig>;
@@ -65,122 +69,8 @@ export class ReadOnlyL1TxUtils {
65
69
  return this.client.getBlockNumber();
66
70
  }
67
71
 
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;
72
+ public getCode(address: EthAddress): Promise<GetCodeReturnType> {
73
+ return this.client.getCode({ address: address.toString() });
184
74
  }
185
75
 
186
76
  /**
@@ -194,74 +84,47 @@ export class ReadOnlyL1TxUtils {
194
84
  ): Promise<GasPrice> {
195
85
  const gasConfig = merge(this.config, gasConfigOverrides);
196
86
 
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',
87
+ // Execute strategy - it handles all RPC calls internally and returns everything we need
88
+ const strategyResult = await retry(
89
+ () =>
90
+ CurrentStrategy.execute(this.client, {
91
+ gasConfig,
92
+ isBlobTx,
93
+ logger: this.logger,
94
+ }),
95
+ 'Executing priority fee strategy',
96
+ makeBackoff(times(2, () => 0)),
97
+ this.logger,
98
+ true,
205
99
  );
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) {
100
+
101
+ const { latestBlock, blobBaseFee, priorityFee: strategyPriorityFee } = strategyResult;
102
+
103
+ // Extract base fee from latest block
104
+ const baseFee = latestBlock.baseFeePerGas ?? 0n;
105
+
106
+ // Handle blob base fee
107
+ if (isBlobTx && blobBaseFee === undefined) {
240
108
  this.logger?.warn('Failed to get L1 blob base fee', attempt);
241
109
  }
242
110
 
243
- // Get competitive priority fee
244
- let priorityFee = this.getCompetitivePriorityFee(networkEstimateResult, pendingBlockResult, feeHistoryResult);
111
+ let priorityFee = strategyPriorityFee;
245
112
 
246
- // Apply minimum priority fee as a floor if configured
113
+ // Apply minimum priority fee floor if configured
247
114
  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),
115
+ const minimumPriorityFee = BigInt(Math.trunc(gasConfig.minimumPriorityFeePerGas * Number(WEI_CONST)));
116
+ if (priorityFee < minimumPriorityFee) {
117
+ this.logger?.debug('Applying minimum priority fee floor', {
118
+ calculatedPriorityFee: formatGwei(priorityFee),
119
+ minimumPriorityFeePerGas: gasConfig.minimumPriorityFeePerGas,
120
+ appliedFee: formatGwei(minimumPriorityFee),
259
121
  });
122
+ priorityFee = minimumPriorityFee;
260
123
  }
261
124
  }
262
125
  let maxFeePerGas = baseFee;
263
126
 
264
- let maxFeePerBlobGas = blobBaseFee;
127
+ let maxFeePerBlobGas = blobBaseFee ?? 0n;
265
128
 
266
129
  // Bump base fee so it's valid for next blocks if it stalls
267
130
  const numBlocks = Math.ceil(gasConfig.stallTimeMs! / BLOCK_TIME_MS);
@@ -355,7 +218,7 @@ export class ReadOnlyL1TxUtils {
355
218
  baseFee: formatGwei(baseFee),
356
219
  maxFeePerGas: formatGwei(maxFeePerGas),
357
220
  maxPriorityFeePerGas: formatGwei(maxPriorityFeePerGas),
358
- blobBaseFee: formatGwei(blobBaseFee),
221
+ blobBaseFee: formatGwei(blobBaseFee ?? 0n),
359
222
  maxFeePerBlobGas: formatGwei(maxFeePerBlobGas),
360
223
  },
361
224
  );
@@ -386,12 +249,18 @@ export class ReadOnlyL1TxUtils {
386
249
  ...request,
387
250
  ..._blobInputs,
388
251
  maxFeePerBlobGas: gasPrice.maxFeePerBlobGas!,
389
- gas: LARGE_GAS_LIMIT,
252
+ gas: MAX_L1_TX_LIMIT,
253
+ blockTag: 'latest',
390
254
  });
391
255
 
392
256
  this.logger?.trace(`Estimated gas for blob tx: ${initialEstimate}`);
393
257
  } else {
394
- initialEstimate = await this.client.estimateGas({ account, ...request, gas: LARGE_GAS_LIMIT });
258
+ initialEstimate = await this.client.estimateGas({
259
+ account,
260
+ ...request,
261
+ gas: MAX_L1_TX_LIMIT,
262
+ blockTag: 'latest',
263
+ });
395
264
  this.logger?.trace(`Estimated gas for non-blob tx: ${initialEstimate}`);
396
265
  }
397
266
 
@@ -547,11 +416,4 @@ export class ReadOnlyL1TxUtils {
547
416
  });
548
417
  return bumpedGasLimit;
549
418
  }
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
419
  }
@@ -1,5 +1,5 @@
1
1
  import { pick } from '@aztec/foundation/collection';
2
- import { createLogger } from '@aztec/foundation/log';
2
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
3
3
 
4
4
  import { L1TxUtils, TxUtilsState } from './l1_tx_utils/index.js';
5
5
 
@@ -28,13 +28,15 @@ const busyStates: TxUtilsState[] = [
28
28
  export type PublisherFilter<UtilsType extends L1TxUtils> = (utils: UtilsType) => boolean;
29
29
 
30
30
  export class PublisherManager<UtilsType extends L1TxUtils = L1TxUtils> {
31
- private log = createLogger('publisher:manager');
31
+ private log: Logger;
32
32
  private config: { publisherAllowInvalidStates?: boolean };
33
33
 
34
34
  constructor(
35
35
  private publishers: UtilsType[],
36
36
  config: { publisherAllowInvalidStates?: boolean },
37
+ bindings?: LoggerBindings,
37
38
  ) {
39
+ this.log = createLogger('publisher:manager', bindings);
38
40
  this.log.info(`PublisherManager initialized with ${publishers.length} publishers.`);
39
41
  this.publishers = publishers;
40
42
  this.config = pick(config, 'publisherAllowInvalidStates');
package/src/queries.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { EthAddress } from '@aztec/foundation/eth-address';
2
2
 
3
- import type { L1ContractsConfig } from './config.js';
3
+ import { DefaultL1ContractsConfig, type L1ContractsConfig } from './config.js';
4
4
  import { ReadOnlyGovernanceContract } from './contracts/governance.js';
5
5
  import { GovernanceProposerContract } from './contracts/governance_proposer.js';
6
+ import { InboxContract } from './contracts/inbox.js';
6
7
  import { RollupContract } from './contracts/rollup.js';
7
8
  import type { ViemPublicClient } from './types.js';
8
9
 
@@ -25,6 +26,8 @@ export async function getL1ContractsConfig(
25
26
  const rollup = new RollupContract(publicClient, rollupAddress.toString());
26
27
  const slasherProposer = await rollup.getSlashingProposer();
27
28
  const slasher = await rollup.getSlasherContract();
29
+ const rollupAddresses = await rollup.getRollupAddresses();
30
+ const inboxContract = new InboxContract(publicClient, rollupAddresses.inboxAddress.toString());
28
31
 
29
32
  const [
30
33
  l1StartBlock,
@@ -35,6 +38,7 @@ export async function getL1ContractsConfig(
35
38
  aztecTargetCommitteeSize,
36
39
  lagInEpochsForValidatorSet,
37
40
  lagInEpochsForRandao,
41
+ inboxLag,
38
42
  activationThreshold,
39
43
  ejectionThreshold,
40
44
  localEjectionThreshold,
@@ -62,6 +66,7 @@ export async function getL1ContractsConfig(
62
66
  rollup.getTargetCommitteeSize(),
63
67
  rollup.getLagInEpochsForValidatorSet(),
64
68
  rollup.getLagInEpochsForRandao(),
69
+ inboxContract.getLag(),
65
70
  rollup.getActivationThreshold(),
66
71
  rollup.getEjectionThreshold(),
67
72
  rollup.getLocalEjectionThreshold(),
@@ -91,13 +96,15 @@ export async function getL1ContractsConfig(
91
96
  aztecTargetCommitteeSize: Number(aztecTargetCommitteeSize),
92
97
  lagInEpochsForValidatorSet: Number(lagInEpochsForValidatorSet),
93
98
  lagInEpochsForRandao: Number(lagInEpochsForRandao),
99
+ inboxLag: Number(inboxLag),
94
100
  governanceProposerQuorum: Number(governanceProposerQuorum),
95
101
  governanceProposerRoundSize: Number(governanceProposerRoundSize),
102
+ governanceVotingDuration: DefaultL1ContractsConfig.governanceVotingDuration,
96
103
  activationThreshold,
97
104
  ejectionThreshold,
98
105
  localEjectionThreshold,
99
106
  slashingQuorum: Number(slashingQuorum),
100
- slashingRoundSizeInEpochs: Number(slashingRoundSize / aztecEpochDuration),
107
+ slashingRoundSizeInEpochs: Number(Number(slashingRoundSize) / aztecEpochDuration),
101
108
  slashingLifetimeInRounds: Number(slashingLifetimeInRounds),
102
109
  slashingExecutionDelayInRounds: Number(slashingExecutionDelayInRounds),
103
110
  slashingVetoer,
@@ -105,12 +112,13 @@ export async function getL1ContractsConfig(
105
112
  manaTarget,
106
113
  provingCostPerMana: provingCostPerMana,
107
114
  rollupVersion: Number(rollupVersion),
108
- genesisArchiveTreeRoot,
115
+ genesisArchiveTreeRoot: genesisArchiveTreeRoot.toString(),
109
116
  exitDelaySeconds: Number(exitDelay),
110
117
  slasherFlavor: slasherProposer?.type ?? 'tally',
111
118
  slashingOffsetInRounds: Number(slashingOffsetInRounds),
112
119
  slashAmountSmall: slashingAmounts[0],
113
120
  slashAmountMedium: slashingAmounts[1],
114
121
  slashAmountLarge: slashingAmounts[2],
122
+ initialEthPerFeeAsset: DefaultL1ContractsConfig.initialEthPerFeeAsset,
115
123
  };
116
124
  }
@@ -156,7 +156,7 @@ export class ChainMonitor extends EventEmitter<ChainMonitorEventMap> {
156
156
  let committee: EthAddress[] | undefined;
157
157
  if (l2Epoch !== this.l2EpochNumber) {
158
158
  this.l2EpochNumber = l2Epoch;
159
- committee = (await this.rollup.getCurrentEpochCommittee())?.map(addr => EthAddress.fromString(addr));
159
+ committee = await this.rollup.getCurrentEpochCommittee();
160
160
  this.emit('l2-epoch', { l2EpochNumber: l2Epoch, timestamp, committee });
161
161
  msg += ` starting new epoch ${this.l2EpochNumber} `;
162
162
  }
@@ -35,7 +35,7 @@ export class EthCheatCodes {
35
35
  public chain: Chain = foundry,
36
36
  ) {
37
37
  this.publicClient = createPublicClient({
38
- transport: fallback(this.rpcUrls.map(url => http(url))),
38
+ transport: fallback(this.rpcUrls.map(url => http(url, { batch: false }))),
39
39
  chain: chain,
40
40
  });
41
41
  }
@@ -1,4 +1,4 @@
1
- import { RollupContract } from '@aztec/ethereum/contracts';
1
+ import { OutboxContract, RollupContract } from '@aztec/ethereum/contracts';
2
2
  import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
3
3
  import type { ViemPublicClient } from '@aztec/ethereum/types';
4
4
  import { CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
@@ -32,7 +32,7 @@ export class RollupCheatCodes {
32
32
  ) {
33
33
  this.client = createPublicClient({
34
34
  chain: ethCheatCodes.chain,
35
- transport: fallback(ethCheatCodes.rpcUrls.map(url => http(url))),
35
+ transport: fallback(ethCheatCodes.rpcUrls.map(url => http(url, { batch: false }))),
36
36
  });
37
37
  this.rollup = getContract({
38
38
  abi: RollupAbi,
@@ -56,6 +56,15 @@ export class RollupCheatCodes {
56
56
  return SlotNumber.fromBigInt(await this.rollup.read.getSlotAt([ts]));
57
57
  }
58
58
 
59
+ /** Returns the number of seconds until the start of the given slot based on L1 block timestamp. */
60
+ public async getSecondsUntilSlot(slot: SlotNumber): Promise<number> {
61
+ const [currentTimestamp, targetTimestamp] = await Promise.all([
62
+ this.client.getBlock().then(b => BigInt(b.timestamp)),
63
+ this.rollup.read.getTimestampForSlot([BigInt(slot)]),
64
+ ]);
65
+ return Math.max(0, Number(targetTimestamp - currentTimestamp));
66
+ }
67
+
59
68
  /** Returns the current epoch */
60
69
  public async getEpoch(): Promise<EpochNumber> {
61
70
  const slotNumber = await this.getSlot();
@@ -124,7 +133,7 @@ export class RollupCheatCodes {
124
133
  } = {},
125
134
  ) {
126
135
  const { epochDuration: slotsInEpoch } = await this.getConfig();
127
- const slotNumber = SlotNumber(epoch * Number(slotsInEpoch));
136
+ const slotNumber = SlotNumber(Number(epoch) * Number(slotsInEpoch));
128
137
  const timestamp = (await this.rollup.read.getTimestampForSlot([BigInt(slotNumber)])) + BigInt(opts.offset ?? 0);
129
138
  try {
130
139
  await this.ethCheatCodes.warp(Number(timestamp), { ...opts, silent: true, resetBlockInterval: true });
@@ -176,7 +185,7 @@ export class RollupCheatCodes {
176
185
  * Marks the specified checkpoint (or latest if none) as proven
177
186
  * @param maybeCheckpointNumber - The checkpoint number to mark as proven (defaults to latest pending)
178
187
  */
179
- public markAsProven(maybeCheckpointNumber?: number | bigint) {
188
+ public markAsProven(maybeCheckpointNumber?: CheckpointNumber) {
180
189
  return this.ethCheatCodes.execWithPausedAnvil(async () => {
181
190
  const tipsBefore = await this.getTips();
182
191
  const { pending, proven } = tipsBefore;
@@ -250,6 +259,15 @@ export class RollupCheatCodes {
250
259
  });
251
260
  }
252
261
 
262
+ public insertOutbox(epoch: EpochNumber, outHash: bigint) {
263
+ return this.ethCheatCodes.execWithPausedAnvil(async () => {
264
+ const outboxAddress = await this.rollup.read.getOutbox();
265
+ const epochRootSlot = OutboxContract.getEpochRootStorageSlot(epoch);
266
+ await this.ethCheatCodes.store(EthAddress.fromString(outboxAddress), epochRootSlot, outHash);
267
+ this.logger.warn(`Advanced outbox to epoch ${epoch} with out hash ${outHash}`);
268
+ });
269
+ }
270
+
253
271
  /**
254
272
  * Executes an action impersonated as the owner of the Rollup contract.
255
273
  * @param action - The action to execute
@@ -33,7 +33,7 @@ export async function startAnvil(
33
33
  const anvil = createAnvil({
34
34
  anvilBinary,
35
35
  host: '127.0.0.1',
36
- port: opts.port ?? 8545,
36
+ port: opts.port ?? (process.env.ANVIL_PORT ? parseInt(process.env.ANVIL_PORT) : 8545),
37
37
  blockTime: opts.l1BlockTime,
38
38
  stopTimeout: 1000,
39
39
  accounts: opts.accounts ?? 20,
@@ -232,7 +232,7 @@ export function withDelayer<T extends ViemClient>(
232
232
  return Promise.resolve(txHash!);
233
233
  } else {
234
234
  const txHash = await client.sendRawTransaction(...args);
235
- logger.verbose(`Sent tx immediately ${txHash}`);
235
+ logger.debug(`Sent tx immediately ${txHash}`);
236
236
  delayer.sentTxHashes.push(txHash);
237
237
  return txHash;
238
238
  }
package/src/utils.ts CHANGED
@@ -4,15 +4,18 @@ import { ErrorsAbi } from '@aztec/l1-artifacts/ErrorsAbi';
4
4
 
5
5
  import {
6
6
  type Abi,
7
+ type AbiItem,
7
8
  BaseError,
8
9
  type ContractEventName,
9
10
  ContractFunctionRevertedError,
10
11
  type DecodeEventLogReturnType,
12
+ type FormattedTransaction,
11
13
  type Hex,
12
14
  type Log,
13
15
  decodeErrorResult,
14
16
  decodeEventLog,
15
17
  } from 'viem';
18
+ import { formatAbiItem, formatAbiParams } from 'viem/utils';
16
19
 
17
20
  export interface L2Claim {
18
21
  claimSecret: Fr;
@@ -92,6 +95,57 @@ export function prettyLogViemErrorMsg(err: any) {
92
95
  return err?.message ?? err;
93
96
  }
94
97
 
98
+ export function mergeAbis(abis: Abi[]): Abi {
99
+ let merged: Abi = [];
100
+ const seen = new Set<string>();
101
+
102
+ for (const abi of abis) {
103
+ for (const item of abi) {
104
+ const key = getAbiItemKey(item);
105
+ if (!seen.has(key)) {
106
+ seen.add(key);
107
+ merged = [...merged, item];
108
+ }
109
+ }
110
+ }
111
+
112
+ return merged;
113
+ }
114
+
115
+ function getAbiItemKey(item: AbiItem): string {
116
+ if (item.type === 'function') {
117
+ const signature = formatAbiItem(item);
118
+ const outputs = formatAbiParams(item.outputs);
119
+ const stateMutability = typeof item.stateMutability === 'string' ? item.stateMutability : '';
120
+ return `function:${signature}:${outputs}:${stateMutability}`;
121
+ }
122
+
123
+ if (item.type === 'event') {
124
+ const signature = formatAbiItem(item);
125
+ const indexed = (item.inputs ?? []).map(input => ((input as { indexed?: boolean }).indexed ? '1' : '0')).join('');
126
+ const anonymous = item.anonymous ? 'anonymous' : 'not-anonymous';
127
+ return `event:${signature}:${indexed}:${anonymous}`;
128
+ }
129
+
130
+ if (item.type === 'error') {
131
+ const signature = formatAbiItem(item);
132
+ return `error:${signature}`;
133
+ }
134
+
135
+ if (item.type === 'constructor') {
136
+ const inputs = formatAbiParams(item.inputs);
137
+ const stateMutability = typeof item.stateMutability === 'string' ? item.stateMutability : '';
138
+ return `constructor::${inputs}:${stateMutability}`;
139
+ }
140
+
141
+ if (item.type === 'fallback' || item.type === 'receive') {
142
+ const stateMutability = typeof item.stateMutability === 'string' ? item.stateMutability : '';
143
+ return `${item.type}:::${stateMutability}`;
144
+ }
145
+
146
+ return 'unknown';
147
+ }
148
+
95
149
  function getNestedErrorData(error: unknown): string | undefined {
96
150
  // If nothing, bail
97
151
  if (!error) {
@@ -233,3 +287,31 @@ export function tryGetCustomErrorName(err: any) {
233
287
  return undefined;
234
288
  }
235
289
  }
290
+
291
+ /**
292
+ * Type guard to check if a transaction is a blob transaction (EIP-4844).
293
+ * Blob transactions have maxFeePerBlobGas and blobVersionedHashes fields.
294
+ */
295
+ export function isBlobTransaction(tx: FormattedTransaction): tx is FormattedTransaction & {
296
+ maxFeePerBlobGas: bigint;
297
+ blobVersionedHashes: readonly Hex[];
298
+ } {
299
+ return (
300
+ 'maxFeePerBlobGas' in tx &&
301
+ tx.maxFeePerBlobGas !== undefined &&
302
+ 'blobVersionedHashes' in tx &&
303
+ tx.blobVersionedHashes !== undefined
304
+ );
305
+ }
306
+
307
+ /**
308
+ * Calculates a percentile from an array of bigints
309
+ */
310
+ export function calculatePercentile(values: bigint[], percentile: number): bigint {
311
+ if (values.length === 0) {
312
+ return 0n;
313
+ }
314
+ const sorted = [...values].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
315
+ const index = Math.ceil((sorted.length - 1) * (percentile / 100));
316
+ return sorted[index];
317
+ }