solana_exec/utilities/
close_token_account_check.rs

1use crate::constants::COMPUTE_UNITS;
2use crate::types::swap_config::SwapConfig;
3use solana_central::SwapDirection;
4use solana_central::constants::SOLANA_PROGRAMS;
5use solana_sdk::instruction::Instruction;
6use solana_sdk::pubkey::Pubkey;
7use spl_associated_token_account::get_associated_token_address;
8use spl_token::instruction::close_account;
9
10/// Add instructions to close token accounts after swaps if needed. Iterates through swap configs
11/// and adds close-account instructions for any swaps where `close_token_account` is true. Updates
12/// the compute unit budget accordingly.
13pub fn close_token_account_check(
14  swap_configs: &Vec<SwapConfig>,
15  instructions: &mut Vec<Instruction>,
16  compute_unit_budget: &mut u32,
17) {
18  for swap_config in swap_configs {
19    let pool = swap_config.pool.read().unwrap();
20    if swap_config.close_token_account {
21      let mut token_address: &Pubkey = pool.token_a_address();
22      if swap_config.direction == SwapDirection::BToA {
23        token_address = pool.token_b_address();
24      }
25      let token_account = get_associated_token_address(&swap_config.wallet, token_address);
26      instructions.push(
27        close_account(
28          &SOLANA_PROGRAMS.token_program,
29          &token_account,
30          &swap_config.wallet,
31          &swap_config.wallet,
32          &[],
33        )
34        .unwrap(),
35      );
36      *compute_unit_budget += COMPUTE_UNITS.close_token_account;
37    }
38  }
39}