1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
use anchor_lang::prelude::*;
use anchor_spl::token::TokenAccount;
use solana_program::{
    account_info::AccountInfo,
    program::invoke_signed,
    rent::Rent,
    system_instruction,
};
use spl_token::ID;

use crate::{wrapped_sol, SharedError};

pub fn transfer_native<'info>(
    from_account: &AccountInfo<'info>,
    tmp_token_account: &AccountInfo<'info>, // used for transferring wrapped SOL, must be owned by payer
    target_token_account: &AccountInfo<'info>, // final target token account for wrapped SOL
    authority_seeds: Option<&[&[u8]]>,      // None or Some as needed for CPI
    payer: &AccountInfo<'info>,
    token_program: &AccountInfo<'info>,
    mint: &AccountInfo<'info>,
    native_sol_auth_seeds: &[&[u8]], // None or Some as needed for CPI
    amount: u64,
) -> Result<()> {
    // this is a native transfer
    let minimum_rent = Rent::get()?.minimum_balance(TokenAccount::LEN);
    msg!("Transferring native token");

    let mut create_tmp_account = false;
    if tmp_token_account.data_is_empty() {
        create_tmp_account = true;
        let wrap_infos = vec![
            from_account.to_account_info(),
            tmp_token_account.to_account_info(),
        ];
        match authority_seeds {
            Some(_authority_seeds) => {
                // if native_sol_auth_seeds.is_none() {
                //     return Err(SharedError::NativeSolAuthSeedsNotSpecified.into())
                // }
                // wrapped sol token account
                invoke_signed(
                    &system_instruction::create_account(
                        &payer.key(),
                        &tmp_token_account.key(),
                        // rent.minimum_balance(Mint::LEN),
                        minimum_rent + amount,
                        TokenAccount::LEN as u64,
                        &ID,
                    ),
                    wrap_infos.as_slice(),
                    &[_authority_seeds, native_sol_auth_seeds],
                )?;

                anchor_spl::token::initialize_account3(CpiContext::new_with_signer(
                    token_program.to_account_info(),
                    anchor_spl::token::InitializeAccount3 {
                        account: tmp_token_account.to_account_info(),
                        mint: mint.to_account_info(),
                        authority: payer.to_account_info(),
                    },
                    &[_authority_seeds],
                ))?;
            }
            None => {
                msg!("Create account");
                invoke_signed(
                    &system_instruction::create_account(
                        &payer.key(),
                        &tmp_token_account.key(),
                        // rent.minimum_balance(Mint::LEN),
                        minimum_rent + amount,
                        TokenAccount::LEN as u64,
                        &ID,
                    ),
                    wrap_infos.as_slice(),
                    &[native_sol_auth_seeds],
                )?;

                msg!("Initialise account");
                anchor_spl::token::initialize_account3(CpiContext::new(
                    token_program.to_account_info(),
                    anchor_spl::token::InitializeAccount3 {
                        account: tmp_token_account.to_account_info(),
                        mint: mint.to_account_info(),
                        authority: payer.to_account_info(),
                    },
                ))?;
                msg!("Created & initialised.");
            }
        }
    } else {
        msg!("bad token account ");
        // ok we can use an existing one as long as the owner and mint match
        let tai = tmp_token_account.to_account_info();
        let data: &[u8] = &tai.try_borrow_data()?;
        #[allow(noop_method_call)]
        let tmp_token_account_obj = TokenAccount::try_deserialize(&mut data.clone())?;
        if tmp_token_account_obj.mint != wrapped_sol::ID {
            return Err(SharedError::BadTokenAccountMint.into());
        }

        if tmp_token_account_obj.owner != payer.key() {
            return Err(SharedError::BadTokenAccountOwner.into());
        }

        // transfer the native sol
        match authority_seeds {
            Some(_authority_seeds) => {
                anchor_lang::solana_program::program::invoke_signed(
                    &anchor_lang::solana_program::system_instruction::transfer(
                        &payer.key(),
                        &tmp_token_account.key(),
                        amount,
                    ),
                    &[payer.clone(), tmp_token_account.clone()],
                    &[_authority_seeds],
                )?;
            }
            None => {
                anchor_lang::solana_program::program::invoke(
                    &anchor_lang::solana_program::system_instruction::transfer(
                        &payer.key(),
                        &tmp_token_account.key(),
                        amount,
                    ),
                    &[payer.clone(), tmp_token_account.clone()],
                )?;
            }
        }
    }

    match authority_seeds {
        Some(_authority_seeds) => {
            msg!("Transferring native token");
            anchor_spl::token::transfer(
                CpiContext::new_with_signer(
                    token_program.to_account_info(),
                    anchor_spl::token::Transfer {
                        to: target_token_account.to_account_info(),
                        from: tmp_token_account.to_account_info(),
                        authority: from_account.to_account_info(),
                    },
                    &[_authority_seeds],
                ),
                amount,
            )?;
            if create_tmp_account {
                // clean up
                anchor_spl::token::close_account(CpiContext::new_with_signer(
                    token_program.to_account_info(),
                    anchor_spl::token::CloseAccount {
                        account: tmp_token_account.to_account_info(),
                        destination: payer.to_account_info(),
                        authority: payer.to_account_info(),
                    },
                    &[_authority_seeds],
                ))?;
            }
        },
        None => {
            msg!("Transferring native token without auth");
            anchor_spl::token::transfer(
                CpiContext::new(
                    token_program.to_account_info(),
                    anchor_spl::token::Transfer {
                        to: target_token_account.to_account_info(),
                        from: tmp_token_account.to_account_info(),
                        authority: from_account.to_account_info(),
                    },
                ),
                amount,
            )?;

            msg!("Cleaning up");
            if create_tmp_account {
                anchor_spl::token::close_account(CpiContext::new(
                    token_program.to_account_info(),
                    anchor_spl::token::CloseAccount {
                        account: tmp_token_account.to_account_info(),
                        destination: payer.to_account_info(),
                        authority: payer.to_account_info(),
                    },
                ))?;
            }
        }
    };

    // clean up if we created this

    Ok(())
}