@aztec/sequencer-client 0.0.1-commit.03f7ef2 → 0.0.1-commit.04d373f

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 (145) hide show
  1. package/README.md +282 -21
  2. package/dest/client/sequencer-client.d.ts +20 -11
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +67 -33
  5. package/dest/config.d.ts +29 -7
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +82 -37
  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 +58 -0
  14. package/dest/global_variable_builder/global_builder.d.ts +14 -16
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +16 -50
  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/index.d.ts +2 -3
  21. package/dest/index.d.ts.map +1 -1
  22. package/dest/index.js +1 -2
  23. package/dest/publisher/config.d.ts +47 -17
  24. package/dest/publisher/config.d.ts.map +1 -1
  25. package/dest/publisher/config.js +121 -42
  26. package/dest/publisher/index.d.ts +2 -1
  27. package/dest/publisher/index.d.ts.map +1 -1
  28. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  29. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  30. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  31. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +58 -0
  32. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  33. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +1 -0
  34. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  35. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  36. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +34 -0
  37. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  38. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  39. package/dest/publisher/l1_tx_failed_store/index.js +2 -0
  40. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  41. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  42. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  43. package/dest/publisher/sequencer-publisher-factory.d.ts +12 -6
  44. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  45. package/dest/publisher/sequencer-publisher-factory.js +27 -3
  46. package/dest/publisher/sequencer-publisher-metrics.d.ts +1 -1
  47. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  48. package/dest/publisher/sequencer-publisher-metrics.js +23 -86
  49. package/dest/publisher/sequencer-publisher.d.ts +108 -81
  50. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  51. package/dest/publisher/sequencer-publisher.js +876 -403
  52. package/dest/sequencer/automine/automine_factory.d.ts +54 -0
  53. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  54. package/dest/sequencer/automine/automine_factory.js +84 -0
  55. package/dest/sequencer/automine/automine_sequencer.d.ts +151 -0
  56. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  57. package/dest/sequencer/automine/automine_sequencer.js +506 -0
  58. package/dest/sequencer/chain_state_overrides.d.ts +61 -0
  59. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  60. package/dest/sequencer/chain_state_overrides.js +98 -0
  61. package/dest/sequencer/checkpoint_proposal_job.d.ts +87 -16
  62. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  63. package/dest/sequencer/checkpoint_proposal_job.js +1331 -203
  64. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  65. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  66. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  67. package/dest/sequencer/checkpoint_voter.d.ts +3 -3
  68. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  69. package/dest/sequencer/checkpoint_voter.js +34 -13
  70. package/dest/sequencer/events.d.ts +47 -2
  71. package/dest/sequencer/events.d.ts.map +1 -1
  72. package/dest/sequencer/index.d.ts +3 -3
  73. package/dest/sequencer/index.d.ts.map +1 -1
  74. package/dest/sequencer/index.js +2 -2
  75. package/dest/sequencer/metrics.d.ts +23 -8
  76. package/dest/sequencer/metrics.d.ts.map +1 -1
  77. package/dest/sequencer/metrics.js +158 -143
  78. package/dest/sequencer/sequencer.d.ts +92 -29
  79. package/dest/sequencer/sequencer.d.ts.map +1 -1
  80. package/dest/sequencer/sequencer.js +818 -157
  81. package/dest/sequencer/timetable.d.ts +17 -6
  82. package/dest/sequencer/timetable.d.ts.map +1 -1
  83. package/dest/sequencer/timetable.js +51 -46
  84. package/dest/sequencer/types.d.ts +2 -2
  85. package/dest/sequencer/types.d.ts.map +1 -1
  86. package/dest/test/index.d.ts +4 -7
  87. package/dest/test/index.d.ts.map +1 -1
  88. package/dest/test/mock_checkpoint_builder.d.ts +29 -17
  89. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  90. package/dest/test/mock_checkpoint_builder.js +86 -34
  91. package/dest/test/utils.d.ts +13 -9
  92. package/dest/test/utils.d.ts.map +1 -1
  93. package/dest/test/utils.js +31 -20
  94. package/package.json +29 -28
  95. package/src/client/sequencer-client.ts +94 -38
  96. package/src/config.ts +107 -46
  97. package/src/global_variable_builder/README.md +44 -0
  98. package/src/global_variable_builder/fee_predictor.ts +172 -0
  99. package/src/global_variable_builder/fee_provider.ts +75 -0
  100. package/src/global_variable_builder/global_builder.ts +26 -63
  101. package/src/global_variable_builder/index.ts +3 -1
  102. package/src/index.ts +5 -4
  103. package/src/publisher/config.ts +157 -45
  104. package/src/publisher/index.ts +3 -0
  105. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  106. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  107. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  108. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  109. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  110. package/src/publisher/sequencer-publisher-factory.ts +39 -10
  111. package/src/publisher/sequencer-publisher-metrics.ts +17 -69
  112. package/src/publisher/sequencer-publisher.ts +611 -521
  113. package/src/sequencer/README.md +152 -450
  114. package/src/sequencer/automine/README.md +46 -0
  115. package/src/sequencer/automine/automine_factory.ts +145 -0
  116. package/src/sequencer/automine/automine_sequencer.ts +592 -0
  117. package/src/sequencer/chain_state_overrides.ts +162 -0
  118. package/src/sequencer/checkpoint_proposal_job.ts +1138 -230
  119. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  120. package/src/sequencer/checkpoint_voter.ts +31 -17
  121. package/src/sequencer/events.ts +50 -2
  122. package/src/sequencer/index.ts +2 -2
  123. package/src/sequencer/metrics.ts +168 -151
  124. package/src/sequencer/sequencer.ts +535 -162
  125. package/src/sequencer/timetable.ts +70 -57
  126. package/src/sequencer/types.ts +1 -1
  127. package/src/test/index.ts +3 -6
  128. package/src/test/mock_checkpoint_builder.ts +149 -73
  129. package/src/test/utils.ts +78 -30
  130. package/dest/sequencer/block_builder.d.ts +0 -26
  131. package/dest/sequencer/block_builder.d.ts.map +0 -1
  132. package/dest/sequencer/block_builder.js +0 -129
  133. package/dest/sequencer/checkpoint_builder.d.ts +0 -63
  134. package/dest/sequencer/checkpoint_builder.d.ts.map +0 -1
  135. package/dest/sequencer/checkpoint_builder.js +0 -131
  136. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  137. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  138. package/dest/tx_validator/nullifier_cache.js +0 -24
  139. package/dest/tx_validator/tx_validator_factory.d.ts +0 -18
  140. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  141. package/dest/tx_validator/tx_validator_factory.js +0 -53
  142. package/src/sequencer/block_builder.ts +0 -217
  143. package/src/sequencer/checkpoint_builder.ts +0 -217
  144. package/src/tx_validator/nullifier_cache.ts +0 -30
  145. package/src/tx_validator/tx_validator_factory.ts +0 -133
