-
Notifications
You must be signed in to change notification settings - Fork 55
/
lib.rs
2238 lines (2096 loc) · 86.7 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
use std::convert::TryInto;
use std::fmt;
use std::collections::{HashMap, HashSet};
use degen_swap::degen::{global_get_degen, global_set_degen, DegenTrait};
use degen_swap::DegenSwapPool;
use near_contract_standards::storage_management::{
StorageBalance, StorageBalanceBounds, StorageManagement,
};
use near_sdk::serde::{Deserialize, Serialize};
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::{LookupMap, UnorderedSet, Vector, UnorderedMap};
use near_sdk::json_types::{ValidAccountId, U128};
use near_sdk::{
assert_one_yocto, env, log, near_bindgen, AccountId, Balance, PanicOnDefault, Promise,
PromiseResult, StorageUsage, BorshStorageKey, PromiseOrValue, ext_contract, Gas
};
use utils::{NO_DEPOSIT, GAS_FOR_BASIC_OP};
use crate::account_deposit::*;
pub use crate::action::{SwapAction, SwapByOutputAction, Action, ActionResult, get_tokens_in_actions, assert_all_same_action_type};
use crate::errors::*;
use crate::admin_fee::AdminFees;
use crate::pool::Pool;
use crate::simple_pool::SimplePool;
use crate::stable_swap::StableSwapPool;
use crate::rated_swap::{RatedSwapPool, rate::{RateTrait, global_get_rate, global_set_rate}};
use crate::utils::{check_token_duplicates, pair_rated_price_to_vec_u8, TokenCache};
pub use crate::custom_keys::*;
pub use crate::views::{PoolInfo, ShadowRecordInfo, RatedPoolInfo, StablePoolInfo, ContractMetadata, RatedTokenInfo, DegenTokenInfo, AddLiquidityPrediction, RefStorageState};
pub use crate::token_receiver::{AddLiquidityInfo, VIRTUAL_ACC};
pub use crate::shadow_actions::*;
pub use crate::unit_lpt_cumulative_infos::*;
pub use crate::oracle::*;
pub use crate::degen_swap::*;
pub use crate::pool_limit_info::*;
pub use crate::client_echo_limit::*;
mod account_deposit;
mod action;
mod errors;
mod admin_fee;
mod legacy;
mod multi_fungible_token;
mod owner;
mod pool;
mod simple_pool;
mod stable_swap;
mod rated_swap;
mod degen_swap;
mod oracle;
mod storage_impl;
mod token_receiver;
mod utils;
mod views;
mod custom_keys;
mod shadow_actions;
mod unit_lpt_cumulative_infos;
mod pool_limit_info;
mod client_echo_limit;
mod donation;
mod event;
near_sdk::setup_alloc!();
#[derive(BorshStorageKey, BorshSerialize)]
pub(crate) enum StorageKey {
Pools,
Accounts,
Shares { pool_id: u32 },
Whitelist,
Guardian,
AccountTokens {account_id: AccountId},
Frozenlist,
Referral,
ShadowRecord {account_id: AccountId},
UnitShareCumulativeInfo,
PoolLimit,
ClientEchoTokenIdWhitelistItem,
ClientEchoSenderIdWhitelistItem,
}
#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(crate = "near_sdk::serde")]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
pub enum RunningState {
Running, Paused
}
impl fmt::Display for RunningState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
RunningState::Running => write!(f, "Running"),
RunningState::Paused => write!(f, "Paused"),
}
}
}
#[ext_contract(ext_self)]
pub trait SelfCallbacks {
fn update_token_rate_callback(&mut self, token_id: AccountId);
fn update_degen_token_price_callback(&mut self, token_id: AccountId);
fn batch_update_degen_token_by_price_oracle_callback(&mut self, token_id_decimals_map: HashMap<AccountId, u8>);
fn batch_update_degen_token_by_pyth_oracle_callback(&mut self, price_id_token_id_map: HashMap<pyth_oracle::PriceIdentifier, AccountId>);
}
#[near_bindgen]
#[derive(BorshSerialize, BorshDeserialize, PanicOnDefault)]
pub struct Contract {
/// Account of the owner.
owner_id: AccountId,
/// Account of the boost_farm contract.
boost_farm_id: AccountId,
/// Account of the burrowland contract.
burrowland_id: AccountId,
/// Admin fee rate in total fee.
admin_fee_bps: u32,
/// List of all the pools.
pools: Vector<Pool>,
/// Accounts registered, keeping track all the amounts deposited, storage and more.
accounts: LookupMap<AccountId, VAccount>,
/// Set of whitelisted tokens by "owner".
whitelisted_tokens: UnorderedSet<AccountId>,
/// Set of guardians.
guardians: UnorderedSet<AccountId>,
/// Running state
state: RunningState,
/// Set of frozenlist tokens
frozen_tokens: UnorderedSet<AccountId>,
/// Map of referrals
referrals: UnorderedMap<AccountId, u32>,
cumulative_info_record_interval_sec: u32,
unit_share_cumulative_infos: UnorderedMap<u64, VUnitShareCumulativeInfo>,
wnear_id: Option<AccountId>,
auto_whitelisted_postfix: HashSet<String>
}
#[near_bindgen]
impl Contract {
#[init]
pub fn new(owner_id: ValidAccountId, boost_farm_id: ValidAccountId, burrowland_id: ValidAccountId, exchange_fee: u32, referral_fee: u32) -> Self {
Self {
owner_id: owner_id.as_ref().clone(),
boost_farm_id: boost_farm_id.as_ref().clone(),
burrowland_id: burrowland_id.as_ref().clone(),
admin_fee_bps: exchange_fee + referral_fee,
pools: Vector::new(StorageKey::Pools),
accounts: LookupMap::new(StorageKey::Accounts),
whitelisted_tokens: UnorderedSet::new(StorageKey::Whitelist),
guardians: UnorderedSet::new(StorageKey::Guardian),
state: RunningState::Running,
frozen_tokens: UnorderedSet::new(StorageKey::Frozenlist),
referrals: UnorderedMap::new(StorageKey::Referral),
cumulative_info_record_interval_sec: 12 * 60, // 12 min
unit_share_cumulative_infos: UnorderedMap::new(StorageKey::UnitShareCumulativeInfo),
wnear_id: None,
auto_whitelisted_postfix: HashSet::new()
}
}
/// Adds new "Simple Pool" with given tokens and given fee.
/// Attached NEAR should be enough to cover the added storage.
#[payable]
pub fn add_simple_pool(&mut self, tokens: Vec<ValidAccountId>, fee: u32) -> u64 {
self.assert_contract_running();
check_token_duplicates(&tokens);
self.internal_add_pool(Pool::SimplePool(SimplePool::new(
self.pools.len() as u32,
tokens,
fee,
)))
}
/// Adds new "Stable Pool" with given tokens, decimals, fee and amp.
/// It is limited to owner or guardians, cause a complex and correct config is needed.
/// tokens: pool tokens in this stable swap.
/// decimals: each pool tokens decimal, needed to make them comparable.
/// fee: total fee of the pool, admin fee is inclusive.
/// amp_factor: algorithm parameter, decide how stable the pool will be.
#[payable]
pub fn add_stable_swap_pool(
&mut self,
tokens: Vec<ValidAccountId>,
decimals: Vec<u8>,
fee: u32,
amp_factor: u64,
) -> u64 {
assert!(self.is_owner_or_guardians(), "{}", ERR100_NOT_ALLOWED);
check_token_duplicates(&tokens);
self.internal_add_pool(Pool::StableSwapPool(StableSwapPool::new(
self.pools.len() as u32,
tokens,
decimals,
amp_factor as u128,
fee,
)))
}
///
#[payable]
pub fn add_rated_swap_pool(
&mut self,
tokens: Vec<ValidAccountId>,
decimals: Vec<u8>,
fee: u32,
amp_factor: u64,
) -> u64 {
assert!(self.is_owner_or_guardians(), "{}", ERR100_NOT_ALLOWED);
check_token_duplicates(&tokens);
self.internal_add_pool(Pool::RatedSwapPool(RatedSwapPool::new(
self.pools.len() as u32,
tokens,
decimals,
amp_factor as u128,
fee,
)))
}
#[payable]
pub fn add_degen_swap_pool(
&mut self,
tokens: Vec<ValidAccountId>,
decimals: Vec<u8>,
fee: u32,
amp_factor: u64,
) -> u64 {
assert!(self.is_owner_or_guardians(), "{}", ERR100_NOT_ALLOWED);
check_token_duplicates(&tokens);
self.internal_add_pool(Pool::DegenSwapPool(DegenSwapPool::new(
self.pools.len() as u32,
tokens,
decimals,
amp_factor as u128,
fee,
)))
}
#[payable]
pub fn execute_actions_in_va(
&mut self,
use_tokens: HashMap<AccountId, U128>,
actions: Vec<Action>,
referral_id: Option<ValidAccountId>,
) -> HashMap<AccountId, U128> {
self.assert_contract_running();
assert_ne!(actions.len(), 0, "{}", ERR72_AT_LEAST_ONE_SWAP);
let sender_id = env::predecessor_account_id();
let mut account = self.internal_unwrap_account(&sender_id);
// Validate that all tokens are whitelisted if no deposit (e.g. trade with access key).
if env::attached_deposit() == 0 {
for action in &actions {
for token in action.tokens() {
assert!(
account.get_balance(&token).is_some()
|| self.is_whitelisted_token(&token),
"{}",
// [AUDIT_05]
ERR27_DEPOSIT_NEEDED
);
}
}
}
let mut virtual_account: Account = Account::new(&String::from(VIRTUAL_ACC));
let referral_info :Option<(AccountId, u32)> = referral_id
.as_ref().and_then(|rid| self.referrals.get(rid.as_ref()))
.map(|fee| (referral_id.unwrap().into(), fee));
for (use_token, use_amount) in use_tokens.iter() {
account.withdraw(use_token, use_amount.0);
virtual_account.deposit(use_token, use_amount.0);
}
let _ = self.internal_execute_actions(
&mut virtual_account,
&referral_info,
&actions,
ActionResult::None,
);
let mut result = HashMap::new();
for (token, amount) in virtual_account.tokens.to_vec() {
if amount > 0 {
account.deposit(&token, amount);
result.insert(token, amount.into());
}
}
virtual_account.tokens.clear();
self.internal_save_account(&sender_id, account);
result
}
/// [AUDIT_03_reject(NOPE action is allowed by design)]
/// [AUDIT_04]
/// Executes generic set of actions.
/// If referrer provided, pays referral_fee to it.
/// If no attached deposit, outgoing tokens used in swaps must be whitelisted.
#[payable]
pub fn execute_actions(
&mut self,
actions: Vec<Action>,
referral_id: Option<ValidAccountId>,
) -> ActionResult {
self.assert_contract_running();
assert_ne!(actions.len(), 0, "{}", ERR72_AT_LEAST_ONE_SWAP);
let sender_id = env::predecessor_account_id();
let mut account = self.internal_unwrap_account(&sender_id);
// Validate that all tokens are whitelisted if no deposit (e.g. trade with access key).
if env::attached_deposit() == 0 {
for action in &actions {
for token in action.tokens() {
assert!(
account.get_balance(&token).is_some()
|| self.is_whitelisted_token(&token),
"{}",
// [AUDIT_05]
ERR27_DEPOSIT_NEEDED
);
}
}
}
let referral_info :Option<(AccountId, u32)> = referral_id
.as_ref().and_then(|rid| self.referrals.get(rid.as_ref()))
.map(|fee| (referral_id.unwrap().into(), fee));
let result =
self.internal_execute_actions(&mut account, &referral_info, &actions, ActionResult::None);
self.internal_save_account(&sender_id, account);
result
}
/// Execute set of swap actions between pools.
/// If referrer provided, pays referral_fee to it.
/// If no attached deposit, outgoing tokens used in swaps must be whitelisted.
#[payable]
pub fn swap(&mut self, actions: Vec<SwapAction>, referral_id: Option<ValidAccountId>) -> U128 {
U128(
self.execute_actions(
actions
.into_iter()
.map(|swap_action| Action::Swap(swap_action))
.collect(),
referral_id,
)
.to_amount(),
)
}
/// Execute set of swap_by_output actions between pools.
/// If referrer provided, pays referral_fee to it.
/// If no attached deposit, outgoing tokens used in swaps must be whitelisted.
#[payable]
pub fn swap_by_output(&mut self, actions: Vec<SwapByOutputAction>, referral_id: Option<ValidAccountId>) -> U128 {
U128(
self.execute_actions(
actions
.into_iter()
.map(|swap_by_output_action| Action::SwapByOutput(swap_by_output_action))
.collect(),
referral_id,
)
.to_amount(),
)
}
/// Add liquidity from already deposited amounts to given pool.
#[payable]
pub fn add_liquidity(
&mut self,
pool_id: u64,
amounts: Vec<U128>,
min_amounts: Option<Vec<U128>>,
) -> U128 {
self.assert_contract_running();
assert!(
env::attached_deposit() > 0,
"{}", ERR35_AT_LEAST_ONE_YOCTO
);
self.internal_update_unit_share_cumulative_info(pool_id);
let prev_storage = env::storage_usage();
let sender_id = env::predecessor_account_id();
let mut amounts: Vec<u128> = amounts.into_iter().map(|amount| amount.into()).collect();
let mut pool = self.pools.get(pool_id).expect(ERR85_NO_POOL);
// feature frozenlist
self.assert_no_frozen_tokens(pool.tokens());
// Add amounts given to liquidity first. It will return the balanced amounts.
let shares = pool.add_liquidity(
&sender_id,
&mut amounts,
false
);
if let Some(min_amounts) = min_amounts {
// Check that all amounts are above request min amounts in case of front running that changes the exchange rate.
for (amount, min_amount) in amounts.iter().zip(min_amounts.iter()) {
assert!(amount >= &min_amount.0, "{}", ERR86_MIN_AMOUNT);
}
}
// [AUDITION_AMENDMENT] 2.3.7 Code Optimization (I)
let mut deposits = self.internal_unwrap_account(&sender_id);
let tokens = pool.tokens();
// Subtract updated amounts from deposits. This will fail if there is not enough funds for any of the tokens.
for i in 0..tokens.len() {
deposits.withdraw(&tokens[i], amounts[i]);
}
self.internal_save_account(&sender_id, deposits);
self.pools.replace(pool_id, &pool);
self.internal_check_storage(prev_storage);
U128(shares)
}
/// For stable swap pool, user can add liquidity with token's combination as his will.
/// But there is a little fee according to the bias of token's combination with the one in the pool.
/// pool_id: stable pool id. If simple pool is given, panic with unimplement.
/// amounts: token's combination (in pool tokens sequence) user want to add into the pool, a 0 means absent of that token.
/// min_shares: Slippage, if shares mint is less than it (cause of fee for too much bias), panic with ERR68_SLIPPAGE
#[payable]
pub fn add_stable_liquidity(
&mut self,
pool_id: u64,
amounts: Vec<U128>,
min_shares: U128,
) -> U128 {
self.assert_contract_running();
assert!(
env::attached_deposit() > 0,
"{}", ERR35_AT_LEAST_ONE_YOCTO
);
self.internal_update_unit_share_cumulative_info(pool_id);
let prev_storage = env::storage_usage();
let sender_id = env::predecessor_account_id();
let amounts: Vec<u128> = amounts.into_iter().map(|amount| amount.into()).collect();
let mut pool = self.pools.get(pool_id).expect(ERR85_NO_POOL);
// feature frozenlist
self.assert_no_frozen_tokens(pool.tokens());
// Add amounts given to liquidity first. It will return the balanced amounts.
let mint_shares = pool.add_stable_liquidity(
&sender_id,
&amounts,
min_shares.into(),
AdminFees::new(self.admin_fee_bps),
false
);
pool.assert_tvl_not_exceed_limit(pool_id);
// [AUDITION_AMENDMENT] 2.3.7 Code Optimization (I)
let mut deposits = self.internal_unwrap_account(&sender_id);
let tokens = pool.tokens();
// Subtract amounts from deposits. This will fail if there is not enough funds for any of the tokens.
for i in 0..tokens.len() {
deposits.withdraw(&tokens[i], amounts[i]);
}
self.internal_save_account(&sender_id, deposits);
self.pools.replace(pool_id, &pool);
self.internal_check_storage(prev_storage);
mint_shares.into()
}
// #[payable]
// pub fn add_rated_liquidity(
// &mut self,
// pool_id: u64,
// amounts: Vec<U128>,
// min_shares: U128,
// ) -> U128 {
// self.add_stable_liquidity(pool_id, amounts, min_shares)
// }
/// Remove liquidity from the pool and add tokens into user internal account.
#[payable]
pub fn remove_liquidity(&mut self, pool_id: u64, shares: U128, min_amounts: Vec<U128>) -> Vec<U128> {
assert_one_yocto();
self.assert_contract_running();
self.internal_update_unit_share_cumulative_info(pool_id);
let sender_id = env::predecessor_account_id();
let mut pool = self.pools.get(pool_id).expect(ERR85_NO_POOL);
let mut deposits = self.internal_unwrap_account(&sender_id);
if let Some(record) = deposits.get_shadow_record(pool_id) {
assert!(shares.0 <= record.free_shares(pool.share_balances(&sender_id)), "Not enough free shares");
}
// feature frozenlist
self.assert_no_frozen_tokens(pool.tokens());
let amounts = pool.remove_liquidity(
&sender_id,
shares.into(),
min_amounts
.into_iter()
.map(|amount| amount.into())
.collect(),
false
);
self.pools.replace(pool_id, &pool);
let tokens = pool.tokens();
for i in 0..tokens.len() {
deposits.deposit(&tokens[i], amounts[i]);
}
self.internal_save_account(&sender_id, deposits);
amounts
.into_iter()
.map(|amount| amount.into())
.collect()
}
/// For stable swap pool, LP can use it to remove liquidity with given token amount and distribution.
/// pool_id: the stable swap pool id. If simple pool is given, panic with Unimplement.
/// amounts: Each tokens (in pool tokens sequence) amounts user want get, a 0 means user don't want to get that token back.
/// max_burn_shares: This is slippage protection, if user request would burn shares more than it, panic with ERR68_SLIPPAGE
#[payable]
pub fn remove_liquidity_by_tokens(
&mut self, pool_id: u64,
amounts: Vec<U128>,
max_burn_shares: U128
) -> U128 {
assert_one_yocto();
self.assert_contract_running();
self.internal_update_unit_share_cumulative_info(pool_id);
let sender_id = env::predecessor_account_id();
let mut pool = self.pools.get(pool_id).expect(ERR85_NO_POOL);
let mut deposits = self.internal_unwrap_account(&sender_id);
let free_shares = if let Some(record) = deposits.get_shadow_record(pool_id) {
record.free_shares(pool.share_balances(&sender_id))
} else {
pool.share_balances(&sender_id)
};
// feature frozenlist
self.assert_no_frozen_tokens(pool.tokens());
let burn_shares = pool.remove_liquidity_by_tokens(
&sender_id,
amounts
.clone()
.into_iter()
.map(|amount| amount.into())
.collect(),
max_burn_shares.into(),
AdminFees::new(self.admin_fee_bps),
false
);
assert!(burn_shares <= free_shares, "Not enough free shares");
self.pools.replace(pool_id, &pool);
let tokens = pool.tokens();
for i in 0..tokens.len() {
deposits.deposit(&tokens[i], amounts[i].into());
}
self.internal_save_account(&sender_id, deposits);
burn_shares.into()
}
/// anyone can trigger an update for some rated token
pub fn update_token_rate(& self, token_id: ValidAccountId) -> PromiseOrValue<bool> {
let caller = env::predecessor_account_id();
let token_id: AccountId = token_id.into();
if let Some(rate) = global_get_rate(&token_id) {
log!("Caller {} invokes token {} rait async-update.", caller, token_id);
rate.async_update().then(ext_self::update_token_rate_callback(
token_id,
&env::current_account_id(),
NO_DEPOSIT,
GAS_FOR_BASIC_OP,
)).into()
} else {
log!("Caller {} invokes token {} rait async-update but it is not a valid token.", caller, token_id);
PromiseOrValue::Value(true)
}
}
/// the async return of update_token_rate
#[private]
pub fn update_token_rate_callback(&mut self, token_id: AccountId) {
let cross_call_result = if env::promise_results_count() == 1 {
let cross_call_result = match env::promise_result(0) {
PromiseResult::Successful(result) => result,
_ => env::panic(ERR124_CROSS_CALL_FAILED.as_bytes()),
};
cross_call_result
} else {
// Only SfraxRate + pyth
assert_eq!(env::promise_results_count(), 2, "{}", ERR123_TWO_PROMISE_RESULT);
let cross_call_result1 = match env::promise_result(0) {
PromiseResult::Successful(result) => result,
_ => env::panic(ERR124_CROSS_CALL_FAILED.as_bytes()),
};
let cross_call_result2 = match env::promise_result(1) {
PromiseResult::Successful(result) => result,
_ => env::panic(ERR124_CROSS_CALL_FAILED.as_bytes()),
};
pair_rated_price_to_vec_u8(cross_call_result1, cross_call_result2)
};
if let Some(mut rate) = global_get_rate(&token_id) {
let new_rate = rate.set(&cross_call_result);
global_set_rate(&token_id, &rate);
log!(
"Token {} got new rate {} from cross-contract call.",
token_id, new_rate
);
}
}
/// anyone can trigger a batch update for degen tokens
///
/// # Arguments
///
/// * `token_ids` - List of token IDs.
pub fn batch_update_degen_token_price(&self, token_ids: Vec<ValidAccountId>) {
internal_batch_update_degen_token_price(token_ids.into_iter().map(|v| v.into()).collect());
}
/// anyone can trigger an update for some degen token
pub fn update_degen_token_price(& self, token_id: ValidAccountId) {
let caller = env::predecessor_account_id();
let token_id: AccountId = token_id.into();
let degen = global_get_degen(&token_id);
log!("Caller {} invokes token {} rait async-update.", caller, token_id);
degen.sync_token_price(&token_id);
}
/// the async return of update_degen_token_price
#[private]
pub fn update_degen_token_price_callback(&mut self, token_id: AccountId) {
if let Some(cross_call_result) = near_sdk::promise_result_as_success() {
let mut degen = global_get_degen(&token_id);
let new_degen = degen.set_price(&cross_call_result);
global_set_degen(&token_id, °en);
log!(
"Token {} got new degen {} from cross-contract call.",
token_id, new_degen
);
}
}
}
/// Internal methods implementation.
impl Contract {
fn assert_contract_running(&self) {
match self.state {
RunningState::Running => (),
_ => env::panic(ERR51_CONTRACT_PAUSED.as_bytes()),
};
}
fn assert_no_frozen_tokens(&self, tokens: &[AccountId]) {
let frozens: Vec<&String> = tokens.iter()
.filter(
|token| self.frozen_tokens.contains(*token)
)
.collect();
assert_eq!(frozens.len(), 0, "{}", ERR52_FROZEN_TOKEN);
}
fn is_whitelisted_token(&self, token_id: &AccountId) -> bool {
self.whitelisted_tokens.contains(token_id) || self.auto_whitelisted_postfix.iter().any(|postfix| token_id.ends_with(postfix))
}
/// Check how much storage taken costs and refund the left over back.
/// Return the storage costs due to this call by far.
fn internal_check_storage(&self, prev_storage: StorageUsage) -> u128 {
let storage_cost = env::storage_usage()
.checked_sub(prev_storage)
.unwrap_or_default() as Balance
* env::storage_byte_cost();
let refund = env::attached_deposit()
.checked_sub(storage_cost)
.expect(
format!(
"ERR_STORAGE_DEPOSIT need {}, attatched {}",
storage_cost, env::attached_deposit()
).as_str()
);
if refund > 0 {
Promise::new(env::predecessor_account_id()).transfer(refund);
}
storage_cost
}
/// Adds given pool to the list and returns it's id.
/// If there is not enough attached balance to cover storage, fails.
/// If too much attached - refunds it back.
fn internal_add_pool(&mut self, mut pool: Pool) -> u64 {
let prev_storage = env::storage_usage();
let id = self.pools.len() as u64;
// exchange share was registered at creation time
pool.share_register(&env::current_account_id());
self.pools.push(&pool);
self.internal_check_storage(prev_storage);
id
}
fn get_degen_tokens_in_actions(&self, actions: &[Action]) -> HashSet<AccountId> {
let mut degen_tokens = HashSet::new();
actions.iter().for_each(|action| {
if let Pool::DegenSwapPool(p) = self.pools.get(action.get_pool_id()).expect(ERR85_NO_POOL) {
degen_tokens.extend(p.tokens().iter().cloned());
}
});
degen_tokens
}
/// Execute sequence of actions on given account. Modifies passed account.
/// Returns result of the last action.
fn internal_execute_actions(
&mut self,
account: &mut Account,
referral_info: &Option<(AccountId, u32)>,
actions: &[Action],
prev_result: ActionResult,
) -> ActionResult {
assert_all_same_action_type(actions);
// fronzen token feature
// [AUDITION_AMENDMENT] 2.3.8 Code Optimization (II)
self.assert_no_frozen_tokens(
&get_tokens_in_actions(actions)
.into_iter()
.map(|token| token)
.collect::<Vec<AccountId>>()
);
let mut result = prev_result;
match actions[0] {
Action::Swap(_) => {
for action in actions {
result = self.internal_execute_action(account, referral_info, action, result);
}
}
Action::SwapByOutput(_) => {
let mut prev_action: Option<&Action> = None;
for action in actions {
if let Some(U128(amount_out)) = action.get_amount_out() {
self.finalize_prev_swap_chain(account, prev_action, &result);
account.deposit(action.get_token_out(), amount_out);
} else {
assert!(prev_action.unwrap().get_token_in() == action.get_token_out());
}
result = self.internal_execute_action(account, referral_info, action, result);
prev_action = Some(action);
}
self.finalize_prev_swap_chain(account, prev_action, &result);
}
}
let degen_token_ids = self.get_degen_tokens_in_actions(actions).into_iter().collect::<Vec<_>>();
internal_batch_update_degen_token_price(degen_token_ids);
result
}
fn finalize_prev_swap_chain(&mut self, account: &mut Account, prev_action: Option<&Action>, prev_result: &ActionResult){
if prev_action.is_some() {
account.withdraw(prev_action.unwrap().get_token_in(), prev_result.to_amount());
}
}
/// Executes single action on given account. Modifies passed account. Returns a result based on type of action.
fn internal_execute_action(
&mut self,
account: &mut Account,
referral_info: &Option<(AccountId, u32)>,
action: &Action,
prev_result: ActionResult,
) -> ActionResult {
match action {
Action::Swap(swap_action) => {
let amount_in = swap_action
.amount_in
.map(|value| value.0)
.unwrap_or_else(|| prev_result.to_amount());
account.withdraw(&swap_action.token_in, amount_in);
let amount_out = self.internal_pool_swap(
swap_action.pool_id,
&swap_action.token_in,
amount_in,
&swap_action.token_out,
swap_action.min_amount_out.0,
referral_info,
);
account.deposit(&swap_action.token_out, amount_out);
// [AUDIT_02]
ActionResult::Amount(U128(amount_out))
}
Action::SwapByOutput(swap_by_output_action) => {
let amount_out = swap_by_output_action
.amount_out
.map(|value| value.0)
.unwrap_or_else(|| prev_result.to_amount());
let amount_in = self.internal_pool_swap_by_output(
swap_by_output_action.pool_id,
&swap_by_output_action.token_in,
amount_out,
&swap_by_output_action.token_out,
swap_by_output_action.max_amount_in.map(|v| v.0),
referral_info,
);
ActionResult::Amount(U128(amount_in))
}
}
}
/// Swaps given amount_in of token_in into token_out via given pool.
/// Should be at least min_amount_out or swap will fail (prevents front running and other slippage issues).
fn internal_pool_swap(
&mut self,
pool_id: u64,
token_in: &AccountId,
amount_in: u128,
token_out: &AccountId,
min_amount_out: u128,
referral_info: &Option<(AccountId, u32)>,
) -> u128 {
self.internal_update_unit_share_cumulative_info(pool_id);
let mut pool = self.pools.get(pool_id).expect(ERR85_NO_POOL);
let amount_out = pool.swap(
token_in,
amount_in,
token_out,
min_amount_out,
AdminFees {
admin_fee_bps: self.admin_fee_bps,
exchange_id: env::current_account_id(),
referral_info: referral_info.clone(),
},
false
);
self.pools.replace(pool_id, &pool);
amount_out
}
/// Swaps token_in into the given amount_out of token_out via a specified pool.
/// Should be at most max_amount_in or swap will fail (prevents front running and other slippage issues).
fn internal_pool_swap_by_output(
&mut self,
pool_id: u64,
token_in: &AccountId,
amount_out: u128,
token_out: &AccountId,
max_amount_in: Option<u128>,
referral_info: &Option<(AccountId, u32)>,
) -> u128 {
self.internal_update_unit_share_cumulative_info(pool_id);
let mut pool = self.pools.get(pool_id).expect(ERR85_NO_POOL);
let amount_in = pool.swap_by_output(
token_in,
amount_out,
token_out,
max_amount_in,
AdminFees {
admin_fee_bps: self.admin_fee_bps,
exchange_id: env::current_account_id(),
referral_info: referral_info.clone(),
},
false
);
self.pools.replace(pool_id, &pool);
amount_in
}
}
impl Contract {
fn internal_execute_actions_by_cache(
&self,
pool_cache: &mut HashMap<u64, Pool>,
token_cache: &mut TokenCache,
referral_info: &Option<(AccountId, u32)>,
actions: &[Action],
prev_result: ActionResult,
) {
assert_all_same_action_type(actions);
self.assert_no_frozen_tokens(
&get_tokens_in_actions(actions)
.into_iter()
.map(|token| token)
.collect::<Vec<AccountId>>()
);
let mut result = prev_result;
match actions[0] {
Action::Swap(_) => {
for action in actions {
result = self.internal_execute_action_by_cache(pool_cache, token_cache, referral_info, action, result);
}
}
Action::SwapByOutput(_) => {
let mut prev_action: Option<&Action> = None;
for action in actions {
if let Some(U128(amount_out)) = action.get_amount_out() {
self.finalize_prev_swap_chain_by_cache(token_cache, prev_action, &result);
token_cache.add(action.get_token_out(), amount_out);
} else {
assert!(prev_action.unwrap().get_token_in() == action.get_token_out());
}
result = self.internal_execute_action_by_cache(pool_cache, token_cache, referral_info, action, result);
prev_action = Some(action);
}
self.finalize_prev_swap_chain_by_cache(token_cache, prev_action, &result);
}
}
}
fn finalize_prev_swap_chain_by_cache(&self, token_cache: &mut TokenCache, prev_action: Option<&Action>, prev_result: &ActionResult){
if prev_action.is_some() {
token_cache.sub(prev_action.unwrap().get_token_in(), prev_result.to_amount());
}
}
fn internal_execute_action_by_cache(
&self,
pool_cache: &mut HashMap<u64, Pool>,
token_cache: &mut TokenCache,
referral_info: &Option<(AccountId, u32)>,
action: &Action,
prev_result: ActionResult,
) -> ActionResult {
match action {
Action::Swap(swap_action) => {
let amount_in = swap_action
.amount_in
.map(|value| value.0)
.unwrap_or_else(|| prev_result.to_amount());
token_cache.sub(&swap_action.token_in, amount_in);
let amount_out = self.internal_pool_swap_by_cache(
pool_cache,
swap_action.pool_id,
&swap_action.token_in,
amount_in,
&swap_action.token_out,
0,
referral_info,
);
token_cache.add(&swap_action.token_out, amount_out);
ActionResult::Amount(U128(amount_out))
}
Action::SwapByOutput(swap_by_output_action) => {
let amount_out = swap_by_output_action
.amount_out
.map(|value| value.0)
.unwrap_or_else(|| prev_result.to_amount());
let amount_in = self.internal_pool_swap_by_output_by_cache(
pool_cache,
swap_by_output_action.pool_id,
&swap_by_output_action.token_in,
amount_out,
&swap_by_output_action.token_out,
swap_by_output_action.max_amount_in.map(|v| v.0),
referral_info,
);
ActionResult::Amount(U128(amount_in))
}
}
}
fn internal_pool_swap_by_cache(
&self,
pool_cache: &mut HashMap<u64, Pool>,
pool_id: u64,
token_in: &AccountId,
amount_in: u128,
token_out: &AccountId,
min_amount_out: u128,
referral_info: &Option<(AccountId, u32)>,
) -> u128 {
let mut pool = pool_cache.remove(&pool_id).unwrap_or(self.pools.get(pool_id).expect(ERR85_NO_POOL));
let amount_out = pool.swap(
token_in,
amount_in,
token_out,
min_amount_out,
AdminFees {
admin_fee_bps: self.admin_fee_bps,
exchange_id: env::current_account_id(),
referral_info: referral_info.clone(),
},
true
);
pool_cache.insert(pool_id, pool);
amount_out
}
fn internal_pool_swap_by_output_by_cache(
&self,
pool_cache: &mut HashMap<u64, Pool>,
pool_id: u64,
token_in: &AccountId,
amount_out: u128,
token_out: &AccountId,
max_amount_in: Option<u128>,
referral_info: &Option<(AccountId, u32)>,
) -> u128 {
let mut pool = pool_cache.remove(&pool_id).unwrap_or(self.pools.get(pool_id).expect(ERR85_NO_POOL));
let amount_in = pool.swap_by_output(
token_in,
amount_out,
token_out,
max_amount_in,
AdminFees {
admin_fee_bps: self.admin_fee_bps,
exchange_id: env::current_account_id(),
referral_info: referral_info.clone(),
},
false
);
pool_cache.insert(pool_id, pool);
amount_in