@aztec/sequencer-client 0.0.1-commit.e558bd1c → 0.0.1-commit.e5a3663dd

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 (103) hide show
  1. package/dest/client/sequencer-client.d.ts +17 -7
  2. package/dest/client/sequencer-client.d.ts.map +1 -1
  3. package/dest/client/sequencer-client.js +63 -30
  4. package/dest/config.d.ts +27 -7
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +58 -37
  7. package/dest/global_variable_builder/fee_predictor.d.ts +37 -0
  8. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  9. package/dest/global_variable_builder/fee_predictor.js +128 -0
  10. package/dest/global_variable_builder/fee_provider.d.ts +21 -0
  11. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  12. package/dest/global_variable_builder/fee_provider.js +58 -0
  13. package/dest/global_variable_builder/global_builder.d.ts +15 -16
  14. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  15. package/dest/global_variable_builder/global_builder.js +16 -50
  16. package/dest/global_variable_builder/index.d.ts +4 -2
  17. package/dest/global_variable_builder/index.d.ts.map +1 -1
  18. package/dest/global_variable_builder/index.js +2 -0
  19. package/dest/publisher/config.d.ts +47 -17
  20. package/dest/publisher/config.d.ts.map +1 -1
  21. package/dest/publisher/config.js +121 -42
  22. package/dest/publisher/index.d.ts +2 -1
  23. package/dest/publisher/index.d.ts.map +1 -1
  24. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  25. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  26. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  27. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +58 -0
  28. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  29. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +1 -0
  30. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  31. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  32. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +34 -0
  33. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  34. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  35. package/dest/publisher/l1_tx_failed_store/index.js +2 -0
  36. package/dest/publisher/sequencer-publisher-factory.d.ts +11 -5
  37. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  38. package/dest/publisher/sequencer-publisher-factory.js +27 -3
  39. package/dest/publisher/sequencer-publisher.d.ts +75 -48
  40. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  41. package/dest/publisher/sequencer-publisher.js +434 -141
  42. package/dest/sequencer/chain_state_overrides.d.ts +25 -0
  43. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  44. package/dest/sequencer/chain_state_overrides.js +39 -0
  45. package/dest/sequencer/checkpoint_proposal_job.d.ts +46 -10
  46. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  47. package/dest/sequencer/checkpoint_proposal_job.js +705 -223
  48. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  49. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  50. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  51. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  52. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  53. package/dest/sequencer/checkpoint_voter.js +2 -5
  54. package/dest/sequencer/events.d.ts +7 -1
  55. package/dest/sequencer/events.d.ts.map +1 -1
  56. package/dest/sequencer/metrics.d.ts +23 -8
  57. package/dest/sequencer/metrics.d.ts.map +1 -1
  58. package/dest/sequencer/metrics.js +117 -21
  59. package/dest/sequencer/sequencer.d.ts +53 -19
  60. package/dest/sequencer/sequencer.d.ts.map +1 -1
  61. package/dest/sequencer/sequencer.js +188 -101
  62. package/dest/sequencer/timetable.d.ts +17 -6
  63. package/dest/sequencer/timetable.d.ts.map +1 -1
  64. package/dest/sequencer/timetable.js +51 -46
  65. package/dest/sequencer/types.d.ts +2 -2
  66. package/dest/sequencer/types.d.ts.map +1 -1
  67. package/dest/test/index.d.ts +3 -5
  68. package/dest/test/index.d.ts.map +1 -1
  69. package/dest/test/mock_checkpoint_builder.d.ts +11 -11
  70. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  71. package/dest/test/mock_checkpoint_builder.js +45 -34
  72. package/dest/test/utils.d.ts +3 -3
  73. package/dest/test/utils.d.ts.map +1 -1
  74. package/dest/test/utils.js +10 -8
  75. package/package.json +27 -28
  76. package/src/client/sequencer-client.ts +81 -30
  77. package/src/config.ts +77 -46
  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 +75 -0
  81. package/src/global_variable_builder/global_builder.ts +27 -63
  82. package/src/global_variable_builder/index.ts +3 -1
  83. package/src/publisher/config.ts +157 -45
  84. package/src/publisher/index.ts +3 -0
  85. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  86. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  87. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  88. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  89. package/src/publisher/sequencer-publisher-factory.ts +38 -9
  90. package/src/publisher/sequencer-publisher.ts +501 -202
  91. package/src/sequencer/README.md +82 -13
  92. package/src/sequencer/chain_state_overrides.ts +87 -0
  93. package/src/sequencer/checkpoint_proposal_job.ts +873 -243
  94. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  95. package/src/sequencer/checkpoint_voter.ts +1 -12
  96. package/src/sequencer/events.ts +6 -1
  97. package/src/sequencer/metrics.ts +132 -25
  98. package/src/sequencer/sequencer.ts +262 -115
  99. package/src/sequencer/timetable.ts +70 -57
  100. package/src/sequencer/types.ts +1 -1
  101. package/src/test/index.ts +2 -4
  102. package/src/test/mock_checkpoint_builder.ts +63 -49
  103. package/src/test/utils.ts +31 -10
