/
lib.rs
231 lines (202 loc) · 7.25 KB
/
lib.rs
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
use anchor_lang::{
prelude::*,
solana_program::{entrypoint::ProgramResult, instruction::Instruction, program::invoke_signed},
system_program,
};
use anchor_spl::token::{self, Mint, Token, TokenAccount};
declare_id!("JUPDWNB9G9Hsg8PKynnP6DyWLsXVn4QnqMCqg6n4ZdM");
pub const AUTHORITY_SEED: &[u8] = b"authority";
pub const WSOL_SEED: &[u8] = b"wsol";
mod jupiter {
use anchor_lang::declare_id;
declare_id!("JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4");
}
#[derive(Clone)]
pub struct Jupiter;
impl anchor_lang::Id for Jupiter {
fn id() -> Pubkey {
jupiter::id()
}
}
#[error_code]
pub enum ErrorCode {
InvalidReturnData,
InvalidJupiterProgram,
IncorrectOwner,
}
#[program]
pub mod swap_to_sol {
use super::*;
pub fn swap_to_sol(ctx: Context<SwapToSOL>, data: Vec<u8>) -> Result<()> {
let authority_bump = ctx.bumps.get("program_authority").unwrap().to_le_bytes();
let wsol_bump = ctx.bumps.get("program_wsol_account").unwrap().to_le_bytes();
create_wsol_token_idempotent(
ctx.accounts.program_authority.clone(),
ctx.accounts.program_wsol_account.clone(),
ctx.accounts.sol_mint.clone(),
ctx.accounts.token_program.clone(),
ctx.accounts.system_program.clone(),
&authority_bump,
&wsol_bump,
)?;
msg!("Swap on Jupiter");
swap_on_jupiter(
ctx.remaining_accounts,
ctx.accounts.jupiter_program.clone(),
data,
)?;
let after_swap_lamports = ctx.accounts.program_wsol_account.lamports();
close_program_wsol(
ctx.accounts.program_authority.clone(),
ctx.accounts.program_wsol_account.clone(),
ctx.accounts.token_program.clone(),
&authority_bump,
)?;
let rent = Rent::get()?;
let space = TokenAccount::LEN;
let token_lamports = rent.minimum_balance(space);
let out_amount = after_swap_lamports - token_lamports;
msg!("Transfer SOL to user");
let signer_seeds: &[&[&[u8]]] = &[&[AUTHORITY_SEED, authority_bump.as_ref()]];
let lamports = out_amount;
system_program::transfer(
CpiContext::new_with_signer(
ctx.accounts.system_program.to_account_info(),
system_program::Transfer {
from: ctx.accounts.program_authority.to_account_info(),
to: ctx.accounts.user_account.to_account_info(),
},
signer_seeds,
),
lamports,
)?;
Ok(())
}
}
fn swap_on_jupiter<'info>(
remaining_accounts: &[AccountInfo],
jupiter_program: Program<'info, Jupiter>,
data: Vec<u8>,
) -> ProgramResult {
let accounts: Vec<AccountMeta> = remaining_accounts
.iter()
.map(|acc| AccountMeta {
pubkey: *acc.key,
is_signer: acc.is_signer,
is_writable: acc.is_writable,
})
.collect();
let accounts_infos: Vec<AccountInfo> = remaining_accounts
.iter()
.map(|acc| AccountInfo { ..acc.clone() })
.collect();
// TODO: Check the first 8 bytes. Only Jupiter Route CPI allowed.
invoke_signed(
&Instruction {
program_id: *jupiter_program.key,
accounts,
data,
},
&accounts_infos,
&[],
)
}
fn create_wsol_token_idempotent<'info>(
program_authority: SystemAccount<'info>,
program_wsol_account: UncheckedAccount<'info>,
sol_mint: Account<'info, Mint>,
token_program: Program<'info, Token>,
system_program: Program<'info, System>,
authority_bump: &[u8],
wsol_bump: &[u8],
) -> Result<TokenAccount> {
if program_wsol_account.data_is_empty() {
let signer_seeds: &[&[&[u8]]] = &[
&[AUTHORITY_SEED, authority_bump.as_ref()],
&[WSOL_SEED, wsol_bump.as_ref()],
];
msg!("Initialize program wSOL account");
let rent = Rent::get()?;
let space = TokenAccount::LEN;
let lamports = rent.minimum_balance(space);
system_program::create_account(
CpiContext::new_with_signer(
system_program.to_account_info(),
system_program::CreateAccount {
from: program_authority.to_account_info(),
to: program_wsol_account.to_account_info(),
},
signer_seeds,
),
lamports,
space as u64,
token_program.key,
)?;
msg!("Initialize program wSOL token account");
token::initialize_account3(CpiContext::new(
token_program.to_account_info(),
token::InitializeAccount3 {
account: program_wsol_account.to_account_info(),
mint: sol_mint.to_account_info(),
authority: program_authority.to_account_info(),
},
))?;
let data = program_wsol_account.try_borrow_data()?;
let wsol_token_account = TokenAccount::try_deserialize(&mut data.as_ref())?;
Ok(wsol_token_account)
} else {
let data = program_wsol_account.try_borrow_data()?;
let wsol_token_account = TokenAccount::try_deserialize(&mut data.as_ref())?;
if &wsol_token_account.owner != program_authority.key {
// TODO: throw error
return err!(ErrorCode::IncorrectOwner);
}
Ok(wsol_token_account)
}
}
fn close_program_wsol<'info>(
program_authority: SystemAccount<'info>,
program_wsol_account: UncheckedAccount<'info>,
token_program: Program<'info, Token>,
authority_bump: &[u8],
) -> Result<()> {
let signer_seeds: &[&[&[u8]]] = &[&[AUTHORITY_SEED, authority_bump.as_ref()]];
msg!("Close program wSOL token account");
token::close_account(CpiContext::new_with_signer(
token_program.to_account_info(),
token::CloseAccount {
account: program_wsol_account.to_account_info(),
destination: program_authority.to_account_info(),
authority: program_authority.to_account_info(),
},
signer_seeds,
))
}
#[derive(Accounts)]
pub struct SwapToSOL<'info> {
#[account(mut, seeds = [AUTHORITY_SEED], bump)]
pub program_authority: SystemAccount<'info>,
/// CHECK: This may not be initialized yet.
#[account(mut, seeds = [WSOL_SEED], bump)]
pub program_wsol_account: UncheckedAccount<'info>,
pub user_account: Signer<'info>,
#[account(address = spl_token::native_mint::id())]
pub sol_mint: Account<'info, Mint>,
pub jupiter_program: Program<'info, Jupiter>,
pub token_program: Program<'info, Token>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct SOLToSwap<'info> {
#[account(mut, seeds = [AUTHORITY_SEED], bump)]
pub program_authority: SystemAccount<'info>,
/// CHECK: This may not be initialized yet.
#[account(mut, seeds = [WSOL_SEED], bump)]
pub program_wsol_account: UncheckedAccount<'info>,
pub user_account: Signer<'info>,
#[account(address = spl_token::native_mint::id())]
pub sol_mint: Account<'info, Mint>,
pub jupiter_program: Program<'info, Jupiter>,
pub token_program: Program<'info, Token>,
pub system_program: Program<'info, System>,
}