Created
March 29, 2021 19:08
-
-
Save jordaaash/5aa90454407aad508547c1a5d82a40ab to your computer and use it in GitHub Desktop.
How to use account data in a Solana program test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![cfg(feature = "test-bpf")] | |
// first, grab some account data, e.g. | |
// ```shell | |
// solana account -u m SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt --output-file account.bin | |
// ``` | |
mod helpers; | |
use helpers::*; | |
use solana_program::{ | |
account_info::AccountInfo, | |
pubkey::Pubkey, | |
program_error::ProgramError, | |
program_pack::{Pack, IsInitialized} | |
}; | |
use solana_program_test::*; | |
use solana_sdk::{ | |
account::Account, | |
account_info::IntoAccountInfo, | |
}; | |
use std::str::FromStr; | |
#[tokio::test] | |
async fn test_success() { | |
// construct Pubkey | |
let pubkey = Pubkey::from_str("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt").unwrap(); | |
// construct Account with the data | |
let mut account = Account { | |
lamports: u32::MAX as u64, | |
data: read_file(find_file("account.bin").unwrap()), | |
owner: Pubkey::new(&[0; 32]), | |
executable: false, | |
rent_epoch: 0, | |
}; | |
// construct AccountInfo from tuple (key, is_signer, account) | |
let account_info = (&pubkey, false, &mut account).into_account_info(); | |
// unpack AccountInfo into a known type (in this case, an SPL Token Mint) | |
let srm_mint = unpack::<spl_token::state::Mint>(&account_info).unwrap(); | |
// ... | |
} | |
fn unpack<T: Pack + IsInitialized>( | |
account_info: &AccountInfo, | |
) -> Result<T, ProgramError> { | |
T::unpack(&account_info.data.borrow()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment