miden-client 0.14.5

Client library that facilitates interaction with the Miden network
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
use alloc::boxed::Box;
use alloc::collections::{BTreeMap, BTreeSet};
use alloc::sync::Arc;
use alloc::vec::Vec;

use miden_protocol::Word;
use miden_protocol::account::delta::AccountUpdateDetails;
use miden_protocol::account::{AccountCode, AccountId, StorageSlot, StorageSlotContent};
use miden_protocol::address::NetworkId;
use miden_protocol::block::{BlockHeader, BlockNumber, ProvenBlock};
use miden_protocol::crypto::merkle::mmr::{Forest, Mmr, MmrProof};
use miden_protocol::crypto::merkle::smt::SmtProof;
use miden_protocol::note::{NoteHeader, NoteId, NoteScript, NoteTag, Nullifier};
use miden_protocol::transaction::{ProvenTransaction, TransactionInputs};
use miden_testing::{MockChain, MockChainNote};
use miden_tx::utils::sync::RwLock;

use crate::Client;
use crate::rpc::domain::account::{
    AccountDetails,
    AccountProof,
    AccountStorageDetails,
    AccountStorageMapDetails,
    AccountStorageRequirements,
    AccountUpdateSummary,
    AccountVaultDetails,
    FetchedAccount,
    StorageMapEntries,
    StorageMapEntry,
};
use crate::rpc::domain::account_vault::{AccountVaultInfo, AccountVaultUpdate};
use crate::rpc::domain::note::{
    CommittedNote,
    CommittedNoteMetadata,
    FetchedNote,
    NoteSyncBlock,
    NoteSyncInfo,
};
use crate::rpc::domain::nullifier::NullifierUpdate;
use crate::rpc::domain::storage_map::{StorageMapInfo, StorageMapUpdate};
use crate::rpc::domain::sync::ChainMmrInfo;
use crate::rpc::domain::transaction::{TransactionRecord, TransactionsInfo};
use crate::rpc::{AccountStateAt, NodeRpcClient, RpcError, RpcStatusInfo};

pub type MockClient<AUTH> = Client<AUTH>;

/// Mock RPC API
///
/// This struct implements the RPC API used by the client to communicate with the node. It simulates
/// most of the functionality of the actual node, with some small differences:
/// - It uses a [`MockChain`] to simulate the blockchain state.
/// - Blocks are not automatically created after time passes, but rather new blocks are created when
///   calling the `prove_block` method.
/// - Network account and transactions aren't supported in the current version.
/// - Account update block numbers aren't tracked, so any endpoint that returns when certain account
///   updates were made will return the chain tip block number instead.
#[derive(Clone)]
pub struct MockRpcApi {
    account_commitment_updates: Arc<RwLock<BTreeMap<BlockNumber, BTreeMap<AccountId, Word>>>>,
    pub mock_chain: Arc<RwLock<MockChain>>,
    oversize_threshold: usize,
}

impl Default for MockRpcApi {
    fn default() -> Self {
        Self::new(MockChain::new())
    }
}

impl MockRpcApi {
    // Constant to use in mocked pagination.
    const PAGINATION_BLOCK_LIMIT: u32 = 5;

    /// Creates a new [`MockRpcApi`] instance with the state of the provided [`MockChain`].
    pub fn new(mock_chain: MockChain) -> Self {
        Self {
            account_commitment_updates: Arc::new(RwLock::new(build_account_updates(&mock_chain))),
            mock_chain: Arc::new(RwLock::new(mock_chain)),
            oversize_threshold: 1000,
        }
    }

    /// Sets the oversize threshold for `get_account_proof`. Any storage map with more
    /// entries than this threshold, or a vault with more assets, will have the
    /// `too_many_entries` / `too_many_assets` flags set in the response.
    #[must_use]
    pub fn with_oversize_threshold(mut self, threshold: usize) -> Self {
        self.oversize_threshold = threshold;
        self
    }

    /// Returns the current MMR of the blockchain.
    pub fn get_mmr(&self) -> Mmr {
        self.mock_chain.read().blockchain().as_mmr().clone()
    }

