@aztec/sequencer-client 0.0.0-test.1 → 0.0.1-commit.0b941701

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 (135) hide show
  1. package/dest/client/index.d.ts +1 -1
  2. package/dest/client/sequencer-client.d.ts +31 -31
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +82 -60
  5. package/dest/config.d.ts +15 -16
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +118 -70
  8. package/dest/global_variable_builder/global_builder.d.ts +26 -15
  9. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  10. package/dest/global_variable_builder/global_builder.js +62 -44
  11. package/dest/global_variable_builder/index.d.ts +1 -1
  12. package/dest/index.d.ts +2 -4
  13. package/dest/index.d.ts.map +1 -1
  14. package/dest/index.js +1 -3
  15. package/dest/publisher/config.d.ts +15 -12
  16. package/dest/publisher/config.d.ts.map +1 -1
  17. package/dest/publisher/config.js +32 -19
  18. package/dest/publisher/index.d.ts +3 -1
  19. package/dest/publisher/index.d.ts.map +1 -1
  20. package/dest/publisher/index.js +3 -0
  21. package/dest/publisher/sequencer-publisher-factory.d.ts +44 -0
  22. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -0
  23. package/dest/publisher/sequencer-publisher-factory.js +51 -0
  24. package/dest/publisher/sequencer-publisher-metrics.d.ts +5 -4
  25. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  26. package/dest/publisher/sequencer-publisher-metrics.js +26 -62
  27. package/dest/publisher/sequencer-publisher.d.ts +134 -87
  28. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  29. package/dest/publisher/sequencer-publisher.js +1146 -249
  30. package/dest/sequencer/checkpoint_proposal_job.d.ts +79 -0
  31. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
  32. package/dest/sequencer/checkpoint_proposal_job.js +1165 -0
  33. package/dest/sequencer/checkpoint_voter.d.ts +35 -0
  34. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -0
  35. package/dest/sequencer/checkpoint_voter.js +109 -0
  36. package/dest/sequencer/config.d.ts +7 -1
  37. package/dest/sequencer/config.d.ts.map +1 -1
  38. package/dest/sequencer/errors.d.ts +11 -0
  39. package/dest/sequencer/errors.d.ts.map +1 -0
  40. package/dest/sequencer/errors.js +15 -0
  41. package/dest/sequencer/events.d.ts +46 -0
  42. package/dest/sequencer/events.d.ts.map +1 -0
  43. package/dest/sequencer/events.js +1 -0
  44. package/dest/sequencer/index.d.ts +4 -2
  45. package/dest/sequencer/index.d.ts.map +1 -1
  46. package/dest/sequencer/index.js +3 -1
  47. package/dest/sequencer/metrics.d.ts +48 -12
  48. package/dest/sequencer/metrics.d.ts.map +1 -1
  49. package/dest/sequencer/metrics.js +204 -69
  50. package/dest/sequencer/sequencer.d.ts +144 -137
  51. package/dest/sequencer/sequencer.d.ts.map +1 -1
  52. package/dest/sequencer/sequencer.js +967 -525
  53. package/dest/sequencer/timetable.d.ts +76 -24
  54. package/dest/sequencer/timetable.d.ts.map +1 -1
  55. package/dest/sequencer/timetable.js +177 -61
  56. package/dest/sequencer/types.d.ts +3 -0
  57. package/dest/sequencer/types.d.ts.map +1 -0
  58. package/dest/sequencer/types.js +1 -0
  59. package/dest/sequencer/utils.d.ts +20 -38
  60. package/dest/sequencer/utils.d.ts.map +1 -1
  61. package/dest/sequencer/utils.js +12 -47
  62. package/dest/test/index.d.ts +9 -1
  63. package/dest/test/index.d.ts.map +1 -1
  64. package/dest/test/index.js +0 -4
  65. package/dest/test/mock_checkpoint_builder.d.ts +95 -0
  66. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -0
  67. package/dest/test/mock_checkpoint_builder.js +222 -0
  68. package/dest/test/utils.d.ts +53 -0
  69. package/dest/test/utils.d.ts.map +1 -0
  70. package/dest/test/utils.js +103 -0
  71. package/package.json +47 -45
  72. package/src/client/sequencer-client.ts +106 -107
  73. package/src/config.ts +131 -81
  74. package/src/global_variable_builder/global_builder.ts +84 -55
  75. package/src/index.ts +1 -3
  76. package/src/publisher/config.ts +45 -32
  77. package/src/publisher/index.ts +4 -0
  78. package/src/publisher/sequencer-publisher-factory.ts +92 -0
  79. package/src/publisher/sequencer-publisher-metrics.ts +30 -64
  80. package/src/publisher/sequencer-publisher.ts +967 -295
  81. package/src/sequencer/README.md +531 -0
  82. package/src/sequencer/checkpoint_proposal_job.ts +845 -0
  83. package/src/sequencer/checkpoint_voter.ts +130 -0
  84. package/src/sequencer/config.ts +8 -0
  85. package/src/sequencer/errors.ts +21 -0
  86. package/src/sequencer/events.ts +27 -0
  87. package/src/sequencer/index.ts +3 -1
  88. package/src/sequencer/metrics.ts +269 -72
  89. package/src/sequencer/sequencer.ts +708 -588
  90. package/src/sequencer/timetable.ts +221 -62
  91. package/src/sequencer/types.ts +6 -0
  92. package/src/sequencer/utils.ts +28 -60
  93. package/src/test/index.ts +12 -4
  94. package/src/test/mock_checkpoint_builder.ts +311 -0
  95. package/src/test/utils.ts +164 -0
  96. package/dest/sequencer/allowed.d.ts +0 -3
  97. package/dest/sequencer/allowed.d.ts.map +0 -1
  98. package/dest/sequencer/allowed.js +0 -27
  99. package/dest/slasher/factory.d.ts +0 -7
  100. package/dest/slasher/factory.d.ts.map +0 -1
  101. package/dest/slasher/factory.js +0 -8
  102. package/dest/slasher/index.d.ts +0 -3
  103. package/dest/slasher/index.d.ts.map +0 -1
  104. package/dest/slasher/index.js +0 -2
  105. package/dest/slasher/slasher_client.d.ts +0 -75
  106. package/dest/slasher/slasher_client.d.ts.map +0 -1
  107. package/dest/slasher/slasher_client.js +0 -132
  108. package/dest/tx_validator/archive_cache.d.ts +0 -14
  109. package/dest/tx_validator/archive_cache.d.ts.map +0 -1
  110. package/dest/tx_validator/archive_cache.js +0 -22
  111. package/dest/tx_validator/gas_validator.d.ts +0 -14
  112. package/dest/tx_validator/gas_validator.d.ts.map +0 -1
  113. package/dest/tx_validator/gas_validator.js +0 -78
  114. package/dest/tx_validator/nullifier_cache.d.ts +0 -16
  115. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  116. package/dest/tx_validator/nullifier_cache.js +0 -24
  117. package/dest/tx_validator/phases_validator.d.ts +0 -12
  118. package/dest/tx_validator/phases_validator.d.ts.map +0 -1
  119. package/dest/tx_validator/phases_validator.js +0 -80
  120. package/dest/tx_validator/test_utils.d.ts +0 -23
  121. package/dest/tx_validator/test_utils.d.ts.map +0 -1
  122. package/dest/tx_validator/test_utils.js +0 -26
  123. package/dest/tx_validator/tx_validator_factory.d.ts +0 -18
  124. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  125. package/dest/tx_validator/tx_validator_factory.js +0 -50
  126. package/src/sequencer/allowed.ts +0 -36
  127. package/src/slasher/factory.ts +0 -15
  128. package/src/slasher/index.ts +0 -2
  129. package/src/slasher/slasher_client.ts +0 -193
  130. package/src/tx_validator/archive_cache.ts +0 -28
  131. package/src/tx_validator/gas_validator.ts +0 -101
  132. package/src/tx_validator/nullifier_cache.ts +0 -30
  133. package/src/tx_validator/phases_validator.ts +0 -98
  134. package/src/tx_validator/test_utils.ts +0 -48
  135. package/src/tx_validator/tx_validator_factory.ts +0 -120
