-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathlib.rs
2420 lines (2197 loc) · 95 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
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
pub mod access_control;
pub mod context;
pub mod error;
pub mod libraries;
pub mod states;
use crate::access_control::*;
use crate::error::ErrorCode;
use crate::libraries::liquidity_amounts;
use crate::libraries::tick_math;
use crate::states::oracle;
use crate::states::oracle::ObservationState;
use crate::states::tokenized_position::{
CollectTokenizedEvent, DecreaseLiquidityEvent, IncreaseLiquidityEvent,
};
use crate::{
libraries::{fixed_point_32, swap_math},
states::{oracle::OBSERVATION_SEED, tick_bitmap},
};
use anchor_lang::prelude::*;
use anchor_lang::solana_program;
use anchor_lang::solana_program::system_instruction::create_account;
use anchor_lang::{solana_program::instruction::Instruction, InstructionData};
use anchor_spl::associated_token::get_associated_token_address;
use anchor_spl::token;
use anchor_spl::token::TokenAccount;
use context::*;
use libraries::full_math::MulDiv;
use libraries::liquidity_math;
use libraries::sqrt_price_math;
use metaplex_token_metadata::{instruction::create_metadata_accounts, state::Creator};
use spl_token::instruction::AuthorityType;
use states::factory::*;
use states::fee::*;
use states::pool::*;
use states::position::*;
use states::tick;
use states::tick::*;
use states::tick_bitmap::*;
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::mem::size_of;
use std::ops::Neg;
use std::ops::{Deref, DerefMut};
declare_id!("cysPXAjehMpVKUapzbMCCnpFxUFFryEWEaLgnb9NrR8");
#[program]
pub mod cyclos_core {
use super::*;
// ---------------------------------------------------------------------
// Factory instructions
// The Factory facilitates creation of pools and control over the protocol fees
/// Initialize the factory state and set the protocol owner
///
/// # Arguments
///
/// * `ctx`- Initializes the factory state account
/// * `factory_state_bump` - Bump to validate factory state address
///
pub fn init_factory(ctx: Context<Initialize>) -> Result<()> {
let mut factory_state = ctx.accounts.factory_state.load_init()?;
factory_state.bump = *ctx.bumps.get("factory_state").unwrap();
factory_state.owner = ctx.accounts.owner.key();
factory_state.fee_protocol = 3; // 1/3 = 33.33%
emit!(OwnerChanged {
old_owner: Pubkey::default(),
new_owner: ctx.accounts.owner.key(),
});
Ok(())
}
/// Updates the owner of the factory
/// Must be called by the current owner
///
/// # Arguments
///
/// * `ctx`- Checks whether protocol owner has signed
///
pub fn set_owner(ctx: Context<SetOwner>) -> Result<()> {
let mut factory_state = ctx.accounts.factory_state.load_mut()?;
factory_state.owner = ctx.accounts.new_owner.key();
emit!(OwnerChanged {
old_owner: ctx.accounts.owner.key(),
new_owner: ctx.accounts.new_owner.key(),
});
Ok(())
}
/// Enables a fee amount with the given tick_spacing
/// Fee amounts may never be removed once enabled
///
/// # Arguments
///
/// * `ctx`- Checks whether protocol owner has signed and initializes the fee account
/// * `fee_state_bump` - Bump to validate fee state address
/// * `fee` - The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
/// * `tick_spacing` - The spacing between ticks to be enforced for all pools created
/// with the given fee amount
///
pub fn enable_fee_amount(
ctx: Context<EnableFeeAmount>,
fee: u32,
tick_spacing: u16,
) -> Result<()> {
assert!(fee < 1_000_000); // 100%
// TODO examine max value of tick_spacing
// tick spacing is capped at 16384 to prevent the situation where tick_spacing is so large that
// tick_bitmap#next_initialized_tick_within_one_word overflows int24 container from a valid tick
// 16384 ticks represents a >5x price change with ticks of 1 bips
let mut fee_state = ctx.accounts.fee_state.load_init()?;
assert!(tick_spacing > 0 && tick_spacing < 16384);
fee_state.bump = *ctx.bumps.get("fee_state").unwrap();
fee_state.fee = fee;
fee_state.tick_spacing = tick_spacing;
emit!(FeeAmountEnabled { fee, tick_spacing });
Ok(())
}
// ---------------------------------------------------------------------
// Pool instructions
/// Creates a pool for the given token pair and fee, and sets the initial price
///
/// A single function in place of Uniswap's Factory.createPool(), PoolDeployer.deploy()
/// Pool.initialize() and pool.Constructor()
///
/// # Arguments
///
/// * `ctx`- Validates token addresses and fee state. Initializes pool, observation and
/// token accounts
/// * `pool_state_bump` - Bump to validate Pool State address
/// * `observation_state_bump` - Bump to validate Observation State address
/// * `sqrt_price_x32` - the initial sqrt price (amount_token_1 / amount_token_0) of the pool as a Q32.32
///
pub fn create_and_init_pool(
ctx: Context<CreateAndInitPool>,
sqrt_price_x32: u64,
) -> Result<()> {
let mut pool_state = ctx.accounts.pool_state.load_init()?;
let fee_state = ctx.accounts.fee_state.load()?;
let tick = tick_math::get_tick_at_sqrt_ratio(sqrt_price_x32)?;
pool_state.bump = *ctx.bumps.get("pool_state").unwrap();
pool_state.token_0 = ctx.accounts.token_0.key();
pool_state.token_1 = ctx.accounts.token_1.key();
pool_state.fee = fee_state.fee;
pool_state.tick_spacing = fee_state.tick_spacing;
pool_state.sqrt_price_x32 = sqrt_price_x32;
pool_state.tick = tick;
pool_state.unlocked = true;
pool_state.observation_cardinality = 1;
pool_state.observation_cardinality_next = 1;
let mut initial_observation_state = ctx.accounts.initial_observation_state.load_init()?;
initial_observation_state.bump = *ctx.bumps.get("initial_observation_state").unwrap();
initial_observation_state.block_timestamp = oracle::_block_timestamp();
initial_observation_state.initialized = true;
// default value 0 for remaining variables
emit!(PoolCreatedAndInitialized {
token_0: ctx.accounts.token_0.key(),
token_1: ctx.accounts.token_1.key(),
fee: fee_state.fee,
tick_spacing: fee_state.tick_spacing,
pool_state: ctx.accounts.pool_state.key(),
sqrt_price_x32,
tick,
});
Ok(())
}
// ---------------------------------------------------------------------
// Oracle
/// Increase the maximum number of price and liquidity observations that this pool will store
///
/// An `ObservationState` account is created per unit increase in cardinality_next,
/// and `observation_cardinality_next` is accordingly incremented.
///
/// # Arguments
///
/// * `ctx` - Holds the pool and payer addresses, along with a vector of
/// observation accounts which will be initialized
/// * `observation_account_bumps` - Vector of bumps to initialize the observation state PDAs
///
pub fn increase_observation_cardinality_next<'a, 'b, 'c, 'info>(
ctx: Context<'a, 'b, 'c, 'info, IncreaseObservationCardinalityNext<'info>>,
observation_account_bumps: Vec<u8>,
) -> Result<()> {
let mut pool_state = ctx.accounts.pool_state.load_mut()?;
require!(pool_state.unlocked, ErrorCode::LOK);
pool_state.unlocked = false;
let mut i: usize = 0;
while i < observation_account_bumps.len() {
let observation_account_seeds = [
&OBSERVATION_SEED.as_bytes(),
pool_state.token_0.as_ref(),
pool_state.token_1.as_ref(),
&pool_state.fee.to_be_bytes(),
&(pool_state.observation_cardinality_next + i as u16).to_be_bytes(),
&[observation_account_bumps[i]],
];
require!(
ctx.remaining_accounts[i].key()
== Pubkey::create_program_address(
&observation_account_seeds[..],
&ctx.program_id
)
.unwrap(),
ErrorCode::OS
);
let space = 8 + size_of::<ObservationState>();
let rent = Rent::get()?;
let lamports = rent.minimum_balance(space);
let ix = create_account(
ctx.accounts.payer.key,
&ctx.remaining_accounts[i].key,
lamports,
space as u64,
ctx.program_id,
);
solana_program::program::invoke_signed(
&ix,
&[
ctx.accounts.payer.to_account_info(),
ctx.remaining_accounts[i].to_account_info(),
ctx.accounts.system_program.to_account_info(),
],
&[&observation_account_seeds[..]],
)?;
let observation_state_loader = AccountLoader::<ObservationState>::try_from_unchecked(
&cyclos_core::id(),
&ctx.remaining_accounts[i].to_account_info(),
)?;
let mut observation_state = observation_state_loader.load_init()?;
// this data will not be used because the initialized boolean is still false
observation_state.bump = observation_account_bumps[i];
observation_state.index = pool_state.observation_cardinality_next + i as u16;
observation_state.block_timestamp = 1;
drop(observation_state);
observation_state_loader.exit(ctx.program_id)?;
i += 1;
}
let observation_cardinality_next_old = pool_state.observation_cardinality_next;
pool_state.observation_cardinality_next = pool_state
.observation_cardinality_next
.checked_add(i as u16)
.unwrap();
emit!(oracle::IncreaseObservationCardinalityNext {
observation_cardinality_next_old,
observation_cardinality_next_new: pool_state.observation_cardinality_next,
});
pool_state.unlocked = true;
Ok(())
}
// ---------------------------------------------------------------------
// Pool owner instructions
/// Set the denominator of the protocol's % share of the fees.
///
/// Unlike Uniswap, protocol fee is globally set. It can be updated by factory owner
/// at any time.
///
/// # Arguments
///
/// * `ctx` - Checks for valid owner by looking at signer and factory owner addresses.
/// Holds the Factory State account where protocol fee will be saved.
/// * `fee_protocol` - new protocol fee for all pools
///
pub fn set_fee_protocol(ctx: Context<SetFeeProtocol>, fee_protocol: u8) -> Result<()> {
assert!(fee_protocol >= 2 && fee_protocol <= 10);
let mut factory_state = ctx.accounts.factory_state.load_mut()?;
let fee_protocol_old = factory_state.fee_protocol;
factory_state.fee_protocol = fee_protocol;
emit!(SetFeeProtocolEvent {
fee_protocol_old,
fee_protocol
});
Ok(())
}
/// Collect the protocol fee accrued to the pool
///
/// # Arguments
///
/// * `ctx` - Checks for valid owner by looking at signer and factory owner addresses.
/// Holds the Pool State account where accrued protocol fee is saved, and token accounts to perform
/// transfer.
/// * `amount_0_requested` - The maximum amount of token_0 to send, can be 0 to collect fees in only token_1
/// * `amount_1_requested` - The maximum amount of token_1 to send, can be 0 to collect fees in only token_0
///
pub fn collect_protocol(
ctx: Context<CollectProtocol>,
amount_0_requested: u64,
amount_1_requested: u64,
) -> Result<()> {
let mut pool_state = ctx.accounts.pool_state.load_mut()?;
require!(pool_state.unlocked, ErrorCode::LOK);
pool_state.unlocked = false;
let amount_0 = amount_0_requested.min(pool_state.protocol_fees_token_0);
let amount_1 = amount_1_requested.min(pool_state.protocol_fees_token_1);
let pool_state_seeds = [
&POOL_SEED.as_bytes(),
&pool_state.token_0.to_bytes() as &[u8],
&pool_state.token_1.to_bytes() as &[u8],
&pool_state.fee.to_be_bytes(),
&[pool_state.bump],
];
pool_state.protocol_fees_token_0 -= amount_0;
pool_state.protocol_fees_token_1 -= amount_1;
drop(pool_state);
if amount_0 > 0 {
token::transfer(
CpiContext::new_with_signer(
ctx.accounts.token_program.to_account_info().clone(),
token::Transfer {
from: ctx.accounts.vault_0.to_account_info().clone(),
to: ctx.accounts.recipient_wallet_0.to_account_info().clone(),
authority: ctx.accounts.pool_state.to_account_info().clone(),
},
&[&pool_state_seeds[..]],
),
amount_0,
)?;
}
if amount_1 > 0 {
token::transfer(
CpiContext::new_with_signer(
ctx.accounts.token_program.to_account_info().clone(),
token::Transfer {
from: ctx.accounts.vault_1.to_account_info().clone(),
to: ctx.accounts.recipient_wallet_1.to_account_info().clone(),
authority: ctx.accounts.pool_state.to_account_info().clone(),
},
&[&pool_state_seeds[..]],
),
amount_1,
)?;
}
emit!(CollectProtocolEvent {
pool_state: ctx.accounts.pool_state.key(),
sender: ctx.accounts.owner.key(),
recipient_wallet_0: ctx.accounts.recipient_wallet_0.key(),
recipient_wallet_1: ctx.accounts.recipient_wallet_1.key(),
amount_0,
amount_1,
});
pool_state = ctx.accounts.pool_state.load_mut()?;
pool_state.unlocked = true;
Ok(())
}
/// ---------------------------------------------------------------------
/// Account init instructions
///
/// Having separate instructions to initialize instructions saves compute units
/// and reduces code in downstream instructions
///
/// Initializes an empty program account for a price tick
///
/// # Arguments
///
/// * `ctx` - Contains accounts to initialize an empty tick account
/// * `tick_account_bump` - Bump to validate tick account PDA
/// * `tick` - The tick for which the account is created
///
pub fn init_tick_account(ctx: Context<InitTickAccount>, tick: i32) -> Result<()> {
let pool_state = ctx.accounts.pool_state.load()?;
check_tick(tick, pool_state.tick_spacing)?;
let mut tick_state = ctx.accounts.tick_state.load_init()?;
tick_state.bump = *ctx.bumps.get("tick_state").unwrap();
tick_state.tick = tick;
Ok(())
}
/// Reclaims lamports from a cleared tick account
///
/// # Arguments
///
/// * `ctx` - Holds tick and recipient accounts with validation and closure code
///
pub fn close_tick_account(_ctx: Context<CloseTickAccount>) -> Result<()> {
Ok(())
}
/// Initializes an empty program account for a tick bitmap
///
/// # Arguments
///
/// * `ctx` - Contains accounts to initialize an empty bitmap account
/// * `bitmap_account_bump` - Bump to validate the bitmap account PDA
/// * `word_pos` - The bitmap key for which to create account. To find word position from a tick,
/// divide the tick by tick spacing to get a 24 bit compressed result, then right shift to obtain the
/// most significant 16 bits.
///
pub fn init_bitmap_account(ctx: Context<InitBitmapAccount>, word_pos: i16) -> Result<()> {
let pool_state = ctx.accounts.pool_state.load()?;
let max_word_pos = ((tick_math::MAX_TICK / pool_state.tick_spacing as i32) >> 8) as i16;
let min_word_pos = ((tick_math::MIN_TICK / pool_state.tick_spacing as i32) >> 8) as i16;
require!(word_pos >= min_word_pos, ErrorCode::TLM);
require!(word_pos <= max_word_pos, ErrorCode::TUM);
let mut bitmap_account = ctx.accounts.bitmap_state.load_init()?;
bitmap_account.bump = *ctx.bumps.get("bitmap_state").unwrap();
bitmap_account.word_pos = word_pos;
Ok(())
}
/// Initializes an empty program account for a position
///
/// # Arguments
///
/// * `ctx` - Contains accounts to initialize an empty position account
/// * `bump` - Bump to validate the position account PDA
/// * `tick` - The tick for which the bitmap account is created. Program address of
/// the account is derived using most significant 16 bits of the tick
///
pub fn init_position_account(ctx: Context<InitPositionAccount>) -> Result<()> {
let mut position_account = ctx.accounts.position_state.load_init()?;
position_account.bump = *ctx.bumps.get("position_state").unwrap();
Ok(())
}
// ---------------------------------------------------------------------
// Position instructions
/// Callback to pay tokens for creating or adding liquidity to a position
///
/// Callback function lies in core program instead of non_fungible_position_manager since
/// reentrancy is disallowed in Solana. Integrators can use a second program to handle callbacks.
///
/// # Arguments
///
/// * `amount_0_owed` - The amount of token_0 due to the pool for the minted liquidity
/// * `amount_1_owed` - The amount of token_1 due to the pool for the minted liquidity
///
pub fn mint_callback(
ctx: Context<MintCallback>,
amount_0_owed: u64,
amount_1_owed: u64,
) -> Result<()> {
if amount_0_owed > 0 {
token::transfer(
CpiContext::new(
ctx.accounts.token_program.to_account_info(),
token::Transfer {
from: ctx.accounts.token_account_0.to_account_info(),
to: ctx.accounts.vault_0.to_account_info(),
authority: ctx.accounts.minter.to_account_info(),
},
),
amount_0_owed,
)?;
}
if amount_1_owed > 0 {
token::transfer(
CpiContext::new(
ctx.accounts.token_program.to_account_info(),
token::Transfer {
from: ctx.accounts.token_account_1.to_account_info(),
to: ctx.accounts.vault_1.to_account_info(),
authority: ctx.accounts.minter.to_account_info(),
},
),
amount_1_owed,
)?;
}
Ok(())
}
/// Callback to pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be the core program.
/// amount_0_delta and amount_1_delta can both be 0 if no tokens were swapped.
///
/// # Arguments
///
/// * `ctx` - Token accounts for payment
/// * `amount_0_delta` - The amount of token_0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token_0 to the pool.
/// * `amount_1_delta` - The amount of token_1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token_1 to the pool.
///
pub fn swap_callback(
ctx: Context<SwapCallback>,
amount_0_delta: i64,
amount_1_delta: i64,
) -> Result<()> {
let (exact_input, amount_to_pay) = if amount_0_delta > 0 {
(
ctx.accounts.input_vault.mint < ctx.accounts.output_vault.mint,
amount_0_delta as u64,
)
} else {
(
ctx.accounts.output_vault.mint < ctx.accounts.input_vault.mint,
amount_1_delta as u64,
)
};
if exact_input {
msg!("amount to pay {}, delta 0 {}, delta 1 {}", amount_to_pay, amount_0_delta, amount_1_delta);
token::transfer(
CpiContext::new(
ctx.accounts.token_program.to_account_info(),
token::Transfer {
from: ctx.accounts.input_token_account.to_account_info(),
to: ctx.accounts.input_vault.to_account_info(),
authority: ctx.accounts.signer.to_account_info(),
},
),
amount_to_pay,
)?;
} else {
msg!("exact output not implemented");
};
Ok(())
}
/// Adds liquidity for the given pool/recipient/tickLower/tickUpper position
///
/// # Arguments
///
/// * `ctx` - Holds the recipient's address and program accounts for
/// pool, position and ticks.
/// * `amount` - The amount of liquidity to mint
///
pub fn mint<'a, 'b, 'c, 'info>(
ctx: Context<'a, 'b, 'c, 'info, MintContext<'info>>,
amount: u64,
) -> Result<()> {
let mut pool = ctx.accounts.pool_state.load_mut()?;
assert!(
ctx.accounts.vault_0.key()
== get_associated_token_address(&ctx.accounts.pool_state.key(), &pool.token_0)
);
assert!(
ctx.accounts.vault_1.key()
== get_associated_token_address(&ctx.accounts.pool_state.key(), &pool.token_1)
);
let tick_lower = *ctx.accounts.tick_lower_state.load()?.deref();
pool.validate_tick_address(
&ctx.accounts.tick_lower_state.key(),
tick_lower.bump,
tick_lower.tick,
)?;
let tick_upper = *ctx.accounts.tick_upper_state.load()?.deref();
pool.validate_tick_address(
&ctx.accounts.tick_upper_state.key(),
tick_upper.bump,
tick_upper.tick,
)?;
let bitmap_lower_state = AccountLoader::<TickBitmapState>::try_from(
&ctx.accounts.bitmap_lower_state.to_account_info(),
)?;
pool.validate_bitmap_address(
&ctx.accounts.bitmap_lower_state.key(),
bitmap_lower_state.load()?.bump,
tick_bitmap::position(tick_lower.tick / pool.tick_spacing as i32).word_pos,
)?;
let bitmap_upper_state = AccountLoader::<TickBitmapState>::try_from(
&ctx.accounts.bitmap_upper_state.to_account_info(),
)?;
pool.validate_bitmap_address(
&ctx.accounts.bitmap_upper_state.key(),
bitmap_upper_state.load()?.bump,
tick_bitmap::position(tick_upper.tick / pool.tick_spacing as i32).word_pos,
)?;
let position_state = AccountLoader::<PositionState>::try_from(
&ctx.accounts.position_state.to_account_info(),
)?;
pool.validate_position_address(
&ctx.accounts.position_state.key(),
position_state.load()?.bump,
&ctx.accounts.recipient.key(),
tick_lower.tick,
tick_upper.tick,
)?;
let last_observation_state = AccountLoader::<ObservationState>::try_from(
&ctx.accounts.last_observation_state.to_account_info(),
)?;
pool.validate_observation_address(
&last_observation_state.key(),
last_observation_state.load()?.bump,
false,
)?;
require!(pool.unlocked, ErrorCode::LOK);
pool.unlocked = false;
assert!(amount > 0);
let (amount_0_int, amount_1_int) = _modify_position(
i64::try_from(amount).unwrap(),
pool.deref_mut(),
&position_state,
&ctx.accounts.tick_lower_state,
&ctx.accounts.tick_upper_state,
&bitmap_lower_state,
&bitmap_upper_state,
&last_observation_state,
ctx.remaining_accounts,
)?;
let amount_0 = amount_0_int as u64;
let amount_1 = amount_1_int as u64;
let balance_0_before = if amount_0 > 0 {
ctx.accounts.vault_0.amount
} else {
0
};
let balance_1_before = if amount_1 > 0 {
ctx.accounts.vault_1.amount
} else {
0
};
drop(pool);
let mint_callback_ix = cyclos_core::instruction::MintCallback {
amount_0_owed: amount_0,
amount_1_owed: amount_1,
};
let ix = Instruction::new_with_bytes(
ctx.accounts.callback_handler.key(),
&mint_callback_ix.data(),
ctx.accounts.to_account_metas(None),
);
solana_program::program::invoke(&ix, &ctx.accounts.to_account_infos())?;
ctx.accounts.vault_0.reload()?;
ctx.accounts.vault_1.reload()?;
if amount_0 > 0 {
require!(
balance_0_before + amount_0 <= ctx.accounts.vault_0.amount,
ErrorCode::M0
);
}
if amount_1 > 0 {
require!(
balance_1_before + amount_1 <= ctx.accounts.vault_1.amount,
ErrorCode::M1
);
}
emit!(MintEvent {
pool_state: ctx.accounts.pool_state.key(),
sender: ctx.accounts.minter.key(),
owner: ctx.accounts.recipient.key(),
tick_lower: tick_lower.tick,
tick_upper: tick_upper.tick,
amount,
amount_0,
amount_1
});
ctx.accounts.pool_state.load_mut()?.unlocked = true;
Ok(())
}
/// Burn liquidity from the sender and account tokens owed for the liquidity to the position.
/// Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 (poke).
/// Fees must be collected separately via a call to #collect
///
/// # Arguments
///
/// * `ctx` - Holds position and other validated accounts need to burn liquidity
/// * `amount` - Amount of liquidity to be burned
///
pub fn burn<'a, 'b, 'c, 'info>(
ctx: Context<'a, 'b, 'c, 'info, BurnContext<'info>>,
amount: u64,
) -> Result<()> {
let pool_state =
AccountLoader::<PoolState>::try_from(&ctx.accounts.pool_state.to_account_info())?;
let mut pool = pool_state.load_mut()?;
let tick_lower_state =
AccountLoader::<TickState>::try_from(&ctx.accounts.tick_lower_state.to_account_info())?;
let tick_lower = *tick_lower_state.load()?.deref();
pool.validate_tick_address(
&ctx.accounts.tick_lower_state.key(),
tick_lower.bump,
tick_lower.tick,
)?;
let tick_upper_state =
AccountLoader::<TickState>::try_from(&ctx.accounts.tick_upper_state.to_account_info())?;
let tick_upper = *tick_upper_state.load()?.deref();
pool.validate_tick_address(
&ctx.accounts.tick_upper_state.key(),
tick_upper.bump,
tick_upper.tick,
)?;
let bitmap_lower_state = AccountLoader::<TickBitmapState>::try_from(
&ctx.accounts.bitmap_lower_state.to_account_info(),
)?;
pool.validate_bitmap_address(
&ctx.accounts.bitmap_lower_state.key(),
bitmap_lower_state.load()?.bump,
tick_bitmap::position(tick_lower.tick / pool.tick_spacing as i32).word_pos,
)?;
let bitmap_upper_state = AccountLoader::<TickBitmapState>::try_from(
&ctx.accounts.bitmap_upper_state.to_account_info(),
)?;
pool.validate_bitmap_address(
&ctx.accounts.bitmap_upper_state.key(),
bitmap_upper_state.load()?.bump,
tick_bitmap::position(tick_upper.tick / pool.tick_spacing as i32).word_pos,
)?;
let position_state = AccountLoader::<PositionState>::try_from(
&ctx.accounts.position_state.to_account_info(),
)?;
pool.validate_position_address(
&ctx.accounts.position_state.key(),
position_state.load()?.bump,
&ctx.accounts.owner.key(),
tick_lower.tick,
tick_upper.tick,
)?;
let last_observation_state = AccountLoader::<ObservationState>::try_from(
&ctx.accounts.last_observation_state.to_account_info(),
)?;
pool.validate_observation_address(
&ctx.accounts.last_observation_state.key(),
last_observation_state.load()?.bump,
false,
)?;
msg!("accounts validated");
require!(pool.unlocked, ErrorCode::LOK);
pool.unlocked = false;
let (amount_0_int, amount_1_int) = _modify_position(
-i64::try_from(amount).unwrap(),
pool.deref_mut(),
&ctx.accounts.position_state,
&tick_lower_state,
&tick_upper_state,
&bitmap_lower_state,
&bitmap_upper_state,
&last_observation_state,
ctx.remaining_accounts,
)?;
let amount_0 = (-amount_0_int) as u64;
let amount_1 = (-amount_1_int) as u64;
if amount_0 > 0 || amount_1 > 0 {
let mut position_state = ctx.accounts.position_state.load_mut()?;
position_state.tokens_owed_0 += amount_0;
position_state.tokens_owed_1 += amount_1;
}
emit!(BurnEvent {
pool_state: ctx.accounts.pool_state.key(),
owner: ctx.accounts.owner.key(),
tick_lower: tick_lower.tick,
tick_upper: tick_lower.tick,
amount,
amount_0,
amount_1,
});
pool.unlocked = true;
Ok(())
}
/// Collects tokens owed to a position.
///
/// Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token_0 or only token_1, amount_0_requested or
/// amount_1_requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. u64::MAX. Tokens owed may be from accumulated swap fees or burned liquidity.
///
/// # Arguments
///
/// * `amount_0_requested` - How much token_0 should be withdrawn from the fees owed
/// * `amount_1_requested` - How much token_1 should be withdrawn from the fees owed
///
pub fn collect(
ctx: Context<CollectContext>,
amount_0_requested: u64,
amount_1_requested: u64,
) -> Result<()> {
let pool_state =
AccountLoader::<PoolState>::try_from(&ctx.accounts.pool_state.to_account_info())?;
let mut pool = pool_state.load_mut()?;
let tick_lower_state =
AccountLoader::<TickState>::try_from(&ctx.accounts.tick_lower_state.to_account_info())?;
let tick_lower = *tick_lower_state.load()?.deref();
pool.validate_tick_address(
&ctx.accounts.tick_lower_state.key(),
tick_lower.bump,
tick_lower.tick,
)?;
let tick_upper_state =
AccountLoader::<TickState>::try_from(&ctx.accounts.tick_upper_state.to_account_info())?;
let tick_upper = *tick_upper_state.load()?.deref();
pool.validate_tick_address(
&ctx.accounts.tick_upper_state.key(),
tick_upper.bump,
tick_upper.tick,
)?;
let position_state = AccountLoader::<PositionState>::try_from(
&ctx.accounts.position_state.to_account_info(),
)?;
pool.validate_position_address(
&ctx.accounts.position_state.key(),
position_state.load()?.bump,
&ctx.accounts.owner.key(),
tick_lower.tick,
tick_upper.tick,
)?;
require!(pool.unlocked, ErrorCode::LOK);
pool.unlocked = false;
let mut position = position_state.load_mut()?;
let amount_0 = amount_0_requested.min(position.tokens_owed_0);
let amount_1 = amount_1_requested.min(position.tokens_owed_1);
let pool_state_seeds = [
&POOL_SEED.as_bytes(),
&pool.token_0.to_bytes() as &[u8],
&pool.token_1.to_bytes() as &[u8],
&pool.fee.to_be_bytes(),
&[pool.bump],
];
drop(pool);
if amount_0 > 0 {
position.tokens_owed_0 -= amount_0;
token::transfer(
CpiContext::new_with_signer(
ctx.accounts.token_program.to_account_info().clone(),
token::Transfer {
from: ctx.accounts.vault_0.to_account_info().clone(),
to: ctx.accounts.recipient_wallet_0.to_account_info().clone(),
authority: pool_state.to_account_info().clone(),
},
&[&pool_state_seeds[..]],
),
amount_0,
)?;
}
if amount_1 > 0 {
position.tokens_owed_1 -= amount_1;
token::transfer(
CpiContext::new_with_signer(
ctx.accounts.token_program.to_account_info().clone(),
token::Transfer {
from: ctx.accounts.vault_1.to_account_info().clone(),
to: ctx.accounts.recipient_wallet_1.to_account_info().clone(),
authority: pool_state.to_account_info().clone(),
},
&[&pool_state_seeds[..]],
),
amount_1,
)?;
}
emit!(CollectEvent {
pool_state: pool_state.key(),
owner: ctx.accounts.owner.key(),
tick_lower: tick_lower.tick,
tick_upper: tick_upper.tick,
amount_0,
amount_1,
});
pool_state.load_mut()?.unlocked = true;
Ok(())
}
// ---------------------------------------------------------------------
// 4. Swap instructions
pub struct SwapCache {
// the protocol fee for the input token
pub fee_protocol: u8,
// liquidity at the beginning of the swap
pub liquidity_start: u64,
// the timestamp of the current block
pub block_timestamp: u32,
// the current value of the tick accumulator, computed only if we cross an initialized tick
pub tick_cumulative: i64,
// the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick
pub seconds_per_liquidity_cumulative_x32: u64,
// whether we've computed and cached the above two accumulators
pub computed_latest_observation: bool,
}
// the top level state of the swap, the results of which are recorded in storage at the end
#[derive(Debug)]
pub struct SwapState {
// the amount remaining to be swapped in/out of the input/output asset
pub amount_specified_remaining: i64,
// the amount already swapped out/in of the output/input asset
pub amount_calculated: i64,
// current sqrt(price)
pub sqrt_price_x32: u64,
// the tick associated with the current price
pub tick: i32,
// the global fee growth of the input token
pub fee_growth_global_x32: u64,
// amount of input token paid as protocol fee
pub protocol_fee: u64,
// the current liquidity in range
pub liquidity: u64,
}
#[derive(Default)]
struct StepComputations {
// the price at the beginning of the step
sqrt_price_start_x32: u64,
// the next tick to swap to from the current tick in the swap direction
tick_next: i32,
// whether tick_next is initialized or not
initialized: bool,
// sqrt(price) for the next tick (1/0)
sqrt_price_next_x32: u64,
// how much is being swapped in in this step
amount_in: u64,
// how much is being swapped out
amount_out: u64,
// how much fee is being paid in
fee_amount: u64,
}
/// Swap token_0 for token_1, or token_1 for token_0
///
/// Outstanding tokens must be paid in #swap_callback
///
/// # Arguments
///
/// * `ctx` - Accounts required for the swap. Remaining accounts should contain each bitmap leading to
/// the end tick, and each tick being flipped
/// account leading to the destination tick
/// * `deadline` - The time by which the transaction must be included to effect the change
/// * `amount_specified` - The amount of the swap, which implicitly configures the swap as exact input (positive),
/// or exact output (negative)
/// * `sqrt_price_limit` - The Q32.32 sqrt price √P limit. If zero for one, the price cannot
/// be less than this value after the swap. If one for zero, the price cannot be greater than
/// this value after the swap.
///
pub fn swap(
ctx: Context<SwapContext>,
amount_specified: i64,
sqrt_price_limit_x32: u64,
) -> Result<()> {
require!(amount_specified != 0, ErrorCode::AS);
let factory_state =
AccountLoader::<FactoryState>::try_from(&ctx.accounts.factory_state.to_account_info())?;
let pool_loader =
AccountLoader::<PoolState>::try_from(&ctx.accounts.pool_state.to_account_info())?;