@aztec/node-lib 3.0.0-nightly.20251004 → 3.0.0-nightly.20251007

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.
@@ -0,0 +1,264 @@
1
+ import { jsonStringify } from '@aztec/foundation/json-rpc';
2
+ import { createLogger } from '@aztec/foundation/log';
3
+ /**
4
+ * Store for persisting L1 transaction states across all L1TxUtils instances.
5
+ * Each state is stored individually with a unique ID, and blobs are stored separately.
6
+ * @remarks This class lives in this package instead of `ethereum` because it depends on `kv-store`.
7
+ */ export class L1TxStore {
8
+ store;
9
+ log;
10
+ static SCHEMA_VERSION = 2;
11
+ states;
12
+ blobs;
13
+ stateIdCounter;
14
+ constructor(store, log = createLogger('l1-tx-utils:store')){
15
+ this.store = store;
16
+ this.log = log;
17
+ this.states = store.openMap('l1_tx_states');
18
+ this.blobs = store.openMap('l1_tx_blobs');
19
+ this.stateIdCounter = store.openMap('l1_tx_state_id_counter');
20
+ }
21
+ /**
22
+ * Gets the next available state ID for an account.
23
+ */ consumeNextStateId(account) {
24
+ return this.store.transactionAsync(async ()=>{
25
+ const currentId = await this.stateIdCounter.getAsync(account) ?? 0;
26
+ const nextId = currentId + 1;
27
+ await this.stateIdCounter.set(account, nextId);
28
+ return nextId;
29
+ });
30
+ }
31
+ /**
32
+ * Creates a storage key for state/blob data.
33
+ */ makeKey(account, stateId) {
34
+ return `${account}-${stateId.toString().padStart(10, '0')}`;
35
+ }
36
+ /**
37
+ * Saves a single transaction state for a specific account.
38
+ * Blobs are not stored here, use saveBlobs instead.
39
+ * @param account - The sender account address
40
+ * @param state - Transaction state to save
41
+ */ async saveState(account, state) {
42
+ const key = this.makeKey(account, state.id);
43
+ const serializable = this.serializeState(state);
44
+ await this.states.set(key, jsonStringify(serializable));
45
+ this.log.debug(`Saved tx state ${state.id} for account ${account} with nonce ${state.nonce}`);
46
+ return state;
47
+ }
48
+ /**
49
+ * Saves blobs for a given state.
50
+ * @param account - The sender account address
51
+ * @param stateId - The state ID
52
+ * @param blobInputs - Blob inputs to save
53
+ */ async saveBlobs(account, stateId, blobInputs) {
54
+ if (!blobInputs) {
55
+ return;
56
+ }
57
+ const key = this.makeKey(account, stateId);
58
+ const blobData = this.serializeBlobInputs(blobInputs);
59
+ await this.blobs.set(key, jsonStringify(blobData));
60
+ this.log.debug(`Saved blobs for state ${stateId} of account ${account}`);
61
+ }
62
+ /**
63
+ * Loads all transaction states for a specific account.
64
+ * @param account - The sender account address
65
+ * @returns Array of transaction states with their IDs
66
+ */ async loadStates(account) {
67
+ const states = [];
68
+ const prefix = `${account}-`;
69
+ for await (const [key, stateJson] of this.states.entriesAsync({
70
+ start: prefix,
71
+ end: `${prefix}Z`
72
+ })){
73
+ const [keyAccount, stateIdStr] = key.split('-');
74
+ if (keyAccount !== account) {
75
+ throw new Error(`Mismatched account in key: expected ${account} but got ${keyAccount}`);
76
+ }
77
+ const stateId = parseInt(stateIdStr, 10);
78
+ try {
79
+ const serialized = JSON.parse(stateJson);
80
+ // Load blobs if they exist
81
+ let blobInputs;
82
+ if (serialized.hasBlobInputs) {
83
+ const blobJson = await this.blobs.getAsync(key);
84
+ if (blobJson) {
85
+ blobInputs = this.deserializeBlobInputs(JSON.parse(blobJson), serialized.blobMetadata);
86
+ }
87
+ }
88
+ const state = this.deserializeState(serialized, blobInputs);
89
+ states.push({
90
+ ...state,
91
+ id: stateId
92
+ });
93
+ } catch (err) {
94
+ this.log.error(`Failed to deserialize state ${key}`, err);
95
+ }
96
+ }
97
+ // Sort by ID
98
+ states.sort((a, b)=>a.id - b.id);
99
+ this.log.debug(`Loaded ${states.length} tx states for account ${account}`);
100
+ return states;
101
+ }
102
+ /**
103
+ * Loads a single state by ID.
104
+ * @param account - The sender account address
105
+ * @param stateId - The state ID
106
+ * @returns The transaction state or undefined if not found
107
+ */ async loadState(account, stateId) {
108
+ const key = this.makeKey(account, stateId);
109
+ const stateJson = await this.states.getAsync(key);
110
+ if (!stateJson) {
111
+ return undefined;
112
+ }
113
+ try {
114
+ const serialized = JSON.parse(stateJson);
115
+ // Load blobs if they exist
116
+ let blobInputs;
117
+ if (serialized.hasBlobInputs) {
118
+ const blobJson = await this.blobs.getAsync(key);
119
+ if (blobJson) {
120
+ blobInputs = this.deserializeBlobInputs(JSON.parse(blobJson), serialized.blobMetadata);
121
+ }
122
+ }
123
+ const state = this.deserializeState(serialized, blobInputs);
124
+ return {
125
+ ...state,
126
+ id: stateId
127
+ };
128
+ } catch (err) {
129
+ this.log.error(`Failed to deserialize state ${key}`, err);
130
+ return undefined;
131
+ }
132
+ }
133
+ /**
134
+ * Deletes a specific state and its associated blobs.
135
+ * @param account - The sender account address
136
+ * @param stateId - The state ID to delete
137
+ */ async deleteState(account, stateId) {
138
+ const key = this.makeKey(account, stateId);
139
+ await this.states.delete(key);
140
+ await this.blobs.delete(key);
141
+ this.log.debug(`Deleted state ${stateId} for account ${account}`);
142
+ }
143
+ /**
144
+ * Clears all transaction states for a specific account.
145
+ * @param account - The sender account address
146
+ */ async clearStates(account) {
147
+ const states = await this.loadStates(account);
148
+ for (const state of states){
149
+ await this.deleteState(account, state.id);
150
+ }
151
+ await this.stateIdCounter.delete(account);
152
+ this.log.info(`Cleared all tx states for account ${account}`);
153
+ }
154
+ /**
155
+ * Gets all accounts that have stored states.
156
+ * @returns Array of account addresses
157
+ */ async getAllAccounts() {
158
+ const accounts = new Set();
159
+ for await (const [key] of this.states.entriesAsync()){
160
+ const account = key.substring(0, key.lastIndexOf('-'));
161
+ accounts.add(account);
162
+ }
163
+ return Array.from(accounts);
164
+ }
165
+ /**
166
+ * Closes the store.
167
+ */ async close() {
168
+ await this.store.close();
169
+ this.log.info('Closed L1 tx state store');
170
+ }
171
+ /**
172
+ * Serializes an L1TxState for storage.
173
+ */ serializeState(state) {
174
+ const txConfigOverrides = {
175
+ ...state.txConfigOverrides,
176
+ gasLimit: state.txConfigOverrides.gasLimit?.toString(),
177
+ txTimeoutAt: state.txConfigOverrides.txTimeoutAt?.getTime()
178
+ };
179
+ return {
180
+ id: state.id,
181
+ txHashes: state.txHashes,
182
+ cancelTxHashes: state.cancelTxHashes,
183
+ gasLimit: state.gasLimit.toString(),
184
+ gasPrice: {
185
+ maxFeePerGas: state.gasPrice.maxFeePerGas.toString(),
186
+ maxPriorityFeePerGas: state.gasPrice.maxPriorityFeePerGas.toString(),
187
+ maxFeePerBlobGas: state.gasPrice.maxFeePerBlobGas?.toString()
188
+ },
189
+ txConfigOverrides,
190
+ request: {
191
+ ...state.request,
192
+ value: state.request.value?.toString()
193
+ },
194
+ status: state.status,
195
+ nonce: state.nonce,
196
+ sentAt: state.sentAtL1Ts.getTime(),
197
+ lastSentAt: state.lastSentAtL1Ts.getTime(),
198
+ receipt: state.receipt,
199
+ hasBlobInputs: state.blobInputs !== undefined,
200
+ blobMetadata: state.blobInputs?.maxFeePerBlobGas ? {
201
+ maxFeePerBlobGas: state.blobInputs.maxFeePerBlobGas.toString()
202
+ } : undefined
203
+ };
204
+ }
205
+ /**
206
+ * Deserializes a stored state back to L1TxState.
207
+ */ deserializeState(stored, blobInputs) {
208
+ const txConfigOverrides = {
209
+ ...stored.txConfigOverrides,
210
+ gasLimit: stored.txConfigOverrides.gasLimit !== undefined ? BigInt(stored.txConfigOverrides.gasLimit) : undefined,
211
+ txTimeoutAt: stored.txConfigOverrides.txTimeoutAt !== undefined ? new Date(stored.txConfigOverrides.txTimeoutAt) : undefined
212
+ };
213
+ const receipt = stored.receipt ? {
214
+ ...stored.receipt,
215
+ blockNumber: BigInt(stored.receipt.blockNumber),
216
+ cumulativeGasUsed: BigInt(stored.receipt.cumulativeGasUsed),
217
+ effectiveGasPrice: BigInt(stored.receipt.effectiveGasPrice),
218
+ gasUsed: BigInt(stored.receipt.gasUsed)
219
+ } : undefined;
220
+ return {
221
+ id: stored.id,
222
+ txHashes: stored.txHashes,
223
+ cancelTxHashes: stored.cancelTxHashes,
224
+ gasLimit: BigInt(stored.gasLimit),
225
+ gasPrice: {
226
+ maxFeePerGas: BigInt(stored.gasPrice.maxFeePerGas),
227
+ maxPriorityFeePerGas: BigInt(stored.gasPrice.maxPriorityFeePerGas),
228
+ maxFeePerBlobGas: stored.gasPrice.maxFeePerBlobGas ? BigInt(stored.gasPrice.maxFeePerBlobGas) : undefined
229
+ },
230
+ txConfigOverrides,
231
+ request: {
232
+ to: stored.request.to,
233
+ data: stored.request.data,
234
+ value: stored.request.value ? BigInt(stored.request.value) : undefined
235
+ },
236
+ status: stored.status,
237
+ nonce: stored.nonce,
238
+ sentAtL1Ts: new Date(stored.sentAt),
239
+ lastSentAtL1Ts: new Date(stored.lastSentAt),
240
+ receipt,
241
+ blobInputs
242
+ };
243
+ }
244
+ /**
245
+ * Serializes blob inputs for separate storage.
246
+ */ serializeBlobInputs(blobInputs) {
247
+ return {
248
+ blobs: blobInputs.blobs.map((b)=>Buffer.from(b).toString('base64')),
249
+ kzg: jsonStringify(blobInputs.kzg)
250
+ };
251
+ }
252
+ /**
253
+ * Deserializes blob inputs from storage, combining blob data with metadata.
254
+ */ deserializeBlobInputs(stored, metadata) {
255
+ const blobInputs = {
256
+ blobs: stored.blobs.map((b)=>new Uint8Array(Buffer.from(b, 'base64'))),
257
+ kzg: JSON.parse(stored.kzg)
258
+ };
259
+ if (metadata?.maxFeePerBlobGas) {
260
+ blobInputs.maxFeePerBlobGas = BigInt(metadata.maxFeePerBlobGas);
261
+ }
262
+ return blobInputs;
263
+ }
264
+ }
package/package.json CHANGED
@@ -1,10 +1,13 @@
1
1
  {
2
2
  "name": "@aztec/node-lib",
3
- "version": "3.0.0-nightly.20251004",
3
+ "version": "3.0.0-nightly.20251007",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  "./actions": "./dest/actions/index.js",
7
- "./config": "./dest/config/index.js"
7
+ "./config": "./dest/config/index.js",
8
+ "./factories": "./dest/factories/index.js",
9
+ "./metrics": "./dest/metrics/index.js",
10
+ "./stores": "./dest/stores/index.js"
8
11
  },
