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
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::all)]
use common::fixnum::ops::{CheckedAdd, CheckedSub};
use common::prelude::{Balance, FixedWrapper, SwapAmount};
use common::{
fixed, fixed_wrapper, AccountIdOf, AssetInfoProvider, BuyBackHandler, DexInfoProvider,
EnsureDEXManager, Fixed, LiquidityProxyTrait, LiquiditySourceFilter, LiquiditySourceType,
OnPoolCreated, OnPswapBurned, PoolXykPallet, PswapRemintInfo,
};
use core::convert::TryInto;
use frame_support::dispatch::{DispatchError, DispatchResult, DispatchResultWithPostInfo, Weight};
use frame_support::traits::Get;
use frame_support::{ensure, fail};
use frame_system::ensure_signed;
use sp_arithmetic::traits::{Saturating, Zero};
pub mod weights;
pub mod migrations;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
pub const TECH_ACCOUNT_PREFIX: &[u8] = b"pswap-distribution";
pub const TECH_ACCOUNT_MAIN: &[u8] = b"main";
type DexIdOf<T> = <T as common::Config>::DEXId;
type AssetIdOf<T> = <T as assets::Config>::AssetId;
type Assets<T> = assets::Pallet<T>;
type System<T> = frame_system::Pallet<T>;
pub use weights::WeightInfo;
#[derive(Default, Clone)]
pub struct DistributionWeightParams {
pub skipped: u32,
pub distributed: u32,
pub shareholders: u32,
}
impl<T: Config> Pallet<T> {
pub fn is_subscribed(fees_account_id: &T::AccountId) -> bool {
SubscribedAccounts::<T>::get(fees_account_id).is_some()
}
pub fn subscribe(
fees_account_id: T::AccountId,
dex_id: T::DEXId,
pool_account: AccountIdOf<T>,
frequency: Option<T::BlockNumber>,
) -> DispatchResult {
ensure!(
!Self::is_subscribed(&fees_account_id),
Error::<T>::SubscriptionActive
);
let frequency = frequency.unwrap_or(T::GetDefaultSubscriptionFrequency::get());
ensure!(!frequency.is_zero(), Error::<T>::InvalidFrequency);
let current_block = System::<T>::block_number();
frame_system::Pallet::<T>::inc_consumers(&fees_account_id)
.map_err(|_| Error::<T>::IncRefError)?;
SubscribedAccounts::<T>::insert(
fees_account_id.clone(),
(dex_id, pool_account, frequency, current_block),
);
Ok(())
}
pub fn unsubscribe(fees_account_id: T::AccountId) -> DispatchResult {
let value = SubscribedAccounts::<T>::take(&fees_account_id);
ensure!(value.is_some(), Error::<T>::UnknownSubscription);
frame_system::Pallet::<T>::dec_consumers(&fees_account_id);
Ok(())
}
pub fn claimable_amount(account_id: &T::AccountId) -> Result<Balance, DispatchError> {
let current_position = ShareholderAccounts::<T>::get(&account_id);
Ok(current_position
.into_bits()
.try_into()
.map_err(|_| Error::<T>::CalculationError)?)
}
fn claim_by_account(account_id: &T::AccountId) -> DispatchResult {
let current_position = ShareholderAccounts::<T>::get(&account_id);
if current_position != fixed!(0) {
ShareholderAccounts::<T>::mutate(&account_id, |current| *current = fixed!(0));
ClaimableShares::<T>::mutate(|current| {
*current = current.saturating_sub(current_position)
});
let incentives_asset_id = T::GetIncentiveAssetId::get();
let tech_account_id = T::GetTechnicalAccountId::get();
let _result = Assets::<T>::transfer_from(
&incentives_asset_id,
&tech_account_id,
&account_id,
current_position
.into_bits()
.try_into()
.map_err(|_| Error::<T>::CalculationError)?,
)?;
Ok(().into())
} else {
fail!(Error::<T>::ZeroClaimableIncentives)
}
}
fn exchange_fees_to_incentive(
fees_account_id: &T::AccountId,
dex_id: T::DEXId,
) -> DispatchResult {
let dex_info = T::DexInfoProvider::get_dex_info(&dex_id)?;
let base_total = Assets::<T>::free_balance(&dex_info.base_asset_id, &fees_account_id)?;
if base_total == 0 {
Self::deposit_event(Event::<T>::NothingToExchange(
dex_id.clone(),
fees_account_id.clone(),
));
return Ok(());
}
let outcome = T::LiquidityProxy::exchange(
dex_id,
fees_account_id,
fees_account_id,
&dex_info.base_asset_id,
&T::GetIncentiveAssetId::get(),
SwapAmount::with_desired_input(base_total.clone(), Balance::zero()),
LiquiditySourceFilter::with_allowed(
dex_id.clone(),
[LiquiditySourceType::XYKPool].into(),
),
);
match outcome {
Ok(swap_outcome) => Self::deposit_event(Event::<T>::FeesExchanged(
dex_id.clone(),
fees_account_id.clone(),
dex_info.base_asset_id,
base_total,
T::GetIncentiveAssetId::get(),
swap_outcome.amount,
)),
Err(error) => Self::deposit_event(Event::<T>::FeesExchangeFailed(
dex_id.clone(),
fees_account_id.clone(),
dex_info.base_asset_id,
base_total,
T::GetIncentiveAssetId::get(),
error,
)),
}
Ok(())
}
fn distribute_incentive(
fees_account_id: &T::AccountId,
dex_id: &T::DEXId,
pool_account: &AccountIdOf<T>,
tech_account_id: &T::AccountId,
) -> Result<u32, DispatchError> {
common::with_transaction(|| {
let incentive_asset_id = T::GetIncentiveAssetId::get();
let pool_tokens_total = T::PoolXykPallet::total_issuance(&pool_account)?;
let incentive_total = Assets::<T>::free_balance(&incentive_asset_id, &fees_account_id)?;
if incentive_total == 0 || pool_tokens_total == 0 {
Self::deposit_event(Event::<T>::NothingToDistribute(
dex_id.clone(),
fees_account_id.clone(),
));
return Ok(0);
}
let mut distribution = Self::calculate_and_burn_distribution(
fees_account_id,
tech_account_id,
&incentive_asset_id,
incentive_total,
)?;
let mut shareholders_distributed_amount = fixed_wrapper!(0);
let mut shareholders_num = 0u32;
for (account_id, pool_tokens) in T::PoolXykPallet::pool_providers(pool_account) {
let share = FixedWrapper::from(pool_tokens)
* FixedWrapper::from(distribution.liquidity_providers)
/ FixedWrapper::from(pool_tokens_total);
let share = share.get().map_err(|_| Error::<T>::CalculationError)?;
ShareholderAccounts::<T>::mutate(&account_id, |current| {
*current = current.saturating_add(share)
});
ClaimableShares::<T>::mutate(|current| *current = current.saturating_add(share));
shareholders_distributed_amount = shareholders_distributed_amount + share;
shareholders_num += 1;
}
let undistributed_lp_amount = distribution.liquidity_providers.saturating_sub(
shareholders_distributed_amount
.try_into_balance()
.map_err(|_| Error::<T>::CalculationError)?,
);
if undistributed_lp_amount > 0 {
distribution.liquidity_providers = distribution
.liquidity_providers
.saturating_sub(undistributed_lp_amount);
distribution.buy_back_xst = distribution
.buy_back_xst
.saturating_add(undistributed_lp_amount);
}
assets::Pallet::<T>::mint_to(
&incentive_asset_id,
tech_account_id,
tech_account_id,
distribution.liquidity_providers,
)?;
T::BuyBackHandler::mint_buy_back_and_burn(
&incentive_asset_id,
&T::GetXSTAssetId::get(),
distribution.buy_back_xst,
)?;
Self::deposit_event(Event::<T>::IncentiveDistributed(
dex_id.clone(),
fees_account_id.clone(),
incentive_asset_id,
distribution.liquidity_providers,
shareholders_num as u128,
));
Ok(shareholders_num)
})
}
fn calculate_and_burn_distribution(
fees_account_id: &T::AccountId,
tech_account_id: &T::AccountId,
incentive_asset_id: &T::AssetId,
incentive_total: Balance,
) -> Result<PswapRemintInfo, DispatchError> {
let distribution = Self::calculate_pswap_distribution(incentive_total)?;
assets::Pallet::<T>::burn_from(
&incentive_asset_id,
tech_account_id,
fees_account_id,
incentive_total,
)?;
T::OnPswapBurnedAggregator::on_pswap_burned(distribution.clone());
Ok(distribution)
}
fn calculate_pswap_distribution(
amount_burned: Balance,
) -> Result<PswapRemintInfo, DispatchError> {
let amount_burned = FixedWrapper::from(amount_burned);
let amount_buy_back = (amount_burned.clone() * BuyBackXSTFraction::<T>::get())
.try_into_balance()
.map_err(|_| Error::<T>::CalculationError)?;
let mut amount_left = (amount_burned.clone() - amount_buy_back)
.try_into_balance()
.map_err(|_| Error::<T>::CalculationError)?;
let fraction_lp = fixed_wrapper!(1) - BurnRate::<T>::get();
let amount_lp = (FixedWrapper::from(amount_burned) * fraction_lp)
.try_into_balance()
.map_err(|_| Error::<T>::CalculationError)?;
let amount_lp = amount_lp.min(amount_left);
amount_left = amount_left.saturating_sub(amount_lp); let amount_vesting = amount_left.saturating_sub(T::PSWAP_BURN_PERCENT * amount_left); Ok(PswapRemintInfo {
liquidity_providers: amount_lp,
vesting: amount_vesting,
buy_back_xst: amount_buy_back,
})
}
pub fn incentive_distribution_routine(block_num: T::BlockNumber) -> DistributionWeightParams {
let tech_account_id = T::GetTechnicalAccountId::get();
let mut weight_params = DistributionWeightParams::default();
for (fees_account, (dex_id, pool_account, frequency, block_offset)) in
SubscribedAccounts::<T>::iter()
{
if (block_num.saturating_sub(block_offset) % frequency).is_zero() {
let _exchange_result = Self::exchange_fees_to_incentive(&fees_account, dex_id);
let distribute_result = common::with_transaction(|| {
Self::distribute_incentive(
&fees_account,
&dex_id,
&pool_account,
&tech_account_id,
)
});
match distribute_result {
Ok(shareholders) => {
weight_params.shareholders += shareholders;
}
Err(err) => {
frame_support::log::error!("Incentive distribution failed: {err:?}");
Self::deposit_event(Event::<T>::IncentiveDistributionFailed(
dex_id,
fees_account,
));
}
}
weight_params.distributed += 1;
} else {
weight_params.skipped += 1;
}
}
weight_params
}
fn update_burn_rate() {
let mut burn_rate = BurnRate::<T>::get();
let (increase_delta, max) = BurnUpdateInfo::<T>::get();
if burn_rate < max {
burn_rate = max.min(burn_rate.cadd(increase_delta).unwrap());
BurnRate::<T>::mutate(|val| *val = burn_rate.clone());
Self::deposit_event(Event::<T>::BurnRateChanged(burn_rate))
}
}
pub fn burn_rate_update_routine(block_num: T::BlockNumber) {
if (block_num % T::GetBurnUpdateFrequency::get()).is_zero() {
Self::update_burn_rate();
}
}
}
impl<T: Config> OnPoolCreated for Pallet<T> {
type AccountId = AccountIdOf<T>;
type DEXId = DexIdOf<T>;
fn on_pool_created(
fee_account: Self::AccountId,
dex_id: Self::DEXId,
pool_account: Self::AccountId,
) -> DispatchResult {
Self::subscribe(fee_account, dex_id, pool_account, None)
}
}
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use common::{AccountIdOf, DEXInfo, PoolXykPallet};
use frame_support::pallet_prelude::*;
use frame_support::sp_runtime::Percent;
use frame_support::traits::StorageVersion;
use frame_system::pallet_prelude::*;
#[pallet::config]
pub trait Config:
frame_system::Config + common::Config + assets::Config + technical::Config
{
const PSWAP_BURN_PERCENT: Percent;
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type GetIncentiveAssetId: Get<Self::AssetId>;
type GetXSTAssetId: Get<Self::AssetId>;
type LiquidityProxy: LiquidityProxyTrait<Self::DEXId, Self::AccountId, Self::AssetId>;
type CompatBalance: From<<Self as tokens::Config>::Balance>
+ Into<Balance>
+ From<Balance>
+ Clone
+ Zero;
type GetTechnicalAccountId: Get<Self::AccountId>;
type GetDefaultSubscriptionFrequency: Get<Self::BlockNumber>;
type GetBurnUpdateFrequency: Get<Self::BlockNumber>;
type EnsureDEXManager: EnsureDEXManager<Self::DEXId, Self::AccountId, DispatchError>;
type OnPswapBurnedAggregator: OnPswapBurned;
type WeightInfo: WeightInfo;
type GetParliamentAccountId: Get<Self::AccountId>;
type PoolXykPallet: PoolXykPallet<Self::AccountId, Self::AssetId>;
type BuyBackHandler: BuyBackHandler<Self::AccountId, Self::AssetId>;
type DexInfoProvider: DexInfoProvider<Self::DEXId, DEXInfo<Self::AssetId>>;
}
const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
#[pallet::storage_version(STORAGE_VERSION)]
#[pallet::without_storage_info]
pub struct Pallet<T>(PhantomData<T>);
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_initialize(block_num: T::BlockNumber) -> Weight {
let weight_params = Self::incentive_distribution_routine(block_num);
Self::burn_rate_update_routine(block_num);
<T as Config>::WeightInfo::on_initialize(
weight_params.skipped,
weight_params.distributed,
weight_params.shareholders,
)
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(<T as Config>::WeightInfo::claim_incentive())]
pub fn claim_incentive(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
let who = ensure_signed(origin)?;
Self::claim_by_account(&who)?;
Ok(().into())
}
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
FeesExchanged(
DexIdOf<T>,
AccountIdOf<T>,
AssetIdOf<T>,
Balance,
AssetIdOf<T>,
Balance,
),
FeesExchangeFailed(
DexIdOf<T>,
AccountIdOf<T>,
AssetIdOf<T>,
Balance,
AssetIdOf<T>,
DispatchError,
),
IncentiveDistributed(DexIdOf<T>, AccountIdOf<T>, AssetIdOf<T>, Balance, u128),
IncentiveDistributionFailed(DexIdOf<T>, AccountIdOf<T>),
BurnRateChanged(Fixed),
NothingToExchange(DexIdOf<T>, AccountIdOf<T>),
NothingToDistribute(DexIdOf<T>, AccountIdOf<T>),
IncentivesBurnedAfterExchange(DexIdOf<T>, AssetIdOf<T>, Balance, Balance),
}
#[pallet::error]
pub enum Error<T> {
CalculationError,
SubscriptionActive,
UnknownSubscription,
InvalidFrequency,
ZeroClaimableIncentives,
IncRefError,
}
#[pallet::storage]
#[pallet::getter(fn subscribed_accounts)]
pub type SubscribedAccounts<T: Config> = StorageMap<
_,
Blake2_128Concat,
T::AccountId,
(T::DEXId, AccountIdOf<T>, T::BlockNumber, T::BlockNumber),
>;
#[pallet::storage]
#[pallet::getter(fn burn_rate)]
pub type BurnRate<T: Config> = StorageValue<_, Fixed, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn burn_update_info)]
pub(super) type BurnUpdateInfo<T: Config> = StorageValue<_, (Fixed, Fixed), ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn shareholder_accounts)]
pub type ShareholderAccounts<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, Fixed, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn claimable_shares)]
pub type ClaimableShares<T: Config> = StorageValue<_, Fixed, ValueQuery>;
#[pallet::type_value]
pub(super) fn DefaultForBuyBackXSTFraction() -> Fixed {
fixed!(0.1)
}
#[pallet::storage]
#[pallet::getter(fn buy_back_xst_fraction)]
pub(super) type BuyBackXSTFraction<T: Config> =
StorageValue<_, Fixed, ValueQuery, DefaultForBuyBackXSTFraction>;
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub subscribed_accounts: Vec<(
T::AccountId,
(DexIdOf<T>, AccountIdOf<T>, T::BlockNumber, T::BlockNumber),
)>,
pub burn_info: (Fixed, Fixed, Fixed),
}
#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self {
subscribed_accounts: Default::default(),
burn_info: Default::default(),
}
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
fn build(&self) {
self.subscribed_accounts.iter().for_each(
|(fees_account, (dex_id, pool_account, freq, block_offset))| {
frame_system::Pallet::<T>::inc_consumers(&fees_account).unwrap();
SubscribedAccounts::<T>::insert(
fees_account,
(dex_id, pool_account, freq, block_offset),
);
},
);
let (initial_rate, increase_delta, max) = self.burn_info;
BurnRate::<T>::mutate(|rate| *rate = initial_rate);
BurnUpdateInfo::<T>::mutate(|info| *info = (increase_delta, max));
}
}
}