    /// Returns the chain tip block number.
    pub fn get_chain_tip_block_num(&self) -> BlockNumber {
        self.mock_chain.read().latest_block_header().block_num()
    }

    /// Advances the mock chain by proving the next block, committing all pending objects to the
    /// chain in the process.
    pub fn prove_block(&self) {
        let proven_block = self.mock_chain.write().prove_next_block().unwrap();
        let mut account_commitment_updates = self.account_commitment_updates.write();
        let block_num = proven_block.header().block_num();
        let updates: BTreeMap<AccountId, Word> = proven_block
            .body()
            .updated_accounts()
            .iter()
            .map(|update| (update.account_id(), update.final_state_commitment()))
            .collect();

        if !updates.is_empty() {
            account_commitment_updates.insert(block_num, updates);
        }
    }

    /// Retrieves a block by its block number.
    fn get_block_by_num(&self, block_num: BlockNumber) -> BlockHeader {
        self.mock_chain.read().block_header(block_num.as_usize())
    }

    /// Retrieves account vault updates in a given block range.
    /// This method tries to simulate pagination by limiting the number of blocks processed per
    /// request.
    fn get_sync_account_vault_request(
        &self,
        block_from: BlockNumber,
        block_to: Option<BlockNumber>,
        account_id: AccountId,
    ) -> AccountVaultInfo {
        let chain_tip = self.get_chain_tip_block_num();
        let target_block = block_to.unwrap_or(chain_tip).min(chain_tip);

        let page_end_block: BlockNumber = (block_from.as_u32() + Self::PAGINATION_BLOCK_LIMIT)
            .min(target_block.as_u32())
            .into();

        let mut updates = vec![];
        for block in self.mock_chain.read().proven_blocks() {
            let block_number = block.header().block_num();
            // Only include blocks in range (block_from, page_end_block]
            if block_number <= block_from || block_number > page_end_block {
                continue;
            }

            for update in block
                .body()
                .updated_accounts()
                .iter()
                .filter(|block_acc_update| block_acc_update.account_id() == account_id)
            {
                let AccountUpdateDetails::Delta(account_delta) = update.details().clone() else {
                    continue;
                };

                let vault_delta = account_delta.vault();

                for asset in vault_delta.added_assets() {
                    let account_vault_update = AccountVaultUpdate {
                        block_num: block_number,
                        asset: Some(asset),
                        vault_key: asset.vault_key(),
                    };
                    updates.push(account_vault_update);
                }
            }
        }

        AccountVaultInfo {
            chain_tip,
            block_number: page_end_block,
            updates,
        }
    }

    /// Retrieves transactions in a given block range that match the provided account IDs
    fn get_sync_transactions_request(
        &self,
        block_from: BlockNumber,
        block_to: Option<BlockNumber>,
        account_ids: &[AccountId],
    ) -> TransactionsInfo {
        let chain_tip = self.get_chain_tip_block_num();
        let block_to = match block_to {
            Some(block_to) => block_to,
            None => chain_tip,
        };

        let mut transaction_records = vec![];
        for block in self.mock_chain.read().proven_blocks() {
            let block_number = block.header().block_num();
            if block_number <= block_from || block_number > block_to {
                continue;
            }

            for transaction_header in block.body().transactions().as_slice() {
                if !account_ids.contains(&transaction_header.account_id()) {
                    continue;
                }

                transaction_records.push(TransactionRecord {
                    block_num: block_number,
                    transaction_header: transaction_header.clone(),
                    output_notes: vec![],
                    erased_output_note_ids: vec![],
                });
            }
        }

        TransactionsInfo {
            chain_tip,
            block_num: block_to,
            transaction_records,
        }
    }