9
12
  "inherits": [
10
13
  "../package.common.json"
@@ -54,27 +57,28 @@
54
57
  ]
55
58
  },
56
59
  "dependencies": {
57
- "@aztec/archiver": "3.0.0-nightly.20251004",
58
- "@aztec/bb-prover": "3.0.0-nightly.20251004",
59
- "@aztec/blob-sink": "3.0.0-nightly.20251004",
60
- "@aztec/constants": "3.0.0-nightly.20251004",
61
- "@aztec/epoch-cache": "3.0.0-nightly.20251004",
62
- "@aztec/ethereum": "3.0.0-nightly.20251004",
63
- "@aztec/foundation": "3.0.0-nightly.20251004",
64
- "@aztec/kv-store": "3.0.0-nightly.20251004",
65
- "@aztec/merkle-tree": "3.0.0-nightly.20251004",
66
- "@aztec/p2p": "3.0.0-nightly.20251004",
67
- "@aztec/protocol-contracts": "3.0.0-nightly.20251004",
68
- "@aztec/prover-client": "3.0.0-nightly.20251004",
69
- "@aztec/sequencer-client": "3.0.0-nightly.20251004",
70
- "@aztec/simulator": "3.0.0-nightly.20251004",
71
- "@aztec/stdlib": "3.0.0-nightly.20251004",
72
- "@aztec/telemetry-client": "3.0.0-nightly.20251004",
73
- "@aztec/validator-client": "3.0.0-nightly.20251004",
74
- "@aztec/world-state": "3.0.0-nightly.20251004",
60
+ "@aztec/archiver": "3.0.0-nightly.20251007",
61
+ "@aztec/bb-prover": "3.0.0-nightly.20251007",
62
+ "@aztec/blob-sink": "3.0.0-nightly.20251007",
63
+ "@aztec/constants": "3.0.0-nightly.20251007",
64
+ "@aztec/epoch-cache": "3.0.0-nightly.20251007",
65
+ "@aztec/ethereum": "3.0.0-nightly.20251007",
66
+ "@aztec/foundation": "3.0.0-nightly.20251007",
67
+ "@aztec/kv-store": "3.0.0-nightly.20251007",
68
+ "@aztec/merkle-tree": "3.0.0-nightly.20251007",
69
+ "@aztec/p2p": "3.0.0-nightly.20251007",
70
+ "@aztec/protocol-contracts": "3.0.0-nightly.20251007",
71
+ "@aztec/prover-client": "3.0.0-nightly.20251007",
72
+ "@aztec/sequencer-client": "3.0.0-nightly.20251007",
73
+ "@aztec/simulator": "3.0.0-nightly.20251007",
74
+ "@aztec/stdlib": "3.0.0-nightly.20251007",
75
+ "@aztec/telemetry-client": "3.0.0-nightly.20251007",
76
+ "@aztec/validator-client": "3.0.0-nightly.20251007",
77
+ "@aztec/world-state": "3.0.0-nightly.20251007",
75
78
  "tslib": "^2.4.0"
76
79
  },
