3

Is it possible to fetch account balance or token balance in the smart contract itself?

2 Answers 2

3

You can only read and write from the accounts which are included in the transaction. This is how you get the token balance and the SOL balance (in lamports):

pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
    let bal = ctx.accounts.token_account.amount;
    let sol_bal = ctx.accounts.admin.lamports();
    Ok(())
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(mut)]
    pub admin: Signer<'info>,
    #[account(mut)]
    pub staking_token: InterfaceAccount<'info, Mint>,
    #[account(mut)]
    pub token_account: InterfaceAccount<'info, TokenAccount>,
}

You cannot fetch the balance of an account which is not included in the accounts array in the transaction.

2

Hey yes you can always access the lamports of an account that was passed into the transaction like so :

let lamports = ctx.accounts.player.lamports();

or mutable

**ctx
                .accounts
                .player
                .to_account_info()
                .try_borrow_mut_lamports()?

You can even change them if you have signer rights for the account that you are subtracting from:

        **ctx
            .accounts
            .chest_vault
            .to_account_info()
            .try_borrow_mut_lamports()? -= CHEST_REWARD;
        **ctx
            .accounts
            .player
            .to_account_info()
            .try_borrow_mut_lamports()? += CHEST_REWARD;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.