    /// Retrieves storage map updates in a given block range.
    ///
    /// This method tries to simulate pagination of the real node.
    fn get_sync_storage_maps_request(
        &self,
        block_from: BlockNumber,
        block_to: Option<BlockNumber>,
        account_id: AccountId,
    ) -> StorageMapInfo {
        let chain_tip = self.get_chain_tip_block_num();
        let target_block = block_to.unwrap_or(chain_tip).min(chain_tip);

        let page_end_block: BlockNumber = (block_from.as_u32() + Self::PAGINATION_BLOCK_LIMIT)
            .min(target_block.as_u32())
            .into();

        let mut updates = vec![];
        for block in self.mock_chain.read().proven_blocks() {
            let block_number = block.header().block_num();
            if block_number <= block_from || block_number > page_end_block {
                continue;
            }

            for update in block
                .body()
                .updated_accounts()
                .iter()
                .filter(|block_acc_update| block_acc_update.account_id() == account_id)
            {
                let AccountUpdateDetails::Delta(account_delta) = update.details().clone() else {
                    continue;
                };

                let storage_delta = account_delta.storage();

                for (slot_name, map_delta) in storage_delta.maps() {
                    for (key, value) in map_delta.entries() {
                        let storage_map_info = StorageMapUpdate {
                            block_num: block_number,
                            slot_name: slot_name.clone(),
                            key: *key,
                            value: *value,
                        };
                        updates.push(storage_map_info);
                    }
                }
            }
        }

        StorageMapInfo {
            chain_tip,
            block_number: page_end_block,
            updates,
        }
    }

    pub fn get_available_notes(&self) -> Vec<MockChainNote> {
        self.mock_chain.read().committed_notes().values().cloned().collect()
    }

    pub fn get_public_available_notes(&self) -> Vec<MockChainNote> {
        self.mock_chain
            .read()
            .committed_notes()
            .values()
            .filter(|n| matches!(n, MockChainNote::Public(_, _)))
            .cloned()
            .collect()
    }

    pub fn get_private_available_notes(&self) -> Vec<MockChainNote> {
        self.mock_chain
            .read()
            .committed_notes()
            .values()
            .filter(|n| matches!(n, MockChainNote::Private(_, _, _)))
            .cloned()
            .collect()
    }

    pub fn advance_blocks(&self, num_blocks: u32) {
        let current_height = self.get_chain_tip_block_num();
        let mut mock_chain = self.mock_chain.write();
        mock_chain.prove_until_block(current_height + num_blocks).unwrap();
    }
}
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
impl NodeRpcClient for MockRpcApi {
    fn has_genesis_commitment(&self) -> Option<Word> {
        None
    }

    async fn set_genesis_commitment(&self, _commitment: Word) -> Result<(), RpcError> {
        // The mock client doesn't use accept headers, so we don't need to do anything here.
        Ok(())
    }

    /// Returns note updates after the specified block number. Only notes that match the
    /// provided tags will be returned, grouped by block.
    async fn sync_notes(
        &self,
        block_num: BlockNumber,
        block_to: Option<BlockNumber>,
        note_tags: &BTreeSet<NoteTag>,
    ) -> Result<NoteSyncInfo, RpcError> {
        let chain_tip = self.get_chain_tip_block_num();
        let upper_bound = block_to.unwrap_or(chain_tip);

        // Collect all blocks with matching notes in the range (block_num, upper_bound]
        let mut blocks_with_notes: BTreeMap<BlockNumber, BTreeMap<NoteId, CommittedNote>> =
            BTreeMap::new();
        for note in self.mock_chain.read().committed_notes().values() {
            let note_block = note.inclusion_proof().location().block_num();
            if note_tags.contains(&note.metadata().tag())
                && note_block > block_num
                && note_block <= upper_bound
            {
                let committed = CommittedNote::new(
                    note.id(),
                    CommittedNoteMetadata::Full(note.metadata().clone()),
                    note.inclusion_proof().clone(),
                );
                blocks_with_notes.entry(note_block).or_default().insert(note.id(), committed);
            }
        }

        // Always include the upper_bound block (with empty notes if needed), matching the
        // node behavior where the range-end block is always present when the scan completes.
        blocks_with_notes.entry(upper_bound).or_default();

        let blocks: Vec<NoteSyncBlock> = blocks_with_notes
            .into_iter()
            .map(|(bn, notes)| {
                let block_header = self.get_block_by_num(bn);
                let mmr_path = self.get_mmr().open(bn.as_usize()).unwrap().merkle_path().clone();
                NoteSyncBlock { block_header, mmr_path, notes }
            })
            .collect();

        Ok(NoteSyncInfo { chain_tip, block_to: upper_bound, blocks })
    }