77
80
  "devDependencies": {
81
+ "@aztec/blob-lib": "3.0.0-nightly.20251007",
78
82
  "@jest/globals": "^30.0.0",
79
83
  "@types/jest": "^30.0.0",
80
84
  "@types/node": "^22.15.17",
@@ -0,0 +1 @@
1
+ export * from './l1_tx_utils.js';
@@ -0,0 +1,122 @@
1
+ import {
2
+ createL1TxUtilsFromEthSigner as createL1TxUtilsFromEthSignerBase,
3
+ createL1TxUtilsFromViemWallet as createL1TxUtilsFromViemWalletBase,
4
+ } from '@aztec/ethereum';
5
+ import type { EthSigner, ExtendedViemWalletClient, L1TxUtilsConfig, ViemClient } from '@aztec/ethereum';
6
+ import {
7
+ createL1TxUtilsWithBlobsFromEthSigner as createL1TxUtilsWithBlobsFromEthSignerBase,
8
+ createL1TxUtilsWithBlobsFromViemWallet as createL1TxUtilsWithBlobsFromViemWalletBase,
9
+ } from '@aztec/ethereum/l1-tx-utils-with-blobs';
10
+ import { omit } from '@aztec/foundation/collection';
11
+ import { createLogger } from '@aztec/foundation/log';
12
+ import type { DateProvider } from '@aztec/foundation/timer';
13
+ import type { DataStoreConfig } from '@aztec/kv-store/config';
14
+ import { createStore } from '@aztec/kv-store/lmdb-v2';
15
+ import type { TelemetryClient } from '@aztec/telemetry-client';
16
+
17
+ import type { L1TxScope } from '../metrics/l1_tx_metrics.js';
18
+ import { L1TxMetrics } from '../metrics/l1_tx_metrics.js';
19
+ import { L1TxStore } from '../stores/l1_tx_store.js';
20
+
21
+ const L1_TX_STORE_NAME = 'l1-tx-utils';
22
+
23
+ /**
24
+ * Creates shared dependencies (logger, store, metrics) for L1TxUtils instances.
25
+ */
26
+ async function createSharedDeps(
27
+ config: DataStoreConfig & { scope?: L1TxScope },
28
+ deps: {
29
+ telemetry: TelemetryClient;
30
+ logger?: ReturnType<typeof createLogger>;
31
+ dateProvider?: DateProvider;
32
+ },
33
+ ) {
34
+ const logger = deps.logger ?? createLogger('l1-tx-utils');
35
+
36
+ // Note that we do NOT bind them to the rollup address, since we still need to
37
+ // monitor and cancel txs for previous rollups to free up our nonces.
38
+ const noRollupConfig = omit(config, 'l1Contracts');
39
+ const kvStore = await createStore(L1_TX_STORE_NAME, L1TxStore.SCHEMA_VERSION, noRollupConfig, logger);
40
+ const store = new L1TxStore(kvStore, logger);
41
+
42
+ const meter = deps.telemetry.getMeter('L1TxUtils');
43
+ const metrics = new L1TxMetrics(meter, config.scope ?? 'other', logger);
44
+
45
+ return { logger, store, metrics, dateProvider: deps.dateProvider };
46
+ }
47
+
48
+ /**
49
+ * Creates L1TxUtils with blobs from multiple Viem wallets, sharing store and metrics.
50
+ */
51
+ export async function createL1TxUtilsWithBlobsFromViemWallet(
52
+ clients: ExtendedViemWalletClient[],
53
+ config: DataStoreConfig & Partial<L1TxUtilsConfig> & { debugMaxGasLimit?: boolean; scope?: L1TxScope },
54
+ deps: {
55
+ telemetry: TelemetryClient;
56
+ logger?: ReturnType<typeof createLogger>;
57
+ dateProvider?: DateProvider;
58
+ },
59
+ ) {
60
+ const sharedDeps = await createSharedDeps(config, deps);
61
+
62
+ return clients.map(client =>
63
+ createL1TxUtilsWithBlobsFromViemWalletBase(client, sharedDeps, config, config.debugMaxGasLimit),
64
+ );
65
+ }
66
+
67
+ /**
68
+ * Creates L1TxUtils with blobs from multiple EthSigners, sharing store and metrics.
69
+ */
70
+ export async function createL1TxUtilsWithBlobsFromEthSigner(
71
+ client: ViemClient,
72
+ signers: EthSigner[],
73
+ config: DataStoreConfig & Partial<L1TxUtilsConfig> & { debugMaxGasLimit?: boolean; scope?: L1TxScope },
74
+ deps: {
75
+ telemetry: TelemetryClient;
76
+ logger?: ReturnType<typeof createLogger>;
77
+ dateProvider?: DateProvider;
78
+ },
79
+ ) {
80
+ const sharedDeps = await createSharedDeps(config, deps);
81
+
82
+ return signers.map(signer =>
83
+ createL1TxUtilsWithBlobsFromEthSignerBase(client, signer, sharedDeps, config, config.debugMaxGasLimit),
84
+ );
85
+ }
86
+
87
+ /**
88
+ * Creates L1TxUtils (without blobs) from multiple Viem wallets, sharing store and metrics.
89
+ */
90
+ export async function createL1TxUtilsFromViemWalletWithStore(
91
+ clients: ExtendedViemWalletClient[],
92
+ config: DataStoreConfig & Partial<L1TxUtilsConfig> & { debugMaxGasLimit?: boolean; scope?: L1TxScope },
93
+ deps: {
94
+ telemetry: TelemetryClient;
95
+ logger?: ReturnType<typeof createLogger>;
96
+ dateProvider?: DateProvider;
97
+ scope?: L1TxScope;
98
+ },
99
+ ) {
100
+ const sharedDeps = await createSharedDeps(config, deps);
101
+
102
+ return clients.map(client => createL1TxUtilsFromViemWalletBase(client, sharedDeps, config));
103
+ }
104
+
105
+ /**
106
+ * Creates L1TxUtils (without blobs) from multiple EthSigners, sharing store and metrics.
107
+ */
108
+ export async function createL1TxUtilsFromEthSignerWithStore(
109
+ client: ViemClient,
110
+ signers: EthSigner[],
111
+ config: DataStoreConfig & Partial<L1TxUtilsConfig> & { debugMaxGasLimit?: boolean; scope?: L1TxScope },
112
+ deps: {
113
+ telemetry: TelemetryClient;
114
+ logger?: ReturnType<typeof createLogger>;
115
+ dateProvider?: DateProvider;
116
+ scope?: L1TxScope;
117
+ },
118
+ ) {
119
+ const sharedDeps = await createSharedDeps(config, deps);
120
+
121
+ return signers.map(signer => createL1TxUtilsFromEthSignerBase(client, signer, sharedDeps, config));
122
+ }
@@ -0,0 +1 @@
1
+ export * from './l1_tx_metrics.js';
@@ -0,0 +1,169 @@
1
+ import type { IL1TxMetrics, L1TxState } from '@aztec/ethereum';
2
+ import { TxUtilsState } from '@aztec/ethereum';
3
+ import { createLogger } from '@aztec/foundation/log';
4
+ import {
5
+ Attributes,
6
+ type Histogram,
7
+ type Meter,
8
+ Metrics,
9
+ type UpDownCounter,
10
+ ValueType,
11
+ } from '@aztec/telemetry-client';
12
+
13
+ export type L1TxScope = 'sequencer' | 'prover' | 'other';
14
+
15
+ /**
16
+ * Metrics for L1 transaction utils tracking tx lifecycle and gas costs.
17
+ */
18
+ export class L1TxMetrics implements IL1TxMetrics {
19
+ // Time until tx is mined
20
+ private txMinedDuration: Histogram;
21
+
22
+ // Number of attempts until mined
23
+ private txAttemptsUntilMined: Histogram;
24
+
25
+ // Counters for end states
26
+ private txMinedCount: UpDownCounter;
27
+ private txRevertedCount: UpDownCounter;
28
+ private txCancelledCount: UpDownCounter;
29
+ private txNotMinedCount: UpDownCounter;
30
+
31
+ // Gas price histograms (at end state, in wei)
32
+ private maxPriorityFeeHistogram: Histogram;
33
+ private maxFeeHistogram: Histogram;
34
+ private blobFeeHistogram: Histogram;
35
+
36
+ constructor(
37
+ private meter: Meter,
38
+ private scope: L1TxScope = 'other',
39
+ private logger = createLogger('l1-tx-utils:metrics'),
40
+ ) {
41
+ this.txMinedDuration = this.meter.createHistogram(Metrics.L1_TX_MINED_DURATION, {
42
+ description: 'Time from initial tx send until mined',
43
+ unit: 's',
44
+ valueType: ValueType.INT,
45
+ });
46
+
47
+ this.txAttemptsUntilMined = this.meter.createHistogram(Metrics.L1_TX_ATTEMPTS_UNTIL_MINED, {
48
+ description: 'Number of tx attempts (including speed-ups) until mined',
49
+ unit: 'attempts',
50
+ valueType: ValueType.INT,
51
+ });
52
+
53
+ this.txMinedCount = this.meter.createUpDownCounter(Metrics.L1_TX_MINED_COUNT, {
54
+ description: 'Count of transactions successfully mined',
55
+ valueType: ValueType.INT,
56
+ });
57
+
58
+ this.txRevertedCount = this.meter.createUpDownCounter(Metrics.L1_TX_REVERTED_COUNT, {
59
+ description: 'Count of transactions that reverted',
60
+ valueType: ValueType.INT,
61
+ });
62
+
63
+ this.txCancelledCount = this.meter.createUpDownCounter(Metrics.L1_TX_CANCELLED_COUNT, {
64
+ description: 'Count of transactions cancelled',
65
+ valueType: ValueType.INT,
66
+ });
67
+
68
+ this.txNotMinedCount = this.meter.createUpDownCounter(Metrics.L1_TX_NOT_MINED_COUNT, {
69
+ description: 'Count of transactions not mined (timed out)',
70
+ valueType: ValueType.INT,
71
+ });
72
+
73
+ this.maxPriorityFeeHistogram = this.meter.createHistogram(Metrics.L1_TX_MAX_PRIORITY_FEE, {
74
+ description: 'Max priority fee per gas at tx end state (in wei)',
75
+ unit: 'wei',
76
+ valueType: ValueType.INT,
77
+ });
78
+
79
+ this.maxFeeHistogram = this.meter.createHistogram(Metrics.L1_TX_MAX_FEE, {
80
+ description: 'Max fee per gas at tx end state (in wei)',
81
+ unit: 'wei',
82
+ valueType: ValueType.INT,
83
+ });
84
+
85
+ this.blobFeeHistogram = this.meter.createHistogram(Metrics.L1_TX_BLOB_FEE, {
86
+ description: 'Max fee per blob gas at tx end state (in wei)',
87
+ unit: 'wei',
88
+ valueType: ValueType.INT,
89
+ });
90
+ }
91
+
92
+ /**
93
+ * Records metrics when a transaction is mined.
94
+ * @param state - The L1 transaction state
95
+ * @param l1Timestamp - The current L1 timestamp
96
+ */
97
+ public recordMinedTx(state: L1TxState, l1Timestamp: Date): void {
98
+ if (state.status !== TxUtilsState.MINED) {
99
+ this.logger.warn(
100
+ `Attempted to record mined tx metrics for a tx not in MINED state (state: ${TxUtilsState[state.status]})`,
101
+ { scope: this.scope, nonce: state.nonce },
102
+ );
103
+ return;
104
+ }
105
+
106
+ const attributes = { [Attributes.L1_TX_SCOPE]: this.scope };
107
+ const isCancelTx = state.cancelTxHashes.length > 0;
108
+ const isReverted = state.receipt?.status === 'reverted';
109
+
110
+ if (isCancelTx) {
111
+ this.txCancelledCount.add(1, attributes);
112
+ } else if (isReverted) {
113
+ this.txRevertedCount.add(1, attributes);
114
+ } else {
115
+ this.txMinedCount.add(1, attributes);
116
+ }
117
+
118
+ // Record time to mine using provided L1 timestamp
119
+ const duration = Math.floor((l1Timestamp.getTime() - state.sentAtL1Ts.getTime()) / 1000);
120
+ this.txMinedDuration.record(duration, attributes);
121
+
122
+ // Record number of attempts until mined
123
+ const attempts = isCancelTx ? state.cancelTxHashes.length : state.txHashes.length;
124
+ this.txAttemptsUntilMined.record(attempts, attributes);
125
+
126
+ // Record gas prices at end state (in wei as integers)
127
+ const maxPriorityFeeWei = Number(state.gasPrice.maxPriorityFeePerGas);
128
+ const maxFeeWei = Number(state.gasPrice.maxFeePerGas);
129
+ const blobFeeWei = state.gasPrice.maxFeePerBlobGas ? Number(state.gasPrice.maxFeePerBlobGas) : undefined;
130
+
131
+ this.maxPriorityFeeHistogram.record(maxPriorityFeeWei, attributes);
132
+ this.maxFeeHistogram.record(maxFeeWei, attributes);
133
+
134
+ // Record blob fee if present (in wei as integer)
135
+ if (blobFeeWei !== undefined) {
136
+ this.blobFeeHistogram.record(blobFeeWei, attributes);
137
+ }
138
+
139
+ this.logger.debug(`Recorded tx end state metrics`, {
140
+ status: TxUtilsState[state.status],
141
+ nonce: state.nonce,
142
+ isCancelTx,
143
+ isReverted,
144
+ scope: this.scope,
145
+ maxPriorityFeeWei,
146
+ maxFeeWei,
147
+ blobFeeWei,
148
+ });
149
+ }
150
+
151
+ public recordDroppedTx(state: L1TxState): void {
152
+ if (state.status !== TxUtilsState.NOT_MINED) {
153
+ this.logger.warn(
154
+ `Attempted to record dropped tx metrics for a tx not in NOT_MINED state (state: ${TxUtilsState[state.status]})`,
155
+ { scope: this.scope, nonce: state.nonce },
156
+ );
157
+ return;
158
+ }
159
+
160
+ const attributes = { [Attributes.L1_TX_SCOPE]: this.scope };
161
+ this.txNotMinedCount.add(1, attributes);
162
+
163
+ this.logger.debug(`Recorded tx dropped metrics`, {
164
+ status: TxUtilsState[state.status],
165
+ nonce: state.nonce,
166
+ scope: this.scope,
167
+ });
168
+ }
169
+ }
@@ -0,0 +1 @@
1
+ export * from './l1_tx_store.js';