@aztec/archiver 0.0.1-commit.b655e406 → 0.0.1-commit.b6e433891

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 (214) hide show
  1. package/README.md +156 -22
  2. package/dest/archiver.d.ts +138 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +732 -0
  5. package/dest/config.d.ts +30 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/{archiver/config.js → config.js} +28 -6
  8. package/dest/errors.d.ts +53 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/errors.js +75 -0
  11. package/dest/factory.d.ts +8 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +93 -10
  14. package/dest/index.d.ts +11 -4
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +9 -3
  17. package/dest/interfaces.d.ts +9 -0
  18. package/dest/interfaces.d.ts.map +1 -0
  19. package/dest/interfaces.js +3 -0
  20. package/dest/l1/bin/retrieve-calldata.d.ts +3 -0
  21. package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
  22. package/dest/l1/bin/retrieve-calldata.js +152 -0
  23. package/dest/l1/calldata_retriever.d.ts +135 -0
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/l1/calldata_retriever.js +402 -0
  26. package/dest/l1/data_retrieval.d.ts +88 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/l1/data_retrieval.js +314 -0
  29. package/dest/l1/debug_tx.d.ts +19 -0
  30. package/dest/l1/debug_tx.d.ts.map +1 -0
  31. package/dest/l1/debug_tx.js +73 -0
  32. package/dest/l1/spire_proposer.d.ts +70 -0
  33. package/dest/l1/spire_proposer.d.ts.map +1 -0
  34. package/dest/l1/spire_proposer.js +149 -0
  35. package/dest/l1/trace_tx.d.ts +97 -0
  36. package/dest/l1/trace_tx.d.ts.map +1 -0
  37. package/dest/l1/trace_tx.js +91 -0
  38. package/dest/l1/types.d.ts +12 -0
  39. package/dest/l1/types.d.ts.map +1 -0
  40. package/dest/l1/types.js +3 -0
  41. package/dest/l1/validate_trace.d.ts +32 -0
  42. package/dest/l1/validate_trace.d.ts.map +1 -0
  43. package/dest/l1/validate_trace.js +154 -0
  44. package/dest/modules/data_source_base.d.ts +89 -0
  45. package/dest/modules/data_source_base.d.ts.map +1 -0
  46. package/dest/modules/data_source_base.js +216 -0
  47. package/dest/modules/data_store_updater.d.ts +88 -0
  48. package/dest/modules/data_store_updater.d.ts.map +1 -0
  49. package/dest/modules/data_store_updater.js +342 -0
  50. package/dest/modules/instrumentation.d.ts +50 -0
  51. package/dest/modules/instrumentation.d.ts.map +1 -0
  52. package/dest/{archiver → modules}/instrumentation.js +49 -62
  53. package/dest/modules/l1_synchronizer.d.ts +72 -0
  54. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  55. package/dest/modules/l1_synchronizer.js +1147 -0
  56. package/dest/modules/validation.d.ts +17 -0
  57. package/dest/modules/validation.d.ts.map +1 -0
  58. package/dest/{archiver → modules}/validation.js +35 -21
  59. package/dest/store/block_store.d.ts +195 -0
  60. package/dest/store/block_store.d.ts.map +1 -0
  61. package/dest/store/block_store.js +773 -0
  62. package/dest/store/contract_class_store.d.ts +18 -0
  63. package/dest/store/contract_class_store.d.ts.map +1 -0
  64. package/dest/{archiver/kv_archiver_store → store}/contract_class_store.js +13 -9
  65. package/dest/store/contract_instance_store.d.ts +24 -0
  66. package/dest/store/contract_instance_store.d.ts.map +1 -0
  67. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +1 -1
  68. package/dest/store/kv_archiver_store.d.ts +367 -0
  69. package/dest/store/kv_archiver_store.d.ts.map +1 -0
  70. package/dest/store/kv_archiver_store.js +481 -0
  71. package/dest/store/l2_tips_cache.d.ts +19 -0
  72. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  73. package/dest/store/l2_tips_cache.js +89 -0
  74. package/dest/store/log_store.d.ts +57 -0
  75. package/dest/store/log_store.d.ts.map +1 -0
  76. package/dest/store/log_store.js +533 -0
  77. package/dest/store/message_store.d.ts +44 -0
  78. package/dest/store/message_store.d.ts.map +1 -0
  79. package/dest/{archiver/kv_archiver_store → store}/message_store.js +29 -15
  80. package/dest/structs/data_retrieval.d.ts +27 -0
  81. package/dest/structs/data_retrieval.d.ts.map +1 -0
  82. package/dest/structs/inbox_message.d.ts +15 -0
  83. package/dest/structs/inbox_message.d.ts.map +1 -0
  84. package/dest/{archiver/structs → structs}/inbox_message.js +6 -5
  85. package/dest/structs/published.d.ts +2 -0
  86. package/dest/structs/published.d.ts.map +1 -0
  87. package/dest/test/fake_l1_state.d.ts +202 -0
  88. package/dest/test/fake_l1_state.d.ts.map +1 -0
  89. package/dest/test/fake_l1_state.js +455 -0
  90. package/dest/test/index.d.ts +2 -1
  91. package/dest/test/index.d.ts.map +1 -1
  92. package/dest/test/index.js +4 -1
  93. package/dest/test/mock_archiver.d.ts +16 -8
  94. package/dest/test/mock_archiver.d.ts.map +1 -1
  95. package/dest/test/mock_archiver.js +19 -14
  96. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  97. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  98. package/dest/test/mock_l1_to_l2_message_source.js +21 -11
  99. package/dest/test/mock_l2_block_source.d.ts +55 -20
  100. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  101. package/dest/test/mock_l2_block_source.js +251 -85
  102. package/dest/test/mock_structs.d.ts +83 -4
  103. package/dest/test/mock_structs.d.ts.map +1 -1
  104. package/dest/test/mock_structs.js +157 -11
  105. package/dest/test/noop_l1_archiver.d.ts +26 -0
  106. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  107. package/dest/test/noop_l1_archiver.js +72 -0
  108. package/package.json +20 -20
  109. package/src/archiver.ts +486 -0
  110. package/src/{archiver/config.ts → config.ts} +41 -13
  111. package/src/errors.ts +118 -0
  112. package/src/factory.ts +144 -12
  113. package/src/index.ts +11 -3
  114. package/src/interfaces.ts +9 -0
  115. package/src/l1/README.md +55 -0
  116. package/src/l1/bin/retrieve-calldata.ts +194 -0
  117. package/src/l1/calldata_retriever.ts +511 -0
  118. package/src/l1/data_retrieval.ts +493 -0
  119. package/src/l1/debug_tx.ts +99 -0
  120. package/src/l1/spire_proposer.ts +152 -0
  121. package/src/l1/trace_tx.ts +128 -0
  122. package/src/l1/types.ts +13 -0
  123. package/src/l1/validate_trace.ts +229 -0
  124. package/src/modules/data_source_base.ts +333 -0
  125. package/src/modules/data_store_updater.ts +464 -0
  126. package/src/{archiver → modules}/instrumentation.ts +61 -64
  127. package/src/modules/l1_synchronizer.ts +967 -0
  128. package/src/modules/validation.ts +129 -0
  129. package/src/store/block_store.ts +1018 -0
  130. package/src/{archiver/kv_archiver_store → store}/contract_class_store.ts +13 -9
  131. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +2 -2
  132. package/src/store/kv_archiver_store.ts +697 -0
  133. package/src/store/l2_tips_cache.ts +89 -0
  134. package/src/store/log_store.ts +736 -0
  135. package/src/{archiver/kv_archiver_store → store}/message_store.ts +41 -19
  136. package/src/{archiver/structs → structs}/inbox_message.ts +8 -8
  137. package/src/structs/published.ts +1 -0
  138. package/src/test/fake_l1_state.ts +698 -0
  139. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  140. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  141. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  142. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  143. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  144. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  145. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  146. package/src/test/index.ts +4 -0
  147. package/src/test/mock_archiver.ts +23 -16
  148. package/src/test/mock_l1_to_l2_message_source.ts +18 -11
  149. package/src/test/mock_l2_block_source.ts +312 -93
  150. package/src/test/mock_structs.ts +289 -13
  151. package/src/test/noop_l1_archiver.ts +115 -0
  152. package/dest/archiver/archiver.d.ts +0 -277
  153. package/dest/archiver/archiver.d.ts.map +0 -1
  154. package/dest/archiver/archiver.js +0 -1322
  155. package/dest/archiver/archiver_store.d.ts +0 -255
  156. package/dest/archiver/archiver_store.d.ts.map +0 -1
  157. package/dest/archiver/archiver_store.js +0 -4
  158. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  159. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  160. package/dest/archiver/archiver_store_test_suite.js +0 -1288
  161. package/dest/archiver/config.d.ts +0 -21
  162. package/dest/archiver/config.d.ts.map +0 -1
  163. package/dest/archiver/data_retrieval.d.ts +0 -79
  164. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  165. package/dest/archiver/data_retrieval.js +0 -362
  166. package/dest/archiver/errors.d.ts +0 -12
  167. package/dest/archiver/errors.d.ts.map +0 -1
  168. package/dest/archiver/errors.js +0 -17
  169. package/dest/archiver/index.d.ts +0 -7
  170. package/dest/archiver/index.d.ts.map +0 -1
  171. package/dest/archiver/index.js +0 -4
  172. package/dest/archiver/instrumentation.d.ts +0 -35
  173. package/dest/archiver/instrumentation.d.ts.map +0 -1
  174. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -124
  175. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  176. package/dest/archiver/kv_archiver_store/block_store.js +0 -370
  177. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  178. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  179. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  180. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  181. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -168
  182. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  183. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -296
  184. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -49
  185. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  186. package/dest/archiver/kv_archiver_store/log_store.js +0 -336
  187. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -39
  188. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  189. package/dest/archiver/structs/data_retrieval.d.ts +0 -27
  190. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  191. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  192. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  193. package/dest/archiver/structs/published.d.ts +0 -2
  194. package/dest/archiver/structs/published.d.ts.map +0 -1
  195. package/dest/archiver/validation.d.ts +0 -11
  196. package/dest/archiver/validation.d.ts.map +0 -1
  197. package/dest/rpc/index.d.ts +0 -9
  198. package/dest/rpc/index.d.ts.map +0 -1
  199. package/dest/rpc/index.js +0 -15
  200. package/src/archiver/archiver.ts +0 -1722
  201. package/src/archiver/archiver_store.ts +0 -305
  202. package/src/archiver/archiver_store_test_suite.ts +0 -1263
  203. package/src/archiver/data_retrieval.ts +0 -545
  204. package/src/archiver/errors.ts +0 -26
  205. package/src/archiver/index.ts +0 -6
  206. package/src/archiver/kv_archiver_store/block_store.ts +0 -481
  207. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -422
  208. package/src/archiver/kv_archiver_store/log_store.ts +0 -406
  209. package/src/archiver/structs/published.ts +0 -1
  210. package/src/archiver/validation.ts +0 -99
  211. package/src/rpc/index.ts +0 -16
  212. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  213. /package/dest/{archiver/structs → structs}/published.js +0 -0
  214. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
