@aztec/p2p 0.0.1-commit.e3c1de76 → 0.0.1-commit.e558bd1c

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 (188) hide show
  1. package/dest/client/factory.d.ts +3 -3
  2. package/dest/client/factory.d.ts.map +1 -1
  3. package/dest/client/factory.js +5 -3
  4. package/dest/client/interface.d.ts +9 -2
  5. package/dest/client/interface.d.ts.map +1 -1
  6. package/dest/client/p2p_client.d.ts +7 -4
  7. package/dest/client/p2p_client.d.ts.map +1 -1
  8. package/dest/client/p2p_client.js +22 -7
  9. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker.js +1 -1
  10. package/dest/config.d.ts +9 -3
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +3 -1
  13. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts +94 -87
  14. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts.map +1 -1
  15. package/dest/mem_pools/attestation_pool/attestation_pool.js +411 -3
  16. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts +2 -2
  17. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts.map +1 -1
  18. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.js +351 -85
  19. package/dest/mem_pools/attestation_pool/index.d.ts +2 -3
  20. package/dest/mem_pools/attestation_pool/index.d.ts.map +1 -1
  21. package/dest/mem_pools/attestation_pool/index.js +1 -2
  22. package/dest/mem_pools/index.d.ts +2 -2
  23. package/dest/mem_pools/index.d.ts.map +1 -1
  24. package/dest/mem_pools/index.js +1 -1
  25. package/dest/mem_pools/interface.d.ts +3 -3
  26. package/dest/mem_pools/interface.d.ts.map +1 -1
  27. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts +2 -0
  28. package/dest/mem_pools/tx_pool_v2/archive/index.d.ts.map +1 -0
  29. package/dest/mem_pools/tx_pool_v2/archive/index.js +1 -0
  30. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts +43 -0
  31. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts.map +1 -0
  32. package/dest/mem_pools/tx_pool_v2/archive/tx_archive.js +103 -0
  33. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts +47 -0
  34. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts.map +1 -0
  35. package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.js +119 -0
  36. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts +17 -0
  37. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts.map +1 -0
  38. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.js +90 -0
  39. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts +19 -0
  40. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts.map +1 -0
  41. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.js +89 -0
  42. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts +10 -0
  43. package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts.map +1 -0
  44. package/dest/mem_pools/tx_pool_v2/eviction/index.js +11 -0
  45. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts +131 -0
  46. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts.map +1 -0
  47. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.js +17 -0
  48. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts +15 -0
  49. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts.map +1 -0
  50. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.js +63 -0
  51. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts +17 -0
  52. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts.map +1 -0
  53. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.js +91 -0
  54. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts +16 -0
  55. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts.map +1 -0
  56. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.js +70 -0
  57. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts +20 -0
  58. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts.map +1 -0
  59. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.js +63 -0
  60. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts +15 -0
  61. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts.map +1 -0
  62. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.js +19 -0
  63. package/dest/mem_pools/tx_pool_v2/index.d.ts +5 -0
  64. package/dest/mem_pools/tx_pool_v2/index.d.ts.map +1 -0
  65. package/dest/mem_pools/tx_pool_v2/index.js +4 -0
  66. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts +197 -0
  67. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts.map +1 -0
  68. package/dest/mem_pools/tx_pool_v2/interfaces.js +6 -0
  69. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts +71 -0
  70. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts.map +1 -0
  71. package/dest/mem_pools/tx_pool_v2/tx_metadata.js +95 -0
  72. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts +26 -0
  73. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts.map +1 -0
  74. package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.js +70 -0
  75. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts +99 -0
  76. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts.map +1 -0
  77. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.js +332 -0
  78. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts +55 -0
  79. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts.map +1 -0
  80. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.js +156 -0
  81. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts +69 -0
  82. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts.map +1 -0
  83. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.js +748 -0
  84. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts +3 -3
  85. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts.map +1 -1
  86. package/dest/services/dummy_service.d.ts +6 -2
  87. package/dest/services/dummy_service.d.ts.map +1 -1
  88. package/dest/services/dummy_service.js +3 -0
  89. package/dest/services/index.d.ts +2 -1
  90. package/dest/services/index.d.ts.map +1 -1
  91. package/dest/services/index.js +1 -0
  92. package/dest/services/libp2p/libp2p_service.d.ts +74 -33
  93. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -1
  94. package/dest/services/libp2p/libp2p_service.js +299 -228
  95. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts +4 -4
  96. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.d.ts.map +1 -1
  97. package/dest/services/reqresp/batch-tx-requester/batch_tx_requester.js +8 -8
  98. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts +6 -4
  99. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts.map +1 -1
  100. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.js +16 -11
  101. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts +15 -10
  102. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts.map +1 -1
  103. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.js +12 -11
  104. package/dest/services/service.d.ts +18 -1
  105. package/dest/services/service.d.ts.map +1 -1
  106. package/dest/services/tx_collection/config.d.ts +3 -3
  107. package/dest/services/tx_collection/config.js +3 -3
  108. package/dest/services/tx_collection/fast_tx_collection.d.ts +4 -5
  109. package/dest/services/tx_collection/fast_tx_collection.d.ts.map +1 -1
  110. package/dest/services/tx_collection/fast_tx_collection.js +10 -14
  111. package/dest/services/tx_collection/index.d.ts +1 -1
  112. package/dest/services/tx_collection/proposal_tx_collector.d.ts +12 -12
  113. package/dest/services/tx_collection/proposal_tx_collector.d.ts.map +1 -1
  114. package/dest/services/tx_collection/proposal_tx_collector.js +4 -5
  115. package/dest/services/tx_file_store/config.d.ts +18 -0
  116. package/dest/services/tx_file_store/config.d.ts.map +1 -0
  117. package/dest/services/tx_file_store/config.js +26 -0
  118. package/dest/services/tx_file_store/index.d.ts +4 -0
  119. package/dest/services/tx_file_store/index.d.ts.map +1 -0
  120. package/dest/services/tx_file_store/index.js +3 -0
  121. package/dest/services/tx_file_store/instrumentation.d.ts +15 -0
  122. package/dest/services/tx_file_store/instrumentation.d.ts.map +1 -0
  123. package/dest/services/tx_file_store/instrumentation.js +29 -0
  124. package/dest/services/tx_file_store/tx_file_store.d.ts +47 -0
  125. package/dest/services/tx_file_store/tx_file_store.d.ts.map +1 -0
  126. package/dest/services/tx_file_store/tx_file_store.js +149 -0
  127. package/dest/test-helpers/testbench-utils.d.ts +10 -16
  128. package/dest/test-helpers/testbench-utils.d.ts.map +1 -1
  129. package/dest/test-helpers/testbench-utils.js +32 -30
  130. package/dest/testbench/p2p_client_testbench_worker.js +1 -1
  131. package/package.json +14 -14
  132. package/src/client/factory.ts +7 -4
  133. package/src/client/interface.ts +13 -1
  134. package/src/client/p2p_client.ts +30 -8
  135. package/src/client/test/tx_proposal_collector/proposal_tx_collector_worker.ts +1 -1
  136. package/src/config.ts +8 -1
  137. package/src/mem_pools/attestation_pool/attestation_pool.ts +444 -90
  138. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +436 -100
  139. package/src/mem_pools/attestation_pool/index.ts +9 -2
  140. package/src/mem_pools/index.ts +1 -1
  141. package/src/mem_pools/interface.ts +2 -2
  142. package/src/mem_pools/tx_pool_v2/README.md +209 -0
  143. package/src/mem_pools/tx_pool_v2/archive/index.ts +1 -0
  144. package/src/mem_pools/tx_pool_v2/archive/tx_archive.ts +120 -0
  145. package/src/mem_pools/tx_pool_v2/eviction/eviction_manager.ts +147 -0
  146. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.ts +118 -0
  147. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.ts +111 -0
  148. package/src/mem_pools/tx_pool_v2/eviction/index.ts +23 -0
  149. package/src/mem_pools/tx_pool_v2/eviction/interfaces.ts +164 -0
  150. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.ts +74 -0
  151. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.ts +101 -0
  152. package/src/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.ts +86 -0
  153. package/src/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.ts +72 -0
  154. package/src/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.ts +31 -0
  155. package/src/mem_pools/tx_pool_v2/index.ts +11 -0
  156. package/src/mem_pools/tx_pool_v2/interfaces.ts +227 -0
  157. package/src/mem_pools/tx_pool_v2/tx_metadata.ts +161 -0
  158. package/src/mem_pools/tx_pool_v2/tx_pool_bench_metrics.ts +77 -0
  159. package/src/mem_pools/tx_pool_v2/tx_pool_indices.ts +417 -0
  160. package/src/mem_pools/tx_pool_v2/tx_pool_v2.ts +212 -0
  161. package/src/mem_pools/tx_pool_v2/tx_pool_v2_impl.ts +882 -0
  162. package/src/msg_validators/attestation_validator/fisherman_attestation_validator.ts +2 -2
  163. package/src/services/dummy_service.ts +6 -0
  164. package/src/services/index.ts +1 -0
  165. package/src/services/libp2p/libp2p_service.ts +304 -230
  166. package/src/services/reqresp/batch-tx-requester/README.md +7 -7
  167. package/src/services/reqresp/batch-tx-requester/batch_tx_requester.ts +11 -11
  168. package/src/services/reqresp/protocols/block_txs/block_txs_handler.ts +22 -13
  169. package/src/services/reqresp/protocols/block_txs/block_txs_reqresp.ts +21 -15
  170. package/src/services/service.ts +20 -0
  171. package/src/services/tx_collection/config.ts +6 -6
  172. package/src/services/tx_collection/fast_tx_collection.ts +14 -24
  173. package/src/services/tx_collection/index.ts +1 -1
  174. package/src/services/tx_collection/proposal_tx_collector.ts +12 -14
  175. package/src/services/tx_file_store/config.ts +43 -0
  176. package/src/services/tx_file_store/index.ts +3 -0
  177. package/src/services/tx_file_store/instrumentation.ts +36 -0
  178. package/src/services/tx_file_store/tx_file_store.ts +173 -0
  179. package/src/test-helpers/testbench-utils.ts +18 -39
  180. package/src/testbench/p2p_client_testbench_worker.ts +1 -1
  181. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts +0 -40
  182. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts.map +0 -1
  183. package/dest/mem_pools/attestation_pool/kv_attestation_pool.js +0 -218
  184. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts +0 -31
  185. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts.map +0 -1
  186. package/dest/mem_pools/attestation_pool/memory_attestation_pool.js +0 -180
  187. package/src/mem_pools/attestation_pool/kv_attestation_pool.ts +0 -320
  188. package/src/mem_pools/attestation_pool/memory_attestation_pool.ts +0 -264
