@aztec/sequencer-client 5.0.0-private.20260318 → 5.0.0-rc.1

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 (108) hide show
  1. package/README.md +281 -21
  2. package/dest/client/sequencer-client.d.ts +8 -15
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +35 -96
  5. package/dest/config.d.ts +8 -2
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +48 -26
  8. package/dest/global_variable_builder/fee_predictor.d.ts +37 -0
  9. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  10. package/dest/global_variable_builder/fee_predictor.js +128 -0
  11. package/dest/global_variable_builder/fee_provider.d.ts +21 -0
  12. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  13. package/dest/global_variable_builder/fee_provider.js +67 -0
  14. package/dest/global_variable_builder/global_builder.d.ts +14 -14
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +16 -51
  17. package/dest/global_variable_builder/index.d.ts +4 -2
  18. package/dest/global_variable_builder/index.d.ts.map +1 -1
  19. package/dest/global_variable_builder/index.js +2 -0
  20. package/dest/publisher/config.d.ts +15 -3
  21. package/dest/publisher/config.d.ts.map +1 -1
  22. package/dest/publisher/config.js +19 -4
  23. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +3 -4
  24. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -1
  25. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  26. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  27. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  28. package/dest/publisher/sequencer-publisher-factory.d.ts +3 -5
  29. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  30. package/dest/publisher/sequencer-publisher-factory.js +2 -3
  31. package/dest/publisher/sequencer-publisher.d.ts +73 -65
  32. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  33. package/dest/publisher/sequencer-publisher.js +317 -532
  34. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  35. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  36. package/dest/sequencer/automine/automine_factory.js +85 -0
  37. package/dest/sequencer/automine/automine_sequencer.d.ts +184 -0
  38. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  39. package/dest/sequencer/automine/automine_sequencer.js +677 -0
  40. package/dest/sequencer/automine/index.d.ts +3 -0
  41. package/dest/sequencer/automine/index.d.ts.map +1 -0
  42. package/dest/sequencer/automine/index.js +2 -0
  43. package/dest/sequencer/chain_state_overrides.d.ts +61 -0
  44. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  45. package/dest/sequencer/chain_state_overrides.js +98 -0
  46. package/dest/sequencer/checkpoint_proposal_job.d.ts +77 -17
  47. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  48. package/dest/sequencer/checkpoint_proposal_job.js +768 -209
  49. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  50. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  51. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  52. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  53. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  54. package/dest/sequencer/checkpoint_voter.js +2 -5
  55. package/dest/sequencer/errors.d.ts +1 -8
  56. package/dest/sequencer/errors.d.ts.map +1 -1
  57. package/dest/sequencer/errors.js +0 -9
  58. package/dest/sequencer/events.d.ts +62 -4
  59. package/dest/sequencer/events.d.ts.map +1 -1
  60. package/dest/sequencer/metrics.d.ts +13 -10
  61. package/dest/sequencer/metrics.d.ts.map +1 -1
  62. package/dest/sequencer/metrics.js +45 -20
  63. package/dest/sequencer/sequencer.d.ts +115 -30
  64. package/dest/sequencer/sequencer.d.ts.map +1 -1
  65. package/dest/sequencer/sequencer.js +506 -174
  66. package/dest/sequencer/types.d.ts +2 -2
  67. package/dest/sequencer/types.d.ts.map +1 -1
  68. package/dest/test/index.d.ts +3 -3
  69. package/dest/test/index.d.ts.map +1 -1
  70. package/dest/test/mock_checkpoint_builder.d.ts +4 -8
  71. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  72. package/dest/test/utils.d.ts +15 -1
  73. package/dest/test/utils.d.ts.map +1 -1
  74. package/dest/test/utils.js +23 -6
  75. package/package.json +28 -27
  76. package/src/client/sequencer-client.ts +53 -123
  77. package/src/config.ts +57 -23
  78. package/src/global_variable_builder/README.md +44 -0
  79. package/src/global_variable_builder/fee_predictor.ts +172 -0
  80. package/src/global_variable_builder/fee_provider.ts +80 -0
  81. package/src/global_variable_builder/global_builder.ts +25 -63
  82. package/src/global_variable_builder/index.ts +3 -1
  83. package/src/publisher/config.ts +40 -6
  84. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +3 -1
  85. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  86. package/src/publisher/sequencer-publisher-factory.ts +3 -6
  87. package/src/publisher/sequencer-publisher.ts +376 -577
  88. package/src/sequencer/automine/README.md +60 -0
  89. package/src/sequencer/automine/automine_factory.ts +152 -0
  90. package/src/sequencer/automine/automine_sequencer.ts +783 -0
  91. package/src/sequencer/automine/index.ts +6 -0
  92. package/src/sequencer/chain_state_overrides.ts +169 -0
  93. package/src/sequencer/checkpoint_proposal_job.ts +917 -241
  94. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  95. package/src/sequencer/checkpoint_voter.ts +1 -12
  96. package/src/sequencer/errors.ts +0 -15
  97. package/src/sequencer/events.ts +65 -4
  98. package/src/sequencer/metrics.ts +57 -24
  99. package/src/sequencer/sequencer.ts +604 -195
  100. package/src/sequencer/types.ts +1 -1
  101. package/src/test/index.ts +2 -2
  102. package/src/test/mock_checkpoint_builder.ts +3 -3
  103. package/src/test/utils.ts +59 -10
  104. package/dest/sequencer/timetable.d.ts +0 -88
  105. package/dest/sequencer/timetable.d.ts.map +0 -1
  106. package/dest/sequencer/timetable.js +0 -222
  107. package/src/sequencer/README.md +0 -531
  108. package/src/sequencer/timetable.ts +0 -283
