forked from ref-finance/ref-contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
1526 lines (1428 loc) · 58.2 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 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};
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
};
use utils::{NO_DEPOSIT, GAS_FOR_BASIC_OP};
use crate::account_deposit::{VAccount, Account};
pub use crate::action::SwapAction;
use crate::action::{Action, ActionResult};
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;
pub use crate::custom_keys::*;
pub use crate::views::{PoolInfo, RatedPoolInfo, ContractMetadata, RatedTokenInfo};
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 storage_impl;
mod token_receiver;
mod utils;
mod views;
mod custom_keys;
near_sdk::setup_alloc!();
#[derive(BorshStorageKey, BorshSerialize)]
pub(crate) enum StorageKey {
Pools,
Accounts,
Shares { pool_id: u32 },
Whitelist,
Guardian,
AccountTokens {account_id: AccountId},
}
#[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);
}
#[near_bindgen]
#[derive(BorshSerialize, BorshDeserialize, PanicOnDefault)]
pub struct Contract {
/// Account of the owner.
owner_id: AccountId,
/// Exchange fee, that goes to exchange itself (managed by governance).
exchange_fee: u32,
/// Referral fee, that goes to referrer in the call.
referral_fee: 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,
}
#[near_bindgen]
impl Contract {
#[init]
pub fn new(owner_id: ValidAccountId, exchange_fee: u32, referral_fee: u32) -> Self {
Self {
owner_id: owner_id.as_ref().clone(),
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,
}
}
/// 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,
0,
0,
)))
}
/// 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,
)))
}
/// [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();
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.whitelisted_tokens.contains(&token),
"{}",
// [AUDIT_05]
ERR27_DEPOSIT_NEEDED
);
}
}
}
let referral_id = referral_id.map(|r| r.into());
let result =
self.internal_execute_actions(&mut account, &referral_id, &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 {
self.assert_contract_running();
assert_ne!(actions.len(), 0, "{}", ERR72_AT_LEAST_ONE_SWAP);
U128(
self.execute_actions(
actions
.into_iter()
.map(|swap_action| Action::Swap(swap_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
);
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);
// Add amounts given to liquidity first. It will return the balanced amounts.
let shares = pool.add_liquidity(
&sender_id,
&mut amounts,
);
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);
}
}
let mut deposits = self.internal_unwrap_or_default_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
);
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);
// 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.exchange_fee),
);
let mut deposits = self.internal_unwrap_or_default_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 into general pool of liquidity.
#[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();
let prev_storage = env::storage_usage();
let sender_id = env::predecessor_account_id();
let mut pool = self.pools.get(pool_id).expect(ERR85_NO_POOL);
let amounts = pool.remove_liquidity(
&sender_id,
shares.into(),
min_amounts
.into_iter()
.map(|amount| amount.into())
.collect(),
);
self.pools.replace(pool_id, &pool);
let tokens = pool.tokens();
let mut deposits = self.internal_unwrap_or_default_account(&sender_id);
for i in 0..tokens.len() {
deposits.deposit(&tokens[i], amounts[i]);
}
// Freed up storage balance from LP tokens will be returned to near_balance.
if prev_storage > env::storage_usage() {
deposits.near_amount +=
(prev_storage - env::storage_usage()) as Balance * env::storage_byte_cost();
}
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();
let prev_storage = env::storage_usage();
let sender_id = env::predecessor_account_id();
let mut pool = self.pools.get(pool_id).expect(ERR85_NO_POOL);
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.exchange_fee),
);
self.pools.replace(pool_id, &pool);
let tokens = pool.tokens();
let mut deposits = self.internal_unwrap_or_default_account(&sender_id);
for i in 0..tokens.len() {
deposits.deposit(&tokens[i], amounts[i].into());
}
// Freed up storage balance from LP tokens will be returned to near_balance.
if prev_storage > env::storage_usage() {
deposits.near_amount +=
(prev_storage - env::storage_usage()) as Balance * env::storage_byte_cost();
}
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) {
assert_eq!(env::promise_results_count(), 1, "{}", ERR123_ONE_PROMISE_RESULT);
let cross_call_result = match env::promise_result(0) {
PromiseResult::Successful(result) => result,
_ => env::panic(ERR124_CROSS_CALL_FAILED.as_bytes()),
};
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
);
}
}
}
/// Internal methods implementation.
impl Contract {
fn assert_contract_running(&self) {
match self.state {
RunningState::Running => (),
_ => env::panic(ERR51_CONTRACT_PAUSED.as_bytes()),
};
}
/// Check how much storage taken costs and refund the left over back.
fn internal_check_storage(&self, prev_storage: StorageUsage) {
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);
}
}
/// 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
}
/// 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_id: &Option<AccountId>,
actions: &[Action],
prev_result: ActionResult,
) -> ActionResult {
let mut result = prev_result;
for action in actions {
result = self.internal_execute_action(account, referral_id, action, result);
}
result
}
/// 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_id: &Option<AccountId>,
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_id,
);
account.deposit(&swap_action.token_out, amount_out);
// [AUDIT_02]
ActionResult::Amount(U128(amount_out))
}
}
}
/// 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_id: &Option<AccountId>,
) -> u128 {
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 {
exchange_fee: self.exchange_fee,
exchange_id: env::current_account_id(),
referral_fee: self.referral_fee,
referral_id: referral_id.clone(),
},
);
self.pools.replace(pool_id, &pool);
amount_out
}
}
#[cfg(test)]
mod tests {
use std::convert::TryFrom;
use near_contract_standards::fungible_token::receiver::FungibleTokenReceiver;
use near_sdk::test_utils::{accounts, VMContextBuilder};
use near_sdk::{testing_env, Balance, MockedBlockchain};
use near_sdk_sim::to_yocto;
use super::*;
/// Creates contract and a pool with tokens with 0.3% of total fee.
fn setup_contract() -> (VMContextBuilder, Contract) {
let mut context = VMContextBuilder::new();
testing_env!(context.predecessor_account_id(accounts(0)).build());
let contract = Contract::new(accounts(0), 1600, 400);
(context, contract)
}
fn deposit_tokens(
context: &mut VMContextBuilder,
contract: &mut Contract,
account_id: ValidAccountId,
token_amounts: Vec<(ValidAccountId, Balance)>,
) {
if contract.storage_balance_of(account_id.clone()).is_none() {
testing_env!(context
.predecessor_account_id(account_id.clone())
.attached_deposit(to_yocto("1"))
.build());
contract.storage_deposit(None, None);
}
testing_env!(context
.predecessor_account_id(account_id.clone())
.attached_deposit(to_yocto("1"))
.build());
let tokens = token_amounts
.iter()
.map(|(token_id, _)| token_id.clone().into())
.collect();
testing_env!(context.attached_deposit(1).build());
contract.register_tokens(tokens);
for (token_id, amount) in token_amounts {
testing_env!(context
.predecessor_account_id(token_id)
.attached_deposit(1)
.build());
contract.ft_on_transfer(account_id.clone(), U128(amount), "".to_string());
}
}
fn create_pool_with_liquidity(
context: &mut VMContextBuilder,
contract: &mut Contract,
account_id: ValidAccountId,
token_amounts: Vec<(ValidAccountId, Balance)>,
) -> u64 {
let tokens = token_amounts
.iter()
.map(|(x, _)| x.clone())
.collect::<Vec<_>>();
testing_env!(context.predecessor_account_id(accounts(0)).attached_deposit(1).build());
contract.extend_whitelisted_tokens(tokens.clone());
testing_env!(context
.predecessor_account_id(account_id.clone())
.attached_deposit(env::storage_byte_cost() * 300)
.build());
let pool_id = contract.add_simple_pool(tokens, 25);
testing_env!(context
.predecessor_account_id(account_id.clone())
.attached_deposit(to_yocto("0.03"))
.build());
contract.storage_deposit(None, None);
deposit_tokens(context, contract, accounts(3), token_amounts.clone());
testing_env!(context
.predecessor_account_id(account_id.clone())
.attached_deposit(to_yocto("0.0007"))
.build());
contract.add_liquidity(
pool_id,
token_amounts.into_iter().map(|(_, x)| U128(x)).collect(),
None,
);
pool_id
}
fn swap(
contract: &mut Contract,
pool_id: u64,
token_in: ValidAccountId,
amount_in: Balance,
token_out: ValidAccountId,
) -> Balance {
contract
.swap(
vec![SwapAction {
pool_id,
token_in: token_in.into(),
amount_in: Some(U128(amount_in)),
token_out: token_out.into(),
min_amount_out: U128(1),
}],
None,
)
.0
}
#[test]
fn test_basics() {
let one_near = 10u128.pow(24);
let (mut context, mut contract) = setup_contract();
// add liquidity of (1,2) tokens
create_pool_with_liquidity(
&mut context,
&mut contract,
accounts(3),
vec![(accounts(1), to_yocto("5")), (accounts(2), to_yocto("10"))],
);
deposit_tokens(
&mut context,
&mut contract,
accounts(3),
vec![
(accounts(1), to_yocto("100")),
(accounts(2), to_yocto("100")),
],
);
deposit_tokens(&mut context, &mut contract, accounts(1), vec![]);
assert_eq!(
contract.get_deposit(accounts(3), accounts(1)),
to_yocto("100").into()
);
assert_eq!(
contract.get_deposit(accounts(3), accounts(2)),
to_yocto("100").into()
);
assert_eq!(
contract.get_pool_total_shares(0).0,
crate::utils::INIT_SHARES_SUPPLY
);
// Get price from pool :0 1 -> 2 tokens.
let expected_out = contract.get_return(0, accounts(1), one_near.into(), accounts(2));
assert_eq!(expected_out.0, 1663192997082117548978741);
testing_env!(context
.predecessor_account_id(accounts(3))
.attached_deposit(1)
.build());
let amount_out = swap(&mut contract, 0, accounts(1), one_near, accounts(2));
assert_eq!(amount_out, expected_out.0);
assert_eq!(
contract.get_deposit(accounts(3), accounts(1)).0,
99 * one_near
);
// transfer some of token_id 2 from acc 3 to acc 1.
testing_env!(context.predecessor_account_id(accounts(3)).build());
contract.mft_transfer(accounts(2).to_string(), accounts(1), U128(one_near), None);
assert_eq!(
contract.get_deposit(accounts(3), accounts(2)).0,
99 * one_near + amount_out
);
assert_eq!(contract.get_deposit(accounts(1), accounts(2)).0, one_near);
testing_env!(context
.predecessor_account_id(accounts(3))
.attached_deposit(to_yocto("0.0067"))
.build());
contract.mft_register(":0".to_string(), accounts(1));
testing_env!(context
.predecessor_account_id(accounts(3))
.attached_deposit(1)
.build());
// transfer 1m shares in pool 0 to acc 1.
contract.mft_transfer(":0".to_string(), accounts(1), U128(1_000_000), None);
testing_env!(context.predecessor_account_id(accounts(3)).build());
contract.remove_liquidity(
0,
contract.get_pool_shares(0, accounts(3)),
vec![1.into(), 2.into()],
);
// Exchange fees left in the pool as liquidity + 1m from transfer.
assert_eq!(
contract.get_pool_total_shares(0).0,
33336806279123620258 + 1_000_000
);
contract.withdraw(
accounts(1),
contract.get_deposit(accounts(3), accounts(1)),
None,
);
assert_eq!(contract.get_deposit(accounts(3), accounts(1)).0, 0);
}
/// Test liquidity management.
#[test]
fn test_liquidity() {
let (mut context, mut contract) = setup_contract();
deposit_tokens(
&mut context,
&mut contract,
accounts(3),
vec![
(accounts(1), to_yocto("100")),
(accounts(2), to_yocto("100")),
],
);
testing_env!(context
.predecessor_account_id(accounts(3))
.attached_deposit(to_yocto("1"))
.build());
let id = contract.add_simple_pool(vec![accounts(1), accounts(2)], 25);
testing_env!(context.attached_deposit(to_yocto("0.0007")).build());
contract.add_liquidity(id, vec![U128(to_yocto("50")), U128(to_yocto("10"))], None);
contract.add_liquidity(id, vec![U128(to_yocto("50")), U128(to_yocto("50"))], None);
testing_env!(context.attached_deposit(1).build());
contract.remove_liquidity(id, U128(to_yocto("1")), vec![U128(1), U128(1)]);
// Check that amounts add up to deposits.
let amounts = contract.get_pool(id).amounts;
let deposit1 = contract.get_deposit(accounts(3), accounts(1)).0;
let deposit2 = contract.get_deposit(accounts(3), accounts(2)).0;
assert_eq!(amounts[0].0 + deposit1, to_yocto("100"));
assert_eq!(amounts[1].0 + deposit2, to_yocto("100"));
}
/// Should deny creating a pool with duplicate tokens.
#[test]
#[should_panic(expected = "E92: token duplicated")]
fn test_deny_duplicate_tokens_pool() {
let (mut context, mut contract) = setup_contract();
create_pool_with_liquidity(
&mut context,
&mut contract,
accounts(3),
vec![(accounts(1), to_yocto("5")), (accounts(1), to_yocto("10"))],
);
}
/// Deny pool with a single token
#[test]
#[should_panic(expected = "E89: wrong token count")]
fn test_deny_single_token_pool() {
let (mut context, mut contract) = setup_contract();
create_pool_with_liquidity(
&mut context,
&mut contract,
accounts(3),
vec![(accounts(1), to_yocto("5"))],
);
}
/// Deny pool with a single token
#[test]
#[should_panic(expected = "E89: wrong token count")]
fn test_deny_too_many_tokens_pool() {
let (mut context, mut contract) = setup_contract();
create_pool_with_liquidity(
&mut context,
&mut contract,
accounts(3),
vec![
(accounts(1), to_yocto("5")),
(accounts(2), to_yocto("10")),
(accounts(3), to_yocto("10")),
],
);
}
#[test]
#[should_panic(expected = "E12: token not whitelisted")]
fn test_deny_send_malicious_token() {
let (mut context, mut contract) = setup_contract();
let acc = ValidAccountId::try_from("test_user").unwrap();
testing_env!(context
.predecessor_account_id(acc.clone())
.attached_deposit(to_yocto("1"))
.build());
contract.storage_deposit(Some(acc.clone()), None);
testing_env!(context
.predecessor_account_id(ValidAccountId::try_from("malicious").unwrap())
.build());
contract.ft_on_transfer(acc, U128(1_000), "".to_string());
}
#[test]
fn test_send_user_specific_token() {
let (mut context, mut contract) = setup_contract();
let acc = ValidAccountId::try_from("test_user").unwrap();
let custom_token = ValidAccountId::try_from("custom").unwrap();
testing_env!(context
.predecessor_account_id(acc.clone())
.attached_deposit(to_yocto("1"))
.build());
contract.storage_deposit(None, None);
testing_env!(context.attached_deposit(1).build());
contract.register_tokens(vec![custom_token.clone()]);
testing_env!(context.predecessor_account_id(custom_token.clone()).build());
contract.ft_on_transfer(acc.clone(), U128(1_000), "".to_string());
let prev = contract.storage_balance_of(acc.clone()).unwrap();
testing_env!(context
.predecessor_account_id(acc.clone())
.attached_deposit(1)
.build());
contract.withdraw(custom_token, U128(1_000), Some(true));
let new = contract.storage_balance_of(acc.clone()).unwrap();
// More available storage after withdrawing & unregistering the token.
assert!(new.available.0 > prev.available.0);
}
#[test]
#[should_panic(expected = "E68: slippage error")]
fn test_deny_min_amount() {
let (mut context, mut contract) = setup_contract();
create_pool_with_liquidity(
&mut context,
&mut contract,
accounts(3),
vec![(accounts(1), to_yocto("1")), (accounts(2), to_yocto("1"))],
);
let acc = ValidAccountId::try_from("test_user").unwrap();
deposit_tokens(
&mut context,
&mut contract,
acc.clone(),
vec![(accounts(1), 1_000_000)],
);
testing_env!(context
.predecessor_account_id(acc.clone())
.attached_deposit(1)
.build());
contract.swap(
vec![SwapAction {
pool_id: 0,
token_in: accounts(1).into(),
amount_in: Some(U128(1_000_000)),
token_out: accounts(2).into(),
min_amount_out: U128(1_000_000),
}],
None,
);
}
#[test]
fn test_second_storage_deposit_works() {
let (mut context, mut contract) = setup_contract();
testing_env!(context.attached_deposit(to_yocto("1")).build());
contract.storage_deposit(None, None);
testing_env!(context.attached_deposit(to_yocto("0.001")).build());
contract.storage_deposit(None, None);
}
#[test]
#[should_panic(expected = "E72: at least one swap")]
fn test_fail_swap_no_actions() {
let (mut context, mut contract) = setup_contract();
testing_env!(context.attached_deposit(to_yocto("1")).build());
contract.storage_deposit(None, None);
testing_env!(context.attached_deposit(1).build());
contract.swap(vec![], None);
}
/// Check that can not swap non whitelisted tokens when attaching 0 deposit (access key).
#[test]
#[should_panic(expected = "E27: attach 1yN to swap tokens not in whitelist")]
fn test_fail_swap_not_whitelisted() {
let (mut context, mut contract) = setup_contract();
deposit_tokens(
&mut context,
&mut contract,
accounts(0),
vec![(accounts(1), 2_000_000), (accounts(2), 1_000_000)],
);
create_pool_with_liquidity(
&mut context,
&mut contract,
accounts(0),
vec![(accounts(1), 1_000_000), (accounts(2), 1_000_000)],
);
testing_env!(context.attached_deposit(1).build());
contract.remove_whitelisted_tokens(vec![accounts(2)]);
testing_env!(context.attached_deposit(1).build());
contract.unregister_tokens(vec![accounts(2)]);
testing_env!(context.attached_deposit(0).build());
swap(&mut contract, 0, accounts(1), 10, accounts(2));
}
#[test]
fn test_roundtrip_swap() {
let (mut context, mut contract) = setup_contract();
create_pool_with_liquidity(
&mut context,
&mut contract,
accounts(3),
vec![(accounts(1), to_yocto("5")), (accounts(2), to_yocto("10"))],
);
let acc = ValidAccountId::try_from("test_user").unwrap();
deposit_tokens(
&mut context,
&mut contract,
acc.clone(),
vec![(accounts(1), 1_000_000)],
);
testing_env!(context
.predecessor_account_id(acc.clone())
.attached_deposit(1)
.build());
contract.swap(
vec![
SwapAction {
pool_id: 0,
token_in: accounts(1).into(),
amount_in: Some(U128(1_000)),
token_out: accounts(2).into(),
min_amount_out: U128(1),
},
SwapAction {
pool_id: 0,
token_in: accounts(2).into(),
amount_in: None,
token_out: accounts(1).into(),
min_amount_out: U128(1),
},
],
None,
);
// Roundtrip returns almost everything except 0.25% fee.
assert_eq!(contract.get_deposit(acc, accounts(1)).0, 1_000_000 - 6);
}
#[test]
#[should_panic(expected = "E14: LP already registered")]
fn test_lpt_transfer() {
// account(0) -- swap contract
// account(1) -- token0 contract
// account(2) -- token1 contract
// account(3) -- user account
// account(4) -- another user account
let (mut context, mut contract) = setup_contract();
deposit_tokens(
&mut context,