Search code examples
rustsolanaanchor-solana

How to transfer SOL in anchor smart contract instruction


I am creating a dapp where multiple users can deposit SOL into an event account, and depending on whoever wins the event, they can redeem SOL back to their wallet.

How can I transfer native SOL (not any other spl-token) directly into the event account's vault address in an anchor smart contract instruction?

Would the following anchor instruction work? If yes, what should be the PROGRAM_ACCOUNT in the following? Presumably, it should be the account that handles native SOL, but I couldn't find it in the documentation.

token::transfer(
    CpiContext::new(
        PROGRAM_ACCOUNT,
        anchor_spl::token::Transfer {
            from: source_user_info,
            to: destination_user_info,
            authority: source_user_info,
        },
    ),
    1,
)?; 

Thanks in advance!


Solution

  • To send native SOL using Anchor, you can use the following code inside an instruction:

        let ix = anchor_lang::solana_program::system_instruction::transfer(
            &ctx.accounts.from.key(),
            &ctx.accounts.to.key(),
            amount,
        );
        anchor_lang::solana_program::program::invoke(
            &ix,
            &[
                ctx.accounts.from.to_account_info(),
                ctx.accounts.to.to_account_info(),
            ],
        );
    

    Where amount is a number (u64) representing the Lamports (0.000000001 SOL).

    You can check the Transfer function in the Solana Program documentation and the Solana Cookbook section of Sending SOL.