generated from substrate-developer-hub/substrate-node-template
-
Notifications
You must be signed in to change notification settings - Fork 60
/
lib.rs
1948 lines (1633 loc) · 65.6 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
// This file is part of galacticcouncil/warehouse.
// Copyright (C) 2020-2022 Intergalactic, Limited (GIB). SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Abbr:
// rpvs - reward per valued share
// rpz - reward per share in global farm
// Notion spec naming map:
// * shares -> s
// * total_shares -> S
// * valued_shares -> s'
// * total_valued_shares -> S'
// * stake_in_global_pool -> z
// * total_shares_z -> Z
// * multiplier -> m
//! # Liquidity mining pallet
//!
//! ## Overview
//!
//! This pallet provides functionality for a liquidity mining program with a time incentive (loyalty
//! factor) and multiple incentives scheme.
//! Users are rewarded for each period they stay in the liq. mining program.
//!
//! Reward per one period is derived from the user's loyalty factor which grows with time (periods)
//! the user is in the liq. mining program and the amount of LP shares the user locked into deposit.
//! User's loyalty factor is reset if the user exits and reenters liquidity mining.
//! User can claim rewards without resetting loyalty factor, only withdrawing shares
//! is penalized by loyalty factor reset.
//! The user is rewarded from the next period after they enters.
//!
//! Multiple Incentives
//!
//! This feature allows users to redeposit already deposited LP shares to multiple yield farms and
//! receive incentives from these farms.
//! Deposit in yield farm is called "farm entry".
//! Maximal number of redepositing same LP shares is configured by variable: `MaxFarmEntriesPerDeposit`.
//! Set `MaxFarmEntriesPerDeposit` to `1` to disable multiple incentives scheme. !!!NEVER set this
//! variable to `0`.
//! LP shares can be redeposited only to different yield farms running liquidity mining for same
//! pair of assets.
//!
//! Notes:
//! * LP shares are returned ONLY if deposit is destroyed - withdrawing LP shares can
//! be used to "free slot" for re-lock LP shares to different yield farm. Withdrawing LP shares result in
//! resetting loyalty factor for yield farm user is withdrawing from(other farm entries in the
//! deposit are not affected). If deposit has no more farm entries, deposit is destroyed and LP
//! shares are returned back to user.
//! * `YieldFarm` - can be in the 3 states: [`Active`, `Stopped`, `Terminated`]
//! * `Active` - liquidity mining is running, users are able to deposit, claim and withdraw LP
//! shares. `YieldFarm` is rewarded from `GlobalFarm` in this state.
//! * `Stopped` - liquidity mining is stopped. Users can claim and withdraw LP shares from the
//! farm. Users CAN'T deposit new LP shares to stopped farm. Stopped farm is not rewarded from the
//! `GlobalFarm`.
//! Note: stopped farm can be resumed or destroyed.
//! * `Terminated` - liquidity mining is ended. User's CAN'T deposit or claim rewards from
//! stopped farm. Users CAN only withdraw LP shares(without rewards).
//! `YieldFarm` must be stopped before it can be terminated. Terminated farm stays in the storage
//! until last farm's entry is withdrawn. Last withdrawn from yield farm will remove terminated
//! farm from the storage.
//! Note: Terminated farm CAN'T be resumed.
//! * `GlobalFarm` - can be in the 2 states: [`Active`, `Terminated`]
//! * `Active` - liquidity mining program is running, new yield farms can be added to the
//! global farm.
//! * `Terminated` - liquidity mining program is ended. Yield farms can't be added to the global
//! farm. Global farm MUST be empty(all yield farms in the global farm must be destroyed)
//! before it can be destroyed. Destroying global farm transfer undistributed rewards to farm's
//! owner. Terminated global farm stay in the storage until all yield farms are removed from
//! the storage. Last yield farm removal from storage triggers global farm removal from
//! storage.
//! Note: Terminated global farm CAN'T be resumed.
//! * Pot - account holding all rewards allocated for all `YieldFarm`s from all `GlobalFarm`s.
//! User's rewards are transferred from `pot`'s account to user's accounts.
//!
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::derive_partial_eq_without_eq)]
#[cfg(test)]
mod tests;
mod types;
pub use pallet::*;
pub use crate::types::{
Balance, DefaultPriceAdjustment, DepositData, DepositId, FarmId, FarmMultiplier, FarmState, GlobalFarmData,
GlobalFarmId, LoyaltyCurve, YieldFarmData, YieldFarmEntry, YieldFarmId,
};
use codec::{Decode, Encode, FullCodec};
use frame_support::{
defensive,
pallet_prelude::*,
require_transactional,
sp_runtime::{
traits::{AccountIdConversion, BlockNumberProvider, MaybeSerializeDeserialize, One, Zero},
RuntimeDebug,
},
traits::{Defensive, DefensiveOption},
PalletId,
};
use frame_system::pallet_prelude::BlockNumberFor;
use sp_runtime::ArithmeticError;
use hydra_dx_math::liquidity_mining as math;
use hydradx_traits::{liquidity_mining::PriceAdjustment, pools::DustRemovalAccountWhitelist, registry::Inspect};
use orml_traits::{GetByKey, MultiCurrency};
use scale_info::TypeInfo;
use sp_arithmetic::{
fixed_point::FixedU128,
traits::{CheckedAdd, CheckedDiv, CheckedSub},
Perquintill,
};
use sp_std::{
convert::{From, Into, TryInto},
vec::Vec,
};
type PeriodOf<T> = BlockNumberFor<T>;
//WARN: MIN_YIELD_FARM_MULTIPLIER.check_mul_int(MIN_DEPOSIT) >= 1. This rule is important otherwise
//non-zero deposit can result in a zero stake in global-farm and farm can be falsely identified as
//empty. https://github.com/galacticcouncil/warehouse/issues/127
/// Min value farm's owner can set as `min_deposit`
pub(crate) const MIN_DEPOSIT: Balance = 1_000;
/// Min value farm's owner can set as yield-farm's `multiplier`
pub(crate) const MIN_YIELD_FARM_MULTIPLIER: FixedU128 = FixedU128::from_inner(1_000_000_000_000_000);
#[frame_support::pallet]
pub mod pallet {
use super::*;
#[pallet::pallet]
pub struct Pallet<T, I = ()>(PhantomData<(T, I)>);
#[pallet::hooks]
impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
fn integrity_test() {
assert!(
T::MaxFarmEntriesPerDeposit::get().ge(&1_u32),
"`T::MaxFarmEntriesPerDeposit` must be greater or equal to 1"
);
}
}
#[pallet::genesis_config]
#[derive(frame_support::DefaultNoBound)]
pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
#[serde(skip)]
pub _phantom: PhantomData<(T, I)>,
}
#[pallet::genesis_build]
impl<T: Config<I>, I: 'static> BuildGenesisConfig for GenesisConfig<T, I> {
fn build(&self) {
let pot = <Pallet<T, I>>::pot_account_id().unwrap();
T::NonDustableWhitelistHandler::add_account(&pot).unwrap();
}
}
#[pallet::config]
pub trait Config<I: 'static = ()>: frame_system::Config + TypeInfo {
type RuntimeEvent: From<Event<Self, I>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Asset type.
type AssetId: Parameter + Member + Copy + MaybeSerializeDeserialize + MaxEncodedLen + Into<u32>;
/// Currency for transfers.
type MultiCurrency: MultiCurrency<Self::AccountId, CurrencyId = Self::AssetId, Balance = Balance>;
/// Pallet id.
#[pallet::constant]
type PalletId: Get<PalletId>;
/// Treasury account to receive claimed rewards lower than ED
#[pallet::constant]
type TreasuryAccountId: Get<Self::AccountId>;
/// Minimum total rewards to distribute from global farm during liquidity mining.
#[pallet::constant]
type MinTotalFarmRewards: Get<Balance>;
/// Minimum number of periods to run liquidity mining program.
#[pallet::constant]
type MinPlannedYieldingPeriods: Get<BlockNumberFor<Self>>;
/// The block number provider
type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
/// Id used to identify amm pool in liquidity mining pallet.
type AmmPoolId: Parameter + Member + Clone + FullCodec + MaxEncodedLen;
/// Maximum number of yield farms same LP shares can be re/deposited into. This value always
/// MUST BE >= 1.
#[pallet::constant]
type MaxFarmEntriesPerDeposit: Get<u32>;
/// Max number of yield farms can exist in global farm. This includes all farms in the
/// storage(active, stopped, terminated).
#[pallet::constant]
type MaxYieldFarmsPerGlobalFarm: Get<u32>;
/// Asset Registry - used to check if asset is correctly registered in asset registry and
/// provides information about existential deposit of the asset.
type AssetRegistry: Inspect<AssetId = Self::AssetId> + GetByKey<Self::AssetId, Balance>;
/// Account whitelist manager to exclude pool accounts from dusting mechanism.
type NonDustableWhitelistHandler: DustRemovalAccountWhitelist<Self::AccountId, Error = DispatchError>;
type PriceAdjustment: PriceAdjustment<
GlobalFarmData<Self, I>,
Error = DispatchError,
PriceAdjustment = FixedU128,
>;
}
#[pallet::error]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub enum Error<T, I = ()> {
/// Global farm does not exist.
GlobalFarmNotFound,
/// Yield farm does not exist.
YieldFarmNotFound,
/// Multiple claims in the same period is not allowed.
DoubleClaimInPeriod,
/// Liquidity mining is canceled.
LiquidityMiningCanceled,
/// Liquidity mining is not canceled.
LiquidityMiningIsActive,
/// Liquidity mining is in `active` or `terminated` state and action cannot be completed.
LiquidityMiningIsNotStopped,
/// LP shares amount is not valid.
InvalidDepositAmount,
/// Account is not allowed to perform action.
Forbidden,
/// Yield farm multiplier can't be 0.
InvalidMultiplier,
/// Yield farm with given `amm_pool_id` already exists in global farm.
YieldFarmAlreadyExists,
/// Loyalty curve's initial reward percentage is not valid. Valid range is: [0, 1).
InvalidInitialRewardPercentage,
/// One or more yield farms exist in global farm.
GlobalFarmIsNotEmpty,
/// Farm's `incentivized_asset` is missing in provided asset pair.
MissingIncentivizedAsset,
/// Reward currency balance is not sufficient.
InsufficientRewardCurrencyBalance,
/// Blocks per period can't be 0.
InvalidBlocksPerPeriod,
/// Yield per period can't be 0.
InvalidYieldPerPeriod,
/// Total rewards is less than `MinTotalFarmRewards`.
InvalidTotalRewards,
/// Planned yielding periods is less than `MinPlannedYieldingPeriods`.
InvalidPlannedYieldingPeriods,
/// Maximum number of locks reached for deposit.
MaxEntriesPerDeposit,
/// Trying to lock LP shares into already locked yield farm.
DoubleLock,
/// Yield farm entry doesn't exist for given deposit.
YieldFarmEntryNotFound,
/// Max number of yield farms in global farm was reached. Global farm can't accept new
/// yield farms until some yield farm is not removed from storage.
GlobalFarmIsFull,
/// Invalid min. deposit was set for global farm.
InvalidMinDeposit,
/// Price adjustment multiplier can't be 0.
InvalidPriceAdjustment,
/// Account creation from id failed.
ErrorGetAccountId,
/// Value of deposited shares amount in reward currency is bellow min. limit.
IncorrectValuedShares,
/// `reward_currency` is not registered in asset registry.
RewardCurrencyNotRegistered,
/// `incentivized_asset` is not registered in asset registry.
IncentivizedAssetNotRegistered,
/// Action cannot be completed because unexpected error has occurred. This should be reported
/// to protocol maintainers.
InconsistentState(InconsistentStateError),
}
//NOTE: these errors should never happen.
#[derive(Encode, Decode, Eq, PartialEq, TypeInfo, frame_support::PalletError, RuntimeDebug)]
pub enum InconsistentStateError {
/// Yield farm does not exist.
YieldFarmNotFound,
/// Global farm does not exist.
GlobalFarmNotFound,
/// Liquidity mining is `stopped` or `terminated`.
LiquidityIsNotActive,
/// Global farm is terminated.
GlobalFarmIsNotActive,
/// Deposit does not exist.
DepositNotFound,
/// Period calculation overflow.
InvalidPeriod,
/// Rewards allocated for yield-farm are lower then calculated rewards.
NotEnoughRewardsInYieldFarm,
/// Global-farm's `live_yield_farms_count` calculation overflow.
InvalidLiveYielFarmsCount,
/// Global-farm's `total_yield_farms_count` calculation overflow.
InvalidTotalYieldFarmsCount,
/// Yield-farm's entries count calculation overflow.
InvalidYieldFarmEntriesCount,
/// Yield-farm's `total_shares` calculation overflow.
InvalidTotalShares,
/// Yield-farm's `valued_shares` calculation overflow.
InvalidValuedShares,
/// Global-farm's `total_shares_z` calculation overflow.
InvalidTotalSharesZ,
/// Global-farm's `paid_accumulated_rewards` calculation overflow.
InvalidPaidAccumulatedRewards,
/// `FarmId` can't be 0.
InvalidFarmId,
/// Loyalty multiplier can't be greater than one.
InvalidLoyaltyMultiplier,
/// No existential deposit configured for asset in registry.
NoExistentialDepositForAsset,
}
impl<T, I> From<InconsistentStateError> for Error<T, I> {
fn from(e: InconsistentStateError) -> Error<T, I> {
Error::<T, I>::InconsistentState(e)
}
}
/// Id sequencer for `GlobalFarm` and `YieldFarm`.
#[pallet::storage]
#[pallet::getter(fn last_farm_id)]
pub type FarmSequencer<T: Config<I>, I: 'static = ()> = StorageValue<_, FarmId, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn deposit_id)]
pub type DepositSequencer<T: Config<I>, I: 'static = ()> = StorageValue<_, DepositId, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn global_farm)]
pub type GlobalFarm<T: Config<I>, I: 'static = ()> =
StorageMap<_, Blake2_128Concat, GlobalFarmId, GlobalFarmData<T, I>, OptionQuery>;
/// Yield farm details.
#[pallet::storage]
#[pallet::getter(fn yield_farm)]
pub type YieldFarm<T: Config<I>, I: 'static = ()> = StorageNMap<
_,
(
NMapKey<Blake2_128Concat, T::AmmPoolId>,
NMapKey<Blake2_128Concat, GlobalFarmId>,
NMapKey<Blake2_128Concat, YieldFarmId>,
),
YieldFarmData<T, I>,
OptionQuery,
>;
/// Deposit details.
#[pallet::storage]
#[pallet::getter(fn deposit)]
pub type Deposit<T: Config<I>, I: 'static = ()> =
StorageMap<_, Twox64Concat, DepositId, DepositData<T, I>, OptionQuery>;
/// Active(farms able to receive LP shares deposits) yield farms.
#[pallet::storage]
#[pallet::getter(fn active_yield_farm)]
pub type ActiveYieldFarm<T: Config<I>, I: 'static = ()> =
StorageDoubleMap<_, Blake2_128Concat, T::AmmPoolId, Blake2_128Concat, GlobalFarmId, YieldFarmId>;
#[pallet::event]
#[pallet::generate_deposit(pub(crate) fn deposit_event)]
pub enum Event<T: Config<I>, I: 'static = ()> {
/// Global farm accumulated reward per share was updated.
GlobalFarmAccRPZUpdated {
global_farm_id: GlobalFarmId,
accumulated_rpz: FixedU128,
total_shares_z: Balance,
},
/// Yield farm accumulated reward per valued share was updated.
YieldFarmAccRPVSUpdated {
global_farm_id: GlobalFarmId,
yield_farm_id: YieldFarmId,
accumulated_rpvs: FixedU128,
total_valued_shares: Balance,
},
/// Global farm has no more rewards to distribute in the moment.
AllRewardsDistributed { global_farm_id: GlobalFarmId },
}
#[pallet::call]
impl<T: Config<I>, I: 'static> Pallet<T, I> {}
}
impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// Create a new liquidity mining program with provided parameters.
///
/// `owner` account has to have at least `total_rewards` balance. These funds will be
/// transferred from `owner` to farm account.
///
/// Returns: `(GlobalFarmId, max reward per period)`
///
/// Parameters:
/// - `total_rewards`: total rewards planned to distribute. These rewards will be
/// distributed between all yield farms in the global farm.
/// - `planned_yielding_periods`: planned number of periods to distribute `total_rewards`.
/// WARN: THIS IS NOT HARD DEADLINE. Not all rewards have to be distributed in
/// `planned_yielding_periods`. Rewards are distributed based on the situation in the yield
/// farm and can be distributed in a longer, though never in a shorter, time frame.
/// - `blocks_per_period`: number of blocks in a single period. Min. number of blocks per
/// period is 1.
/// - `incentivized_asset`: asset to be incentivized in AMM pools. All yield farms added into
/// global farm must to have `incentivized_asset` in their pair.
/// - `reward_currency`: payoff currency of rewards.
/// - `owner`: liq. mining farm owner.
/// - `yield_per_period`: percentage return on `reward_currency` of all pools.
/// - `min_deposit`: minimum amount of LP shares to be deposited into liquidity mining by each user.
/// - `price_adjustment`: price adjustment between `incentivized_asset` and `reward_currency`.
/// This value should be `1` if `incentivized_asset` and `reward_currency` are the same.
#[allow(clippy::too_many_arguments)]
#[require_transactional]
fn create_global_farm(
total_rewards: Balance,
planned_yielding_periods: PeriodOf<T>,
blocks_per_period: BlockNumberFor<T>,
incentivized_asset: T::AssetId,
reward_currency: T::AssetId,
owner: T::AccountId,
yield_per_period: Perquintill,
min_deposit: Balance,
price_adjustment: FixedU128,
) -> Result<(GlobalFarmId, Balance), DispatchError> {
Self::validate_create_global_farm_data(
total_rewards,
planned_yielding_periods,
blocks_per_period,
yield_per_period,
min_deposit,
price_adjustment,
)?;
ensure!(
T::AssetRegistry::exists(reward_currency),
Error::<T, I>::RewardCurrencyNotRegistered
);
ensure!(
T::AssetRegistry::exists(incentivized_asset),
Error::<T, I>::IncentivizedAssetNotRegistered
);
T::MultiCurrency::ensure_can_withdraw(reward_currency, &owner, total_rewards)
.map_err(|_| Error::<T, I>::InsufficientRewardCurrencyBalance)?;
let planned_periods =
TryInto::<u128>::try_into(planned_yielding_periods).map_err(|_| ArithmeticError::Overflow)?;
let max_reward_per_period = total_rewards
.checked_div(planned_periods)
.ok_or(ArithmeticError::DivisionByZero)?;
let current_period = Self::get_current_period(blocks_per_period)?;
let farm_id = Self::get_next_farm_id()?;
let global_farm = GlobalFarmData::new(
farm_id,
current_period,
reward_currency,
yield_per_period,
planned_yielding_periods,
blocks_per_period,
owner,
incentivized_asset,
max_reward_per_period,
min_deposit,
price_adjustment,
);
<GlobalFarm<T, I>>::insert(global_farm.id, &global_farm);
let global_farm_account = Self::farm_account_id(global_farm.id)?;
T::NonDustableWhitelistHandler::add_account(&global_farm_account)?;
T::MultiCurrency::transfer(reward_currency, &global_farm.owner, &global_farm_account, total_rewards)?;
Ok((farm_id, max_reward_per_period))
}
/// Update global farm's price adjustment.
///
/// Only farm's owner can perform this action.
///
/// Parameters:
/// - `who`: farm's owner
/// - `global_farm_id`: global farm id.
/// - `price_adjustment`: new price adjustment value.
fn update_global_farm_price_adjustment(
who: T::AccountId,
global_farm_id: GlobalFarmId,
price_adjustment: FixedU128,
) -> Result<(), DispatchError> {
ensure!(!price_adjustment.is_zero(), Error::<T, I>::InvalidPriceAdjustment);
<GlobalFarm<T, I>>::try_mutate(global_farm_id, |maybe_global_farm| {
let global_farm = maybe_global_farm.as_mut().ok_or(Error::<T, I>::GlobalFarmNotFound)?;
ensure!(global_farm.state.is_active(), Error::<T, I>::GlobalFarmNotFound);
ensure!(who == global_farm.owner, Error::<T, I>::Forbidden);
let current_period = Self::get_current_period(global_farm.blocks_per_period)?;
Self::sync_global_farm(global_farm, current_period)?;
global_farm.price_adjustment = price_adjustment;
Ok(())
})
}
/// Terminate existing liquidity mining program. Undistributed rewards are transferred to
/// owner(`who`).
///
/// Only farm's owner can perform this action.
///
/// WARN: To successfully terminate a global farm, farm have to be empty(all yield farms in the
/// global farm must be terminated)
///
/// Returns: `(reward currency, undistributed rewards, destination account)`
///
/// Parameters:
/// - `who`: farm's owner.
/// - `farm_id`: id of farm to be terminated.
#[require_transactional]
fn terminate_global_farm(
who: T::AccountId,
farm_id: GlobalFarmId,
) -> Result<(T::AssetId, Balance, T::AccountId), DispatchError> {
<GlobalFarm<T, I>>::try_mutate_exists(farm_id, |maybe_global_farm| {
let global_farm = maybe_global_farm.as_mut().ok_or(Error::<T, I>::GlobalFarmNotFound)?;
ensure!(who == global_farm.owner, Error::<T, I>::Forbidden);
ensure!(global_farm.state.is_active(), Error::<T, I>::GlobalFarmNotFound);
ensure!(!global_farm.has_live_farms(), Error::<T, I>::GlobalFarmIsNotEmpty);
let global_farm_account = Self::farm_account_id(global_farm.id)?;
let undistributed_rewards =
T::MultiCurrency::free_balance(global_farm.reward_currency, &global_farm_account);
T::MultiCurrency::transfer(
global_farm.reward_currency,
&global_farm_account,
&who,
undistributed_rewards,
)?;
//Mark for removal from storage on last `YieldFarm` in the farm removed.
global_farm.state = FarmState::Terminated;
//NOTE: Nothing can be send to this account because `YieldFarm`'s has to be terminated
//first so it can be dusted.
T::NonDustableWhitelistHandler::remove_account(&global_farm_account)?;
let reward_currency = global_farm.reward_currency;
if global_farm.can_be_removed() {
*maybe_global_farm = None;
}
Ok((reward_currency, undistributed_rewards, who))
})
}
/// Add yield farm to global farm and start liquidity mining for given assets pair.
///
/// Only farm owner can perform this action.
///
/// One of the AMM assets has to be `incentivized_token`. Same AMM can be
/// in the same farm only once.
///
/// Returns: `(YieldFarmId)`
///
/// Parameters:
/// - `who`: farm's owner
/// - `global_farm_id`: farm id to which a yield farm will be added.
/// - `multiplier`: yield farm multiplier.
/// - `loyalty_curve`: curve to calculate loyalty multiplier to distribute rewards to users
/// with time incentive. `None` means no loyalty multiplier.
/// - `amm_pool_id`: identifier of the AMM pool.
/// - `assets`: list of assets in the AMM pool. One of this assets must be incentivized asset
#[require_transactional]
fn create_yield_farm(
who: T::AccountId,
global_farm_id: GlobalFarmId,
multiplier: FarmMultiplier,
loyalty_curve: Option<LoyaltyCurve>,
amm_pool_id: T::AmmPoolId,
assets: Vec<T::AssetId>,
) -> Result<YieldFarmId, DispatchError> {
ensure!(
multiplier >= MIN_YIELD_FARM_MULTIPLIER,
Error::<T, I>::InvalidMultiplier
);
if let Some(ref curve) = loyalty_curve {
ensure!(
curve.initial_reward_percentage.lt(&FixedU128::one()),
Error::<T, I>::InvalidInitialRewardPercentage
);
}
<GlobalFarm<T, I>>::try_mutate(
global_farm_id,
|maybe_global_farm| -> Result<YieldFarmId, DispatchError> {
let global_farm = maybe_global_farm.as_mut().ok_or(Error::<T, I>::GlobalFarmNotFound)?;
//This is basically same as farm not found.
ensure!(global_farm.state.is_active(), Error::<T, I>::GlobalFarmNotFound);
ensure!(who == global_farm.owner, Error::<T, I>::Forbidden);
ensure!(!global_farm.is_full(), Error::<T, I>::GlobalFarmIsFull);
ensure!(
assets.contains(&global_farm.incentivized_asset),
Error::<T, I>::MissingIncentivizedAsset
);
<ActiveYieldFarm<T, I>>::try_mutate(amm_pool_id.clone(), global_farm_id, |maybe_active_yield_farm| {
ensure!(maybe_active_yield_farm.is_none(), Error::<T, I>::YieldFarmAlreadyExists);
let current_period = Self::get_current_period(global_farm.blocks_per_period)?;
Self::sync_global_farm(global_farm, current_period)?;
let yield_farm_id = Self::get_next_farm_id()?;
let yield_farm =
YieldFarmData::new(yield_farm_id, current_period, loyalty_curve.clone(), multiplier);
<YieldFarm<T, I>>::insert((amm_pool_id, global_farm_id, yield_farm_id), yield_farm);
global_farm.increase_yield_farm_counts()?;
*maybe_active_yield_farm = Some(yield_farm_id);
Ok(yield_farm_id)
})
},
)
}
/// Update yield farm's multiplier.
///
/// Only farm's owner can perform this action.
///
/// Returns: `(YieldFarmId)`
///
/// Parameters:
/// - `who`: farm's owner
/// - `global_farm_id`: global farm id in which yield farm will be updated.
/// - `multiplier`: new yield farm multiplier.
/// - `amm_pool_id`: identifier of the AMM pool.
#[require_transactional]
fn update_yield_farm_multiplier(
who: T::AccountId,
global_farm_id: GlobalFarmId,
amm_pool_id: T::AmmPoolId,
multiplier: FarmMultiplier,
) -> Result<YieldFarmId, DispatchError> {
ensure!(
multiplier >= MIN_YIELD_FARM_MULTIPLIER,
Error::<T, I>::InvalidMultiplier
);
let yield_farm_id =
Self::active_yield_farm(amm_pool_id.clone(), global_farm_id).ok_or(Error::<T, I>::YieldFarmNotFound)?;
<YieldFarm<T, I>>::try_mutate((amm_pool_id, global_farm_id, yield_farm_id), |maybe_yield_farm| {
//NOTE: yield-farm must exist if it's in the active_yield_farm storage.
let yield_farm = maybe_yield_farm
.as_mut()
.defensive_ok_or::<Error<T, I>>(InconsistentStateError::YieldFarmNotFound.into())?;
ensure!(yield_farm.state.is_active(), Error::<T, I>::LiquidityMiningCanceled);
<GlobalFarm<T, I>>::try_mutate(global_farm_id, |maybe_global_farm| {
//NOTE: global-farm must exist if yield-farm exists.
let global_farm = maybe_global_farm
.as_mut()
.defensive_ok_or::<Error<T, I>>(InconsistentStateError::GlobalFarmNotFound.into())?;
ensure!(who == global_farm.owner, Error::<T, I>::Forbidden);
let old_stake_in_global_farm =
math::calculate_global_farm_shares(yield_farm.total_valued_shares, yield_farm.multiplier)
.map_err(|_| ArithmeticError::Overflow)?;
let current_period = Self::get_current_period(global_farm.blocks_per_period)?;
Self::sync_global_farm(global_farm, current_period)?;
Self::sync_yield_farm(yield_farm, global_farm, current_period)?;
let new_stake_in_global_farm =
math::calculate_global_farm_shares(yield_farm.total_valued_shares, multiplier)
.map_err(|_| ArithmeticError::Overflow)?;
global_farm.remove_stake(old_stake_in_global_farm)?;
global_farm.add_stake(new_stake_in_global_farm)?;
yield_farm.multiplier = multiplier;
Ok(yield_farm.id)
})
})
}
/// Stop liquidity mining for specific yield farm.
///
/// This function claims rewards from `GlobalFarm` for the last time and stops yield farm
/// incentivization from a `GlobalFarm`. Users will be able to only claim and withdraw LP
/// shares after calling this function.
/// `deposit_lp_shares()` is not allowed on stopped yield farm.
///
/// Returns: `(YieldFarmId)`
///
/// Only farm owner can perform this action.
///
/// Parameters:
/// - `who`: farm's owner.
/// - `global_farm_id`: farm id in which yield farm will be stopped.
/// - `amm_pool_id`: identifier of the AMM pool.
#[require_transactional]
fn stop_yield_farm(
who: T::AccountId,
global_farm_id: GlobalFarmId,
amm_pool_id: T::AmmPoolId,
) -> Result<YieldFarmId, DispatchError> {
<ActiveYieldFarm<T, I>>::try_mutate_exists(
amm_pool_id.clone(),
global_farm_id,
|maybe_active_yield_farm_id| -> Result<YieldFarmId, DispatchError> {
let yield_farm_id = maybe_active_yield_farm_id
.as_ref()
.ok_or(Error::<T, I>::YieldFarmNotFound)?;
<YieldFarm<T, I>>::try_mutate(
(amm_pool_id, global_farm_id, yield_farm_id),
|maybe_yield_farm| -> Result<(), DispatchError> {
//NOTE: yield-farm must exist if it's in the active_yield_farm storage.
let yield_farm = maybe_yield_farm
.as_mut()
.defensive_ok_or::<Error<T, I>>(InconsistentStateError::YieldFarmNotFound.into())?;
//NOTE: inactive yield-farm can't be in the active_yield_farm storage.
ensure!(
yield_farm.state.is_active(),
Self::defensive_err(Error::<T, I>::InconsistentState(
InconsistentStateError::LiquidityIsNotActive
))
);
<GlobalFarm<T, I>>::try_mutate(global_farm_id, |maybe_global_farm| {
//NOTE: global-farm must exist when yield-farm exists.
let global_farm = maybe_global_farm
.as_mut()
.defensive_ok_or::<Error<T, I>>(InconsistentStateError::GlobalFarmNotFound.into())?;
ensure!(global_farm.owner == who, Error::<T, I>::Forbidden);
let current_period = Self::get_current_period(global_farm.blocks_per_period)?;
Self::sync_global_farm(global_farm, current_period)?;
Self::sync_yield_farm(yield_farm, global_farm, current_period)?;
let old_stake_in_global_farm = math::calculate_global_farm_shares(
yield_farm.total_valued_shares,
yield_farm.multiplier,
)
.map_err(|_| ArithmeticError::Overflow)?;
global_farm.remove_stake(old_stake_in_global_farm)?;
yield_farm.state = FarmState::Stopped;
yield_farm.multiplier = FarmMultiplier::default();
Ok(())
})
},
)?;
let yield_farm_id = *yield_farm_id;
//Remove yield farm from active farms storage.
*maybe_active_yield_farm_id = None;
Ok(yield_farm_id)
},
)
}
/// Resume liquidity mining for stopped yield farm.
///
/// This function resume incentivization from `GlobalPool` and restore full functionality
/// for yield farm. Users will be able to deposit, claim and withdraw again.
///
/// Yield farm is not rewarded for the time it was stopped.
///
/// Only farm's owner can perform this action.
///
/// Parameters:
/// - `who`: farm's owner
/// - `global_farm_id`: farm id in which yield farm will be resumed.
/// - `yield_farm_id`: id of yield farm to resume.
/// - `amm_pool_id`: identifier of the AMM pool.
/// - `multiplier`: yield farm's multiplier.
#[require_transactional]
fn resume_yield_farm(
who: T::AccountId,
global_farm_id: GlobalFarmId,
yield_farm_id: YieldFarmId,
amm_pool_id: T::AmmPoolId,
multiplier: FarmMultiplier,
) -> Result<(), DispatchError> {
ensure!(
multiplier >= MIN_YIELD_FARM_MULTIPLIER,
Error::<T, I>::InvalidMultiplier
);
<ActiveYieldFarm<T, I>>::try_mutate(amm_pool_id.clone(), global_farm_id, |maybe_active_yield_farm_id| {
ensure!(
maybe_active_yield_farm_id.is_none(),
Error::<T, I>::YieldFarmAlreadyExists
);
<YieldFarm<T, I>>::try_mutate((amm_pool_id, global_farm_id, yield_farm_id), |maybe_yield_farm| {
let yield_farm = maybe_yield_farm.as_mut().ok_or(Error::<T, I>::YieldFarmNotFound)?;
//Active or terminated yield farms can't be resumed.
ensure!(
yield_farm.state.is_stopped(),
Error::<T, I>::LiquidityMiningIsNotStopped
);
<GlobalFarm<T, I>>::try_mutate(global_farm_id, |maybe_global_farm| {
//NOTE: global-farm must exist if yield-farm exists.
let global_farm = maybe_global_farm
.as_mut()
.defensive_ok_or::<Error<T, I>>(InconsistentStateError::GlobalFarmNotFound.into())?;
ensure!(global_farm.owner == who, Error::<T, I>::Forbidden);
let current_period = Self::get_current_period(global_farm.blocks_per_period)?;
Self::sync_global_farm(global_farm, current_period)?;
//NOTE: this should never fail.
let stopped_periods = current_period
.checked_sub(&yield_farm.updated_at)
.defensive_ok_or::<Error<T, I>>(InconsistentStateError::InvalidPeriod.into())?;
let new_stake_in_global_farm =
math::calculate_global_farm_shares(yield_farm.total_valued_shares, multiplier)
.map_err(|_| ArithmeticError::Overflow)?;
global_farm.add_stake(new_stake_in_global_farm)?;
yield_farm.accumulated_rpz = global_farm.accumulated_rpz;
yield_farm.updated_at = current_period;
yield_farm.state = FarmState::Active;
yield_farm.multiplier = multiplier;
yield_farm.total_stopped = yield_farm
.total_stopped
.checked_add(&stopped_periods)
.ok_or(ArithmeticError::Overflow)?;
//add yield farm to active farms.
*maybe_active_yield_farm_id = Some(yield_farm.id);
Ok(())
})
})
})
}
/// This function marks an yield farm ready for removal from storage when it's empty. Users will
/// be able to only withdraw shares(without claiming rewards from yield farm). Unpaid rewards
/// will be transferred back to global farm and will be used to distribute to other yield farms.
///
/// Yield farm must be stopped before calling this function.
///
/// Only farm's owner can perform this action. Yield farm stays in the storage until it's
/// empty(all farm entries are withdrawn). Last withdrawn from yield farm trigger removing from
/// the storage.
///
/// Parameters:
/// - `who`: farm's owner.
/// - `global_farm_id`: farm id from which yield farm will be removed.
/// - `yield_farm_id`: yield farm id of farm to terminate.
/// - `amm_pool_id`: identifier of the AMM pool.
#[require_transactional]
fn terminate_yield_farm(
who: T::AccountId,
global_farm_id: GlobalFarmId,
yield_farm_id: YieldFarmId,
amm_pool_id: T::AmmPoolId,
) -> Result<(), DispatchError> {
ensure!(
<ActiveYieldFarm<T, I>>::get(amm_pool_id.clone(), global_farm_id) != Some(yield_farm_id),
Error::<T, I>::LiquidityMiningIsActive
);
<GlobalFarm<T, I>>::try_mutate_exists(global_farm_id, |maybe_global_farm| {
let global_farm = maybe_global_farm.as_mut().ok_or(Error::<T, I>::GlobalFarmNotFound)?;
ensure!(global_farm.owner == who, Error::<T, I>::Forbidden);
<YieldFarm<T, I>>::try_mutate_exists(
(amm_pool_id, global_farm_id, yield_farm_id),
|maybe_yield_farm| -> Result<(), DispatchError> {
let yield_farm = maybe_yield_farm.as_mut().ok_or(Error::<T, I>::YieldFarmNotFound)?;
//Only stopped farms can be resumed.
ensure!(
yield_farm.state.is_stopped(),
Error::<T, I>::LiquidityMiningIsNotStopped
);
//Transfer yield-farm's unpaid rewards back to global farm.
let global_farm_account = Self::farm_account_id(global_farm.id)?;
let pot = Self::pot_account_id().ok_or(Error::<T, I>::ErrorGetAccountId)?;
global_farm.accumulated_paid_rewards = global_farm
.accumulated_paid_rewards
.checked_sub(yield_farm.left_to_distribute)
.ok_or(ArithmeticError::Overflow)?;
T::MultiCurrency::transfer(
global_farm.reward_currency,
&pot,
&global_farm_account,
yield_farm.left_to_distribute,
)?;
yield_farm.left_to_distribute = Zero::zero();
//Delete yield farm.
yield_farm.state = FarmState::Terminated;
global_farm.decrease_live_yield_farm_count()?;
//Cleanup if it's possible
if yield_farm.can_be_removed() {
global_farm.decrease_total_yield_farm_count()?;
*maybe_yield_farm = None;