@@ -0,0 +1,32 @@
1
+ import { type Logger, createLogger } from '@aztec/foundation/log';
2
+ import { createFileStore } from '@aztec/stdlib/file-store';
3
+
4
+ import type { L1TxFailedStore } from './failed_tx_store.js';
5
+ import { FileStoreL1TxFailedStore } from './file_store_failed_tx_store.js';
6
+
7
+ /**
8
+ * Creates an L1TxFailedStore from a config string.
9
+ * Supports any backend that FileStore supports (GCS, S3, R2, local filesystem).
10
+ * @param config - Config string (e.g., 'gs://bucket/path', 's3://bucket/path', 'file:///path'). If undefined, returns undefined.
11
+ * @param logger - Optional logger.
12
+ * @returns The store instance, or undefined if config is not provided.
13
+ */
14
+ export async function createL1TxFailedStore(
15
+ config: string | undefined,
16
+ logger: Logger = createLogger('sequencer:l1-tx-failed-store'),
17
+ ): Promise<L1TxFailedStore | undefined> {
18
+ if (!config) {
19
+ return undefined;
20
+ }
21
+
22
+ const fileStore = await createFileStore(config, logger);
23
+ if (!fileStore) {
24
+ throw new Error(
25
+ `Failed to create file store from config: '${config}'. ` +
26
+ `Supported formats: 'gs://bucket/path', 's3://bucket/path', 'file:///path'.`,
27
+ );
28
+ }
29
+
30
+ logger.info(`Created L1 tx failed store`, { config });
31
+ return new FileStoreL1TxFailedStore(fileStore, logger);
32
+ }
@@ -0,0 +1,57 @@
1
+ import type { Branded } from '@aztec/foundation/branded-types';
2
+
3
+ import type { Hex } from 'viem';
4
+
5
+ /** URI pointing to a stored failed L1 transaction. */
6
+ export type FailedL1TxUri = Branded<string, 'FailedL1TxUri'>;
7
+
8
+ /** A failed L1 transaction captured for debugging and replay. */
9
+ export type FailedL1Tx = {
10
+ /** Tx hash (for reverts) or keccak256(request.data) (for simulation/send failures). */
11
+ id: Hex;
12
+ /** Unix timestamp (ms) when failure occurred. */
13
+ timestamp: number;
14
+ /** Whether the failure was during simulation or after sending. */
15
+ failureType: 'simulation' | 'revert' | 'send-error';
16
+ /** The actual L1 transaction for replay (multicall-encoded for bundled txs). */
17
+ request: {
18
+ to: Hex;
19
+ data: Hex;
20
+ value?: string; // bigint as string
21
+ };
22
+ /** Raw blob data as hex for replay. */
23
+ blobData?: Hex[];
24
+ /** L1 block number at time of failure (simulation target or receipt block). */
25
+ l1BlockNumber: string; // bigint as string
26
+ /** Receipt info (present only for on-chain reverts). */
27
+ receipt?: {
28
+ transactionHash: Hex;
29
+ blockNumber: string; // bigint as string
30
+ gasUsed: string; // bigint as string
31
+ status: 'reverted';
32
+ };
33
+ /** Error information. */
34
+ error: {
35
+ message: string;
36
+ /** Decoded error name (e.g., 'Rollup__InvalidProposer'). */
37
+ name?: string;
38
+ };
39
+ /** Context metadata. */
40
+ context: {
41
+ /** Actions involved (e.g., ['propose', 'governance-signal']). */
42
+ actions: string[];
43
+ /** Individual request data for each action (metadata, not used for replay). */
44
+ requests?: Array<{ action: string; to: Hex; data: Hex }>;
45
+ checkpointNumber?: number;
46
+ slot?: number;
47
+ sender: Hex;
48
+ };
49
+ };
50
+
51
+ /** Store for failed L1 transactions for debugging purposes. */
52
+ export interface L1TxFailedStore {
53
+ /** Saves a failed transaction and returns its URI. */
54
+ saveFailedTx(tx: FailedL1Tx): Promise<FailedL1TxUri>;
55
+ /** Retrieves a failed transaction by its URI. */
56
+ getFailedTx(uri: FailedL1TxUri): Promise<FailedL1Tx>;
57
+ }
@@ -0,0 +1,46 @@
1
+ import { type Logger, createLogger } from '@aztec/foundation/log';
2
+ import type { FileStore } from '@aztec/stdlib/file-store';
3
+
4
+ import type { FailedL1Tx, FailedL1TxUri, L1TxFailedStore } from './failed_tx_store.js';
5
+
6
+ /**
7
+ * L1TxFailedStore implementation using the FileStore abstraction.
8
+ * Supports any backend that FileStore supports (GCS, S3, R2, local filesystem).
9
+ */
10
+ export class FileStoreL1TxFailedStore implements L1TxFailedStore {
11
+ private readonly log: Logger;
12
+
13
+ constructor(
14
+ private readonly fileStore: FileStore,
15
+ logger?: Logger,
16
+ ) {
17
+ this.log = logger ?? createLogger('sequencer:l1-tx-failed-store');
18
+ }
19
+
20
+ public async saveFailedTx(tx: FailedL1Tx): Promise<FailedL1TxUri> {
21
+ const prefix = tx.receipt ? 'tx' : 'data';
22
+ const path = `${tx.failureType}/${prefix}-${tx.id}.json`;
23
+ const json = JSON.stringify(tx, null, 2);
24
+
25
+ const uri = await this.fileStore.save(path, Buffer.from(json), {
26
+ metadata: {
27
+ 'content-type': 'application/json',
28
+ actions: tx.context.actions.join(','),
29
+ 'failure-type': tx.failureType,
30
+ },
31
+ });
32
+
33
+ this.log.info(`Saved failed L1 tx to ${uri}`, {
34
+ id: tx.id,
35
+ failureType: tx.failureType,
36
+ actions: tx.context.actions.join(','),
37
+ });
38
+
39
+ return uri as FailedL1TxUri;
40
+ }
41
+
42
+ public async getFailedTx(uri: FailedL1TxUri): Promise<FailedL1Tx> {
43
+ const data = await this.fileStore.read(uri);
44
+ return JSON.parse(data.toString()) as FailedL1Tx;
45
+ }
46
+ }
@@ -0,0 +1,3 @@
1
+ export { type FailedL1Tx, type FailedL1TxUri, type L1TxFailedStore } from './failed_tx_store.js';
2
+ export { createL1TxFailedStore } from './factory.js';
3
+ export { FileStoreL1TxFailedStore } from './file_store_failed_tx_store.js';
@@ -0,0 +1,254 @@
1
+ import type { EpochCache } from '@aztec/epoch-cache';
2
+ import { Multicall3, type RollupContract, buildSimulationOverridesStateOverride } from '@aztec/ethereum/contracts';
3
+ import { type L1TxUtils, MAX_L1_TX_LIMIT } from '@aztec/ethereum/l1-tx-utils';
4
+ import { formatViemError } from '@aztec/ethereum/utils';
5
+ import type { SlotNumber } from '@aztec/foundation/branded-types';
6
+ import { type Logger, createLogger } from '@aztec/foundation/log';
7
+ import { getLastL1SlotTimestampForL2Slot } from '@aztec/stdlib/epoch-helpers';
8
+
9
+ import type { Hex, StateOverride } from 'viem';
10
+
11
+ import type { RequestWithExpiry } from './sequencer-publisher.js';
12
+
13
+ /** A request that was dropped by bundle simulation, with the decoded revert reason. */
14
+ export type DroppedRequest = {
15
+ request: RequestWithExpiry;
16
+ revertReason: string | undefined;
17
+ returnData: Hex | undefined;
18
+ };
19
+
20
+ /**
21
+ * Result of {@link SequencerBundleSimulator.simulate}.
22
+ *
23
+ * - `success`: simulation succeeded. `requests` is the filtered survivor list, `gasLimit` is
24
+ * the bumped gas limit derived from `gasUsed` (plus blob evaluation gas). `droppedRequests`
25
+ * lists the entries that were observed to revert in simulation.
26
+ * - `fallback`: the node does not support eth_simulateV1 (or the simulate call threw). The
27
+ * caller should send `requests` as-is with a safe gas limit (e.g. {@link MAX_L1_TX_LIMIT}).
28
+ * `droppedRequests` carries any entries that the first pass already proved reverted, so the
29
+ * caller does not re-include them when the second pass falls back.
30
+ * - `aborted`: the bundle cannot be sent. `droppedRequests` contains only entries that were
31
+ * actually observed to revert (so they can be reported as simulation failures); it is empty
32
+ * when the abort was caused by an empty input bundle.
33
+ */
34
+ export type BundleSimulateResult =
35
+ | { kind: 'success'; requests: RequestWithExpiry[]; gasLimit: bigint; droppedRequests: DroppedRequest[] }
36
+ | { kind: 'fallback'; requests: RequestWithExpiry[]; droppedRequests: DroppedRequest[] }
37
+ | { kind: 'aborted'; reason: AbortReason; droppedRequests: DroppedRequest[] };
38
+
39
+ export type AbortReason = 'empty-bundle' | 'all-reverted' | 'second-pass-reverts';
40
+
41
+ type SimulatePassResult =
42
+ | { kind: 'decoded'; survivors: RequestWithExpiry[]; droppedRequests: DroppedRequest[]; gasUsed: bigint }
43
+ | { kind: 'fallback' };
44
+
45
+ /**
46
+ * Bundle-level simulator for the aggregate3 payload that `SequencerPublisher` is about to send.
47
+ *
48
+ * Runs `eth_simulateV1` against `Multicall3.aggregate3`, drops entries that revert, and returns
49
+ * a gasLimit for the survivors. When `eth_simulateV1` is unavailable, signals fallback to the
50
+ * caller so it can send the bundle as-is with a conservative gas limit.
51
+ */
52
+ export class SequencerBundleSimulator {
53
+ private readonly log: Logger;
54
+
55
+ constructor(
56
+ private readonly deps: {
57
+ getL1TxUtils: () => L1TxUtils;
58
+ rollupContract: RollupContract;
59
+ epochCache: EpochCache;
60
+ log?: Logger;
61
+ },
62
+ ) {
63
+ this.log = deps.log ?? createLogger('sequencer:publisher:bundle-simulator');
64
+ }
65
+
66
+ /**
67
+ * Simulates the given bundle near the end of the target slot and filters out entries
68
+ * that revert.
69
+ *
70
+ * - If all entries pass on the first pass, returns `success` with the gasLimit.
71
+ * - If some entries revert, re-simulates the survivors. If the second pass is clean, returns
72
+ * `success` with the survivors and dropped entries. If the second pass surfaces any revert,
73
+ * returns `aborted` — we refuse to send a bundle whose composition still has internal
74
+ * reverts after one round of filtering.
75
+ * - If eth_simulateV1 is unavailable, returns `fallback`. The caller is expected to send the
76
+ * bundle as-is with a safe gas limit.
77
+ *
78
+ * The simulation `block.timestamp` is the last L1 slot timestamp inside the target L2 slot.
79
+ * This still maps to the target L2 slot for propose's `validateHeader` and EIP-712 signature
80
+ * checks, while avoiding eth_simulateV1 rejecting a child block whose timestamp is not strictly
81
+ * greater than the current L1 head.
82
+ *
83
+ * Known limitation: on networks where L1 is mining behind cadence (missed L1 slots, anvil with
84
+ * overridden timestamps), the actual `block.timestamp` at send time can land in the prior L2
85
+ * slot. In that case `propose` would revert silently inside the multicall. The simulator does
86
+ * not detect this case because it simulates inside the target slot — the prior implementation
87
+ * used `min(predictedNextL1Ts, targetTimestamp)` to surface this failure mode at simulate time.
88
+ */
89
+ public async simulate(validRequests: RequestWithExpiry[], targetSlot: SlotNumber): Promise<BundleSimulateResult> {
90
+ if (validRequests.length === 0) {
91
+ return { kind: 'aborted', reason: 'empty-bundle', droppedRequests: [] };
92
+ }
93
+ // Pin the publisher we'll use across the whole simulate call so that the publisher's rotation
94
+ // can't change l1TxUtils mid-flight.
95
+ const l1TxUtils = this.deps.getL1TxUtils();
96
+
97
+ const proposeRequest = validRequests.find(r => r.action === 'propose');
98
+ const simulateTimestamp = getLastL1SlotTimestampForL2Slot(targetSlot, this.deps.epochCache.getL1Constants());
99
+ const firstPassOverrides = await this.buildStateOverrides(!!proposeRequest);
100
+
101
+ const firstPass = await this.simulateAndDecode(l1TxUtils, validRequests, simulateTimestamp, firstPassOverrides);
102
+
103
+ if (firstPass.kind === 'fallback') {
104
+ this.log.warn('Bundle simulate fallback (eth_simulateV1 unavailable); caller will send bundle as-is', {
105
+ actions: validRequests.map(r => r.action),
106
+ });
107
+ return { kind: 'fallback', requests: validRequests, droppedRequests: [] };
108
+ }
109
+
110
+ if (firstPass.survivors.length === 0) {
111
+ this.log.warn('All bundle entries dropped in simulation; aborting send', {
112
+ actions: validRequests.map(r => r.action),
113
+ });
114
+ return { kind: 'aborted', reason: 'all-reverted', droppedRequests: firstPass.droppedRequests };
115
+ }
116
+
117
+ if (firstPass.droppedRequests.length === 0) {
118
+ return this.buildSuccessResult(l1TxUtils, firstPass.survivors, [], firstPass.gasUsed, proposeRequest);
119
+ }
120
+
121
+ this.log.warn('Some bundle entries reverted; re-simulating reduced bundle', {
122
+ droppedActions: firstPass.droppedRequests.map(d => d.request.action),
123
+ remainingActions: firstPass.survivors.map(r => r.action),
124
+ });
125
+
126
+ // Rebuild overrides for the reduced bundle: if propose was dropped, we no longer need the blob-check override
127
+ const proposeSurvived = proposeRequest !== undefined && firstPass.survivors.includes(proposeRequest);
128
+ const secondPassOverrides = proposeSurvived ? firstPassOverrides : await this.buildStateOverrides(false);
129
+ const secondPass = await this.simulateAndDecode(
130
+ l1TxUtils,
131
+ firstPass.survivors,
132
+ simulateTimestamp,
133
+ secondPassOverrides,
134
+ );
135
+
136
+ if (secondPass.kind === 'fallback') {
137
+ this.log.warn(
138
+ 'Bundle simulate errored on second pass (eth_simulateV1 unavailable); sending first-pass survivors as-is',
139
+ {
140
+ actions: firstPass.survivors.map(r => r.action),
141
+ droppedActions: firstPass.droppedRequests.map(d => d.request.action),
142
+ },
143
+ );
144
+ return { kind: 'fallback', requests: firstPass.survivors, droppedRequests: firstPass.droppedRequests };
145
+ }
146
+
147
+ // We refuse to chase reverts through repeated trimming: anything other than a clean second pass aborts the whole send
148
+ if (secondPass.droppedRequests.length > 0) {
149
+ this.log.error('Re-simulate surfaced reverts; aborting send', {
150
+ secondPassDroppedActions: secondPass.droppedRequests.map(d => d.request.action),
151
+ });
152
+ return {
153
+ kind: 'aborted',
154
+ reason: 'second-pass-reverts',
155
+ droppedRequests: [...firstPass.droppedRequests, ...secondPass.droppedRequests],
156
+ };
157
+ }
158
+
159
+ return this.buildSuccessResult(
160
+ l1TxUtils,
161
+ secondPass.survivors,
162
+ firstPass.droppedRequests,
163
+ secondPass.gasUsed,
164
+ proposeRequest,
165
+ );
166
+ }
167
+
168
+ private buildSuccessResult(
169
+ l1TxUtils: L1TxUtils,
170
+ survivors: RequestWithExpiry[],
171
+ droppedRequests: DroppedRequest[],
172
+ bundleGasUsed: bigint,
173
+ proposeRequest: RequestWithExpiry | undefined,
174
+ ): BundleSimulateResult {
175
+ const proposeSurvived = proposeRequest !== undefined && survivors.includes(proposeRequest);
176
+ const blobEvaluationGas = proposeSurvived ? (proposeRequest?.blobEvaluationGas ?? 0n) : 0n;
177
+ const gasLimit = this.computeGasLimit(l1TxUtils, bundleGasUsed, blobEvaluationGas);
178
+ this.log.debug('Bundle simulate complete', {
179
+ survivingRequests: survivors.length,
180
+ bundleGasUsed,
181
+ gasLimit,
182
+ actions: survivors.map(r => r.action),
183
+ });
184
+ return { kind: 'success', requests: survivors, gasLimit, droppedRequests };
185
+ }
186
+
187
+ /**
188
+ * `gasLimit = bumpGasLimit(ceil(gasUsed * 64 / 63))`, plus blob evaluation gas if a propose
189
+ * survived, capped at the L1 block gas limit.
190
+ */
191
+ private computeGasLimit(l1TxUtils: L1TxUtils, bundleGasUsed: bigint, blobEvaluationGas: bigint): bigint {
192
+ const gasUsedWithEip150 = (bundleGasUsed * 64n + 62n) / 63n;
193
+ const gasLimit = l1TxUtils.bumpGasLimit(gasUsedWithEip150) + blobEvaluationGas;
194
+ return gasLimit > MAX_L1_TX_LIMIT ? MAX_L1_TX_LIMIT : gasLimit;
195
+ }
196
+
197
+ /**
198
+ * eth_simulateV1 cannot carry blob sidecar data, so disable the rollup's on-chain blob check
199
+ * when a propose is in the bundle.
200
+ */
201
+ private buildStateOverrides(hasProposeAction: boolean): Promise<StateOverride> {
202
+ return buildSimulationOverridesStateOverride(
203
+ this.deps.rollupContract,
204
+ hasProposeAction ? { disableBlobCheck: true } : undefined,
205
+ );
206
+ }
207
+
208
+ private async simulateAndDecode(
209
+ l1TxUtils: L1TxUtils,
210
+ requests: RequestWithExpiry[],
211
+ simulateTimestamp: bigint,
212
+ stateOverrides: StateOverride,
213
+ ): Promise<SimulatePassResult> {
214
+ let simResult: Awaited<ReturnType<typeof Multicall3.simulateAggregate3>>;
215
+ try {
216
+ simResult = await Multicall3.simulateAggregate3(
217
+ requests.map(r => ({ to: r.request.to! as Hex, data: r.request.data! as Hex, abi: r.request.abi })),
218
+ l1TxUtils,
219
+ {
220
+ blockOverrides: { time: simulateTimestamp, gasLimit: MAX_L1_TX_LIMIT * 2n },
221
+ stateOverrides,
222
+ gas: MAX_L1_TX_LIMIT,
223
+ fallbackGasEstimate: MAX_L1_TX_LIMIT,
224
+ },
225
+ );
226
+ } catch (err) {
227
+ this.log.warn('Bundle simulate threw; treating as fallback', {
228
+ err: formatViemError(err),
229
+ actions: requests.map(r => r.action),
230
+ });
231
+ return { kind: 'fallback' };
232
+ }
233
+
234
+ if (simResult.kind === 'fallback') {
235
+ return { kind: 'fallback' };
236
+ }
237
+
238
+ const survivors: RequestWithExpiry[] = [];
239
+ const droppedRequests: DroppedRequest[] = [];
240
+ for (let i = 0; i < requests.length; i++) {
241
+ const entry = simResult.entries[i];
242
+ if (entry.success) {
243
+ survivors.push(requests[i]);
244
+ continue;
245
+ }
246
+ droppedRequests.push({
247
+ request: requests[i],
248
+ revertReason: entry.revertReason,
249
+ returnData: entry.returnData,
250
+ });
251
+ }
252
+ return { kind: 'decoded', survivors, droppedRequests, gasUsed: simResult.gasUsed };
253
+ }
254
+ }
@@ -3,11 +3,10 @@ import { type Logger, createLogger } from '@aztec/aztec.js/log';
3
3
  import type { BlobClientInterface } from '@aztec/blob-client/client';
