@aztec/p2p 0.0.1-commit.a072138 → 0.0.1-commit.aada20e3

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 (106) hide show
  1. package/dest/client/factory.d.ts +1 -1
  2. package/dest/client/factory.d.ts.map +1 -1
  3. package/dest/client/factory.js +3 -1
  4. package/dest/client/p2p_client.d.ts +4 -2
  5. package/dest/client/p2p_client.d.ts.map +1 -1
  6. package/dest/client/p2p_client.js +6 -2
  7. package/dest/config.d.ts +8 -2
  8. package/dest/config.d.ts.map +1 -1
  9. package/dest/config.js +3 -1
  10. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts +2 -0
  11. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts.map +1 -0
  12. package/dest/mem_pools/tx_pool_v2/archive/index.js +1 -0
  13. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts +43 -0
  14. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts.map +1 -0
  15. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.js +103 -0
  16. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts +47 -0
  17. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts.map +1 -0
  18. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.js +119 -0
  19. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts +17 -0
  20. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts.map +1 -0
  21. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.js +90 -0
  22. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts +19 -0
  23. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts.map +1 -0
  24. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.js +89 -0
  25. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts +10 -0
  26. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts.map +1 -0
  27. package/dest/mem_pools/tx_pool_v2/eviction/index.js +11 -0
  28. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts +131 -0
  29. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts.map +1 -0
  30. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.js +17 -0
  31. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts +15 -0
  32. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts.map +1 -0
  33. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.js +63 -0
  34. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts +17 -0
  35. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts.map +1 -0
  36. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.js +91 -0
  37. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts +16 -0
  38. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts.map +1 -0
  39. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.js +70 -0
  40. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts +20 -0
  41. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts.map +1 -0
  42. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.js +63 -0
  43. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts +15 -0
  44. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts.map +1 -0
  45. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.js +19 -0
  46. package/dest/mem_pools/tx_pool_v2/index.d.ts +5 -0
  47. package/dest/mem_pools/tx_pool_v2/index.d.ts.map +1 -0
  48. package/dest/mem_pools/tx_pool_v2/index.js +4 -0
  49. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts +193 -0
  50. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts.map +1 -0
  51. package/dest/mem_pools/tx_pool_v2/interfaces.js +6 -0
  52. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts +71 -0
  53. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts.map +1 -0
  54. package/dest/mem_pools/tx_pool_v2/tx_metadata.js +94 -0
  55. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts +26 -0
  56. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts.map +1 -0
  57. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.js +70 -0
  58. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts +55 -0
  59. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts.map +1 -0
  60. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.js +150 -0
  61. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts +69 -0
  62. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts.map +1 -0
  63. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.js +1041 -0
  64. package/dest/services/index.d.ts +2 -1
  65. package/dest/services/index.d.ts.map +1 -1
  66. package/dest/services/index.js +1 -0
  67. package/dest/services/tx_file_store/config.d.ts +18 -0
  68. package/dest/services/tx_file_store/config.d.ts.map +1 -0
  69. package/dest/services/tx_file_store/config.js +26 -0
  70. package/dest/services/tx_file_store/index.d.ts +4 -0
  71. package/dest/services/tx_file_store/index.d.ts.map +1 -0
  72. package/dest/services/tx_file_store/index.js +3 -0
  73. package/dest/services/tx_file_store/instrumentation.d.ts +15 -0
  74. package/dest/services/tx_file_store/instrumentation.d.ts.map +1 -0
  75. package/dest/services/tx_file_store/instrumentation.js +29 -0
  76. package/dest/services/tx_file_store/tx_file_store.d.ts +47 -0
  77. package/dest/services/tx_file_store/tx_file_store.d.ts.map +1 -0
  78. package/dest/services/tx_file_store/tx_file_store.js +149 -0
  79. package/package.json +14 -14
  80. package/src/client/factory.ts +4 -0
  81. package/src/client/p2p_client.ts +5 -0
  82. package/src/config.ts +8 -1
  83. package/src/mem_pools/tx_pool_v2/README.md +188 -0
  84. package/src/mem_pools/tx_pool_v2/archive/index.ts +1 -0
  85. package/src/mem_pools/tx_pool_v2/archive/tx_archive.ts +120 -0
  86. package/src/mem_pools/tx_pool_v2/eviction/eviction_manager.ts +147 -0
  87. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.ts +118 -0
  88. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.ts +111 -0
  89. package/src/mem_pools/tx_pool_v2/eviction/index.ts +23 -0
  90. package/src/mem_pools/tx_pool_v2/eviction/interfaces.ts +164 -0
  91. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.ts +74 -0
  92. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.ts +101 -0
  93. package/src/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.ts +86 -0
  94. package/src/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.ts +72 -0
  95. package/src/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.ts +31 -0
  96. package/src/mem_pools/tx_pool_v2/index.ts +11 -0
  97. package/src/mem_pools/tx_pool_v2/interfaces.ts +225 -0
  98. package/src/mem_pools/tx_pool_v2/tx_metadata.ts +160 -0
  99. package/src/mem_pools/tx_pool_v2/tx_pool_bench_metrics.ts +77 -0
  100. package/src/mem_pools/tx_pool_v2/tx_pool_v2.ts +209 -0
  101. package/src/mem_pools/tx_pool_v2/tx_pool_v2_impl.ts +1265 -0
  102. package/src/services/index.ts +1 -0
  103. package/src/services/tx_file_store/config.ts +43 -0
  104. package/src/services/tx_file_store/index.ts +3 -0
  105. package/src/services/tx_file_store/instrumentation.ts +36 -0
  106. package/src/services/tx_file_store/tx_file_store.ts +173 -0
