-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathpump.rs
377 lines (349 loc) · 14.4 KB
/
pump.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
use std::{str::FromStr, sync::Arc};
use anyhow::{anyhow, Context, Result};
use borsh::from_slice;
use borsh_derive::{BorshDeserialize, BorshSerialize};
use raydium_amm::math::U128;
use serde::{Deserialize, Serialize};
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_sdk::{
instruction::{AccountMeta, Instruction},
pubkey::Pubkey,
signature::Keypair,
signer::Signer,
system_program,
};
use spl_associated_token_account::{
get_associated_token_address, instruction::create_associated_token_account,
};
use spl_token::{amount_to_ui_amount, ui_amount_to_amount};
use spl_token_client::token::TokenError;
use tracing::{debug, error, info, warn};
use crate::{
swap::{SwapDirection, SwapInType},
token, tx,
};
pub const TEN_THOUSAND: u64 = 10000;
pub const TOKEN_PROGRAM: &str = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
pub const RENT_PROGRAM: &str = "SysvarRent111111111111111111111111111111111";
pub const ASSOCIATED_TOKEN_PROGRAM: &str = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
pub const PUMP_GLOBAL: &str = "4wTV1YmiEkRvAtNtsSGPtUrqRYQMe5SKy2uB4Jjaxnjf";
pub const PUMP_FEE_RECIPIENT: &str = "CebN5WGQ4jvEPvsVU4EoHEpgzq1VV7AbicfhtW4xC9iM";
pub const PUMP_PROGRAM: &str = "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P";
// pub const PUMP_FUN_MINT_AUTHORITY: &str = "TSLvdd1pWpHVjahSpsvCXUbgwsL3JAcvokwaKt1eokM";
pub const PUMP_ACCOUNT: &str = "Ce6TQqeHC9p8KetsN6JsjHK7UTZk7nasjjnr7XxXp9F1";
pub const PUMP_BUY_METHOD: u64 = 16927863322537952870;
pub const PUMP_SELL_METHOD: u64 = 12502976635542562355;
pub struct Pump {
pub client: Arc<RpcClient>,
pub keypair: Arc<Keypair>,
pub client_blocking: Option<Arc<solana_client::rpc_client::RpcClient>>,
}
impl Pump {
pub fn new(client: Arc<RpcClient>, keypair: Arc<Keypair>) -> Self {
Self {
client,
keypair,
client_blocking: None,
}
}
pub fn with_blocking_client(
&mut self,
client: Arc<solana_client::rpc_client::RpcClient>,
) -> &mut Self {
self.client_blocking = Some(client);
self
}
pub async fn swap(
&self,
mint: &str,
amount_in: f64,
swap_direction: SwapDirection,
in_type: SwapInType,
slippage: u64,
use_jito: bool,
) -> Result<Vec<String>> {
// slippage_bps = 50u64; // 0.5%
let slippage_bps = slippage * 100;
let owner = self.keypair.pubkey();
let mint =
Pubkey::from_str(mint).map_err(|e| anyhow!("failed to parse mint pubkey: {}", e))?;
let program_id = spl_token::ID;
let native_mint = spl_token::native_mint::ID;
let (token_in, token_out, pump_method) = match swap_direction {
SwapDirection::Buy => (native_mint, mint, PUMP_BUY_METHOD),
SwapDirection::Sell => (mint, native_mint, PUMP_SELL_METHOD),
};
let pump_program = Pubkey::from_str(PUMP_PROGRAM)?;
let (bonding_curve, associated_bonding_curve, bonding_curve_account) =
get_bonding_curve_account(self.client_blocking.clone().unwrap(), &mint, &pump_program)
.await?;
let in_ata = get_associated_token_address(&owner, &token_in);
let out_ata = get_associated_token_address(&owner, &token_out);
let mut create_instruction = None;
let mut close_instruction = None;
let (amount_specified, amount_ui_pretty) = match swap_direction {
SwapDirection::Buy => {
// Create base ATA if it doesn't exist.
match token::get_account_info(
self.client.clone(),
self.keypair.clone(),
&token_out,
&out_ata,
)
.await
{
Ok(_) => debug!("base ata exists. skipping creation.."),
Err(TokenError::AccountNotFound) | Err(TokenError::AccountInvalidOwner) => {
info!(
"base ATA for mint {} does not exist. will be create",
token_out
);
create_instruction = Some(create_associated_token_account(
&owner,
&owner,
&token_out,
&program_id,
));
}
Err(error) => error!("error retrieving out ATA: {}", error),
}
(
ui_amount_to_amount(amount_in, spl_token::native_mint::DECIMALS),
(amount_in, spl_token::native_mint::DECIMALS),
)
}
SwapDirection::Sell => {
let in_account = token::get_account_info(
self.client.clone(),
self.keypair.clone(),
&token_in,
&in_ata,
)
.await?;
let in_mint =
token::get_mint_info(self.client.clone(), self.keypair.clone(), &token_in)
.await?;
let amount = match in_type {
SwapInType::Qty => ui_amount_to_amount(amount_in, in_mint.base.decimals),
SwapInType::Pct => {
let amount_in_pct = amount_in.min(1.0);
if amount_in_pct == 1.0 {
// sell all, close ata
info!("sell all. will be close ATA for mint {}", token_in);
close_instruction = Some(spl_token::instruction::close_account(
&program_id,
&in_ata,
&owner,
&owner,
&vec![&owner],
)?);
in_account.base.amount
} else {
(amount_in_pct * 100.0) as u64 * in_account.base.amount / 100
}
}
};
(
amount,
(
amount_to_ui_amount(amount, in_mint.base.decimals),
in_mint.base.decimals,
),
)
}
};
info!(
"swap: {}, value: {:?} -> {}",
token_in, amount_ui_pretty, token_out
);
let client = self
.client_blocking
.clone()
.context("failed to get rpc client")?;
// Calculate tokens out
let virtual_sol_reserves = U128::from(bonding_curve_account.virtual_sol_reserves);
let virtual_token_reserves = U128::from(bonding_curve_account.virtual_token_reserves);
let unit_price = (bonding_curve_account.virtual_sol_reserves as f64
/ bonding_curve_account.virtual_token_reserves as f64)
/ 1000.0;
let (token_amount, sol_amount_threshold, input_accouts) = match swap_direction {
SwapDirection::Buy => {
let max_sol_cost = max_amount_with_slippage(amount_specified, slippage_bps);
(
U128::from(amount_specified)
.checked_mul(virtual_token_reserves)
.unwrap()
.checked_div(virtual_sol_reserves)
.unwrap()
.as_u64(),
max_sol_cost,
vec![
AccountMeta::new_readonly(Pubkey::from_str(PUMP_GLOBAL)?, false),
AccountMeta::new(Pubkey::from_str(PUMP_FEE_RECIPIENT)?, false),
AccountMeta::new_readonly(mint, false),
AccountMeta::new(bonding_curve, false),
AccountMeta::new(associated_bonding_curve, false),
AccountMeta::new(out_ata, false),
AccountMeta::new(owner, true),
AccountMeta::new_readonly(system_program::id(), false),
AccountMeta::new_readonly(program_id, false),
AccountMeta::new_readonly(Pubkey::from_str(RENT_PROGRAM)?, false),
AccountMeta::new_readonly(Pubkey::from_str(PUMP_ACCOUNT)?, false),
AccountMeta::new_readonly(pump_program, false),
],
)
}
SwapDirection::Sell => {
let sol_output = U128::from(amount_specified)
.checked_mul(virtual_sol_reserves)
.unwrap()
.checked_div(virtual_token_reserves)
.unwrap()
.as_u64();
let min_sol_output = min_amount_with_slippage(sol_output, slippage_bps);
(
amount_specified,
min_sol_output,
vec![
AccountMeta::new_readonly(Pubkey::from_str(PUMP_GLOBAL)?, false),
AccountMeta::new(Pubkey::from_str(PUMP_FEE_RECIPIENT)?, false),
AccountMeta::new_readonly(mint, false),
AccountMeta::new(bonding_curve, false),
AccountMeta::new(associated_bonding_curve, false),
AccountMeta::new(in_ata, false),
AccountMeta::new(owner, true),
AccountMeta::new_readonly(system_program::id(), false),
AccountMeta::new_readonly(
Pubkey::from_str(ASSOCIATED_TOKEN_PROGRAM)?,
false,
),
AccountMeta::new_readonly(program_id, false),
AccountMeta::new_readonly(Pubkey::from_str(PUMP_ACCOUNT)?, false),
AccountMeta::new_readonly(pump_program, false),
],
)
}
};
info!(
"token_amount: {}, sol_amount_threshold: {}, unit_price: {} sol",
token_amount, sol_amount_threshold, unit_price
);
let build_swap_instruction = Instruction::new_with_bincode(
pump_program,
&(pump_method, token_amount, sol_amount_threshold),
input_accouts,
);
// build instructions
let mut instructions = vec![];
if let Some(create_instruction) = create_instruction {
instructions.push(create_instruction);
}
if amount_specified > 0 {
instructions.push(build_swap_instruction)
}
if let Some(close_instruction) = close_instruction {
instructions.push(close_instruction);
}
if instructions.len() == 0 {
return Err(anyhow!("instructions is empty, no tx required"));
}
tx::new_signed_and_send(&client, &self.keypair, instructions, use_jito).await
}
}
fn min_amount_with_slippage(input_amount: u64, slippage_bps: u64) -> u64 {
input_amount
.checked_mul(TEN_THOUSAND.checked_sub(slippage_bps).unwrap())
.unwrap()
.checked_div(TEN_THOUSAND)
.unwrap()
}
fn max_amount_with_slippage(input_amount: u64, slippage_bps: u64) -> u64 {
input_amount
.checked_mul(slippage_bps.checked_add(TEN_THOUSAND).unwrap())
.unwrap()
.checked_div(TEN_THOUSAND)
.unwrap()
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RaydiumInfo {
pub base: f64,
pub quote: f64,
pub price: f64,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PumpInfo {
pub mint: String,
pub bonding_curve: String,
pub associated_bonding_curve: String,
pub raydium_pool: Option<String>,
pub raydium_info: Option<RaydiumInfo>,
pub complete: bool,
pub virtual_sol_reserves: u64,
pub virtual_token_reserves: u64,
pub total_supply: u64,
}
#[derive(Debug, BorshSerialize, BorshDeserialize)]
pub struct BondingCurveAccount {
pub discriminator: u64,
pub virtual_token_reserves: u64,
pub virtual_sol_reserves: u64,
pub real_token_reserves: u64,
pub real_sol_reserves: u64,
pub token_total_supply: u64,
pub complete: bool,
}
pub async fn get_bonding_curve_account(
rpc_client: Arc<solana_client::rpc_client::RpcClient>,
mint: &Pubkey,
program_id: &Pubkey,
) -> Result<(Pubkey, Pubkey, BondingCurveAccount)> {
let bonding_curve = get_pda(mint, program_id)?;
let associated_bonding_curve = get_associated_token_address(&bonding_curve, &mint);
let bonding_curve_data = rpc_client
.get_account_data(&bonding_curve)
.inspect_err(|err| {
warn!(
"Failed to get bonding curve account data: {}, err: {}",
bonding_curve, err
);
})?;
let bonding_curve_account =
from_slice::<BondingCurveAccount>(&bonding_curve_data).map_err(|e| {
anyhow!(
"Failed to deserialize bonding curve account: {}",
e.to_string()
)
})?;
Ok((
bonding_curve,
associated_bonding_curve,
bonding_curve_account,
))
}
pub fn get_pda(mint: &Pubkey, program_id: &Pubkey) -> Result<Pubkey> {
let seeds = [b"bonding-curve".as_ref(), mint.as_ref()];
let (bonding_curve, _bump) = Pubkey::find_program_address(&seeds, program_id);
Ok(bonding_curve)
}
// https://frontend-api.pump.fun/coins/8zSLdDzM1XsqnfrHmHvA9ir6pvYDjs8UXz6B2Tydd6b2
pub async fn get_pump_info(
rpc_client: Arc<solana_client::rpc_client::RpcClient>,
mint: &str,
) -> Result<PumpInfo> {
let mint = Pubkey::from_str(mint)?;
let program_id = Pubkey::from_str(PUMP_PROGRAM)?;
let (bonding_curve, associated_bonding_curve, bonding_curve_account) =
get_bonding_curve_account(rpc_client, &mint, &program_id).await?;
let pump_info = PumpInfo {
mint: mint.to_string(),
bonding_curve: bonding_curve.to_string(),
associated_bonding_curve: associated_bonding_curve.to_string(),
raydium_pool: None,
raydium_info: None,
complete: bonding_curve_account.complete,
virtual_sol_reserves: bonding_curve_account.virtual_sol_reserves,
virtual_token_reserves: bonding_curve_account.virtual_token_reserves,
total_supply: bonding_curve_account.token_total_supply,
};
Ok(pump_info)
}