Search code examples
rustblockchainsmartcontractssolana

How to send SOL with a solana rust contract


I'm a noob Rust/Solana Developer and feel like I'm encountering an issue that would be helpful to most other noobs.

I want to how to transfer SOL from an account to a program during an instruction, and then be able to send SOL back to the account who called the instruction.

I read the https://docs.solana.com/ but I could not find anything about SOL transfers via programs.

Example:

Acc1 calls the gamble instruction in Program1, which transfers 1 SOL from the caller and then runs a verifiable random function. If Acct1 wins the gamble, Program1 then sends 2 SOL back to Acct1.

I would really appreciate some help, thanks!


Solution

  • You can have a program similar to this one in the cookbook: https://solanacookbook.com/references/programs.html#how-to-do-cross-program-invocation

    The differences in your case are to:

    • use solana_program::system_instruction::transfer instead of spl_token::instruction::transfer
    • only have source and destination accounts, without the owner
    • sign with the source account
    • pass in the system program instead of the token program