package/src/config.ts CHANGED
@@ -3,8 +3,10 @@ import { type L1ReaderConfig, l1ReaderConfigMappings } from '@aztec/ethereum/l1-
3
3
  import {
4
4
  type ConfigMappingsType,
5
5
  booleanConfigHelper,
6
+ floatConfigHelper,
6
7
  getConfigFromMappings,
7
8
  numberConfigHelper,
9
+ optionalNumberConfigHelper,
8
10
  pickConfigMappings,
9
11
  } from '@aztec/foundation/config';
10
12
  import { EthAddress } from '@aztec/foundation/eth-address';
@@ -13,10 +15,13 @@ import { type P2PConfig, p2pConfigMappings } from '@aztec/p2p/config';
13
15
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
14
16
  import {
15
17
  type ChainConfig,
18
+ DEFAULT_BLOCK_DURATION_MS,
19
+ DEFAULT_MAX_BLOCKS_PER_CHECKPOINT,
16
20
  type SequencerConfig,
17
21
  chainConfigMappings,
18
22
  sharedSequencerConfigMappings,
19
23
  } from '@aztec/stdlib/config';
24
+ import { MIN_PER_BLOCK_ALLOCATION_MULTIPLIER, MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER } from '@aztec/stdlib/gas';
20
25
  import type { ResolvedSequencerConfig } from '@aztec/stdlib/interfaces/server';
21
26
  import { DEFAULT_P2P_PROPAGATION_TIME } from '@aztec/stdlib/timetable';
22
27
  import { type ValidatorClientConfig, validatorClientConfigMappings } from '@aztec/validator-client/config';