@@ -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,75 @@
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.l1Contracts.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();
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 getPredictedMinFees(manaUsage?: ManaUsageEstimate): Promise<GasFees[]> {
73
+ return this.feePredictor.getPredictedMinFees(manaUsage ?? ManaUsageEstimate.Target);
74
+ }
75
+ }
@@ -1,14 +1,16 @@
1
- import { createEthereumChain } from '@aztec/ethereum/chain';
2
- import type { L1ContractsConfig } from '@aztec/ethereum/config';
3
- import { RollupContract } from '@aztec/ethereum/contracts';
4
- import type { L1ReaderConfig } from '@aztec/ethereum/l1-reader';
1
+ import {
2
+ RollupContract,
3
+ type SimulationOverridesPlan,
4
+ buildSimulationOverridesStateOverride,
5
+ } from '@aztec/ethereum/contracts';
6
+ import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
5
7
  import type { ViemPublicClient } from '@aztec/ethereum/types';
6
8
  import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
7
9
  import { Fr } from '@aztec/foundation/curves/bn254';
8
10
  import type { EthAddress } from '@aztec/foundation/eth-address';
9
- import { createLogger } from '@aztec/foundation/log';
11
+ import type { DateProvider } from '@aztec/foundation/timer';
10
12
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
11
- import { type L1RollupConstants, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
13
+ import { type L1RollupConstants, getNextL1SlotTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
12
14
  import { GasFees } from '@aztec/stdlib/gas';
13
15
  import type {
14
16
  CheckpointGlobalVariables,
@@ -16,18 +18,18 @@ import type {
16
18
  } from '@aztec/stdlib/tx';
17
19
  import { GlobalVariables } from '@aztec/stdlib/tx';
18
20
 
19
- import { createPublicClient, fallback, http } from 'viem';
21
+ /** Configuration for the GlobalVariableBuilder (excludes L1 client config). */
22
+ export type GlobalVariableBuilderConfig = {
23
+ l1Contracts: Pick<L1ContractAddresses, 'rollupAddress'>;
24
+ ethereumSlotDuration: number;
25
+ rollupVersion: bigint;
26
+ } & Pick<L1RollupConstants, 'slotDuration' | 'l1GenesisTime'>;
20
27
 
21
28
  /**
22
29
  * Simple global variables builder.
23
30
  */
24
31
  export class GlobalVariableBuilder implements GlobalVariableBuilderInterface {
25
- private log = createLogger('sequencer:global_variable_builder');
26
- private currentMinFees: Promise<GasFees> = Promise.resolve(new GasFees(0, 0));
27
- private currentL1BlockNumber: bigint | undefined = undefined;
28
-
29
32
  private readonly rollupContract: RollupContract;
30
- private readonly publicClient: ViemPublicClient;
31
33
  private readonly ethereumSlotDuration: number;
32
34
  private readonly aztecSlotDuration: number;
33
35
  private readonly l1GenesisTime: bigint;
@@ -36,59 +38,18 @@ export class GlobalVariableBuilder implements GlobalVariableBuilderInterface {
36
38
  private version: Fr;
37
39
 
38
40
  constructor(
39
- config: L1ReaderConfig &
40
- Pick<L1ContractsConfig, 'ethereumSlotDuration'> &
41
- Pick<L1RollupConstants, 'slotDuration' | 'l1GenesisTime'> & { rollupVersion: bigint },
41
+ private readonly dateProvider: DateProvider,
42
+ private readonly publicClient: ViemPublicClient,
43
+ config: GlobalVariableBuilderConfig,
42
44
  ) {
43
- const { l1RpcUrls, l1ChainId: chainId, l1Contracts } = config;
44
-
45
- const chain = createEthereumChain(l1RpcUrls, chainId);
46
-
47
45
  this.version = new Fr(config.rollupVersion);
48
- this.chainId = new Fr(chainId);
46
+ this.chainId = new Fr(this.publicClient.chain!.id);
49
47
 
50
48
  this.ethereumSlotDuration = config.ethereumSlotDuration;
51
49
  this.aztecSlotDuration = config.slotDuration;
52
50
  this.l1GenesisTime = config.l1GenesisTime;
53
51
 
54
- this.publicClient = createPublicClient({
55
- chain: chain.chainInfo,
56
- transport: fallback(chain.rpcUrls.map(url => http(url, { batch: false }))),
57
- pollingInterval: config.viemPollingIntervalMS,
58
- });
59
-
60
- this.rollupContract = new RollupContract(this.publicClient, l1Contracts.rollupAddress);
61
- }
62
-
63
- /**
64
- * Computes the "current" min fees, e.g., the price that you currently should pay to get include in the next block
65
- * @returns Min fees for the next block
66
- */
67
- private async computeCurrentMinFees(): Promise<GasFees> {
68
- // Since this might be called in the middle of a slot where a block might have been published,
69
- // we need to fetch the last block written, and estimate the earliest timestamp for the next block.
70
- // The timestamp of that last block will act as a lower bound for the next block.
71
-
72
- const lastCheckpoint = await this.rollupContract.getPendingCheckpoint();
73
- const earliestTimestamp = await this.rollupContract.getTimestampForSlot(
74
- SlotNumber.fromBigInt(BigInt(lastCheckpoint.slotNumber) + 1n),
75
- );
76
- const nextEthTimestamp = BigInt((await this.publicClient.getBlock()).timestamp + BigInt(this.ethereumSlotDuration));
77
- const timestamp = earliestTimestamp > nextEthTimestamp ? earliestTimestamp : nextEthTimestamp;
78
-
79
- return new GasFees(0, await this.rollupContract.getManaMinFeeAt(timestamp, true));
80
- }
81
-
82
- public async getCurrentMinFees(): Promise<GasFees> {
83
- // Get the current block number
84
- const blockNumber = await this.publicClient.getBlockNumber();
85
-
86
- // If the L1 block number has changed then chain a new promise to get the current min fees
87
- if (this.currentL1BlockNumber === undefined || blockNumber > this.currentL1BlockNumber) {
88
- this.currentL1BlockNumber = blockNumber;
89
- this.currentMinFees = this.currentMinFees.then(() => this.computeCurrentMinFees());
90
- }
91
- return this.currentMinFees;
52
+ this.rollupContract = new RollupContract(this.publicClient, config.l1Contracts.rollupAddress);
92
53
  }
93
54
 
94
55
  /**
@@ -108,7 +69,10 @@ export class GlobalVariableBuilder implements GlobalVariableBuilderInterface {
108
69
  const slot: SlotNumber =
109
70
  maybeSlot ??
110
71
  (await this.rollupContract.getSlotAt(
111
- BigInt((await this.publicClient.getBlock()).timestamp + BigInt(this.ethereumSlotDuration)),
72
+ getNextL1SlotTimestamp(this.dateProvider.nowInSeconds(), {
73
+ l1GenesisTime: this.l1GenesisTime,
74
+ ethereumSlotDuration: this.ethereumSlotDuration,
75
+ }),
112
76
  ));
113
77
 
114
78
  const checkpointGlobalVariables = await this.buildCheckpointGlobalVariables(coinbase, feeRecipient, slot);
@@ -120,7 +84,8 @@ export class GlobalVariableBuilder implements GlobalVariableBuilderInterface {
120
84
  coinbase: EthAddress,
121
85
  feeRecipient: AztecAddress,
122
86
  slotNumber: SlotNumber,
123
- ): Promise<CheckpointGlobalVariables & { timestamp: bigint }> {
87
+ simulationOverridesPlan?: SimulationOverridesPlan,
88
+ ): Promise<CheckpointGlobalVariables> {
124
89
  const { chainId, version } = this;
125
90
 
126
91
  const timestamp = getTimestampForSlot(slotNumber, {
@@ -128,9 +93,8 @@ export class GlobalVariableBuilder implements GlobalVariableBuilderInterface {
128
93
  l1GenesisTime: this.l1GenesisTime,
129
94
  });
130
95
 
131
- // We can skip much of the logic in getCurrentMinFees since it we already check that we are not within a slot elsewhere.
132
- // TODO(palla/mbps): Can we use a cached value here?
133
- const gasFees = new GasFees(0, await this.rollupContract.getManaMinFeeAt(timestamp, true));
96
+ const stateOverride = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
97
+ const gasFees = new GasFees(0, await this.rollupContract.getManaMinFeeAt(timestamp, true, stateOverride));
134
98
 
135
99
  return { chainId, version, slotNumber, timestamp, coinbase, feeRecipient, gasFees };
136
100
  }
@@ -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';
@@ -1,32 +1,47 @@
1
1
  import { type BlobClientConfig, blobClientConfigMapping } from '@aztec/blob-client/client/config';
2
2
  import { type L1ReaderConfig, l1ReaderConfigMappings } from '@aztec/ethereum/l1-reader';
3
3
  import { type L1TxUtilsConfig, l1TxUtilsConfigMappings } from '@aztec/ethereum/l1-tx-utils/config';
4
- import {
5
- type ConfigMappingsType,
6
- SecretValue,
7
- booleanConfigHelper,
8
- getConfigFromMappings,
9
- } from '@aztec/foundation/config';
4
+ import { type ConfigMappingsType, SecretValue, booleanConfigHelper } from '@aztec/foundation/config';
10
5
  import { EthAddress } from '@aztec/foundation/eth-address';
11
6
 
12
- /**
13
- * The configuration of the rollup transaction publisher.
14
- */
7
+ import { parseEther } from 'viem';
8
+
9
+ /** Configuration of the transaction publisher. */
15
10
  export type TxSenderConfig = L1ReaderConfig & {
16
- /**
17
- * The private key to be used by the publisher.
18
- */
11
+ /** The private key to be used by the publisher. */
19
12
  publisherPrivateKeys?: SecretValue<`0x${string}`>[];
20
13
 
21
- /**
22
- * Publisher addresses to be used with a remote signer
23
- */
14
+ /** Publisher addresses to be used with a remote signer */
24
15
  publisherAddresses?: EthAddress[];
25
16
  };
26
17
 
27
- /**
28
- * Configuration of the L1Publisher.
29
- */
18
+ export type ProverTxSenderConfig = L1ReaderConfig & {
19
+ proverPublisherPrivateKeys?: SecretValue<`0x${string}`>[];
20
+ proverPublisherAddresses?: EthAddress[];
21
+ };
22
+
23
+ export type SequencerTxSenderConfig = L1ReaderConfig & {
24
+ sequencerPublisherPrivateKeys?: SecretValue<`0x${string}`>[];
25
+ sequencerPublisherAddresses?: EthAddress[];
26
+ };
27
+
28
+ export function getTxSenderConfigFromProverConfig(config: ProverTxSenderConfig): TxSenderConfig {
29
+ return {
30
+ ...config,
31
+ publisherPrivateKeys: config.proverPublisherPrivateKeys,
32
+ publisherAddresses: config.proverPublisherAddresses,
33
+ };
34
+ }
35
+
36
+ export function getTxSenderConfigFromSequencerConfig(config: SequencerTxSenderConfig): TxSenderConfig {
37
+ return {
38
+ ...config,
39
+ publisherPrivateKeys: config.sequencerPublisherPrivateKeys,
40
+ publisherAddresses: config.sequencerPublisherAddresses,
41
+ };
42
+ }
43
+
44
+ /** Configuration of the L1Publisher. */
30
45
  export type PublisherConfig = L1TxUtilsConfig &
31
46
  BlobClientConfig & {
32
47
  /** True to use publishers in invalid states (timed out, cancelled, etc) if no other is available */
@@ -35,37 +50,113 @@ export type PublisherConfig = L1TxUtilsConfig &
35
50
  fishermanMode?: boolean;
36
51
  /** Address of the forwarder contract to wrap all L1 transactions through (for testing purposes only) */
37
52
  publisherForwarderAddress?: EthAddress;
53
+ /** Store for failed L1 transaction inputs (test networks only). Format: gs://bucket/path */
54
+ l1TxFailedStore?: string;
55
+ /** Min ETH balance below which a publisher gets funded. Undefined = funding disabled. */
56
+ publisherFundingThreshold?: bigint;
57
+ /** Amount of ETH to send when funding a publisher. Undefined = funding disabled. */
58
+ publisherFundingAmount?: bigint;
59
+ };
60
+
61
+ /** Shared config mappings for publisher funding, used by both sequencer and prover publisher configs. */
62
+ const publisherFundingConfigMappings = {
63
+ publisherFundingThreshold: {
64
+ env: 'PUBLISHER_FUNDING_THRESHOLD' as const,
65
+ description:
66
+ 'Min ETH balance below which a publisher gets funded. Specified in ether (e.g. 0.1). Unset = funding disabled.',
67
+ parseEnv: (val: string) => parseEther(val),
68
+ },
69
+ publisherFundingAmount: {
70
+ env: 'PUBLISHER_FUNDING_AMOUNT' as const,
71
+ description:
72
+ 'Amount of ETH to send when funding a publisher. Specified in ether (e.g. 0.5). Unset = funding disabled.',
73
+ parseEnv: (val: string) => parseEther(val),
74
+ },
75
+ };
76
+
77
+ export type ProverPublisherConfig = L1TxUtilsConfig &
78
+ BlobClientConfig & {
79
+ fishermanMode?: boolean;
80
+ proverPublisherAllowInvalidStates?: boolean;
81
+ proverPublisherForwarderAddress?: EthAddress;
82
+ /** Min ETH balance below which a publisher gets funded. Undefined = funding disabled. */
83
+ publisherFundingThreshold?: bigint;
84
+ /** Amount of ETH to send when funding a publisher. Undefined = funding disabled. */
85
+ publisherFundingAmount?: bigint;
86
+ };
87
+
88
+ export type SequencerPublisherConfig = L1TxUtilsConfig &
89
+ BlobClientConfig & {
90
+ fishermanMode?: boolean;
91
+ sequencerPublisherAllowInvalidStates?: boolean;
92
+ sequencerPublisherForwarderAddress?: EthAddress;
93
+ /** Store for failed L1 transaction inputs (test networks only). Format: gs://bucket/path */
94
+ l1TxFailedStore?: string;
95
+ /** Min ETH balance below which a publisher gets funded. Undefined = funding disabled. */
96
+ publisherFundingThreshold?: bigint;
97
+ /** Amount of ETH to send when funding a publisher. Undefined = funding disabled. */
98
+ publisherFundingAmount?: bigint;
99
+ };
100
+
101
+ export function getPublisherConfigFromProverConfig(config: ProverPublisherConfig): PublisherConfig {
102
+ return {
103
+ ...config,
104
+ publisherAllowInvalidStates: config.proverPublisherAllowInvalidStates,
105
+ publisherForwarderAddress: config.proverPublisherForwarderAddress,
106
+ };
107
+ }
108
+
109
+ export function getPublisherConfigFromSequencerConfig(config: SequencerPublisherConfig): PublisherConfig {
110
+ return {
111
+ ...config,
112
+ publisherAllowInvalidStates: config.sequencerPublisherAllowInvalidStates,
113
+ publisherForwarderAddress: config.sequencerPublisherForwarderAddress,
114
+ l1TxFailedStore: config.l1TxFailedStore,
38
115
  };
116
+ }
39
117
 
40
- export const getTxSenderConfigMappings: (
41
- scope: 'PROVER' | 'SEQ',
42
- ) => ConfigMappingsType<Omit<TxSenderConfig, 'l1Contracts'>> = (scope: 'PROVER' | 'SEQ') => ({
118
+ export const proverTxSenderConfigMappings: ConfigMappingsType<Omit<ProverTxSenderConfig, 'l1Contracts'>> = {
43
119
  ...l1ReaderConfigMappings,
44
- publisherPrivateKeys: {
45
- env: scope === 'PROVER' ? `PROVER_PUBLISHER_PRIVATE_KEYS` : `SEQ_PUBLISHER_PRIVATE_KEYS`,
46
- description: 'The private keys to be used by the publisher.',
47
- parseEnv: (val: string) => val.split(',').map(key => new SecretValue(`0x${key.replace('0x', '')}`)),
120
+ proverPublisherPrivateKeys: {
121
+ env: `PROVER_PUBLISHER_PRIVATE_KEYS`,
122
+ description: 'The private keys to be used by the prover publisher.',
123
+ parseEnv: (val: string) =>
124
+ val.split(',').map(key => new SecretValue(`0x${key.replace('0x', '')}` as `0x${string}`)),
48
125
  defaultValue: [],
49
- fallback: [scope === 'PROVER' ? `PROVER_PUBLISHER_PRIVATE_KEY` : `SEQ_PUBLISHER_PRIVATE_KEY`],
126
+ fallback: [`PROVER_PUBLISHER_PRIVATE_KEY`],
50
127
  },
51
- publisherAddresses: {
52
- env: scope === 'PROVER' ? `PROVER_PUBLISHER_ADDRESSES` : `SEQ_PUBLISHER_ADDRESSES`,
128
+ proverPublisherAddresses: {
129
+ env: `PROVER_PUBLISHER_ADDRESSES`,
53
130
  description: 'The addresses of the publishers to use with remote signers',
54
131
  parseEnv: (val: string) => val.split(',').map(address => EthAddress.fromString(address)),
55
132
  defaultValue: [],
56
133
  },
57
- });
134
+ };
58
135
 
59
- export function getTxSenderConfigFromEnv(scope: 'PROVER' | 'SEQ'): Omit<TxSenderConfig, 'l1Contracts'> {
60
- return getConfigFromMappings(getTxSenderConfigMappings(scope));
61
- }
136
+ export const sequencerTxSenderConfigMappings: ConfigMappingsType<Omit<SequencerTxSenderConfig, 'l1Contracts'>> = {
137
+ ...l1ReaderConfigMappings,
138
+ sequencerPublisherPrivateKeys: {
139
+ env: `SEQ_PUBLISHER_PRIVATE_KEYS`,
140
+ description: 'The private keys to be used by the sequencer publisher.',
141
+ parseEnv: (val: string) =>
142
+ val.split(',').map(key => new SecretValue(`0x${key.replace('0x', '')}` as `0x${string}`)),
143
+ defaultValue: [],
144
+ fallback: [`SEQ_PUBLISHER_PRIVATE_KEY`],
145
+ },
146
+ sequencerPublisherAddresses: {
147
+ env: `SEQ_PUBLISHER_ADDRESSES`,
148
+ description: 'The addresses of the publishers to use with remote signers',
149
+ parseEnv: (val: string) => val.split(',').map(address => EthAddress.fromString(address)),
150
+ defaultValue: [],
151
+ },
152
+ };
62
153
 
63
- export const getPublisherConfigMappings: (
64
- scope: 'PROVER' | 'SEQ',
65
- ) => ConfigMappingsType<PublisherConfig & L1TxUtilsConfig> = scope => ({
66
- publisherAllowInvalidStates: {
154
+ export const sequencerPublisherConfigMappings: ConfigMappingsType<SequencerPublisherConfig & L1TxUtilsConfig> = {
155
+ ...l1TxUtilsConfigMappings,
156
+ ...blobClientConfigMapping,
157
+ sequencerPublisherAllowInvalidStates: {
158
+ env: `SEQ_PUBLISHER_ALLOW_INVALID_STATES`,
67
159
  description: 'True to use publishers in invalid states (timed out, cancelled, etc) if no other is available',
68
- env: scope === `PROVER` ? `PROVER_PUBLISHER_ALLOW_INVALID_STATES` : `SEQ_PUBLISHER_ALLOW_INVALID_STATES`,
69
160
  ...booleanConfigHelper(true),
70
161
  },
71
162
  fishermanMode: {
@@ -74,15 +165,36 @@ export const getPublisherConfigMappings: (
74
165
  'Whether to run in fisherman mode: builds blocks on every slot for validation without publishing to L1',
75
166
  ...booleanConfigHelper(false),
76
167
  },
77
- publisherForwarderAddress: {
78
- env: scope === `PROVER` ? `PROVER_PUBLISHER_FORWARDER_ADDRESS` : `SEQ_PUBLISHER_FORWARDER_ADDRESS`,
168
+ sequencerPublisherForwarderAddress: {
169
+ env: `SEQ_PUBLISHER_FORWARDER_ADDRESS`,
79
170
  description: 'Address of the forwarder contract to wrap all L1 transactions through (for testing purposes only)',
80
- parseEnv: (val: string) => (val ? EthAddress.fromString(val) : undefined),
171
+ parseEnv: (val: string) => EthAddress.fromString(val),
172
+ },
173
+ l1TxFailedStore: {
174
+ env: 'L1_TX_FAILED_STORE',
175
+ description: 'Store for failed L1 transaction inputs (test networks only). Format: gs://bucket/path',
81
176
  },
177
+ ...publisherFundingConfigMappings,
178
+ };
179
+
180
+ export const proverPublisherConfigMappings: ConfigMappingsType<ProverPublisherConfig & L1TxUtilsConfig> = {
82
181
  ...l1TxUtilsConfigMappings,
83
182
  ...blobClientConfigMapping,
84
- });
85
-
86
- export function getPublisherConfigFromEnv(scope: 'PROVER' | 'SEQ'): PublisherConfig {
87
- return getConfigFromMappings(getPublisherConfigMappings(scope));
88
- }
183
+ proverPublisherAllowInvalidStates: {
184
+ env: `PROVER_PUBLISHER_ALLOW_INVALID_STATES`,
185
+ description: 'True to use publishers in invalid states (timed out, cancelled, etc) if no other is available',
186
+ ...booleanConfigHelper(true),
187
+ },
188
+ fishermanMode: {
189
+ env: 'FISHERMAN_MODE',
190
+ description:
191
+ 'Whether to run in fisherman mode: builds blocks on every slot for validation without publishing to L1',
192
+ ...booleanConfigHelper(false),
193
+ },
194
+ proverPublisherForwarderAddress: {
195
+ env: `PROVER_PUBLISHER_FORWARDER_ADDRESS`,
196
+ description: 'Address of the forwarder contract to wrap all L1 transactions through (for testing purposes only)',
197
+ parseEnv: (val: string) => EthAddress.fromString(val),
198
+ },
199
+ ...publisherFundingConfigMappings,
200
+ };
@@ -3,3 +3,6 @@ export { SequencerPublisherFactory } from './sequencer-publisher-factory.js';
3
3
 
4
4
  // Used for tests
5
5
  export { SequencerPublisherMetrics } from './sequencer-publisher-metrics.js';
6
+
7
+ // Failed L1 tx store (optional, for test networks)
8
+ export { type FailedL1Tx, type FailedL1TxUri, type L1TxFailedStore } from './l1_tx_failed_store/index.js';