@aztec-labs/sequencer-client 6.0.0-nightly.20260829

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 (165) hide show
  1. package/README.md +307 -0
  2. package/dest/client/index.d.ts +2 -0
  3. package/dest/client/index.d.ts.map +1 -0
  4. package/dest/client/index.js +1 -0
  5. package/dest/client/sequencer-client.d.ts +94 -0
  6. package/dest/client/sequencer-client.d.ts.map +1 -0
  7. package/dest/client/sequencer-client.js +177 -0
  8. package/dest/config.d.ts +56 -0
  9. package/dest/config.d.ts.map +1 -0
  10. package/dest/config.js +251 -0
  11. package/dest/global_variable_builder/fee_predictor.d.ts +49 -0
  12. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  13. package/dest/global_variable_builder/fee_predictor.js +127 -0
  14. package/dest/global_variable_builder/fee_provider.d.ts +28 -0
  15. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  16. package/dest/global_variable_builder/fee_provider.js +87 -0
  17. package/dest/global_variable_builder/global_builder.d.ts +28 -0
  18. package/dest/global_variable_builder/global_builder.d.ts.map +1 -0
  19. package/dest/global_variable_builder/global_builder.js +40 -0
  20. package/dest/global_variable_builder/index.d.ts +4 -0
  21. package/dest/global_variable_builder/index.d.ts.map +1 -0
  22. package/dest/global_variable_builder/index.js +3 -0
  23. package/dest/index.d.ts +7 -0
  24. package/dest/index.d.ts.map +1 -0
  25. package/dest/index.js +8 -0
  26. package/dest/publisher/config.d.ts +68 -0
  27. package/dest/publisher/config.d.ts.map +1 -0
  28. package/dest/publisher/config.js +137 -0
  29. package/dest/publisher/index.d.ts +5 -0
  30. package/dest/publisher/index.d.ts.map +1 -0
  31. package/dest/publisher/index.js +4 -0
  32. package/dest/publisher/l1_to_l2_messaging.d.ts +21 -0
  33. package/dest/publisher/l1_to_l2_messaging.d.ts.map +1 -0
  34. package/dest/publisher/l1_to_l2_messaging.js +70 -0
  35. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  36. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  37. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  38. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +101 -0
  39. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  40. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +68 -0
  41. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  42. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  43. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +36 -0
  44. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  45. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  46. package/dest/publisher/l1_tx_failed_store/index.js +3 -0
  47. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  48. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  49. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  50. package/dest/publisher/sequencer-publisher-factory.d.ts +50 -0
  51. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -0
  52. package/dest/publisher/sequencer-publisher-factory.js +75 -0
  53. package/dest/publisher/sequencer-publisher-metrics.d.ts +26 -0
  54. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -0
  55. package/dest/publisher/sequencer-publisher-metrics.js +101 -0
  56. package/dest/publisher/sequencer-publisher.d.ts +254 -0
  57. package/dest/publisher/sequencer-publisher.d.ts.map +1 -0
  58. package/dest/publisher/sequencer-publisher.js +1784 -0
  59. package/dest/publisher/write_json.d.ts +11 -0
  60. package/dest/publisher/write_json.d.ts.map +1 -0
  61. package/dest/publisher/write_json.js +57 -0
  62. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  63. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  64. package/dest/sequencer/automine/automine_factory.js +85 -0
  65. package/dest/sequencer/automine/automine_sequencer.d.ts +189 -0
  66. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  67. package/dest/sequencer/automine/automine_sequencer.js +732 -0
  68. package/dest/sequencer/automine/index.d.ts +3 -0
  69. package/dest/sequencer/automine/index.d.ts.map +1 -0
  70. package/dest/sequencer/automine/index.js +2 -0
  71. package/dest/sequencer/checkpoint_proposal_job.d.ts +169 -0
  72. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
  73. package/dest/sequencer/checkpoint_proposal_job.js +1961 -0
  74. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  75. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  76. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  77. package/dest/sequencer/checkpoint_voter.d.ts +34 -0
  78. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -0
  79. package/dest/sequencer/checkpoint_voter.js +106 -0
  80. package/dest/sequencer/config.d.ts +8 -0
  81. package/dest/sequencer/config.d.ts.map +1 -0
  82. package/dest/sequencer/config.js +1 -0
  83. package/dest/sequencer/errors.d.ts +11 -0
  84. package/dest/sequencer/errors.d.ts.map +1 -0
  85. package/dest/sequencer/errors.js +15 -0
  86. package/dest/sequencer/events.d.ts +103 -0
  87. package/dest/sequencer/events.d.ts.map +1 -0
  88. package/dest/sequencer/events.js +1 -0
  89. package/dest/sequencer/inbox_bucket_selector.d.ts +88 -0
  90. package/dest/sequencer/inbox_bucket_selector.d.ts.map +1 -0
  91. package/dest/sequencer/inbox_bucket_selector.js +80 -0
  92. package/dest/sequencer/index.d.ts +6 -0
  93. package/dest/sequencer/index.d.ts.map +1 -0
  94. package/dest/sequencer/index.js +5 -0
  95. package/dest/sequencer/metrics.d.ts +75 -0
  96. package/dest/sequencer/metrics.d.ts.map +1 -0
  97. package/dest/sequencer/metrics.js +343 -0
  98. package/dest/sequencer/missing_committee.d.ts +72 -0
  99. package/dest/sequencer/missing_committee.d.ts.map +1 -0
  100. package/dest/sequencer/missing_committee.js +139 -0
  101. package/dest/sequencer/requests_tracker.d.ts +22 -0
  102. package/dest/sequencer/requests_tracker.d.ts.map +1 -0
  103. package/dest/sequencer/requests_tracker.js +33 -0
  104. package/dest/sequencer/sequencer.d.ts +326 -0
  105. package/dest/sequencer/sequencer.d.ts.map +1 -0
  106. package/dest/sequencer/sequencer.js +1495 -0
  107. package/dest/sequencer/types.d.ts +3 -0
  108. package/dest/sequencer/types.d.ts.map +1 -0
  109. package/dest/sequencer/types.js +1 -0
  110. package/dest/sequencer/utils.d.ts +30 -0
  111. package/dest/sequencer/utils.d.ts.map +1 -0
  112. package/dest/sequencer/utils.js +18 -0
  113. package/dest/test/index.d.ts +23 -0
  114. package/dest/test/index.d.ts.map +1 -0
  115. package/dest/test/index.js +6 -0
  116. package/dest/test/mock_checkpoint_builder.d.ts +95 -0
  117. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -0
  118. package/dest/test/mock_checkpoint_builder.js +230 -0
  119. package/dest/test/utils.d.ts +67 -0
  120. package/dest/test/utils.d.ts.map +1 -0
  121. package/dest/test/utils.js +121 -0
  122. package/package.json +118 -0
  123. package/src/client/index.ts +1 -0
  124. package/src/client/sequencer-client.ts +281 -0
  125. package/src/config.ts +309 -0
  126. package/src/global_variable_builder/README.md +44 -0
  127. package/src/global_variable_builder/fee_predictor.ts +176 -0
  128. package/src/global_variable_builder/fee_provider.ts +104 -0
  129. package/src/global_variable_builder/global_builder.ts +68 -0
  130. package/src/global_variable_builder/index.ts +3 -0
  131. package/src/index.ts +15 -0
  132. package/src/publisher/config.ts +220 -0
  133. package/src/publisher/index.ts +8 -0
  134. package/src/publisher/l1_to_l2_messaging.ts +85 -0
  135. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  136. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +166 -0
  137. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +47 -0
  138. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  139. package/src/publisher/sequencer-bundle-simulator.ts +253 -0
  140. package/src/publisher/sequencer-publisher-factory.ts +121 -0
  141. package/src/publisher/sequencer-publisher-metrics.ts +145 -0
  142. package/src/publisher/sequencer-publisher.ts +1719 -0
  143. package/src/publisher/write_json.ts +77 -0
  144. package/src/sequencer/README.md +243 -0
  145. package/src/sequencer/automine/README.md +60 -0
  146. package/src/sequencer/automine/automine_factory.ts +156 -0
  147. package/src/sequencer/automine/automine_sequencer.ts +841 -0
  148. package/src/sequencer/automine/index.ts +6 -0
  149. package/src/sequencer/checkpoint_proposal_job.ts +1889 -0
  150. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  151. package/src/sequencer/checkpoint_voter.ts +118 -0
  152. package/src/sequencer/config.ts +9 -0
  153. package/src/sequencer/errors.ts +21 -0
  154. package/src/sequencer/events.ts +93 -0
  155. package/src/sequencer/inbox_bucket_selector.ts +160 -0
  156. package/src/sequencer/index.ts +5 -0
  157. package/src/sequencer/metrics.ts +463 -0
  158. package/src/sequencer/missing_committee.ts +192 -0
  159. package/src/sequencer/requests_tracker.ts +43 -0
  160. package/src/sequencer/sequencer.ts +1401 -0
  161. package/src/sequencer/types.ts +6 -0
  162. package/src/sequencer/utils.ts +42 -0
  163. package/src/test/index.ts +26 -0
  164. package/src/test/mock_checkpoint_builder.ts +324 -0
  165. package/src/test/utils.ts +215 -0
