@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
@@ -0,0 +1,677 @@
1
+ function _ts_add_disposable_resource(env, value, async) {
2
+ if (value !== null && value !== void 0) {
3
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
+ var dispose, inner;
5
+ if (async) {
6
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
+ dispose = value[Symbol.asyncDispose];
8
+ }
9
+ if (dispose === void 0) {
10
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
+ dispose = value[Symbol.dispose];
12
+ if (async) inner = dispose;
13
+ }
14
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
+ if (inner) dispose = function() {
16
+ try {
17
+ inner.call(this);
18
+ } catch (e) {
19
+ return Promise.reject(e);
20
+ }
21
+ };
22
+ env.stack.push({
23
+ value: value,
24
+ dispose: dispose,
25
+ async: async
26
+ });
27
+ } else if (async) {
28
+ env.stack.push({
29
+ async: true
30
+ });
31
+ }
32
+ return value;
33
+ }
34
+ function _ts_dispose_resources(env) {
35
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
36
+ var e = new Error(message);
37
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
38
+ };
39
+ return (_ts_dispose_resources = function _ts_dispose_resources(env) {
40
+ function fail(e) {
41
+ env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
42
+ env.hasError = true;
43
+ }
44
+ var r, s = 0;
45
+ function next() {
46
+ while(r = env.stack.pop()){
47
+ try {
48
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
49
+ if (r.dispose) {
50
+ var result = r.dispose.call(r.value);
51
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
52
+ fail(e);
53
+ return next();
54
+ });
55
+ } else s |= 1;
56
+ } catch (e) {
57
+ fail(e);
58
+ }
59
+ }
60
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
61
+ if (env.hasError) throw env.error;
62
+ }
63
+ return next();
64
+ })(env);
65
+ }
66
+ import { RollupCheatCodes } from '@aztec/ethereum/test';
67
+ import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
68
+ import { Signature } from '@aztec/foundation/eth-signature';
69
+ import { createLogger } from '@aztec/foundation/log';
70
+ import { SerialQueue } from '@aztec/foundation/queue';
71
+ import { RunningPromise } from '@aztec/foundation/running-promise';
72
+ import { isErrorClass } from '@aztec/foundation/types';
73
+ import { settleEpochOutbox } from '@aztec/prover-client/test';
74
+ import { CommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
75
+ import { getPreviousCheckpointOutHashes } from '@aztec/stdlib/checkpoint';
76
+ import { getEpochAtSlot, getSlotAtTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
77
+ import { InsufficientValidTxsError } from '@aztec/stdlib/interfaces/server';
78
+ /**
79
+ * Minimal, deterministic, queue-driven sequencer for e2e tests that don't exercise
80
+ * block-building or consensus (e.g. e2e_token, e2e_amm, e2e_authwit).
81
+ *
82
+ * Differences from the production `Sequencer`:
83
+ * - No proposer-turn check (single sequencer).
84
+ * - No sync check, no pipelining, no validator orchestration, no attestations,
85
+ * no slashing, no votes, no P2P proposal gossip, no timetable enforcement.
86
+ * - No event emission — consumers (archiver, world-state, `EpochTestSettler`) observe
87
+ * L1 and the archiver tip rather than sequencer events.
88
+ * - All test-driven time control (warp / mine empty block) goes through a single
89
+ * serial queue alongside mempool-driven builds; the three never interleave.
90
+ *
91
+ * Requires `aztecTargetCommitteeSize == 0` on the deployed rollup so that the
92
+ * L1 `verifyProposer` / `verifyAttestations` short-circuits accept an empty
93
+ * `CommitteeAttestationsAndSigners` (see
94
+ * `l1-contracts/src/core/libraries/rollup/ValidatorSelectionLib.sol:244`).
95
+ */ export class AutomineSequencer {
96
+ log;
97
+ queue;
98
+ pollIntervalMs;
99
+ deps;
100
+ running = false;
101
+ stopped = false;
102
+ paused = false;
103
+ mempoolPoller;
104
+ /** Loop that settles epochs and reconciles the clock while {@link AutomineSequencerDeps.autoSettle} is set. */ settler;
105
+ publisher;
106
+ attestorAddress;
107
+ /** Set while a mempool-driven build is queued but not yet run; used to coalesce. */ buildQueued = undefined;
108
+ /** Last L2 slot we published a checkpoint for (-1 means none yet). */ lastBuiltSlot = -1;
109
+ /** Lazily-built cheat codes for synthetic epoch settlement (outbox roots + proven tip). */ rollupCheatCodes;
110
+ constructor(deps){
111
+ this.deps = deps;
112
+ this.log = deps.log ?? createLogger('sequencer:automine');
113
+ this.queue = new SerialQueue();
114
+ this.pollIntervalMs = deps.pollIntervalMs ?? 50;
115
+ }
116
+ /** Cheat codes for the rollup, built from the same EthCheatCodes the sequencer uses for time control. */ getRollupCheatCodes() {
117
+ this.rollupCheatCodes ??= new RollupCheatCodes(this.deps.ethCheatCodes, {
118
+ rollupAddress: this.deps.config.rollupAddress
119
+ });
120
+ return this.rollupCheatCodes;
121
+ }
122
+ /**
123
+ * Starts the sequencer. Switches anvil into automine mode (no interval mining),
124
+ * acquires a publisher, and begins polling the mempool for pending txs.
125
+ */ async start() {
126
+ if (this.running) {
127
+ return;
128
+ }
129
+ this.running = true;
130
+ await this.deps.ethCheatCodes.setIntervalMining(0, {
131
+ silent: true
132
+ });
133
+ await this.deps.ethCheatCodes.setAutomine(true, {
134
+ silent: true
135
+ });
136
+ const { publisher, attestorAddress } = await this.deps.publisherFactory.create();
137
+ this.publisher = publisher;
138
+ this.attestorAddress = attestorAddress;
139
+ this.log.info(`AutomineSequencer started`, {
140
+ publisher: this.publisher.getSenderAddress().toString(),
141
+ attestor: this.attestorAddress.toString()
142
+ });
143
+ this.queue.start();
144
+ // Fallback poller that triggers a build if we discover pending txs without an explicit
145
+ // notification. Tests can also call `buildIfPending()` directly to skip the poll wait.
146
+ this.mempoolPoller = new RunningPromise(()=>this.maybeEnqueueBuild(), this.log, this.pollIntervalMs);
147
+ this.mempoolPoller.start();
148
+ // Local-network only: settle epochs and reconcile the clock to L1 as checkpoints land. Both run
149
+ // through the same serial queue as builds/warps, so they never interleave with a checkpoint build.
150
+ if (this.deps.autoSettle) {
151
+ this.settler = new RunningPromise(()=>this.maybeSettle(), this.log, this.deps.settlePollIntervalMs ?? 200);
152
+ this.settler.start();
153
+ }
154
+ }
155
+ /**
156
+ * Stops the sequencer. Drains the queue, unsubscribes the mempool poller, and runs any
157
+ * registered {@link AutomineSequencerDeps.stopExtras} hook (e.g. the PublisherManager's
158
+ * funding loop). Idempotent: subsequent calls return without re-running cleanup.
159
+ */ async stop() {
160
+ if (this.stopped) {
161
+ return;
162
+ }
163
+ this.stopped = true;
164
+ this.running = false;
165
+ await this.mempoolPoller?.stop();
166
+ await this.settler?.stop();
167
+ await this.queue.end();
168
+ await this.deps.stopExtras?.();
169
+ this.log.info('AutomineSequencer stopped');
170
+ }
171
+ /**
172
+ * Enqueues a mempool-driven build. Coalesces consecutive calls so a burst of new txs
173
+ * collapses into one build job. Returns the built block (or undefined if nothing was built
174
+ * or the sequencer is paused).
175
+ */ buildIfPending() {
176
+ if (!this.running || this.paused) {
177
+ return Promise.resolve(undefined);
178
+ }
179
+ if (this.buildQueued) {
180
+ // A build is already queued; coalesce. The pending build will pick up the new txs.
181
+ return this.buildQueued;
182
+ }
183
+ this.buildQueued = this.queue.put(async ()=>{
184
+ try {
185
+ return await this.runBuild({
186
+ allowEmpty: false
187
+ });
188
+ } finally{
189
+ this.buildQueued = undefined;
190
+ }
191
+ });
192
+ return this.buildQueued;
193
+ }
194
+ /**
195
+ * Pauses mempool-driven block production. Pending txs accumulate in the pool without being
196
+ * mined. Explicit test-harness operations (`buildEmptyBlock`, `warpTo`, `revertToCheckpoint`)
197
+ * continue to work; this only gates the mempool poller and `buildIfPending`.
198
+ */ pause() {
199
+ if (this.paused) {
200
+ return;
201
+ }
202
+ this.paused = true;
203
+ this.log.info('AutomineSequencer paused');
204
+ }
205
+ /** Resumes mempool-driven block production after a previous {@link pause}. */ resume() {
206
+ if (!this.paused) {
207
+ return;
208
+ }
209
+ this.paused = false;
210
+ this.log.info('AutomineSequencer resumed');
211
+ }
212
+ /**
213
+ * Updates the in-memory sequencer config. Mirrors {@link SequencerClient.updateConfig} so that
214
+ * `AztecNode.setConfig` (e.g. tests bumping `minTxsPerBlock` to bundle multiple txs into one
215
+ * block) propagates to the AutomineSequencer's gating logic in {@link runBuild}.
216
+ */ updateConfig(config) {
217
+ Object.assign(this.deps.config, config);
218
+ }
219
+ /** Returns a snapshot of the current sequencer config (used by pause/resume bookkeeping). */ getConfig() {
220
+ return this.deps.config;
221
+ }
222
+ /** Enqueues an empty-block build. Resolves to the built block. */ buildEmptyBlock() {
223
+ return this.queue.put(async ()=>{
224
+ const block = await this.runBuild({
225
+ allowEmpty: true
226
+ });
227
+ if (!block) {
228
+ throw new Error('buildEmptyBlock: runBuild returned undefined');
229
+ }
230
+ return block;
231
+ });
232
+ }
233
+ /**
234
+ * Warps L1 timestamp to `targetTimestampSec`. Rounded up to the next aztec-slot
235
+ * boundary so the next build lands on a fresh slot. Atomic with respect to builds —
236
+ * the queue ensures no build is in flight while the warp executes.
237
+ */ warpTo(targetTimestampSec) {
238
+ return this.queue.put(()=>this.runWarp(targetTimestampSec));
239
+ }
240
+ /** Warps L1 timestamp forward by `deltaSec` seconds from the current L1 time. */ warpBy(deltaSec) {
241
+ return this.queue.put(async ()=>{
242
+ const current = await this.deps.ethCheatCodes.lastBlockTimestamp();
243
+ await this.runWarp(current + deltaSec);
244
+ });
245
+ }
246
+ /**
247
+ * Reorgs L1 so that every L1 block strictly after the one that published
248
+ * `targetCheckpoint` is removed. The archiver, world-state, and date provider
249
+ * are all brought back in sync before the promise resolves.
250
+ *
251
+ * Runs inside the serial queue so it never interleaves with a build or warp.
252
+ */ revertToCheckpoint(targetCheckpoint) {
253
+ return this.queue.put(()=>this.runRevert(targetCheckpoint));
254
+ }
255
+ /** Awaits the queue draining to a fully idle state. */ syncPoint() {
256
+ return this.queue.syncPoint();
257
+ }
258
+ /**
259
+ * Synthetically "proves" the L2 chain up to `upToCheckpoint` (default: the latest checkpointed
260
+ * checkpoint). For every epoch newly covered — including a partial final epoch — the epoch out hash
261
+ * is written into the L1 Outbox so the L2-to-L1 messages in those checkpoints become consumable,
262
+ * then the rollup's proven tip is advanced to the target. There is no real proof; this is the
263
+ * local-network equivalent of an epoch proof landing on L1.
264
+ *
265
+ * Clamps the target down to the latest checkpointed checkpoint and no-ops when it is already proven.
266
+ * Runs inside the serial queue so it never interleaves with a build or warp.
267
+ *
268
+ * @returns The proven checkpoint after the call (the target, or the existing proven tip on no-op).
269
+ */ prove(upToCheckpoint) {
270
+ return this.queue.put(()=>this.runProve(upToCheckpoint));
271
+ }
272
+ /**
273
+ * Auto-settle tick (local-network only). Proving up to the latest checkpointed checkpoint also
274
+ * reconciles the clock at the head of {@link runProve}, so this single tick keeps both the
275
+ * proven tip and the date provider current even when no build is happening.
276
+ */ async maybeSettle() {
277
+ if (!this.running) {
278
+ return;
279
+ }
280
+ try {
281
+ await this.prove();
282
+ } catch (err) {
283
+ this.log.warn('Automine auto-settle tick failed', {
284
+ err: err instanceof Error ? err.message : String(err)
285
+ });
286
+ }
287
+ }
288
+ /**
289
+ * Advances the injected date provider to the latest *mined* L1 timestamp when it has fallen behind
290
+ * (e.g. an unrelated L1 tx mined a block between our builds). Never advances to the pending, un-mined
291
+ * timestamp. Keeps node-side consumers of `dateProvider.now()` aligned with L1 without our own builds.
292
+ */ async reconcileDateProvider() {
293
+ const lastTsMs = await this.deps.ethCheatCodes.lastBlockTimestamp() * 1000;
294
+ if (lastTsMs > this.deps.dateProvider.now()) {
295
+ this.deps.dateProvider.setTime(lastTsMs);
296
+ }
297
+ }
298
+ /** Called from the mempool poller. Enqueues a build if there are pending txs. */ async maybeEnqueueBuild() {
299
+ if (!this.running || this.paused || this.buildQueued) {
300
+ return;
301
+ }
302
+ try {
303
+ const pending = await this.deps.p2pClient.getPendingTxCount();
304
+ if (pending > 0) {
305
+ // Fire-and-forget; the build result is delivered via `buildIfPending()` callers,
306
+ // not via the poller.
307
+ void this.buildIfPending().catch((err)=>{
308
+ this.log.error('Mempool-driven build failed', err);
309
+ });
310
+ }
311
+ } catch (err) {
312
+ this.log.warn('Failed to poll mempool', {
313
+ err: err instanceof Error ? err.message : String(err)
314
+ });
315
+ }
316
+ }
317
+ /**
318
+ * Builds and publishes one checkpoint, returning the built block — or `undefined` when there was
319
+ * nothing to build or the propose failed. A failed propose mines no checkpoint on L1 (it reverts
320
+ * inside the multicall or is never sent), so recovery is purely local: the optimistic archiver insert
321
+ * is rolled back, the block's txs return to the pending pool, and the L1 nonce is reset. No L1 reorg
322
+ * is performed, and the build is not retried inline — once the txs are back in the pending pool the
323
+ * mempool poller re-enqueues a build on its next tick (see {@link maybeEnqueueBuild}).
324
+ */ async runBuild({ allowEmpty }) {
325
+ const env = {
326
+ stack: [],
327
+ error: void 0,
328
+ hasError: false
329
+ };
330
+ try {
331
+ if (!this.running || !this.publisher || !this.attestorAddress) {
332
+ return undefined;
333
+ }
334
+ await this.reconcileDateProvider();
335
+ const txCount = await this.deps.p2pClient.getPendingTxCount();
336
+ // For mempool-driven builds, wait for at least `minTxsPerBlock` pending txs (or 1 if not set)
337
+ // before building. This mirrors the production sequencer's `waitForMinTxs` behavior, and is
338
+ // required for tests that bundle multiple txs into one block via `setConfig({ minTxsPerBlock })`.
339
+ // Explicit empty-block / warp paths pass `allowEmpty: true` and bypass this gate.
340
+ const minRequired = allowEmpty ? 0 : Math.max(this.deps.config.minTxsPerBlock ?? 1, 1);
341
+ if (txCount < minRequired) {
342
+ return undefined;
343
+ }
344
+ // Decide target slot from the pending block's timestamp — picks up any prior
345
+ // `setNextBlockTimestamp` call (e.g. queued by runWarp) instead of assuming +1 over
346
+ // the last mined block.
347
+ const pendingBlockTs = await this.deps.ethCheatCodes.nextBlockTimestamp();
348
+ let targetSlot = Number(getSlotAtTimestamp(BigInt(pendingBlockTs), this.deps.l1Constants));
349
+ if (targetSlot <= this.lastBuiltSlot) {
350
+ // Pending block doesn't reach a new slot yet; advance to the next slot we own.
351
+ targetSlot = this.lastBuiltSlot + 1;
352
+ }
353
+ const slotBoundaryTs = Number(getTimestampForSlot(SlotNumber(targetSlot), this.deps.l1Constants));
354
+ // Pre-set anvil's next block timestamp only if the slot boundary is past what's already
355
+ // scheduled. setNextBlockTimestamp rejects values not strictly greater than the last block's
356
+ // timestamp, and pendingBlockTs is always > lastBlockTimestamp, so this guard is sufficient.
357
+ if (slotBoundaryTs > pendingBlockTs) {
358
+ await this.deps.ethCheatCodes.setNextBlockTimestamp(slotBoundaryTs);
359
+ }
360
+ const tips = await this.deps.l2BlockSource.getL2Tips();
361
+ const syncedToBlockNumber = tips.proposed.number;
362
+ // Ensure world state has processed the archiver's tip before forking. Without this,
363
+ // world state may still be at the previous block (since it syncs asynchronously from
364
+ // the archiver), and `fork(syncedToBlockNumber)` would fail with
365
+ // "Unable to initialize from future block".
366
+ await this.deps.worldState.syncImmediate(BlockNumber(syncedToBlockNumber));
367
+ const nextBlockNumber = BlockNumber(syncedToBlockNumber + 1);
368
+ const checkpointNumber = CheckpointNumber(tips.proposedCheckpoint.checkpoint.number + 1);
369
+ const targetEpoch = getEpochAtSlot(SlotNumber(targetSlot), this.deps.l1Constants);
370
+ this.log.verbose(`Building automine checkpoint`, {
371
+ checkpointNumber,
372
+ blockNumber: nextBlockNumber,
373
+ slot: targetSlot,
374
+ slotTimestamp: slotBoundaryTs,
375
+ txCount,
376
+ allowEmpty
377
+ });
378
+ const checkpointGlobals = await this.deps.globalsBuilder.buildCheckpointGlobalVariables(this.deps.coinbase, this.deps.feeRecipient, SlotNumber(targetSlot));
379
+ const l1ToL2Messages = await this.deps.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
380
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
381
+ blockSource: this.deps.l2BlockSource,
382
+ epoch: targetEpoch,
383
+ checkpointNumber,
384
+ l1Constants: this.deps.l1Constants,
385
+ pipeliningEnabled: false,
386
+ log: this.log
387
+ });
388
+ const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier();
389
+ const fork = _ts_add_disposable_resource(env, await this.deps.worldState.fork(syncedToBlockNumber, {
390
+ closeDelayMs: 0
391
+ }), true);
392
+ const checkpointBuilder = await this.deps.checkpointsBuilder.startCheckpoint(checkpointNumber, checkpointGlobals, feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, this.log.getBindings());
393
+ // Block building only executes txs, and automine publishes straight to L1, so the proofs are never needed.
394
+ const pendingTxs = this.deps.p2pClient.iterateEligiblePendingTxs({
395
+ includeProof: false
396
+ });
397
+ const buildResult = await this.tryBuildBlock(checkpointBuilder, pendingTxs, nextBlockNumber, checkpointGlobals.timestamp, allowEmpty, checkpointNumber);
398
+ if (!buildResult) {
399
+ return undefined;
400
+ }
401
+ const checkpoint = await checkpointBuilder.completeCheckpoint();
402
+ // Empty CommitteeAttestationsAndSigners is accepted on-chain when committee size is 0.
403
+ const emptyAttestations = CommitteeAttestationsAndSigners.empty(this.deps.signatureContext);
404
+ const emptyAttestationsSignature = Signature.empty();
405
+ // Push the block and proposed checkpoint into the archiver locally BEFORE publishing to L1.
406
+ // This avoids racing the archiver's L1 polling: if the L1 publish happened first, polling
407
+ // could surface the checkpoint and reject our subsequent local push as duplicate. Pushing
408
+ // first means the archiver already has the proposed entry when L1 polling fires; the L1
409
+ // sync path then promotes the existing proposed checkpoint via promoteProposedToCheckpointed
410
+ // rather than re-adding it.
411
+ await this.deps.archiver.addBlock(buildResult.block);
412
+ await this.deps.archiver.addProposedCheckpoint({
413
+ header: checkpoint.header,
414
+ checkpointNumber,
415
+ startBlock: BlockNumber(buildResult.block.number),
416
+ blockCount: 1,
417
+ totalManaUsed: checkpoint.header.totalManaUsed.toBigInt(),
418
+ feeAssetPriceModifier
419
+ });
420
+ await this.publisher.enqueueProposeCheckpoint(checkpoint, emptyAttestations, emptyAttestationsSignature);
421
+ // Automine publishes synchronously in the current slot via `sendRequests`. It must NOT use the
422
+ // production `sendRequestsAt` (or `canProposeAt`), which always apply the one-slot pipelining
423
+ // offset — automine is the deliberate non-pipelined exception and builds/publishes in place.
424
+ const result = await this.publisher.sendRequests(SlotNumber(targetSlot));
425
+ const proposeSucceeded = !!result?.successfulActions?.some((action)=>action === 'propose');
426
+ if (!proposeSucceeded) {
427
+ this.log.warn('Automine propose did not succeed; rolled back optimistic insert, will rebuild from the poller', {
428
+ slot: targetSlot,
429
+ checkpointNumber,
430
+ successful: result?.successfulActions,
431
+ failed: result?.failedActions
432
+ });
433
+ await this.rollbackOptimisticInsert(syncedToBlockNumber);
434
+ return undefined;
435
+ }
436
+ // Force one full L1-sync cycle synchronously. The local addBlock/addProposedCheckpoint
437
+ // above advances the proposed tip, but tips.checkpointed and the L1->L2 inbox tree state
438
+ // only advance when the archiver observes the L1-confirmed checkpoint via its sync loop.
439
+ await this.deps.archiver.syncImmediate();
440
+ // Sync the date provider to the L1 block timestamp we just mined.
441
+ const newL1Ts = await this.deps.ethCheatCodes.lastBlockTimestamp();
442
+ this.deps.dateProvider.setTime(newL1Ts * 1000);
443
+ // A successful propose is validated on-chain against the mined L1 block's slot, so the mined slot
444
+ // should equal our target; warn (without rolling back — the checkpoint is on L1) if it ever differs.
445
+ const minedSlot = Number(getSlotAtTimestamp(BigInt(newL1Ts), this.deps.l1Constants));
446
+ if (minedSlot !== targetSlot) {
447
+ this.log.warn(`Automine checkpoint mined in slot ${minedSlot} but targeted ${targetSlot}`, {
448
+ minedSlot,
449
+ targetSlot,
450
+ checkpointNumber
451
+ });
452
+ }
453
+ this.lastBuiltSlot = targetSlot;
454
+ this.log.verbose(`Automine checkpoint published`, {
455
+ checkpointNumber,
456
+ blockNumber: nextBlockNumber,
457
+ slot: targetSlot,
458
+ l1Timestamp: newL1Ts,
459
+ txCount: buildResult.numTxs
460
+ });
461
+ return buildResult.block;
462
+ } catch (e) {
463
+ env.error = e;
464
+ env.hasError = true;
465
+ } finally{
466
+ const result = _ts_dispose_resources(env);
467
+ if (result) await result;
468
+ }
469
+ }
470
+ /**
471
+ * Undoes an optimistic archiver insert (uncheckpointed block + proposed checkpoint) without reorging
472
+ * L1: removes the uncheckpointed block and evicts the proposed checkpoint that referenced it, so the
473
+ * proposed tip drops back to `toBlockNumber`. `p2pClient.sync()` then observes the lowered tip and
474
+ * restores the block's txs to the pending pool; `worldState.syncImmediate()` drops any applied effects;
475
+ * and the L1 nonce is reset (a reverted-but-mined propose consumes one) so the build can be retried.
476
+ *
477
+ * Note: `archiver.rollbackTo` is NOT usable here — it is checkpoint-granular and no-ops on a
478
+ * proposed-only tip (the inserted checkpoint is not yet in the checkpointed set).
479
+ */ async rollbackOptimisticInsert(toBlockNumber) {
480
+ await this.deps.archiver.removeUncheckpointedBlocksAfter(toBlockNumber);
481
+ await this.deps.p2pClient.sync();
482
+ await this.deps.worldState.syncImmediate();
483
+ this.deps.l1TxUtils.forEach((utils)=>utils.resetNonce());
484
+ }
485
+ /**
486
+ * Warps L1 timestamp to (or past) `targetTimestampSec`, rounded up to the next aztec-slot
487
+ * boundary, by queuing an empty-checkpoint build at that slot. Mines exactly one L1 block
488
+ * (the propose tx auto-mined under anvil's automine mode), with the timestamp pre-set so
489
+ * the mined block lands on the slot boundary.
490
+ */ async runWarp(targetTimestampSec) {
491
+ await this.reconcileDateProvider();
492
+ const currentL1Ts = await this.deps.ethCheatCodes.lastBlockTimestamp();
493
+ if (targetTimestampSec <= currentL1Ts) {
494
+ this.log.debug(`Warp target ${targetTimestampSec} is not in the future of current L1 ts ${currentL1Ts}`);
495
+ return;
496
+ }
497
+ // Round up to the next aztec-slot boundary so the next build naturally lands on a new slot.
498
+ const targetSlot = Number(getSlotAtTimestamp(BigInt(targetTimestampSec), this.deps.l1Constants));
499
+ const slotBoundaryTs = Number(getTimestampForSlot(SlotNumber(targetSlot + 1), this.deps.l1Constants));
500
+ // Queue the next L1 block at the slot boundary timestamp, then build (and publish) an
501
+ // empty L2 checkpoint. The propose tx auto-mines a single L1 block at slotBoundaryTs,
502
+ // and `runBuild` syncs the date provider to the new L1 timestamp.
503
+ await this.deps.ethCheatCodes.setNextBlockTimestamp(slotBoundaryTs);
504
+ await this.runBuild({
505
+ allowEmpty: true
506
+ });
507
+ this.log.verbose(`Warped L1 to slot boundary`, {
508
+ slot: targetSlot + 1,
509
+ timestamp: slotBoundaryTs
510
+ });
511
+ }
512
+ /**
513
+ * Rolls L1 back to the block that published `targetCheckpoint`, drops the archiver's
514
+ * in-memory state to match, and resets internal slot bookkeeping.
515
+ */ async runRevert(targetCheckpoint) {
516
+ const checkpointData = await this.deps.l2BlockSource.getCheckpointData({
517
+ number: CheckpointNumber(targetCheckpoint)
518
+ });
519
+ if (!checkpointData) {
520
+ throw new Error(`AutomineSequencer: checkpoint ${targetCheckpoint} not found in archiver`);
521
+ }
522
+ const targetL1Block = Number(checkpointData.l1.blockNumber);
523
+ this.log.verbose(`Reverting to checkpoint ${targetCheckpoint}`, {
524
+ targetCheckpoint,
525
+ targetL1Block,
526
+ checkpointSlot: checkpointData.header.slotNumber
527
+ });
528
+ // Roll the archiver back to the last block of targetCheckpoint before the L1 reorg,
529
+ // since the archiver needs to fetch the target checkpoint's L1 block hash during rollback.
530
+ const lastBlockInCheckpoint = BlockNumber(checkpointData.startBlock + checkpointData.blockCount - 1);
531
+ await this.deps.archiver.rollbackTo(lastBlockInCheckpoint);
532
+ // Force the P2P block stream to run one cycle immediately so it processes the
533
+ // chain-pruned event triggered by the archiver rollback above. Without this, the
534
+ // P2P pool may not have restored rolled-back txs to pending by the time the next
535
+ // build runs.
536
+ await this.deps.p2pClient.sync();
537
+ // Force world-state to process the archiver's prune event immediately, so the next build
538
+ // doesn't try to insert nullifiers that were already in the pruned checkpoints.
539
+ await this.deps.worldState.syncImmediate();
540
+ // Remove all L1 blocks strictly after the target checkpoint's publish block so that
541
+ // the propose txs for later checkpoints are gone from L1. We use reorg(depth) directly
542
+ // to keep targetL1Block itself as the new chain tip.
543
+ const currentL1Block = await this.deps.ethCheatCodes.publicClient.getBlockNumber();
544
+ const depth = Number(currentL1Block) - targetL1Block;
545
+ if (depth > 0) {
546
+ await this.deps.ethCheatCodes.reorg(depth);
547
+ }
548
+ // anvil_rollback re-queues the rolled-back txs into the mempool. Clear them so they
549
+ // don't get re-mined, then reset the publisher nonce tracker so the next propose tx
550
+ // uses the correct nonce for the post-reorg chain state.
551
+ await this.deps.ethCheatCodes.rpcCall('anvil_dropAllTransactions', []);
552
+ this.deps.l1TxUtils.forEach((utils)=>utils.resetNonce());
553
+ // Reset slot bookkeeping so the next build picks up at the correct slot.
554
+ this.lastBuiltSlot = Number(checkpointData.header.slotNumber);
555
+ this.log.verbose(`Reverted to checkpoint ${targetCheckpoint}`, {
556
+ targetCheckpoint,
557
+ targetL1Block
558
+ });
559
+ }
560
+ /**
561
+ * Writes outbox roots for every epoch newly covered up to `maybeCheckpoint` and advances the proven
562
+ * tip. Settles each fully-covered epoch in full and the final epoch only up to the target checkpoint
563
+ * (a partial epoch, which the AZIP-14 Outbox supports via per-`numCheckpointsInEpoch` roots).
564
+ */ async runProve(upToCheckpoint) {
565
+ await this.reconcileDateProvider();
566
+ const rollupCheatCodes = this.getRollupCheatCodes();
567
+ const tips = await this.deps.l2BlockSource.getL2Tips();
568
+ const checkpointedTip = tips.checkpointed.checkpoint.number;
569
+ // Never prove beyond what the archiver has actually checkpointed; default to that tip.
570
+ const target = CheckpointNumber(Math.min(upToCheckpoint ?? checkpointedTip, checkpointedTip));
571
+ const { proven } = await rollupCheatCodes.getTips();
572
+ if (target <= proven) {
573
+ this.log.debug(`Checkpoint ${target} already proven`, {
574
+ target,
575
+ proven,
576
+ checkpointedTip
577
+ });
578
+ return proven;
579
+ }
580
+ const startEpoch = await this.getEpochOfCheckpoint(CheckpointNumber(proven + 1));
581
+ const endEpoch = await this.getEpochOfCheckpoint(target);
582
+ if (startEpoch === undefined || endEpoch === undefined) {
583
+ this.log.warn(`Cannot resolve epoch range to prove up to checkpoint ${target}`, {
584
+ target,
585
+ proven,
586
+ startEpoch,
587
+ endEpoch
588
+ });
589
+ return proven;
590
+ }
591
+ for(let epoch = startEpoch; epoch <= endEpoch; epoch++){
592
+ const lastCovered = await settleEpochOutbox({
593
+ rollupCheatCodes,
594
+ l2BlockSource: this.deps.l2BlockSource,
595
+ epoch: EpochNumber(epoch),
596
+ maxCheckpoint: epoch === endEpoch ? target : undefined,
597
+ log: this.log
598
+ });
599
+ if (lastCovered === undefined) {
600
+ // An epoch in (proven, target] with no checkpointed blocks — expected when warps skip a whole
601
+ // epoch. Logged so it's distinguishable from the archiver failing to serve the epoch's blocks.
602
+ this.log.debug(`No checkpointed blocks to settle for epoch ${epoch} while proving to ${target}`, {
603
+ epoch,
604
+ target
605
+ });
606
+ }
607
+ }
608
+ await rollupCheatCodes.markAsProven(target);
609
+ // Settlement is a direct L1 storage write that mines no block, unlike a real epoch proof landing
610
+ // on L1. The archiver's L1 sync short-circuits while the L1 block hash is unchanged, so it would
611
+ // never re-read the proven tip until the next build/warp mines a block. Mine one empty L1 block so
612
+ // the block hash advances, then force an immediate sync that observes the new proven checkpoint.
613
+ await this.deps.ethCheatCodes.mineEmptyBlock();
614
+ await this.deps.archiver.syncImmediate();
615
+ this.log.verbose(`Proved up to checkpoint ${target}`, {
616
+ target,
617
+ proven,
618
+ startEpoch,
619
+ endEpoch
620
+ });
621
+ return target;
622
+ }
623
+ /** Resolves the epoch a checkpoint belongs to from its slot, or undefined if the archiver lacks it. */ async getEpochOfCheckpoint(checkpointNumber) {
624
+ const checkpointData = await this.deps.l2BlockSource.getCheckpointData({
625
+ number: checkpointNumber
626
+ });
627
+ if (!checkpointData) {
628
+ return undefined;
629
+ }
630
+ const slot = SlotNumber(Number(checkpointData.header.slotNumber));
631
+ return Number(getEpochAtSlot(slot, this.deps.l1Constants));
632
+ }
633
+ /**
634
+ * Wraps `checkpointBuilder.buildBlock` with the failed-tx handling shared by both error
635
+ * and success paths: drops the failed txs from the P2P mempool, and returns `undefined`
636
+ * when `InsufficientValidTxsError` aborts the build (so the caller skips publishing).
637
+ */ async tryBuildBlock(checkpointBuilder, pendingTxs, nextBlockNumber, timestamp, allowEmpty, checkpointNumber) {
638
+ let buildResult;
639
+ try {
640
+ buildResult = await checkpointBuilder.buildBlock(pendingTxs, nextBlockNumber, timestamp, {
641
+ maxTransactions: this.deps.config.maxTxsPerBlock,
642
+ // Allow empty for explicit-empty builds; require at least 1 valid tx otherwise.
643
+ minValidTxs: allowEmpty ? 0 : 1,
644
+ isBuildingProposal: true,
645
+ maxBlocksPerCheckpoint: 1,
646
+ perBlockAllocationMultiplier: 1
647
+ });
648
+ } catch (err) {
649
+ // Mirrors production's checkpoint_proposal_job: if every pending tx failed execution and
650
+ // we didn't reach minValidTxs, drop the failed txs from the mempool so they don't block
651
+ // the poller forever, then abort this build with no checkpoint published.
652
+ if (isErrorClass(err, InsufficientValidTxsError)) {
653
+ await this.dropFailedTxsFromP2P(err.failedTxs);
654
+ this.log.verbose(`AutomineSequencer: insufficient valid txs, skipping build`, {
655
+ checkpointNumber,
656
+ processedCount: err.processedCount,
657
+ minRequired: err.minRequired,
658
+ failedCount: err.failedTxs.length
659
+ });
660
+ return undefined;
661
+ }
662
+ throw err;
663
+ }
664
+ // Drop any txs that failed execution but didn't trigger InsufficientValidTxsError, so we
665
+ // don't re-pick them up on the next build.
666
+ await this.dropFailedTxsFromP2P(buildResult.failedTxs);
667
+ return buildResult;
668
+ }
669
+ /** Removes txs that failed execution from the P2P mempool so they don't get retried. */ async dropFailedTxsFromP2P(failedTxs) {
670
+ if (failedTxs.length === 0) {
671
+ return;
672
+ }
673
+ const failedTxHashes = failedTxs.map((fail)=>fail.tx.getTxHash());
674
+ this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
675
+ await this.deps.p2pClient.handleFailedExecution(failedTxHashes);
676
+ }
677
+ }