forked from zenlinkpro/Zenlink-DEX-Module
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.rs
More file actions
991 lines (895 loc) · 29 KB
/
Copy pathlib.rs
File metadata and controls
991 lines (895 loc) · 29 KB
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
// Copyright 2021-2022 Zenlink.
// Licensed under Apache 2.0.
//! # Standard AMM Pallet
//!
//! Based on the Uniswap V2 architecture.
//!
//! ## Overview
//!
//! This pallet provides functionality for:
//!
//! - Creating pools
//! - Bootstrapping pools
//! - Adding / removing liquidity
//! - Swapping currencies
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::unused_unit)]
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use codec::{Decode, Encode, FullCodec};
use frame_support::{
inherent::Vec,
pallet_prelude::*,
sp_runtime::SaturatedConversion,
traits::{
Currency, ExistenceRequirement, ExistenceRequirement::KeepAlive, Get, WithdrawReasons,
},
PalletId, RuntimeDebug,
};
use sp_core::U256;
use sp_runtime::traits::{AccountIdConversion, Hash, MaybeSerializeDeserialize, One, Zero};
use sp_std::{
collections::btree_map::BTreeMap, convert::TryInto, fmt::Debug, marker::PhantomData,
prelude::*, vec,
};
mod fee;
mod foreign;
mod multiassets;
mod primitives;
mod rpc;
mod swap;
mod traits;
#[cfg(any(feature = "runtime-benchmarks", test))]
pub mod benchmarking;
mod default_weights;
pub use default_weights::WeightInfo;
pub use multiassets::{MultiAssetsHandler, ZenlinkMultiAssets};
pub use primitives::{
AssetBalance, AssetId, AssetInfo, BootstrapParameter, PairLpGenerate, PairMetadata, PairStatus,
PairStatus::{Bootstrap, Disable, Trading},
LIQUIDITY, LOCAL, NATIVE, RESERVED,
};
pub use rpc::PairInfo;
pub use swap::util::*;
pub use traits::{ExportZenlink, GenerateLpAssetId, LocalAssetHandler, OtherAssetHandler};
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_system::pallet_prelude::*;
/// Configure the pallet by specifying the parameters and types on which it depends.
#[pallet::config]
pub trait Config: frame_system::Config {
/// Because this pallet emits events, it depends on the runtime's definition of an event.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// The assets interface beyond native currency and other assets.
type MultiAssetsHandler: MultiAssetsHandler<Self::AccountId, Self::AssetId>;
/// This pallet id.
#[pallet::constant]
type PalletId: Get<PalletId>;
/// The asset type.
type AssetId: FullCodec
+ Eq
+ PartialEq
+ Ord
+ PartialOrd
+ Copy
+ MaybeSerializeDeserialize
+ AssetInfo
+ Debug
+ scale_info::TypeInfo
+ MaxEncodedLen;
/// Generate the AssetId for the pair.
type LpGenerate: GenerateLpAssetId<Self::AssetId>;
/// This parachain id.
type SelfParaId: Get<u32>;
/// Account Identifier from which the internal Pot is generated.
type PotId: Get<PalletId>;
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
}
#[pallet::pallet]
#[pallet::without_storage_info]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
/// Foreign foreign storage
#[pallet::storage]
#[pallet::getter(fn foreign_ledger)]
/// The number of units of assets held by any given account.
pub type ForeignLedger<T: Config> =
StorageMap<_, Blake2_128Concat, (T::AssetId, T::AccountId), AssetBalance, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn foreign_meta)]
/// TWOX-NOTE: `AssetId` is trusted, so this is safe.
pub type ForeignMeta<T: Config> =
StorageMap<_, Twox64Concat, T::AssetId, AssetBalance, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn foreign_list)]
pub type ForeignList<T: Config> = StorageValue<_, Vec<T::AssetId>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn k_last)]
/// Refer: https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2Pair.sol#L88
/// Last unliquidated protocol fee;
pub type KLast<T: Config> =
StorageMap<_, Twox64Concat, (T::AssetId, T::AssetId), U256, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn fee_meta)]
/// (Option<fee_receiver>, fee_point)
pub(super) type FeeMeta<T: Config> = StorageValue<_, (Option<T::AccountId>, u8), ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn lp_pairs)]
pub type LiquidityPairs<T: Config> =
StorageMap<_, Blake2_128Concat, (T::AssetId, T::AssetId), Option<T::AssetId>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn pair_status)]
/// (T::AssetId, T::AssetId) -> PairStatus
pub type PairStatuses<T: Config> = StorageMap<
_,
Twox64Concat,
(T::AssetId, T::AssetId),
PairStatus<AssetBalance, T::BlockNumber, T::AccountId>,
ValueQuery,
>;
#[pallet::storage]
#[pallet::getter(fn bootstrap_personal_supply)]
pub type BootstrapPersonalSupply<T: Config> = StorageMap<
_,
Blake2_128Concat,
((T::AssetId, T::AssetId), T::AccountId),
(AssetBalance, AssetBalance),
ValueQuery,
>;
/// End status of bootstrap
///
/// BootstrapEndStatus: map bootstrap pair => pairStatus
#[pallet::storage]
#[pallet::getter(fn bootstrap_end_status)]
pub type BootstrapEndStatus<T: Config> = StorageMap<
_,
Twox64Concat,
(T::AssetId, T::AssetId),
PairStatus<AssetBalance, T::BlockNumber, T::AccountId>,
ValueQuery,
>;
#[pallet::storage]
#[pallet::getter(fn get_bootstrap_rewards)]
pub type BootstrapRewards<T: Config> = StorageMap<
_,
Twox64Concat,
(T::AssetId, T::AssetId),
BTreeMap<T::AssetId, AssetBalance>,
ValueQuery,
>;
#[pallet::storage]
#[pallet::getter(fn get_bootstrap_limits)]
pub type BootstrapLimits<T: Config> = StorageMap<
_,
Twox64Concat,
(T::AssetId, T::AssetId),
BTreeMap<T::AssetId, AssetBalance>,
ValueQuery,
>;
#[pallet::genesis_config]
/// Refer: https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2Pair.sol#L88
pub struct GenesisConfig<T: Config> {
/// The admin of the protocol fee.
// pub fee_admin: T::AccountId,
/// The receiver of the protocol fee.
pub fee_receiver: Option<T::AccountId>,
/// The fee point which integer between [0,30]
/// 0 means no protocol fee.
/// 30 means 0.3% * 100% = 0.0030.
/// default is 5 and means 0.3% * 1 / 6 = 0.0005.
pub fee_point: u8,
}
#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self { fee_receiver: None, fee_point: 5 }
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
fn build(&self) {
<FeeMeta<T>>::put((&self.fee_receiver, &self.fee_point));
}
}
#[cfg(feature = "std")]
impl<T: Config> GenesisConfig<T> {
/// Direct implementation of `GenesisBuild::build_storage`.
///
/// Kept in order not to break dependency.
pub fn build_storage(&self) -> Result<sp_runtime::Storage, String> {
<Self as GenesisBuild<T>>::build_storage(self)
}
/// Direct implementation of `GenesisBuild::assimilate_storage`.
///
/// Kept in order not to break dependency.
pub fn assimilate_storage(&self, storage: &mut sp_runtime::Storage) -> Result<(), String> {
<Self as GenesisBuild<T>>::assimilate_storage(self, storage)
}
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// Foreign Asset
/// Some assets were transferred. \[asset_id, owner, target, amount\]
Transferred(T::AssetId, T::AccountId, T::AccountId, AssetBalance),
/// Some assets were burned. \[asset_id, owner, amount\]
Burned(T::AssetId, T::AccountId, AssetBalance),
/// Some assets were minted. \[asset_id, owner, amount\]
Minted(T::AssetId, T::AccountId, AssetBalance),
/// Swap
/// Create a trading pair. \[asset_0, asset_1\]
PairCreated(T::AssetId, T::AssetId),
/// Add liquidity. \[owner, asset_0, asset_1, add_balance_0, add_balance_1,
/// mint_balance_lp\]
LiquidityAdded(
T::AccountId,
T::AssetId,
T::AssetId,
AssetBalance,
AssetBalance,
AssetBalance,
),
/// Remove liquidity. \[owner, recipient, asset_0, asset_1, rm_balance_0, rm_balance_1,
/// burn_balance_lp\]
LiquidityRemoved(
T::AccountId,
T::AccountId,
T::AssetId,
T::AssetId,
AssetBalance,
AssetBalance,
AssetBalance,
),
/// Transact in trading \[owner, recipient, swap_path, balances\]
AssetSwap(T::AccountId, T::AccountId, Vec<T::AssetId>, Vec<AssetBalance>),
/// Contribute to bootstrap pair. \[who, asset_0, asset_0_contribute, asset_1_contribute\]
BootstrapContribute(T::AccountId, T::AssetId, AssetBalance, T::AssetId, AssetBalance),
/// A bootstrap pair end. \[asset_0, asset_1, asset_0_amount, asset_1_amount,
/// total_lp_supply]
BootstrapEnd(T::AssetId, T::AssetId, AssetBalance, AssetBalance, AssetBalance),
/// Create a bootstrap pair. \[bootstrap_pair_account, asset_0, asset_1,
/// total_supply_0,total_supply_1, capacity_supply_0,capacity_supply_1, end\]
BootstrapCreated(
T::AccountId,
T::AssetId,
T::AssetId,
AssetBalance,
AssetBalance,
AssetBalance,
AssetBalance,
T::BlockNumber,
),
/// Claim a bootstrap pair. \[bootstrap_pair_account, claimer, receiver, asset_0, asset_1,
/// asset_0_refund, asset_1_refund, lp_amount\]
BootstrapClaim(
T::AccountId,
T::AccountId,
T::AccountId,
T::AssetId,
T::AssetId,
AssetBalance,
AssetBalance,
AssetBalance,
),
/// Update a bootstrap pair. \[caller, asset_0, asset_1,
/// total_supply_0,total_supply_1, capacity_supply_0,capacity_supply_1\]
BootstrapUpdate(
T::AccountId,
T::AssetId,
T::AssetId,
AssetBalance,
AssetBalance,
AssetBalance,
AssetBalance,
T::BlockNumber,
),
/// Refund from disable bootstrap pair. \[bootstrap_pair_account, caller, asset_0, asset_1,
/// asset_0_refund, asset_1_refund\]
BootstrapRefund(
T::AccountId,
T::AccountId,
T::AssetId,
T::AssetId,
AssetBalance,
AssetBalance,
),
/// Bootstrap distribute some rewards to contributors.
DistributeReward(T::AssetId, T::AssetId, T::AccountId, Vec<(T::AssetId, AssetBalance)>),
/// Charge reward into a bootstrap.
ChargeReward(T::AssetId, T::AssetId, T::AccountId, Vec<(T::AssetId, AssetBalance)>),
/// Withdraw all reward from a bootstrap.
WithdrawReward(T::AssetId, T::AssetId, T::AccountId),
}
#[pallet::error]
pub enum Error<T> {
/// Require the admin who can reset the admin and receiver of the protocol fee.
RequireProtocolAdmin,
/// Require the admin candidate who can become new admin after confirm.
RequireProtocolAdminCandidate,
/// Invalid fee_point
InvalidFeePoint,
/// Unsupported AssetId by this ZenlinkProtocol Version.
UnsupportedAssetType,
/// Account balance must be greater than or equal to the transfer amount.
InsufficientAssetBalance,
/// Account native currency balance must be greater than ExistentialDeposit.
NativeBalanceTooLow,
/// Trading pair can't be created.
DeniedCreatePair,
/// Trading pair already exists.
PairAlreadyExists,
/// Trading pair does not exist.
PairNotExists,
/// Asset does not exist.
AssetNotExists,
/// LP asset not exist.
LPAssetNotExists,
/// LP pair status invalid.
InvalidStatus,
/// Liquidity is not enough.
InsufficientLiquidity,
/// Trading pair does have enough foreign.
InsufficientPairReserve,
/// Get target amount is less than exception.
InsufficientTargetAmount,
/// Sold amount is more than exception.
ExcessiveSoldAmount,
/// Liquidity amount is zero.
ZeroLiquidity,
/// Can't find pair though trading path.
InvalidPath,
/// Incorrect foreign amount range.
IncorrectAssetAmountRange,
/// Overflow.
Overflow,
/// Transaction block number is larger than the end block number.
Deadline,
/// Location given was invalid or unsupported.
AccountIdBadLocation,
/// XCM execution failed.
ExecutionFailed,
/// Transfer to self by XCM message.
DeniedTransferToSelf,
/// Not in ZenlinkRegistedParaChains.
TargetChainNotRegistered,
/// Can't pass the K value check
InvariantCheckFailed,
/// Created pair can't create now
PairCreateForbidden,
/// Pair is not in bootstrap
NotInBootstrap,
/// Amount of contribution is invalid.
InvalidContributionAmount,
/// Amount of contribution is invalid.
UnqualifiedBootstrap,
/// Zero contribute in bootstrap
ZeroContribute,
/// Bootstrap deny refund
DenyRefund,
/// Bootstrap is disable
DisableBootstrap,
/// Not eligible to contribute
NotQualifiedAccount,
/// Reward of bootstrap is not set.
NoRewardTokens,
/// Charge bootstrap extrinsic args has error,
ChargeRewardParamsError,
/// Exist some reward in bootstrap,
ExistRewardsInBootstrap,
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Set the new receiver of the protocol fee.
///
/// # Arguments
///
/// - `send_to`:
/// (1) Some(receiver): it turn on the protocol fee and the new receiver account.
/// (2) None: it turn off the protocol fee.
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::set_fee_receiver())]
pub fn set_fee_receiver(
origin: OriginFor<T>,
receiver: Option<T::AccountId>,
) -> DispatchResult {
ensure_root(origin)?;
FeeMeta::<T>::mutate(|fee_meta| fee_meta.0 = receiver);
Ok(())
}
/// Set the protocol fee point.
///
/// # Arguments
///
/// - `fee_point`:
/// The fee_point which integer between [0,30]
/// 0 means no protocol fee.
/// 30 means 0.3% * 100% = 0.0030.
/// default is 5 and means 0.3% * 1 / 6 = 0.0005.
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::set_fee_point())]
pub fn set_fee_point(origin: OriginFor<T>, fee_point: u8) -> DispatchResult {
ensure_root(origin)?;
ensure!(fee_point <= 30, Error::<T>::InvalidFeePoint);
FeeMeta::<T>::mutate(|fee_meta| fee_meta.1 = fee_point);
Ok(())
}
/// Move some assets from one holder to another.
///
/// # Arguments
///
/// - `asset_id`: The foreign id.
/// - `target`: The receiver of the foreign.
/// - `amount`: The amount of the foreign to transfer.
#[pallet::call_index(2)]
#[pallet::weight(1_000_000)]
pub fn transfer(
origin: OriginFor<T>,
asset_id: T::AssetId,
recipient: T::AccountId,
#[pallet::compact] amount: AssetBalance,
) -> DispatchResult {
let origin = ensure_signed(origin)?;
let balance = T::MultiAssetsHandler::balance_of(asset_id, &origin);
ensure!(balance >= amount, Error::<T>::InsufficientAssetBalance);
T::MultiAssetsHandler::transfer(asset_id, &origin, &recipient, amount)?;
Ok(())
}
/// Create pair by two assets.
///
/// The order of foreign dot effect result.
///
/// # Arguments
///
/// - `asset_0`: Asset which make up Pair
/// - `asset_1`: Asset which make up Pair
#[pallet::call_index(4)]
#[pallet::weight(T::WeightInfo::create_pair())]
pub fn create_pair(
origin: OriginFor<T>,
asset_0: T::AssetId,
asset_1: T::AssetId,
) -> DispatchResult {
ensure_root(origin)?;
ensure!(asset_0.is_support() && asset_1.is_support(), Error::<T>::UnsupportedAssetType);
ensure!(asset_0 != asset_1, Error::<T>::DeniedCreatePair);
ensure!(T::MultiAssetsHandler::is_exists(asset_0), Error::<T>::AssetNotExists);
ensure!(T::MultiAssetsHandler::is_exists(asset_1), Error::<T>::AssetNotExists);
let pair = Self::sort_asset_id(asset_0, asset_1);
PairStatuses::<T>::try_mutate(pair, |status| match status {
Trading(_) => Err(Error::<T>::PairAlreadyExists),
Bootstrap(params) =>
if Self::bootstrap_disable(params) {
BootstrapEndStatus::<T>::insert(pair, Bootstrap((*params).clone()));
*status = Trading(PairMetadata {
pair_account: Self::pair_account_id(pair.0, pair.1),
total_supply: Zero::zero(),
});
Ok(())
} else {
Err(Error::<T>::PairAlreadyExists)
},
Disable => {
*status = Trading(PairMetadata {
pair_account: Self::pair_account_id(pair.0, pair.1),
total_supply: Zero::zero(),
});
Ok(())
},
})?;
Self::mutate_lp_pairs(asset_0, asset_1)?;
Self::deposit_event(Event::PairCreated(asset_0, asset_1));
Ok(())
}
/// Provide liquidity to a pair.
///
/// The order of foreign dot effect result.
///
/// # Arguments
///
/// - `asset_0`: Asset which make up pair
/// - `asset_1`: Asset which make up pair
/// - `amount_0_desired`: Maximum amount of asset_0 added to the pair
/// - `amount_1_desired`: Maximum amount of asset_1 added to the pair
/// - `amount_0_min`: Minimum amount of asset_0 added to the pair
/// - `amount_1_min`: Minimum amount of asset_1 added to the pair
/// - `deadline`: Height of the cutoff block of this transaction
#[pallet::call_index(5)]
#[pallet::weight(T::WeightInfo::add_liquidity())]
#[frame_support::transactional]
#[allow(clippy::too_many_arguments)]
pub fn add_liquidity(
origin: OriginFor<T>,
asset_0: T::AssetId,
asset_1: T::AssetId,
#[pallet::compact] amount_0_desired: AssetBalance,
#[pallet::compact] amount_1_desired: AssetBalance,
#[pallet::compact] amount_0_min: AssetBalance,
#[pallet::compact] amount_1_min: AssetBalance,
#[pallet::compact] deadline: T::BlockNumber,
) -> DispatchResult {
ensure!(asset_0.is_support() && asset_1.is_support(), Error::<T>::UnsupportedAssetType);
let who = ensure_signed(origin)?;
let now = frame_system::Pallet::<T>::block_number();
ensure!(deadline > now, Error::<T>::Deadline);
Self::inner_add_liquidity(
&who,
asset_0,
asset_1,
amount_0_desired,
amount_1_desired,
amount_0_min,
amount_1_min,
)
}
/// Extract liquidity.
///
/// The order of foreign dot effect result.
///
/// # Arguments
///
/// - `asset_0`: Asset which make up pair
/// - `asset_1`: Asset which make up pair
/// - `amount_asset_0_min`: Minimum amount of asset_0 to exact
/// - `amount_asset_1_min`: Minimum amount of asset_1 to exact
/// - `recipient`: Account that accepts withdrawal of assets
/// - `deadline`: Height of the cutoff block of this transaction
#[pallet::call_index(6)]
#[pallet::weight(T::WeightInfo::remove_liquidity())]
#[frame_support::transactional]
#[allow(clippy::too_many_arguments)]
pub fn remove_liquidity(
origin: OriginFor<T>,
asset_0: T::AssetId,
asset_1: T::AssetId,
#[pallet::compact] liquidity: AssetBalance,
#[pallet::compact] amount_0_min: AssetBalance,
#[pallet::compact] amount_1_min: AssetBalance,
recipient: T::AccountId,
#[pallet::compact] deadline: T::BlockNumber,
) -> DispatchResult {
ensure!(asset_0.is_support() && asset_1.is_support(), Error::<T>::UnsupportedAssetType);
let who = ensure_signed(origin)?;
let now = frame_system::Pallet::<T>::block_number();
ensure!(deadline > now, Error::<T>::Deadline);
Self::inner_remove_liquidity(
&who,
asset_0,
asset_1,
liquidity,
amount_0_min,
amount_1_min,
&recipient,
)
}
/// Sell amount of foreign by path.
///
/// # Arguments
///
/// - `amount_in`: Amount of the foreign will be sold
/// - `amount_out_min`: Minimum amount of target foreign
/// - `path`: path can convert to pairs.
/// - `recipient`: Account that receive the target foreign
/// - `deadline`: Height of the cutoff block of this transaction
#[pallet::call_index(7)]
#[pallet::weight(T::WeightInfo::swap_exact_assets_for_assets())]
#[frame_support::transactional]
pub fn swap_exact_assets_for_assets(
origin: OriginFor<T>,
#[pallet::compact] amount_in: AssetBalance,
#[pallet::compact] amount_out_min: AssetBalance,
path: Vec<T::AssetId>,
recipient: T::AccountId,
#[pallet::compact] deadline: T::BlockNumber,
) -> DispatchResult {
ensure!(path.iter().all(|id| id.is_support()), Error::<T>::UnsupportedAssetType);
let who = ensure_signed(origin)?;
let now = frame_system::Pallet::<T>::block_number();
ensure!(deadline > now, Error::<T>::Deadline);
Self::inner_swap_exact_assets_for_assets(
&who,
amount_in,
amount_out_min,
&path,
&recipient,
)
}
/// Buy amount of foreign by path.
///
/// # Arguments
///
/// - `amount_out`: Amount of the foreign will be bought
/// - `amount_in_max`: Maximum amount of sold foreign
/// - `path`: path can convert to pairs.
/// - `recipient`: Account that receive the target foreign
/// - `deadline`: Height of the cutoff block of this transaction
#[pallet::call_index(8)]
#[pallet::weight(T::WeightInfo::swap_assets_for_exact_assets())]
#[frame_support::transactional]
pub fn swap_assets_for_exact_assets(
origin: OriginFor<T>,
#[pallet::compact] amount_out: AssetBalance,
#[pallet::compact] amount_in_max: AssetBalance,
path: Vec<T::AssetId>,
recipient: T::AccountId,
#[pallet::compact] deadline: T::BlockNumber,
) -> DispatchResult {
ensure!(path.iter().all(|id| id.is_support()), Error::<T>::UnsupportedAssetType);
let who = ensure_signed(origin)?;
let now = frame_system::Pallet::<T>::block_number();
ensure!(deadline > now, Error::<T>::Deadline);
Self::inner_swap_assets_for_exact_assets(
&who,
amount_out,
amount_in_max,
&path,
&recipient,
)
}
/// Create bootstrap pair
///
/// The order of asset don't affect result.
///
/// # Arguments
///
/// - `asset_0`: Asset which make up bootstrap pair
/// - `asset_1`: Asset which make up bootstrap pair
/// - `target_supply_0`: Target amount of asset_0 total contribute
/// - `target_supply_0`: Target amount of asset_1 total contribute
/// - `capacity_supply_0`: The max amount of asset_0 total contribute
/// - `capacity_supply_1`: The max amount of asset_1 total contribute
/// - `end`: The earliest ending block.
#[pallet::call_index(9)]
#[pallet::weight(T::WeightInfo::bootstrap_create())]
#[frame_support::transactional]
#[allow(clippy::too_many_arguments)]
pub fn bootstrap_create(
origin: OriginFor<T>,
asset_0: T::AssetId,
asset_1: T::AssetId,
#[pallet::compact] target_supply_0: AssetBalance,
#[pallet::compact] target_supply_1: AssetBalance,
#[pallet::compact] capacity_supply_0: AssetBalance,
#[pallet::compact] capacity_supply_1: AssetBalance,
#[pallet::compact] end: T::BlockNumber,
rewards: Vec<T::AssetId>,
limits: Vec<(T::AssetId, AssetBalance)>,
) -> DispatchResult {
ensure_root(origin)?;
let pair = Self::sort_asset_id(asset_0, asset_1);
let (target_supply_0, target_supply_1, capacity_supply_0, capacity_supply_1) =
if pair.0 == asset_0 {
(target_supply_0, target_supply_1, capacity_supply_0, capacity_supply_1)
} else {
(target_supply_1, target_supply_0, capacity_supply_1, capacity_supply_0)
};
Self::do_bootstrap_create(
pair,
target_supply_0,
target_supply_1,
capacity_supply_0,
capacity_supply_1,
end,
rewards,
limits,
)?;
Self::deposit_event(Event::BootstrapCreated(
Self::account_id(),
pair.0,
pair.1,
target_supply_0,
target_supply_1,
capacity_supply_1,
capacity_supply_0,
end,
));
Ok(())
}
/// Contribute some asset to a bootstrap pair
///
/// # Arguments
///
/// - `asset_0`: Asset which make up bootstrap pair
/// - `asset_1`: Asset which make up bootstrap pair
/// - `amount_0_contribute`: The amount of asset_0 contribute to this bootstrap pair
/// - `amount_1_contribute`: The amount of asset_1 contribute to this bootstrap pair
/// - `deadline`: Height of the cutoff block of this transaction
#[pallet::call_index(10)]
#[pallet::weight(T::WeightInfo::bootstrap_contribute())]
#[frame_support::transactional]
pub fn bootstrap_contribute(
who: OriginFor<T>,
asset_0: T::AssetId,
asset_1: T::AssetId,
#[pallet::compact] amount_0_contribute: AssetBalance,
#[pallet::compact] amount_1_contribute: AssetBalance,
#[pallet::compact] deadline: T::BlockNumber,
) -> DispatchResult {
let who = ensure_signed(who)?;
ensure!(
Self::bootstrap_check_limits(asset_0, asset_1, &who),
Error::<T>::NotQualifiedAccount
);
let now = frame_system::Pallet::<T>::block_number();
ensure!(deadline > now, Error::<T>::Deadline);
Self::do_bootstrap_contribute(
who,
asset_0,
asset_1,
amount_0_contribute,
amount_1_contribute,
)
}
/// Claim lp asset from a bootstrap pair
///
/// # Arguments
///
/// - `asset_0`: Asset which make up bootstrap pair
/// - `asset_1`: Asset which make up bootstrap pair
/// - `deadline`: Height of the cutoff block of this transaction
#[pallet::call_index(11)]
#[pallet::weight(T::WeightInfo::bootstrap_claim())]
#[frame_support::transactional]
pub fn bootstrap_claim(
origin: OriginFor<T>,
recipient: T::AccountId,
asset_0: T::AssetId,
asset_1: T::AssetId,
#[pallet::compact] deadline: T::BlockNumber,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let now = frame_system::Pallet::<T>::block_number();
ensure!(deadline > now, Error::<T>::Deadline);
Self::do_bootstrap_claim(who, recipient, asset_0, asset_1)
}
/// End a bootstrap pair
///
/// # Arguments
///
/// - `asset_0`: Asset which make up bootstrap pair
/// - `asset_1`: Asset which make up bootstrap pair
#[pallet::call_index(12)]
#[pallet::weight(T::WeightInfo::bootstrap_end())]
#[frame_support::transactional]
pub fn bootstrap_end(
origin: OriginFor<T>,
asset_0: T::AssetId,
asset_1: T::AssetId,
) -> DispatchResult {
ensure_signed(origin)?;
Self::mutate_lp_pairs(asset_0, asset_1)?;
Self::do_end_bootstrap(asset_0, asset_1)
}
/// update a bootstrap pair
///
/// # Arguments
///
/// - `asset_0`: Asset which make up bootstrap pair
/// - `asset_1`: Asset which make up bootstrap pair
/// - `target_supply_0`: The new target amount of asset_0 total contribute
/// - `target_supply_0`: The new target amount of asset_1 total contribute
/// - `capacity_supply_0`: The new max amount of asset_0 total contribute
/// - `capacity_supply_1`: The new max amount of asset_1 total contribute
/// - `end`: The earliest ending block.
#[pallet::call_index(13)]
#[pallet::weight(T::WeightInfo::bootstrap_update())]
#[frame_support::transactional]
#[allow(clippy::too_many_arguments)]
pub fn bootstrap_update(
origin: OriginFor<T>,
asset_0: T::AssetId,
asset_1: T::AssetId,
#[pallet::compact] target_supply_0: AssetBalance,
#[pallet::compact] target_supply_1: AssetBalance,
#[pallet::compact] capacity_supply_0: AssetBalance,
#[pallet::compact] capacity_supply_1: AssetBalance,
#[pallet::compact] end: T::BlockNumber,
rewards: Vec<T::AssetId>,
limits: Vec<(T::AssetId, AssetBalance)>,
) -> DispatchResult {
ensure_root(origin)?;
let pair = Self::sort_asset_id(asset_0, asset_1);
let (target_supply_0, target_supply_1, capacity_supply_0, capacity_supply_1) =
if pair.0 == asset_0 {
(target_supply_0, target_supply_1, capacity_supply_0, capacity_supply_1)
} else {
(target_supply_1, target_supply_0, capacity_supply_1, capacity_supply_0)
};
let pair_account = Self::pair_account_id(asset_0, asset_1);
Self::do_bootstrap_update(
pair,
target_supply_0,
target_supply_1,
capacity_supply_0,
capacity_supply_1,
end,
rewards,
limits,
)?;
Self::deposit_event(Event::BootstrapUpdate(
pair_account,
pair.0,
pair.1,
target_supply_0,
target_supply_1,
capacity_supply_0,
capacity_supply_1,
end,
));
Ok(())
}
/// Contributor refund from disable bootstrap pair
///
/// # Arguments
///
/// - `asset_0`: Asset which make up bootstrap pair
/// - `asset_1`: Asset which make up bootstrap pair
#[pallet::call_index(14)]
#[pallet::weight(T::WeightInfo::bootstrap_refund())]
#[frame_support::transactional]
pub fn bootstrap_refund(
origin: OriginFor<T>,
asset_0: T::AssetId,
asset_1: T::AssetId,
) -> DispatchResult {
let who = ensure_signed(origin)?;
Self::do_bootstrap_refund(who, asset_0, asset_1)
}
#[pallet::call_index(16)]
#[pallet::weight(100_000_000)]
#[frame_support::transactional]
pub fn bootstrap_charge_reward(
origin: OriginFor<T>,
asset_0: T::AssetId,
asset_1: T::AssetId,
charge_rewards: Vec<(T::AssetId, AssetBalance)>,
) -> DispatchResult {
let pair = Self::sort_asset_id(asset_0, asset_1);
let who = ensure_signed(origin)?;
BootstrapRewards::<T>::try_mutate(pair, |rewards| -> DispatchResult {
ensure!(rewards.len() == charge_rewards.len(), Error::<T>::ChargeRewardParamsError);
for (asset_id, amount) in &charge_rewards {
let already_charge_amount =
rewards.get(asset_id).ok_or(Error::<T>::NoRewardTokens)?;
T::MultiAssetsHandler::transfer(*asset_id, &who, &Self::account_id(), *amount)?;
let new_charge_amount =
already_charge_amount.checked_add(*amount).ok_or(Error::<T>::Overflow)?;
rewards.insert(*asset_id, new_charge_amount);
}
Self::deposit_event(Event::ChargeReward(pair.0, pair.1, who, charge_rewards));
Ok(())
})?;
Ok(())
}
#[pallet::call_index(17)]
#[pallet::weight(100_000_000)]
#[frame_support::transactional]
pub fn bootstrap_withdraw_reward(
origin: OriginFor<T>,
asset_0: T::AssetId,
asset_1: T::AssetId,
recipient: T::AccountId,
) -> DispatchResult {
ensure_root(origin)?;
let pair = Self::sort_asset_id(asset_0, asset_1);
BootstrapRewards::<T>::try_mutate(pair, |rewards| -> DispatchResult {
for (asset_id, amount) in rewards {
T::MultiAssetsHandler::transfer(
*asset_id,
&Self::account_id(),
&recipient,
*amount,
)?;
*amount = Zero::zero();
}
Ok(())
})?;
Self::deposit_event(Event::WithdrawReward(pair.0, pair.1, recipient));
Ok(())
}
}
}