git.delta.rocks / unique-network / refs/commits / 35da4ee40eea

difftreelog

code refactor & comments

PraetorP2022-09-08parent: #f980616.patch.diff
in: master

12 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -12147,7 +12147,7 @@
 
 [[package]]
 name = "uc-rpc"
-version = "0.1.3"
+version = "0.1.4"
 dependencies = [
  "anyhow",
  "app-promotion-rpc",
modifiedclient/rpc/CHANGELOG.mddiffbeforeafterboth
--- a/client/rpc/CHANGELOG.md
+++ b/client/rpc/CHANGELOG.md
@@ -3,15 +3,21 @@
 All notable changes to this project will be documented in this file.
 
 <!-- bureaucrate goes here -->
+
+## [v0.1.4] 2022-09-08
+
+### Added
+-  Support RPC for `AppPromotion` pallet. 
+
 ## [v0.1.3] 2022-08-16
 
 ### Other changes
 
-- build: Upgrade polkadot to v0.9.27 2c498572636f2b34d53b1c51b7283a761a7dc90a
+-   build: Upgrade polkadot to v0.9.27 2c498572636f2b34d53b1c51b7283a761a7dc90a
 
-- build: Upgrade polkadot to v0.9.26 85515e54c4ca1b82a2630034e55dcc804c643bf8
+-   build: Upgrade polkadot to v0.9.26 85515e54c4ca1b82a2630034e55dcc804c643bf8
 
-- build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
+-   build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
 
 ## [0.1.2] - 2022-08-12
 
modifiedclient/rpc/Cargo.tomldiffbeforeafterboth
--- a/client/rpc/Cargo.toml
+++ b/client/rpc/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "uc-rpc"
-version = "0.1.3"
+version = "0.1.4"
 license = "GPLv3"
 edition = "2021"
 
modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
22//!22//!
23//! ### Dispatchable Functions23//! ### Dispatchable Functions
24//!24//!
25//! * `start_inflation` - This method sets the inflation start date. Can be only called once.
26//! Inflation start block can be backdated and will catch up. The method will create Treasury
27//! account if it does not exist and perform the first inflation deposit.
2825
29// #![recursion_limit = "1024"]26// #![recursion_limit = "1024"]
30#![cfg_attr(not(feature = "std"), no_std)]27#![cfg_attr(not(feature = "std"), no_std)]
48use pallet_balances::BalanceLock;45use pallet_balances::BalanceLock;
49pub use types::*;46pub use types::*;
5047
51// use up_common::constants::{DAYS, UNIQUE};
52use up_data_structs::CollectionId;48use up_data_structs::CollectionId;
5349
54use frame_support::{50use frame_support::{
8783
88 #[pallet::config]84 #[pallet::config]
89 pub trait Config: frame_system::Config + pallet_evm::account::Config {85 pub trait Config: frame_system::Config + pallet_evm::account::Config {
86 /// Type to interact with the native token
90 type Currency: ExtendedLockableCurrency<Self::AccountId>87 type Currency: ExtendedLockableCurrency<Self::AccountId>
91 + ReservableCurrency<Self::AccountId>;88 + ReservableCurrency<Self::AccountId>;
9289
90 /// Type for interacting with collections
93 type CollectionHandler: CollectionHandler<91 type CollectionHandler: CollectionHandler<
94 AccountId = Self::AccountId,92 AccountId = Self::AccountId,
95 CollectionId = CollectionId,93 CollectionId = CollectionId,
96 >;94 >;
9795
96 /// Type for interacting with conrtacts
98 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;97 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;
9998
99 /// ID for treasury
100 type TreasuryAccountId: Get<Self::AccountId>;100 type TreasuryAccountId: Get<Self::AccountId>;
101101
102 /// The app's pallet id, used for deriving its sovereign account ID.102 /// The app's pallet id, used for deriving its sovereign account ID.
107 #[pallet::constant]107 #[pallet::constant]
108 type RecalculationInterval: Get<Self::BlockNumber>;108 type RecalculationInterval: Get<Self::BlockNumber>;
109
109 /// In relay blocks.110 /// In parachain blocks.
110 #[pallet::constant]111 #[pallet::constant]
111 type PendingInterval: Get<Self::BlockNumber>;112 type PendingInterval: Get<Self::BlockNumber>;
112113
114 /// Rate of return for interval in blocks defined in `RecalculationInterval`.
113 #[pallet::constant]115 #[pallet::constant]
114 type Nominal: Get<BalanceOf<Self>>;116 type IntervalIncome: Get<Perbill>;
115117
118 /// Decimals for the `Currency`.
116 #[pallet::constant]119 #[pallet::constant]
117 type IntervalIncome: Get<Perbill>;120 type Nominal: Get<BalanceOf<Self>>;
118121
119 /// Weight information for extrinsics in this pallet.122 /// Weight information for extrinsics in this pallet.
120 type WeightInfo: WeightInfo;123 type WeightInfo: WeightInfo;
133 #[pallet::event]136 #[pallet::event]
134 #[pallet::generate_deposit(fn deposit_event)]137 #[pallet::generate_deposit(fn deposit_event)]
135 pub enum Event<T: Config> {138 pub enum Event<T: Config> {
139 /// Staking recalculation was performed
140 ///
141 /// # Arguments
142 /// * AccountId: ID of the staker.
143 /// * Balance : recalculation base
144 /// * Balance : total income
136 StakingRecalculation(145 StakingRecalculation(
137 /// An recalculated staker146 /// An recalculated staker
138 T::AccountId,147 T::AccountId,
142 BalanceOf<T>,151 BalanceOf<T>,
143 ),152 ),
153
154 /// Staking was performed
155 ///
156 /// # Arguments
157 /// * AccountId: ID of the staker
158 /// * Balance : staking amount
144 Stake(T::AccountId, BalanceOf<T>),159 Stake(T::AccountId, BalanceOf<T>),
160
161 /// Unstaking was performed
162 ///
163 /// # Arguments
164 /// * AccountId: ID of the staker
165 /// * Balance : unstaking amount
145 Unstake(T::AccountId, BalanceOf<T>),166 Unstake(T::AccountId, BalanceOf<T>),
167
168 /// The admin was set
169 ///
170 /// # Arguments
171 /// * AccountId: ID of the admin
146 SetAdmin(T::AccountId),172 SetAdmin(T::AccountId),
147 }173 }
148174
149 #[pallet::error]175 #[pallet::error]
150 pub enum Error<T> {176 pub enum Error<T> {
151 /// Error due to action requiring admin to be set177 /// Error due to action requiring admin to be set.
152 AdminNotSet,178 AdminNotSet,
153 /// No permission to perform an action179 /// No permission to perform an action.
154 NoPermission,180 NoPermission,
155 /// Insufficient funds to perform an action181 /// Insufficient funds to perform an action.
156 NotSufficientFunds,182 NotSufficientFunds,
183 /// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.
157 PendingForBlockOverflow,184 PendingForBlockOverflow,
158 /// An error related to the fact that an invalid argument was passed to perform an action185 /// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.
159 SponsorNotSet,186 SponsorNotSet,
187 /// Errors caused by incorrect actions with a locked balance.
188 IncorrectLockedBalanceOperation,
160 }189 }
161190
162 #[pallet::storage]191 #[pallet::storage]
189 ValueQuery,218 ValueQuery,
190 >;219 >;
191220
192 /// Stores hash a record for which the last revenue recalculation was performed.221 /// Stores a key for record for which the next revenue recalculation would be performed.
193 /// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.222 /// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.
194 #[pallet::storage]223 #[pallet::storage]
195 #[pallet::getter(fn get_next_calculated_record)]224 #[pallet::getter(fn get_next_calculated_record)]
198227
199 #[pallet::hooks]228 #[pallet::hooks]
200 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {229 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
230 /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize
231 /// implies the execution of a strictly limited number of relatively lightweight operations.
232 /// A separate benchmark has been implemented to scale the weight depending on the number of pendings.
201 fn on_initialize(current_block_number: T::BlockNumber) -> Weight233 fn on_initialize(current_block_number: T::BlockNumber) -> Weight
202 where234 where
203 <T as frame_system::Config>::BlockNumber: From<u32>,235 <T as frame_system::Config>::BlockNumber: From<u32>,
242 );274 );
243275
244 ensure!(276 ensure!(
245 amount >= Into::<BalanceOf<T>>::into(100u128) * T::Nominal::get(),277 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),
246 ArithmeticError::Underflow278 ArithmeticError::Underflow
247 );279 );
248280
249 let balance =281 let balance =
250 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);282 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);
251
252 // ensure!(balance >= amount, ArithmeticError::Underflow);
253283
254 <<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(284 <<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(
255 &staker_id,285 &staker_id,
325355
326 <PendingUnstake<T>>::insert(block, pendings);356 <PendingUnstake<T>>::insert(block, pendings);
327357
328 Self::unlock_balance_unchecked(&staker_id, total_staked);358 Self::unlock_balance(&staker_id, total_staked)?;
329359
330 <T::Currency as ReservableCurrency<T::AccountId>>::reserve(&staker_id, total_staked)?;360 <T::Currency as ReservableCurrency<T::AccountId>>::reserve(&staker_id, total_staked)?;
331361
402 ensure!(432 ensure!(
403 T::ContractHandler::sponsor(contract_id)?.ok_or(<Error<T>>::SponsorNotSet)?433 T::ContractHandler::sponsor(contract_id)?
434 .ok_or(<Error<T>>::SponsorNotSet)?
404 == T::CrossAccountId::from_sub(Self::account_id()),435 .as_sub() == &Self::account_id(),
405 <Error<T>>::NoPermission436 <Error<T>>::NoPermission
406 );437 );
407 T::ContractHandler::remove_contract_sponsor(contract_id)438 T::ContractHandler::remove_contract_sponsor(contract_id)
474 // }505 // }
475 // }506 // }
476
477 // {
478 // let mut stakers_number = stakers_number.unwrap_or(20);
479 // let last_id = RefCell::new(None);
480 // let income_acc = RefCell::new(BalanceOf::<T>::default());
481 // let amount_acc = RefCell::new(BalanceOf::<T>::default());
482
483 // let flush_stake = || -> DispatchResult {
484 // if let Some(last_id) = &*last_id.borrow() {
485 // if !income_acc.borrow().is_zero() {
486 // <T::Currency as Currency<T::AccountId>>::transfer(
487 // &T::TreasuryAccountId::get(),
488 // last_id,
489 // *income_acc.borrow(),
490 // ExistenceRequirement::KeepAlive,
491 // )
492 // .and_then(|_| {
493 // Self::add_lock_balance(last_id, *income_acc.borrow());
494 // <TotalStaked<T>>::try_mutate(|staked| {
495 // staked
496 // .checked_add(&*income_acc.borrow())
497 // .ok_or(ArithmeticError::Overflow.into())
498 // })
499 // })?;
500
501 // Self::deposit_event(Event::StakingRecalculation(
502 // last_id.clone(),
503 // *amount_acc.borrow(),
504 // *income_acc.borrow(),
505 // ));
506 // }
507
508 // *income_acc.borrow_mut() = BalanceOf::<T>::default();
509 // *amount_acc.borrow_mut() = BalanceOf::<T>::default();
510 // }
511 // Ok(())
512 // };
513
514 // while let Some((
515 // (current_id, staked_block),
516 // (amount, next_recalc_block_for_stake),
517 // )) = storage_iterator.next()
518 // {
519 // if stakers_number == 0 {
520 // NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));
521 // break;
522 // }
523 // stakers_number -= 1;
524 // if last_id.borrow().as_ref() != Some(&current_id) {
525 // flush_stake()?;
526 // };
527 // *last_id.borrow_mut() = Some(current_id.clone());
528 // if current_recalc_block >= next_recalc_block_for_stake {
529 // *amount_acc.borrow_mut() += amount;
530 // Self::recalculate_and_insert_stake(
531 // &current_id,
532 // staked_block,
533 // next_recalc_block,
534 // amount,
535 // ((current_recalc_block - next_recalc_block_for_stake)
536 // / T::RecalculationInterval::get())
537 // .into() + 1,
538 // &mut *income_acc.borrow_mut(),
539 // );
540 // }
541 // }
542 // flush_stake()?;
543 // }
544507
545 {508 {
546 let mut stakers_number = stakers_number.unwrap_or(20);509 let mut stakers_number = stakers_number.unwrap_or(20);
620 T::PalletId::get().into_account_truncating()583 T::PalletId::get().into_account_truncating()
621 }584 }
622585
623 fn unlock_balance_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {586 fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {
624 let mut locked_balance = Self::get_locked_balance(staker).map(|l| l.amount).unwrap();587 let locked_balance = Self::get_locked_balance(staker)
625 locked_balance -= amount;588 .map(|l| l.amount)
589 .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;
590
591 // It is understood that we cannot unlock more funds than were locked by staking.
592 // Therefore, if implemented correctly, this error should not occur.
626 Self::set_lock_unchecked(staker, locked_balance);593 Self::set_lock_unchecked(
594 staker,
595 locked_balance
596 .checked_sub(&amount)
597 .ok_or(ArithmeticError::Underflow)?,
598 );
599 Ok(())
627 }600 }
628601
629 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {602 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {
745where718where
746 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,719 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,
747{720{
721 /// Since user funds are not transferred anywhere by staking, overflow protection is provided
722 /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,
723 /// the staker must have more funds on his account than the maximum set for `Balance` type.
748 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {724 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {
749 staker.map_or(725 staker.map_or(
750 PendingUnstake::<T>::iter_values()726 PendingUnstake::<T>::iter_values()
modifiedpallets/unique/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/unique/CHANGELOG.md
+++ b/pallets/unique/CHANGELOG.md
@@ -8,6 +8,8 @@
 
 ### Added
 
+-   Methods `force_set_sponsor` , `force_remove_collection_sponsor` to be able to administer sponsorships with other pallets. Added to implement `AppPromotion` pallet logic.
+
 ## [v0.1.3] 2022-08-16
 
 ### Other changes
modifiedtests/src/interfaces/augment-api-consts.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-consts.ts
+++ b/tests/src/interfaces/augment-api-consts.ts
@@ -16,14 +16,20 @@
 declare module '@polkadot/api-base/types/consts' {
   interface AugmentedConsts<ApiType extends ApiTypes> {
     appPromotion: {
+      /**
+       * Rate of return for interval in blocks defined in `RecalculationInterval`.
+       **/
       intervalIncome: Perbill & AugmentedConst<ApiType>;
+      /**
+       * Decimals for the `Currency`.
+       **/
       nominal: u128 & AugmentedConst<ApiType>;
       /**
        * The app's pallet id, used for deriving its sovereign account ID.
        **/
       palletId: FrameSupportPalletId & AugmentedConst<ApiType>;
       /**
-       * In relay blocks.
+       * In parachain blocks.
        **/
       pendingInterval: u32 & AugmentedConst<ApiType>;
       /**
modifiedtests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -13,23 +13,30 @@
   interface AugmentedErrors<ApiType extends ApiTypes> {
     appPromotion: {
       /**
-       * Error due to action requiring admin to be set
+       * Error due to action requiring admin to be set.
        **/
       AdminNotSet: AugmentedError<ApiType>;
       /**
-       * An error related to the fact that an invalid argument was passed to perform an action
+       * Errors caused by incorrect actions with a locked balance.
        **/
-      InvalidArgument: AugmentedError<ApiType>;
+      IncorrectLockedBalanceOperation: AugmentedError<ApiType>;
       /**
-       * No permission to perform an action
+       * No permission to perform an action.
        **/
       NoPermission: AugmentedError<ApiType>;
       /**
-       * Insufficient funds to perform an action
+       * Insufficient funds to perform an action.
        **/
       NotSufficientFunds: AugmentedError<ApiType>;
+      /**
+       * Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.
+       **/
       PendingForBlockOverflow: AugmentedError<ApiType>;
       /**
+       * The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.
+       **/
+      SponsorNotSet: AugmentedError<ApiType>;
+      /**
        * Generic error
        **/
       [key: string]: AugmentedError<ApiType>;
modifiedtests/src/interfaces/augment-api-events.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-events.ts
+++ b/tests/src/interfaces/augment-api-events.ts
@@ -16,9 +16,37 @@
 declare module '@polkadot/api-base/types/events' {
   interface AugmentedEvents<ApiType extends ApiTypes> {
     appPromotion: {
+      /**
+       * The admin was set
+       * 
+       * # Arguments
+       * * AccountId: ID of the admin
+       **/
       SetAdmin: AugmentedEvent<ApiType, [AccountId32]>;
+      /**
+       * Staking was performed
+       * 
+       * # Arguments
+       * * AccountId: ID of the staker
+       * * Balance : staking amount
+       **/
       Stake: AugmentedEvent<ApiType, [AccountId32, u128]>;
+      /**
+       * Staking recalculation was performed
+       * 
+       * # Arguments
+       * * AccountId: ID of the staker.
+       * * Balance : recalculation base
+       * * Balance : total income
+       **/
       StakingRecalculation: AugmentedEvent<ApiType, [AccountId32, u128, u128]>;
+      /**
+       * Unstaking was performed
+       * 
+       * # Arguments
+       * * AccountId: ID of the staker
+       * * Balance : unstaking amount
+       **/
       Unstake: AugmentedEvent<ApiType, [AccountId32, u128]>;
       /**
        * Generic event
modifiedtests/src/interfaces/augment-api-query.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-query.ts
+++ b/tests/src/interfaces/augment-api-query.ts
@@ -20,13 +20,10 @@
     appPromotion: {
       admin: AugmentedQuery<ApiType, () => Observable<Option<AccountId32>>, []> & QueryableStorageEntry<ApiType, []>;
       /**
-       * Stores hash a record for which the last revenue recalculation was performed.
+       * Stores a key for record for which the next revenue recalculation would be performed.
        * If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.
        **/
       nextCalculatedRecord: AugmentedQuery<ApiType, () => Observable<Option<ITuple<[AccountId32, u32]>>>, []> & QueryableStorageEntry<ApiType, []>;
-      /**
-       * Amount of tokens pending unstake per user per block.
-       **/
       pendingUnstake: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Vec<ITuple<[AccountId32, u128]>>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
       /**
        * Amount of tokens staked by account in the blocknumber.
modifiedtests/src/interfaces/default/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -846,8 +846,9 @@
   readonly isNoPermission: boolean;
   readonly isNotSufficientFunds: boolean;
   readonly isPendingForBlockOverflow: boolean;
-  readonly isInvalidArgument: boolean;
-  readonly type: 'AdminNotSet' | 'NoPermission' | 'NotSufficientFunds' | 'PendingForBlockOverflow' | 'InvalidArgument';
+  readonly isSponsorNotSet: boolean;
+  readonly isIncorrectLockedBalanceOperation: boolean;
+  readonly type: 'AdminNotSet' | 'NoPermission' | 'NotSufficientFunds' | 'PendingForBlockOverflow' | 'SponsorNotSet' | 'IncorrectLockedBalanceOperation';
 }
 
 /** @name PalletAppPromotionEvent */
modifiedtests/src/interfaces/lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -3115,7 +3115,7 @@
    * Lookup416: pallet_app_promotion::pallet::Error<T>
    **/
   PalletAppPromotionError: {
-    _enum: ['AdminNotSet', 'NoPermission', 'NotSufficientFunds', 'PendingForBlockOverflow', 'InvalidArgument']
+    _enum: ['AdminNotSet', 'NoPermission', 'NotSufficientFunds', 'PendingForBlockOverflow', 'SponsorNotSet', 'IncorrectLockedBalanceOperation']
   },
   /**
    * Lookup419: pallet_evm::pallet::Error<T>
modifiedtests/src/interfaces/types-lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -3309,8 +3309,9 @@
     readonly isNoPermission: boolean;
     readonly isNotSufficientFunds: boolean;
     readonly isPendingForBlockOverflow: boolean;
-    readonly isInvalidArgument: boolean;
-    readonly type: 'AdminNotSet' | 'NoPermission' | 'NotSufficientFunds' | 'PendingForBlockOverflow' | 'InvalidArgument';
+    readonly isSponsorNotSet: boolean;
+    readonly isIncorrectLockedBalanceOperation: boolean;
+    readonly type: 'AdminNotSet' | 'NoPermission' | 'NotSufficientFunds' | 'PendingForBlockOverflow' | 'SponsorNotSet' | 'IncorrectLockedBalanceOperation';
   }
 
   /** @name PalletEvmError (419) */