    async fn sync_chain_mmr(
        &self,
        block_from: BlockNumber,
        block_to: Option<BlockNumber>,
    ) -> Result<ChainMmrInfo, RpcError> {
        let chain_tip = self.get_chain_tip_block_num();
        let target_block = block_to.unwrap_or(chain_tip).min(chain_tip);

        let from_forest = if block_from == chain_tip {
            target_block.as_usize()
        } else {
            block_from.as_u32() as usize + 1
        };

        let mmr_delta = self
            .get_mmr()
            .get_delta(Forest::new(from_forest), Forest::new(target_block.as_usize()))
            .unwrap();

        let block_header = self.get_block_by_num(target_block);

        Ok(ChainMmrInfo {
            block_from,
            block_to: target_block,
            mmr_delta,
            block_header,
        })
    }

    /// Retrieves the block header for the specified block number. If the block number is not
    /// provided, the chain tip block header will be returned.
    async fn get_block_header_by_number(
        &self,
        block_num: Option<BlockNumber>,
        include_mmr_proof: bool,
    ) -> Result<(BlockHeader, Option<MmrProof>), RpcError> {
        let block = if let Some(block_num) = block_num {
            self.mock_chain.read().block_header(block_num.as_usize())
        } else {
            self.mock_chain.read().latest_block_header()
        };

        let mmr_proof = if include_mmr_proof {
            Some(self.get_mmr().open(block_num.unwrap().as_usize()).unwrap())
        } else {
            None
        };

        Ok((block, mmr_proof))
    }

    /// Returns the node's tracked notes that match the provided note IDs.
    async fn get_notes_by_id(&self, note_ids: &[NoteId]) -> Result<Vec<FetchedNote>, RpcError> {
        // assume all public notes for now
        let notes = self.mock_chain.read().committed_notes().clone();

        let hit_notes = note_ids.iter().filter_map(|id| notes.get(id));
        let mut return_notes = vec![];
        for note in hit_notes {
            let fetched_note = match note {
                MockChainNote::Private(note_id, note_metadata, note_inclusion_proof) => {
                    let note_header = NoteHeader::new(*note_id, note_metadata.clone());
                    FetchedNote::Private(note_header, note_inclusion_proof.clone())
                },
                MockChainNote::Public(note, note_inclusion_proof) => {
                    FetchedNote::Public(note.clone(), note_inclusion_proof.clone())
                },
            };
            return_notes.push(fetched_note);
        }
        Ok(return_notes)
    }

    /// Simulates the submission of a proven transaction to the node. This will create a new block
    /// just for the new transaction and return the block number of the newly created block.
    async fn submit_proven_transaction(
        &self,
        proven_transaction: ProvenTransaction,
        _tx_inputs: TransactionInputs, // Unnecessary for testing client itself.
    ) -> Result<BlockNumber, RpcError> {
        // TODO: add some basic validations to test error cases

        {
            let mut mock_chain = self.mock_chain.write();
            mock_chain.add_pending_proven_transaction(proven_transaction.clone());
        };

        let block_num = self.get_chain_tip_block_num();

        Ok(block_num)
    }

    /// Returns the node's tracked account details for the specified account ID.
    /// Always returns the full account for public accounts.
    async fn get_account_details(&self, account_id: AccountId) -> Result<FetchedAccount, RpcError> {
        let summary =
            self.account_commitment_updates
                .read()
                .iter()
                .rev()
                .find_map(|(block_num, updates)| {
                    updates.get(&account_id).map(|commitment| AccountUpdateSummary {
                        commitment: *commitment,
                        last_block_num: *block_num,
                    })
                });

        if let Ok(account) = self.mock_chain.read().committed_account(account_id) {
            let summary = summary.unwrap_or_else(|| AccountUpdateSummary {
                commitment: account.to_commitment(),
                last_block_num: BlockNumber::GENESIS,
            });
            Ok(FetchedAccount::new_public(account.clone(), summary))
        } else if let Some(summary) = summary {
            Ok(FetchedAccount::new_private(account_id, summary))
        } else {
            Err(RpcError::ExpectedDataMissing(format!(
                "account {account_id} not found in mock commitment updates or mock chain"
            )))
        }
    }

    /// Returns the account proof for the specified account. The `known_account_code` parameter
    /// is ignored in the mock implementation and the latest account code is always returned.
    async fn get_account_proof(
        &self,
        account_id: AccountId,
        account_storage_requirements: AccountStorageRequirements,
        account_state: AccountStateAt,
        _known_account_code: Option<AccountCode>,
        _known_vault_commitment: Option<Word>,
    ) -> Result<(BlockNumber, AccountProof), RpcError> {
        let mock_chain = self.mock_chain.read();

        let block_number = match account_state {
            AccountStateAt::Block(number) => number,
            AccountStateAt::ChainTip => mock_chain.latest_block_header().block_num(),
        };

        let headers = if account_id.has_public_state() {
            let account = mock_chain.committed_account(account_id).unwrap();

            let mut map_details = vec![];
            for slot_name in account_storage_requirements.inner().keys() {
                if let Some(StorageSlotContent::Map(storage_map)) =
                    account.storage().get(slot_name).map(StorageSlot::content)
                {
                    let entries: Vec<StorageMapEntry> = storage_map
                        .entries()
                        .map(|(key, value)| StorageMapEntry { key: *key, value: *value })
                        .collect();

                    // NOTE: The mock returns all entries even when too_many_entries is set.
                    // In production, the node would return partial data for oversized maps.
                    let too_many_entries = entries.len() > self.oversize_threshold;
                    let account_storage_map_detail = AccountStorageMapDetails {
                        slot_name: slot_name.clone(),
                        too_many_entries,
                        entries: StorageMapEntries::AllEntries(entries),
                    };

                    map_details.push(account_storage_map_detail);
                } else {
                    panic!("Storage slot {slot_name} is not a map");
                }
            }

            let storage_details = AccountStorageDetails {
                header: account.storage().to_header(),
                map_details,
            };

            let mut assets = vec![];
            for asset in account.vault().assets() {
                assets.push(asset);
            }
            let vault_details = AccountVaultDetails {
                too_many_assets: assets.len() > self.oversize_threshold,
                assets,
            };

            Some(AccountDetails {
                header: account.into(),
                storage_details,
                code: account.code().clone(),
                vault_details,
            })
        } else {
            None
        };

        let witness = mock_chain.account_tree().open(account_id);

        let proof = AccountProof::new(witness, headers).unwrap();

        Ok((block_number, proof))
    }