@@ -0,0 +1,130 @@
1
+ import type { SlotNumber } from '@aztec/foundation/branded-types';
2
+ import type { EthAddress } from '@aztec/foundation/eth-address';
3
+ import type { Logger } from '@aztec/foundation/log';
4
+ import type { SlasherClientInterface } from '@aztec/slasher';
5
+ import { getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
6
+ import type { ResolvedSequencerConfig } from '@aztec/stdlib/interfaces/server';
7
+ import type { ValidatorClient } from '@aztec/validator-client';
8
+ import { DutyAlreadySignedError } from '@aztec/validator-ha-signer/errors';
9
+ import { DutyType, type SigningContext } from '@aztec/validator-ha-signer/types';
10
+
11
+ import type { TypedDataDefinition } from 'viem';
12
+
13
+ import type { SequencerPublisher } from '../publisher/sequencer-publisher.js';
14
+ import type { SequencerMetrics } from './metrics.js';
15
+ import type { SequencerRollupConstants } from './types.js';
16
+
17
+ /**
18
+ * Handles governance and slashing voting for a given slot.
19
+ */
20
+ export class CheckpointVoter {
21
+ private slotTimestamp: bigint;
22
+ private governanceSigner: (msg: TypedDataDefinition) => Promise<`0x${string}`>;
23
+ private slashingSigner: (msg: TypedDataDefinition) => Promise<`0x${string}`>;
24
+
25
+ constructor(
26
+ private readonly slot: SlotNumber,
27
+ private readonly publisher: SequencerPublisher,
28
+ private readonly attestorAddress: EthAddress,
29
+ private readonly validatorClient: ValidatorClient,
30
+ private readonly slasherClient: SlasherClientInterface | undefined,
31
+ private readonly l1Constants: SequencerRollupConstants,
32
+ private readonly config: ResolvedSequencerConfig,
33
+ private readonly metrics: SequencerMetrics,
34
+ private readonly log: Logger,
35
+ ) {
36
+ this.slotTimestamp = getTimestampForSlot(this.slot, this.l1Constants);
37
+
38
+ // Create separate signers with appropriate duty contexts for governance and slashing votes
39
+ // These use HA protection to ensure only one node signs per slot/duty
40
+ const governanceContext: SigningContext = { slot: this.slot, dutyType: DutyType.GOVERNANCE_VOTE };
41
+ this.governanceSigner = (msg: TypedDataDefinition) =>
42
+ this.validatorClient.signWithAddress(this.attestorAddress, msg, governanceContext).then(s => s.toString());
43
+
44
+ const slashingContext: SigningContext = { slot: this.slot, dutyType: DutyType.SLASHING_VOTE };
45
+ this.slashingSigner = (msg: TypedDataDefinition) =>
46
+ this.validatorClient.signWithAddress(this.attestorAddress, msg, slashingContext).then(s => s.toString());
47
+ }
48
+
49
+ /**
50
+ * Enqueues governance and slashing votes with the publisher.
51
+ * Returns a tuple of promises that resolve to whether each vote was successfully enqueued.
52
+ */
53
+ enqueueVotes(): [Promise<boolean | undefined>, Promise<boolean | undefined>] {
54
+ try {
55
+ const enqueueGovernancePromise = this.enqueueGovernanceVote();
56
+ const enqueueSlashingPromise = this.enqueueSlashingVote();
57
+
58
+ return [enqueueGovernancePromise, enqueueSlashingPromise];
59
+ } catch (err) {
60
+ this.log.error(`Error enqueueing governance and slashing votes`, err);
61
+ return [Promise.resolve(false), Promise.resolve(false)];
62
+ }
63
+ }
64
+
65
+ private async enqueueGovernanceVote(): Promise<boolean | undefined> {
66
+ const governanceProposerPayload = this.config.governanceProposerPayload;
67
+ if (!governanceProposerPayload || governanceProposerPayload.isZero()) {
68
+ return undefined;
69
+ }
70
+
71
+ this.log.info(`Enqueuing vote for ${governanceProposerPayload} governance for slot ${this.slot}`, {
72
+ slot: this.slot,
73
+ governanceProposerPayload: governanceProposerPayload.toString(),
74
+ });
75
+
76
+ try {
77
+ return await this.publisher.enqueueGovernanceCastSignal(
78
+ governanceProposerPayload,
79
+ this.slot,
80
+ this.slotTimestamp,
81
+ this.attestorAddress,
82
+ this.governanceSigner,
83
+ );
84
+ } catch (err) {
85
+ if (err instanceof DutyAlreadySignedError) {
86
+ this.log.info(`Governance vote already signed by another node`, {
87
+ slot: this.slot,
88
+ signedByNode: err.signedByNode,
89
+ });
90
+ } else {
91
+ this.log.error(`Error enqueueing governance vote`, err);
92
+ }
93
+ return false;
94
+ }
95
+ }
96
+
97
+ private async enqueueSlashingVote(): Promise<boolean | undefined> {
98
+ try {
99
+ const actions = await this.slasherClient?.getProposerActions(this.slot);
100
+ if (!actions || actions.length === 0) {
101
+ return undefined;
102
+ }
103
+
104
+ this.log.info(`Enqueuing vote for ${actions.length} slashing actions for slot ${this.slot}`, {
105
+ slot: this.slot,
106
+ actionCount: actions.length,
107
+ });
108
+
109
+ this.metrics.recordSlashingAttempt(actions.length);
110
+
111
+ return await this.publisher.enqueueSlashingActions(
112
+ actions,
113
+ this.slot,
114
+ this.slotTimestamp,
115
+ this.attestorAddress,
116
+ this.slashingSigner,
117
+ );
118
+ } catch (err) {
119
+ if (err instanceof DutyAlreadySignedError) {
120
+ this.log.info(`Slashing vote already signed by another node`, {
121
+ slot: this.slot,
122
+ signedByNode: err.signedByNode,
123
+ });
124
+ } else {
125
+ this.log.error(`Error enqueueing slashing vote`, err);
126
+ }
127
+ return false;
128
+ }
129
+ }
130
+ }
@@ -1 +1,9 @@
1
+ import type { GovernanceProposerContract } from '@aztec/ethereum/contracts';
2
+ import type { RollupContract } from '@aztec/ethereum/contracts/rollup';
3
+
1
4
  export { type SequencerConfig } from '@aztec/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,27 @@
1
+ import type { BlockNumber, CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
2
+
3
+ import type { Action } from '../publisher/sequencer-publisher.js';
4
+ import type { SequencerState } from './utils.js';
5
+
6
+ export type SequencerEvents = {
7
+ ['state-changed']: (args: {
8
+ oldState: SequencerState;
9
+ newState: SequencerState;
10
+ secondsIntoSlot?: number;
11
+ slot?: SlotNumber;
12
+ }) => void;
13
+ ['proposer-rollup-check-failed']: (args: { reason: string; slot: SlotNumber }) => void;
14
+ ['block-tx-count-check-failed']: (args: { minTxs: number; availableTxs: number; slot: SlotNumber }) => void;
15
+ ['block-build-failed']: (args: { reason: string; slot: SlotNumber }) => void;
16
+ ['block-proposed']: (args: { blockNumber: BlockNumber; slot: SlotNumber }) => void;
17
+ ['checkpoint-empty']: (args: { slot: SlotNumber }) => void;
18
+ ['checkpoint-publish-failed']: (args: {
19
+ slot: SlotNumber;
20
+ successfulActions?: Action[];
21
+ failedActions?: Action[];
22
+ sentActions?: Action[];
23
+ expiredActions?: Action[];
24
+ }) => void;
25
+ ['checkpoint-published']: (args: { checkpoint: CheckpointNumber; slot: SlotNumber }) => void;
26
+ ['checkpoint-error']: (args: { error: Error }) => void;
27
+ };
@@ -1,3 +1,5 @@
1
+ export * from './checkpoint_proposal_job.js';
2
+ export * from './checkpoint_voter.js';
1
3
  export * from './config.js';
4
+ export * from './events.js';
2
5
  export * from './sequencer.js';
3
- export * from './allowed.js';
@@ -1,108 +1,168 @@
1
+ import { EthAddress } from '@aztec/aztec.js/addresses';
2
+ import type { RollupContract } from '@aztec/ethereum/contracts';
3
+ import type { L1FeeAnalysisResult } from '@aztec/ethereum/l1-fee-analysis';
4
+ import type { SlotNumber } from '@aztec/foundation/branded-types';
1
5
  import {
2
6
  Attributes,
3
7
  type Gauge,
4
8
  type Histogram,
9
+ type Meter,
5
10
  Metrics,
6
11
  type TelemetryClient,
7
12
  type Tracer,
8
13
  type UpDownCounter,
9
- ValueType,
10
14
  } from '@aztec/telemetry-client';
11
15
 
12
- import { type SequencerState, type SequencerStateCallback, sequencerStateToNumber } from './utils.js';
16
+ import { type Hex, formatUnits } from 'viem';
13
17
 
18
+ import type { SequencerState } from './utils.js';
19
+
20
+ // TODO(palla/mbps): Review all metrics and add any missing ones per checkpoint
14
21
  export class SequencerMetrics {
15
22
  public readonly tracer: Tracer;
23
+ private meter: Meter;
16
24
 
17
25
  private blockCounter: UpDownCounter;
18
26
  private blockBuildDuration: Histogram;
19
27
  private blockBuildManaPerSecond: Gauge;
20
28
  private stateTransitionBufferDuration: Histogram;
21
- private currentBlockNumber: Gauge;
22
- private currentBlockSize: Gauge;
23
- private blockBuilderInsertions: Histogram;
24
29
 
30
+ // these are gauges because for individual sequencers building a block is not something that happens often enough to warrant a histogram
25
31
  private timeToCollectAttestations: Gauge;
32
+ private allowanceToCollectAttestations: Gauge;
33
+ private requiredAttestions: Gauge;
34
+ private collectedAttestions: Gauge;
35
+
36
+ private rewards: Gauge;
37
+
38
+ private slots: UpDownCounter;
39
+ private filledSlots: UpDownCounter;
40
+
41
+ private blockProposalFailed: UpDownCounter;
42
+ private blockProposalSuccess: UpDownCounter;
43
+ private blockProposalPrecheckFailed: UpDownCounter;
44
+ private checkpointSuccess: UpDownCounter;
45
+ private slashingAttempts: UpDownCounter;
46
+ private checkpointAttestationDelay: Histogram;
47
+
48
+ // Fisherman fee analysis metrics
49
+ private fishermanWouldBeIncluded: UpDownCounter;
50
+ private fishermanTimeBeforeBlock: Histogram;
51
+ private fishermanPendingBlobTxCount: Histogram;
52
+ private fishermanIncludedBlobTxCount: Histogram;
53
+ private fishermanCalculatedPriorityFee: Histogram;
54
+ private fishermanPriorityFeeDelta: Histogram;
55
+ private fishermanEstimatedCost: Histogram;
56
+ private fishermanEstimatedOverpayment: Histogram;
57
+ private fishermanMinedBlobTxPriorityFee: Histogram;
58
+ private fishermanMinedBlobTxTotalCost: Histogram;
26
59
 
27
- constructor(client: TelemetryClient, getState: SequencerStateCallback, name = 'Sequencer') {
28
- const meter = client.getMeter(name);
60
+ private lastSeenSlot?: SlotNumber;
61
+
62
+ constructor(
63
+ client: TelemetryClient,
64
+ private rollup: RollupContract,
65
+ name = 'Sequencer',
66
+ ) {
67
+ this.meter = client.getMeter(name);
29
68
  this.tracer = client.getTracer(name);
30
69
 
31
- this.blockCounter = meter.createUpDownCounter(Metrics.SEQUENCER_BLOCK_COUNT);
70
+ this.blockCounter = this.meter.createUpDownCounter(Metrics.SEQUENCER_BLOCK_COUNT);
32
71
 
33
- this.blockBuildDuration = meter.createHistogram(Metrics.SEQUENCER_BLOCK_BUILD_DURATION, {
34
- unit: 'ms',
35
- description: 'Duration to build a block',
36
- valueType: ValueType.INT,
37
- });
72
+ this.blockBuildDuration = this.meter.createHistogram(Metrics.SEQUENCER_BLOCK_BUILD_DURATION);
38
73
 
39
- this.blockBuildManaPerSecond = meter.createGauge(Metrics.SEQUENCER_BLOCK_BUILD_MANA_PER_SECOND, {
40
- unit: 'mana/s',
41
- description: 'Mana per second when building a block',
42
- valueType: ValueType.INT,
43
- });
74
+ this.blockBuildManaPerSecond = this.meter.createGauge(Metrics.SEQUENCER_BLOCK_BUILD_MANA_PER_SECOND);
44
75
 
45
- this.stateTransitionBufferDuration = meter.createHistogram(Metrics.SEQUENCER_STATE_TRANSITION_BUFFER_DURATION, {
46
- unit: 'ms',
47
- description:
48
- 'The time difference between when the sequencer needed to transition to a new state and when it actually did.',
49
- valueType: ValueType.INT,
50
- });
76
+ this.stateTransitionBufferDuration = this.meter.createHistogram(Metrics.SEQUENCER_STATE_TRANSITION_BUFFER_DURATION);
51
77
 
52
- const currentState = meter.createObservableGauge(Metrics.SEQUENCER_CURRENT_STATE, {
53
- description: 'Current state of the sequencer',
54
- });
78
+ this.checkpointAttestationDelay = this.meter.createHistogram(Metrics.SEQUENCER_CHECKPOINT_ATTESTATION_DELAY);
55
79
 
56
- currentState.addCallback(observer => {
57
- observer.observe(sequencerStateToNumber(getState()));
80
+ // Init gauges and counters
81
+ this.blockCounter.add(0, {
82
+ [Attributes.STATUS]: 'failed',
58
83
  });
59
-
60
- this.currentBlockNumber = meter.createGauge(Metrics.SEQUENCER_CURRENT_BLOCK_NUMBER, {
61
- description: 'Current block number',
62
- valueType: ValueType.INT,
84
+ this.blockCounter.add(0, {
85
+ [Attributes.STATUS]: 'built',
63
86
  });
64
87
 
65
- this.currentBlockSize = meter.createGauge(Metrics.SEQUENCER_CURRENT_BLOCK_SIZE, {
66
- description: 'Current block size',
67
- valueType: ValueType.INT,
68
- });
88
+ this.rewards = this.meter.createGauge(Metrics.SEQUENCER_CURRENT_BLOCK_REWARDS);
69
89
 
70
- this.timeToCollectAttestations = meter.createGauge(Metrics.SEQUENCER_TIME_TO_COLLECT_ATTESTATIONS, {
71
- description: 'The time spent collecting attestations from committee members',
72
- valueType: ValueType.INT,
73
- });
90
+ this.slots = this.meter.createUpDownCounter(Metrics.SEQUENCER_SLOT_COUNT);
74
91
 
75
- this.blockBuilderInsertions = meter.createHistogram(Metrics.SEQUENCER_BLOCK_BUILD_INSERTION_TIME, {
76
- description: 'Timer for tree insertions performed by the block builder',
77
- unit: 'us',
78
- valueType: ValueType.INT,
79
- });
92
+ /**
93
+ * NOTE: we do not track missed slots as a separate metric. That would be difficult to determine
94
+ * Instead, use a computed metric, `slots - filledSlots` to get the number of slots a sequencer has missed.
95
+ */
96
+ this.filledSlots = this.meter.createUpDownCounter(Metrics.SEQUENCER_FILLED_SLOT_COUNT);
80
97
 
81
- this.setCurrentBlock(0, 0);
82
- }
98
+ this.timeToCollectAttestations = this.meter.createGauge(Metrics.SEQUENCER_COLLECT_ATTESTATIONS_DURATION);
99
+
100
+ this.allowanceToCollectAttestations = this.meter.createGauge(Metrics.SEQUENCER_COLLECT_ATTESTATIONS_TIME_ALLOWANCE);
101
+
102
+ this.requiredAttestions = this.meter.createGauge(Metrics.SEQUENCER_REQUIRED_ATTESTATIONS_COUNT);
83
103
 
84
- startCollectingAttestationsTimer(): () => void {
85
- const startTime = Date.now();
86
- const stop = () => {
87
- const duration = Date.now() - startTime;
88
- this.recordTimeToCollectAttestations(duration);
89
- };
90
- return stop.bind(this);
104
+ this.collectedAttestions = this.meter.createGauge(Metrics.SEQUENCER_COLLECTED_ATTESTATIONS_COUNT);
105
+
106
+ this.blockProposalFailed = this.meter.createUpDownCounter(Metrics.SEQUENCER_BLOCK_PROPOSAL_FAILED_COUNT);
107
+
108
+ this.blockProposalSuccess = this.meter.createUpDownCounter(Metrics.SEQUENCER_BLOCK_PROPOSAL_SUCCESS_COUNT);
109
+
110
+ this.checkpointSuccess = this.meter.createUpDownCounter(Metrics.SEQUENCER_CHECKPOINT_SUCCESS_COUNT);
111
+
112
+ this.blockProposalPrecheckFailed = this.meter.createUpDownCounter(
113
+ Metrics.SEQUENCER_BLOCK_PROPOSAL_PRECHECK_FAILED_COUNT,
114
+ );
115
+
116
+ this.slashingAttempts = this.meter.createUpDownCounter(Metrics.SEQUENCER_SLASHING_ATTEMPTS_COUNT);
117
+
118
+ // Fisherman fee analysis metrics
119
+ this.fishermanWouldBeIncluded = this.meter.createUpDownCounter(Metrics.FISHERMAN_FEE_ANALYSIS_WOULD_BE_INCLUDED);
120
+
121
+ this.fishermanTimeBeforeBlock = this.meter.createHistogram(Metrics.FISHERMAN_FEE_ANALYSIS_TIME_BEFORE_BLOCK);
122
+
123
+ this.fishermanPendingBlobTxCount = this.meter.createHistogram(Metrics.FISHERMAN_FEE_ANALYSIS_PENDING_BLOB_TX_COUNT);
124
+
125
+ this.fishermanIncludedBlobTxCount = this.meter.createHistogram(
126
+ Metrics.FISHERMAN_FEE_ANALYSIS_INCLUDED_BLOB_TX_COUNT,
127
+ );
128
+
129
+ this.fishermanCalculatedPriorityFee = this.meter.createHistogram(
130
+ Metrics.FISHERMAN_FEE_ANALYSIS_CALCULATED_PRIORITY_FEE,
131
+ );
132
+
133
+ this.fishermanPriorityFeeDelta = this.meter.createHistogram(Metrics.FISHERMAN_FEE_ANALYSIS_PRIORITY_FEE_DELTA);
134
+
135
+ this.fishermanEstimatedCost = this.meter.createHistogram(Metrics.FISHERMAN_FEE_ANALYSIS_ESTIMATED_COST);
136
+
137
+ this.fishermanEstimatedOverpayment = this.meter.createHistogram(
138
+ Metrics.FISHERMAN_FEE_ANALYSIS_ESTIMATED_OVERPAYMENT,
139
+ );
140
+
141
+ this.fishermanMinedBlobTxPriorityFee = this.meter.createHistogram(
142
+ Metrics.FISHERMAN_FEE_ANALYSIS_MINED_BLOB_TX_PRIORITY_FEE,
143
+ );
144
+
145
+ this.fishermanMinedBlobTxTotalCost = this.meter.createHistogram(
146
+ Metrics.FISHERMAN_FEE_ANALYSIS_MINED_BLOB_TX_TOTAL_COST,
147
+ );
91
148
  }
92
149
 
93
- recordTimeToCollectAttestations(time: number) {
94
- this.timeToCollectAttestations.record(time);
150
+ public recordRequiredAttestations(requiredAttestationsCount: number, allowanceMs: number) {
151
+ this.requiredAttestions.record(requiredAttestationsCount);
152
+ this.allowanceToCollectAttestations.record(Math.ceil(allowanceMs));
153
+
154
+ // reset
155
+ this.collectedAttestions.record(0);
156
+ this.timeToCollectAttestations.record(0);
95
157
  }
96
158
 
97
- recordBlockBuilderTreeInsertions(timeUs: number) {
98
- this.blockBuilderInsertions.record(Math.ceil(timeUs));
159
+ public recordCheckpointAttestationDelay(duration: number) {
160
+ this.checkpointAttestationDelay.record(duration);
99
161
  }
100
162
 
101
- recordCancelledBlock() {
102
- this.blockCounter.add(1, {
103
- [Attributes.STATUS]: 'cancelled',
104
- });
105
- this.setCurrentBlock(0, 0);
163
+ public recordCollectedAttestations(count: number, durationMs: number) {
164
+ this.collectedAttestions.record(count);
165
+ this.timeToCollectAttestations.record(Math.ceil(durationMs));
106
166
  }
107
167
 
108
168
  recordBuiltBlock(buildDurationMs: number, totalMana: number) {
@@ -117,11 +177,6 @@ export class SequencerMetrics {
117
177
  this.blockCounter.add(1, {
118
178
  [Attributes.STATUS]: 'failed',
119
179
  });
120
- this.setCurrentBlock(0, 0);
121
- }
122
-
123
- recordNewBlock(blockNumber: number, txCount: number) {
124
- this.setCurrentBlock(blockNumber, txCount);
125
180
  }
126
181
 
127
182
  recordStateTransitionBufferMs(durationMs: number, state: SequencerState) {
@@ -130,8 +185,150 @@ export class SequencerMetrics {
130
185
  });
131
186
  }
132
187
 
133
- private setCurrentBlock(blockNumber: number, txCount: number) {
134
- this.currentBlockNumber.record(blockNumber);
135
- this.currentBlockSize.record(txCount);
188
+ incOpenSlot(slot: SlotNumber, proposer: string) {
189
+ // sequencer went through the loop a second time. Noop
190
+ if (slot === this.lastSeenSlot) {
191
+ return;
192
+ }
193
+
194
+ this.slots.add(1, {
195
+ [Attributes.BLOCK_PROPOSER]: proposer,
196
+ });
197
+
198
+ this.lastSeenSlot = slot;
199
+ }
200
+
201
+ async incFilledSlot(proposer: string, coinbase: Hex | EthAddress | undefined): Promise<void> {
202
+ this.filledSlots.add(1, {
203
+ [Attributes.BLOCK_PROPOSER]: proposer,
204
+ });
205
+ this.lastSeenSlot = undefined;
206
+
207
+ if (coinbase) {
208
+ try {
209
+ const rewards = await this.rollup.getSequencerRewards(coinbase);
210
+ const fmt = parseFloat(formatUnits(rewards, 18));
211
+ this.rewards.record(fmt, {
212
+ [Attributes.COINBASE]: coinbase.toString(),
213
+ });
214
+ } catch {
215
+ // no-op
216
+ }
217
+ }
218
+ }
219
+
220
+ recordCheckpointSuccess() {
221
+ this.checkpointSuccess.add(1);
222
+ }
223
+
224
+ recordBlockProposalFailed(reason?: string) {
225
+ this.blockProposalFailed.add(1, {
226
+ ...(reason && { [Attributes.ERROR_TYPE]: reason }),
227
+ });
228
+ }
229
+
230
+ recordBlockProposalSuccess() {
231
+ this.blockProposalSuccess.add(1);
232
+ }
233
+
234
+ recordBlockProposalPrecheckFailed(checkType: string) {
235
+ this.blockProposalPrecheckFailed.add(1, {
236
+ [Attributes.ERROR_TYPE]: checkType,
237
+ });
238
+ }
239
+
240
+ recordSlashingAttempt(actionCount: number) {
241
+ this.slashingAttempts.add(actionCount);
242
+ }
243
+
244
+ /**
245
+ * Records metrics for a completed fisherman fee analysis
246
+ * @param analysis - The completed fee analysis result
247
+ */
248
+ recordFishermanFeeAnalysis(analysis: L1FeeAnalysisResult) {
249
+ // In fisherman mode, we should always have strategy results
250
+ if (!analysis.computedPrices.strategyResults || analysis.computedPrices.strategyResults.length === 0) {
251
+ // This should never happen in fisherman mode - log an error
252
+ // We don't record metrics without strategy IDs as that defeats the purpose
253
+ throw new Error(
254
+ `No strategy results found in fisherman fee analysis ${analysis.id}. This indicates a bug in the fee analysis.`,
255
+ );
256
+ }
257
+
258
+ // Record metrics for each strategy separately
259
+ for (const strategyResult of analysis.computedPrices.strategyResults) {
260
+ const strategyAttributes = {
261
+ [Attributes.FISHERMAN_FEE_STRATEGY_ID]: strategyResult.strategyId,
262
+ };
263
+
264
+ // Record pending block snapshot data (once per strategy for comparison)
265
+ this.fishermanPendingBlobTxCount.record(analysis.pendingSnapshot.pendingBlobTxCount, strategyAttributes);
266
+
267
+ // Record mined block data if available
268
+ if (analysis.minedBlock) {
269
+ this.fishermanIncludedBlobTxCount.record(analysis.minedBlock.includedBlobTxCount, strategyAttributes);
270
+
271
+ // Record actual fees from blob transactions in the mined block
272
+ for (const blobTx of analysis.minedBlock.includedBlobTxs) {
273
+ // Record priority fee per gas in Gwei
274
+ const priorityFeeGwei = Number(blobTx.maxPriorityFeePerGas) / 1e9;
275
+ this.fishermanMinedBlobTxPriorityFee.record(priorityFeeGwei, strategyAttributes);
276
+
277
+ // Calculate total cost in ETH
278
+ // Cost = (gas * (baseFee + priorityFee)) + (blobCount * blobGasPerBlob * blobBaseFee)
279
+ const baseFee = analysis.minedBlock.baseFeePerGas;
280
+ const effectiveGasPrice = baseFee + blobTx.maxPriorityFeePerGas;
281
+
282
+ // Calculate execution cost using actual gas limit from the transaction
283
+ const executionCost = blobTx.gas * effectiveGasPrice;
284
+
285
+ // Calculate blob cost using maxFeePerBlobGas * blobCount * GAS_PER_BLOB
286
+ const blobCost = blobTx.maxFeePerBlobGas * BigInt(blobTx.blobCount) * 131072n; // 128KB per blob
287
+
288
+ const totalCostWei = executionCost + blobCost;
289
+ const totalCostEth = Number(totalCostWei) / 1e18;
290
+
291
+ this.fishermanMinedBlobTxTotalCost.record(totalCostEth, strategyAttributes);
292
+ }
293
+ }
294
+
295
+ // Record the calculated priority fee for this strategy
296
+ const calculatedPriorityFeeGwei = Number(strategyResult.calculatedPriorityFee) / 1e9;
297
+ this.fishermanCalculatedPriorityFee.record(calculatedPriorityFeeGwei, strategyAttributes);
298
+
299
+ // Record analysis results if available
300
+ if (analysis.analysis) {
301
+ this.fishermanTimeBeforeBlock.record(Math.ceil(analysis.analysis.timeBeforeBlockMs), strategyAttributes);
302
+
303
+ // Record strategy-specific inclusion result
304
+ if (strategyResult.wouldBeIncluded !== undefined) {
305
+ if (strategyResult.wouldBeIncluded) {
306
+ this.fishermanWouldBeIncluded.add(1, { ...strategyAttributes, [Attributes.OK]: true });
307
+ } else {
308
+ this.fishermanWouldBeIncluded.add(1, {
309
+ ...strategyAttributes,
310
+ [Attributes.OK]: false,
311
+ ...(strategyResult.exclusionReason && { [Attributes.ERROR_TYPE]: strategyResult.exclusionReason }),
312
+ });
313
+ }
314
+ }
315
+
316
+ // Record strategy-specific priority fee delta
317
+ if (strategyResult.priorityFeeDelta !== undefined) {
318
+ const priorityFeeDeltaGwei = Number(strategyResult.priorityFeeDelta) / 1e9;
319
+ this.fishermanPriorityFeeDelta.record(priorityFeeDeltaGwei, strategyAttributes);
320
+ }
321
+
322
+ // Record estimated cost if available
323
+ if (strategyResult.estimatedCostEth !== undefined) {
324
+ this.fishermanEstimatedCost.record(strategyResult.estimatedCostEth, strategyAttributes);
325
+ }
326
+
327
+ // Record estimated overpayment if available
328
+ if (strategyResult.estimatedOverpaymentEth !== undefined) {
329
+ this.fishermanEstimatedOverpayment.record(strategyResult.estimatedOverpaymentEth, strategyAttributes);
330
+ }
331
+ }
332
+ }
136
333
  }
137
334
  }