Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor SOL transfer program for improved security and clarity #124

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions basics/transfer-sol/anchor/programs/transfer-sol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,13 @@ declare_id!("4fQVnLWKKKYxtxgGn7Haw8v2g2Hzbu8K61JvWKvqAi7W");
pub mod transfer_sol {
use super::*;

/// Transfer SOL using Cross-Program Invocation (CPI)
pub fn transfer_sol_with_cpi(ctx: Context<TransferSolWithCpi>, amount: u64) -> Result<()> {
// Check for sufficient balance before transferring
let payer_balance = **ctx.accounts.payer.try_borrow_lamports()?;
require!(payer_balance >= amount, CustomError::InsufficientFunds);

// CPI-based transfer using the system program's transfer function
system_program::transfer(
CpiContext::new(
ctx.accounts.system_program.to_account_info(),
Expand All @@ -29,6 +35,10 @@ pub mod transfer_sol {
ctx: Context<TransferSolWithProgram>,
amount: u64,
) -> Result<()> {
// Check if the payer has sufficient funds for the transfer
let payer_balance = **ctx.accounts.payer.try_borrow_lamports()?;
require!(payer_balance >= amount, CustomError::InsufficientFunds);

**ctx.accounts.payer.try_borrow_mut_lamports()? -= amount;
**ctx.accounts.recipient.try_borrow_mut_lamports()? += amount;
Ok(())
Expand All @@ -55,3 +65,9 @@ pub struct TransferSolWithProgram<'info> {
#[account(mut)]
recipient: SystemAccount<'info>,
}

#[error_code]
pub enum CustomError {
#[msg("Insufficient funds for the transfer.")]
InsufficientFunds,
}