4
4
  import type { EpochCache } from '@aztec/epoch-cache';
5
5
  import type { GovernanceProposerContract, RollupContract } from '@aztec/ethereum/contracts';
6
- import type { L1TxUtilsWithBlobs } from '@aztec/ethereum/l1-tx-utils-with-blobs';
6
+ import type { L1TxUtils } from '@aztec/ethereum/l1-tx-utils';
7
7
  import type { PublisherFilter, PublisherManager } from '@aztec/ethereum/publisher-manager';
8
8
  import { SlotNumber } from '@aztec/foundation/branded-types';
9
9
  import type { DateProvider } from '@aztec/foundation/timer';
10
- import type { SlashFactoryContract } from '@aztec/stdlib/l1-contracts';
11
10
  import type { TelemetryClient } from '@aztec/telemetry-client';
12
11
  import { NodeKeystoreAdapter } from '@aztec/validator-client';
13
12
 
@@ -26,26 +25,37 @@ export class SequencerPublisherFactory {
26
25
  /** Stores the last slot in which every action was carried out by a publisher */
27
26
  private lastActions: Partial<Record<Action, SlotNumber>> = {};
28
27
 
28
+ private nodeKeyStore: NodeKeystoreAdapter;
29
+
29
30
  private logger: Logger;
30
31
 
31
32
  constructor(
32
33
  private sequencerConfig: SequencerClientConfig,
33
34
  private deps: {
34
35
  telemetry: TelemetryClient;
35
- publisherManager: PublisherManager<L1TxUtilsWithBlobs>;
36
- blobClient?: BlobClientInterface;
36
+ publisherManager: PublisherManager<L1TxUtils>;
37
+ blobClient: BlobClientInterface;
37
38
  dateProvider: DateProvider;
38
39
  epochCache: EpochCache;
39
40
  rollupContract: RollupContract;
40
41
  governanceProposerContract: GovernanceProposerContract;
41
- slashFactoryContract: SlashFactoryContract;
42
42
  nodeKeyStore: NodeKeystoreAdapter;
43
43
  logger?: Logger;
44
44
  },
45
45
  ) {
46
46
  this.publisherMetrics = new SequencerPublisherMetrics(deps.telemetry, 'SequencerPublisher');
47
47
  this.logger = deps.logger ?? createLogger('sequencer');
48
+ this.nodeKeyStore = this.deps.nodeKeyStore;
49
+ }
50
+
51
+ /**
52
+ * Updates the node keystore adapter used for publisher lookups.
53
+ * Called when the keystore is reloaded at runtime to reflect new validator-publisher mappings.
54
+ */
55
+ public updateNodeKeyStore(adapter: NodeKeystoreAdapter): void {
56
+ this.nodeKeyStore = adapter;
48
57
  }
58
+
49
59
  /**
50
60
  * Creates a new SequencerPublisher instance.
51
61
  * @param _validatorAddress - The address of the validator that will be using the publisher.
@@ -54,30 +64,44 @@ export class SequencerPublisherFactory {
54
64
  public async create(validatorAddress?: EthAddress): Promise<AttestorPublisherPair> {
55
65
  // If we have been given an attestor address we must only allow publishers permitted for that attestor
56
66
 
57
- const allowedPublishers = !validatorAddress ? [] : this.deps.nodeKeyStore.getPublisherAddresses(validatorAddress);
58
- const filter: PublisherFilter<L1TxUtilsWithBlobs> = !validatorAddress
67
+ const allowedPublishers = !validatorAddress ? [] : this.nodeKeyStore.getPublisherAddresses(validatorAddress);
68
+ const filter: PublisherFilter<L1TxUtils> = !validatorAddress
59
69
  ? () => true
60
- : (utils: L1TxUtilsWithBlobs) => {
70
+ : (utils: L1TxUtils) => {
61
71
  const publisherAddress = utils.getSenderAddress();
62
72
  return allowedPublishers.some(allowedPublisher => allowedPublisher.equals(publisherAddress));
63
73
  };
64
74
 
65
75
  const l1Publisher = await this.deps.publisherManager.getAvailablePublisher(filter);
66
76
  const attestorAddress =
67
- validatorAddress ?? this.deps.nodeKeyStore.getAttestorForPublisher(l1Publisher.getSenderAddress());
77
+ validatorAddress ?? this.nodeKeyStore.getAttestorForPublisher(l1Publisher.getSenderAddress());
68
78
 
69
79
  const rollup = this.deps.rollupContract;
70
80
  const slashingProposerContract = await rollup.getSlashingProposer();
71
81
 
82
+ const getNextPublisher = async (excludeAddresses: EthAddress[]): Promise<L1TxUtils | undefined> => {
83
+ const exclusionFilter: PublisherFilter<L1TxUtils> = (utils: L1TxUtils) => {
84
+ if (excludeAddresses.some(addr => addr.equals(utils.getSenderAddress()))) {
85
+ return false;
86
+ }
87
+ return filter(utils);
88
+ };
89
+ try {
90
+ return await this.deps.publisherManager.getAvailablePublisher(exclusionFilter);
91
+ } catch {
92
+ return undefined;
93
+ }
94
+ };
95
+
72
96
  const publisher = new SequencerPublisher(this.sequencerConfig, {
73
97
  l1TxUtils: l1Publisher,
98
+ getNextPublisher,
74
99
  telemetry: this.deps.telemetry,
75
100
  blobClient: this.deps.blobClient,
76
101
  rollupContract: this.deps.rollupContract,
77
102
  epochCache: this.deps.epochCache,
78
103
  governanceProposerContract: this.deps.governanceProposerContract,
79
104
  slashingProposerContract,
80
- slashFactoryContract: this.deps.slashFactoryContract,
81
105
  dateProvider: this.deps.dateProvider,
82
106
  metrics: this.publisherMetrics,
83
107
  lastActions: this.lastActions,
@@ -89,4 +113,9 @@ export class SequencerPublisherFactory {
89
113
  publisher,
90
114
  };
91
115
  }
116
+
117
+ /** Stops all publishers managed by this factory. Used during sequencer shutdown. */
118
+ public async stopAll(): Promise<void> {
119
+ await this.deps.publisherManager.stop();
120
+ }
92
121
  }
