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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
use solana_program::program::invoke_signed_unchecked;
use {
crate::{
id::zero,
instruction::raydium::{
RaydiumAddLiquidity, RaydiumRemoveLiquidity, RaydiumStake, RaydiumSwapFixedIn,
RaydiumSwapFixedOut, RaydiumUnstake,
},
math,
pack::check_data_len,
program::account,
},
arrayref::{array_ref, array_refs},
solana_program::{
account_info::AccountInfo,
entrypoint::ProgramResult,
instruction::{AccountMeta, Instruction},
msg,
program::{invoke, invoke_signed},
program_error::ProgramError,
pubkey::Pubkey,
},
};
pub mod serum_v3 {
solana_program::declare_id!("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin");
}
pub mod raydium_v2 {
solana_program::declare_id!("RVKd61ztZW9GUwhRbbLoYVRE5Xf1B2tVscKqwZqXgEr");
}
pub mod raydium_v3 {
solana_program::declare_id!("27haf8L6oxUeXrHrgEgsexjSY5hbVUWEmvv9Nyxg8vQv");
}
pub mod raydium_v4 {
solana_program::declare_id!("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8");
}
pub mod raydium_dev_v4 {
solana_program::declare_id!("9rpQHSyFVM1dkkHFQ2TtTzPEW7DVmEyPmN8wVniqJtuC");
}
pub mod raydium_stake {
solana_program::declare_id!("EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q");
}
pub mod raydium_stake_v4 {
solana_program::declare_id!("CBuCnLe26faBpcBP2fktp4rp8abpcAnTWft6ZrP5Q4T");
}
pub mod raydium_stake_v5 {
solana_program::declare_id!("9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z");
}
pub mod raydium_stake_v5_dev {
solana_program::declare_id!("EcLzTrNg9V7qhcdyXDe2qjtPkiGzDM2UbdRaeaadU5r2");
}
pub const RAYDIUM_FEE: f64 = 0.0025;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RaydiumUserStakeInfo {
pub state: u64,
pub farm_id: Pubkey,
pub stake_owner: Pubkey,
pub deposit_balance: u64,
pub reward_debt: u64,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RaydiumUserStakeInfoV4 {
pub state: u64,
pub farm_id: Pubkey,
pub stake_owner: Pubkey,
pub deposit_balance: u64,
pub reward_debt: u64,
pub reward_debt_b: u64,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RaydiumUserStakeInfoV5 {
pub state: u64,
pub farm_id: Pubkey,
pub stake_owner: Pubkey,
pub deposit_balance: u64,
pub reward_debt: u64,
pub reward_debt_b: u64,
}
#[derive(Debug, Clone, Copy)]
pub struct OpenOrders {
pub buf1: [u8; 5],
pub account_flags: u64,
pub market: [u8; 32],
pub owner: [u8; 32],
pub native_coin_free: u64,
pub native_coin_total: u64,
pub native_pc_free: u64,
pub native_pc_total: u64,
pub free_slot_bits: u128,
pub is_bid_bits: u128,
pub orders: [u8; 2048],
pub client_order_ids: [u8; 1024],
pub referrer_rebates_accrued: u64,
pub buf2: [u8; 7],
}
impl OpenOrders {
pub const LEN: usize = 3228;
pub fn get_size(&self) -> usize {
OpenOrders::LEN
}
pub fn unpack(input: &[u8]) -> Result<Self, ProgramError> {
check_data_len(input, Self::LEN)?;
let input = array_ref![input, 0, OpenOrders::LEN];
#[allow(clippy::ptr_offset_with_cast)]
let (
buf1,
account_flags,
market,
owner,
native_coin_free,
native_coin_total,
native_pc_free,
native_pc_total,
free_slot_bits,
is_bid_bits,
orders,
client_order_ids,
referrer_rebates_accrued,
buf2,
) = array_refs![input, 5, 8, 32, 32, 8, 8, 8, 8, 16, 16, 2048, 1024, 8, 7];
Ok(Self {
buf1: *buf1,
account_flags: u64::from_le_bytes(*account_flags),
market: *market,
owner: *owner,
native_coin_free: u64::from_le_bytes(*native_coin_free),
native_coin_total: u64::from_le_bytes(*native_coin_total),
native_pc_free: u64::from_le_bytes(*native_pc_free),
native_pc_total: u64::from_le_bytes(*native_pc_total),
free_slot_bits: u128::from_le_bytes(*free_slot_bits),
is_bid_bits: u128::from_le_bytes(*is_bid_bits),
orders: *orders,
client_order_ids: *client_order_ids,
referrer_rebates_accrued: u64::from_le_bytes(*referrer_rebates_accrued),
buf2: *buf2,
})
}
}
impl RaydiumUserStakeInfo {
pub const LEN: usize = 88;
pub fn get_size(&self) -> usize {
RaydiumUserStakeInfo::LEN
}
pub fn unpack(input: &[u8]) -> Result<Self, ProgramError> {
check_data_len(input, RaydiumUserStakeInfo::LEN)?;
let input = array_ref![input, 0, RaydiumUserStakeInfo::LEN];
#[allow(clippy::ptr_offset_with_cast)]
let (state, farm_id, stake_owner, deposit_balance, reward_debt) =
array_refs![input, 8, 32, 32, 8, 8];
Ok(Self {
state: u64::from_le_bytes(*state),
farm_id: Pubkey::new_from_array(*farm_id),
stake_owner: Pubkey::new_from_array(*stake_owner),
deposit_balance: u64::from_le_bytes(*deposit_balance),
reward_debt: u64::from_le_bytes(*reward_debt),
})
}
}
impl RaydiumUserStakeInfoV4 {
pub const LEN: usize = 96;
pub fn get_size(&self) -> usize {
RaydiumUserStakeInfoV4::LEN
}
pub fn unpack(input: &[u8]) -> Result<Self, ProgramError> {
check_data_len(input, RaydiumUserStakeInfoV4::LEN)?;
let input = array_ref![input, 0, RaydiumUserStakeInfoV4::LEN];
#[allow(clippy::ptr_offset_with_cast)]
let (state, farm_id, stake_owner, deposit_balance, reward_debt, reward_debt_b) =
array_refs![input, 8, 32, 32, 8, 8, 8];
Ok(Self {
state: u64::from_le_bytes(*state),
farm_id: Pubkey::new_from_array(*farm_id),
stake_owner: Pubkey::new_from_array(*stake_owner),
deposit_balance: u64::from_le_bytes(*deposit_balance),
reward_debt: u64::from_le_bytes(*reward_debt),
reward_debt_b: u64::from_le_bytes(*reward_debt_b),
})
}
}
impl RaydiumUserStakeInfoV5 {
pub const LEN: usize = 96;
pub fn get_size(&self) -> usize {
RaydiumUserStakeInfoV5::LEN
}
pub fn unpack(input: &[u8]) -> Result<Self, ProgramError> {
check_data_len(input, RaydiumUserStakeInfoV5::LEN)?;
let input = array_ref![input, 0, RaydiumUserStakeInfoV5::LEN];
#[allow(clippy::ptr_offset_with_cast)]
let (state, farm_id, stake_owner, deposit_balance, reward_debt, reward_debt_b) =
array_refs![input, 8, 32, 32, 8, 8, 8];
Ok(Self {
state: u64::from_le_bytes(*state),
farm_id: Pubkey::new_from_array(*farm_id),
stake_owner: Pubkey::new_from_array(*stake_owner),
deposit_balance: u64::from_le_bytes(*deposit_balance),
reward_debt: u64::from_le_bytes(*reward_debt),
reward_debt_b: u64::from_le_bytes(*reward_debt_b),
})
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AmmInfoV4 {
pub status: u64,
pub nonce: u64,
pub order_num: u64,
pub depth: u64,
pub coin_decimals: u64,
pub pc_decimals: u64,
pub state: u64,
pub reset_flag: u64,
pub min_size: u64,
pub vol_max_cut_ratio: u64,
pub amount_wave: u64,
pub coin_lot_size: u64,
pub pc_lot_size: u64,
pub min_price_multiplier: u64,
pub max_price_multiplier: u64,
pub sys_decimal_value: u64,
pub min_separate_numerator: u64,
pub min_separate_denominator: u64,
pub trade_fee_numerator: u64,
pub trade_fee_denominator: u64,
pub pnl_numerator: u64,
pub pnl_denominator: u64,
pub swap_fee_numerator: u64,
pub swap_fee_denominator: u64,
pub need_take_pnl_coin: u64,
pub need_take_pnl_pc: u64,
pub total_pnl_pc: u64,
pub total_pnl_coin: u64,
pub pool_total_deposit_pc: u128,
pub pool_total_deposit_coin: u128,
pub swap_coin_in_amount: u128,
pub swap_pc_out_amount: u128,
pub swap_coin_to_pc_fee: u64,
pub swap_pc_in_amount: u128,
pub swap_coin_out_amount: u128,
pub swap_pc_to_coin_fee: u64,
pub token_coin: Pubkey,
pub token_pc: Pubkey,
pub coin_mint: Pubkey,
pub pc_mint: Pubkey,
pub lp_mint: Pubkey,
pub open_orders: Pubkey,
pub market: Pubkey,
pub serum_dex: Pubkey,
pub target_orders: Pubkey,
pub withdraw_queue: Pubkey,
pub token_temp_lp: Pubkey,
pub amm_owner: Pubkey,
pub pnl_owner: Pubkey,
}
impl AmmInfoV4 {
pub const LEN: usize = 752;
pub fn get_size(&self) -> usize {
AmmInfoV4::LEN
}
pub fn unpack(input: &[u8]) -> Result<Self, ProgramError> {
check_data_len(input, AmmInfoV4::LEN)?;
let input = array_ref![input, 0, AmmInfoV4::LEN];
#[allow(clippy::ptr_offset_with_cast)]
let (
status,
nonce,
order_num,
depth,
coin_decimals,
pc_decimals,
state,
reset_flag,
min_size,
vol_max_cut_ratio,
amount_wave,
coin_lot_size,
pc_lot_size,
min_price_multiplier,
max_price_multiplier,
sys_decimal_value,
min_separate_numerator,
min_separate_denominator,
trade_fee_numerator,
trade_fee_denominator,
pnl_numerator,
pnl_denominator,
swap_fee_numerator,
swap_fee_denominator,
need_take_pnl_coin,
need_take_pnl_pc,
total_pnl_pc,
total_pnl_coin,
pool_total_deposit_pc,
pool_total_deposit_coin,
swap_coin_in_amount,
swap_pc_out_amount,
swap_coin_to_pc_fee,
swap_pc_in_amount,
swap_coin_out_amount,
swap_pc_to_coin_fee,
token_coin,
token_pc,
coin_mint,
pc_mint,
lp_mint,
open_orders,
market,
serum_dex,
target_orders,
withdraw_queue,
token_temp_lp,
amm_owner,
pnl_owner,
) = array_refs![
input, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 16, 16, 16, 16, 8, 16, 16, 8, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32
];
Ok(Self {
status: u64::from_le_bytes(*status),
nonce: u64::from_le_bytes(*nonce),
order_num: u64::from_le_bytes(*order_num),
depth: u64::from_le_bytes(*depth),
coin_decimals: u64::from_le_bytes(*coin_decimals),
pc_decimals: u64::from_le_bytes(*pc_decimals),
state: u64::from_le_bytes(*state),
reset_flag: u64::from_le_bytes(*reset_flag),
min_size: u64::from_le_bytes(*min_size),
vol_max_cut_ratio: u64::from_le_bytes(*vol_max_cut_ratio),
amount_wave: u64::from_le_bytes(*amount_wave),
coin_lot_size: u64::from_le_bytes(*coin_lot_size),
pc_lot_size: u64::from_le_bytes(*pc_lot_size),
min_price_multiplier: u64::from_le_bytes(*min_price_multiplier),
max_price_multiplier: u64::from_le_bytes(*max_price_multiplier),
sys_decimal_value: u64::from_le_bytes(*sys_decimal_value),
min_separate_numerator: u64::from_le_bytes(*min_separate_numerator),
min_separate_denominator: u64::from_le_bytes(*min_separate_denominator),
trade_fee_numerator: u64::from_le_bytes(*trade_fee_numerator),
trade_fee_denominator: u64::from_le_bytes(*trade_fee_denominator),
pnl_numerator: u64::from_le_bytes(*pnl_numerator),
pnl_denominator: u64::from_le_bytes(*pnl_denominator),
swap_fee_numerator: u64::from_le_bytes(*swap_fee_numerator),
swap_fee_denominator: u64::from_le_bytes(*swap_fee_denominator),
need_take_pnl_coin: u64::from_le_bytes(*need_take_pnl_coin),
need_take_pnl_pc: u64::from_le_bytes(*need_take_pnl_pc),
total_pnl_pc: u64::from_le_bytes(*total_pnl_pc),
total_pnl_coin: u64::from_le_bytes(*total_pnl_coin),
pool_total_deposit_pc: u128::from_le_bytes(*pool_total_deposit_pc),
pool_total_deposit_coin: u128::from_le_bytes(*pool_total_deposit_coin),
swap_coin_in_amount: u128::from_le_bytes(*swap_coin_in_amount),
swap_pc_out_amount: u128::from_le_bytes(*swap_pc_out_amount),
swap_coin_to_pc_fee: u64::from_le_bytes(*swap_coin_to_pc_fee),
swap_pc_in_amount: u128::from_le_bytes(*swap_pc_in_amount),
swap_coin_out_amount: u128::from_le_bytes(*swap_coin_out_amount),
swap_pc_to_coin_fee: u64::from_le_bytes(*swap_pc_to_coin_fee),
token_coin: Pubkey::new_from_array(*token_coin),
token_pc: Pubkey::new_from_array(*token_pc),
coin_mint: Pubkey::new_from_array(*coin_mint),
pc_mint: Pubkey::new_from_array(*pc_mint),
lp_mint: Pubkey::new_from_array(*lp_mint),
open_orders: Pubkey::new_from_array(*open_orders),
market: Pubkey::new_from_array(*market),
serum_dex: Pubkey::new_from_array(*serum_dex),
target_orders: Pubkey::new_from_array(*target_orders),
withdraw_queue: Pubkey::new_from_array(*withdraw_queue),
token_temp_lp: Pubkey::new_from_array(*token_temp_lp),
amm_owner: Pubkey::new_from_array(*amm_owner),
pnl_owner: Pubkey::new_from_array(*pnl_owner),
})
}
}
pub fn check_pool_program_id(program_id: &Pubkey) -> bool {
program_id == &raydium_v2::id()
|| program_id == &raydium_v3::id()
|| program_id == &raydium_v4::id()
|| program_id == &raydium_dev_v4::id()
}
pub fn check_stake_program_id(program_id: &Pubkey) -> bool {
program_id == &raydium_stake::id()
|| program_id == &raydium_stake_v4::id()
|| program_id == &raydium_stake_v5::id()
|| program_id == &raydium_stake_v5_dev::id()
}
pub fn get_lp_token_amount(
stake_info_account: &AccountInfo,
vault_lp_token_amount: u64,
vault_lp_token_mint: &AccountInfo,
) -> Result<u64, ProgramError> {
let vt_supply_amount = account::get_token_supply(vault_lp_token_mint)?;
let stake_balance = get_stake_account_balance(stake_info_account)?;
if vt_supply_amount == 0 {
return Ok(0);
}
let lp_token_amount = account::to_token_amount(
stake_balance as f64 * (vault_lp_token_amount as f64 / vt_supply_amount as f64),
0,
)?;
Ok(lp_token_amount)
}
pub fn get_stake_account_balance(stake_account: &AccountInfo) -> Result<u64, ProgramError> {
let data = stake_account.try_borrow_data()?;
if data.len() == RaydiumUserStakeInfoV4::LEN || data.len() == 248 {
Ok(RaydiumUserStakeInfoV4::unpack(&data)?.deposit_balance)
} else if data.len() == RaydiumUserStakeInfo::LEN {
Ok(RaydiumUserStakeInfo::unpack(&data)?.deposit_balance)
} else {
Err(ProgramError::InvalidAccountData)
}
}
pub fn get_pool_token_balances<'a, 'b>(
pool_coin_token_account: &'a AccountInfo<'b>,
pool_pc_token_account: &'a AccountInfo<'b>,
amm_open_orders: &'a AccountInfo<'b>,
amm_id: &'a AccountInfo<'b>,
) -> Result<(u64, u64), ProgramError> {
let mut token_a_balance = account::get_token_balance(pool_coin_token_account)?;
let mut token_b_balance = account::get_token_balance(pool_pc_token_account)?;
msg!(
"Token a reserve balance: {}, Token b reserve balance: {}",
token_a_balance,
token_b_balance
);
if amm_open_orders.data_len() == 3228 {
let open_orders_data = amm_open_orders.try_borrow_data()?;
let base_token_total = array_ref![open_orders_data, 85, 8];
let quote_token_total = array_ref![open_orders_data, 101, 8];
msg!(
"base token total: {} quote_token_total: {}",
u64::from_le_bytes(*base_token_total),
u64::from_le_bytes(*quote_token_total)
);
token_a_balance += u64::from_le_bytes(*base_token_total);
token_b_balance += u64::from_le_bytes(*quote_token_total);
}
msg!(
"After adjusting for open orders...Token a reserve balance: {}, Token b reserve balance: {}",
token_a_balance,
token_b_balance
);
let (pnl_coin_offset, pnl_pc_offset) = if amm_id.data_len() == 624 {
(136, 144)
} else if amm_id.data_len() == 680 {
(144, 152)
} else if amm_id.data_len() == 752 {
(192, 200)
} else {
(0, 0)
};
if pnl_coin_offset > 0 {
let amm_id_data = amm_id.try_borrow_data()?;
let need_take_pnl_coin = u64::from_le_bytes(*array_ref![amm_id_data, pnl_coin_offset, 8]);
let need_take_pnl_pc = u64::from_le_bytes(*array_ref![amm_id_data, pnl_pc_offset, 8]);
token_a_balance -= if need_take_pnl_coin < token_a_balance {
need_take_pnl_coin
} else {
token_a_balance
};
token_b_balance -= if need_take_pnl_pc < token_b_balance {
need_take_pnl_pc
} else {
token_b_balance
};
}
msg!(
"After adjusting for amm take pnl...Token a reserve balance: {}, Token b reserve balance: {}",
token_a_balance,
token_b_balance
);
Ok((token_a_balance, token_b_balance))
}
pub fn get_pool_deposit_amounts<'a, 'b>(
pool_coin_token_account: &'a AccountInfo<'b>,
pool_pc_token_account: &'a AccountInfo<'b>,
amm_open_orders: &'a AccountInfo<'b>,
amm_id: &'a AccountInfo<'b>,
max_coin_token_amount: u64,
max_pc_token_amount: u64,
) -> Result<(u64, u64), ProgramError> {
if max_coin_token_amount > 0 && max_pc_token_amount > 0 {
return Ok((max_coin_token_amount, max_pc_token_amount));
}
if max_coin_token_amount == 0 && max_pc_token_amount == 0 {
msg!("Error: At least one of token amounts must be non-zero");
return Err(ProgramError::InvalidArgument);
}
let mut coin_token_amount = max_coin_token_amount;
let mut pc_token_amount = max_pc_token_amount;
let (coin_balance, pc_balance) = get_pool_token_balances(
pool_coin_token_account,
pool_pc_token_account,
amm_open_orders,
amm_id,
)?;
if coin_balance == 0 || pc_balance == 0 {
msg!("Error: Both amounts must be specified for the initial deposit to an empty pool");
return Err(ProgramError::InvalidArgument);
}
if max_coin_token_amount == 0 {
let estimated_coin_amount = math::checked_as_u64(
coin_balance as f64 * max_pc_token_amount as f64 / (pc_balance as f64),
)?;
coin_token_amount = if estimated_coin_amount > 1 {
estimated_coin_amount - 1
} else {
0
};
} else {
pc_token_amount = math::checked_as_u64(
pc_balance as f64 * max_coin_token_amount as f64 / (coin_balance as f64),
)?;
}
Ok((coin_token_amount, math::checked_add(pc_token_amount, 1)?))
}
pub fn get_pool_withdrawal_amounts<'a, 'b>(
pool_coin_token_account: &'a AccountInfo<'b>,
pool_pc_token_account: &'a AccountInfo<'b>,
amm_open_orders: &'a AccountInfo<'b>,
amm_id: &'a AccountInfo<'b>,
lp_token_mint: &'a AccountInfo<'b>,
lp_token_amount: u64,
) -> Result<(u64, u64), ProgramError> {
if lp_token_amount == 0 {
msg!("Error: LP token amount must be non-zero");
return Err(ProgramError::InvalidArgument);
}
let (coin_balance, pc_balance) = get_pool_token_balances(
pool_coin_token_account,
pool_pc_token_account,
amm_open_orders,
amm_id,
)?;
if coin_balance == 0 && pc_balance == 0 {
return Ok((0, 0));
}
let lp_token_supply = account::get_token_supply(lp_token_mint)?;
if lp_token_supply == 0 {
return Ok((0, 0));
}
let stake = lp_token_amount as f64 / lp_token_supply as f64;
Ok((
math::checked_as_u64(coin_balance as f64 * stake)?,
math::checked_as_u64(pc_balance as f64 * stake)?,
))
}
pub fn get_pool_swap_amounts<'a, 'b>(
pool_coin_token_account: &'a AccountInfo<'b>,
pool_pc_token_account: &'a AccountInfo<'b>,
amm_open_orders: &'a AccountInfo<'b>,
amm_id: &'a AccountInfo<'b>,
coin_token_amount_in: u64,
pc_token_amount_in: u64,
) -> Result<(u64, u64), ProgramError> {
if (coin_token_amount_in == 0 && pc_token_amount_in == 0)
|| (coin_token_amount_in > 0 && pc_token_amount_in > 0)
{
msg!("Error: One and only one of token amounts must be non-zero");
return Err(ProgramError::InvalidArgument);
}
let (coin_balance, pc_balance) = get_pool_token_balances(
pool_coin_token_account,
pool_pc_token_account,
amm_open_orders,
amm_id,
)?;
if coin_balance == 0 || pc_balance == 0 {
msg!("Error: Can't swap in an empty pool");
return Err(ProgramError::Custom(412));
}
if coin_token_amount_in == 0 {
let amount_in_no_fee = (pc_token_amount_in as f64 * (1.0 - RAYDIUM_FEE)) as u64;
let estimated_coin_amount = math::checked_as_u64(
coin_balance as f64 * amount_in_no_fee as f64
/ (pc_balance as f64 + amount_in_no_fee as f64),
)?;
Ok((
pc_token_amount_in,
if estimated_coin_amount > 1 {
estimated_coin_amount - 1
} else {
0
},
))
} else {
let amount_in_no_fee = (coin_token_amount_in as f64 * (1.0 - RAYDIUM_FEE)) as u64;
let estimated_pc_amount = math::checked_as_u64(
pc_balance as f64 * amount_in_no_fee as f64
/ (coin_balance as f64 + amount_in_no_fee as f64),
)?;
Ok((
coin_token_amount_in,
if estimated_pc_amount > 1 {
estimated_pc_amount - 1
} else {
0
},
))
}
}
pub fn estimate_lp_tokens_amount(
lp_token_mint: &AccountInfo,
token_a_deposit: u64,
token_b_deposit: u64,
pool_coin_balance: u64,
pool_pc_balance: u64,
) -> Result<u64, ProgramError> {
if pool_coin_balance != 0 && pool_pc_balance != 0 {
Ok(std::cmp::min(
math::checked_as_u64(
(token_a_deposit as f64 / pool_coin_balance as f64)
* account::get_token_supply(lp_token_mint)? as f64,
)?,
math::checked_as_u64(
(token_b_deposit as f64 / pool_pc_balance as f64)
* account::get_token_supply(lp_token_mint)? as f64,
)?,
))
} else if pool_coin_balance != 0 {
math::checked_as_u64(
(token_a_deposit as f64 / pool_coin_balance as f64)
* account::get_token_supply(lp_token_mint)? as f64,
)
} else if pool_pc_balance != 0 {
math::checked_as_u64(
(token_b_deposit as f64 / pool_pc_balance as f64)
* account::get_token_supply(lp_token_mint)? as f64,
)
} else {
Ok(0)
}
}
pub fn add_liquidity(
accounts: &[AccountInfo],
max_coin_token_amount: u64,
max_pc_token_amount: u64,
) -> ProgramResult {
if let [user_account, user_token_a_account, user_token_b_account, user_lp_token_account, pool_program_id, pool_coin_token_account, pool_pc_token_account, lp_token_mint, spl_token_id, amm_id, amm_authority, amm_open_orders, amm_target, serum_market] =
accounts
{
msg!("checking pool program id...");
if !check_pool_program_id(pool_program_id.key) {
msg!(
"Need one of the following program ids {} {} {}",
raydium_v2::id(),
&raydium_v3::id(),
&raydium_v4::id()
);
return Err(ProgramError::IncorrectProgramId);
}
let raydium_accounts = vec![
AccountMeta::new_readonly(*spl_token_id.key, false),
AccountMeta::new(*amm_id.key, false),
AccountMeta::new_readonly(*amm_authority.key, false),
AccountMeta::new_readonly(*amm_open_orders.key, false),
AccountMeta::new(*amm_target.key, false),
AccountMeta::new(*lp_token_mint.key, false),
AccountMeta::new(*pool_coin_token_account.key, false),
AccountMeta::new(*pool_pc_token_account.key, false),
AccountMeta::new_readonly(*serum_market.key, false),
AccountMeta::new(*user_token_a_account.key, false),
AccountMeta::new(*user_token_b_account.key, false),
AccountMeta::new(*user_lp_token_account.key, false),
AccountMeta::new_readonly(*user_account.key, true),
];
let instruction = Instruction {
program_id: *pool_program_id.key,
accounts: raydium_accounts,
data: RaydiumAddLiquidity {
instruction: 3,
max_coin_token_amount,
max_pc_token_amount,
base_side: 0,
}
.to_vec()?,
};
invoke(&instruction, accounts)
} else {
Err(ProgramError::NotEnoughAccountKeys)
}
}
pub fn add_liquidity_with_seeds(
accounts: &[AccountInfo],
seeds: &[&[&[u8]]],
max_coin_token_amount: u64,
max_pc_token_amount: u64,
) -> ProgramResult {
if let [authority_account, token_a_custody_account, token_b_custody_account, lp_token_custody_account, pool_program_id, pool_coin_token_account, pool_pc_token_account, lp_token_mint, spl_token_id, amm_id, amm_authority, amm_open_orders, amm_target, serum_market] =
accounts
{
if !check_pool_program_id(pool_program_id.key) {
return Err(ProgramError::IncorrectProgramId);
}
let raydium_accounts = vec![
AccountMeta::new_readonly(*spl_token_id.key, false),
AccountMeta::new(*amm_id.key, false),
AccountMeta::new_readonly(*amm_authority.key, false),
AccountMeta::new_readonly(*amm_open_orders.key, false),
AccountMeta::new(*amm_target.key, false),
AccountMeta::new(*lp_token_mint.key, false),
AccountMeta::new(*pool_coin_token_account.key, false),
AccountMeta::new(*pool_pc_token_account.key, false),
AccountMeta::new_readonly(*serum_market.key, false),
AccountMeta::new(*token_a_custody_account.key, false),
AccountMeta::new(*token_b_custody_account.key, false),
AccountMeta::new(*lp_token_custody_account.key, false),
AccountMeta::new_readonly(*authority_account.key, true),
];
let instruction = Instruction {
program_id: *pool_program_id.key,
accounts: raydium_accounts,
data: RaydiumAddLiquidity {
instruction: 3,
max_coin_token_amount,
max_pc_token_amount,
base_side: 0,
}
.to_vec()?,
};
invoke_signed(&instruction, accounts, seeds)
} else {
Err(ProgramError::NotEnoughAccountKeys)
}
}
pub fn remove_liquidity_with_seeds(
accounts: &[AccountInfo],
seeds: &[&[&[u8]]],
amount: u64,
) -> ProgramResult {
if let [authority_account, token_a_custody_account, token_b_custody_account, lp_token_custody_account, pool_program_id, pool_withdraw_queue, pool_temp_lp_token_account, pool_coin_token_account, pool_pc_token_account, lp_token_mint, spl_token_id, amm_id, amm_authority, amm_open_orders, amm_target, serum_market, serum_program_id, serum_coin_vault_account, serum_pc_vault_account, serum_vault_signer, serum_event_queue, serum_bids, serum_asks, _system_program] =
accounts
{
if !check_pool_program_id(pool_program_id.key) {
return Err(ProgramError::IncorrectProgramId);
}
let raydium_accounts = vec![
AccountMeta::new_readonly(*spl_token_id.key, false),
AccountMeta::new(*amm_id.key, false),
AccountMeta::new_readonly(*amm_authority.key, false),
AccountMeta::new(*amm_open_orders.key, false),
AccountMeta::new(*amm_target.key, false),
AccountMeta::new(*lp_token_mint.key, false),
AccountMeta::new(*pool_coin_token_account.key, false),
AccountMeta::new(*pool_pc_token_account.key, false),
AccountMeta::new(*pool_withdraw_queue.key, false),
AccountMeta::new(*pool_temp_lp_token_account.key, false),
AccountMeta::new_readonly(*serum_program_id.key, false),
AccountMeta::new(*serum_market.key, false),
AccountMeta::new(*serum_coin_vault_account.key, false),
AccountMeta::new(*serum_pc_vault_account.key, false),
AccountMeta::new_readonly(*serum_vault_signer.key, false),
AccountMeta::new(*lp_token_custody_account.key, false),
AccountMeta::new(*token_a_custody_account.key, false),
AccountMeta::new(*token_b_custody_account.key, false),
AccountMeta::new_readonly(*authority_account.key, true),
AccountMeta::new(*serum_event_queue.key, false),
AccountMeta::new(*serum_bids.key, false),
AccountMeta::new(*serum_asks.key, false),
AccountMeta::new_readonly(Pubkey::default(), false),
];
let instruction = Instruction {
program_id: *pool_program_id.key,
accounts: raydium_accounts,
data: RaydiumRemoveLiquidity {
instruction: 4,
amount: if amount > 0 {
amount
} else {
account::get_token_balance(lp_token_custody_account)?
},
}
.to_vec()?,
};
invoke_signed(&instruction, accounts, seeds)
} else {
Err(ProgramError::NotEnoughAccountKeys)
}
}
pub fn stake_with_seeds(
accounts: &[AccountInfo],
seeds: &[&[&[u8]]],
amount: u64,
) -> ProgramResult {
if let [authority_account, stake_info_account, lp_token_custody_account, token_a_custody_account, token_b_custody_account, pool_program_id, farm_lp_token_account, farm_reward_token_a_account, farm_reward_token_b_account, clock_id, spl_token_id, farm_id, farm_authority] =
accounts
{
if !check_stake_program_id(pool_program_id.key) {
return Err(ProgramError::IncorrectProgramId);
}
let mut raydium_accounts = vec![
AccountMeta::new(*farm_id.key, false),
AccountMeta::new_readonly(*farm_authority.key, false),
AccountMeta::new(*stake_info_account.key, false),
AccountMeta::new_readonly(*authority_account.key, true),
AccountMeta::new(*lp_token_custody_account.key, false),
AccountMeta::new(*farm_lp_token_account.key, false),
AccountMeta::new(*token_a_custody_account.key, false),
AccountMeta::new(*farm_reward_token_a_account.key, false),
AccountMeta::new_readonly(*clock_id.key, false),
AccountMeta::new_readonly(*spl_token_id.key, false),
];
if *farm_reward_token_b_account.key != zero::id() {
msg!("Farm Reward Token B Account was not zero.");
raydium_accounts.push(AccountMeta::new(*token_b_custody_account.key, false));
raydium_accounts.push(AccountMeta::new(*farm_reward_token_b_account.key, false));
}
msg!("Creating Raydium Stake Instruction for amount: {}", amount);
let instruction = Instruction {
program_id: *pool_program_id.key,
accounts: raydium_accounts,
data: RaydiumStake {
instruction: 1,
amount,
}
.to_vec()?,
};
msg!("Sending Raydium Stake Instruction");
invoke_signed(&instruction, accounts, seeds)
} else {
Err(ProgramError::NotEnoughAccountKeys)
}
}
pub fn swap_with_seeds_fixed_out(
accounts: &[AccountInfo],
seeds: &[&[&[u8]]],
max_amount_in: u64,
amount_out: u64,
) -> ProgramResult {
if let [authority_account, token_a_custody_account, token_b_custody_account, pool_program_id, pool_coin_token_account, pool_pc_token_account, spl_token_id, amm_id, amm_authority, amm_open_orders, amm_target, serum_market, serum_program_id, serum_bids, serum_asks, serum_event_queue, serum_coin_vault_account, serum_pc_vault_account, serum_vault_signer] =
accounts
{
if !check_pool_program_id(pool_program_id.key) {
return Err(ProgramError::IncorrectProgramId);
}
let raydium_accounts = vec![
AccountMeta::new_readonly(*spl_token_id.key, false),
AccountMeta::new(*amm_id.key, false),
AccountMeta::new_readonly(*amm_authority.key, false),
AccountMeta::new(*amm_open_orders.key, false),
AccountMeta::new(*amm_target.key, false),
AccountMeta::new(*pool_coin_token_account.key, false),
AccountMeta::new(*pool_pc_token_account.key, false),
AccountMeta::new_readonly(*serum_program_id.key, false),
AccountMeta::new(*serum_market.key, false),
AccountMeta::new(*serum_bids.key, false),
AccountMeta::new(*serum_asks.key, false),
AccountMeta::new(*serum_event_queue.key, false),
AccountMeta::new(*serum_coin_vault_account.key, false),
AccountMeta::new(*serum_pc_vault_account.key, false),
AccountMeta::new_readonly(*serum_vault_signer.key, false),
AccountMeta::new(*token_a_custody_account.key, false),
AccountMeta::new(*token_b_custody_account.key, false),
AccountMeta::new_readonly(*authority_account.key, true),
];
let instruction = Instruction {
program_id: *pool_program_id.key,
accounts: raydium_accounts,
data: RaydiumSwapFixedOut {
instruction: 11,
max_amount_in,
amount_out,
}
.to_vec()?,
};
invoke_signed(&instruction, accounts, seeds)
} else {
Err(ProgramError::NotEnoughAccountKeys)
}
}
pub fn swap_with_seeds_fixed_in(
accounts: &[AccountInfo],
seeds: &[&[&[u8]]],
amount_in: u64,
min_amount_out: u64,
) -> ProgramResult {
if let [authority_account, token_a_custody_account, token_b_custody_account, pool_program_id, pool_coin_token_account, pool_pc_token_account, spl_token_id, amm_id, amm_authority, amm_open_orders, amm_target, serum_market, serum_program_id, serum_bids, serum_asks, serum_event_queue, serum_coin_vault_account, serum_pc_vault_account, serum_vault_signer] =
accounts
{
if !check_pool_program_id(pool_program_id.key) {
return Err(ProgramError::IncorrectProgramId);
}
let raydium_accounts = vec![
AccountMeta::new_readonly(*spl_token_id.key, false),
AccountMeta::new(*amm_id.key, false),
AccountMeta::new_readonly(*amm_authority.key, false),
AccountMeta::new(*amm_open_orders.key, false),
AccountMeta::new(*amm_target.key, false),
AccountMeta::new(*pool_coin_token_account.key, false),
AccountMeta::new(*pool_pc_token_account.key, false),
AccountMeta::new_readonly(*serum_program_id.key, false),
AccountMeta::new(*serum_market.key, false),
AccountMeta::new(*serum_bids.key, false),
AccountMeta::new(*serum_asks.key, false),
AccountMeta::new(*serum_event_queue.key, false),
AccountMeta::new(*serum_coin_vault_account.key, false),
AccountMeta::new(*serum_pc_vault_account.key, false),
AccountMeta::new_readonly(*serum_vault_signer.key, false),
AccountMeta::new(*token_a_custody_account.key, false),
AccountMeta::new(*token_b_custody_account.key, false),
AccountMeta::new_readonly(*authority_account.key, true),
];
let instruction = Instruction {
program_id: *pool_program_id.key,
accounts: raydium_accounts,
data: RaydiumSwapFixedIn {
instruction: 9,
amount_in,
min_amount_out,
}
.to_vec()?,
};
invoke_signed(&instruction, accounts, seeds)
} else {
Err(ProgramError::NotEnoughAccountKeys)
}
}
pub fn unstake_with_seeds(
accounts: &[AccountInfo],
seeds: &[&[&[u8]]],
amount: u64,
) -> ProgramResult {
if let [authority_account, stake_info_account, lp_token_custody_account, token_a_custody_account, token_b_custody_account, pool_program_id, farm_lp_token_account, farm_reward_token_a_account, farm_reward_token_b_account, clock_id, spl_token_id, farm_id, farm_authority] =
accounts
{
if !check_stake_program_id(pool_program_id.key) {
return Err(ProgramError::IncorrectProgramId);
}
let mut raydium_accounts = vec![
AccountMeta::new(*farm_id.key, false),
AccountMeta::new_readonly(*farm_authority.key, false),
AccountMeta::new(*stake_info_account.key, false),
AccountMeta::new_readonly(*authority_account.key, true),
AccountMeta::new(*lp_token_custody_account.key, false),
AccountMeta::new(*farm_lp_token_account.key, false),
AccountMeta::new(*token_a_custody_account.key, false),
AccountMeta::new(*farm_reward_token_a_account.key, false),
AccountMeta::new_readonly(*clock_id.key, false),
AccountMeta::new_readonly(*spl_token_id.key, false),
];
if *farm_reward_token_b_account.key != zero::id() {
raydium_accounts.push(AccountMeta::new(*token_b_custody_account.key, false));
raydium_accounts.push(AccountMeta::new(*farm_reward_token_b_account.key, false));
}
let instruction = Instruction {
program_id: *pool_program_id.key,
accounts: raydium_accounts,
data: RaydiumUnstake {
instruction: 2,
amount,
}
.to_vec()?,
};
invoke_signed(&instruction, accounts, seeds)
} else {
Err(ProgramError::NotEnoughAccountKeys)
}
}