@@ -0,0 +1,698 @@
1
+ import type { BlobClientInterface } from '@aztec/blob-client/client';
2
+ import { type Blob, getBlobsPerL1Block, getPrefixedEthBlobCommitments } from '@aztec/blob-lib';
3
+ import { INITIAL_CHECKPOINT_NUMBER } from '@aztec/constants';
4
+ import type { CheckpointProposedLog, InboxContract, MessageSentLog, RollupContract } from '@aztec/ethereum/contracts';
5
+ import { MULTI_CALL_3_ADDRESS } from '@aztec/ethereum/contracts';
6
+ import type { ViemPublicClient } from '@aztec/ethereum/types';
7
+ import { type BlockNumber, CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
8
+ import { Buffer16, Buffer32 } from '@aztec/foundation/buffer';
9
+ import { Secp256k1Signer } from '@aztec/foundation/crypto/secp256k1-signer';
10
+ import { Fr } from '@aztec/foundation/curves/bn254';
11
+ import { EthAddress } from '@aztec/foundation/eth-address';
12
+ import { createLogger } from '@aztec/foundation/log';
13
+ import { RollupAbi } from '@aztec/l1-artifacts';
14
+ import { CommitteeAttestation, CommitteeAttestationsAndSigners, L2Block } from '@aztec/stdlib/block';
15
+ import { Checkpoint } from '@aztec/stdlib/checkpoint';
16
+ import { getSlotAtTimestamp } from '@aztec/stdlib/epoch-helpers';
17
+ import { InboxLeaf } from '@aztec/stdlib/messaging';
18
+ import { ConsensusPayload, SignatureDomainSeparator } from '@aztec/stdlib/p2p';
19
+ import {
20
+ makeAndSignCommitteeAttestationsAndSigners,
21
+ makeCheckpointAttestationFromCheckpoint,
22
+ mockCheckpointAndMessages,
23
+ } from '@aztec/stdlib/testing';
24
+ import { AppendOnlyTreeSnapshot } from '@aztec/stdlib/trees';
25
+
26
+ import { type MockProxy, mock } from 'jest-mock-extended';
27
+ import {
28
+ type AbiParameter,
29
+ type FormattedBlock,
30
+ type Transaction,
31
+ encodeAbiParameters,
32
+ encodeFunctionData,
33
+ keccak256,
34
+ multicall3Abi,
35
+ toHex,
36
+ } from 'viem';
37
+
38
+ import { updateRollingHash } from '../structs/inbox_message.js';
39
+
40
+ /** Configuration for the fake L1 state. */
41
+ export type FakeL1StateConfig = {
42
+ /** Genesis archive root. */
43
+ genesisArchiveRoot: Fr;
44
+ /** L1 start block number. */
45
+ l1StartBlock: bigint;
46
+ /** L1 genesis time in seconds. */
47
+ l1GenesisTime: bigint;
48
+ /** Ethereum slot duration in seconds. */
49
+ ethereumSlotDuration: number;
50
+ /** Rollup address for mock contracts. */
51
+ rollupAddress: EthAddress;
52
+ /** Inbox address for mock contracts. */
53
+ inboxAddress: EthAddress;
54
+ /** Aztec slot duration in seconds */
55
+ slotDuration: number;
56
+ };
57
+
58
+ /** Options for adding a checkpoint. */
59
+ type AddCheckpointOptions = {
60
+ /** L1 block number where checkpoint was proposed. */
61
+ l1BlockNumber: bigint;
62
+ /** Number of L2 blocks in the checkpoint. Default: 1 */
63
+ numBlocks?: number;
64
+ /** Or the actual blocks for the checkpoint */
65
+ blocks?: L2Block[];
66
+ /** Number of transactions per block. Default: 4 */
67
+ txsPerBlock?: number;
68
+ /** Max number of effects per tx (for generating large blobs). Default: undefined */
69
+ maxEffects?: number;
70
+ /** Signers for attestations. Default: none */
71
+ signers?: Secp256k1Signer[];
72
+ /** Override slot number. */
73
+ slotNumber?: SlotNumber;
74
+ /** Override previous archive. */
75
+ previousArchive?: AppendOnlyTreeSnapshot;
76
+ /** Timestamp for the checkpoint. */
77
+ timestamp?: bigint;
78
+ /** Number of L1-to-L2 messages. Default: 3 */
79
+ numL1ToL2Messages?: number;
80
+ /** L1 block number where messages were sent. Default: l1BlockNumber - 3 */
81
+ messagesL1BlockNumber?: bigint;
82
+ };
83
+
84
+ /** Result from adding a checkpoint. */
85
+ type AddCheckpointResult = {
86
+ /** The checkpoint that was created. */
87
+ checkpoint: Checkpoint;
88
+ /** The L1-to-L2 messages for this checkpoint. */
89
+ messages: Fr[];
90
+ };
91
+
92
+ /** Data stored for a checkpoint. */
93
+ type CheckpointData = {
94
+ checkpointNumber: CheckpointNumber;
95
+ checkpoint: Checkpoint;
96
+ l1BlockNumber: bigint;
97
+ tx: Transaction;
98
+ blobHashes: `0x${string}`[];
99
+ blobs: Blob[];
100
+ signers: Secp256k1Signer[];
101
+ /** Hash of the packed attestations, matching what the L1 event emits. */
102
+ attestationsHash: Buffer32;
103
+ /** Payload digest, matching what the L1 event emits. */
104
+ payloadDigest: Buffer32;
105
+ /** If true, archiveAt will ignore it */
106
+ pruned?: boolean;
107
+ };
108
+
109
+ /** Data stored for a message. */
110
+ type MessageData = {
111
+ l1BlockNumber: bigint;
112
+ checkpointNumber: CheckpointNumber;
113
+ index: bigint;
114
+ leaf: Fr;
115
+ rollingHash: Buffer16;
116
+ };
117
+
118
+ /**
119
+ * Stateful fake for L1 data used by the archiver.
120
+ *
121
+ * This class simulates the L1 blockchain state that the archiver reads from:
122
+ * - RollupContract: status(), archiveAt(), getVersion(), getTargetCommitteeSize(), CheckpointProposed events
123
+ * - InboxContract: getState(), MessageSent events
124
+ * - PublicClient: getBlockNumber(), getBlock(), getTransaction()
125
+ * - BlobClient: getBlobSidecar()
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * const fake = new FakeL1State(config);
130
+ *
131
+ * // Add checkpoint (creates messages automatically)
132
+ * const { checkpoint, messages } = await fake.addCheckpoint(CheckpointNumber(1), { l1BlockNumber: 101n });
133
+ * fake.setL1BlockNumber(105n);
134
+ *
135
+ * // Status auto-updated
136
+ * expect(fake.getRollupStatus().pendingCheckpointNumber).toEqual(CheckpointNumber(1));
137
+ * ```
138
+ */
139
+ export class FakeL1State {
140
+ private readonly log = createLogger('archiver:test:fake-l1');
141
+ private l1BlockNumber: bigint;
142
+ private checkpoints: CheckpointData[] = [];
143
+ private messages: MessageData[] = [];
144
+ private messagesRollingHash: Buffer16 = Buffer16.ZERO;
145
+ private lastArchive: AppendOnlyTreeSnapshot;
146
+ private provenCheckpointNumber: CheckpointNumber = CheckpointNumber(0);
147
+ private targetCommitteeSize: number = 0;
148
+ private version: bigint = 1n;
149
+ private canPruneResult: boolean = false;
150
+
151
+ // Computed from checkpoints based on L1 block visibility
152
+ private pendingCheckpointNumber: CheckpointNumber = CheckpointNumber(0);
153
+
154
+ // The L1 block number reported as "finalized" (defaults to the start block)
155
+ private finalizedL1BlockNumber: bigint;
156
+
157
+ constructor(private readonly config: FakeL1StateConfig) {
158
+ this.l1BlockNumber = config.l1StartBlock;
159
+ this.finalizedL1BlockNumber = config.l1StartBlock;
160
+ this.lastArchive = new AppendOnlyTreeSnapshot(config.genesisArchiveRoot, 1);
161
+ }
162
+
163
+ /**
164
+ * Adds messages for a checkpoint. Returns the message leaves.
165
+ * Auto-updates rolling hash.
166
+ *
167
+ * Note: For most use cases, use `addCheckpoint` which creates both checkpoint and messages.
168
+ * Use this method only when you need to add messages without creating a checkpoint (e.g., for reorg tests).
169
+ */
170
+ addMessages(checkpointNumber: CheckpointNumber, l1BlockNumber: bigint, messageLeaves: Fr[]): void {
171
+ messageLeaves.forEach((leaf, i) => {
172
+ const index = InboxLeaf.smallestIndexForCheckpoint(checkpointNumber) + BigInt(i);
173
+ this.messagesRollingHash = updateRollingHash(this.messagesRollingHash, leaf);
174
+
175
+ this.messages.push({
176
+ l1BlockNumber,
177
+ checkpointNumber,
178
+ index,
179
+ leaf,
180
+ rollingHash: this.messagesRollingHash,
181
+ });
182
+ });
183
+ }
184
+
185
+ /**
186
+ * Creates blocks for a checkpoint without adding them to L1 state.
187
+ * Useful for creating blocks to pass to addBlock() for testing provisional block handling.
188
+ * Returns the blocks directly.
189
+ */
190
+ public async makeBlocks(checkpointNumber: CheckpointNumber, options: Partial<AddCheckpointOptions>) {
191
+ return (await this.makeCheckpointAndMessages(checkpointNumber, options)).checkpoint.blocks;
192
+ }
193
+
194
+ /**
195
+ * Creates and adds a checkpoint with its L1-to-L2 messages.
196
+ * Returns both the checkpoint and the message leaves.
197
+ * Auto-chains from lastArchive, auto-updates pending status if L1 block >= checkpoint's L1 block.
198
+ */
199
+ public async addCheckpoint(
200
+ checkpointNumber: CheckpointNumber,
201
+ options: AddCheckpointOptions,
202
+ ): Promise<AddCheckpointResult> {
203
+ this.log.warn(`Adding checkpoint ${checkpointNumber}`);
204
+
205
+ const { l1BlockNumber, signers = [], messagesL1BlockNumber = l1BlockNumber - 3n } = options;
206
+
207
+ // Create the checkpoint using the stdlib helper
208
+ const { checkpoint, messages, lastArchive } = await this.makeCheckpointAndMessages(checkpointNumber, {
209
+ ...options,
210
+ numL1ToL2Messages: options.numL1ToL2Messages ?? 3,
211
+ });
212
+
213
+ // Store the messages internally so they match the checkpoint's inHash
214
+ this.addMessages(checkpointNumber, messagesL1BlockNumber, messages);
215
+
216
+ // Create the transaction, blobs, and event hashes
217
+ const { tx, attestationsHash, payloadDigest } = await this.makeRollupTx(checkpoint, signers);
218
+ const blobHashes = await this.makeVersionedBlobHashes(checkpoint);
219
+ const blobs = await this.makeBlobsFromCheckpoint(checkpoint);
220
+
221
+ // Store the checkpoint data
222
+ this.checkpoints.push({
223
+ checkpointNumber,
224
+ checkpoint,
225
+ l1BlockNumber,
226
+ tx,
227
+ blobHashes,
228
+ blobs,
229
+ signers,
230
+ attestationsHash,
231
+ payloadDigest,
232
+ });
233
+
234
+ // Update last archive for auto-chaining
235
+ this.lastArchive = lastArchive ?? checkpoint.blocks.at(-1)!.archive;
236
+
237
+ // Auto-update pending checkpoint number
238
+ this.updatePendingCheckpointNumber();
239
+
240
+ return { checkpoint, messages };
241
+ }
242
+
243
+ /** Creates a checkpoint and messages without adding them to L1 state. */
244
+ private makeCheckpointAndMessages(checkpointNumber: CheckpointNumber, options: Partial<AddCheckpointOptions>) {
245
+ const {
246
+ numBlocks = 1,
247
+ txsPerBlock = 4,
248
+ maxEffects,
249
+ slotNumber,
250
+ previousArchive = this.lastArchive,
251
+ timestamp,
252
+ l1BlockNumber,
253
+ numL1ToL2Messages = 0,
254
+ blocks,
255
+ } = options;
256
+
257
+ return mockCheckpointAndMessages(checkpointNumber, {
258
+ startBlockNumber: this.getNextBlockNumber(checkpointNumber),
259
+ numBlocks,
260
+ blocks,
261
+ numTxsPerBlock: txsPerBlock,
262
+ numL1ToL2Messages,
263
+ previousArchive,
264
+ slotNumber: slotNumber ?? (l1BlockNumber !== undefined ? this.getL2SlotAtL1Block(l1BlockNumber) : undefined),
265
+ timestamp: timestamp ?? (l1BlockNumber !== undefined ? this.getTimestampAtL1Block(l1BlockNumber) : undefined),
266
+ ...(maxEffects !== undefined ? { maxEffects } : {}),
267
+ });
268
+ }
269
+
270
+ /** Returns the L2 slot at the given L1 block (assuming all L1 blocks are mined) */
271
+ public getL2SlotAtL1Block(l1BlockNumber: bigint): SlotNumber {
272
+ const timestamp = this.getTimestampAtL1Block(l1BlockNumber);
273
+ return getSlotAtTimestamp(timestamp, this.config);
274
+ }
275
+
276
+ /** Returns the timestamp at the given L1 block (assuming all L1 blocks are mined) */
277
+ public getTimestampAtL1Block(l1BlockNumber: bigint): bigint {
278
+ const { l1GenesisTime, l1StartBlock, ethereumSlotDuration } = this.config;
279
+ return l1GenesisTime + (l1BlockNumber - l1StartBlock) * BigInt(ethereumSlotDuration);
280
+ }
281
+
282
+ /**
283
+ * Sets the current L1 block number.
284
+ * Auto-updates pending checkpoint number based on visible checkpoints.
285
+ */
286
+ setL1BlockNumber(blockNumber: bigint): void {
287
+ this.l1BlockNumber = blockNumber;
288
+ this.updatePendingCheckpointNumber();
289
+ }
290
+
291
+ /** Sets the L1 block number that will be reported as "finalized". */
292
+ setFinalizedL1BlockNumber(blockNumber: bigint): void {
293
+ this.finalizedL1BlockNumber = blockNumber;
294
+ }
295
+
296
+ /** Marks a checkpoint as proven. Updates provenCheckpointNumber. */
297
+ markCheckpointAsProven(checkpointNumber: CheckpointNumber): void {
298
+ this.provenCheckpointNumber = checkpointNumber;
299
+ }
300
+
301
+ /**
302
+ * Simulates what `rollup.getProvenCheckpointNumber({ blockNumber: atL1Block })` would return.
303
+ */
304
+ getProvenCheckpointNumberAtL1Block(atL1Block: bigint): CheckpointNumber {
305
+ if (this.provenCheckpointNumber === 0) {
306
+ return CheckpointNumber(0);
307
+ }
308
+ const checkpoint = this.checkpoints.find(cp => cp.checkpointNumber === this.provenCheckpointNumber);
309
+ if (checkpoint && checkpoint.l1BlockNumber <= atL1Block) {
310
+ return this.provenCheckpointNumber;
311
+ }
312
+ return CheckpointNumber(0);
313
+ }
314
+
315
+ /** Sets the target committee size for attestation validation. */
316
+ setTargetCommitteeSize(size: number): void {
317
+ this.targetCommitteeSize = size;
318
+ }
319
+
320
+ /** Sets whether the rollup contract would allow pruning at the next block. */
321
+ setCanPrune(value: boolean): void {
322
+ this.canPruneResult = value;
323
+ }
324
+
325
+ /**
326
+ * Removes all entries for a checkpoint number (simulates L1 reorg or prune).
327
+ * Note: Does NOT remove messages for this checkpoint (use numL1ToL2Messages: 0 when re-adding).
328
+ * Auto-updates pending status.
329
+ */
330
+ removeCheckpoint(checkpointNumber: CheckpointNumber): void {
331
+ this.checkpoints = this.checkpoints.filter(cpData => cpData.checkpointNumber !== checkpointNumber);
332
+ this.updatePendingCheckpointNumber();
333
+ }
334
+
335
+ /**
336
+ * Removes messages after a given total index (simulates L1 reorg).
337
+ * Auto-updates rolling hash.
338
+ */
339
+ removeMessagesAfter(totalIndex: number): void {
340
+ this.messages = this.messages.slice(0, totalIndex);
341
+ // Recalculate rolling hash
342
+ this.messagesRollingHash = this.messages.reduce((hash, msg) => updateRollingHash(hash, msg.leaf), Buffer16.ZERO);
343
+ }
344
+
345
+ /**
346
+ * Simulates a pruned checkpoint by marking all entries with this number as pruned.
347
+ * The event will still be returned, but archiveAt() will return the previous checkpoint's archive
348
+ * (or genesis if no previous checkpoint), causing a mismatch that the archiver will detect.
349
+ */
350
+ markCheckpointAsPruned(checkpointNumber: CheckpointNumber): void {
351
+ for (const cpData of this.checkpoints) {
352
+ if (cpData.checkpointNumber === checkpointNumber) {
353
+ cpData.pruned = true;
354
+ }
355
+ }
356
+ this.updatePendingCheckpointNumber();
357
+ }
358
+
359
+ /**
360
+ * Moves messages at a given L1 block to a new L1 block.
361
+ * Useful for simulating partial message visibility (messages at higher L1 blocks won't be fetched).
362
+ */
363
+ moveMessagesToL1Block(fromL1Block: bigint, toL1Block: bigint): void {
364
+ this.messages.forEach(msg => {
365
+ if (msg.l1BlockNumber === fromL1Block) {
366
+ msg.l1BlockNumber = toL1Block;
367
+ }
368
+ });
369
+ }
370
+
371
+ /**
372
+ * Moves a specific message (by index in the messages array) to a new L1 block.
373
+ */
374
+ moveMessageAtIndexToL1Block(index: number, toL1Block: bigint): void {
375
+ if (this.messages[index]) {
376
+ this.messages[index].l1BlockNumber = toL1Block;
377
+ }
378
+ }
379
+
380
+ /** Gets current rollup status. */
381
+ getRollupStatus(): {
382
+ provenCheckpointNumber: CheckpointNumber;
383
+ pendingCheckpointNumber: CheckpointNumber;
384
+ provenArchive: Fr;
385
+ pendingArchive: Fr;
386
+ } {
387
+ return {
388
+ provenCheckpointNumber: this.provenCheckpointNumber,
389
+ pendingCheckpointNumber: this.pendingCheckpointNumber,
390
+ provenArchive: this.getArchiveAt(this.provenCheckpointNumber),
391
+ pendingArchive: this.getArchiveAt(this.pendingCheckpointNumber),
392
+ };
393
+ }
394
+
395
+ /** Gets the last archive (for manual chaining if needed). */
396
+ getLastArchive(): AppendOnlyTreeSnapshot {
397
+ return this.lastArchive;
398
+ }
399
+
400
+ /** Gets the latest checkpoint entry by number (returns the last added one). */
401
+ getCheckpoint(checkpointNumber: CheckpointNumber): Checkpoint | undefined {
402
+ return this.checkpoints.findLast(cpData => cpData.checkpointNumber === checkpointNumber)?.checkpoint;
403
+ }
404
+
405
+ /** Gets messages for a checkpoint. */
406
+ getMessages(checkpointNumber: CheckpointNumber): Fr[] {
407
+ return this.messages.filter(m => m.checkpointNumber === checkpointNumber).map(m => m.leaf);
408
+ }
409
+
410
+ /** Gets the blobs for a checkpoint. */
411
+ getCheckpointBlobs(checkpointNumber: CheckpointNumber): Blob[] {
412
+ return this.checkpoints.findLast(cpData => cpData.checkpointNumber === checkpointNumber)?.blobs ?? [];
413
+ }
414
+
415
+ /** Creates mock RollupContract that reads from this fake state. */
416
+ createMockRollupContract(_publicClient: MockProxy<ViemPublicClient>): MockProxy<RollupContract> {
417
+ const mockRollup = mock<RollupContract>();
418
+
419
+ mockRollup.getVersion.mockImplementation(() => Promise.resolve(this.version));
420
+ mockRollup.getTargetCommitteeSize.mockImplementation(() => Promise.resolve(this.targetCommitteeSize));
421
+ mockRollup.archiveAt.mockImplementation((cpNum: CheckpointNumber) => Promise.resolve(this.getArchiveAt(cpNum)));
422
+ mockRollup.status.mockImplementation((localCheckpointNum: CheckpointNumber) => {
423
+ const status = this.getRollupStatus();
424
+ return Promise.resolve({
425
+ provenCheckpointNumber: status.provenCheckpointNumber,
426
+ provenArchive: status.provenArchive,
427
+ pendingCheckpointNumber: status.pendingCheckpointNumber,
428
+ pendingArchive: status.pendingArchive,
429
+ archiveOfMyCheckpoint: this.getArchiveAt(localCheckpointNum),
430
+ });
431
+ });
432
+
433
+ mockRollup.getProvenCheckpointNumber.mockImplementation((options?: { blockNumber?: bigint }) => {
434
+ const atBlock = options?.blockNumber ?? this.l1BlockNumber;
435
+ return Promise.resolve(this.getProvenCheckpointNumberAtL1Block(atBlock));
436
+ });
437
+
438
+ mockRollup.canPruneAtTime.mockImplementation(() => Promise.resolve(this.canPruneResult));
439
+
440
+ // Mock the wrapper method for fetching checkpoint events
441
+ mockRollup.getCheckpointProposedEvents.mockImplementation((fromBlock: bigint, toBlock: bigint) =>
442
+ Promise.resolve(this.getCheckpointProposedLogs(fromBlock, toBlock)),
443
+ );
444
+
445
+ Object.defineProperty(mockRollup, 'address', { get: () => this.config.rollupAddress.toString() });
446
+
447
+ return mockRollup;
448
+ }
449
+
450
+ /** Creates mock InboxContract that reads from this fake state. */
451
+ createMockInboxContract(_publicClient: MockProxy<ViemPublicClient>): MockProxy<InboxContract> {
452
+ const mockInbox = mock<InboxContract>();
453
+
454
+ mockInbox.getState.mockImplementation(() => {
455
+ // treeInProgress must be > any sealed checkpoint. On L1, a checkpoint can only be proposed
456
+ // after its messages are sealed, so treeInProgress > checkpointNumber for all published checkpoints.
457
+ const maxFromMessages =
458
+ this.messages.length > 0 ? Math.max(...this.messages.map(m => Number(m.checkpointNumber))) + 1 : 0;
459
+ const maxFromCheckpoints =
460
+ this.checkpoints.length > 0
461
+ ? Math.max(...this.checkpoints.filter(cp => !cp.pruned).map(cp => Number(cp.checkpointNumber))) + 1
462
+ : 0;
463
+ const treeInProgress = Math.max(maxFromMessages, maxFromCheckpoints, INITIAL_CHECKPOINT_NUMBER);
464
+ return Promise.resolve({
465
+ messagesRollingHash: this.messagesRollingHash,
466
+ totalMessagesInserted: BigInt(this.messages.length),
467
+ treeInProgress: BigInt(treeInProgress),
468
+ });
469
+ });
470
+
471
+ // Mock the wrapper methods for fetching message events
472
+ mockInbox.getMessageSentEvents.mockImplementation((fromBlock: bigint, toBlock: bigint) =>
473
+ Promise.resolve(this.getMessageSentLogs(fromBlock, toBlock)),
474
+ );
475
+
476
+ mockInbox.getMessageSentEventByHash.mockImplementation((hash: string, fromBlock: bigint, toBlock: bigint) =>
477
+ Promise.resolve(this.getMessageSentLogs(fromBlock, toBlock, hash)),
478
+ );
479
+
480
+ return mockInbox;
481
+ }
482
+
483
+ /** Creates mock PublicClient that reads from this fake state. */
484
+ createMockPublicClient(): MockProxy<ViemPublicClient> {
485
+ const publicClient = mock<ViemPublicClient>();
486
+
487
+ publicClient.getChainId.mockResolvedValue(1);
488
+ publicClient.getBlockNumber.mockImplementation(() => Promise.resolve(this.l1BlockNumber));
489
+
490
+ publicClient.getBlock.mockImplementation((async (args: { blockNumber?: bigint; blockTag?: string } = {}) => {
491
+ let blockNum: bigint;
492
+ if (args.blockTag === 'finalized') {
493
+ blockNum = this.finalizedL1BlockNumber;
494
+ } else {
495
+ blockNum = args.blockNumber ?? (await publicClient.getBlockNumber());
496
+ }
497
+ return {
498
+ number: blockNum,
499
+ timestamp: BigInt(blockNum) * BigInt(this.config.ethereumSlotDuration) + this.config.l1GenesisTime,
500
+ hash: Buffer32.fromBigInt(blockNum).toString(),
501
+ } as FormattedBlock;
502
+ }) as any);
503
+
504
+ // Use the same pattern as existing test for getTransaction
505
+ publicClient.getTransaction.mockImplementation((args: { hash?: `0x${string}` }) =>
506
+ Promise.resolve(
507
+ args.hash ? (this.checkpoints.find(cpData => cpData.tx.hash === args.hash)?.tx as any) : undefined,
508
+ ),
509
+ );
510
+
511
+ return publicClient;
512
+ }
513
+
514
+ /** Creates mock BlobClient that reads from this fake state. */
515
+ createMockBlobClient(): MockProxy<BlobClientInterface> {
516
+ const blobClient = mock<BlobClientInterface>();
517
+
518
+ // The blockId is the transaction's blockHash, which we set to the checkpoint's archive root
519
+ blobClient.getBlobSidecar.mockImplementation((blockId: `0x${string}`) =>
520
+ Promise.resolve(
521
+ this.checkpoints.find(cpData => cpData.checkpoint.archive.root.toString() === blockId)?.blobs ?? [],
522
+ ),
523
+ );
524
+
525
+ blobClient.testSources.mockResolvedValue(undefined);
526
+
527
+ return blobClient;
528
+ }
529
+
530
+ private updatePendingCheckpointNumber(): void {
531
+ this.pendingCheckpointNumber = this.checkpoints
532
+ .filter(cpData => cpData.l1BlockNumber <= this.l1BlockNumber && !cpData.pruned)
533
+ .reduce((max, cpData) => (cpData.checkpointNumber > max ? cpData.checkpointNumber : max), CheckpointNumber(0));
534
+ }
535
+
536
+ private getArchiveAt(checkpointNumber: CheckpointNumber): Fr {
537
+ if (checkpointNumber === 0) {
538
+ return this.config.genesisArchiveRoot;
539
+ }
540
+ // Find the latest non-pruned entry for this checkpoint number
541
+ const entries = this.checkpoints.filter(cpData => cpData.checkpointNumber === checkpointNumber);
542
+ const latestEntry = entries.at(-1);
543
+
544
+ if (!latestEntry || latestEntry.pruned) {
545
+ // For pruned or missing checkpoints, return the previous non-pruned checkpoint's archive
546
+ return this.getArchiveAt(CheckpointNumber(checkpointNumber - 1));
547
+ }
548
+ return latestEntry.checkpoint.archive.root;
549
+ }
550
+
551
+ private getNextBlockNumber(checkpointNumber: CheckpointNumber): BlockNumber {
552
+ const lastBlockNumber = this.checkpoints
553
+ .filter(cpData => cpData.checkpointNumber < checkpointNumber)
554
+ .flatMap(cpData => cpData.checkpoint.blocks.map(b => b.number))
555
+ .reduce((max, num) => Math.max(max, num), 0);
556
+ return (lastBlockNumber + 1) as BlockNumber;
557
+ }
558
+
559
+ private getCheckpointProposedLogs(fromBlock: bigint, toBlock: bigint): CheckpointProposedLog[] {
560
+ return this.checkpoints
561
+ .filter(cpData => cpData.l1BlockNumber >= fromBlock && cpData.l1BlockNumber <= toBlock)
562
+ .map(cpData => ({
563
+ l1BlockNumber: cpData.l1BlockNumber,
564
+ l1BlockHash: Buffer32.fromBigInt(cpData.l1BlockNumber),
565
+ l1TransactionHash: cpData.tx.hash as `0x${string}`,
566
+ args: {
567
+ checkpointNumber: cpData.checkpointNumber,
568
+ archive: cpData.checkpoint.archive.root,
569
+ versionedBlobHashes: cpData.blobHashes.map(h => Buffer.from(h.slice(2), 'hex')),
570
+ attestationsHash: cpData.attestationsHash,
571
+ payloadDigest: cpData.payloadDigest,
572
+ },
573
+ }));
574
+ }
575
+
576
+ private getMessageSentLogs(fromBlock?: bigint, toBlock?: bigint, hashFilter?: string): MessageSentLog[] {
577
+ return this.messages
578
+ .filter(
579
+ msg =>
580
+ (!hashFilter || msg.leaf.toString() === hashFilter) &&
581
+ (!fromBlock || msg.l1BlockNumber >= fromBlock) &&
582
+ (!toBlock || msg.l1BlockNumber <= toBlock),
583
+ )
584
+ .map(msg => ({
585
+ l1BlockNumber: msg.l1BlockNumber,
586
+ l1BlockHash: Buffer32.fromBigInt(msg.l1BlockNumber),
587
+ l1TransactionHash: `0x${msg.l1BlockNumber.toString(16)}` as `0x${string}`,
588
+ args: {
589
+ checkpointNumber: msg.checkpointNumber,
590
+ index: msg.index,
591
+ leaf: msg.leaf,
592
+ rollingHash: msg.rollingHash,
593
+ },
594
+ }));
595
+ }
596
+
597
+ private async makeRollupTx(
598
+ checkpoint: Checkpoint,
599
+ signers: Secp256k1Signer[],
600
+ ): Promise<{ tx: Transaction; attestationsHash: Buffer32; payloadDigest: Buffer32 }> {
601
+ const attestations = signers
602
+ .map(signer => makeCheckpointAttestationFromCheckpoint(checkpoint, signer))
603
+ .map(attestation => CommitteeAttestation.fromSignature(attestation.signature))
604
+ .map(committeeAttestation => committeeAttestation.toViem());
605
+
606
+ const header = checkpoint.header.toViem();
607
+ const blobInput = getPrefixedEthBlobCommitments(await getBlobsPerL1Block(checkpoint.toBlobFields()));
608
+ const archive = toHex(checkpoint.archive.root.toBuffer());
609
+ const attestationsAndSigners = new CommitteeAttestationsAndSigners(
610
+ attestations.map(attestation => CommitteeAttestation.fromViem(attestation)),
611
+ );
612
+
613
+ const attestationsAndSignersSignature = makeAndSignCommitteeAttestationsAndSigners(
614
+ attestationsAndSigners,
615
+ signers[0],
616
+ );
617
+
618
+ const packedAttestations = attestationsAndSigners.getPackedAttestations();
619
+
620
+ const rollupInput = encodeFunctionData({
621
+ abi: RollupAbi,
622
+ functionName: 'propose',
623
+ args: [
624
+ {
625
+ header,
626
+ archive,
627
+ oracleInput: { feeAssetPriceModifier: 0n },
628
+ },
629
+ packedAttestations,
630
+ attestationsAndSigners.getSigners().map(signer => signer.toString()),
631
+ attestationsAndSignersSignature.toViemSignature(),
632
+ blobInput,
633
+ ],
634
+ });
635
+
636
+ const multiCallInput = encodeFunctionData({
637
+ abi: multicall3Abi,
638
+ functionName: 'aggregate3',
639
+ args: [
640
+ [
641
+ {
642
+ target: this.config.rollupAddress.toString(),
643
+ callData: rollupInput,
644
+ allowFailure: false,
645
+ },
646
+ ],
647
+ ],
648
+ });
649
+
650
+ // Compute attestationsHash (same logic as CalldataRetriever)
651
+ const attestationsHash = Buffer32.fromString(
652
+ keccak256(encodeAbiParameters([this.getCommitteeAttestationsStructDef()], [packedAttestations])),
653
+ );
654
+
655
+ // Compute payloadDigest (same logic as CalldataRetriever)
656
+ const consensusPayload = ConsensusPayload.fromCheckpoint(checkpoint);
657
+ const payloadToSign = consensusPayload.getPayloadToSign(SignatureDomainSeparator.checkpointAttestation);
658
+ const payloadDigest = Buffer32.fromString(keccak256(payloadToSign));
659
+
660
+ const tx = {
661
+ input: multiCallInput,
662
+ hash: archive,
663
+ blockHash: archive,
664
+ to: MULTI_CALL_3_ADDRESS as `0x${string}`,
665
+ } as Transaction<bigint, number>;
666
+
667
+ return { tx, attestationsHash, payloadDigest };
668
+ }
669
+
670
+ /** Extracts the CommitteeAttestations struct definition from RollupAbi for hash computation. */
671
+ private getCommitteeAttestationsStructDef(): AbiParameter {
672
+ const proposeFunction = RollupAbi.find(item => item.type === 'function' && item.name === 'propose') as
673
+ | { type: 'function'; name: string; inputs: readonly AbiParameter[] }
674
+ | undefined;
675
+
676
+ if (!proposeFunction) {
677
+ throw new Error('propose function not found in RollupAbi');
678
+ }
679
+
680
+ const attestationsParam = proposeFunction.inputs.find(param => param.name === '_attestations');
681
+ if (!attestationsParam) {
682
+ throw new Error('_attestations parameter not found in propose function');
683
+ }
684
+
685
+ const tupleParam = attestationsParam as unknown as { type: 'tuple'; components?: readonly AbiParameter[] };
686
+ return { type: 'tuple', components: tupleParam.components || [] } as AbiParameter;
687
+ }
688
+
689
+ private async makeVersionedBlobHashes(checkpoint: Checkpoint): Promise<`0x${string}`[]> {
690
+ return (await getBlobsPerL1Block(checkpoint.toBlobFields())).map(
691
+ b => `0x${b.getEthVersionedBlobHash().toString('hex')}` as `0x${string}`,
692
+ );
693
+ }
694
+
695
+ private async makeBlobsFromCheckpoint(checkpoint: Checkpoint): Promise<Blob[]> {
696
+ return await getBlobsPerL1Block(checkpoint.toBlobFields());
697
+ }
698
+ }