A vault’s token account holds 40 tokens. A successful classic SPL Token transfer sends it 15 more. Within the same instruction, the token program’s state now says 55, while an Anchor handler can still read 40 from vault.amount. Both reads have a source. One decodes the account bytes after the call. The other reads the Rust value decoded when the handler started.
That distinction matters when a program credits a user with the amount actually received. Reading the same snapshot twice gives a delta of 0. Keeping the first reading, reloading the destination after the CPI and then subtracting gives 15. This example assumes a successful transfer without transfer fees. A fee-bearing mint changes the credited delta, while the rule for reading it stays the same. Anchor’s account wrapper
Trace the 15-token transfer#
In this handler excerpt, vault is a mutable Account<TokenAccount>. The source belongs to the signing user. Save the destination's starting amount before asking SPL Token to move the tokens.
let vault = &mut ctx.accounts.vault;
let before = vault.amount;
let transfer = anchor_spl::token::Transfer {
from: ctx.accounts.user_token_account.to_account_info(),
to: vault.to_account_info(),
authority: ctx.accounts.user_authority.to_account_info(),
};
let cpi = CpiContext::new(ctx.accounts.token_program.to_account_info(), transfer);
anchor_spl::token::transfer(cpi, 15)?;
let cached = vault.amount;
vault.reload()?;
let received = vault.amount.checked_sub(before);For this successful transfer, before and cached are 40. After the reload, vault.amount is 55 and received is Some(15). A production handler that admits decreases must handle the subtraction failure according to its own accounting rules.
What is native Solana doing?#
Below is a native-style example where the value you read does change after CPI.
// before CPI: read from runtime memory directly
let before = **from.lamports.borrow();
msg!("Before CPI: {}", before);
invoke(
&system_instruction::transfer(from.key, to.key, 1_000),
&[from.clone(), to.clone(), system_program.clone()],
)?;
// after CPI: borrow again, read the same runtime memory
let after = **from.lamports.borrow();
msg!("After CPI: {}", after);During execution, Solana programs do not operate on the ledger directly. Instead, accounts are loaded into the runtime as a working set, and instructions mutate that in-memory state.
In the snippet above, from is an AccountInfo, and from.lamports.borrow() reads the lamports from the runtime state. After CPI, borrowing again reads the updated runtime value.
Important nuance: this "auto-updates" property comes from re-borrowing the underlying bytes/lamports from AccountInfo. If you deserialize account data into your own struct and keep that struct around, that struct is still just a snapshot (more on this later).
How is Anchor handling this?#
Let's take a look at the Account struct in Anchor:
#[derive(Clone)]
pub struct Account<'info, T: AccountSerialize + AccountDeserialize + Clone> {
account: T,
info: &'info AccountInfo<'info>,
}Anchor's Account<'info, T> is a wrapper around:
info: theAccountInfohandle to the runtime accountaccount: a deserializedTvalue (a cached view)
AccountInfo contains the live, runtime-owned fields (lamports and raw data bytes):
/// Account information
#[derive(Clone)]
#[repr(C)]
pub struct AccountInfo<'a> {
/// Public key of the account
pub key: &'a Pubkey,
/// The lamports in the account. Modifiable by programs.
pub lamports: Rc<RefCell<&'a mut u64>>,
/// The data held in this account. Modifiable by programs.
pub data: Rc<RefCell<&'a mut [u8]>>,
/// Program that owns this account
pub owner: &'a Pubkey,
/// The epoch at which this account will next owe rent
pub rent_epoch: Epoch,
/// Was the transaction signed by this account's public key?
pub is_signer: bool,
/// Is the account writable?
pub is_writable: bool,
/// This account's data contains a loaded program (and is now read-only)
pub executable: bool,
}When interacting with info#
When you call something like get_lamports() (Anchor's Lamports helpers), you're reading through AccountInfo:
impl<'info, T: AccountSerialize + AccountDeserialize + Clone> AsRef<AccountInfo<'info>>
for Account<'info, T>
{
fn as_ref(&self) -> &AccountInfo<'info> {
self.info
}
}get_lamports uses as_ref to obtain the underlying AccountInfo, and then borrows lamports from it.
/// Lamports related utility methods for accounts.
pub trait Lamports<'info>: AsRef<AccountInfo<'info>> {
/// Get the lamports of the account.
fn get_lamports(&self) -> u64 {
self.as_ref().lamports()
}
// ... other methods
}A fresh borrow after the System Program transfer in the example reads the new lamport balance. Reading the amount field of an SPL token account uses a different piece of memory.
When interacting with account#
Unlike info, the account field (type T) is a deserialized snapshot of the account data bytes.
At the start of the instruction, Anchor constructs your accounts by deserializing them in the generated handler (see the "Deserialize accounts" section in handlers.rs):
// Deserialize accounts.
let mut __remaining_accounts: &[AccountInfo] = __accounts;
let mut __accounts = #anchor::try_accounts(
__program_id,
&mut __remaining_accounts,
__ix_data,
&mut __bumps,
&mut __reallocs,
)?;Later, Account::try_from deserializes T from info.data:
/// Deserializes the given `info` into a `Account`.
#[inline(never)]
pub fn try_from(info: &'a AccountInfo<'a>) -> Result<Account<'a, T>> {
if info.owner == &system_program::ID && info.lamports() == 0 {
return Err(ErrorCode::AccountNotInitialized.into());
}
if info.owner != &T::owner() {
return Err(Error::from(ErrorCode::AccountOwnedByWrongProgram)
.with_pubkeys((*info.owner, T::owner())));
}
let mut data: &[u8] = &info.try_borrow_data()?;
Ok(Account::new(info, T::try_deserialize(&mut data)?))
}The checks performed by try_deserialize depend on the type. Anchor-defined accounts commonly use a discriminator. The SPL token-account wrapper decodes the token program’s layout. Treat the discriminator size and layout as properties of the account type and Anchor version.
At that point the handler owns a Rust value containing the decoded fields. Changing the stored bytes leaves this previously decoded value in memory.
So after CPI, even if the account data bytes in runtime memory change, the cached T inside Account<T> does not change. But AccountInfo-based reads (like lamports helpers) still reflect the latest runtime state.
┌─────────────────────────────┐
│ Runtime Memory │
│ (AccountInfo, live state) │
│ │
│ ┌───────────────┐ │
│ │ lamports │ │
│ │ data[...] │ │
│ └───────────────┘ │
│ ▲ │
│ │ CPI modifies │
│ │ │
└───────────┴─────────────────┘
│
▼
┌───────────────────────────┐
│ Anchor Execution │
│ Context / View │
│ │
│ ┌───────────────┐ │
│ │ Account<T> │ │
│ │ struct data │ ←── Detached snapshot
│ └───────────────┘ │
│ Reads here see stale │
│ CPI changes do NOT │
│ automatically update │
│ view │
└───────────────────────────┘
Note:
- Writes to `Account<T>` inside your program can be serialized back to `AccountInfo` at the end of the instruction
- Detachment only means CPI / runtime changes do not propagate automatically into the view
For a mutable account owned by the executing application, Anchor can write the local value back on exit. If a call changed the stored bytes, serializing an older local value can overwrite those changes. A token account in this example belongs to the Token Program. The application can refresh its view of that account, but its ordinary exit does not serialize the local token amount back.
What is reloading doing?#
When you call reload() (see account.rs):
Anchor's docs say "reload from storage", but in practice this re-reads and deserializes from the current AccountInfo.data bytes held by the runtime.
/// Reloads the account from storage. This is useful, for example, when
/// observing side effects after CPI.
///
/// This method also re-validates that the program owner has not
/// changed since the initial validation
pub fn reload(&mut self) -> Result<()> {
if self.info.owner != &T::owner() {
return Err(Error::from(ErrorCode::AccountOwnedByWrongProgram)
.with_pubkeys((*self.info.owner, T::owner())));
}
let mut data: &[u8] = &self.info.try_borrow_data()?;
self.account = T::try_deserialize(&mut data)?; // deserialize again from the (now-updated) runtime bytes
Ok(())
}reload() re-deserializes from the current AccountInfo.data bytes, updating the cached T so subsequent field reads (like vault.amount) reflect CPI side effects.
The final writeback for anchor account#
After your handler returns, the generated code runs an exit routine (see handlers.rs):
// Exit routine.
__accounts.exit(__program_id)In the exit:
impl<'info, T: AccountSerialize + AccountDeserialize + Owner + Clone> AccountsExit<'info>
for Account<'info, T>
{
fn exit(&self, program_id: &Pubkey) -> Result<()> {
self.exit_with_expected_owner(&T::owner(), program_id)
}
}This function persists the cached T back into the account data only if the account is owned by the currently executing program (and not closed):
pub(crate) fn exit_with_expected_owner(
&self,
expected_owner: &Pubkey,
program_id: &Pubkey,
) -> Result<()> {
// Only persist if the owner is the current program and the account is not closed.
if expected_owner == program_id && !crate::common::is_closed(self.info) {
let mut data = self.info.try_borrow_mut_data()?;
let dst: &mut [u8] = &mut data;
let mut writer = BpfWriter::new(dst);
self.account.try_serialize(&mut writer)?;
}
Ok(())
}Pick the read that answers the question#
| Value the handler needs | Where to read it |
|---|---|
| Current lamports | Borrow the balance through AccountInfo after the CPI. |
Updated fields in an Account<T> | Save any required pre-call values, invoke the CPI, then call reload()? before reading the fields again. |
Current fields of a zero-copy AccountLoader<T> | Release any outstanding data borrow before the CPI, then acquire a fresh load() or load_mut() borrow afterward. |
| A value manually deserialized before the call | Decode it again from freshly borrowed account data. |
A reload replaces the local typed value, including edits that have not yet been serialized. It checks the expected program owner and deserializes the data. If the application relies on a relationship between two accounts, it must check that relationship where it uses it. In the opening transfer, the two quantities the application needs are the saved 40 and the newly decoded 55. Anchor account wrapper · Zero-copy account loader
Worth sharing?
Send this analysis to another reviewer.
