litesvm_token/
sync_native.rs

1use {
2    super::{spl_token::instruction::sync_native, TOKEN_ID},
3    litesvm::{types::FailedTransactionMetadata, LiteSVM},
4    solana_keypair::Keypair,
5    solana_pubkey::Pubkey,
6    solana_signer::Signer,
7    solana_transaction::Transaction,
8};
9
10/// ### Description
11/// Builder for the [`sync_native`] instruction.
12///
13/// ### Optional fields
14/// - `token_program_id`: [`TOKEN_ID`] by default.
15pub struct SyncNative<'a> {
16    svm: &'a mut LiteSVM,
17    payer: &'a Keypair,
18    account: &'a Pubkey,
19    token_program_id: Option<&'a Pubkey>,
20}
21
22impl<'a> SyncNative<'a> {
23    /// Creates a new instance of [`sync_native`] instruction.
24    pub fn new(svm: &'a mut LiteSVM, payer: &'a Keypair, account: &'a Pubkey) -> Self {
25        SyncNative {
26            svm,
27            payer,
28            account,
29            token_program_id: None,
30        }
31    }
32
33    /// Sets the token program id for the instruction.
34    pub fn token_program_id(mut self, program_id: &'a Pubkey) -> Self {
35        self.token_program_id = Some(program_id);
36        self
37    }
38
39    /// Sends the transaction.
40    pub fn send(self) -> Result<(), FailedTransactionMetadata> {
41        let token_program_id = self.token_program_id.unwrap_or(&TOKEN_ID);
42
43        let ix = sync_native(token_program_id, self.account)?;
44
45        let block_hash = self.svm.latest_blockhash();
46        let tx = Transaction::new_signed_with_payer(
47            &[ix],
48            Some(&self.payer.pubkey()),
49            &[self.payer],
50            block_hash,
51        );
52        self.svm.send_transaction(tx)?;
53
54        Ok(())
55    }
56}