@aztec-labs/node-lib 6.0.0-nightly.20260829

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +3 -0
  2. package/dest/actions/build-snapshot-metadata.d.ts +5 -0
  3. package/dest/actions/build-snapshot-metadata.d.ts.map +1 -0
  4. package/dest/actions/build-snapshot-metadata.js +19 -0
  5. package/dest/actions/create-backups.d.ts +6 -0
  6. package/dest/actions/create-backups.d.ts.map +1 -0
  7. package/dest/actions/create-backups.js +32 -0
  8. package/dest/actions/index.d.ts +5 -0
  9. package/dest/actions/index.d.ts.map +1 -0
  10. package/dest/actions/index.js +4 -0
  11. package/dest/actions/snapshot-sync.d.ts +29 -0
  12. package/dest/actions/snapshot-sync.d.ts.map +1 -0
  13. package/dest/actions/snapshot-sync.js +238 -0
  14. package/dest/actions/upload-snapshot.d.ts +12 -0
  15. package/dest/actions/upload-snapshot.d.ts.map +1 -0
  16. package/dest/actions/upload-snapshot.js +38 -0
  17. package/dest/config/index.d.ts +23 -0
  18. package/dest/config/index.d.ts.map +1 -0
  19. package/dest/config/index.js +53 -0
  20. package/dest/factories/index.d.ts +2 -0
  21. package/dest/factories/index.d.ts.map +1 -0
  22. package/dest/factories/index.js +1 -0
  23. package/dest/factories/l1_tx_utils.d.ts +66 -0
  24. package/dest/factories/l1_tx_utils.d.ts.map +1 -0
  25. package/dest/factories/l1_tx_utils.js +94 -0
  26. package/dest/metrics/index.d.ts +2 -0
  27. package/dest/metrics/index.d.ts.map +1 -0
  28. package/dest/metrics/index.js +1 -0
  29. package/dest/metrics/l1_tx_metrics.d.ts +29 -0
  30. package/dest/metrics/l1_tx_metrics.d.ts.map +1 -0
  31. package/dest/metrics/l1_tx_metrics.js +111 -0
  32. package/dest/stores/index.d.ts +2 -0
  33. package/dest/stores/index.d.ts.map +1 -0
  34. package/dest/stores/index.js +1 -0
  35. package/dest/stores/l1_tx_store.d.ts +89 -0
  36. package/dest/stores/l1_tx_store.d.ts.map +1 -0
  37. package/dest/stores/l1_tx_store.js +276 -0
  38. package/package.json +102 -0
  39. package/src/actions/build-snapshot-metadata.ts +29 -0
  40. package/src/actions/create-backups.ts +40 -0
  41. package/src/actions/index.ts +4 -0
  42. package/src/actions/snapshot-sync.ts +290 -0
  43. package/src/actions/upload-snapshot.ts +49 -0
  44. package/src/config/index.ts +86 -0
  45. package/src/factories/index.ts +1 -0
  46. package/src/factories/l1_tx_utils.ts +156 -0
  47. package/src/metrics/index.ts +1 -0
  48. package/src/metrics/l1_tx_metrics.ts +140 -0
  49. package/src/stores/index.ts +1 -0
  50. package/src/stores/l1_tx_store.ts +410 -0