@@ -0,0 +1,128 @@
1
+ import {
2
+ Attributes,
3
+ type Gauge,
4
+ type Histogram,
5
+ type Meter,
6
+ Metrics,
7
+ type TelemetryClient,
8
+ } from '@aztec-labs/telemetry-client';
9
+
10
+ type CheckpointProposalJobInstruments = {
11
+ checkpointAttestationDelay: Histogram;
12
+ checkpointBuildDuration: Histogram;
13
+ checkpointStartToFirstBlockDuration: Histogram;
14
+ checkpointLastBlockToBroadcastDuration: Histogram;
15
+ pipelinedCheckpointBuildStartOffsetFromSlotBoundary: Histogram;
16
+ checkpointBlockCount: Gauge;
17
+ checkpointTxCount: Gauge;
18
+ checkpointTotalMana: Gauge;
19
+ };
20
+
21
+ /**
22
+ * Per-job recording surface used by {@link CheckpointProposalJob}.
23
+ *
24
+ * Ownership split:
25
+ * - {@link CheckpointProposalJobMetrics} owns the OpenTelemetry meter and instruments and should live for the
26
+ * lifetime of the sequencer process.
27
+ * - A recorder owns only mutable timing state for one checkpoint proposal job so overlapping jobs cannot
28
+ * overwrite each other's timing markers.
29
+ */
30
+ export interface CheckpointProposalJobMetricsRecorder {
31
+ recordCheckpointAttestationDelay(durationMs: number): void;
32
+ recordCheckpointBuild(durationMs: number, blockCount: number, txCount: number, totalMana: number): void;
33
+ recordPipelinedCheckpointBuildStartOffsetFromSlotBoundary(offsetMs: number): void;
34
+ startCheckpointTiming(nowMs: number): void;
35
+ noteCheckpointBlockBuilt(nowMs: number, opts: { isFirstBlock: boolean; isLastBlock: boolean }): void;
36
+ noteCheckpointBroadcast(nowMs: number): void;
37
+ }
38
+
39
+ /**
40
+ * Concrete per-job recorder.
41
+ *
42
+ * This class should be short-lived: create one recorder per checkpoint proposal job and discard it when the job
43
+ * completes. It intentionally does not create instruments; it only holds the job-local timestamps needed to derive
44
+ * timing metrics safely.
45
+ */
46
+ class CheckpointProposalJobMetricsRecorderImpl implements CheckpointProposalJobMetricsRecorder {
47
+ private checkpointStartedAt?: number;
48
+ private checkpointLastBlockBuiltAt?: number;
49
+
50
+ constructor(private readonly instruments: CheckpointProposalJobInstruments) {}
51
+
52
+ public recordCheckpointAttestationDelay(durationMs: number) {
53
+ this.instruments.checkpointAttestationDelay.record(Math.ceil(durationMs));
54
+ }
55
+
56
+ public recordCheckpointBuild(durationMs: number, blockCount: number, txCount: number, totalMana: number) {
57
+ this.instruments.checkpointBuildDuration.record(Math.ceil(durationMs));
58
+ this.instruments.checkpointBlockCount.record(blockCount);
59
+ this.instruments.checkpointTxCount.record(txCount);
60
+ this.instruments.checkpointTotalMana.record(totalMana);
61
+ }
62
+
63
+ public recordPipelinedCheckpointBuildStartOffsetFromSlotBoundary(offsetMs: number) {
64
+ this.instruments.pipelinedCheckpointBuildStartOffsetFromSlotBoundary.record(Math.ceil(Math.abs(offsetMs)), {
65
+ [Attributes.SLOT_BOUNDARY_SIDE]: offsetMs < 0 ? 'before' : 'after',
66
+ });
67
+ }
68
+
69
+ public startCheckpointTiming(nowMs: number) {
70
+ this.checkpointStartedAt = nowMs;
71
+ this.checkpointLastBlockBuiltAt = undefined;
72
+ }
73
+
74
+ public noteCheckpointBlockBuilt(nowMs: number, opts: { isFirstBlock: boolean; isLastBlock: boolean }) {
75
+ if (opts.isFirstBlock && this.checkpointStartedAt !== undefined) {
76
+ this.instruments.checkpointStartToFirstBlockDuration.record(Math.ceil(nowMs - this.checkpointStartedAt));
77
+ }
78
+
79
+ if (opts.isLastBlock) {
80
+ this.checkpointLastBlockBuiltAt = nowMs;
81
+ }
82
+ }
83
+
84
+ public noteCheckpointBroadcast(nowMs: number) {
85
+ if (this.checkpointLastBlockBuiltAt !== undefined) {
86
+ this.instruments.checkpointLastBlockToBroadcastDuration.record(
87
+ Math.ceil(nowMs - this.checkpointLastBlockBuiltAt),
88
+ );
89
+ }
90
+
91
+ this.checkpointLastBlockBuiltAt = undefined;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Long-lived owner of checkpoint proposal job telemetry instruments.
97
+ *
98
+ * The sequencer should construct this once and reuse it across jobs. Each call to {@link createRecorder} returns a
99
+ * lightweight recorder with isolated mutable state for a single checkpoint proposal job.
100
+ */
101
+ export class CheckpointProposalJobMetrics {
102
+ private readonly meter: Meter;
103
+ private readonly instruments: CheckpointProposalJobInstruments;
104
+
105
+ constructor(client: TelemetryClient, name = 'CheckpointProposalJob') {
106
+ this.meter = client.getMeter(name);
107
+ this.instruments = {
108
+ checkpointAttestationDelay: this.meter.createHistogram(Metrics.SEQUENCER_CHECKPOINT_ATTESTATION_DELAY),
109
+ checkpointBuildDuration: this.meter.createHistogram(Metrics.SEQUENCER_CHECKPOINT_BUILD_DURATION),
110
+ checkpointStartToFirstBlockDuration: this.meter.createHistogram(
111
+ Metrics.SEQUENCER_CHECKPOINT_START_TO_FIRST_BLOCK_DURATION,
112
+ ),
113
+ checkpointLastBlockToBroadcastDuration: this.meter.createHistogram(
114
+ Metrics.SEQUENCER_CHECKPOINT_LAST_BLOCK_TO_BROADCAST_DURATION,
115
+ ),
116
+ pipelinedCheckpointBuildStartOffsetFromSlotBoundary: this.meter.createHistogram(
117
+ Metrics.SEQUENCER_PIPELINED_CHECKPOINT_BUILD_START_OFFSET_FROM_SLOT_BOUNDARY,
118
+ ),
119
+ checkpointBlockCount: this.meter.createGauge(Metrics.SEQUENCER_CHECKPOINT_BLOCK_COUNT),
120
+ checkpointTxCount: this.meter.createGauge(Metrics.SEQUENCER_CHECKPOINT_TX_COUNT),
121
+ checkpointTotalMana: this.meter.createGauge(Metrics.SEQUENCER_CHECKPOINT_TOTAL_MANA),
122
+ };
123
+ }
124
+
125
+ public createRecorder(): CheckpointProposalJobMetricsRecorder {
126
+ return new CheckpointProposalJobMetricsRecorderImpl(this.instruments);
127
+ }
128
+ }
@@ -0,0 +1,118 @@
1
+ import type { SlotNumber } from '@aztec-labs/foundation/branded-types';
2
+ import type { EthAddress } from '@aztec-labs/foundation/eth-address';
3
+ import type { Logger } from '@aztec-labs/foundation/log';
4
+ import type { SlasherClientInterface } from '@aztec-labs/slasher';
5
+ import type { ResolvedSequencerConfig } from '@aztec-labs/stdlib/interfaces/server';
6
+ import type { ValidatorClient } from '@aztec-labs/validator-client';
7
+ import { DutyAlreadySignedError } from '@aztec-labs/validator-ha-signer/errors';
8
+ import { DutyType, type SigningContext } from '@aztec-labs/validator-ha-signer/types';
9
+ import type { TypedDataDefinition } from 'viem';
10
+
11
+ import type { SequencerPublisher } from '../publisher/sequencer-publisher.js';
12
+ import type { SequencerMetrics } from './metrics.js';
13
+ import type { SequencerRollupConstants } from './types.js';
14
+
15
+ /**
16
+ * Handles governance and slashing voting for a given slot.
17
+ */
18
+ export class CheckpointVoter {
19
+ private governanceSigner: (msg: TypedDataDefinition) => Promise<`0x${string}`>;
20
+ private slashingSigner: (msg: TypedDataDefinition) => Promise<`0x${string}`>;
21
+
22
+ constructor(
23
+ private readonly slot: SlotNumber,
24
+ private readonly publisher: SequencerPublisher,
25
+ private readonly attestorAddress: EthAddress,
26
+ private readonly validatorClient: ValidatorClient,
27
+ private readonly slasherClient: SlasherClientInterface | undefined,
28
+ private readonly l1Constants: SequencerRollupConstants,
29
+ private readonly config: ResolvedSequencerConfig,
30
+ private readonly metrics: SequencerMetrics,
31
+ private readonly log: Logger,
32
+ ) {
33
+ // Create separate signers with appropriate duty contexts for governance and slashing votes
34
+ // These use HA protection to ensure only one node signs per slot/duty
35
+ const governanceContext: SigningContext = { slot: this.slot, dutyType: DutyType.GOVERNANCE_VOTE };
36
+ this.governanceSigner = (msg: TypedDataDefinition) =>
37
+ this.validatorClient.signWithAddress(this.attestorAddress, msg, governanceContext).then(s => s.toString());
38
+
39
+ const slashingContext: SigningContext = { slot: this.slot, dutyType: DutyType.SLASHING_VOTE };
40
+ this.slashingSigner = (msg: TypedDataDefinition) =>
41
+ this.validatorClient.signWithAddress(this.attestorAddress, msg, slashingContext).then(s => s.toString());
42
+ }
43
+
44
+ /**
45
+ * Enqueues governance and slashing votes with the publisher.
46
+ * Returns a tuple of promises that resolve to whether each vote was successfully enqueued.
47
+ */
48
+ enqueueVotes(): [Promise<boolean | undefined>, Promise<boolean | undefined>] {
49
+ try {
50
+ const enqueueGovernancePromise = this.enqueueGovernanceVote();
51
+ const enqueueSlashingPromise = this.enqueueSlashingVote();
52
+
53
+ return [enqueueGovernancePromise, enqueueSlashingPromise];
54
+ } catch (err) {
55
+ this.log.error(`Error enqueueing governance and slashing votes`, err);
56
+ return [Promise.resolve(false), Promise.resolve(false)];
57
+ }
58
+ }
59
+
60
+ private async enqueueGovernanceVote(): Promise<boolean | undefined> {
61
+ const governanceProposerPayload = this.config.governanceProposerPayload;
62
+ if (!governanceProposerPayload || governanceProposerPayload.isZero()) {
63
+ return undefined;
64
+ }
65
+
66
+ this.log.info(`Enqueuing vote for ${governanceProposerPayload} governance for slot ${this.slot}`, {
67
+ slot: this.slot,
68
+ governanceProposerPayload: governanceProposerPayload.toString(),
69
+ });
70
+
71
+ try {
72
+ return await this.publisher.enqueueGovernanceCastSignal(
73
+ governanceProposerPayload,
74
+ this.slot,
75
+ this.attestorAddress,
76
+ this.governanceSigner,
77
+ );
78
+ } catch (err) {
79
+ if (err instanceof DutyAlreadySignedError) {
80
+ this.log.info(`Governance vote already signed by another node`, {
81
+ slot: this.slot,
82
+ signedByNode: err.signedByNode,
83
+ });
84
+ } else {
85
+ this.log.error(`Error enqueueing governance vote`, err);
86
+ }
87
+ return false;
88
+ }
89
+ }
90
+
91
+ private async enqueueSlashingVote(): Promise<boolean | undefined> {
92
+ try {
93
+ const actions = await this.slasherClient?.getProposerActions(this.slot);
94
+ if (!actions || actions.length === 0) {
95
+ return undefined;
96
+ }
97
+
98
+ this.log.info(`Enqueuing vote for ${actions.length} slashing actions for slot ${this.slot}`, {
99
+ slot: this.slot,
100
+ actionCount: actions.length,
101
+ });
102
+
103
+ this.metrics.recordSlashingAttempt(actions.length);
104
+
105
+ return await this.publisher.enqueueSlashingActions(actions, this.slot, this.attestorAddress, this.slashingSigner);
106
+ } catch (err) {
107
+ if (err instanceof DutyAlreadySignedError) {
108
+ this.log.info(`Slashing vote already signed by another node`, {
109
+ slot: this.slot,
110
+ signedByNode: err.signedByNode,
111
+ });
112
+ } else {
113
+ this.log.error(`Error enqueueing slashing vote`, err);
114
+ }
115
+ return false;
116
+ }
117
+ }
118
+ }
@@ -0,0 +1,9 @@
1
+ import type { GovernanceProposerContract } from '@aztec-labs/ethereum/contracts';
2
+ import type { RollupContract } from '@aztec-labs/ethereum/contracts/rollup';
3
+
4
+ export { type SequencerConfig } from '@aztec-labs/stdlib/config';
5
+
6
+ export type SequencerContracts = {
7
+ rollupContract: RollupContract;
8
+ governanceProposerContract: GovernanceProposerContract;
9
+ };
@@ -0,0 +1,21 @@
1
+ import type { SequencerState } from './utils.js';
2
+
3
+ export class SequencerTooSlowError extends Error {
4
+ constructor(
5
+ public readonly proposedState: SequencerState,
6
+ public readonly maxAllowedTime: number,
7
+ public readonly currentTime: number,
8
+ ) {
9
+ super(
10
+ `Too far into slot for ${proposedState} (time into slot ${currentTime}s greater than ${maxAllowedTime}s allowance)`,
11
+ );
12
+ this.name = 'SequencerTooSlowError';
13
+ }
14
+ }
15
+
16
+ export class SequencerInterruptedError extends Error {
17
+ constructor() {
18
+ super(`Sequencer was interrupted`);
19
+ this.name = 'SequencerInterruptedError';
20
+ }
21
+ }
@@ -0,0 +1,93 @@
1
+ import type {
2
+ BlockNumber,
3
+ CheckpointNumber,
4
+ IndexWithinCheckpoint,
5
+ SlotNumber,
6
+ } from '@aztec-labs/foundation/branded-types';
7
+ import type { BlockHash } from '@aztec-labs/stdlib/block';
8
+
9
+ import type { Action } from '../publisher/sequencer-publisher.js';
10
+ import type { SequencerState } from './utils.js';
11
+
12
+ export type SequencerEvents = {
13
+ /**
14
+ * Emitted on every sequencer state transition (including no-op transitions to the same state). The
15
+ * timing fields are anchored to the build frame of the slot being proposed for, not to wall-clock
16
+ * slot boundaries, because the proposer builds for `targetSlot` during the previous (build) slot.
17
+ *
18
+ * - `oldState` / `newState` are the previous and new {@link SequencerState}.
19
+ * - `secondsIntoBuildFrame` is the wall-clock seconds elapsed since the build-frame start of
20
+ * `targetSlot` (`now − getBuildFrameStart(targetSlot)`). Undefined for lifecycle states with no
21
+ * associated slot (e.g. IDLE/STOPPING). It can be negative if the transition happens before the
22
+ * build frame opens.
23
+ * - `targetSlot` is the slot the checkpoint is being proposed for (the submission slot, one ahead of
24
+ * the wall-clock build slot under pipelining). Undefined for lifecycle states with no slot.
25
+ */
26
+ ['state-changed']: (args: {
27
+ oldState: SequencerState;
28
+ newState: SequencerState;
29
+ secondsIntoBuildFrame?: number;
30
+ targetSlot?: SlotNumber;
31
+ }) => void;
32
+ /**
33
+ * Emitted by the sequencer once it has decided it is going to attempt to build a
34
+ * checkpoint for `targetSlot`, after computing the L1 simulation overrides used by
35
+ * `canProposeAt`. Fired BEFORE the L1 simulation is run, so consumers can observe the
36
+ * decision regardless of whether the propose ultimately lands.
37
+ *
38
+ * - `hadProposedParent` indicates whether the build saw a proposed (pipelined) parent
39
+ * checkpoint that hasn't landed on L1 yet.
40
+ * - `provenOverride` is the assumed proven checkpoint number pinned for the L1
41
+ * simulation. The plan always pins both chain tips to short-circuit `canPruneAtTime`,
42
+ * so this is populated whenever a simulation plan was built — the value either
43
+ * matches the on-chain proven snapshot (defensive pin) or the assumed-proven
44
+ * checkpoint when building optimistically across a pruning boundary.
45
+ * - `simulatedPending` is the pending checkpoint passed to L1 simulation. The plan
46
+ * always pins both chain tips to short-circuit `canPruneAtTime`, so this reflects
47
+ * either the pipelined/invalidated tip or the on-chain pending snapshot.
48
+ */
49
+ ['preparing-checkpoint']: (args: {
50
+ targetSlot: SlotNumber;
51
+ checkpointNumber: CheckpointNumber;
52
+ hadProposedParent: boolean;
53
+ provenOverride: CheckpointNumber | undefined;
54
+ simulatedPending: CheckpointNumber | undefined;
55
+ }) => void;
56
+ ['proposer-rollup-check-failed']: (args: { reason: string; slot: SlotNumber }) => void;
57
+ ['block-tx-count-check-failed']: (args: { minTxs: number; slot: SlotNumber }) => void;
58
+ ['block-build-failed']: (args: { reason: string; slot: SlotNumber }) => void;
59
+ ['block-proposed']: (args: {
60
+ blockNumber: BlockNumber;
61
+ blockHash: BlockHash;
62
+ checkpointNumber: CheckpointNumber;
63
+ indexWithinCheckpoint: IndexWithinCheckpoint;
64
+ slot: SlotNumber;
65
+ buildSlot: SlotNumber;
66
+ }) => void;
67
+ ['checkpoint-empty']: (args: { slot: SlotNumber }) => void;
68
+ /**
69
+ * Emitted when the proposer's pre-broadcast `validateCheckpointHeader` simulation fails. This is a
70
+ * last-chance check before we gossip a checkpoint proposal: a failure here means the header
71
+ * would not be accepted by L1 (e.g. archive mismatch, stale chain tip, or some other state
72
+ * drift between when we built the checkpoint and when we are about to broadcast it).
73
+ */
74
+ ['header-validation-failed']: (args: {
75
+ slot: SlotNumber;
76
+ checkpointNumber: CheckpointNumber;
77
+ reason: string;
78
+ }) => void;
79
+ ['checkpoint-publish-failed']: (args: {
80
+ slot: SlotNumber;
81
+ successfulActions?: Action[];
82
+ failedActions?: Action[];
83
+ sentActions?: Action[];
84
+ expiredActions?: Action[];
85
+ }) => void;
86
+ ['checkpoint-published']: (args: { checkpoint: CheckpointNumber; slot: SlotNumber }) => void;
87
+ ['checkpoint-error']: (args: { error: Error }) => void;
88
+ ['pipelined-checkpoint-discarded']: (args: {
89
+ slot: SlotNumber;
90
+ checkpointNumber: CheckpointNumber;
91
+ reason: string;
92
+ }) => void;
93
+ };
@@ -0,0 +1,160 @@
1
+ import type { Fr } from '@aztec-labs/foundation/curves/bn254';
2
+ import { type InboxBucket, type L1ToL2MessageSource, isInboxConsumptionSufficient } from '@aztec-labs/stdlib/messaging';
3
+
4
+ /** The subset of the archiver's Inbox-bucket queries the selector needs. */
5
+ export type InboxBucketSource = Pick<
6
+ L1ToL2MessageSource,
7
+ 'getInboxBucket' | 'getLatestInboxBucketAtOrBefore' | 'getL1ToL2MessagesBetweenBuckets'
8
+ >;
9
+
10
+ /**
11
+ * The last-consumed Inbox bucket a block streams from. Only the sequence number and cumulative message count are
12
+ * needed: the sequence number bounds the derived bundle, and the count is the per-block/per-checkpoint cap origin.
13
+ * At a checkpoint's first block this is the parent checkpoint's last-consumed bucket; the genesis base case is
14
+ * `{ seq: 0, totalMsgCount: 0 }` (bundles derive from the start of the Inbox).
15
+ */
16
+ export type ConsumedBucketCursor = Pick<InboxBucket, 'seq' | 'totalMsgCount'>;
17
+
18
+ /** Inputs to a single block's streaming Inbox-bucket selection. */
19
+ export type SelectInboxBucketInput = {
20
+ /** Archiver Inbox-bucket queries. */
21
+ messageSource: InboxBucketSource;
22
+ /** Wall-clock time of this sub-slot, in seconds; the lag-eligibility anchor. */
23
+ now: bigint;
24
+ /**
25
+ * Minimum bucket age in seconds for a bucket to be lag-eligible this sub-slot: one configured Ethereum slot, the
26
+ * same value the validator's acceptance check applies (which documents why age in seconds is only a proxy for the
27
+ * L1 reorg depth this really guards against).
28
+ */
29
+ minBucketAgeSeconds: bigint;
30
+ /** The last bucket consumed by this checkpoint so far (parent checkpoint's at the first block). */
31
+ parent: ConsumedBucketCursor;
32
+ /** Cumulative Inbox message count consumed as of the parent checkpoint; the per-checkpoint cap origin. */
33
+ checkpointStartTotalMsgCount: bigint;
34
+ /** Maximum number of messages this block may consume. */
35
+ perBlockCap: number;
36
+ /** Maximum number of messages the checkpoint may consume in total. */
37
+ perCheckpointCap: number;
38
+ /** True on the checkpoint's final block, where the censorship cutoff becomes a consumption floor. */
39
+ isLastBlock: boolean;
40
+ /**
41
+ * Censorship cutoff timestamp from `getInboxCutoffTimestamp` (mirrors `ProposeLib.validateInboxConsumption`).
42
+ * Buckets opened at or before it are mandatory to consume by the checkpoint's last block.
43
+ */
44
+ cutoffTimestamp: bigint;
45
+ };
46
+
47
+ /** Whether and through which bucket a block consumes. */
48
+ type InboxBucketConsumption =
49
+ | {
50
+ /** The block consumes messages, advancing to `bucket`. */
51
+ consume: true;
52
+ /** The newest bucket this block consumes through. */
53
+ bucket: InboxBucket;
54
+ /** The message leaves consumed this block, in insertion order (may be empty for an empty bucket). */
55
+ bundle: Fr[];
56
+ }
57
+ | {
58
+ /** The block consumes nothing; it reuses the parent bucket reference. */
59
+ consume: false;
60
+ };
61
+
62
+ /** Result of a block's streaming Inbox-bucket selection. */
63
+ export type InboxBucketSelection = InboxBucketConsumption & {
64
+ /**
65
+ * Set on the checkpoint's final block when the selected position still leaves a mandatory bucket unconsumed, so no
66
+ * checkpoint ending on this block can satisfy the censorship floor. The consumption fields still describe the best
67
+ * reachable prefix, but proposing it would produce a checkpoint every honest validator refuses to attest and that
68
+ * L1 `propose` would revert, so the caller is expected to abandon the checkpoint rather than build on it.
69
+ */
70
+ insufficientFinalBlockCapacity?: true;
71
+ };
72
+
73
+ /**
74
+ * Selects the newest Inbox bucket a block streams from, mirroring the L1 consumption predicate in
75
+ * `ProposeLib.validateInboxConsumption`. The policy, per block:
76
+ *
77
+ * 1. Pick the newest lag-eligible bucket: the newest bucket opened at or before `now - minBucketAgeSeconds`. On the
78
+ * checkpoint's last block, also consider the cutoff bucket (newest opened at or before `cutoffTimestamp`) and take
79
+ * whichever is newer, so the checkpoint reaches the censorship floor even if the sub-slot lag preferred less.
80
+ * 2. If nothing is newer than the parent bucket, consume nothing.
81
+ * 3. Otherwise walk back from the candidate to the newest bucket whose consumption fits both the per-block cap
82
+ * (`bucket.totalMsgCount - parent.totalMsgCount`) and the per-checkpoint cap
83
+ * (`bucket.totalMsgCount - checkpointStartTotalMsgCount`). If even the first bucket past the parent overshoots the
84
+ * per-checkpoint cap, consume nothing — the L1 cap-escape (`ProposeLib` allows leaving a bucket unconsumed when
85
+ * consuming through it would exceed the per-checkpoint cap).
86
+ * 4. On the last block only, check the resulting position against the censorship floor with the shared
87
+ * `isInboxConsumptionSufficient` predicate. Because buckets are indivisible, the walk-back in step 3 can be forced
88
+ * onto a prefix that still leaves a mandatory bucket behind; that is reported as
89
+ * `insufficientFinalBlockCapacity` rather than passed off as a usable selection.
90
+ *
91
+ * The `<=` comparisons make a bucket exactly `minBucketAgeSeconds` old lag-eligible and a bucket exactly at the cutoff
92
+ * mandatory, matching the strict `>` "past cutoff" test on L1 (`next.timestamp > cutoff` leaves it optional).
93
+ *
94
+ * A single bucket never exceeds the per-block cap by construction (the Inbox bucket size is at most the per-block cap),
95
+ * so per-block walk-back always lands on at least one bucket; only the per-checkpoint cap can force consuming nothing.
96
+ */
97
+ export async function selectInboxBucketForBlock(input: SelectInboxBucketInput): Promise<InboxBucketSelection> {
98
+ const consumption = await selectConsumption(input);
99
+ if (!input.isLastBlock) {
100
+ return consumption;
101
+ }
102
+
103
+ const { messageSource, parent, checkpointStartTotalMsgCount, perCheckpointCap, cutoffTimestamp } = input;
104
+ const finalSeq = consumption.consume ? consumption.bucket.seq : parent.seq;
105
+ const nextBucket = await messageSource.getInboxBucket(finalSeq + 1n);
106
+ const sufficient = isInboxConsumptionSufficient({
107
+ nextBucket,
108
+ cutoffTimestamp,
109
+ checkpointStartTotalMsgCount,
110
+ perCheckpointCap,
111
+ });
112
+ return sufficient ? consumption : { ...consumption, insufficientFinalBlockCapacity: true };
113
+ }
114
+
115
+ /** Steps 1 to 3 of {@link selectInboxBucketForBlock}: the cap-bounded walk back from the newest eligible bucket. */
116
+ async function selectConsumption(input: SelectInboxBucketInput): Promise<InboxBucketConsumption> {
117
+ const {
118
+ messageSource,
119
+ now,
120
+ minBucketAgeSeconds,
121
+ parent,
122
+ checkpointStartTotalMsgCount,
123
+ perBlockCap,
124
+ perCheckpointCap,
125
+ isLastBlock,
126
+ cutoffTimestamp,
127
+ } = input;
128
+
129
+ let candidate = await messageSource.getLatestInboxBucketAtOrBefore(now - minBucketAgeSeconds);
130
+
131
+ if (isLastBlock) {
132
+ const cutoffBucket = await messageSource.getLatestInboxBucketAtOrBefore(cutoffTimestamp);
133
+ if (cutoffBucket !== undefined && (candidate === undefined || cutoffBucket.seq > candidate.seq)) {
134
+ candidate = cutoffBucket;
135
+ }
136
+ }
137
+
138
+ if (candidate === undefined || candidate.seq <= parent.seq) {
139
+ return { consume: false };
140
+ }
141
+
142
+ const perBlockCapBig = BigInt(perBlockCap);
143
+ const perCheckpointCapBig = BigInt(perCheckpointCap);
144
+
145
+ let selected: InboxBucket | undefined = candidate;
146
+ while (selected !== undefined && selected.seq > parent.seq) {
147
+ const blockCount = selected.totalMsgCount - parent.totalMsgCount;
148
+ const checkpointCount = selected.totalMsgCount - checkpointStartTotalMsgCount;
149
+ if (blockCount <= perBlockCapBig && checkpointCount <= perCheckpointCapBig) {
150
+ const bundle = await messageSource.getL1ToL2MessagesBetweenBuckets(parent.seq, selected.seq);
151
+ return { consume: true, bucket: selected, bundle };
152
+ }
153
+ if (selected.seq - 1n <= parent.seq) {
154
+ break;
155
+ }
156
+ selected = await messageSource.getInboxBucket(selected.seq - 1n);
157
+ }
158
+
159
+ return { consume: false };
160
+ }
@@ -0,0 +1,5 @@
1
+ export * from './checkpoint_proposal_job.js';
2
+ export * from './checkpoint_voter.js';
3
+ export * from './config.js';
4
+ export * from './events.js';
5
+ export * from './sequencer.js';