@@ -0,0 +1,1265 @@
1
+ import { SlotNumber } from '@aztec/foundation/branded-types';
2
+ import type { Logger } from '@aztec/foundation/log';
3
+ import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec/kv-store';
4
+ import { ProtocolContractAddress } from '@aztec/protocol-contracts';
5
+ import { computeFeePayerBalanceStorageSlot } from '@aztec/protocol-contracts/fee-juice';
6
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
7
+ import type { L2Block, L2BlockId, L2BlockSource } from '@aztec/stdlib/block';
8
+ import type { WorldStateSynchronizer } from '@aztec/stdlib/interfaces/server';
9
+ import { DatabasePublicStateSource } from '@aztec/stdlib/trees';
10
+ import { BlockHeader, Tx, TxHash, type TxValidator } from '@aztec/stdlib/tx';
11
+
12
+ import { TxArchive } from './archive/index.js';
13
+ import {
14
+ EvictionManager,
15
+ FeePayerBalanceEvictionRule,
16
+ FeePayerBalancePreAddRule,
17
+ InvalidTxsAfterMiningRule,
18
+ InvalidTxsAfterReorgRule,
19
+ LowPriorityEvictionRule,
20
+ LowPriorityPreAddRule,
21
+ NullifierConflictRule,
22
+ type PoolOperations,
23
+ type PreAddPoolAccess,
24
+ } from './eviction/index.js';
25
+ import {
26
+ type AddTxsResult,
27
+ DEFAULT_TX_POOL_V2_CONFIG,
28
+ type PoolReadAccess,
29
+ type TxPoolV2Config,
30
+ type TxPoolV2Dependencies,
31
+ } from './interfaces.js';
32
+ import {
33
+ type TxMetaData,
34
+ type TxState,
35
+ buildTxMetaData,
36
+ checkNullifierConflict,
37
+ compareFee,
38
+ compareTxHash,
39
+ } from './tx_metadata.js';
40
+
41
+ /**
42
+ * Callbacks for the implementation to notify the outer class about events and metrics.
43
+ */
44
+ export interface TxPoolV2Callbacks {
45
+ onTxsAdded: (txs: Tx[], opts: { source?: string }) => void;
46
+ onTxsRemoved: (txHashes: string[] | bigint[]) => void;
47
+ }
48
+
49
+ /**
50
+ * Implementation of TxPoolV2 logic.
51
+ *
52
+ * This class contains all the actual transaction pool logic.
53
+ */
54
+ export class TxPoolV2Impl {
55
+ // === Persistence ===
56
+ #store: AztecAsyncKVStore;
57
+ #txsDB: AztecAsyncMap<string, Buffer>;
58
+
59
+ // === Dependencies ===
60
+ #l2BlockSource: L2BlockSource;
61
+ #worldStateSynchronizer: WorldStateSynchronizer;
62
+ #pendingTxValidator: TxValidator<Tx>;
63
+
64
+ // === In-Memory Indices ===
65
+ /** Primary metadata store: txHash -> TxMetaData */
66
+ #metadata: Map<string, TxMetaData> = new Map();
67
+ /** Nullifier to txHash index (pending txs only) */
68
+ #nullifierToTxHash: Map<string, string> = new Map();
69
+ /** Fee payer to txHashes index (pending txs only) */
70
+ #feePayerToTxHashes: Map<string, Set<string>> = new Map();
71
+ /**
72
+ * Pending txHashes grouped by priority fee.
73
+ * Outer map: priorityFee -> Set of txHashes at that fee level.
74
+ */
75
+ #pendingByPriority: Map<bigint, Set<string>> = new Map();
76
+ /** Protected transactions: txHash -> slotNumber. Includes txs we have and txs we expect to receive. */
77
+ #protectedTransactions: Map<string, SlotNumber> = new Map();
78
+
79
+ // === Config & Services ===
80
+ #config: TxPoolV2Config;
81
+ #archive: TxArchive;
82
+ #evictionManager: EvictionManager;
83
+ #log: Logger;
84
+ #callbacks: TxPoolV2Callbacks;
85
+
86
+ constructor(
87
+ store: AztecAsyncKVStore,
88
+ archiveStore: AztecAsyncKVStore,
89
+ deps: TxPoolV2Dependencies,
90
+ callbacks: TxPoolV2Callbacks,
91
+ config: Partial<TxPoolV2Config> = {},
92
+ log: Logger,
93
+ ) {
94
+ this.#store = store;
95
+ this.#txsDB = store.openMap('txs');
96
+
97
+ this.#l2BlockSource = deps.l2BlockSource;
98
+ this.#worldStateSynchronizer = deps.worldStateSynchronizer;
99
+ this.#pendingTxValidator = deps.pendingTxValidator;
100
+
101
+ this.#config = { ...DEFAULT_TX_POOL_V2_CONFIG, ...config };
102
+ this.#archive = new TxArchive(archiveStore, this.#config.archivedTxLimit, log);
103
+ this.#log = log;
104
+ this.#callbacks = callbacks;
105
+
106
+ // Setup eviction manager with rules
107
+ this.#evictionManager = new EvictionManager(this.#createPoolOperations(), log);
108
+
109
+ // Pre-add rules (run during addPendingTxs) - work with TxMetaData
110
+ this.#evictionManager.registerPreAddRule(new NullifierConflictRule());
111
+ this.#evictionManager.registerPreAddRule(new FeePayerBalancePreAddRule());
112
+ this.#evictionManager.registerPreAddRule(
113
+ new LowPriorityPreAddRule({ maxPoolSize: this.#config.maxPendingTxCount }),
114
+ );
115
+
116
+ // Post-event eviction rules (run after events to check ALL pending txs)
117
+ this.#evictionManager.registerRule(new InvalidTxsAfterMiningRule());
118
+ this.#evictionManager.registerRule(new InvalidTxsAfterReorgRule(deps.worldStateSynchronizer));
119
+ this.#evictionManager.registerRule(new FeePayerBalanceEvictionRule(deps.worldStateSynchronizer));
120
+ // LowPriorityEvictionRule handles cases where txs become pending via prepareForSlot (unprotect)
121
+ // The pre-add rule handles the addPendingTxs case, but post-event is needed for unprotect
122
+ this.#evictionManager.registerRule(new LowPriorityEvictionRule({ maxPoolSize: this.#config.maxPendingTxCount }));
123
+ }
124
+
125
+ // ============================================================================
126
+ // PUBLIC IMPLEMENTATION METHODS
127
+ // ============================================================================
128
+
129
+ /**
130
+ * Hydrates the in-memory state from the database on startup.
131
+ * Pipeline: Load → Check Mined Status → Partition → Validate Non-Mined → Rebuild Pending Pool → Delete Invalid
132
+ *
133
+ * Note: Protected status is lost on restart. All non-mined txs are rebuilt as pending
134
+ * by running pre-add rules to resolve nullifier conflicts, balance checks, and pool size limits.
135
+ */
136
+ async hydrateFromDatabase(): Promise<void> {
137
+ // Step 1: Load all transactions from DB
138
+ const { loaded, errors: deserializationErrors } = await this.#loadAllTxsFromDb();
139
+
140
+ // Step 2: Check mined status for each tx
141
+ await this.#markMinedStatusBatch(loaded.map(l => l.meta));
142
+
143
+ // Step 3: Partition by mined status
144
+ const { mined, nonMined } = this.#partitionByMinedStatus(loaded);
145
+
146
+ // Step 4: Validate non-mined transactions
147
+ const { valid, invalid } = await this.#validateNonMinedTxs(nonMined);
148
+
149
+ // Step 5: Populate mined indices (these don't need conflict resolution)
150
+ this.#populateMinedIndices(mined);
151
+
152
+ // Step 6: Rebuild pending pool by running pre-add rules for each tx
153
+ // This resolves nullifier conflicts, fee payer balance issues, and pool size limits
154
+ const { rejected } = await this.#rebuildPendingPool(valid);
155
+
156
+ // Step 7: Delete invalid and rejected txs from DB
157
+ const toDelete = [...deserializationErrors, ...invalid, ...rejected];
158
+ if (toDelete.length === 0) {
159
+ return;
160
+ }
161
+ await this.#store.transactionAsync(async () => {
162
+ for (const txHashStr of toDelete) {
163
+ await this.#txsDB.delete(txHashStr);
164
+ }
165
+ });
166
+ this.#log.info(`Deleted ${toDelete.length} invalid/rejected transactions on startup`);
167
+ }
168
+
169
+ async addPendingTxs(txs: Tx[], opts: { source?: string }): Promise<AddTxsResult> {
170
+ const accepted: TxHash[] = [];
171
+ const ignored: TxHash[] = [];
172
+ const rejected: TxHash[] = [];
173
+ const newlyAdded: Tx[] = [];
174
+ const acceptedPending = new Set<string>();
175
+
176
+ const poolAccess = this.#createPreAddPoolAccess();
177
+
178
+ await this.#store.transactionAsync(async () => {
179
+ for (const tx of txs) {
180
+ const txHash = tx.getTxHash();
181
+ const txHashStr = txHash.toString();
182
+
183
+ // Skip duplicates
184
+ if (this.#isDuplicateTx(txHashStr)) {
185
+ ignored.push(txHash);
186
+ continue;
187
+ }
188
+
189
+ // Check mined status first (applies to all paths)
190
+ const minedBlockId = await this.#getMinedBlockId(txHash);
191
+ const preProtectedSlot = this.#protectedTransactions.get(txHashStr);
192
+
193
+ if (minedBlockId) {
194
+ // Already mined - add directly (protection already set if pre-protected)
195
+ await this.#addNewMinedTx(tx, minedBlockId);
196
+ accepted.push(txHash);
197
+ newlyAdded.push(tx);
198
+ } else if (preProtectedSlot !== undefined) {
199
+ // Pre-protected and not mined - add as protected (bypass validation)
200
+ await this.#addNewProtectedTx(tx, preProtectedSlot);
201
+ accepted.push(txHash);
202
+ newlyAdded.push(tx);
203
+ } else {
204
+ // Regular pending tx - validate and run pre-add rules
205
+ const result = await this.#tryAddRegularPendingTx(tx, poolAccess, acceptedPending, ignored);
206
+ if (result.status === 'accepted') {
207
+ acceptedPending.add(txHashStr);
208
+ newlyAdded.push(tx);
209
+ } else if (result.status === 'rejected') {
210
+ rejected.push(txHash);
211
+ } else {
212
+ ignored.push(txHash);
213
+ }
214
+ }
215
+ }
216
+ });
217
+
218
+ // Build final accepted list for pending txs (excludes intra-batch evictions)
219
+ for (const txHashStr of acceptedPending) {
220
+ accepted.push(TxHash.fromString(txHashStr));
221
+ }
222
+
223
+ // Run post-add eviction rules for pending txs
224
+ if (acceptedPending.size > 0) {
225
+ const feePayers = Array.from(acceptedPending).map(txHash => this.#metadata.get(txHash)!.feePayer);
226
+ const uniqueFeePayers = new Set<string>(feePayers);
227
+ await this.#evictionManager.evictAfterNewTxs(Array.from(acceptedPending), [...uniqueFeePayers]);
228
+ }
229
+
230
+ // Emit events
231
+ if (newlyAdded.length > 0) {
232
+ this.#callbacks.onTxsAdded(newlyAdded, opts);
233
+ }
234
+
235
+ return { accepted, ignored, rejected };
236
+ }
237
+
238
+ /** Validates and adds a regular pending tx. Returns status. */
239
+ async #tryAddRegularPendingTx(
240
+ tx: Tx,
241
+ poolAccess: PreAddPoolAccess,
242
+ acceptedPending: Set<string>,
243
+ ignored: TxHash[],
244
+ ): Promise<{ status: 'accepted' | 'ignored' | 'rejected' }> {
245
+ const txHash = tx.getTxHash();
246
+ const txHashStr = txHash.toString();
247
+
248
+ // Validate transaction
249
+ const validationResult = await this.#pendingTxValidator.validateTx(tx);
250
+ if (validationResult.result !== 'valid') {
251
+ this.#log.info(`Rejecting tx ${txHashStr}: ${validationResult.reason?.join(', ')}`);
252
+ return { status: 'rejected' };
253
+ }
254
+
255
+ // Build metadata and run pre-add rules
256
+ const meta = await buildTxMetaData(tx);
257
+ const preAddResult = await this.#evictionManager.runPreAddRules(meta, poolAccess);
258
+
259
+ if (preAddResult.shouldIgnore) {
260
+ this.#log.debug(`Ignoring tx ${txHashStr}: ${preAddResult.reason}`);
261
+ return { status: 'ignored' };
262
+ }
263
+
264
+ // Evict conflicts (tracking intra-batch evictions)
265
+ for (const evictHashStr of preAddResult.txHashesToEvict) {
266
+ await this.#deleteTx(evictHashStr);
267
+ this.#log.debug(`Evicted tx ${evictHashStr} due to higher-fee tx ${txHashStr}`);
268
+ if (acceptedPending.has(evictHashStr)) {
269
+ acceptedPending.delete(evictHashStr);
270
+ ignored.push(TxHash.fromString(evictHashStr));
271
+ }
272
+ }
273
+
274
+ // Add the transaction
275
+ await this.#addNewPendingTx(tx);
276
+ return { status: 'accepted' };
277
+ }
278
+
279
+ async canAddPendingTx(tx: Tx): Promise<'accepted' | 'ignored' | 'rejected'> {
280
+ const txHashStr = tx.getTxHash().toString();
281
+
282
+ // Check if already in pool
283
+ if (this.#metadata.has(txHashStr)) {
284
+ return 'ignored';
285
+ }
286
+
287
+ // Validate transaction
288
+ const validationResult = await this.#pendingTxValidator.validateTx(tx);
289
+ if (validationResult.result !== 'valid') {
290
+ return 'rejected';
291
+ }
292
+
293
+ // Build metadata and use pre-add rules
294
+ const meta = await buildTxMetaData(tx);
295
+ const poolAccess = this.#createPreAddPoolAccess();
296
+ const preAddResult = await this.#evictionManager.runPreAddRules(meta, poolAccess);
297
+
298
+ return preAddResult.shouldIgnore ? 'ignored' : 'accepted';
299
+ }
300
+
301
+ async addProtectedTxs(txs: Tx[], block: BlockHeader, opts: { source?: string }): Promise<void> {
302
+ const slotNumber = block.globalVariables.slotNumber;
303
+ const newlyAdded: Tx[] = [];
304
+
305
+ await this.#store.transactionAsync(async () => {
306
+ for (const tx of txs) {
307
+ const txHash = tx.getTxHash();
308
+ const txHashStr = txHash.toString();
309
+ const isNew = !this.#metadata.has(txHashStr);
310
+ const minedBlockId = await this.#getMinedBlockId(txHash);
311
+
312
+ if (isNew) {
313
+ // New tx - add as mined or protected
314
+ if (minedBlockId) {
315
+ await this.#addNewMinedTx(tx, minedBlockId);
316
+ this.#protectedTransactions.set(txHashStr, slotNumber);
317
+ } else {
318
+ await this.#addNewProtectedTx(tx, slotNumber);
319
+ }
320
+ newlyAdded.push(tx);
321
+ } else {
322
+ // Existing tx - update protection and mined status
323
+ this.#updateProtection(txHashStr, slotNumber);
324
+ if (minedBlockId) {
325
+ this.#markAsMined(this.#metadata.get(txHashStr)!, minedBlockId);
326
+ }
327
+ }
328
+ }
329
+ });
330
+
331
+ if (newlyAdded.length > 0) {
332
+ this.#callbacks.onTxsAdded(newlyAdded, opts);
333
+ }
334
+ }
335
+
336
+ protectTxs(txHashes: TxHash[], block: BlockHeader): TxHash[] {
337
+ const slotNumber = block.globalVariables.slotNumber;
338
+ const missing: TxHash[] = [];
339
+
340
+ for (const txHash of txHashes) {
341
+ const txHashStr = txHash.toString();
342
+
343
+ if (this.#metadata.has(txHashStr)) {
344
+ // Step 1a: Update protection for existing tx
345
+ this.#updateProtection(txHashStr, slotNumber);
346
+ } else {
347
+ // Step 1b: Pre-record protection for tx we don't have yet
348
+ this.#protectedTransactions.set(txHashStr, slotNumber);
349
+ missing.push(txHash);
350
+ }
351
+ }
352
+
353
+ return missing;
354
+ }
355
+
356
+ async addMinedTxs(txs: Tx[], block: BlockHeader, opts: { source?: string }): Promise<void> {
357
+ // Step 1: Build block ID
358
+ const blockId = await this.#buildBlockId(block);
359
+ const newlyAdded: Tx[] = [];
360
+
361
+ await this.#store.transactionAsync(async () => {
362
+ for (const tx of txs) {
363
+ const txHashStr = tx.getTxHash().toString();
364
+ const existingMeta = this.#metadata.get(txHashStr);
365
+
366
+ if (existingMeta) {
367
+ // Step 2a: Mark existing tx as mined
368
+ this.#markAsMined(existingMeta, blockId);
369
+ } else {
370
+ // Step 2b: Add new mined tx
371
+ await this.#addNewMinedTx(tx, blockId);
372
+ newlyAdded.push(tx);
373
+ }
374
+ }
375
+ });
376
+
377
+ // Step 3: Emit events for newly added txs
378
+ if (newlyAdded.length > 0) {
379
+ this.#callbacks.onTxsAdded(newlyAdded, opts);
380
+ }
381
+ }
382
+
383
+ async handleMinedBlock(block: L2Block): Promise<void> {
384
+ // Step 1: Build block ID
385
+ const blockId = await this.#buildBlockId(block.header);
386
+
387
+ // Step 2: Extract tx hashes and nullifiers directly from the block
388
+ const txHashes = block.body.txEffects.map(tx => tx.txHash);
389
+ const nullifiers = block.body.txEffects.flatMap(tx => tx.nullifiers.map(n => n.toString()));
390
+
391
+ // Step 3: Collect fee payers from txs we have in the pool (for balance-based eviction)
392
+ const feePayers: string[] = [];
393
+ const found: TxMetaData[] = [];
394
+ for (const txHash of txHashes) {
395
+ const meta = this.#metadata.get(txHash.toString());
396
+ if (meta) {
397
+ feePayers.push(meta.feePayer);
398
+ found.push(meta);
399
+ }
400
+ }
401
+
402
+ // Step 4: Mark txs as mined (only those we have in the pool)
403
+ this.#markTxsAsMined(found, blockId);
404
+
405
+ // Step 5: Run eviction rules (remove pending txs with conflicting nullifiers/expired timestamps)
406
+ await this.#evictionManager.evictAfterNewBlock(block.header, nullifiers, feePayers);
407
+
408
+ this.#callbacks.onTxsRemoved(txHashes.map(h => h.toBigInt()));
409
+ this.#log.info(`Marked ${found.length} txs as mined in block ${blockId.number}`);
410
+ }
411
+
412
+ async prepareForSlot(slotNumber: SlotNumber): Promise<void> {
413
+ // Step 1: Find expired protected txs
414
+ const expiredProtected = this.#findExpiredProtectedTxs(slotNumber);
415
+
416
+ // Step 2: Clear protection for all expired entries (including those without metadata)
417
+ this.#clearProtection(expiredProtected);
418
+
419
+ // Step 3: Filter to only txs that have metadata and are not mined
420
+ const txsToRestore = this.#filterRestorable(expiredProtected);
421
+ if (txsToRestore.length === 0) {
422
+ return;
423
+ }
424
+
425
+ this.#log.info(`Preparing for slot ${slotNumber}: unprotecting ${txsToRestore.length} txs`);
426
+
427
+ // Step 4: Validate for pending pool
428
+ const { valid, invalid } = await this.#validateForPending(txsToRestore);
429
+
430
+ // Step 5: Resolve nullifier conflicts and add winners to pending indices
431
+ const { added, toEvict } = this.#applyNullifierConflictResolution(valid);
432
+
433
+ // Step 6: Delete invalid and evicted txs
434
+ await this.#deleteTxsBatch([...invalid, ...toEvict]);
435
+
436
+ // Step 7: Run eviction rules (enforce pool size limit)
437
+ if (added.length > 0) {
438
+ const feePayers = added.map(meta => meta.feePayer);
439
+ const uniqueFeePayers = new Set<string>(feePayers);
440
+ await this.#evictionManager.evictAfterNewTxs(
441
+ added.map(m => m.txHash),
442
+ [...uniqueFeePayers],
443
+ );
444
+ }
445
+ }
446
+
447
+ async handlePrunedBlocks(latestBlock: L2BlockId): Promise<void> {
448
+ // Step 1: Find transactions mined after the prune point
449
+ const txsToUnmine = this.#findTxsMinedAfter(latestBlock.number);
450
+ if (txsToUnmine.length === 0) {
451
+ this.#log.debug(`No transactions to un-mine for prune to block ${latestBlock.number}`);
452
+ return;
453
+ }
454
+
455
+ this.#log.info(`Handling prune to block ${latestBlock.number}: un-mining ${txsToUnmine.length} txs`);
456
+
457
+ // Step 2: Unmine - clear mined status from metadata
458
+ this.#unmineTxs(txsToUnmine);
459
+
460
+ // Step 3: Filter out protected txs (they'll be handled by prepareForSlot)
461
+ const unprotectedTxs = this.#filterUnprotected(txsToUnmine);
462
+
463
+ // Step 4: Validate for pending pool
464
+ const { valid, invalid } = await this.#validateForPending(unprotectedTxs);
465
+
466
+ // Step 5: Resolve nullifier conflicts and add winners to pending indices
467
+ const { toEvict } = this.#applyNullifierConflictResolution(valid);
468
+
469
+ // Step 6: Delete invalid and evicted txs
470
+ await this.#deleteTxsBatch([...invalid, ...toEvict]);
471
+
472
+ // Step 7: Run eviction rules for ALL pending txs (not just restored ones)
473
+ // This handles cases like existing pending txs with invalid fee payer balances
474
+ await this.#evictionManager.evictAfterChainPrune(latestBlock.number);
475
+ }
476
+
477
+ async handleFailedExecution(txHashes: TxHash[]): Promise<void> {
478
+ // Step 1: Delete failed txs
479
+ await this.#deleteTxsBatch(txHashes.map(h => h.toString()));
480
+
481
+ this.#log.info(`Deleted ${txHashes.length} failed txs`);
482
+ }
483
+
484
+ async handleFinalizedBlock(block: BlockHeader): Promise<void> {
485
+ const blockNumber = block.globalVariables.blockNumber;
486
+
487
+ // Step 1: Find txs mined at or before finalized block
488
+ const txsToFinalize = this.#findTxsMinedAtOrBefore(blockNumber);
489
+ if (txsToFinalize.length === 0) {
490
+ return;
491
+ }
492
+
493
+ // Step 2: Collect txs for archiving (before deletion)
494
+ const txsToArchive: Tx[] = [];
495
+ if (this.#archive.isEnabled()) {
496
+ for (const txHashStr of txsToFinalize) {
497
+ const buffer = await this.#txsDB.getAsync(txHashStr);
498
+ if (buffer) {
499
+ txsToArchive.push(Tx.fromBuffer(buffer));
500
+ }
501
+ }
502
+ }
503
+
504
+ // Step 3: Delete from active pool
505
+ await this.#deleteTxsBatch(txsToFinalize);
506
+
507
+ // Step 4: Archive
508
+ if (txsToArchive.length > 0) {
509
+ await this.#archive.archiveTxs(txsToArchive);
510
+ }
511
+
512
+ this.#log.info(`Finalized ${txsToFinalize.length} txs from blocks up to ${blockNumber}`);
513
+ }
514
+
515
+ // === Query Methods ===
516
+
517
+ async getTxByHash(txHash: TxHash): Promise<Tx | undefined> {
518
+ const buffer = await this.#txsDB.getAsync(txHash.toString());
519
+ return buffer ? Tx.fromBuffer(buffer) : undefined;
520
+ }
521
+
522
+ async getTxsByHash(txHashes: TxHash[]): Promise<(Tx | undefined)[]> {
523
+ const results: (Tx | undefined)[] = [];
524
+ for (const h of txHashes) {
525
+ const buffer = await this.#txsDB.getAsync(h.toString());
526
+ results.push(buffer ? Tx.fromBuffer(buffer) : undefined);
527
+ }
528
+ return results;
529
+ }
530
+
531
+ hasTxs(txHashes: TxHash[]): boolean[] {
532
+ return txHashes.map(h => this.#metadata.has(h.toString()));
533
+ }
534
+
535
+ getTxStatus(txHash: TxHash): TxState | undefined {
536
+ const meta = this.#metadata.get(txHash.toString());
537
+ if (!meta) {
538
+ return undefined;
539
+ }
540
+ return this.#getTxState(meta);
541
+ }
542
+
543
+ getPendingTxHashes(): TxHash[] {
544
+ return [...this.#iteratePendingByPriority('desc')].map(hash => TxHash.fromString(hash));
545
+ }
546
+
547
+ getPendingTxCount(): number {
548
+ let count = 0;
549
+ for (const hashes of this.#pendingByPriority.values()) {
550
+ count += hashes.size;
551
+ }
552
+ return count;
553
+ }
554
+
555
+ getMinedTxHashes(): [TxHash, L2BlockId][] {
556
+ const result: [TxHash, L2BlockId][] = [];
557
+ for (const [txHash, meta] of this.#metadata) {
558
+ if (meta.minedL2BlockId !== undefined) {
559
+ result.push([TxHash.fromString(txHash), meta.minedL2BlockId]);
560
+ }
561
+ }
562
+ return result;
563
+ }
564
+
565
+ getMinedTxCount(): number {
566
+ let count = 0;
567
+ for (const meta of this.#metadata.values()) {
568
+ if (meta.minedL2BlockId !== undefined) {
569
+ count++;
570
+ }
571
+ }
572
+ return count;
573
+ }
574
+
575
+ isEmpty(): boolean {
576
+ return this.#metadata.size === 0;
577
+ }
578
+
579
+ getTxCount(): number {
580
+ return this.#metadata.size;
581
+ }
582
+
583
+ getArchivedTxByHash(txHash: TxHash): Promise<Tx | undefined> {
584
+ return this.#archive.getTxByHash(txHash);
585
+ }
586
+
587
+ getLowestPriorityPending(limit: number): TxHash[] {
588
+ if (limit <= 0) {
589
+ return [];
590
+ }
591
+
592
+ const result: TxHash[] = [];
593
+ for (const hash of this.#iteratePendingByPriority('asc')) {
594
+ result.push(TxHash.fromString(hash));
595
+ if (result.length >= limit) {
596
+ break;
597
+ }
598
+ }
599
+ return result;
600
+ }
601
+
602
+ // === Configuration ===
603
+
604
+ updateConfig(config: Partial<TxPoolV2Config>): void {
605
+ if (config.maxPendingTxCount !== undefined) {
606
+ this.#config.maxPendingTxCount = config.maxPendingTxCount;
607
+ }
608
+ if (config.archivedTxLimit !== undefined) {
609
+ this.#config.archivedTxLimit = config.archivedTxLimit;
610
+ this.#archive.updateLimit(config.archivedTxLimit);
611
+ }
612
+ // Update eviction rules with new config
613
+ this.#evictionManager.updateConfig(config);
614
+ }
615
+
616
+ // === Pool Read Access ===
617
+
618
+ getPoolReadAccess(): PoolReadAccess {
619
+ return {
620
+ getMetadata: (txHash: string) => this.#metadata.get(txHash),
621
+ getTxHashByNullifier: (nullifier: string) => this.#nullifierToTxHash.get(nullifier),
622
+ getTxHashesByFeePayer: (feePayer: string) => this.#feePayerToTxHashes.get(feePayer),
623
+ getPendingTxCount: () => this.getPendingTxCount(),
624
+ };
625
+ }
626
+
627
+ // === Metrics ===
628
+
629
+ countTxs(): { pending: number; protected: number; mined: number } {
630
+ let pending = 0;
631
+ let protected_ = 0;
632
+ let mined = 0;
633
+
634
+ for (const meta of this.#metadata.values()) {
635
+ const state = this.#getTxState(meta);
636
+ if (state === 'pending') {
637
+ pending++;
638
+ } else if (state === 'protected') {
639
+ protected_++;
640
+ } else if (state === 'mined') {
641
+ mined++;
642
+ }
643
+ }
644
+
645
+ return { pending, protected: protected_, mined };
646
+ }
647
+
648
+ // ============================================================================
649
+ // PRIVATE QUERY IMPLEMENTATIONS
650
+ // ============================================================================
651
+
652
+ /**
653
+ * Derives the transaction state from its metadata and protection status.
654
+ * A transaction is:
655
+ * - 'mined' if it has a minedL2BlockId
656
+ * - 'protected' if it's in the protectedTransactions map (but not mined)
657
+ * - 'pending' otherwise
658
+ */
659
+ #getTxState(meta: TxMetaData): TxState {
660
+ if (meta.minedL2BlockId !== undefined) {
661
+ return 'mined';
662
+ } else if (this.#protectedTransactions.has(meta.txHash)) {
663
+ return 'protected';
664
+ } else {
665
+ return 'pending';
666
+ }
667
+ }
668
+
669
+ /**
670
+ * Iterates pending transaction hashes in priority order.
671
+ * @param order - 'desc' for highest priority first, 'asc' for lowest priority first
672
+ */
673
+ *#iteratePendingByPriority(order: 'asc' | 'desc'): Generator<string> {
674
+ // Use shared comparators, negating for descending order
675
+ const feeCompareFn =
676
+ order === 'desc' ? (a: bigint, b: bigint) => compareFee(b, a) : (a: bigint, b: bigint) => compareFee(a, b);
677
+ const hashCompareFn =
678
+ order === 'desc' ? (a: string, b: string) => compareTxHash(b, a) : (a: string, b: string) => compareTxHash(a, b);
679
+
680
+ const sortedFees = [...this.#pendingByPriority.keys()].sort(feeCompareFn);
681
+
682
+ for (const fee of sortedFees) {
683
+ const hashesAtFee = this.#pendingByPriority.get(fee)!;
684
+ const sortedHashes = [...hashesAtFee].sort(hashCompareFn);
685
+ for (const hash of sortedHashes) {
686
+ yield hash;
687
+ }
688
+ }
689
+ }
690
+
691
+ // ============================================================================
692
+ // HELPER FUNCTIONS - Pipeline Step Functions
693
+ // ============================================================================
694
+
695
+ // --- Finding & Filtering Steps ---
696
+
697
+ /** Finds all transactions mined in blocks after the given block number */
698
+ #findTxsMinedAfter(blockNumber: number): TxMetaData[] {
699
+ const result: TxMetaData[] = [];
700
+ for (const meta of this.#metadata.values()) {
701
+ if (meta.minedL2BlockId !== undefined && meta.minedL2BlockId.number > blockNumber) {
702
+ result.push(meta);
703
+ }
704
+ }
705
+ return result;
706
+ }
707
+
708
+ /** Finds tx hashes mined at or before the given block number */
709
+ #findTxsMinedAtOrBefore(blockNumber: number): string[] {
710
+ const result: string[] = [];
711
+ for (const [txHashStr, meta] of this.#metadata) {
712
+ if (meta.minedL2BlockId !== undefined && meta.minedL2BlockId.number <= blockNumber) {
713
+ result.push(txHashStr);
714
+ }
715
+ }
716
+ return result;
717
+ }
718
+
719
+ /** Finds protected tx hashes from slots earlier than the given slot number */
720
+ #findExpiredProtectedTxs(slotNumber: SlotNumber): string[] {
721
+ const result: string[] = [];
722
+ for (const [txHashStr, protectedSlot] of this.#protectedTransactions) {
723
+ if (protectedSlot < slotNumber) {
724
+ result.push(txHashStr);
725
+ }
726
+ }
727
+ return result;
728
+ }
729
+
730
+ /** Filters out transactions that are currently protected */
731
+ #filterUnprotected(txs: TxMetaData[]): TxMetaData[] {
732
+ return txs.filter(meta => !this.#protectedTransactions.has(meta.txHash));
733
+ }
734
+
735
+ /** Filters to transactions that have metadata and are not mined */
736
+ #filterRestorable(txHashes: string[]): TxMetaData[] {
737
+ const result: TxMetaData[] = [];
738
+ for (const txHashStr of txHashes) {
739
+ const meta = this.#metadata.get(txHashStr);
740
+ if (meta && meta.minedL2BlockId === undefined) {
741
+ result.push(meta);
742
+ }
743
+ }
744
+ return result;
745
+ }
746
+
747
+ // --- Validation & Conflict Resolution Steps ---
748
+
749
+ /** Validates transactions for pending pool, returning valid and invalid groups */
750
+ async #validateForPending(txs: TxMetaData[]): Promise<{ valid: TxMetaData[]; invalid: string[] }> {
751
+ const valid: TxMetaData[] = [];
752
+ const invalid: string[] = [];
753
+
754
+ for (const meta of txs) {
755
+ const buffer = await this.#txsDB.getAsync(meta.txHash);
756
+ if (!buffer) {
757
+ this.#log.warn(`Tx ${meta.txHash} not found in DB during validation`);
758
+ invalid.push(meta.txHash);
759
+ continue;
760
+ }
761
+
762
+ const tx = Tx.fromBuffer(buffer);
763
+ const result = await this.#pendingTxValidator.validateTx(tx);
764
+
765
+ if (result.result === 'valid') {
766
+ valid.push(meta);
767
+ } else {
768
+ this.#log.info(`Tx ${meta.txHash} failed validation: ${result.reason?.join(', ')}`);
769
+ invalid.push(meta.txHash);
770
+ }
771
+ }
772
+
773
+ return { valid, invalid };
774
+ }
775
+
776
+ /**
777
+ * Resolves nullifier conflicts between incoming txs and existing pending txs.
778
+ * Modifies the pending indices during iteration to maintain consistent state
779
+ * for subsequent conflict checks within the same batch.
780
+ */
781
+ #applyNullifierConflictResolution(txs: TxMetaData[]): { added: TxMetaData[]; toEvict: string[] } {
782
+ const added: TxMetaData[] = [];
783
+ const toEvict: string[] = [];
784
+
785
+ for (const meta of txs) {
786
+ const conflict = checkNullifierConflict(
787
+ meta,
788
+ nullifier => this.#nullifierToTxHash.get(nullifier),
789
+ txHash => this.#metadata.get(txHash),
790
+ );
791
+ if (conflict.shouldIgnore) {
792
+ // Lower priority than existing - don't add, mark for deletion
793
+ toEvict.push(meta.txHash);
794
+ } else {
795
+ // Higher priority - evict existing conflicts
796
+ toEvict.push(...conflict.txHashesToEvict);
797
+ // Remove evicted from indices immediately for subsequent checks
798
+ for (const evictHash of conflict.txHashesToEvict) {
799
+ const evictMeta = this.#metadata.get(evictHash);
800
+ if (evictMeta) {
801
+ this.#removeFromPendingIndices(evictMeta);
802
+ }
803
+ }
804
+ // Add to pending indices immediately so subsequent txs in the batch see this tx
805
+ this.#addToPendingIndices(meta);
806
+ added.push(meta);
807
+ }
808
+ }
809
+
810
+ return { added, toEvict };
811
+ }
812
+
813
+ // --- State Transition Steps ---
814
+
815
+ /** Clears the mined status from transactions, returning them for further processing */
816
+ #unmineTxs(txs: TxMetaData[]): TxMetaData[] {
817
+ for (const meta of txs) {
818
+ meta.minedL2BlockId = undefined;
819
+ }
820
+ return txs;
821
+ }
822
+
823
+ /** Removes protection from tx hashes and clears them from the protected map */
824
+ #clearProtection(txHashes: string[]): void {
825
+ for (const txHashStr of txHashes) {
826
+ this.#protectedTransactions.delete(txHashStr);
827
+ }
828
+ }
829
+
830
+ // --- Batch Operation Steps ---
831
+
832
+ /** Deletes a batch of transactions permanently */
833
+ async #deleteTxsBatch(txHashes: string[]): Promise<void> {
834
+ if (txHashes.length === 0) {
835
+ return;
836
+ }
837
+
838
+ await this.#store.transactionAsync(async () => {
839
+ for (const txHashStr of txHashes) {
840
+ await this.#deleteTx(txHashStr);
841
+ }
842
+ });
843
+
844
+ this.#callbacks.onTxsRemoved(txHashes);
845
+ }
846
+
847
+ // --- Block & Tx Info Steps ---
848
+
849
+ /** Builds a block ID from a block header */
850
+ async #buildBlockId(block: BlockHeader): Promise<L2BlockId> {
851
+ return {
852
+ number: block.globalVariables.blockNumber,
853
+ hash: (await block.hash()).toString(),
854
+ };
855
+ }
856
+
857
+ /** Checks if a tx is already mined and returns its block ID if so */
858
+ async #getMinedBlockId(txHash: TxHash): Promise<L2BlockId | undefined> {
859
+ const txEffect = await this.#l2BlockSource.getTxEffect(txHash);
860
+ if (!txEffect) {
861
+ return undefined;
862
+ }
863
+ return {
864
+ number: txEffect.l2BlockNumber,
865
+ hash: txEffect.l2BlockHash.toString(),
866
+ };
867
+ }
868
+
869
+ /** Marks a batch of transactions as mined */
870
+ #markTxsAsMined(metas: TxMetaData[], blockId: L2BlockId): void {
871
+ for (const meta of metas) {
872
+ this.#markAsMined(meta, blockId);
873
+ }
874
+ }
875
+
876
+ // --- Add Transaction Steps ---
877
+
878
+ /** Persists a transaction to the database */
879
+ async #persistTx(txHashStr: string, tx: Tx): Promise<void> {
880
+ await this.#txsDB.set(txHashStr, tx.toBuffer());
881
+ }
882
+
883
+ /** Adds a new transaction as protected, returning its metadata */
884
+ async #addNewProtectedTx(tx: Tx, slotNumber: SlotNumber): Promise<TxMetaData> {
885
+ const txHashStr = tx.getTxHash().toString();
886
+ const meta = await buildTxMetaData(tx);
887
+
888
+ this.#protectedTransactions.set(txHashStr, slotNumber);
889
+ await this.#persistTx(txHashStr, tx);
890
+ this.#metadata.set(txHashStr, meta);
891
+ // Don't add to pending indices since it's protected
892
+
893
+ this.#log.verbose(`Added protected tx ${txHashStr} for slot ${slotNumber}`);
894
+ return meta;
895
+ }
896
+
897
+ /** Adds a new transaction as mined, returning its metadata */
898
+ async #addNewMinedTx(tx: Tx, blockId: L2BlockId): Promise<TxMetaData> {
899
+ const txHashStr = tx.getTxHash().toString();
900
+ const meta = await buildTxMetaData(tx);
901
+ meta.minedL2BlockId = blockId;
902
+
903
+ await this.#persistTx(txHashStr, tx);
904
+ this.#metadata.set(txHashStr, meta);
905
+ // Don't add to pending indices since it's mined
906
+
907
+ this.#log.verbose(`Added mined tx ${txHashStr} from block ${blockId.number}`);
908
+ return meta;
909
+ }
910
+
911
+ // --- Hydration Steps ---
912
+
913
+ /** Loads all transactions from the database, returning loaded txs and deserialization errors */
914
+ async #loadAllTxsFromDb(): Promise<{
915
+ loaded: { tx: Tx; meta: TxMetaData }[];
916
+ errors: string[];
917
+ }> {
918
+ const loaded: { tx: Tx; meta: TxMetaData }[] = [];
919
+ const errors: string[] = [];
920
+
921
+ for await (const [txHashStr, buffer] of this.#txsDB.entriesAsync()) {
922
+ try {
923
+ const tx = Tx.fromBuffer(buffer);
924
+ const meta = await buildTxMetaData(tx);
925
+ loaded.push({ tx, meta });
926
+ } catch (err) {
927
+ this.#log.warn(`Failed to deserialize tx ${txHashStr}, deleting`, { err });
928
+ errors.push(txHashStr);
929
+ }
930
+ }
931
+
932
+ return { loaded, errors };
933
+ }
934
+
935
+ /** Queries block source and marks mined status on transaction metadata */
936
+ async #markMinedStatusBatch(metas: TxMetaData[]): Promise<void> {
937
+ for (const meta of metas) {
938
+ try {
939
+ const txEffect = await this.#l2BlockSource.getTxEffect(TxHash.fromString(meta.txHash));
940
+ if (txEffect) {
941
+ meta.minedL2BlockId = {
942
+ number: txEffect.l2BlockNumber,
943
+ hash: txEffect.l2BlockHash.toString(),
944
+ };
945
+ }
946
+ } catch (err) {
947
+ this.#log.warn(`Failed to check mined status for tx ${meta.txHash}`, { err });
948
+ }
949
+ }
950
+ }
951
+
952
+ /** Partitions transactions by mined status */
953
+ #partitionByMinedStatus(txs: { tx: Tx; meta: TxMetaData }[]): {
954
+ mined: TxMetaData[];
955
+ nonMined: { tx: Tx; meta: TxMetaData }[];
956
+ } {
957
+ const mined: TxMetaData[] = [];
958
+ const nonMined: { tx: Tx; meta: TxMetaData }[] = [];
959
+
960
+ for (const entry of txs) {
961
+ if (entry.meta.minedL2BlockId !== undefined) {
962
+ mined.push(entry.meta);
963
+ } else {
964
+ nonMined.push(entry);
965
+ }
966
+ }
967
+
968
+ return { mined, nonMined };
969
+ }
970
+
971
+ /** Validates non-mined transactions, returning valid metadata and invalid hashes */
972
+ async #validateNonMinedTxs(txs: { tx: Tx; meta: TxMetaData }[]): Promise<{ valid: TxMetaData[]; invalid: string[] }> {
973
+ const valid: TxMetaData[] = [];
974
+ const invalid: string[] = [];
975
+
976
+ for (const { tx, meta } of txs) {
977
+ const result = await this.#pendingTxValidator.validateTx(tx);
978
+ if (result.result === 'valid') {
979
+ valid.push(meta);
980
+ } else {
981
+ this.#log.info(`Removing invalid tx ${meta.txHash} on startup: ${result.reason?.join(', ')}`);
982
+ invalid.push(meta.txHash);
983
+ }
984
+ }
985
+
986
+ return { valid, invalid };
987
+ }
988
+
989
+ /** Populates metadata index for mined transactions */
990
+ #populateMinedIndices(metas: TxMetaData[]): void {
991
+ for (const meta of metas) {
992
+ this.#metadata.set(meta.txHash, meta);
993
+ }
994
+ }
995
+
996
+ /**
997
+ * Rebuilds the pending pool by processing each tx through pre-add rules.
998
+ * Starts with an empty pending pool and adds txs one by one, resolving conflicts.
999
+ * Returns the list of accepted and rejected tx hashes.
1000
+ */
1001
+ async #rebuildPendingPool(metas: TxMetaData[]): Promise<{ accepted: string[]; rejected: string[] }> {
1002
+ const accepted = new Set<string>();
1003
+ const rejected: string[] = [];
1004
+ const poolAccess = this.#createPreAddPoolAccess();
1005
+
1006
+ for (const meta of metas) {
1007
+ // Run pre-add rules against current pending pool state (metadata not yet in pool)
1008
+ const preAddResult = await this.#evictionManager.runPreAddRules(meta, poolAccess);
1009
+
1010
+ if (preAddResult.shouldIgnore) {
1011
+ // Transaction rejected - mark for deletion from DB
1012
+ rejected.push(meta.txHash);
1013
+ this.#log.debug(`Rejected tx ${meta.txHash} during rebuild: ${preAddResult.reason}`);
1014
+ continue;
1015
+ }
1016
+
1017
+ // Evict any conflicting txs identified by pre-add rules
1018
+ for (const evictHashStr of preAddResult.txHashesToEvict) {
1019
+ const evictMeta = this.#metadata.get(evictHashStr);
1020
+ if (evictMeta) {
1021
+ this.#removeFromPendingIndices(evictMeta);
1022
+ this.#metadata.delete(evictHashStr);
1023
+ rejected.push(evictHashStr);
1024
+ accepted.delete(evictHashStr);
1025
+ this.#log.debug(`Evicted tx ${evictHashStr} during rebuild due to conflict with ${meta.txHash}`);
1026
+ }
1027
+ }
1028
+
1029
+ // Add to metadata and pending indices
1030
+ this.#addToIndices(meta);
1031
+ accepted.add(meta.txHash);
1032
+ }
1033
+
1034
+ this.#log.info(`Rebuilt pending pool: ${accepted.size} accepted, ${rejected.length} rejected`);
1035
+ return { accepted: [...accepted], rejected };
1036
+ }
1037
+
1038
+ // --- Add Pending Tx Steps ---
1039
+
1040
+ /** Checks if a tx is a duplicate (already in pool) */
1041
+ #isDuplicateTx(txHashStr: string): boolean {
1042
+ return this.#metadata.has(txHashStr);
1043
+ }
1044
+
1045
+ /** Adds a new pending tx to the pool, returning its metadata */
1046
+ async #addNewPendingTx(tx: Tx): Promise<TxMetaData> {
1047
+ const txHashStr = tx.getTxHash().toString();
1048
+ const meta = await buildTxMetaData(tx);
1049
+
1050
+ await this.#persistTx(txHashStr, tx);
1051
+ this.#addToIndices(meta);
1052
+
1053
+ this.#log.verbose(`Added tx ${txHashStr} to pool`, {
1054
+ eventName: 'tx-added-to-pool',
1055
+ state: this.#getTxState(meta),
1056
+ });
1057
+
1058
+ return meta;
1059
+ }
1060
+
1061
+ // ============================================================================
1062
+ // HELPER FUNCTIONS - Index Management
1063
+ // ============================================================================
1064
+
1065
+ #addToIndices(meta: TxMetaData): void {
1066
+ this.#metadata.set(meta.txHash, meta);
1067
+
1068
+ if (this.#getTxState(meta) === 'pending') {
1069
+ this.#addToPendingIndices(meta);
1070
+ }
1071
+ // Protected and mined txs don't go into pending indices
1072
+ }
1073
+
1074
+ #addToPendingIndices(meta: TxMetaData): void {
1075
+ // Add to nullifier index
1076
+ for (const nullifier of meta.nullifiers) {
1077
+ this.#nullifierToTxHash.set(nullifier, meta.txHash);
1078
+ }
1079
+
1080
+ // Add to fee payer index
1081
+ let feePayerSet = this.#feePayerToTxHashes.get(meta.feePayer);
1082
+ if (!feePayerSet) {
1083
+ feePayerSet = new Set();
1084
+ this.#feePayerToTxHashes.set(meta.feePayer, feePayerSet);
1085
+ }
1086
+ feePayerSet.add(meta.txHash);
1087
+
1088
+ // Add to priority bucket
1089
+ let prioritySet = this.#pendingByPriority.get(meta.priorityFee);
1090
+ if (!prioritySet) {
1091
+ prioritySet = new Set();
1092
+ this.#pendingByPriority.set(meta.priorityFee, prioritySet);
1093
+ }
1094
+ prioritySet.add(meta.txHash);
1095
+ }
1096
+
1097
+ #removeFromPendingIndices(meta: TxMetaData): void {
1098
+ // Remove from nullifier index
1099
+ for (const nullifier of meta.nullifiers) {
1100
+ this.#nullifierToTxHash.delete(nullifier);
1101
+ }
1102
+
1103
+ // Remove from fee payer index
1104
+ const feePayerSet = this.#feePayerToTxHashes.get(meta.feePayer);
1105
+ if (feePayerSet) {
1106
+ feePayerSet.delete(meta.txHash);
1107
+ if (feePayerSet.size === 0) {
1108
+ this.#feePayerToTxHashes.delete(meta.feePayer);
1109
+ }
1110
+ }
1111
+
1112
+ // Remove from priority map
1113
+ const hashSet = this.#pendingByPriority.get(meta.priorityFee);
1114
+ if (hashSet) {
1115
+ hashSet.delete(meta.txHash);
1116
+ if (hashSet.size === 0) {
1117
+ this.#pendingByPriority.delete(meta.priorityFee);
1118
+ }
1119
+ }
1120
+ }
1121
+
1122
+ #updateProtection(txHashStr: string, slotNumber: SlotNumber): void {
1123
+ const currentSlot = this.#protectedTransactions.get(txHashStr);
1124
+
1125
+ // Only update if not already protected at an equal or later slot
1126
+ if (currentSlot !== undefined && currentSlot >= slotNumber) {
1127
+ return;
1128
+ }
1129
+
1130
+ // Remove from pending indices if transitioning from pending to protected
1131
+ if (currentSlot === undefined) {
1132
+ const meta = this.#metadata.get(txHashStr);
1133
+ if (meta) {
1134
+ this.#removeFromPendingIndices(meta);
1135
+ }
1136
+ }
1137
+
1138
+ this.#protectedTransactions.set(txHashStr, slotNumber);
1139
+ }
1140
+
1141
+ #markAsMined(meta: TxMetaData, blockId: L2BlockId): void {
1142
+ meta.minedL2BlockId = blockId;
1143
+ // Safe to call unconditionally - removeFromPendingIndices is idempotent
1144
+ this.#removeFromPendingIndices(meta);
1145
+ }
1146
+
1147
+ async #deleteTx(txHashStr: string): Promise<void> {
1148
+ const meta = this.#metadata.get(txHashStr);
1149
+ if (!meta) {
1150
+ return;
1151
+ }
1152
+
1153
+ // Remove from all indices
1154
+ this.#metadata.delete(txHashStr);
1155
+ this.#protectedTransactions.delete(txHashStr);
1156
+ this.#removeFromPendingIndices(meta);
1157
+
1158
+ // Remove from persistence
1159
+ await this.#txsDB.delete(txHashStr);
1160
+ }
1161
+
1162
+ // ============================================================================
1163
+ // HELPER FUNCTIONS - Adapters
1164
+ // ============================================================================
1165
+
1166
+ /** Gets all pending transactions for a given fee payer. */
1167
+ #getFeePayerPendingTxs(feePayer: string): TxMetaData[] {
1168
+ const txHashes = this.#feePayerToTxHashes.get(feePayer);
1169
+ if (!txHashes) {
1170
+ return [];
1171
+ }
1172
+ const result: TxMetaData[] = [];
1173
+ for (const txHashStr of txHashes) {
1174
+ const meta = this.#metadata.get(txHashStr);
1175
+ if (meta && this.#getTxState(meta) === 'pending') {
1176
+ result.push(meta);
1177
+ }
1178
+ }
1179
+ return result;
1180
+ }
1181
+
1182
+ /**
1183
+ * Creates a PoolOperations adapter for use with the eviction manager.
1184
+ */
1185
+ #createPoolOperations(): PoolOperations {
1186
+ return {
1187
+ getPendingTxs: (): TxMetaData[] => {
1188
+ const result: TxMetaData[] = [];
1189
+ for (const hashSet of this.#pendingByPriority.values()) {
1190
+ for (const txHashStr of hashSet) {
1191
+ const meta = this.#metadata.get(txHashStr);
1192
+ if (meta) {
1193
+ result.push(meta);
1194
+ }
1195
+ }
1196
+ }
1197
+ return result;
1198
+ },
1199
+ getPendingFeePayers: (): string[] => {
1200
+ return Array.from(this.#feePayerToTxHashes.keys());
1201
+ },
1202
+ getFeePayerPendingTxs: (feePayer: string): TxMetaData[] => {
1203
+ return this.#getFeePayerPendingTxs(feePayer);
1204
+ },
1205
+ getPendingTxCount: (): number => {
1206
+ return this.getPendingTxCount();
1207
+ },
1208
+ getLowestPriorityPending: (limit: number): string[] => {
1209
+ return this.getLowestPriorityPending(limit).map(h => h.toString());
1210
+ },
1211
+ deleteTxs: async (txHashes: string[]): Promise<void> => {
1212
+ await this.#store.transactionAsync(async () => {
1213
+ for (const txHashStr of txHashes) {
1214
+ await this.#deleteTx(txHashStr);
1215
+ }
1216
+ });
1217
+ this.#callbacks.onTxsRemoved(txHashes);
1218
+ },
1219
+ };
1220
+ }
1221
+
1222
+ /**
1223
+ * Creates a PreAddPoolAccess adapter for use with pre-add eviction rules.
1224
+ * All methods work with strings and TxMetaData for efficiency.
1225
+ */
1226
+ #createPreAddPoolAccess(): PreAddPoolAccess {
1227
+ return {
1228
+ getMetadata: (txHashStr: string): TxMetaData | undefined => {
1229
+ const meta = this.#metadata.get(txHashStr);
1230
+ if (!meta || this.#getTxState(meta) !== 'pending') {
1231
+ return undefined;
1232
+ }
1233
+ return meta;
1234
+ },
1235
+ getTxHashByNullifier: (nullifier: string): string | undefined => {
1236
+ return this.#nullifierToTxHash.get(nullifier);
1237
+ },
1238
+ getFeePayerBalance: async (feePayer: string): Promise<bigint> => {
1239
+ const db = this.#worldStateSynchronizer.getCommitted();
1240
+ const publicStateSource = new DatabasePublicStateSource(db);
1241
+ const balance = await publicStateSource.storageRead(
1242
+ ProtocolContractAddress.FeeJuice,
1243
+ await computeFeePayerBalanceStorageSlot(AztecAddress.fromString(feePayer)),
1244
+ );
1245
+ return balance.toBigInt();
1246
+ },
1247
+ getFeePayerPendingTxs: (feePayer: string): TxMetaData[] => {
1248
+ return this.#getFeePayerPendingTxs(feePayer);
1249
+ },
1250
+ getPendingTxCount: (): number => {
1251
+ return this.getPendingTxCount();
1252
+ },
1253
+ getLowestPriorityPendingTx: (): TxMetaData | undefined => {
1254
+ // Iterate in ascending order to find the lowest priority
1255
+ for (const txHashStr of this.#iteratePendingByPriority('asc')) {
1256
+ const meta = this.#metadata.get(txHashStr);
1257
+ if (meta) {
1258
+ return meta;
1259
+ }
1260
+ }
1261
+ return undefined;
1262
+ },
1263
+ };
1264
+ }
1265
+ }