@@ -7,7 +7,7 @@ import {
7
7
  Metrics,
8
8
  type TelemetryClient,
9
9
  type UpDownCounter,
10
- ValueType,
10
+ createUpDownCounterWithDefault,
11
11
  } from '@aztec/telemetry-client';
12
12
 
13
13
  import { formatEther } from 'viem/utils';
@@ -40,88 +40,36 @@ export class SequencerPublisherMetrics {
40
40
  ) {
41
41
  const meter = client.getMeter(name);
42
42
 
43
- this.gasPrice = meter.createHistogram(Metrics.L1_PUBLISHER_GAS_PRICE, {
44
- description: 'The gas price used for transactions',
45
- unit: 'gwei',
46
- valueType: ValueType.DOUBLE,
47
- });
43
+ this.gasPrice = meter.createHistogram(Metrics.L1_PUBLISHER_GAS_PRICE);
48
44
 
49
- this.txCount = meter.createUpDownCounter(Metrics.L1_PUBLISHER_TX_COUNT, {
50
- description: 'The number of transactions processed',
45
+ this.txCount = createUpDownCounterWithDefault(meter, Metrics.L1_PUBLISHER_TX_COUNT, {
46
+ [Attributes.L1_TX_TYPE]: ['process'],
47
+ [Attributes.OK]: [true, false],
51
48
  });
52
49
 
53
- this.txDuration = meter.createHistogram(Metrics.L1_PUBLISHER_TX_DURATION, {
54
- description: 'The duration of transaction processing',
55
- unit: 'ms',
56
- valueType: ValueType.INT,
57
- });
50
+ this.txDuration = meter.createHistogram(Metrics.L1_PUBLISHER_TX_DURATION);
58
51
 
59
- this.txGas = meter.createHistogram(Metrics.L1_PUBLISHER_TX_GAS, {
60
- description: 'The gas consumed by transactions',
61
- unit: 'gas',
62
- valueType: ValueType.INT,
63
- });
52
+ this.txGas = meter.createHistogram(Metrics.L1_PUBLISHER_TX_GAS);
64
53
 
65
- this.txCalldataSize = meter.createHistogram(Metrics.L1_PUBLISHER_TX_CALLDATA_SIZE, {
66
- description: 'The size of the calldata in transactions',
67
- unit: 'By',
68
- valueType: ValueType.INT,
69
- });
54
+ this.txCalldataSize = meter.createHistogram(Metrics.L1_PUBLISHER_TX_CALLDATA_SIZE);
70
55
 
71
- this.txCalldataGas = meter.createHistogram(Metrics.L1_PUBLISHER_TX_CALLDATA_GAS, {
72
- description: 'The gas consumed by the calldata in transactions',
73
- unit: 'gas',
74
- valueType: ValueType.INT,
75
- });
56
+ this.txCalldataGas = meter.createHistogram(Metrics.L1_PUBLISHER_TX_CALLDATA_GAS);
76
57
 
77
- this.txBlobDataGasUsed = meter.createHistogram(Metrics.L1_PUBLISHER_TX_BLOBDATA_GAS_USED, {
78
- description: 'The amount of blob gas used in transactions',
79
- unit: 'gas',
80
- valueType: ValueType.INT,
81
- });
58
+ this.txBlobDataGasUsed = meter.createHistogram(Metrics.L1_PUBLISHER_TX_BLOBDATA_GAS_USED);
82
59
 
83
- this.txBlobDataGasCost = meter.createHistogram(Metrics.L1_PUBLISHER_TX_BLOBDATA_GAS_COST, {
84
- description: 'The gas cost of blobs in transactions',
85
- unit: 'gwei',
86
- valueType: ValueType.INT,
87
- });
60
+ this.txBlobDataGasCost = meter.createHistogram(Metrics.L1_PUBLISHER_TX_BLOBDATA_GAS_COST);
88
61
 
89
- this.blobCountHistogram = meter.createHistogram(Metrics.L1_PUBLISHER_BLOB_COUNT, {
90
- description: 'Number of blobs in L1 transactions',
91
- unit: 'blobs',
92
- valueType: ValueType.INT,
93
- });
62
+ this.blobCountHistogram = meter.createHistogram(Metrics.L1_PUBLISHER_BLOB_COUNT);
94
63
 
95
- this.blobInclusionBlocksHistogram = meter.createHistogram(Metrics.L1_PUBLISHER_BLOB_INCLUSION_BLOCKS, {
96
- description: 'Number of L1 blocks between blob tx submission and inclusion',
97
- unit: 'blocks',
98
- valueType: ValueType.INT,
99
- });
64
+ this.blobInclusionBlocksHistogram = meter.createHistogram(Metrics.L1_PUBLISHER_BLOB_INCLUSION_BLOCKS);
100
65
 
101
- this.blobTxSuccessCounter = meter.createUpDownCounter(Metrics.L1_PUBLISHER_BLOB_TX_SUCCESS, {
102
- description: 'Number of successful L1 transactions with blobs',
103
- });
66
+ this.blobTxSuccessCounter = createUpDownCounterWithDefault(meter, Metrics.L1_PUBLISHER_BLOB_TX_SUCCESS);
104
67
 
105
- this.blobTxFailureCounter = meter.createUpDownCounter(Metrics.L1_PUBLISHER_BLOB_TX_FAILURE, {
106
- description: 'Number of failed L1 transactions with blobs',
107
- });
68
+ this.blobTxFailureCounter = createUpDownCounterWithDefault(meter, Metrics.L1_PUBLISHER_BLOB_TX_FAILURE);
108
69
 
109
- this.txTotalFee = meter.createHistogram(Metrics.L1_PUBLISHER_TX_TOTAL_FEE, {
110
- description: 'How much L1 tx costs',
111
- unit: 'eth',
112
- valueType: ValueType.DOUBLE,
113
- advice: {
114
- explicitBucketBoundaries: [
115
- 0.001, 0.002, 0.004, 0.008, 0.01, 0.02, 0.04, 0.08, 0.1, 0.2, 0.4, 0.8, 1, 1.2, 1.4, 1.8, 2,
116
- ],
117
- },
118
- });
70
+ this.txTotalFee = meter.createHistogram(Metrics.L1_PUBLISHER_TX_TOTAL_FEE);
119
71
 
120
- this.senderBalance = meter.createGauge(Metrics.L1_PUBLISHER_BALANCE, {
121
- unit: 'eth',
122
- description: 'The balance of the sender address',
123
- valueType: ValueType.DOUBLE,
124
- });
72
+ this.senderBalance = meter.createGauge(Metrics.L1_PUBLISHER_BALANCE);
125
73
  }
126
74
 
127
75
  recordFailedTx(txType: L1TxType) {