@@ -0,0 +1,410 @@
1
+ import type { IL1TxStore, L1BlobInputs, L1TxConfig, L1TxState } from '@aztec-labs/ethereum/l1-tx-utils';
2
+ import { jsonStringify } from '@aztec-labs/foundation/json-rpc';
3
+ import type { Logger } from '@aztec-labs/foundation/log';
4
+ import { createLogger } from '@aztec-labs/foundation/log';
5
+ import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec-labs/kv-store';
6
+ import type { TransactionReceipt } from 'viem';
7
+
8
+ /**
9
+ * Serializable version of L1TxRequest for storage.
10
+ */
11
+ interface SerializableL1TxRequest {
12
+ to: string | null;
13
+ data?: string;
14
+ value?: string;
15
+ }
16
+
17
+ /**
18
+ * Serializable version of FeesPerGas for storage.
19
+ */
20
+ interface SerializableFeesPerGas {
21
+ maxFeePerGas: string;
22
+ maxPriorityFeePerGas: string;
23
+ maxFeePerBlobGas?: string;
24
+ }
25
+
26
+ /**
27
+ * Serializable version of L1TxConfig for storage.
28
+ */
29
+ interface SerializableL1TxConfig {
30
+ gasLimit?: string;
31
+ txTimeoutAt?: number;
32
+ txTimeoutMs?: number;
33
+ checkIntervalMs?: number;
34
+ stallTimeMs?: number;
35
+ priorityFeeRetryBumpPercentage?: number;
36
+ maxSpeedUpAttempts?: number;
37
+ cancelTxOnTimeout?: boolean;
38
+ txCancellationFinalTimeoutMs?: number;
39
+ txUnseenConsideredDroppedMs?: number;
40
+ }
41
+
42
+ /**
43
+ * Serializable version of blob inputs for storage (without the actual blob data).
44
+ */
45
+ interface SerializableBlobMetadata {
46
+ maxFeePerBlobGas?: string;
47
+ }
48
+
49
+ /**
50
+ * Serializable version of L1TxState for storage.
51
+ * Dates and bigints are converted to strings/numbers for JSON serialization.
52
+ * Blob data is NOT included here - it's stored separately.
53
+ */
54
+ interface SerializableL1TxState {
55
+ id: number;
56
+ txHashes: string[];
57
+ cancelTxHashes: string[];
58
+ gasLimit: string;
59
+ feesPerGas: SerializableFeesPerGas;
60
+ txConfigOverrides: SerializableL1TxConfig;
61
+ request: SerializableL1TxRequest;
62
+ status: number;
63
+ nonce: number;
64
+ sentAt: number;
65
+ lastSentAt: number;
66
+ receipt?: TransactionReceipt;
67
+ hasBlobInputs: boolean;
68
+ blobMetadata?: SerializableBlobMetadata;
69
+ }
70
+
71
+ /**
72
+ * Shape accepted when reading a state back. States written before the rename spelled `feesPerGas` as `gasPrice`, so
73
+ * both are optional here and `deserializeState` takes whichever is present. Nothing writes `gasPrice` any more; drop
74
+ * it once no store can hold states predating the rename.
75
+ */
76
+ type StoredL1TxState = Omit<SerializableL1TxState, 'feesPerGas'> & {
77
+ feesPerGas?: SerializableFeesPerGas;
78
+ gasPrice?: SerializableFeesPerGas;
79
+ };
80
+
81
+ /**
82
+ * Serializable blob inputs for separate storage.
83
+ */
84
+ interface SerializableBlobInputs {
85
+ blobs: string[]; // base64 encoded
86
+ kzg: string; // JSON stringified KZG instance
87
+ }
88
+
89
+ /**
90
+ * Store for persisting L1 transaction states across all L1TxUtils instances.
91
+ * Each state is stored individually with a unique ID, and blobs are stored separately.
92
+ * @remarks This class lives in this package instead of `ethereum` because it depends on `kv-store`.
93
+ */
94
+ export class L1TxStore implements IL1TxStore {
95
+ public static readonly SCHEMA_VERSION = 2;
96
+
97
+ private readonly states: AztecAsyncMap<string, string>; // key: "account-stateId", value: SerializableL1TxState
98
+ private readonly blobs: AztecAsyncMap<string, string>; // key: "account-stateId", value: SerializableBlobInputs
99
+ private readonly stateIdCounter: AztecAsyncMap<string, number>; // key: "account", value: next ID
100
+
101
+ constructor(
102
+ private readonly store: AztecAsyncKVStore,
103
+ private readonly log: Logger = createLogger('l1-tx-utils:store'),
104
+ ) {
105
+ this.states = store.openMap<string, string>('l1_tx_states');
106
+ this.blobs = store.openMap<string, string>('l1_tx_blobs');
107
+ this.stateIdCounter = store.openMap<string, number>('l1_tx_state_id_counter');
108
+ }
109
+
110
+ /**
111
+ * Gets the next available state ID for an account.
112
+ */
113
+ public consumeNextStateId(account: string): Promise<number> {
114
+ return this.store.transactionAsync(async () => {
115
+ const currentId = (await this.stateIdCounter.getAsync(account)) ?? 0;
116
+ const nextId = currentId + 1;
117
+ await this.stateIdCounter.set(account, nextId);
118
+ return nextId;
119
+ });
120
+ }
121
+
122
+ /**
123
+ * Creates a storage key for state/blob data.
124
+ */
125
+ private makeKey(account: string, stateId: number): string {
126
+ return `${account}-${stateId.toString().padStart(10, '0')}`;
127
+ }
128
+
129
+ /**
130
+ * Saves a single transaction state for a specific account.
131
+ * Blobs are not stored here, use saveBlobs instead.
132
+ * @param account - The sender account address
133
+ * @param state - Transaction state to save
134
+ */
135
+ public async saveState(account: string, state: L1TxState): Promise<L1TxState> {
136
+ const key = this.makeKey(account, state.id);
137
+
138
+ const serializable = this.serializeState(state);
139
+ await this.states.set(key, jsonStringify(serializable));
140
+ this.log.debug(`Saved tx state ${state.id} for account ${account} with nonce ${state.nonce}`);
141
+
142
+ return state as L1TxState;
143
+ }
144
+
145
+ /**
146
+ * Saves blobs for a given state.
147
+ * @param account - The sender account address
148
+ * @param stateId - The state ID
149
+ * @param blobInputs - Blob inputs to save
150
+ */
151
+ public async saveBlobs(account: string, stateId: number, blobInputs: L1BlobInputs | undefined): Promise<void> {
152
+ if (!blobInputs) {
153
+ return;
154
+ }
155
+ const key = this.makeKey(account, stateId);
156
+ const blobData = this.serializeBlobInputs(blobInputs);
157
+ await this.blobs.set(key, jsonStringify(blobData));
158
+ this.log.debug(`Saved blobs for state ${stateId} of account ${account}`);
159
+ }
160
+
161
+ /**
162
+ * Loads all transaction states for a specific account.
163
+ * @param account - The sender account address
164
+ * @returns Array of transaction states with their IDs
165
+ */
166
+ public async loadStates(account: string): Promise<L1TxState[]> {
167
+ const states: L1TxState[] = [];
168
+ const prefix = `${account}-`;
169
+
170
+ for await (const [key, stateJson] of this.states.entriesAsync({ start: prefix, end: `${prefix}Z` })) {
171
+ const [keyAccount, stateIdStr] = key.split('-');
172
+ if (keyAccount !== account) {
173
+ throw new Error(`Mismatched account in key: expected ${account} but got ${keyAccount}`);
174
+ }
175
+
176
+ const stateId = parseInt(stateIdStr, 10);
177
+
178
+ try {
179
+ const serialized: StoredL1TxState = JSON.parse(stateJson);
180
+
181
+ // Load blobs if they exist
182
+ let blobInputs: L1BlobInputs | undefined;
183
+ if (serialized.hasBlobInputs) {
184
+ const blobJson = await this.blobs.getAsync(key);
185
+ if (blobJson) {
186
+ blobInputs = this.deserializeBlobInputs(JSON.parse(blobJson), serialized.blobMetadata);
187
+ }
188
+ }
189
+
190
+ const state = this.deserializeState(serialized, blobInputs);
191
+ states.push({ ...state, id: stateId });
192
+ } catch (err) {
193
+ this.log.error(`Failed to deserialize state ${key}`, err);
194
+ }
195
+ }
196
+
197
+ // Sort by ID
198
+ states.sort((a, b) => a.id - b.id);
199
+
200
+ this.log.debug(`Loaded ${states.length} tx states for account ${account}`);
201
+ return states;
202
+ }
203
+
204
+ /**
205
+ * Loads a single state by ID.
206
+ * @param account - The sender account address
207
+ * @param stateId - The state ID
208
+ * @returns The transaction state or undefined if not found
209
+ */
210
+ public async loadState(account: string, stateId: number): Promise<L1TxState | undefined> {
211
+ const key = this.makeKey(account, stateId);
212
+ const stateJson = await this.states.getAsync(key);
213
+
214
+ if (!stateJson) {
215
+ return undefined;
216
+ }
217
+
218
+ try {
219
+ const serialized: StoredL1TxState = JSON.parse(stateJson);
220
+
221
+ // Load blobs if they exist
222
+ let blobInputs: L1BlobInputs | undefined;
223
+ if (serialized.hasBlobInputs) {
224
+ const blobJson = await this.blobs.getAsync(key);
225
+ if (blobJson) {
226
+ blobInputs = this.deserializeBlobInputs(JSON.parse(blobJson), serialized.blobMetadata);
227
+ }
228
+ }
229
+
230
+ const state = this.deserializeState(serialized, blobInputs);
231
+ return { ...state, id: stateId };
232
+ } catch (err) {
233
+ this.log.error(`Failed to deserialize state ${key}`, err);
234
+ return undefined;
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Deletes a specific state and its associated blobs.
240
+ * @param account - The sender account address
241
+ * @param stateId - The state ID to delete
242
+ */
243
+ public async deleteState(account: string, ...stateIds: number[]): Promise<void> {
244
+ if (stateIds.length === 0) {
245
+ return;
246
+ }
247
+
248
+ await this.store.transactionAsync(async () => {
249
+ for (const stateId of stateIds) {
250
+ const key = this.makeKey(account, stateId);
251
+ await this.states.delete(key);
252
+ await this.blobs.delete(key);
253
+ }
254
+ });
255
+ }
256
+
257
+ /**
258
+ * Clears all transaction states for a specific account.
259
+ * @param account - The sender account address
260
+ */
261
+ public async clearStates(account: string): Promise<void> {
262
+ await this.store.transactionAsync(async () => {
263
+ const states = await this.loadStates(account);
264
+
265
+ for (const state of states) {
266
+ await this.deleteState(account, state.id);
267
+ }
268
+
269
+ await this.stateIdCounter.delete(account);
270
+ this.log.info(`Cleared all tx states for account ${account}`);
271
+ });
272
+ }
273
+
274
+ /**
275
+ * Gets all accounts that have stored states.
276
+ * @returns Array of account addresses
277
+ */
278
+ public async getAllAccounts(): Promise<string[]> {
279
+ const accounts = new Set<string>();
280
+
281
+ for await (const [key] of this.states.entriesAsync()) {
282
+ const account = key.substring(0, key.lastIndexOf('-'));
283
+ accounts.add(account);
284
+ }
285
+
286
+ return Array.from(accounts);
287
+ }
288
+
289
+ /**
290
+ * Closes the store.
291
+ */
292
+ public async close(): Promise<void> {
293
+ await this.store.close();
294
+ this.log.info('Closed L1 tx state store');
295
+ }
296
+
297
+ /**
298
+ * Serializes an L1TxState for storage.
299
+ */
300
+ private serializeState(state: L1TxState): SerializableL1TxState {
301
+ const txConfigOverrides: SerializableL1TxConfig = {
302
+ ...state.txConfigOverrides,
303
+ gasLimit: state.txConfigOverrides.gasLimit?.toString(),
304
+ txTimeoutAt: state.txConfigOverrides.txTimeoutAt?.getTime(),
305
+ };
306
+
307
+ return {
308
+ id: state.id,
309
+ txHashes: state.txHashes,
310
+ cancelTxHashes: state.cancelTxHashes,
311
+ gasLimit: state.gasLimit.toString(),
312
+ feesPerGas: {
313
+ maxFeePerGas: state.feesPerGas.maxFeePerGas.toString(),
314
+ maxPriorityFeePerGas: state.feesPerGas.maxPriorityFeePerGas.toString(),
315
+ maxFeePerBlobGas: state.feesPerGas.maxFeePerBlobGas?.toString(),
316
+ },
317
+ txConfigOverrides,
318
+ request: {
319
+ ...state.request,
320
+ value: state.request.value?.toString(),
321
+ },
322
+ status: state.status,
323
+ nonce: state.nonce,
324
+ sentAt: state.sentAtL1Ts.getTime(),
325
+ lastSentAt: state.lastSentAtL1Ts.getTime(),
326
+ receipt: state.receipt,
327
+ hasBlobInputs: state.blobInputs !== undefined,
328
+ blobMetadata: state.blobInputs?.maxFeePerBlobGas
329
+ ? { maxFeePerBlobGas: state.blobInputs.maxFeePerBlobGas.toString() }
330
+ : undefined,
331
+ };
332
+ }
333
+
334
+ /**
335
+ * Deserializes a stored state back to L1TxState.
336
+ */
337
+ private deserializeState(stored: StoredL1TxState, blobInputs?: L1BlobInputs): L1TxState {
338
+ const feesPerGas = stored.feesPerGas ?? stored.gasPrice;
339
+ if (!feesPerGas) {
340
+ throw new Error(`State ${stored.id} has no fees per gas`);
341
+ }
342
+
343
+ const txConfigOverrides: L1TxConfig = {
344
+ ...stored.txConfigOverrides,
345
+ gasLimit: stored.txConfigOverrides.gasLimit !== undefined ? BigInt(stored.txConfigOverrides.gasLimit) : undefined,
346
+ txTimeoutAt:
347
+ stored.txConfigOverrides.txTimeoutAt !== undefined ? new Date(stored.txConfigOverrides.txTimeoutAt) : undefined,
348
+ };
349
+
350
+ const receipt = stored.receipt
351
+ ? {
352
+ ...stored.receipt,
353
+ blockNumber: BigInt(stored.receipt.blockNumber),
354
+ cumulativeGasUsed: BigInt(stored.receipt.cumulativeGasUsed),
355
+ effectiveGasPrice: BigInt(stored.receipt.effectiveGasPrice),
356
+ gasUsed: BigInt(stored.receipt.gasUsed),
357
+ }
358
+ : undefined;
359
+
360
+ return {
361
+ id: stored.id,
362
+ txHashes: stored.txHashes as `0x${string}`[],
363
+ cancelTxHashes: stored.cancelTxHashes as `0x${string}`[],
364
+ gasLimit: BigInt(stored.gasLimit),
365
+ feesPerGas: {
366
+ maxFeePerGas: BigInt(feesPerGas.maxFeePerGas),
367
+ maxPriorityFeePerGas: BigInt(feesPerGas.maxPriorityFeePerGas),
368
+ maxFeePerBlobGas: feesPerGas.maxFeePerBlobGas ? BigInt(feesPerGas.maxFeePerBlobGas) : undefined,
369
+ },
370
+ txConfigOverrides,
371
+ request: {
372
+ to: stored.request.to as `0x${string}` | null,
373
+ data: stored.request.data as `0x${string}` | undefined,
374
+ value: stored.request.value ? BigInt(stored.request.value) : undefined,
375
+ },
376
+ status: stored.status,
377
+ nonce: stored.nonce,
378
+ sentAtL1Ts: new Date(stored.sentAt),
379
+ lastSentAtL1Ts: new Date(stored.lastSentAt),
380
+ receipt,
381
+ blobInputs,
382
+ };
383
+ }
384
+
385
+ /**
386
+ * Serializes blob inputs for separate storage.
387
+ */
388
+ private serializeBlobInputs(blobInputs: L1BlobInputs): SerializableBlobInputs {
389
+ return {
390
+ blobs: blobInputs.blobs.map(b => Buffer.from(b).toString('base64')),
391
+ kzg: jsonStringify(blobInputs.kzg),
392
+ };
393
+ }
394
+
395
+ /**
396
+ * Deserializes blob inputs from storage, combining blob data with metadata.
397
+ */
398
+ private deserializeBlobInputs(stored: SerializableBlobInputs, metadata?: SerializableBlobMetadata): L1BlobInputs {
399
+ const blobInputs: L1BlobInputs = {
400
+ blobs: stored.blobs.map(b => new Uint8Array(Buffer.from(b, 'base64'))),
401
+ kzg: JSON.parse(stored.kzg),
402
+ };
403
+
404
+ if (metadata?.maxFeePerBlobGas) {
405
+ blobInputs.maxFeePerBlobGas = BigInt(metadata.maxFeePerBlobGas);
406
+ }
407
+
408
+ return blobInputs;
409
+ }
410
+ }