-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathpool.rs
1883 lines (1684 loc) · 74.4 KB
/
pool.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
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
use crate::error::ErrorCode;
use crate::libraries::{
big_num::{U1024, U128, U256},
check_current_tick_array_is_initialized, fixed_point_64,
full_math::MulDiv,
tick_array_bit_map, tick_math,
};
use crate::states::*;
use crate::util::get_recent_epoch;
use anchor_lang::prelude::*;
use anchor_spl::token_interface::Mint;
#[cfg(feature = "enable-log")]
use std::convert::identity;
use std::ops::{BitAnd, BitOr, BitXor};
/// Seed to derive account address and signature
pub const POOL_SEED: &str = "pool";
pub const POOL_VAULT_SEED: &str = "pool_vault";
pub const POOL_REWARD_VAULT_SEED: &str = "pool_reward_vault";
pub const POOL_TICK_ARRAY_BITMAP_SEED: &str = "pool_tick_array_bitmap_extension";
// Number of rewards Token
pub const REWARD_NUM: usize = 3;
#[cfg(feature = "paramset")]
pub mod reward_period_limit {
pub const MIN_REWARD_PERIOD: u64 = 1 * 60 * 60;
pub const MAX_REWARD_PERIOD: u64 = 2 * 60 * 60;
pub const INCREASE_EMISSIONES_PERIOD: u64 = 30 * 60;
}
#[cfg(not(feature = "paramset"))]
pub mod reward_period_limit {
pub const MIN_REWARD_PERIOD: u64 = 7 * 24 * 60 * 60;
pub const MAX_REWARD_PERIOD: u64 = 90 * 24 * 60 * 60;
pub const INCREASE_EMISSIONES_PERIOD: u64 = 72 * 60 * 60;
}
pub enum PoolStatusBitIndex {
OpenPositionOrIncreaseLiquidity,
DecreaseLiquidity,
CollectFee,
CollectReward,
Swap,
}
#[derive(PartialEq, Eq)]
pub enum PoolStatusBitFlag {
Enable,
Disable,
}
/// The pool state
///
/// PDA of `[POOL_SEED, config, token_mint_0, token_mint_1]`
///
#[account(zero_copy(unsafe))]
#[repr(C, packed)]
#[derive(Default, Debug)]
pub struct PoolState {
/// Bump to identify PDA
pub bump: [u8; 1],
// Which config the pool belongs
pub amm_config: Pubkey,
// Pool creator
pub owner: Pubkey,
/// Token pair of the pool, where token_mint_0 address < token_mint_1 address
pub token_mint_0: Pubkey,
pub token_mint_1: Pubkey,
/// Token pair vault
pub token_vault_0: Pubkey,
pub token_vault_1: Pubkey,
/// observation account key
pub observation_key: Pubkey,
/// mint0 and mint1 decimals
pub mint_decimals_0: u8,
pub mint_decimals_1: u8,
/// The minimum number of ticks between initialized ticks
pub tick_spacing: u16,
/// The currently in range liquidity available to the pool.
pub liquidity: u128,
/// The current price of the pool as a sqrt(token_1/token_0) Q64.64 value
pub sqrt_price_x64: u128,
/// The current tick of the pool, i.e. according to the last tick transition that was run.
pub tick_current: i32,
pub padding3: u16,
pub padding4: u16,
/// The fee growth as a Q64.64 number, i.e. fees of token_0 and token_1 collected per
/// unit of liquidity for the entire life of the pool.
pub fee_growth_global_0_x64: u128,
pub fee_growth_global_1_x64: u128,
/// The amounts of token_0 and token_1 that are owed to the protocol.
pub protocol_fees_token_0: u64,
pub protocol_fees_token_1: u64,
/// The amounts in and out of swap token_0 and token_1
pub swap_in_amount_token_0: u128,
pub swap_out_amount_token_1: u128,
pub swap_in_amount_token_1: u128,
pub swap_out_amount_token_0: u128,
/// Bitwise representation of the state of the pool
/// bit0, 1: disable open position and increase liquidity, 0: normal
/// bit1, 1: disable decrease liquidity, 0: normal
/// bit2, 1: disable collect fee, 0: normal
/// bit3, 1: disable collect reward, 0: normal
/// bit4, 1: disable swap, 0: normal
pub status: u8,
/// Leave blank for future use
pub padding: [u8; 7],
pub reward_infos: [RewardInfo; REWARD_NUM],
/// Packed initialized tick array state
pub tick_array_bitmap: [u64; 16],
/// except protocol_fee and fund_fee
pub total_fees_token_0: u64,
/// except protocol_fee and fund_fee
pub total_fees_claimed_token_0: u64,
pub total_fees_token_1: u64,
pub total_fees_claimed_token_1: u64,
pub fund_fees_token_0: u64,
pub fund_fees_token_1: u64,
// The timestamp allowed for swap in the pool.
// Note: The open_time is disabled for now.
pub open_time: u64,
// account recent update epoch
pub recent_epoch: u64,
// Unused bytes for future upgrades.
pub padding1: [u64; 24],
pub padding2: [u64; 32],
}
impl PoolState {
pub const LEN: usize = 8
+ 1
+ 32 * 7
+ 1
+ 1
+ 2
+ 16
+ 16
+ 4
+ 2
+ 2
+ 16
+ 16
+ 8
+ 8
+ 16
+ 16
+ 16
+ 16
+ 8
+ RewardInfo::LEN * REWARD_NUM
+ 8 * 16
+ 512;
pub fn seeds(&self) -> [&[u8]; 5] {
[
&POOL_SEED.as_bytes(),
self.amm_config.as_ref(),
self.token_mint_0.as_ref(),
self.token_mint_1.as_ref(),
self.bump.as_ref(),
]
}
pub fn key(&self) -> Pubkey {
Pubkey::create_program_address(&self.seeds(), &crate::id()).unwrap()
}
pub fn initialize(
&mut self,
bump: u8,
sqrt_price_x64: u128,
open_time: u64,
tick: i32,
pool_creator: Pubkey,
token_vault_0: Pubkey,
token_vault_1: Pubkey,
amm_config: &Account<AmmConfig>,
token_mint_0: &InterfaceAccount<Mint>,
token_mint_1: &InterfaceAccount<Mint>,
observation_state_key: Pubkey,
) -> Result<()> {
self.bump = [bump];
self.amm_config = amm_config.key();
self.owner = pool_creator.key();
self.token_mint_0 = token_mint_0.key();
self.token_mint_1 = token_mint_1.key();
self.mint_decimals_0 = token_mint_0.decimals;
self.mint_decimals_1 = token_mint_1.decimals;
self.token_vault_0 = token_vault_0;
self.token_vault_1 = token_vault_1;
self.tick_spacing = amm_config.tick_spacing;
self.liquidity = 0;
self.sqrt_price_x64 = sqrt_price_x64;
self.tick_current = tick;
self.padding3 = 0;
self.padding4 = 0;
self.reward_infos = [RewardInfo::new(pool_creator); REWARD_NUM];
self.fee_growth_global_0_x64 = 0;
self.fee_growth_global_1_x64 = 0;
self.protocol_fees_token_0 = 0;
self.protocol_fees_token_1 = 0;
self.swap_in_amount_token_0 = 0;
self.swap_out_amount_token_1 = 0;
self.swap_in_amount_token_1 = 0;
self.swap_out_amount_token_0 = 0;
self.status = 0;
self.padding = [0; 7];
self.tick_array_bitmap = [0; 16];
self.total_fees_token_0 = 0;
self.total_fees_claimed_token_0 = 0;
self.total_fees_token_1 = 0;
self.total_fees_claimed_token_1 = 0;
self.fund_fees_token_0 = 0;
self.fund_fees_token_1 = 0;
self.open_time = open_time;
self.recent_epoch = get_recent_epoch()?;
self.padding1 = [0; 24];
self.padding2 = [0; 32];
self.observation_key = observation_state_key;
Ok(())
}
pub fn initialize_reward(
&mut self,
open_time: u64,
end_time: u64,
reward_per_second_x64: u128,
token_mint: &Pubkey,
token_vault: &Pubkey,
authority: &Pubkey,
operation_state: &OperationState,
) -> Result<()> {
let reward_infos = self.reward_infos;
let lowest_index = match reward_infos.iter().position(|r| !r.initialized()) {
Some(lowest_index) => lowest_index,
None => return Err(ErrorCode::FullRewardInfo.into()),
};
if lowest_index >= REWARD_NUM {
return Err(ErrorCode::FullRewardInfo.into());
}
// one of first two reward token must be a vault token and the last reward token must be controled by the admin
let reward_mints: Vec<Pubkey> = reward_infos
.into_iter()
.map(|item| item.token_mint)
.collect();
// check init token_mint is not already in use
require!(
!reward_mints.contains(token_mint),
ErrorCode::RewardTokenAlreadyInUse
);
let whitelist_mints = operation_state.whitelist_mints.to_vec();
// The current init token is the penult.
if lowest_index == REWARD_NUM - 2 {
// If token_mint_0 or token_mint_1 is not contains in the initialized rewards token,
// the current init reward token mint must be token_mint_0 or token_mint_1
if !reward_mints.contains(&self.token_mint_0)
&& !reward_mints.contains(&self.token_mint_1)
{
require!(
*token_mint == self.token_mint_0
|| *token_mint == self.token_mint_1
|| whitelist_mints.contains(token_mint),
ErrorCode::ExceptPoolVaultMint
);
}
} else if lowest_index == REWARD_NUM - 1 {
// the last reward token must be controled by the admin
require!(
*authority == crate::admin::id()
|| operation_state.validate_operation_owner(*authority),
ErrorCode::NotApproved
);
}
// self.reward_infos[lowest_index].reward_state = RewardState::Initialized as u8;
self.reward_infos[lowest_index].last_update_time = open_time;
self.reward_infos[lowest_index].open_time = open_time;
self.reward_infos[lowest_index].end_time = end_time;
self.reward_infos[lowest_index].emissions_per_second_x64 = reward_per_second_x64;
self.reward_infos[lowest_index].token_mint = *token_mint;
self.reward_infos[lowest_index].token_vault = *token_vault;
self.reward_infos[lowest_index].authority = *authority;
#[cfg(feature = "enable-log")]
msg!(
"reward_index:{}, reward_infos:{:?}",
lowest_index,
self.reward_infos[lowest_index],
);
self.recent_epoch = get_recent_epoch()?;
Ok(())
}
// Calculates the next global reward growth variables based on the given timestamp.
// The provided timestamp must be greater than or equal to the last updated timestamp.
pub fn update_reward_infos(&mut self, curr_timestamp: u64) -> Result<[RewardInfo; REWARD_NUM]> {
#[cfg(feature = "enable-log")]
msg!("current block timestamp:{}", curr_timestamp);
let mut next_reward_infos = self.reward_infos;
for i in 0..REWARD_NUM {
let reward_info = &mut next_reward_infos[i];
if !reward_info.initialized() {
continue;
}
if curr_timestamp <= reward_info.open_time {
continue;
}
let latest_update_timestamp = curr_timestamp.min(reward_info.end_time);
if self.liquidity != 0 {
require_gte!(latest_update_timestamp, reward_info.last_update_time);
let time_delta = latest_update_timestamp
.checked_sub(reward_info.last_update_time)
.unwrap();
let reward_growth_delta = U256::from(time_delta)
.mul_div_floor(
U256::from(reward_info.emissions_per_second_x64),
U256::from(self.liquidity),
)
.unwrap();
reward_info.reward_growth_global_x64 = reward_info
.reward_growth_global_x64
.checked_add(reward_growth_delta.as_u128())
.unwrap();
reward_info.reward_total_emissioned = reward_info
.reward_total_emissioned
.checked_add(
U128::from(time_delta)
.mul_div_ceil(
U128::from(reward_info.emissions_per_second_x64),
U128::from(fixed_point_64::Q64),
)
.unwrap()
.as_u64(),
)
.unwrap();
#[cfg(feature = "enable-log")]
msg!(
"reward_index:{},latest_update_timestamp:{},reward_info.reward_last_update_time:{},time_delta:{},reward_emission_per_second_x64:{},reward_growth_delta:{},reward_info.reward_growth_global_x64:{}, reward_info.reward_claim:{}",
i,
latest_update_timestamp,
identity(reward_info.last_update_time),
time_delta,
identity(reward_info.emissions_per_second_x64),
reward_growth_delta,
identity(reward_info.reward_growth_global_x64),
identity(reward_info.reward_claimed)
);
}
reward_info.last_update_time = latest_update_timestamp;
// update reward state
if latest_update_timestamp >= reward_info.open_time
&& latest_update_timestamp < reward_info.end_time
{
reward_info.reward_state = RewardState::Opening as u8;
} else if latest_update_timestamp == next_reward_infos[i].end_time {
next_reward_infos[i].reward_state = RewardState::Ended as u8;
}
}
self.reward_infos = next_reward_infos;
#[cfg(feature = "enable-log")]
msg!("update pool reward info, reward_0_total_emissioned:{}, reward_1_total_emissioned:{}, reward_2_total_emissioned:{}, pool.liquidity:{}",
identity(self.reward_infos[0].reward_total_emissioned),identity(self.reward_infos[1].reward_total_emissioned),identity(self.reward_infos[2].reward_total_emissioned), identity(self.liquidity));
self.recent_epoch = get_recent_epoch()?;
Ok(next_reward_infos)
}
pub fn check_unclaimed_reward(&self, index: usize, reward_amount_owed: u64) -> Result<()> {
assert!(index < REWARD_NUM);
let unclaimed_reward = self.reward_infos[index]
.reward_total_emissioned
.checked_sub(self.reward_infos[index].reward_claimed)
.unwrap();
require_gte!(unclaimed_reward, reward_amount_owed);
Ok(())
}
pub fn add_reward_clamed(&mut self, index: usize, amount: u64) -> Result<()> {
assert!(index < REWARD_NUM);
self.reward_infos[index].reward_claimed = self.reward_infos[index]
.reward_claimed
.checked_add(amount)
.unwrap();
Ok(())
}
pub fn get_tick_array_offset(&self, tick_array_start_index: i32) -> Result<usize> {
require!(
TickArrayState::check_is_valid_start_index(tick_array_start_index, self.tick_spacing),
ErrorCode::InvaildTickIndex
);
let tick_array_offset_in_bitmap = tick_array_start_index
/ TickArrayState::tick_count(self.tick_spacing)
+ tick_array_bit_map::TICK_ARRAY_BITMAP_SIZE;
Ok(tick_array_offset_in_bitmap as usize)
}
fn flip_tick_array_bit_internal(&mut self, tick_array_start_index: i32) -> Result<()> {
let tick_array_offset_in_bitmap = self.get_tick_array_offset(tick_array_start_index)?;
let tick_array_bitmap = U1024(self.tick_array_bitmap);
let mask = U1024::one() << tick_array_offset_in_bitmap.try_into().unwrap();
self.tick_array_bitmap = tick_array_bitmap.bitxor(mask).0;
Ok(())
}
pub fn flip_tick_array_bit<'c: 'info, 'info>(
&mut self,
tickarray_bitmap_extension: Option<&'c AccountInfo<'info>>,
tick_array_start_index: i32,
) -> Result<()> {
if self.is_overflow_default_tickarray_bitmap(vec![tick_array_start_index]) {
require_keys_eq!(
tickarray_bitmap_extension.unwrap().key(),
TickArrayBitmapExtension::key(self.key())
);
AccountLoader::<TickArrayBitmapExtension>::try_from(
tickarray_bitmap_extension.unwrap(),
)?
.load_mut()?
.flip_tick_array_bit(tick_array_start_index, self.tick_spacing)
} else {
self.flip_tick_array_bit_internal(tick_array_start_index)
}
}
pub fn get_first_initialized_tick_array(
&self,
tickarray_bitmap_extension: &Option<TickArrayBitmapExtension>,
zero_for_one: bool,
) -> Result<(bool, i32)> {
let (is_initialized, start_index) =
if self.is_overflow_default_tickarray_bitmap(vec![self.tick_current]) {
tickarray_bitmap_extension
.unwrap()
.check_tick_array_is_initialized(
TickArrayState::get_array_start_index(self.tick_current, self.tick_spacing),
self.tick_spacing,
)?
} else {
check_current_tick_array_is_initialized(
U1024(self.tick_array_bitmap),
self.tick_current,
self.tick_spacing.into(),
)?
};
if is_initialized {
return Ok((true, start_index));
}
let next_start_index = self.next_initialized_tick_array_start_index(
tickarray_bitmap_extension,
TickArrayState::get_array_start_index(self.tick_current, self.tick_spacing),
zero_for_one,
)?;
require!(
next_start_index.is_some(),
ErrorCode::InsufficientLiquidityForDirection
);
return Ok((false, next_start_index.unwrap()));
}
pub fn next_initialized_tick_array_start_index(
&self,
tickarray_bitmap_extension: &Option<TickArrayBitmapExtension>,
mut last_tick_array_start_index: i32,
zero_for_one: bool,
) -> Result<Option<i32>> {
last_tick_array_start_index =
TickArrayState::get_array_start_index(last_tick_array_start_index, self.tick_spacing);
loop {
let (is_found, start_index) =
tick_array_bit_map::next_initialized_tick_array_start_index(
U1024(self.tick_array_bitmap),
last_tick_array_start_index,
self.tick_spacing,
zero_for_one,
);
if is_found {
return Ok(Some(start_index));
}
last_tick_array_start_index = start_index;
if tickarray_bitmap_extension.is_none() {
return err!(ErrorCode::MissingTickArrayBitmapExtensionAccount);
}
let (is_found, start_index) = tickarray_bitmap_extension
.unwrap()
.next_initialized_tick_array_from_one_bitmap(
last_tick_array_start_index,
self.tick_spacing,
zero_for_one,
)?;
if is_found {
return Ok(Some(start_index));
}
last_tick_array_start_index = start_index;
if last_tick_array_start_index < tick_math::MIN_TICK
|| last_tick_array_start_index > tick_math::MAX_TICK
{
return Ok(None);
}
}
}
pub fn set_status(&mut self, status: u8) {
self.status = status
}
pub fn set_status_by_bit(&mut self, bit: PoolStatusBitIndex, flag: PoolStatusBitFlag) {
let s = u8::from(1) << (bit as u8);
if flag == PoolStatusBitFlag::Disable {
self.status = self.status.bitor(s);
} else {
let m = u8::from(255).bitxor(s);
self.status = self.status.bitand(m);
}
}
/// Get status by bit, if it is `noraml` status, return true
pub fn get_status_by_bit(&self, bit: PoolStatusBitIndex) -> bool {
let status = u8::from(1) << (bit as u8);
self.status.bitand(status) == 0
}
pub fn is_overflow_default_tickarray_bitmap(&self, tick_indexs: Vec<i32>) -> bool {
let (min_tick_array_start_index_boundary, max_tick_array_index_boundary) =
self.tick_array_start_index_range();
for tick_index in tick_indexs {
let tick_array_start_index =
TickArrayState::get_array_start_index(tick_index, self.tick_spacing);
if tick_array_start_index >= max_tick_array_index_boundary
|| tick_array_start_index < min_tick_array_start_index_boundary
{
return true;
}
}
false
}
// the range of tick array start index that default tickarray bitmap can represent
// if tick_spacing = 1, the result range is [-30720, 30720)
pub fn tick_array_start_index_range(&self) -> (i32, i32) {
// the range of ticks that default tickarrary can represent
let mut max_tick_boundary =
tick_array_bit_map::max_tick_in_tickarray_bitmap(self.tick_spacing);
let mut min_tick_boundary = -max_tick_boundary;
if max_tick_boundary > tick_math::MAX_TICK {
max_tick_boundary =
TickArrayState::get_array_start_index(tick_math::MAX_TICK, self.tick_spacing);
// find the next tick array start index
max_tick_boundary = max_tick_boundary + TickArrayState::tick_count(self.tick_spacing);
}
if min_tick_boundary < tick_math::MIN_TICK {
min_tick_boundary =
TickArrayState::get_array_start_index(tick_math::MIN_TICK, self.tick_spacing);
}
(min_tick_boundary, max_tick_boundary)
}
}
#[derive(Copy, Clone, AnchorSerialize, AnchorDeserialize, Debug, PartialEq)]
/// State of reward
pub enum RewardState {
/// Reward not initialized
Uninitialized,
/// Reward initialized, but reward time is not start
Initialized,
/// Reward in progress
Opening,
/// Reward end, reward time expire or
Ended,
}
#[zero_copy(unsafe)]
#[repr(C, packed)]
#[derive(Default, Debug, PartialEq, Eq)]
pub struct RewardInfo {
/// Reward state
pub reward_state: u8,
/// Reward open time
pub open_time: u64,
/// Reward end time
pub end_time: u64,
/// Reward last update time
pub last_update_time: u64,
/// Q64.64 number indicates how many tokens per second are earned per unit of liquidity.
pub emissions_per_second_x64: u128,
/// The total amount of reward emissioned
pub reward_total_emissioned: u64,
/// The total amount of claimed reward
pub reward_claimed: u64,
/// Reward token mint.
pub token_mint: Pubkey,
/// Reward vault token account.
pub token_vault: Pubkey,
/// The owner that has permission to set reward param
pub authority: Pubkey,
/// Q64.64 number that tracks the total tokens earned per unit of liquidity since the reward
/// emissions were turned on.
pub reward_growth_global_x64: u128,
}
impl RewardInfo {
pub const LEN: usize = 1 + 8 + 8 + 8 + 16 + 8 + 8 + 32 + 32 + 32 + 16;
/// Creates a new RewardInfo
pub fn new(authority: Pubkey) -> Self {
Self {
authority,
..Default::default()
}
}
/// Returns true if this reward is initialized.
/// Once initialized, a reward cannot transition back to uninitialized.
pub fn initialized(&self) -> bool {
self.token_mint.ne(&Pubkey::default())
}
pub fn get_reward_growths(reward_infos: &[RewardInfo; REWARD_NUM]) -> [u128; REWARD_NUM] {
let mut reward_growths = [0u128; REWARD_NUM];
for i in 0..REWARD_NUM {
reward_growths[i] = reward_infos[i].reward_growth_global_x64;
}
reward_growths
}
}
/// Emitted when a pool is created and initialized with a starting price
///
#[event]
#[cfg_attr(feature = "client", derive(Debug))]
pub struct PoolCreatedEvent {
/// The first token of the pool by address sort order
#[index]
pub token_mint_0: Pubkey,
/// The second token of the pool by address sort order
#[index]
pub token_mint_1: Pubkey,
/// The minimum number of ticks between initialized ticks
pub tick_spacing: u16,
/// The address of the created pool
pub pool_state: Pubkey,
/// The initial sqrt price of the pool, as a Q64.64
pub sqrt_price_x64: u128,
/// The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
pub tick: i32,
/// Vault of token_0
pub token_vault_0: Pubkey,
/// Vault of token_1
pub token_vault_1: Pubkey,
}
/// Emitted when the collected protocol fees are withdrawn by the factory owner
#[event]
#[cfg_attr(feature = "client", derive(Debug))]
pub struct CollectProtocolFeeEvent {
/// The pool whose protocol fee is collected
#[index]
pub pool_state: Pubkey,
/// The address that receives the collected token_0 protocol fees
pub recipient_token_account_0: Pubkey,
/// The address that receives the collected token_1 protocol fees
pub recipient_token_account_1: Pubkey,
/// The amount of token_0 protocol fees that is withdrawn
pub amount_0: u64,
/// The amount of token_0 protocol fees that is withdrawn
pub amount_1: u64,
}
/// Emitted by when a swap is performed for a pool
#[event]
#[cfg_attr(feature = "client", derive(Debug))]
pub struct SwapEvent {
/// The pool for which token_0 and token_1 were swapped
#[index]
pub pool_state: Pubkey,
/// The address that initiated the swap call, and that received the callback
#[index]
pub sender: Pubkey,
/// The payer token account in zero for one swaps, or the recipient token account
/// in one for zero swaps
#[index]
pub token_account_0: Pubkey,
/// The payer token account in one for zero swaps, or the recipient token account
/// in zero for one swaps
#[index]
pub token_account_1: Pubkey,
/// The real delta amount of the token_0 of the pool or user
pub amount_0: u64,
/// The transfer fee charged by the withheld_amount of the token_0
pub transfer_fee_0: u64,
/// The real delta of the token_1 of the pool or user
pub amount_1: u64,
/// The transfer fee charged by the withheld_amount of the token_1
pub transfer_fee_1: u64,
/// if true, amount_0 is negtive and amount_1 is positive
pub zero_for_one: bool,
/// The sqrt(price) of the pool after the swap, as a Q64.64
pub sqrt_price_x64: u128,
/// The liquidity of the pool after the swap
pub liquidity: u128,
/// The log base 1.0001 of price of the pool after the swap
pub tick: i32,
}
/// Emitted pool liquidity change when increase and decrease liquidity
#[event]
#[cfg_attr(feature = "client", derive(Debug))]
pub struct LiquidityChangeEvent {
/// The pool for swap
#[index]
pub pool_state: Pubkey,
/// The tick of the pool
pub tick: i32,
/// The tick lower of position
pub tick_lower: i32,
/// The tick lower of position
pub tick_upper: i32,
/// The liquidity of the pool before liquidity change
pub liquidity_before: u128,
/// The liquidity of the pool after liquidity change
pub liquidity_after: u128,
}
// /// Emitted when price move in a swap step
// #[event]
// #[cfg_attr(feature = "client", derive(Debug))]
// pub struct PriceChangeEvent {
// /// The pool for swap
// #[index]
// pub pool_state: Pubkey,
// /// The tick of the pool before price change
// pub tick_before: i32,
// /// The tick of the pool after tprice change
// pub tick_after: i32,
// /// The sqrt(price) of the pool before price change, as a Q64.64
// pub sqrt_price_x64_before: u128,
// /// The sqrt(price) of the pool after price change, as a Q64.64
// pub sqrt_price_x64_after: u128,
// /// The liquidity of the pool before price change
// pub liquidity_before: u128,
// /// The liquidity of the pool after price change
// pub liquidity_after: u128,
// /// The direction of swap
// pub zero_for_one: bool,
// }
#[cfg(test)]
pub mod pool_test {
use super::*;
use std::cell::RefCell;
pub fn build_pool(
tick_current: i32,
tick_spacing: u16,
sqrt_price_x64: u128,
liquidity: u128,
) -> RefCell<PoolState> {
let mut new_pool = PoolState::default();
new_pool.tick_current = tick_current;
new_pool.tick_spacing = tick_spacing;
new_pool.sqrt_price_x64 = sqrt_price_x64;
new_pool.liquidity = liquidity;
new_pool.token_mint_0 = Pubkey::new_unique();
new_pool.token_mint_1 = Pubkey::new_unique();
new_pool.amm_config = Pubkey::new_unique();
// let mut random = rand::random<u128>();
new_pool.fee_growth_global_0_x64 = rand::random::<u128>();
new_pool.fee_growth_global_1_x64 = rand::random::<u128>();
new_pool.bump = [Pubkey::find_program_address(
&[
&POOL_SEED.as_bytes(),
new_pool.amm_config.as_ref(),
new_pool.token_mint_0.as_ref(),
new_pool.token_mint_1.as_ref(),
],
&crate::id(),
)
.1];
RefCell::new(new_pool)
}
mod tick_array_bitmap_test {
use super::*;
#[test]
fn get_arrary_start_index_negative() {
let mut pool_state = PoolState::default();
pool_state.tick_spacing = 10;
pool_state.flip_tick_array_bit(None, -600).unwrap();
assert!(U1024(pool_state.tick_array_bitmap).bit(511) == true);
pool_state.flip_tick_array_bit(None, -1200).unwrap();
assert!(U1024(pool_state.tick_array_bitmap).bit(510) == true);
pool_state.flip_tick_array_bit(None, -1800).unwrap();
assert!(U1024(pool_state.tick_array_bitmap).bit(509) == true);
pool_state.flip_tick_array_bit(None, -38400).unwrap();
assert!(
U1024(pool_state.tick_array_bitmap)
.bit(pool_state.get_tick_array_offset(-38400).unwrap())
== true
);
pool_state.flip_tick_array_bit(None, -39000).unwrap();
assert!(
U1024(pool_state.tick_array_bitmap)
.bit(pool_state.get_tick_array_offset(-39000).unwrap())
== true
);
pool_state.flip_tick_array_bit(None, -307200).unwrap();
assert!(
U1024(pool_state.tick_array_bitmap)
.bit(pool_state.get_tick_array_offset(-307200).unwrap())
== true
);
}
#[test]
fn get_arrary_start_index_positive() {
let mut pool_state = PoolState::default();
pool_state.tick_spacing = 10;
pool_state.flip_tick_array_bit(None, 0).unwrap();
assert!(pool_state.get_tick_array_offset(0).unwrap() == 512);
assert!(
U1024(pool_state.tick_array_bitmap)
.bit(pool_state.get_tick_array_offset(0).unwrap())
== true
);
pool_state.flip_tick_array_bit(None, 600).unwrap();
assert!(pool_state.get_tick_array_offset(600).unwrap() == 513);
assert!(
U1024(pool_state.tick_array_bitmap)
.bit(pool_state.get_tick_array_offset(600).unwrap())
== true
);
pool_state.flip_tick_array_bit(None, 1200).unwrap();
assert!(
U1024(pool_state.tick_array_bitmap)
.bit(pool_state.get_tick_array_offset(1200).unwrap())
== true
);
pool_state.flip_tick_array_bit(None, 38400).unwrap();
assert!(
U1024(pool_state.tick_array_bitmap)
.bit(pool_state.get_tick_array_offset(38400).unwrap())
== true
);
pool_state.flip_tick_array_bit(None, 306600).unwrap();
assert!(pool_state.get_tick_array_offset(306600).unwrap() == 1023);
assert!(
U1024(pool_state.tick_array_bitmap)
.bit(pool_state.get_tick_array_offset(306600).unwrap())
== true
);
}
#[test]
fn default_tick_array_start_index_range_test() {
let mut pool_state = PoolState::default();
pool_state.tick_spacing = 60;
// -443580 is the min tick can use to open a position when tick_spacing is 60 due to MIN_TICK is -443636
assert!(pool_state.is_overflow_default_tickarray_bitmap(vec![-443580]) == false);
// 443580 is the min tick can use to open a position when tick_spacing is 60 due to MAX_TICK is 443636
assert!(pool_state.is_overflow_default_tickarray_bitmap(vec![443580]) == false);
pool_state.tick_spacing = 10;
assert!(pool_state.is_overflow_default_tickarray_bitmap(vec![-307200]) == false);
assert!(pool_state.is_overflow_default_tickarray_bitmap(vec![-307201]) == true);
assert!(pool_state.is_overflow_default_tickarray_bitmap(vec![307200]) == true);
assert!(pool_state.is_overflow_default_tickarray_bitmap(vec![307199]) == false);
pool_state.tick_spacing = 1;
assert!(pool_state.is_overflow_default_tickarray_bitmap(vec![-30720]) == false);
assert!(pool_state.is_overflow_default_tickarray_bitmap(vec![-30721]) == true);
assert!(pool_state.is_overflow_default_tickarray_bitmap(vec![30720]) == true);
assert!(pool_state.is_overflow_default_tickarray_bitmap(vec![30719]) == false);
}
}
mod pool_status_test {
use super::*;
#[test]
fn get_set_status_by_bit() {
let mut pool_state = PoolState::default();
pool_state.set_status(17); // 00010001
assert_eq!(
pool_state.get_status_by_bit(PoolStatusBitIndex::Swap),
false
);
assert_eq!(
pool_state.get_status_by_bit(PoolStatusBitIndex::OpenPositionOrIncreaseLiquidity),
false
);
assert_eq!(
pool_state.get_status_by_bit(PoolStatusBitIndex::DecreaseLiquidity),
true
);
assert_eq!(
pool_state.get_status_by_bit(PoolStatusBitIndex::CollectFee),
true
);
assert_eq!(
pool_state.get_status_by_bit(PoolStatusBitIndex::CollectReward),
true
);
// disable -> disable, nothing to change
pool_state.set_status_by_bit(PoolStatusBitIndex::Swap, PoolStatusBitFlag::Disable);
assert_eq!(
pool_state.get_status_by_bit(PoolStatusBitIndex::Swap),
false
);
// disable -> enable
pool_state.set_status_by_bit(PoolStatusBitIndex::Swap, PoolStatusBitFlag::Enable);
assert_eq!(pool_state.get_status_by_bit(PoolStatusBitIndex::Swap), true);
// enable -> enable, nothing to change
pool_state.set_status_by_bit(
PoolStatusBitIndex::DecreaseLiquidity,
PoolStatusBitFlag::Enable,
);
assert_eq!(
pool_state.get_status_by_bit(PoolStatusBitIndex::DecreaseLiquidity),
true
);
// enable -> disable
pool_state.set_status_by_bit(
PoolStatusBitIndex::DecreaseLiquidity,
PoolStatusBitFlag::Disable,
);
assert_eq!(
pool_state.get_status_by_bit(PoolStatusBitIndex::DecreaseLiquidity),
false