-
Notifications
You must be signed in to change notification settings - Fork 68
/
quote.rs
519 lines (434 loc) · 15.4 KB
/
quote.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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
use anchor_client::solana_sdk::pubkey::Pubkey;
use anyhow::{ensure, Context, Result};
use lb_clmm::{
pair_action_access::ActivationType,
state::{
bin::{Bin, BinArray, SwapResult},
bin_array_bitmap_extension::BinArrayBitmapExtension,
lb_pair::{LbPair, PairStatus, PairType},
},
utils::pda::derive_bin_array_pda,
};
use std::collections::HashMap;
#[derive(Debug)]
pub struct SwapExactInQuote {
pub amount_out: u64,
pub fee: u64,
}
#[derive(Debug)]
pub struct SwapExactOutQuote {
pub amount_in: u64,
pub fee: u64,
}
fn validate_swap_activation(
lb_pair: &LbPair,
current_timestamp: u64,
current_slot: u64,
) -> Result<()> {
ensure!(
lb_pair.status()?.eq(&PairStatus::Enabled),
"Pair is disabled"
);
let pair_type = lb_pair.pair_type()?;
if pair_type.eq(&PairType::Permission) {
let activation_type = ActivationType::try_from(lb_pair.activation_type)?;
let current_point = match activation_type {
ActivationType::Slot => current_slot,
ActivationType::Timestamp => current_timestamp,
};
ensure!(
current_point >= lb_pair.activation_point,
"Pair is disabled"
);
}
Ok(())
}
pub fn quote_exact_out(
lb_pair_pubkey: Pubkey,
lb_pair: &LbPair,
mut amount_out: u64,
swap_for_y: bool,
bin_arrays: HashMap<Pubkey, BinArray>,
bitmap_extension: Option<&BinArrayBitmapExtension>,
current_timestamp: u64,
current_slot: u64,
) -> Result<SwapExactOutQuote> {
validate_swap_activation(lb_pair, current_timestamp, current_slot)?;
let mut lb_pair = *lb_pair;
lb_pair.update_references(current_timestamp as i64)?;
let mut total_amount_in: u64 = 0;
let mut total_fee: u64 = 0;
while amount_out > 0 {
let active_bin_array_pubkey = get_bin_array_pubkeys_for_swap(
lb_pair_pubkey,
&lb_pair,
bitmap_extension,
swap_for_y,
1,
)?
.pop()
.context("Pool out of liquidity")?;
let mut active_bin_array = bin_arrays
.get(&active_bin_array_pubkey)
.cloned()
.context("Active bin array not found")?;
loop {
if active_bin_array
.is_bin_id_within_range(lb_pair.active_id)
.is_err()
|| amount_out == 0
{
break;
}
lb_pair.update_volatility_accumulator()?;
let active_bin = active_bin_array.get_bin_mut(lb_pair.active_id)?;
let price = active_bin.get_or_store_bin_price(lb_pair.active_id, lb_pair.bin_step)?;
if !active_bin.is_empty(!swap_for_y) {
let bin_max_amount_out = active_bin.get_max_amount_out(swap_for_y);
if amount_out >= bin_max_amount_out {
let max_amount_in = active_bin.get_max_amount_in(price, swap_for_y)?;
let max_fee = lb_pair.compute_fee(max_amount_in)?;
total_amount_in = total_amount_in
.checked_add(max_amount_in)
.context("MathOverflow")?;
total_fee = total_fee.checked_add(max_fee).context("MathOverflow")?;
amount_out = amount_out
.checked_sub(bin_max_amount_out)
.context("MathOverflow")?;
} else {
let amount_in = Bin::get_amount_in(amount_out, price, swap_for_y)?;
let fee = lb_pair.compute_fee(amount_in)?;
total_amount_in = total_amount_in
.checked_add(amount_in)
.context("MathOverflow")?;
total_fee = total_fee.checked_add(fee).context("MathOverflow")?;
amount_out = 0;
}
}
if amount_out > 0 {
lb_pair.advance_active_bin(swap_for_y)?;
}
}
}
Ok(SwapExactOutQuote {
amount_in: total_amount_in,
fee: total_fee,
})
}
pub fn quote_exact_in(
lb_pair_pubkey: Pubkey,
lb_pair: &LbPair,
mut amount_in: u64,
swap_for_y: bool,
bin_arrays: HashMap<Pubkey, BinArray>,
bitmap_extension: Option<&BinArrayBitmapExtension>,
current_timestamp: u64,
current_slot: u64,
) -> Result<SwapExactInQuote> {
validate_swap_activation(lb_pair, current_timestamp, current_slot)?;
let mut lb_pair = *lb_pair;
lb_pair.update_references(current_timestamp as i64)?;
let mut total_amount_out: u64 = 0;
let mut total_fee: u64 = 0;
while amount_in > 0 {
let active_bin_array_pubkey = get_bin_array_pubkeys_for_swap(
lb_pair_pubkey,
&lb_pair,
bitmap_extension,
swap_for_y,
1,
)?
.pop()
.context("Pool out of liquidity")?;
let mut active_bin_array = bin_arrays
.get(&active_bin_array_pubkey)
.cloned()
.context("Active bin array not found")?;
loop {
if active_bin_array
.is_bin_id_within_range(lb_pair.active_id)
.is_err()
|| amount_in == 0
{
break;
}
lb_pair.update_volatility_accumulator()?;
let active_bin = active_bin_array.get_bin_mut(lb_pair.active_id)?;
let price = active_bin.get_or_store_bin_price(lb_pair.active_id, lb_pair.bin_step)?;
if !active_bin.is_empty(!swap_for_y) {
let SwapResult {
amount_in_with_fees,
amount_out,
fee,
..
} = active_bin.swap(amount_in, price, swap_for_y, &lb_pair, None)?;
amount_in = amount_in
.checked_sub(amount_in_with_fees)
.context("MathOverflow")?;
total_amount_out = total_amount_out
.checked_add(amount_out)
.context("MathOverflow")?;
total_fee = total_fee.checked_add(fee).context("MathOverflow")?;
}
if amount_in > 0 {
lb_pair.advance_active_bin(swap_for_y)?;
}
}
}
Ok(SwapExactInQuote {
amount_out: total_amount_out,
fee: total_fee,
})
}
pub fn get_bin_array_pubkeys_for_swap(
lb_pair_pubkey: Pubkey,
lb_pair: &LbPair,
bitmap_extension: Option<&BinArrayBitmapExtension>,
swap_for_y: bool,
take_count: u8,
) -> Result<Vec<Pubkey>> {
let mut start_bin_array_idx = BinArray::bin_id_to_bin_array_index(lb_pair.active_id)?;
let mut bin_array_idx = vec![];
let increment = if swap_for_y { -1 } else { 1 };
loop {
if bin_array_idx.len() == take_count as usize {
break;
}
if lb_pair.is_overflow_default_bin_array_bitmap(start_bin_array_idx) {
let Some(bitmap_extension) = bitmap_extension else {
break;
};
let Ok((next_bin_array_idx, has_liquidity)) = bitmap_extension
.next_bin_array_index_with_liquidity(swap_for_y, start_bin_array_idx)
else {
// Out of search range. No liquidity.
break;
};
if has_liquidity {
bin_array_idx.push(next_bin_array_idx);
start_bin_array_idx = next_bin_array_idx + increment;
} else {
// Switch to internal bitmap
start_bin_array_idx = next_bin_array_idx;
}
} else {
let Ok((next_bin_array_idx, has_liquidity)) = lb_pair
.next_bin_array_index_with_liquidity_internal(swap_for_y, start_bin_array_idx)
else {
break;
};
if has_liquidity {
bin_array_idx.push(next_bin_array_idx);
start_bin_array_idx = next_bin_array_idx + increment;
} else {
// Switch to external bitmap
start_bin_array_idx = next_bin_array_idx;
}
}
}
let bin_array_pubkeys = bin_array_idx
.into_iter()
.map(|idx| derive_bin_array_pda(lb_pair_pubkey, idx.into()).0)
.collect();
Ok(bin_array_pubkeys)
}
#[cfg(test)]
mod tests {
use super::*;
use anchor_client::anchor_lang::AccountDeserialize;
use anchor_client::solana_sdk::clock::Clock;
use anchor_client::{
solana_client::nonblocking::rpc_client::RpcClient,
solana_sdk::{pubkey::Pubkey, signature::Keypair},
Client, Cluster,
};
use std::{rc::Rc, str::FromStr};
/// Get on chain clock
async fn get_clock(rpc_client: RpcClient) -> Result<Clock> {
let clock_account = rpc_client
.get_account(&anchor_client::solana_sdk::sysvar::clock::ID)
.await?;
let clock_state: Clock = bincode::deserialize(clock_account.data.as_ref())?;
Ok(clock_state)
}
#[tokio::test]
async fn test_swap_quote_exact_out() {
// RPC client. No gPA is required.
let rpc_client = RpcClient::new(Cluster::Mainnet.url().to_string());
let client = Client::new(
Cluster::Custom(rpc_client.url(), rpc_client.url()),
Rc::new(Keypair::new()),
);
let program = client.program(lb_clmm::ID).unwrap();
let SOL_USDC = Pubkey::from_str("HTvjzsfX3yU6BUodCjZ5vZkUrAxMDTrBs3CJaq43ashR").unwrap();
let lb_pair = program.account::<LbPair>(SOL_USDC).await.unwrap();
// 3 bin arrays to left, and right is enough to cover most of the swap, and stay under 1.4m CU constraint.
// Get 3 bin arrays to the left from the active bin
let left_bin_array_pubkeys =
get_bin_array_pubkeys_for_swap(SOL_USDC, &lb_pair, None, true, 3).unwrap();
// Get 3 bin arrays to the right the from active bin
let right_bin_array_pubkeys =
get_bin_array_pubkeys_for_swap(SOL_USDC, &lb_pair, None, false, 3).unwrap();
// Fetch bin arrays
let bin_array_pubkeys = left_bin_array_pubkeys
.into_iter()
.chain(right_bin_array_pubkeys.into_iter())
.collect::<Vec<Pubkey>>();
let accounts = rpc_client
.get_multiple_accounts(&bin_array_pubkeys)
.await
.unwrap();
let bin_arrays = accounts
.into_iter()
.zip(bin_array_pubkeys.into_iter())
.map(|(account, key)| {
(
key,
BinArray::try_deserialize(&mut account.unwrap().data.as_ref()).unwrap(),
)
})
.collect::<HashMap<_, _>>();
let usdc_token_multiplier = 1_000_000.0;
let sol_token_multiplier = 1_000_000_000.0;
let out_sol_amount = 1_000_000_000;
let clock = get_clock(rpc_client).await.unwrap();
let quote_result = quote_exact_out(
SOL_USDC,
&lb_pair,
out_sol_amount,
false,
bin_arrays.clone(),
None,
clock.unix_timestamp as u64,
clock.slot,
)
.unwrap();
let in_amount = quote_result.amount_in + quote_result.fee;
println!(
"{} USDC -> exact 1 SOL",
in_amount as f64 / usdc_token_multiplier
);
let quote_result = quote_exact_in(
SOL_USDC,
&lb_pair,
in_amount,
false,
bin_arrays.clone(),
None,
clock.unix_timestamp as u64,
clock.slot,
)
.unwrap();
println!(
"{} USDC -> {} SOL",
in_amount as f64 / usdc_token_multiplier,
quote_result.amount_out as f64 / sol_token_multiplier
);
let out_usdc_amount = 200_000_000;
let quote_result = quote_exact_out(
SOL_USDC,
&lb_pair,
out_usdc_amount,
true,
bin_arrays.clone(),
None,
clock.unix_timestamp as u64,
clock.slot,
)
.unwrap();
let in_amount = quote_result.amount_in + quote_result.fee;
println!(
"{} SOL -> exact 200 USDC",
in_amount as f64 / sol_token_multiplier
);
let quote_result = quote_exact_in(
SOL_USDC,
&lb_pair,
in_amount,
true,
bin_arrays,
None,
clock.unix_timestamp as u64,
clock.slot,
)
.unwrap();
println!(
"{} SOL -> {} USDC",
in_amount as f64 / sol_token_multiplier,
quote_result.amount_out as f64 / usdc_token_multiplier
);
}
#[tokio::test]
async fn test_swap_quote_exact_in() {
// RPC client. No gPA is required.
let rpc_client = RpcClient::new(Cluster::Mainnet.url().to_string());
let client = Client::new(
Cluster::Custom(rpc_client.url(), rpc_client.url()),
Rc::new(Keypair::new()),
);
let program = client.program(lb_clmm::ID).unwrap();
let SOL_USDC = Pubkey::from_str("HTvjzsfX3yU6BUodCjZ5vZkUrAxMDTrBs3CJaq43ashR").unwrap();
let lb_pair = program.account::<LbPair>(SOL_USDC).await.unwrap();
// 3 bin arrays to left, and right is enough to cover most of the swap, and stay under 1.4m CU constraint.
// Get 3 bin arrays to the left from the active bin
let left_bin_array_pubkeys =
get_bin_array_pubkeys_for_swap(SOL_USDC, &lb_pair, None, true, 3).unwrap();
// Get 3 bin arrays to the right the from active bin
let right_bin_array_pubkeys =
get_bin_array_pubkeys_for_swap(SOL_USDC, &lb_pair, None, false, 3).unwrap();
// Fetch bin arrays
let bin_array_pubkeys = left_bin_array_pubkeys
.into_iter()
.chain(right_bin_array_pubkeys.into_iter())
.collect::<Vec<Pubkey>>();
let accounts = rpc_client
.get_multiple_accounts(&bin_array_pubkeys)
.await
.unwrap();
let bin_arrays = accounts
.into_iter()
.zip(bin_array_pubkeys.into_iter())
.map(|(account, key)| {
(
key,
BinArray::try_deserialize(&mut account.unwrap().data.as_ref()).unwrap(),
)
})
.collect::<HashMap<_, _>>();
// 1 SOL -> USDC
let in_sol_amount = 1_000_000_000;
let clock = get_clock(rpc_client).await.unwrap();
let quote_result = quote_exact_in(
SOL_USDC,
&lb_pair,
in_sol_amount,
true,
bin_arrays.clone(),
None,
clock.unix_timestamp as u64,
clock.slot,
)
.unwrap();
println!(
"1 SOL -> {:?} USDC",
quote_result.amount_out as f64 / 1_000_000.0
);
// 100 USDC -> SOL
let in_usdc_amount = 100_000_000;
let quote_result = quote_exact_in(
SOL_USDC,
&lb_pair,
in_usdc_amount,
false,
bin_arrays.clone(),
None,
clock.unix_timestamp as u64,
clock.slot,
)
.unwrap();
println!(
"100 USDC -> {:?} SOL",
quote_result.amount_out as f64 / 1_000_000_000.0
);
}
}