    /// Returns the nullifiers created after the specified block number that match the provided
    /// prefixes.
    async fn sync_nullifiers(
        &self,
        prefixes: &[u16],
        from_block_num: BlockNumber,
        block_to: Option<BlockNumber>,
    ) -> Result<Vec<NullifierUpdate>, RpcError> {
        let nullifiers = self
            .mock_chain
            .read()
            .nullifier_tree()
            .entries()
            .filter_map(|(nullifier, block_num)| {
                let within_range = if let Some(to_block) = block_to {
                    block_num >= from_block_num && block_num <= to_block
                } else {
                    block_num >= from_block_num
                };

                if prefixes.contains(&nullifier.prefix()) && within_range {
                    Some(NullifierUpdate { nullifier, block_num })
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();

        Ok(nullifiers)
    }

    /// Returns proofs for all the provided nullifiers.
    async fn check_nullifiers(&self, nullifiers: &[Nullifier]) -> Result<Vec<SmtProof>, RpcError> {
        Ok(nullifiers
            .iter()
            .map(|nullifier| self.mock_chain.read().nullifier_tree().open(nullifier).into_proof())
            .collect())
    }

    async fn get_block_by_number(&self, block_num: BlockNumber) -> Result<ProvenBlock, RpcError> {
        let block = self
            .mock_chain
            .read()
            .proven_blocks()
            .iter()
            .find(|b| b.header().block_num() == block_num)
            .unwrap()
            .clone();

        Ok(block)
    }

    async fn get_note_script_by_root(&self, root: Word) -> Result<NoteScript, RpcError> {
        let note = self
            .get_available_notes()
            .iter()
            .find(|note| note.note().is_some_and(|n| n.script().root() == root))
            .unwrap()
            .clone();

        Ok(note.note().unwrap().script().clone())
    }

    async fn sync_storage_maps(
        &self,
        block_from: BlockNumber,
        block_to: Option<BlockNumber>,
        account_id: AccountId,
    ) -> Result<StorageMapInfo, RpcError> {
        let mut all_updates = Vec::new();
        let mut current_block_from = block_from;
        let chain_tip = self.get_chain_tip_block_num();
        let target_block = block_to.unwrap_or(chain_tip).min(chain_tip);

        loop {
            let response =
                self.get_sync_storage_maps_request(current_block_from, block_to, account_id);
            all_updates.extend(response.updates);

            if response.block_number >= target_block {
                return Ok(StorageMapInfo {
                    chain_tip: response.chain_tip,
                    block_number: response.block_number,
                    updates: all_updates,
                });
            }

            current_block_from = (response.block_number.as_u32() + 1).into();
        }
    }

    async fn sync_account_vault(
        &self,
        block_from: BlockNumber,
        block_to: Option<BlockNumber>,
        account_id: AccountId,
    ) -> Result<AccountVaultInfo, RpcError> {
        let mut all_updates = Vec::new();
        let mut current_block_from = block_from;
        let chain_tip = self.get_chain_tip_block_num();
        let target_block = block_to.unwrap_or(chain_tip).min(chain_tip);

        loop {
            let response =
                self.get_sync_account_vault_request(current_block_from, block_to, account_id);
            all_updates.extend(response.updates);

            if response.block_number >= target_block {
                return Ok(AccountVaultInfo {
                    chain_tip: response.chain_tip,
                    block_number: response.block_number,
                    updates: all_updates,
                });
            }

            current_block_from = (response.block_number.as_u32() + 1).into();
        }
    }

    async fn sync_transactions(
        &self,
        block_from: BlockNumber,
        block_to: Option<BlockNumber>,
        account_ids: Vec<AccountId>,
    ) -> Result<TransactionsInfo, RpcError> {
        let response = self.get_sync_transactions_request(block_from, block_to, &account_ids);
        Ok(response)
    }

    async fn get_network_id(&self) -> Result<NetworkId, RpcError> {
        Ok(NetworkId::Testnet)
    }

    async fn get_rpc_limits(&self) -> Result<crate::rpc::RpcLimits, RpcError> {
        Ok(crate::rpc::RpcLimits::default())
    }

    fn has_rpc_limits(&self) -> Option<crate::rpc::RpcLimits> {
        None
    }

    async fn set_rpc_limits(&self, _limits: crate::rpc::RpcLimits) {
        // No-op for mock client
    }

    async fn get_status_unversioned(&self) -> Result<RpcStatusInfo, RpcError> {
        Ok(RpcStatusInfo {
            version: env!("CARGO_PKG_VERSION").into(),
            genesis_commitment: None,
            store: None,
            block_producer: None,
        })
    }
}

// CONVERSIONS
// ================================================================================================

impl From<MockChain> for MockRpcApi {
    fn from(mock_chain: MockChain) -> Self {
        MockRpcApi::new(mock_chain)
    }
}

// HELPERS
// ================================================================================================

fn build_account_updates(
    mock_chain: &MockChain,
) -> BTreeMap<BlockNumber, BTreeMap<AccountId, Word>> {
    let mut account_commitment_updates = BTreeMap::new();
    for block in mock_chain.proven_blocks() {
        let block_num = block.header().block_num();
        let mut updates = BTreeMap::new();

        for update in block.body().updated_accounts() {
            updates.insert(update.account_id(), update.final_state_commitment());
        }

        if updates.is_empty() {
            continue;
        }

        account_commitment_updates.insert(block_num, updates);
    }
    account_commitment_updates
}