light_sdk/interface/
close.rs

1use solana_account_info::AccountInfo;
2
3use crate::error::{LightSdkError, Result};
4
5// close native solana account
6pub fn close<'info>(
7    info: &mut AccountInfo<'info>,
8    sol_destination: AccountInfo<'info>,
9) -> Result<()> {
10    let system_program_id = solana_pubkey::pubkey!("11111111111111111111111111111111");
11
12    if info.key == sol_destination.key {
13        info.assign(&system_program_id);
14        info.resize(0)
15            .map_err(|_| LightSdkError::ConstraintViolation)?;
16        return Ok(());
17    }
18
19    let lamports_to_transfer = info.lamports();
20
21    let new_destination_lamports = sol_destination
22        .lamports()
23        .checked_add(lamports_to_transfer)
24        .ok_or(LightSdkError::ConstraintViolation)?;
25
26    {
27        let mut destination_lamports = sol_destination
28            .try_borrow_mut_lamports()
29            .map_err(|_| LightSdkError::ConstraintViolation)?;
30        **destination_lamports = new_destination_lamports;
31    }
32
33    {
34        let mut source_lamports = info
35            .try_borrow_mut_lamports()
36            .map_err(|_| LightSdkError::ConstraintViolation)?;
37        **source_lamports = 0;
38    }
39
40    info.assign(&system_program_id);
41    info.resize(0)
42        .map_err(|_| LightSdkError::ConstraintViolation)?;
43
44    Ok(())
45}