@@ -40,15 +45,20 @@ export const DefaultSequencerConfig = {
40
45
  minTxsPerBlock: 1,
41
46
  buildCheckpointIfEmpty: false,
42
47
  publishTxsWithProposals: false,
43
- perBlockAllocationMultiplier: 1.2,
48
+ perBlockAllocationMultiplier: MIN_PER_BLOCK_ALLOCATION_MULTIPLIER,
49
+ perBlockDAAllocationMultiplier: MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER,
44
50
  redistributeCheckpointBudget: true,
45
- enforceTimeTable: true,
51
+ blockDurationMs: DEFAULT_BLOCK_DURATION_MS,
52
+ l1PublishingTime: 12,
53
+ checkpointProposalSyncGraceSeconds: 2 * (DEFAULT_BLOCK_DURATION_MS / 1000),
46
54
  attestationPropagationTime: DEFAULT_P2P_PROPAGATION_TIME,
47
55
  secondsBeforeInvalidatingBlockAsCommitteeMember: 144, // 12 L1 blocks
48
56
  secondsBeforeInvalidatingBlockAsNonCommitteeMember: 432, // 36 L1 blocks
49
57
  skipCollectingAttestations: false,
50
58
  skipInvalidateBlockAsProposer: false,
59
+ skipWaitForValidParentCheckpointOnL1: false,
51
60
  broadcastInvalidBlockProposal: false,
61
+ broadcastInvalidCheckpointProposalOnly: false,
52
62
  injectFakeAttestation: false,
53
63
  injectHighSValueAttestation: false,
54
64
  injectUnrecoverableSignatureAttestation: false,
@@ -56,6 +66,7 @@ export const DefaultSequencerConfig = {
56
66
  shuffleAttestationOrdering: false,
57
67
  skipPushProposedBlocksToArchiver: false,
58
68
  skipPublishingCheckpointsPercent: 0,
69
+ maxBlocksPerCheckpoint: DEFAULT_MAX_BLOCKS_PER_CHECKPOINT,
59
70
  } satisfies ResolvedSequencerConfig;
60
71
 
61
72
  /**
@@ -80,7 +91,7 @@ export const sequencerConfigMappings: ConfigMappingsType<SequencerConfig> = {
80
91
  maxTxsPerCheckpoint: {
81
92
  env: 'SEQ_MAX_TX_PER_CHECKPOINT',
82
93
  description: 'The maximum number of txs across all blocks in a checkpoint.',
83
- parseEnv: (val: string) => (val ? parseInt(val, 10) : undefined),
94
+ ...optionalNumberConfigHelper(),
84
95
  },
85
96
  minTxsPerBlock: {
86
97
  env: 'SEQ_MIN_TX_PER_BLOCK',
@@ -99,19 +110,26 @@ export const sequencerConfigMappings: ConfigMappingsType<SequencerConfig> = {
99
110
  maxL2BlockGas: {
100
111
  env: 'SEQ_MAX_L2_BLOCK_GAS',
101
112
  description: 'The maximum L2 block gas.',
102
- parseEnv: (val: string) => (val ? parseInt(val, 10) : undefined),
113
+ ...optionalNumberConfigHelper(),
103
114
  },
104
115
  maxDABlockGas: {
105
116
  env: 'SEQ_MAX_DA_BLOCK_GAS',
106
117
  description: 'The maximum DA block gas.',
107
- parseEnv: (val: string) => (val ? parseInt(val, 10) : undefined),
118
+ ...optionalNumberConfigHelper(),
108
119
  },
109
120
  perBlockAllocationMultiplier: {
110
121
  env: 'SEQ_PER_BLOCK_ALLOCATION_MULTIPLIER',
111
122
  description:
112
123
  'Per-block gas budget multiplier for both L2 and DA gas. Budget per block is (checkpointLimit / maxBlocks) * multiplier.' +
113
124
  ' Values greater than one allow early blocks to use more than their even share, relying on checkpoint-level capping for later blocks.',
114
- ...numberConfigHelper(DefaultSequencerConfig.perBlockAllocationMultiplier),
125
+ ...floatConfigHelper(DefaultSequencerConfig.perBlockAllocationMultiplier),
126
+ },
127
+ perBlockDAAllocationMultiplier: {
128
+ env: 'SEQ_PER_BLOCK_DA_ALLOCATION_MULTIPLIER',
129
+ description:
130
+ 'Per-block budget multiplier applied to DA gas and blob fields in place of perBlockAllocationMultiplier.' +
131
+ ' Defaults higher than the general multiplier so the largest contract class deploy fits a single block.',
132
+ ...numberConfigHelper(DefaultSequencerConfig.perBlockDAAllocationMultiplier),
115
133
  },
116
134
  redistributeCheckpointBudget: {
117
135
  env: 'SEQ_REDISTRIBUTE_CHECKPOINT_BUDGET',
@@ -119,12 +137,9 @@ export const sequencerConfigMappings: ConfigMappingsType<SequencerConfig> = {
119
137
  'Redistribute remaining checkpoint budget evenly across remaining blocks instead of allowing a single block to consume the entire remaining budget.',
120
138
  ...booleanConfigHelper(DefaultSequencerConfig.redistributeCheckpointBudget),
121
139
  },
122
- maxBlocksPerCheckpoint: {
123
- description: 'Computed max number of blocks per checkpoint from timetable.',
124
- },
125
140
  coinbase: {
126
141
  env: 'COINBASE',
127
- parseEnv: (val: string) => (val ? EthAddress.fromString(val) : undefined),
142
+ parseEnv: (val: string) => EthAddress.fromString(val),
128
143
  description: 'Recipient of block reward.',
129
144
  },
130
145
  feeRecipient: {
@@ -140,11 +155,6 @@ export const sequencerConfigMappings: ConfigMappingsType<SequencerConfig> = {
140
155
  env: 'ACVM_BINARY_PATH',
141
156
  description: 'The path to the ACVM binary',
142
157
  },
143
- enforceTimeTable: {
144
- env: 'SEQ_ENFORCE_TIME_TABLE',
145
- description: 'Whether to enforce the time table when building blocks',
146
- ...booleanConfigHelper(DefaultSequencerConfig.enforceTimeTable),
147
- },
148
158
  governanceProposerPayload: {
149
159
  env: 'GOVERNANCE_PROPOSER_PAYLOAD_ADDRESS',
150
160
  description: 'The address of the payload for the governanceProposer',
@@ -152,13 +162,8 @@ export const sequencerConfigMappings: ConfigMappingsType<SequencerConfig> = {
152
162
  },
153
163
  l1PublishingTime: {
154
164
  env: 'SEQ_L1_PUBLISHING_TIME_ALLOWANCE_IN_SLOT',
155
- description: 'How much time (in seconds) we allow in the slot for publishing the L1 tx (defaults to 1 L1 slot).',
156
- parseEnv: (val: string) => (val ? parseInt(val, 10) : undefined),
157
- },
158
- attestationPropagationTime: {
159
- env: 'SEQ_ATTESTATION_PROPAGATION_TIME',
160
- description: 'How many seconds it takes for proposals and attestations to travel across the p2p layer (one-way)',
161
- ...numberConfigHelper(DefaultSequencerConfig.attestationPropagationTime),
165
+ description: 'How much time in seconds to allow in the slot for publishing the L1 transaction.',
166
+ ...numberConfigHelper(DefaultSequencerConfig.l1PublishingTime),
162
167
  },
163
168
  fakeProcessingDelayPerTxMs: {
164
169
  description: 'Used for testing to introduce a fake delay after processing each tx',
@@ -189,10 +194,25 @@ export const sequencerConfigMappings: ConfigMappingsType<SequencerConfig> = {
189
194
  description: 'Do not invalidate the previous block if invalid when we are the proposer (for testing only)',
190
195
  ...booleanConfigHelper(DefaultSequencerConfig.skipInvalidateBlockAsProposer),
191
196
  },
197
+ skipWaitForValidParentCheckpointOnL1: {
198
+ description:
199
+ 'Bypass the parent checkpoint validity check before submitting a pipelined checkpoint, ' +
200
+ 'allowing the proposer to publish even when the parent landed on L1 with invalid attestations (for testing only)',
201
+ ...booleanConfigHelper(DefaultSequencerConfig.skipWaitForValidParentCheckpointOnL1),
202
+ },
192
203
  broadcastInvalidBlockProposal: {
193
204
  description: 'Broadcast invalid block proposals with corrupted state (for testing only)',
194
205
  ...booleanConfigHelper(DefaultSequencerConfig.broadcastInvalidBlockProposal),
195
206
  },
207
+ invalidBlockProposalIndexWithinCheckpoint: {
208
+ description: 'Broadcast an invalid block proposal only at this indexWithinCheckpoint (for testing only)',
209
+ ...optionalNumberConfigHelper(),
210
+ },
211
+ broadcastInvalidCheckpointProposalOnly: {
212
+ description:
213
+ 'Broadcast invalid checkpoint proposals while keeping the underlying block proposals valid (for testing only). When unset, the checkpoint follows broadcastInvalidBlockProposal.',
214
+ ...booleanConfigHelper(DefaultSequencerConfig.broadcastInvalidCheckpointProposalOnly),
215
+ },
196
216
  injectFakeAttestation: {
197
217
  description: 'Inject a fake attestation (for testing only)',
198
218
  ...booleanConfigHelper(DefaultSequencerConfig.injectFakeAttestation),
@@ -233,17 +253,31 @@ export const sequencerConfigMappings: ConfigMappingsType<SequencerConfig> = {
233
253
  description: 'Percent probability (0 - 100) of sequencer skipping checkpoint publishing (testing only)',
234
254
  ...numberConfigHelper(DefaultSequencerConfig.skipPublishingCheckpointsPercent),
235
255
  },
256
+ skipBroadcastProposals: {
257
+ description: 'Skip broadcasting checkpoint and block proposals via gossipsub when proposer (for testing only)',
258
+ ...booleanConfigHelper(false),
259
+ },
260
+ skipBroadcastCheckpointProposal: {
261
+ description:
262
+ 'Skip broadcasting only the CheckpointProposal via gossipsub when proposer; the held last block is broadcast ' +
263
+ 'standalone instead so peers still receive it as a proposed-but-uncheckpointed tip (for testing only)',
264
+ ...booleanConfigHelper(false),
265
+ },
266
+ pauseProposingForSlots: {
267
+ description:
268
+ 'List of slots for which the sequencer will not produce a proposal (for testing only). Attestation paths are unaffected.',
269
+ },
236
270
  ...pickConfigMappings(p2pConfigMappings, ['txPublicSetupAllowListExtend']),
237
271
  };
238
272
 
239
273
  export const sequencerClientConfigMappings: ConfigMappingsType<SequencerClientConfig> = {
274
+ ...chainConfigMappings,
240
275
  ...validatorClientConfigMappings,
241
276
  ...sequencerConfigMappings,
242
277
  ...keyStoreConfigMappings,
243
278
  ...l1ReaderConfigMappings,
244
279
  ...sequencerTxSenderConfigMappings,
245
280
  ...sequencerPublisherConfigMappings,
246
- ...chainConfigMappings,
247
281
  ...pickConfigMappings(l1ContractsConfigMappings, ['ethereumSlotDuration', 'aztecSlotDuration', 'aztecEpochDuration']),
248
282
  };
249
283
 
@@ -0,0 +1,44 @@
1
+ # Fee Prediction
2
+
3
+ The `FeePredictor` predicts min fees for upcoming L2 slots based on the current L1
4
+ oracle state and an assumed mana usage pattern.
5
+
6
+ ## Prediction Window
7
+
8
+ The prediction covers `LAG = 2` entries (the next available slot plus 1 more).
9
+ A new oracle update can activate at `startSlot + LAG`, so only the first LAG entries
10
+ are guaranteed stable. Beyond that, L1 fees could change unpredictably.
11
+
12
+ Each entry uses:
13
+
14
+ - The **actual L1 fees** the oracle would return for that slot's timestamp (pre or post,
15
+ depending on whether the slot is before or after `slotOfChange`).
16
+ - A **configurable congestion assumption** (`ManaUsageEstimate`): none (0 mana), target
17
+ (steady state), or limit (worst case, 2x target).
18
+
19
+ The client picks `max(predicted[0..LAG-1])` as their `maxFeesPerGas`.
20
+
21
+ ```
22
+ predicted[0] → fee at next slot (current oracle + current congestion)
23
+ predicted[1] → fee at next slot + 1 (congestion may change based on usage estimate)
24
+ ```
25
+
26
+ ## Why LAG and not LIFETIME?
27
+
28
+ The L1 gas oracle has two timing constants:
29
+
30
+ - **LAG = 2 slots**: when new fees are queued, they activate LAG slots later
31
+ - **LIFETIME = 5 slots**: after an oracle update, the next update is rejected until
32
+ `slotOfChange + (LIFETIME - LAG)` slots have passed
33
+
34
+ If the oracle cooldown has already elapsed (i.e., no recent update), a new update can
35
+ be enqueued at any moment. Its new values would activate LAG slots later. This means
36
+ predictions beyond LAG slots could be invalidated by an oracle update that happens
37
+ right after we query.
38
+
39
+ With a LIFETIME-sized window, we'd give a false sense of coverage: the prediction
40
+ would look like it covers 6 slots, but slots beyond LAG could be wrong if an update
41
+ is enqueued after the prediction is computed.
42
+
43
+ By limiting to LAG entries, we guarantee that all predicted L1 fees are the ones that
44
+ will actually be used — no oracle update can change them within this window.
@@ -0,0 +1,172 @@
1
+ import { type L1FeeData, MAX_FEE_ASSET_PRICE_MODIFIER_BPS, type RollupContract } from '@aztec/ethereum/contracts';
2
+ import { SlotNumber } from '@aztec/foundation/branded-types';
3
+ import { times } from '@aztec/foundation/collection';
4
+ import type { DateProvider } from '@aztec/foundation/timer';
5
+ import { getSlotAtNextL1Block, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
6
+ import {
7
+ FEE_ORACLE_LAG,
8
+ GasFees,
9
+ MIN_ETH_PER_FEE_ASSET,
10
+ ManaUsageEstimate,
11
+ computeExcessMana,
12
+ computeManaMinFee,
13
+ } from '@aztec/stdlib/gas';
14
+
15
+ /** Cached rollup state for fee prediction. Refreshed once per L1 block. */
16
+ type FeeOracleState = {
17
+ lastSlot: SlotNumber;
18
+ excessMana: bigint;
19
+ ethPerFeeAsset: bigint;
20
+ manaTarget: bigint;
21
+ manaLimit: bigint;
22
+ provingCostPerManaEth: bigint;
23
+ epochDuration: bigint;
24
+ /** Pre-resolved L1 fees for each slot in the prediction window. */
25
+ l1FeesBySlot: L1FeeData[];
26
+ };
27
+
28
+ /**
29
+ * Predicts min fees for LAG upcoming slots based on the L1 oracle state.
30
+ * A new oracle update can activate at startSlot + LAG, so only the first LAG entries
31
+ * are guaranteed stable. Caches L1 queries per L1 block and recomputes predictions
32
+ * for each mana usage estimate.
33
+ */
34
+ export class FeePredictor {
35
+ private cachedState: Promise<FeeOracleState> | undefined;
36
+ private cachedL1BlockNumber: bigint | undefined;
37
+
38
+ private readonly slotDuration: number;
39
+ private readonly l1GenesisTime: bigint;
40
+ private readonly ethereumSlotDuration: number;
41
+
42
+ constructor(
43
+ private readonly rollupContract: RollupContract,
44
+ private readonly publicClient: { getBlockNumber: (opts?: { cacheTime?: number }) => Promise<bigint> },
45
+ private readonly dateProvider: DateProvider,
46
+ config: { slotDuration: number; l1GenesisTime: bigint; ethereumSlotDuration: number },
47
+ ) {
48
+ this.slotDuration = config.slotDuration;
49
+ this.l1GenesisTime = config.l1GenesisTime;
50
+ this.ethereumSlotDuration = config.ethereumSlotDuration;
51
+ }
52
+
53
+ /** Returns predicted min fees for each slot in the prediction window. */
54
+ async getPredictedMinFees(manaUsage: ManaUsageEstimate): Promise<GasFees[]> {
55
+ const state = await this.getState();
56
+ return this.computePredictions(state, manaUsage);
57
+ }
58
+
59
+ /** Fetches and caches rollup state. Refreshes when L1 block number advances. */
60
+ private async getState(): Promise<FeeOracleState> {
61
+ const blockNumber = await this.publicClient.getBlockNumber({ cacheTime: 0 });
62
+ if (this.cachedL1BlockNumber === undefined || blockNumber > this.cachedL1BlockNumber) {
63
+ this.cachedL1BlockNumber = blockNumber;
64
+ this.cachedState = this.fetchState(blockNumber);
65
+ }
66
+ return this.cachedState!;
67
+ }
68
+
69
+ private async fetchState(blockNumber: bigint): Promise<FeeOracleState> {
70
+ // Pin all non-constant queries to this L1 block number for a consistent snapshot.
71
+ const opts = { blockNumber };
72
+
73
+ // Cached constants don't need pinning
74
+ const [manaTarget, manaLimit, provingCostPerManaEth, epochDuration] = await Promise.all([
75
+ this.rollupContract.getManaTarget(),
76
+ this.rollupContract.getManaLimit(),
77
+ this.rollupContract.getProvingCostPerMana(),
78
+ this.rollupContract.getEpochDuration(),
79
+ ]);
80
+
81
+ // First, compute the earliest possible nextSlot independently of the checkpoint, so we can
82
+ // evaluate pruneability at the prediction start timestamp instead of the current L1 block time.
83
+ // This avoids an epoch-boundary edge case where the effective parent differs between now and nextSlot.
84
+ const slotConfig = { slotDuration: this.slotDuration, l1GenesisTime: this.l1GenesisTime };
85
+ const currentSlot = await this.rollupContract.getSlotNumber(opts);
86
+
87
+ const slotAtNextL1Block = getSlotAtNextL1Block(BigInt(this.dateProvider.nowInSeconds()), {
88
+ l1GenesisTime: this.l1GenesisTime,
89
+ slotDuration: this.slotDuration,
90
+ ethereumSlotDuration: this.ethereumSlotDuration,
91
+ });
92
+ const preliminaryNextSlot = SlotNumber(Math.max(currentSlot, slotAtNextL1Block));
93
+ const nextSlotTimestamp = getTimestampForSlot(preliminaryNextSlot, slotConfig);
94
+
95
+ // Resolve the effective checkpoint at the prediction start timestamp
96
+ const lastCheckpoint = await this.rollupContract.getEffectivePendingCheckpoint(nextSlotTimestamp, opts);
97
+ const lastSlot = lastCheckpoint.slotNumber;
98
+ // Refine nextSlot: also account for the slot after the last checkpoint
99
+ const nextSlot = SlotNumber(Math.max(SlotNumber.add(lastSlot, 1), preliminaryNextSlot));
100
+ const feeHeader = lastCheckpoint.feeHeader;
101
+
102
+ const slotCount = FEE_ORACLE_LAG;
103
+ const timestamps = times(slotCount, i => getTimestampForSlot(SlotNumber.add(nextSlot, i), slotConfig));
104
+ const l1FeesBySlot = await Promise.all(timestamps.map(ts => this.rollupContract.getL1FeesAt(ts, opts)));
105
+
106
+ return {
107
+ lastSlot,
108
+ excessMana: computeExcessMana(feeHeader.excessMana, feeHeader.manaUsed, manaTarget),
109
+ ethPerFeeAsset: feeHeader.ethPerFeeAsset,
110
+ manaTarget,
111
+ manaLimit,
112
+ provingCostPerManaEth,
113
+ epochDuration: BigInt(epochDuration),
114
+ l1FeesBySlot,
115
+ };
116
+ }
117
+
118
+ /** Computes per-slot fee predictions given cached state and a mana usage assumption. */
119
+ private computePredictions(state: FeeOracleState, manaUsage: ManaUsageEstimate): GasFees[] {
120
+ const assumedManaUsed = this.getAssumedManaUsed(state, manaUsage);
121
+
122
+ const result: GasFees[] = [];
123
+ let { excessMana } = state;
124
+ let { ethPerFeeAsset } = state;
125
+
126
+ // Slot 0: current state (next available slot after last checkpoint)
127
+ result.push(this.computeGasFees(state, excessMana, ethPerFeeAsset, state.l1FeesBySlot[0]));
128
+
129
+ // Slots 1..LAG-1: advance excessMana with the assumed mana usage per checkpoint,
130
+ // and decay ethPerFeeAsset by MAX_FEE_ASSET_PRICE_MODIFIER_BPS per slot for conservative estimates.
131
+ // Lower ethPerFeeAsset means higher fees in fee asset terms.
132
+ for (let i = 1; i < state.l1FeesBySlot.length; i++) {
133
+ excessMana = computeExcessMana(excessMana, assumedManaUsed, state.manaTarget);
134
+ const decayed = (ethPerFeeAsset * (10000n - MAX_FEE_ASSET_PRICE_MODIFIER_BPS)) / 10000n;
135
+ ethPerFeeAsset = decayed < MIN_ETH_PER_FEE_ASSET ? MIN_ETH_PER_FEE_ASSET : decayed;
136
+ result.push(this.computeGasFees(state, excessMana, ethPerFeeAsset, state.l1FeesBySlot[i]));
137
+ }
138
+
139
+ return result;
140
+ }
141
+
142
+ private getAssumedManaUsed(state: FeeOracleState, manaUsage: ManaUsageEstimate): bigint {
143
+ switch (manaUsage) {
144
+ case ManaUsageEstimate.None:
145
+ return 0n;
146
+ case ManaUsageEstimate.Target:
147
+ return state.manaTarget;
148
+ case ManaUsageEstimate.Limit:
149
+ return state.manaLimit;
150
+ }
151
+ }
152
+
153
+ private computeGasFees(
154
+ state: FeeOracleState,
155
+ excessMana: bigint,
156
+ ethPerFeeAsset: bigint,
157
+ l1Fees: L1FeeData,
158
+ ): GasFees {
159
+ return new GasFees(
160
+ 0,
161
+ computeManaMinFee({
162
+ l1BaseFee: l1Fees.baseFee,
163
+ l1BlobFee: l1Fees.blobFee,
164
+ manaTarget: state.manaTarget,
165
+ epochDuration: state.epochDuration,
166
+ provingCostPerManaEth: state.provingCostPerManaEth,
167
+ excessMana,
168
+ ethPerFeeAsset,
169
+ }),
170
+ );
171
+ }
172
+ }
@@ -0,0 +1,80 @@
1
+ import { RollupContract } from '@aztec/ethereum/contracts';
2
+ import type { ViemPublicClient } from '@aztec/ethereum/types';
3
+ import { SlotNumber } from '@aztec/foundation/branded-types';
4
+ import type { DateProvider } from '@aztec/foundation/timer';
5
+ import { getNextL1SlotTimestamp } from '@aztec/stdlib/epoch-helpers';
6
+ import { GasFees, ManaUsageEstimate } from '@aztec/stdlib/gas';
7
+ import type { FeeProvider } from '@aztec/stdlib/tx';
8
+
9
+ import { FeePredictor } from './fee_predictor.js';
10
+ import type { GlobalVariableBuilderConfig } from './global_builder.js';
11
+
12
+ /** Provides current and predicted fee information based on on-chain state. */
13
+ export class FeeProviderImpl implements FeeProvider {
14
+ private currentMinFees: Promise<GasFees> = Promise.resolve(new GasFees(0, 0));
15
+ private currentL1BlockNumber: bigint | undefined = undefined;
16
+
17
+ private readonly rollupContract: RollupContract;
18
+ private readonly feePredictor: FeePredictor;
19
+ private readonly ethereumSlotDuration: number;
20
+ private readonly l1GenesisTime: bigint;
21
+
22
+ constructor(
23
+ private readonly dateProvider: DateProvider,
24
+ private readonly publicClient: ViemPublicClient,
25
+ config: GlobalVariableBuilderConfig,
26
+ ) {
27
+ this.ethereumSlotDuration = config.ethereumSlotDuration;
28
+ this.l1GenesisTime = config.l1GenesisTime;
29
+
30
+ this.rollupContract = new RollupContract(this.publicClient, config.rollupAddress);
31
+ this.feePredictor = new FeePredictor(this.rollupContract, this.publicClient, this.dateProvider, {
32
+ slotDuration: config.slotDuration,
33
+ l1GenesisTime: config.l1GenesisTime,
34
+ ethereumSlotDuration: config.ethereumSlotDuration,
35
+ });
36
+ }
37
+
38
+ /**
39
+ * Computes the "current" min fees, e.g., the price that you currently should pay to get include in the next block
40
+ * @returns Min fees for the next block
41
+ */
42
+ private async computeCurrentMinFees(): Promise<GasFees> {
43
+ // Since this might be called in the middle of a slot where a block might have been published,
44
+ // we need to fetch the last block written, and estimate the earliest timestamp for the next block.
45
+ // The timestamp of that last block will act as a lower bound for the next block.
46
+
47
+ const lastCheckpoint = await this.rollupContract.getPendingCheckpoint();
48
+ const earliestTimestamp = await this.rollupContract.getTimestampForSlot(
49
+ SlotNumber.fromBigInt(BigInt(lastCheckpoint.slotNumber) + 1n),
50
+ );
51
+ const nextEthTimestamp = getNextL1SlotTimestamp(this.dateProvider.nowInSeconds(), {
52
+ l1GenesisTime: this.l1GenesisTime,
53
+ ethereumSlotDuration: this.ethereumSlotDuration,
54
+ });
55
+ const timestamp = earliestTimestamp > nextEthTimestamp ? earliestTimestamp : nextEthTimestamp;
56
+
57
+ return new GasFees(0, await this.rollupContract.getManaMinFeeAt(timestamp, true));
58
+ }
59
+
60
+ public async getCurrentMinFees(): Promise<GasFees> {
61
+ // Get the current block number
62
+ const blockNumber = await this.publicClient.getBlockNumber({ cacheTime: 0 });
63
+
64
+ // If the L1 block number has changed then chain a new promise to get the current min fees
65
+ if (this.currentL1BlockNumber === undefined || blockNumber > this.currentL1BlockNumber) {
66
+ this.currentL1BlockNumber = blockNumber;
67
+ this.currentMinFees = this.currentMinFees.then(() => this.computeCurrentMinFees());
68
+ }
69
+ return this.currentMinFees;
70
+ }
71
+
72
+ public async getPredictedMinFees(manaUsage?: ManaUsageEstimate): Promise<GasFees[]> {
73
+ const [currentMinFees, predictedMinFees] = await Promise.all([
74
+ this.getCurrentMinFees(),
75
+ this.feePredictor.getPredictedMinFees(manaUsage ?? ManaUsageEstimate.Target),
76
+ ]);
77
+
78
+ return [currentMinFees, ...predictedMinFees];
79
+ }
80
+ }
@@ -1,15 +1,15 @@
1
- import { createEthereumChain } from '@aztec/ethereum/chain';
2
- import { makeL1HttpTransport } from '@aztec/ethereum/client';
3
- import type { L1ContractsConfig } from '@aztec/ethereum/config';
4
- import { RollupContract } from '@aztec/ethereum/contracts';
5
- import type { L1ReaderConfig } from '@aztec/ethereum/l1-reader';
1
+ import {
2
+ RollupContract,
3
+ type SimulationOverridesPlan,
4
+ buildSimulationOverridesStateOverride,
5
+ } from '@aztec/ethereum/contracts';
6
6
  import type { ViemPublicClient } from '@aztec/ethereum/types';
7
7
  import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
8
8
  import { Fr } from '@aztec/foundation/curves/bn254';
9
9
  import type { EthAddress } from '@aztec/foundation/eth-address';
10
- import { createLogger } from '@aztec/foundation/log';
10
+ import type { DateProvider } from '@aztec/foundation/timer';
11
11
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
12
- import { type L1RollupConstants, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
12
+ import { type L1RollupConstants, getNextL1SlotTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
13
13
  import { GasFees } from '@aztec/stdlib/gas';
14
14
  import type {
15
15
  CheckpointGlobalVariables,
@@ -17,18 +17,18 @@ import type {
17
17
  } from '@aztec/stdlib/tx';
18
18
  import { GlobalVariables } from '@aztec/stdlib/tx';
19
19
 
20
- import { createPublicClient } from 'viem';
20
+ /** Configuration for the GlobalVariableBuilder (excludes L1 client config). */
21
+ export type GlobalVariableBuilderConfig = {
22
+ rollupAddress: EthAddress;
23
+ ethereumSlotDuration: number;
24
+ rollupVersion: bigint;
25
+ } & Pick<L1RollupConstants, 'slotDuration' | 'l1GenesisTime'>;
21
26
 
22
27
  /**
23
28
  * Simple global variables builder.
24
29
  */
25
30
  export class GlobalVariableBuilder implements GlobalVariableBuilderInterface {
26
- private log = createLogger('sequencer:global_variable_builder');
27
- private currentMinFees: Promise<GasFees> = Promise.resolve(new GasFees(0, 0));
28
- private currentL1BlockNumber: bigint | undefined = undefined;
29
-
30
31
  private readonly rollupContract: RollupContract;
31
- private readonly publicClient: ViemPublicClient;
32
32
  private readonly ethereumSlotDuration: number;
33
33
  private readonly aztecSlotDuration: number;
34
34
  private readonly l1GenesisTime: bigint;
@@ -37,59 +37,18 @@ export class GlobalVariableBuilder implements GlobalVariableBuilderInterface {
37
37
  private version: Fr;
38
38
 
39
39
  constructor(
40
- config: L1ReaderConfig &
41
- Pick<L1ContractsConfig, 'ethereumSlotDuration'> &
42
- Pick<L1RollupConstants, 'slotDuration' | 'l1GenesisTime'> & { rollupVersion: bigint },
40
+ private readonly dateProvider: DateProvider,
41
+ private readonly publicClient: ViemPublicClient,
42
+ config: GlobalVariableBuilderConfig,
43
43
  ) {
44
- const { l1RpcUrls, l1ChainId: chainId, l1Contracts } = config;
45
-
46
- const chain = createEthereumChain(l1RpcUrls, chainId);
47
-
48
44
  this.version = new Fr(config.rollupVersion);
49
- this.chainId = new Fr(chainId);
45
+ this.chainId = new Fr(this.publicClient.chain!.id);
50
46
 
51
47
  this.ethereumSlotDuration = config.ethereumSlotDuration;
52
48
  this.aztecSlotDuration = config.slotDuration;
53
49
  this.l1GenesisTime = config.l1GenesisTime;
54
50
 
55
- this.publicClient = createPublicClient({
56
- chain: chain.chainInfo,
57
- transport: makeL1HttpTransport(chain.rpcUrls, { timeout: config.l1HttpTimeoutMS }),
58
- pollingInterval: config.viemPollingIntervalMS,
59
- });
60
-
61
- this.rollupContract = new RollupContract(this.publicClient, l1Contracts.rollupAddress);
62
- }
63
-
64
- /**
65
- * Computes the "current" min fees, e.g., the price that you currently should pay to get include in the next block
66
- * @returns Min fees for the next block
67
- */
68
- private async computeCurrentMinFees(): Promise<GasFees> {
69
- // Since this might be called in the middle of a slot where a block might have been published,
70
- // we need to fetch the last block written, and estimate the earliest timestamp for the next block.
71
- // The timestamp of that last block will act as a lower bound for the next block.
72
-
73
- const lastCheckpoint = await this.rollupContract.getPendingCheckpoint();
74
- const earliestTimestamp = await this.rollupContract.getTimestampForSlot(
75
- SlotNumber.fromBigInt(BigInt(lastCheckpoint.slotNumber) + 1n),
76
- );
77
- const nextEthTimestamp = BigInt((await this.publicClient.getBlock()).timestamp + BigInt(this.ethereumSlotDuration));
78
- const timestamp = earliestTimestamp > nextEthTimestamp ? earliestTimestamp : nextEthTimestamp;
79
-
80
- return new GasFees(0, await this.rollupContract.getManaMinFeeAt(timestamp, true));
81
- }
82
-
83
- public async getCurrentMinFees(): Promise<GasFees> {
84
- // Get the current block number
85
- const blockNumber = await this.publicClient.getBlockNumber();
86
-
87
- // If the L1 block number has changed then chain a new promise to get the current min fees
88
- if (this.currentL1BlockNumber === undefined || blockNumber > this.currentL1BlockNumber) {
89
- this.currentL1BlockNumber = blockNumber;
90
- this.currentMinFees = this.currentMinFees.then(() => this.computeCurrentMinFees());
91
- }
92
- return this.currentMinFees;
51
+ this.rollupContract = new RollupContract(this.publicClient, config.rollupAddress);
93
52
  }
94
53
 
95
54
  /**
@@ -109,7 +68,10 @@ export class GlobalVariableBuilder implements GlobalVariableBuilderInterface {
109
68
  const slot: SlotNumber =
110
69
  maybeSlot ??
111
70
  (await this.rollupContract.getSlotAt(
112
- BigInt((await this.publicClient.getBlock()).timestamp + BigInt(this.ethereumSlotDuration)),
71
+ getNextL1SlotTimestamp(this.dateProvider.nowInSeconds(), {
72
+ l1GenesisTime: this.l1GenesisTime,
73
+ ethereumSlotDuration: this.ethereumSlotDuration,
74
+ }),
113
75
  ));
114
76
 
115
77
  const checkpointGlobalVariables = await this.buildCheckpointGlobalVariables(coinbase, feeRecipient, slot);
@@ -121,6 +83,7 @@ export class GlobalVariableBuilder implements GlobalVariableBuilderInterface {
121
83
  coinbase: EthAddress,
122
84
  feeRecipient: AztecAddress,
123
85
  slotNumber: SlotNumber,
86
+ simulationOverridesPlan?: SimulationOverridesPlan,
124
87
  ): Promise<CheckpointGlobalVariables> {
125
88
  const { chainId, version } = this;
126
89
 
@@ -129,9 +92,8 @@ export class GlobalVariableBuilder implements GlobalVariableBuilderInterface {
129
92
  l1GenesisTime: this.l1GenesisTime,
130
93
  });
131
94
 
132
- // We can skip much of the logic in getCurrentMinFees since it we already check that we are not within a slot elsewhere.
133
- // TODO(palla/mbps): Can we use a cached value here?
134
- const gasFees = new GasFees(0, await this.rollupContract.getManaMinFeeAt(timestamp, true));
95
+ const stateOverride = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
96
+ const gasFees = new GasFees(0, await this.rollupContract.getManaMinFeeAt(timestamp, true, stateOverride));
135
97
 
136
98
  return { chainId, version, slotNumber, timestamp, coinbase, feeRecipient, gasFees };
137
99
  }
@@ -1 +1,3 @@
1
- export { GlobalVariableBuilder } from './global_builder.js';
1
+ export { FeeProviderImpl } from './fee_provider.js';
2
+ export { GlobalVariableBuilder, type GlobalVariableBuilderConfig } from './global_builder.js';
3
+ export { FeePredictor } from './fee_predictor.js';