@@ -0,0 +1,882 @@
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 { type TxMetaData, type TxState, buildTxMetaData, checkNullifierConflict } from './tx_metadata.js';
33
+ import { TxPoolIndices } from './tx_pool_indices.js';
34
+
35
+ /**
36
+ * Callbacks for the implementation to notify the outer class about events and metrics.
37
+ */
38
+ export interface TxPoolV2Callbacks {
39
+ onTxsAdded: (txs: Tx[], opts: { source?: string }) => void;
40
+ onTxsRemoved: (txHashes: string[] | bigint[]) => void;
41
+ }
42
+
43
+ /**
44
+ * Implementation of TxPoolV2 logic.
45
+ *
46
+ * This class contains all the actual transaction pool logic.
47
+ */
48
+ export class TxPoolV2Impl {
49
+ // === Persistence ===
50
+ #store: AztecAsyncKVStore;
51
+ #txsDB: AztecAsyncMap<string, Buffer>;
52
+
53
+ // === Dependencies ===
54
+ #l2BlockSource: L2BlockSource;
55
+ #worldStateSynchronizer: WorldStateSynchronizer;
56
+ #pendingTxValidator: TxValidator<Tx>;
57
+
58
+ // === In-Memory Indices ===
59
+ #indices: TxPoolIndices = new TxPoolIndices();
60
+
61
+ // === Config & Services ===
62
+ #config: TxPoolV2Config;
63
+ #archive: TxArchive;
64
+ #evictionManager: EvictionManager;
65
+ #log: Logger;
66
+ #callbacks: TxPoolV2Callbacks;
67
+
68
+ constructor(
69
+ store: AztecAsyncKVStore,
70
+ archiveStore: AztecAsyncKVStore,
71
+ deps: TxPoolV2Dependencies,
72
+ callbacks: TxPoolV2Callbacks,
73
+ config: Partial<TxPoolV2Config> = {},
74
+ log: Logger,
75
+ ) {
76
+ this.#store = store;
77
+ this.#txsDB = store.openMap('txs');
78
+
79
+ this.#l2BlockSource = deps.l2BlockSource;
80
+ this.#worldStateSynchronizer = deps.worldStateSynchronizer;
81
+ this.#pendingTxValidator = deps.pendingTxValidator;
82
+
83
+ this.#config = { ...DEFAULT_TX_POOL_V2_CONFIG, ...config };
84
+ this.#archive = new TxArchive(archiveStore, this.#config.archivedTxLimit, log);
85
+ this.#log = log;
86
+ this.#callbacks = callbacks;
87
+
88
+ // Setup eviction manager with rules
89
+ this.#evictionManager = new EvictionManager(this.#createPoolOperations(), log);
90
+
91
+ // Pre-add rules (run during addPendingTxs) - work with TxMetaData
92
+ this.#evictionManager.registerPreAddRule(new NullifierConflictRule());
93
+ this.#evictionManager.registerPreAddRule(new FeePayerBalancePreAddRule());
94
+ this.#evictionManager.registerPreAddRule(
95
+ new LowPriorityPreAddRule({ maxPoolSize: this.#config.maxPendingTxCount }),
96
+ );
97
+
98
+ // Post-event eviction rules (run after events to check ALL pending txs)
99
+ this.#evictionManager.registerRule(new InvalidTxsAfterMiningRule());
100
+ this.#evictionManager.registerRule(new InvalidTxsAfterReorgRule(deps.worldStateSynchronizer));
101
+ this.#evictionManager.registerRule(new FeePayerBalanceEvictionRule(deps.worldStateSynchronizer));
102
+ // LowPriorityEvictionRule handles cases where txs become pending via prepareForSlot (unprotect)
103
+ // The pre-add rule handles the addPendingTxs case, but post-event is needed for unprotect
104
+ this.#evictionManager.registerRule(new LowPriorityEvictionRule({ maxPoolSize: this.#config.maxPendingTxCount }));
105
+ }
106
+
107
+ // ============================================================================
108
+ // PUBLIC IMPLEMENTATION METHODS
109
+ // ============================================================================
110
+
111
+ /**
112
+ * Hydrates the in-memory state from the database on startup.
113
+ * Pipeline: Load → Check Mined Status → Partition → Validate Non-Mined → Rebuild Pending Pool → Delete Invalid
114
+ *
115
+ * Note: Protected status is lost on restart. All non-mined txs are rebuilt as pending
116
+ * by running pre-add rules to resolve nullifier conflicts, balance checks, and pool size limits.
117
+ */
118
+ async hydrateFromDatabase(): Promise<void> {
119
+ // Step 1: Load all transactions from DB
120
+ const { loaded, errors: deserializationErrors } = await this.#loadAllTxsFromDb();
121
+
122
+ // Step 2: Check mined status for each tx
123
+ await this.#markMinedStatusBatch(loaded.map(l => l.meta));
124
+
125
+ // Step 3: Partition by mined status
126
+ const mined: TxMetaData[] = [];
127
+ const nonMined: { tx: Tx; meta: TxMetaData }[] = [];
128
+ for (const entry of loaded) {
129
+ if (entry.meta.minedL2BlockId !== undefined) {
130
+ mined.push(entry.meta);
131
+ } else {
132
+ nonMined.push(entry);
133
+ }
134
+ }
135
+
136
+ // Step 4: Validate non-mined transactions
137
+ const { valid, invalid } = await this.#validateTxBatch(nonMined, 'on startup');
138
+
139
+ // Step 5: Populate mined indices (these don't need conflict resolution)
140
+ for (const meta of mined) {
141
+ this.#indices.addMined(meta);
142
+ }
143
+
144
+ // Step 6: Rebuild pending pool by running pre-add rules for each tx
145
+ // This resolves nullifier conflicts, fee payer balance issues, and pool size limits
146
+ const { rejected } = await this.#rebuildPendingPool(valid);
147
+
148
+ // Step 7: Delete invalid and rejected txs from DB only (indices were never populated for these)
149
+ const toDelete = [...deserializationErrors, ...invalid, ...rejected];
150
+ if (toDelete.length === 0) {
151
+ return;
152
+ }
153
+ await this.#store.transactionAsync(async () => {
154
+ for (const txHashStr of toDelete) {
155
+ await this.#txsDB.delete(txHashStr);
156
+ }
157
+ });
158
+ this.#log.info(`Deleted ${toDelete.length} invalid/rejected transactions on startup`);
159
+ }
160
+
161
+ async addPendingTxs(txs: Tx[], opts: { source?: string }): Promise<AddTxsResult> {
162
+ const accepted: TxHash[] = [];
163
+ const ignored: TxHash[] = [];
164
+ const rejected: TxHash[] = [];
165
+ const acceptedPending = new Set<string>();
166
+
167
+ const poolAccess = this.#createPreAddPoolAccess();
168
+
169
+ await this.#store.transactionAsync(async () => {
170
+ for (const tx of txs) {
171
+ const txHash = tx.getTxHash();
172
+ const txHashStr = txHash.toString();
173
+
174
+ // Skip duplicates
175
+ if (this.#indices.has(txHashStr)) {
176
+ ignored.push(txHash);
177
+ continue;
178
+ }
179
+
180
+ // Check mined status first (applies to all paths)
181
+ const minedBlockId = await this.#getMinedBlockId(txHash);
182
+ const preProtectedSlot = this.#indices.getProtectionSlot(txHashStr);
183
+
184
+ if (minedBlockId) {
185
+ // Already mined - add directly (protection already set if pre-protected)
186
+ await this.#addTx(tx, { mined: minedBlockId }, opts);
187
+ accepted.push(txHash);
188
+ } else if (preProtectedSlot !== undefined) {
189
+ // Pre-protected and not mined - add as protected (bypass validation)
190
+ await this.#addTx(tx, { protected: preProtectedSlot }, opts);
191
+ accepted.push(txHash);
192
+ } else {
193
+ // Regular pending tx - validate and run pre-add rules
194
+ const result = await this.#tryAddRegularPendingTx(tx, opts, poolAccess, acceptedPending, ignored);
195
+ if (result.status === 'accepted') {
196
+ acceptedPending.add(txHashStr);
197
+ } else if (result.status === 'rejected') {
198
+ rejected.push(txHash);
199
+ } else {
200
+ ignored.push(txHash);
201
+ }
202
+ }
203
+ }
204
+ });
205
+
206
+ // Build final accepted list for pending txs (excludes intra-batch evictions)
207
+ for (const txHashStr of acceptedPending) {
208
+ accepted.push(TxHash.fromString(txHashStr));
209
+ }
210
+
211
+ // Run post-add eviction rules for pending txs
212
+ if (acceptedPending.size > 0) {
213
+ const feePayers = Array.from(acceptedPending).map(txHash => this.#indices.getMetadata(txHash)!.feePayer);
214
+ const uniqueFeePayers = new Set<string>(feePayers);
215
+ await this.#evictionManager.evictAfterNewTxs(Array.from(acceptedPending), [...uniqueFeePayers]);
216
+ }
217
+
218
+ return { accepted, ignored, rejected };
219
+ }
220
+
221
+ /** Validates and adds a regular pending tx. Returns status. */
222
+ async #tryAddRegularPendingTx(
223
+ tx: Tx,
224
+ opts: { source?: string },
225
+ poolAccess: PreAddPoolAccess,
226
+ acceptedPending: Set<string>,
227
+ ignored: TxHash[],
228
+ ): Promise<{ status: 'accepted' | 'ignored' | 'rejected' }> {
229
+ const txHash = tx.getTxHash();
230
+ const txHashStr = txHash.toString();
231
+
232
+ // Validate transaction
233
+ if (!(await this.#validateTx(tx))) {
234
+ return { status: 'rejected' };
235
+ }
236
+
237
+ // Build metadata and run pre-add rules
238
+ const meta = await buildTxMetaData(tx);
239
+ const preAddResult = await this.#evictionManager.runPreAddRules(meta, poolAccess);
240
+
241
+ if (preAddResult.shouldIgnore) {
242
+ this.#log.debug(`Ignoring tx ${txHashStr}: ${preAddResult.reason}`);
243
+ return { status: 'ignored' };
244
+ }
245
+
246
+ // Evict conflicts
247
+ for (const evictHashStr of preAddResult.txHashesToEvict) {
248
+ await this.#deleteTx(evictHashStr);
249
+ this.#log.debug(`Evicted tx ${evictHashStr} due to higher-fee tx ${txHashStr}`);
250
+ if (acceptedPending.has(evictHashStr)) {
251
+ // Evicted tx was from this batch - mark as ignored in result
252
+ acceptedPending.delete(evictHashStr);
253
+ ignored.push(TxHash.fromString(evictHashStr));
254
+ }
255
+ }
256
+
257
+ // Add the transaction
258
+ await this.#addTx(tx, 'pending', opts);
259
+ return { status: 'accepted' };
260
+ }
261
+
262
+ async canAddPendingTx(tx: Tx): Promise<'accepted' | 'ignored' | 'rejected'> {
263
+ const txHashStr = tx.getTxHash().toString();
264
+
265
+ // Check if already in pool
266
+ if (this.#indices.has(txHashStr)) {
267
+ return 'ignored';
268
+ }
269
+
270
+ // Validate transaction (no logging for dry-run check)
271
+ const validationResult = await this.#pendingTxValidator.validateTx(tx);
272
+ if (validationResult.result !== 'valid') {
273
+ return 'rejected';
274
+ }
275
+
276
+ // Build metadata and use pre-add rules
277
+ const meta = await buildTxMetaData(tx);
278
+ const poolAccess = this.#createPreAddPoolAccess();
279
+ const preAddResult = await this.#evictionManager.runPreAddRules(meta, poolAccess);
280
+
281
+ return preAddResult.shouldIgnore ? 'ignored' : 'accepted';
282
+ }
283
+
284
+ async addProtectedTxs(txs: Tx[], block: BlockHeader, opts: { source?: string }): Promise<void> {
285
+ const slotNumber = block.globalVariables.slotNumber;
286
+
287
+ await this.#store.transactionAsync(async () => {
288
+ for (const tx of txs) {
289
+ const txHash = tx.getTxHash();
290
+ const txHashStr = txHash.toString();
291
+ const isNew = !this.#indices.has(txHashStr);
292
+ const minedBlockId = await this.#getMinedBlockId(txHash);
293
+
294
+ if (isNew) {
295
+ // New tx - add as mined or protected (callback emitted by #addTx)
296
+ if (minedBlockId) {
297
+ await this.#addTx(tx, { mined: minedBlockId }, opts);
298
+ this.#indices.setProtection(txHashStr, slotNumber);
299
+ } else {
300
+ await this.#addTx(tx, { protected: slotNumber }, opts);
301
+ }
302
+ } else {
303
+ // Existing tx - update protection and mined status
304
+ this.#indices.updateProtection(txHashStr, slotNumber);
305
+ if (minedBlockId) {
306
+ const meta = this.#indices.getMetadata(txHashStr)!;
307
+ this.#indices.markAsMined(meta, minedBlockId);
308
+ }
309
+ }
310
+ }
311
+ });
312
+ }
313
+
314
+ protectTxs(txHashes: TxHash[], block: BlockHeader): TxHash[] {
315
+ const slotNumber = block.globalVariables.slotNumber;
316
+ const missing: TxHash[] = [];
317
+
318
+ for (const txHash of txHashes) {
319
+ const txHashStr = txHash.toString();
320
+
321
+ if (this.#indices.has(txHashStr)) {
322
+ // Update protection for existing tx
323
+ this.#indices.updateProtection(txHashStr, slotNumber);
324
+ } else {
325
+ // Pre-record protection for tx we don't have yet
326
+ this.#indices.setProtection(txHashStr, slotNumber);
327
+ missing.push(txHash);
328
+ }
329
+ }
330
+
331
+ return missing;
332
+ }
333
+
334
+ async addMinedTxs(txs: Tx[], block: BlockHeader, opts: { source?: string }): Promise<void> {
335
+ // Step 1: Build block ID
336
+ const blockId = await this.#buildBlockId(block);
337
+
338
+ await this.#store.transactionAsync(async () => {
339
+ for (const tx of txs) {
340
+ const txHashStr = tx.getTxHash().toString();
341
+ const existingMeta = this.#indices.getMetadata(txHashStr);
342
+
343
+ if (existingMeta) {
344
+ // Mark existing tx as mined
345
+ this.#indices.markAsMined(existingMeta, blockId);
346
+ } else {
347
+ // Add new mined tx (callback emitted by #addTx)
348
+ await this.#addTx(tx, { mined: blockId }, opts);
349
+ }
350
+ }
351
+ });
352
+ }
353
+
354
+ async handleMinedBlock(block: L2Block): Promise<void> {
355
+ // Step 1: Build block ID
356
+ const blockId = await this.#buildBlockId(block.header);
357
+
358
+ // Step 2: Extract tx hashes and nullifiers directly from the block
359
+ const txHashes = block.body.txEffects.map(tx => tx.txHash);
360
+ const nullifiers = block.body.txEffects.flatMap(tx => tx.nullifiers.map(n => n.toString()));
361
+
362
+ // Step 3: Collect fee payers from txs we have in the pool (for balance-based eviction)
363
+ const feePayers: string[] = [];
364
+ const found: TxMetaData[] = [];
365
+ for (const txHash of txHashes) {
366
+ const meta = this.#indices.getMetadata(txHash.toString());
367
+ if (meta) {
368
+ feePayers.push(meta.feePayer);
369
+ found.push(meta);
370
+ }
371
+ }
372
+
373
+ // Step 4: Mark txs as mined (only those we have in the pool)
374
+ for (const meta of found) {
375
+ this.#indices.markAsMined(meta, blockId);
376
+ }
377
+
378
+ // Step 5: Run eviction rules (remove pending txs with conflicting nullifiers/expired timestamps)
379
+ await this.#evictionManager.evictAfterNewBlock(block.header, nullifiers, feePayers);
380
+
381
+ this.#log.info(`Marked ${found.length} txs as mined in block ${blockId.number}`);
382
+ }
383
+
384
+ async prepareForSlot(slotNumber: SlotNumber): Promise<void> {
385
+ // Step 1: Find expired protected txs
386
+ const expiredProtected = this.#indices.findExpiredProtectedTxs(slotNumber);
387
+
388
+ // Step 2: Clear protection for all expired entries (including those without metadata)
389
+ this.#indices.clearProtection(expiredProtected);
390
+
391
+ // Step 3: Filter to only txs that have metadata and are not mined
392
+ const txsToRestore = this.#indices.filterRestorable(expiredProtected);
393
+ if (txsToRestore.length === 0) {
394
+ return;
395
+ }
396
+
397
+ this.#log.info(`Preparing for slot ${slotNumber}: unprotecting ${txsToRestore.length} txs`);
398
+
399
+ // Step 4: Validate for pending pool
400
+ const { valid, invalid } = await this.#loadAndValidateTxs(txsToRestore, 'during prepareForSlot');
401
+
402
+ // Step 5: Resolve nullifier conflicts and add winners to pending indices
403
+ const { added, toEvict } = this.#applyNullifierConflictResolution(valid);
404
+
405
+ // Step 6: Delete invalid and evicted txs
406
+ await this.#deleteTxsBatch([...invalid, ...toEvict]);
407
+
408
+ // Step 7: Run eviction rules (enforce pool size limit)
409
+ if (added.length > 0) {
410
+ const feePayers = added.map(meta => meta.feePayer);
411
+ const uniqueFeePayers = new Set<string>(feePayers);
412
+ await this.#evictionManager.evictAfterNewTxs(
413
+ added.map(m => m.txHash),
414
+ [...uniqueFeePayers],
415
+ );
416
+ }
417
+ }
418
+
419
+ async handlePrunedBlocks(latestBlock: L2BlockId): Promise<void> {
420
+ // Step 1: Find transactions mined after the prune point
421
+ const txsToUnmine = this.#indices.findTxsMinedAfter(latestBlock.number);
422
+ if (txsToUnmine.length === 0) {
423
+ this.#log.debug(`No transactions to un-mine for prune to block ${latestBlock.number}`);
424
+ return;
425
+ }
426
+
427
+ this.#log.info(`Handling prune to block ${latestBlock.number}: un-mining ${txsToUnmine.length} txs`);
428
+
429
+ // Step 2: Unmine - clear mined status from metadata
430
+ for (const meta of txsToUnmine) {
431
+ this.#indices.markAsUnmined(meta);
432
+ }
433
+
434
+ // Step 3: Filter out protected txs (they'll be handled by prepareForSlot)
435
+ const unprotectedTxs = this.#indices.filterUnprotected(txsToUnmine);
436
+
437
+ // Step 4: Validate for pending pool
438
+ const { valid, invalid } = await this.#loadAndValidateTxs(unprotectedTxs, 'during handlePrunedBlocks');
439
+
440
+ // Step 5: Resolve nullifier conflicts and add winners to pending indices
441
+ const { toEvict } = this.#applyNullifierConflictResolution(valid);
442
+
443
+ // Step 6: Delete invalid and evicted txs
444
+ await this.#deleteTxsBatch([...invalid, ...toEvict]);
445
+
446
+ // Step 7: Run eviction rules for ALL pending txs (not just restored ones)
447
+ // This handles cases like existing pending txs with invalid fee payer balances
448
+ await this.#evictionManager.evictAfterChainPrune(latestBlock.number);
449
+ }
450
+
451
+ async handleFailedExecution(txHashes: TxHash[]): Promise<void> {
452
+ // Delete failed txs
453
+ await this.#deleteTxsBatch(txHashes.map(h => h.toString()));
454
+
455
+ this.#log.info(`Deleted ${txHashes.length} failed txs`);
456
+ }
457
+
458
+ async handleFinalizedBlock(block: BlockHeader): Promise<void> {
459
+ const blockNumber = block.globalVariables.blockNumber;
460
+
461
+ // Step 1: Find txs mined at or before finalized block
462
+ const txsToFinalize = this.#indices.findTxsMinedAtOrBefore(blockNumber);
463
+ if (txsToFinalize.length === 0) {
464
+ return;
465
+ }
466
+
467
+ // Step 2: Collect txs for archiving (before deletion)
468
+ const txsToArchive: Tx[] = [];
469
+ if (this.#archive.isEnabled()) {
470
+ for (const txHashStr of txsToFinalize) {
471
+ const buffer = await this.#txsDB.getAsync(txHashStr);
472
+ if (buffer) {
473
+ txsToArchive.push(Tx.fromBuffer(buffer));
474
+ }
475
+ }
476
+ }
477
+
478
+ // Step 3: Delete from active pool
479
+ await this.#deleteTxsBatch(txsToFinalize);
480
+
481
+ // Step 4: Archive
482
+ if (txsToArchive.length > 0) {
483
+ await this.#archive.archiveTxs(txsToArchive);
484
+ }
485
+
486
+ this.#log.info(`Finalized ${txsToFinalize.length} txs from blocks up to ${blockNumber}`);
487
+ }
488
+
489
+ // === Query Methods ===
490
+
491
+ async getTxByHash(txHash: TxHash): Promise<Tx | undefined> {
492
+ const buffer = await this.#txsDB.getAsync(txHash.toString());
493
+ return buffer ? Tx.fromBuffer(buffer) : undefined;
494
+ }
495
+
496
+ async getTxsByHash(txHashes: TxHash[]): Promise<(Tx | undefined)[]> {
497
+ const results: (Tx | undefined)[] = [];
498
+ for (const h of txHashes) {
499
+ const buffer = await this.#txsDB.getAsync(h.toString());
500
+ results.push(buffer ? Tx.fromBuffer(buffer) : undefined);
501
+ }
502
+ return results;
503
+ }
504
+
505
+ hasTxs(txHashes: TxHash[]): boolean[] {
506
+ return txHashes.map(h => this.#indices.has(h.toString()));
507
+ }
508
+
509
+ getTxStatus(txHash: TxHash): TxState | undefined {
510
+ const meta = this.#indices.getMetadata(txHash.toString());
511
+ if (!meta) {
512
+ return undefined;
513
+ }
514
+ return this.#indices.getTxState(meta);
515
+ }
516
+
517
+ getPendingTxHashes(): TxHash[] {
518
+ return [...this.#indices.iteratePendingByPriority('desc')].map(hash => TxHash.fromString(hash));
519
+ }
520
+
521
+ getPendingTxCount(): number {
522
+ return this.#indices.getPendingTxCount();
523
+ }
524
+
525
+ getMinedTxHashes(): [TxHash, L2BlockId][] {
526
+ return this.#indices.getMinedTxs().map(([hash, blockId]) => [TxHash.fromString(hash), blockId]);
527
+ }
528
+
529
+ getMinedTxCount(): number {
530
+ let count = 0;
531
+ for (const [, meta] of this.#indices.iterateMetadata()) {
532
+ if (meta.minedL2BlockId !== undefined) {
533
+ count++;
534
+ }
535
+ }
536
+ return count;
537
+ }
538
+
539
+ isEmpty(): boolean {
540
+ return this.#indices.isEmpty();
541
+ }
542
+
543
+ getTxCount(): number {
544
+ return this.#indices.getTxCount();
545
+ }
546
+
547
+ getArchivedTxByHash(txHash: TxHash): Promise<Tx | undefined> {
548
+ return this.#archive.getTxByHash(txHash);
549
+ }
550
+
551
+ getLowestPriorityPending(limit: number): TxHash[] {
552
+ return this.#indices.getLowestPriorityPending(limit).map(h => TxHash.fromString(h));
553
+ }
554
+
555
+ // === Configuration ===
556
+
557
+ updateConfig(config: Partial<TxPoolV2Config>): void {
558
+ if (config.maxPendingTxCount !== undefined) {
559
+ this.#config.maxPendingTxCount = config.maxPendingTxCount;
560
+ }
561
+ if (config.archivedTxLimit !== undefined) {
562
+ this.#config.archivedTxLimit = config.archivedTxLimit;
563
+ this.#archive.updateLimit(config.archivedTxLimit);
564
+ }
565
+ // Update eviction rules with new config
566
+ this.#evictionManager.updateConfig(config);
567
+ }
568
+
569
+ // === Pool Read Access ===
570
+
571
+ getPoolReadAccess(): PoolReadAccess {
572
+ return {
573
+ getMetadata: (txHash: string) => this.#indices.getMetadata(txHash),
574
+ getTxHashByNullifier: (nullifier: string) => this.#indices.getTxHashByNullifier(nullifier),
575
+ getTxHashesByFeePayer: (feePayer: string) => this.#indices.getTxHashesByFeePayer(feePayer),
576
+ getPendingTxCount: () => this.#indices.getPendingTxCount(),
577
+ };
578
+ }
579
+
580
+ // === Metrics ===
581
+
582
+ countTxs(): { pending: number; protected: number; mined: number } {
583
+ return this.#indices.countTxs();
584
+ }
585
+
586
+ // ============================================================================
587
+ // PRIVATE HELPERS - Transaction Management
588
+ // ============================================================================
589
+
590
+ /**
591
+ * Adds a new transaction to the pool with the specified state.
592
+ * Emits onTxsAdded callback immediately after DB write.
593
+ */
594
+ async #addTx(
595
+ tx: Tx,
596
+ state: 'pending' | { protected: SlotNumber } | { mined: L2BlockId },
597
+ opts: { source?: string } = {},
598
+ ): Promise<TxMetaData> {
599
+ const txHashStr = tx.getTxHash().toString();
600
+ const meta = await buildTxMetaData(tx);
601
+
602
+ await this.#txsDB.set(txHashStr, tx.toBuffer());
603
+ this.#callbacks.onTxsAdded([tx], opts);
604
+
605
+ if (state === 'pending') {
606
+ this.#indices.addPending(meta);
607
+ } else if ('protected' in state) {
608
+ this.#indices.addProtected(meta, state.protected);
609
+ } else {
610
+ meta.minedL2BlockId = state.mined;
611
+ this.#indices.addMined(meta);
612
+ }
613
+
614
+ const stateStr = typeof state === 'string' ? state : Object.keys(state)[0];
615
+ this.#log.verbose(`Added ${stateStr} tx ${txHashStr}`, {
616
+ eventName: 'tx-added-to-pool',
617
+ state: stateStr,
618
+ });
619
+
620
+ return meta;
621
+ }
622
+
623
+ /**
624
+ * Deletes a transaction from both indices and DB.
625
+ * Emits onTxsRemoved callback immediately after DB delete.
626
+ */
627
+ async #deleteTx(txHashStr: string): Promise<void> {
628
+ this.#indices.remove(txHashStr);
629
+ await this.#txsDB.delete(txHashStr);
630
+ this.#callbacks.onTxsRemoved([txHashStr]);
631
+ }
632
+
633
+ /** Deletes a batch of transactions, emitting callbacks individually for each. */
634
+ async #deleteTxsBatch(txHashes: string[]): Promise<void> {
635
+ for (const txHashStr of txHashes) {
636
+ await this.#deleteTx(txHashStr);
637
+ }
638
+ }
639
+
640
+ // ============================================================================
641
+ // PRIVATE HELPERS - Validation & Conflict Resolution
642
+ // ============================================================================
643
+
644
+ /** Validates a single transaction, returning true if valid */
645
+ async #validateTx(tx: Tx, context?: string): Promise<boolean> {
646
+ const result = await this.#pendingTxValidator.validateTx(tx);
647
+ if (result.result !== 'valid') {
648
+ const contextStr = context ? ` ${context}` : '';
649
+ this.#log.info(`Tx ${tx.getTxHash()}${contextStr} failed validation: ${result.reason?.join(', ')}`);
650
+ return false;
651
+ }
652
+ return true;
653
+ }
654
+
655
+ /** Loads transactions from DB, returning loaded txs and missing hashes */
656
+ async #loadTxsFromDb(metas: TxMetaData[]): Promise<{ loaded: { tx: Tx; meta: TxMetaData }[]; missing: string[] }> {
657
+ const loaded: { tx: Tx; meta: TxMetaData }[] = [];
658
+ const missing: string[] = [];
659
+
660
+ for (const meta of metas) {
661
+ const buffer = await this.#txsDB.getAsync(meta.txHash);
662
+ if (!buffer) {
663
+ this.#log.warn(`Tx ${meta.txHash} not found in DB`);
664
+ missing.push(meta.txHash);
665
+ continue;
666
+ }
667
+ loaded.push({ tx: Tx.fromBuffer(buffer), meta });
668
+ }
669
+
670
+ return { loaded, missing };
671
+ }
672
+
673
+ /** Validates a batch of transactions, returning valid and invalid groups */
674
+ async #validateTxBatch(
675
+ txs: { tx: Tx; meta: TxMetaData }[],
676
+ context?: string,
677
+ ): Promise<{ valid: TxMetaData[]; invalid: string[] }> {
678
+ const valid: TxMetaData[] = [];
679
+ const invalid: string[] = [];
680
+
681
+ for (const { tx, meta } of txs) {
682
+ if (await this.#validateTx(tx, context)) {
683
+ valid.push(meta);
684
+ } else {
685
+ invalid.push(meta.txHash);
686
+ }
687
+ }
688
+
689
+ return { valid, invalid };
690
+ }
691
+
692
+ /** Loads transactions from DB and validates them */
693
+ async #loadAndValidateTxs(
694
+ metas: TxMetaData[],
695
+ context?: string,
696
+ ): Promise<{ valid: TxMetaData[]; invalid: string[] }> {
697
+ const { loaded, missing } = await this.#loadTxsFromDb(metas);
698
+ const { valid, invalid } = await this.#validateTxBatch(loaded, context);
699
+ return { valid, invalid: [...missing, ...invalid] };
700
+ }
701
+
702
+ /**
703
+ * Resolves nullifier conflicts between incoming txs and existing pending txs.
704
+ * Modifies the pending indices during iteration to maintain consistent state
705
+ * for subsequent conflict checks within the same batch.
706
+ */
707
+ #applyNullifierConflictResolution(txs: TxMetaData[]): { added: TxMetaData[]; toEvict: string[] } {
708
+ const added: TxMetaData[] = [];
709
+ const toEvict: string[] = [];
710
+
711
+ for (const meta of txs) {
712
+ const conflict = checkNullifierConflict(
713
+ meta,
714
+ nullifier => this.#indices.getTxHashByNullifier(nullifier),
715
+ txHash => this.#indices.getMetadata(txHash),
716
+ );
717
+ if (conflict.shouldIgnore) {
718
+ // Lower priority than existing - don't add, mark for deletion
719
+ toEvict.push(meta.txHash);
720
+ } else {
721
+ // Higher priority - evict existing conflicts
722
+ toEvict.push(...conflict.txHashesToEvict);
723
+ // Remove evicted from indices immediately for subsequent checks
724
+ for (const evictHash of conflict.txHashesToEvict) {
725
+ const evictMeta = this.#indices.getMetadata(evictHash);
726
+ if (evictMeta) {
727
+ this.#indices.removeFromPendingIndices(evictMeta);
728
+ }
729
+ }
730
+ // Add to pending indices immediately so subsequent txs in the batch see this tx
731
+ this.#indices.addToPendingIndices(meta);
732
+ added.push(meta);
733
+ }
734
+ }
735
+
736
+ return { added, toEvict };
737
+ }
738
+
739
+ // ============================================================================
740
+ // PRIVATE HELPERS - Block & Hydration
741
+ // ============================================================================
742
+
743
+ async #buildBlockId(block: BlockHeader): Promise<L2BlockId> {
744
+ return {
745
+ number: block.globalVariables.blockNumber,
746
+ hash: (await block.hash()).toString(),
747
+ };
748
+ }
749
+
750
+ /** Checks if a tx is already mined and returns its block ID if so */
751
+ async #getMinedBlockId(txHash: TxHash): Promise<L2BlockId | undefined> {
752
+ const txEffect = await this.#l2BlockSource.getTxEffect(txHash);
753
+ if (!txEffect) {
754
+ return undefined;
755
+ }
756
+ return {
757
+ number: txEffect.l2BlockNumber,
758
+ hash: txEffect.l2BlockHash.toString(),
759
+ };
760
+ }
761
+
762
+ /** Loads all transactions from the database, returning loaded txs and deserialization errors */
763
+ async #loadAllTxsFromDb(): Promise<{
764
+ loaded: { tx: Tx; meta: TxMetaData }[];
765
+ errors: string[];
766
+ }> {
767
+ const loaded: { tx: Tx; meta: TxMetaData }[] = [];
768
+ const errors: string[] = [];
769
+
770
+ for await (const [txHashStr, buffer] of this.#txsDB.entriesAsync()) {
771
+ try {
772
+ const tx = Tx.fromBuffer(buffer);
773
+ const meta = await buildTxMetaData(tx);
774
+ loaded.push({ tx, meta });
775
+ } catch (err) {
776
+ this.#log.warn(`Failed to deserialize tx ${txHashStr}, deleting`, { err });
777
+ errors.push(txHashStr);
778
+ }
779
+ }
780
+
781
+ return { loaded, errors };
782
+ }
783
+
784
+ /** Queries block source and marks mined status on transaction metadata */
785
+ async #markMinedStatusBatch(metas: TxMetaData[]): Promise<void> {
786
+ for (const meta of metas) {
787
+ try {
788
+ const txEffect = await this.#l2BlockSource.getTxEffect(TxHash.fromString(meta.txHash));
789
+ if (txEffect) {
790
+ meta.minedL2BlockId = {
791
+ number: txEffect.l2BlockNumber,
792
+ hash: txEffect.l2BlockHash.toString(),
793
+ };
794
+ }
795
+ } catch (err) {
796
+ this.#log.warn(`Failed to check mined status for tx ${meta.txHash}`, { err });
797
+ }
798
+ }
799
+ }
800
+
801
+ /**
802
+ * Rebuilds the pending pool by processing each tx through pre-add rules.
803
+ * Starts with an empty pending pool and adds txs one by one, resolving conflicts.
804
+ * Returns the list of accepted and rejected tx hashes.
805
+ */
806
+ async #rebuildPendingPool(metas: TxMetaData[]): Promise<{ accepted: string[]; rejected: string[] }> {
807
+ const accepted = new Set<string>();
808
+ const rejected: string[] = [];
809
+ const poolAccess = this.#createPreAddPoolAccess();
810
+
811
+ for (const meta of metas) {
812
+ // Run pre-add rules against current pending pool state (metadata not yet in pool)
813
+ const preAddResult = await this.#evictionManager.runPreAddRules(meta, poolAccess);
814
+
815
+ if (preAddResult.shouldIgnore) {
816
+ // Transaction rejected - mark for deletion from DB
817
+ rejected.push(meta.txHash);
818
+ this.#log.debug(`Rejected tx ${meta.txHash} during rebuild: ${preAddResult.reason}`);
819
+ continue;
820
+ }
821
+
822
+ // Evict any conflicting txs identified by pre-add rules
823
+ for (const evictHashStr of preAddResult.txHashesToEvict) {
824
+ const evictMeta = this.#indices.getMetadata(evictHashStr);
825
+ if (evictMeta) {
826
+ this.#indices.removeFromPendingIndices(evictMeta);
827
+ this.#indices.remove(evictHashStr);
828
+ rejected.push(evictHashStr);
829
+ accepted.delete(evictHashStr);
830
+ this.#log.debug(`Evicted tx ${evictHashStr} during rebuild due to conflict with ${meta.txHash}`);
831
+ }
832
+ }
833
+
834
+ // Add to indices
835
+ this.#indices.addPending(meta);
836
+ accepted.add(meta.txHash);
837
+ }
838
+
839
+ this.#log.info(`Rebuilt pending pool: ${accepted.size} accepted, ${rejected.length} rejected`);
840
+ return { accepted: [...accepted], rejected };
841
+ }
842
+
843
+ // ============================================================================
844
+ // PRIVATE HELPERS - Pool Access Adapters
845
+ // ============================================================================
846
+
847
+ #createPoolOperations(): PoolOperations {
848
+ return {
849
+ getPendingTxs: () => this.#indices.getPendingTxs(),
850
+ getPendingFeePayers: () => this.#indices.getPendingFeePayers(),
851
+ getFeePayerPendingTxs: (feePayer: string) => this.#indices.getFeePayerPendingTxs(feePayer),
852
+ getPendingTxCount: () => this.#indices.getPendingTxCount(),
853
+ getLowestPriorityPending: (limit: number) => this.#indices.getLowestPriorityPending(limit),
854
+ deleteTxs: (txHashes: string[]) => this.#deleteTxsBatch(txHashes),
855
+ };
856
+ }
857
+
858
+ #createPreAddPoolAccess(): PreAddPoolAccess {
859
+ return {
860
+ getMetadata: (txHashStr: string) => {
861
+ const meta = this.#indices.getMetadata(txHashStr);
862
+ if (!meta || this.#indices.getTxState(meta) !== 'pending') {
863
+ return undefined;
864
+ }
865
+ return meta;
866
+ },
867
+ getTxHashByNullifier: (nullifier: string) => this.#indices.getTxHashByNullifier(nullifier),
868
+ getFeePayerBalance: async (feePayer: string) => {
869
+ const db = this.#worldStateSynchronizer.getCommitted();
870
+ const publicStateSource = new DatabasePublicStateSource(db);
871
+ const balance = await publicStateSource.storageRead(
872
+ ProtocolContractAddress.FeeJuice,
873
+ await computeFeePayerBalanceStorageSlot(AztecAddress.fromString(feePayer)),
874
+ );
875
+ return balance.toBigInt();
876
+ },
877
+ getFeePayerPendingTxs: (feePayer: string) => this.#indices.getFeePayerPendingTxs(feePayer),
878
+ getPendingTxCount: () => this.#indices.getPendingTxCount(),
879
+ getLowestPriorityPendingTx: () => this.#indices.getLowestPriorityPendingTx(),
880
+ };
881
+ }
882
+ }