7

I have SOL in my program account. Is it possible to transfer that native (NOT WSOL) SOL to user?

If yes, How?

2 Answers 2

6

You can do something like this with an account that the program owns. The syntax used to access accounts is slightly anchor specific but the idea works in for regular solana programs too.

    let authority_lamports = ctx.accounts.authority.lamports();
    **ctx.accounts.authority.lamports.borrow_mut() = authority_lamports
        .checked_add(ctx.accounts.your_program_account.lamports())
        .unwrap();

    **ctx.accounts.your_program_account.lamports.borrow_mut() = 0;
3
  • authority is just the user's system program account. Usually authority is used to denote someone who has to sign a transaction to have control over some account.
    – Henry E
    Jul 19, 2022 at 21:03
  • Does solana panic/revert if your addition and subtractions dont match up? And if the account you are subtracting from isnt signing/the program? Jul 21, 2022 at 8:57
  • Yes to both afaik
    – Henry E
    Jul 21, 2022 at 10:28
1
    // creating SOL transfer instruction
    let ix = anchor_lang::solana_program::system_instruction::transfer(
        from_pubkey, 
        &to_pubkey, 
        amount
    );

    // invoking SOL transfer instruction
    anchor_lang::solana_program::program::invoke(
        &ix,
        &[
            // from
            ctx.accounts.from_account.to_account_info(),
            // to
            ctx.accounts.to_account.to_account_info(),
        ]
    )?;

I think this should work for programs aswell. Ofcourse this would fail if amount is higher than balance or the "from" pubkey is not the signer

2
  • 1
    Pretty sure this only works when transfering Sol from accounts owned by the system program.
    – Henry E
    Jul 20, 2022 at 9:02
  • To clarify @henry-e's comment, this works if the program has a PDA that is a system account
    – trent.sol
    Jul 21, 2022 at 0:50

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.