From 35da4ee40eea67e6d3b2b80d7529498df26350f5 Mon Sep 17 00:00:00 2001 From: PraetorP Date: Thu, 08 Sep 2022 11:41:21 +0000 Subject: [PATCH] code refactor & comments --- --- 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", --- 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. + +## [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 --- 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" --- a/pallets/app-promotion/src/lib.rs +++ b/pallets/app-promotion/src/lib.rs @@ -22,9 +22,6 @@ //! //! ### Dispatchable Functions //! -//! * `start_inflation` - This method sets the inflation start date. Can be only called once. -//! Inflation start block can be backdated and will catch up. The method will create Treasury -//! account if it does not exist and perform the first inflation deposit. // #![recursion_limit = "1024"] #![cfg_attr(not(feature = "std"), no_std)] @@ -48,7 +45,6 @@ use pallet_balances::BalanceLock; pub use types::*; -// use up_common::constants::{DAYS, UNIQUE}; use up_data_structs::CollectionId; use frame_support::{ @@ -87,16 +83,20 @@ #[pallet::config] pub trait Config: frame_system::Config + pallet_evm::account::Config { + /// Type to interact with the native token type Currency: ExtendedLockableCurrency + ReservableCurrency; + /// Type for interacting with collections type CollectionHandler: CollectionHandler< AccountId = Self::AccountId, CollectionId = CollectionId, >; + /// Type for interacting with conrtacts type ContractHandler: ContractHandler; + /// ID for treasury type TreasuryAccountId: Get; /// The app's pallet id, used for deriving its sovereign account ID. @@ -106,15 +106,18 @@ /// In relay blocks. #[pallet::constant] type RecalculationInterval: Get; - /// In relay blocks. + + /// In parachain blocks. #[pallet::constant] type PendingInterval: Get; + /// Rate of return for interval in blocks defined in `RecalculationInterval`. #[pallet::constant] - type Nominal: Get>; + type IntervalIncome: Get; + /// Decimals for the `Currency`. #[pallet::constant] - type IntervalIncome: Get; + type Nominal: Get>; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; @@ -133,6 +136,12 @@ #[pallet::event] #[pallet::generate_deposit(fn deposit_event)] pub enum Event { + /// Staking recalculation was performed + /// + /// # Arguments + /// * AccountId: ID of the staker. + /// * Balance : recalculation base + /// * Balance : total income StakingRecalculation( /// An recalculated staker T::AccountId, @@ -141,22 +150,42 @@ /// Amount of accrued interest BalanceOf, ), + + /// Staking was performed + /// + /// # Arguments + /// * AccountId: ID of the staker + /// * Balance : staking amount Stake(T::AccountId, BalanceOf), + + /// Unstaking was performed + /// + /// # Arguments + /// * AccountId: ID of the staker + /// * Balance : unstaking amount Unstake(T::AccountId, BalanceOf), + + /// The admin was set + /// + /// # Arguments + /// * AccountId: ID of the admin SetAdmin(T::AccountId), } #[pallet::error] pub enum Error { - /// Error due to action requiring admin to be set + /// Error due to action requiring admin to be set. AdminNotSet, - /// No permission to perform an action + /// No permission to perform an action. NoPermission, - /// Insufficient funds to perform an action + /// Insufficient funds to perform an action. NotSufficientFunds, + /// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded. PendingForBlockOverflow, - /// An error related to the fact that an invalid argument was passed to perform an action + /// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action. SponsorNotSet, + /// Errors caused by incorrect actions with a locked balance. + IncorrectLockedBalanceOperation, } #[pallet::storage] @@ -189,7 +218,7 @@ ValueQuery, >; - /// 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. #[pallet::storage] #[pallet::getter(fn get_next_calculated_record)] @@ -198,6 +227,9 @@ #[pallet::hooks] impl Hooks> for Pallet { + /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize + /// implies the execution of a strictly limited number of relatively lightweight operations. + /// A separate benchmark has been implemented to scale the weight depending on the number of pendings. fn on_initialize(current_block_number: T::BlockNumber) -> Weight where ::BlockNumber: From, @@ -242,15 +274,13 @@ ); ensure!( - amount >= Into::>::into(100u128) * T::Nominal::get(), + amount >= >::from(100u128) * T::Nominal::get(), ArithmeticError::Underflow ); let balance = <::Currency as Currency>::free_balance(&staker_id); - // ensure!(balance >= amount, ArithmeticError::Underflow); - <::Currency as Currency>::ensure_can_withdraw( &staker_id, amount, @@ -325,7 +355,7 @@ >::insert(block, pendings); - Self::unlock_balance_unchecked(&staker_id, total_staked); + Self::unlock_balance(&staker_id, total_staked)?; >::reserve(&staker_id, total_staked)?; @@ -400,8 +430,9 @@ ); ensure!( - T::ContractHandler::sponsor(contract_id)?.ok_or(>::SponsorNotSet)? - == T::CrossAccountId::from_sub(Self::account_id()), + T::ContractHandler::sponsor(contract_id)? + .ok_or(>::SponsorNotSet)? + .as_sub() == &Self::account_id(), >::NoPermission ); T::ContractHandler::remove_contract_sponsor(contract_id) @@ -469,77 +500,9 @@ // / T::RecalculationInterval::get()) // .into() + 1, // &mut income_acc, - // ); - // } - // } - // } - - // { - // let mut stakers_number = stakers_number.unwrap_or(20); - // let last_id = RefCell::new(None); - // let income_acc = RefCell::new(BalanceOf::::default()); - // let amount_acc = RefCell::new(BalanceOf::::default()); - - // let flush_stake = || -> DispatchResult { - // if let Some(last_id) = &*last_id.borrow() { - // if !income_acc.borrow().is_zero() { - // >::transfer( - // &T::TreasuryAccountId::get(), - // last_id, - // *income_acc.borrow(), - // ExistenceRequirement::KeepAlive, - // ) - // .and_then(|_| { - // Self::add_lock_balance(last_id, *income_acc.borrow()); - // >::try_mutate(|staked| { - // staked - // .checked_add(&*income_acc.borrow()) - // .ok_or(ArithmeticError::Overflow.into()) - // }) - // })?; - - // Self::deposit_event(Event::StakingRecalculation( - // last_id.clone(), - // *amount_acc.borrow(), - // *income_acc.borrow(), - // )); - // } - - // *income_acc.borrow_mut() = BalanceOf::::default(); - // *amount_acc.borrow_mut() = BalanceOf::::default(); - // } - // Ok(()) - // }; - - // while let Some(( - // (current_id, staked_block), - // (amount, next_recalc_block_for_stake), - // )) = storage_iterator.next() - // { - // if stakers_number == 0 { - // NextCalculatedRecord::::set(Some((current_id, staked_block))); - // break; - // } - // stakers_number -= 1; - // if last_id.borrow().as_ref() != Some(¤t_id) { - // flush_stake()?; - // }; - // *last_id.borrow_mut() = Some(current_id.clone()); - // if current_recalc_block >= next_recalc_block_for_stake { - // *amount_acc.borrow_mut() += amount; - // Self::recalculate_and_insert_stake( - // ¤t_id, - // staked_block, - // next_recalc_block, - // amount, - // ((current_recalc_block - next_recalc_block_for_stake) - // / T::RecalculationInterval::get()) - // .into() + 1, - // &mut *income_acc.borrow_mut(), // ); // } // } - // flush_stake()?; // } { @@ -620,10 +583,20 @@ T::PalletId::get().into_account_truncating() } - fn unlock_balance_unchecked(staker: &T::AccountId, amount: BalanceOf) { - let mut locked_balance = Self::get_locked_balance(staker).map(|l| l.amount).unwrap(); - locked_balance -= amount; - Self::set_lock_unchecked(staker, locked_balance); + fn unlock_balance(staker: &T::AccountId, amount: BalanceOf) -> DispatchResult { + let locked_balance = Self::get_locked_balance(staker) + .map(|l| l.amount) + .ok_or(>::IncorrectLockedBalanceOperation)?; + + // It is understood that we cannot unlock more funds than were locked by staking. + // Therefore, if implemented correctly, this error should not occur. + Self::set_lock_unchecked( + staker, + locked_balance + .checked_sub(&amount) + .ok_or(ArithmeticError::Underflow)?, + ); + Ok(()) } fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf) -> DispatchResult { @@ -745,6 +718,9 @@ where <::Currency as Currency>::Balance: Sum, { + /// Since user funds are not transferred anywhere by staking, overflow protection is provided + /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow, + /// the staker must have more funds on his account than the maximum set for `Balance` type. pub fn cross_id_pending_unstake(staker: Option) -> BalanceOf { staker.map_or( PendingUnstake::::iter_values() --- 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 --- 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 { appPromotion: { + /** + * Rate of return for interval in blocks defined in `RecalculationInterval`. + **/ intervalIncome: Perbill & AugmentedConst; + /** + * Decimals for the `Currency`. + **/ nominal: u128 & AugmentedConst; /** * The app's pallet id, used for deriving its sovereign account ID. **/ palletId: FrameSupportPalletId & AugmentedConst; /** - * In relay blocks. + * In parachain blocks. **/ pendingInterval: u32 & AugmentedConst; /** --- a/tests/src/interfaces/augment-api-errors.ts +++ b/tests/src/interfaces/augment-api-errors.ts @@ -13,23 +13,30 @@ interface AugmentedErrors { appPromotion: { /** - * Error due to action requiring admin to be set + * Error due to action requiring admin to be set. **/ AdminNotSet: AugmentedError; /** - * 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; + IncorrectLockedBalanceOperation: AugmentedError; /** - * No permission to perform an action + * No permission to perform an action. **/ NoPermission: AugmentedError; /** - * Insufficient funds to perform an action + * Insufficient funds to perform an action. **/ NotSufficientFunds: AugmentedError; + /** + * Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded. + **/ PendingForBlockOverflow: AugmentedError; /** + * The error is due to the fact that the collection/contract must already be sponsored in order to perform the action. + **/ + SponsorNotSet: AugmentedError; + /** * Generic error **/ [key: string]: AugmentedError; --- 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 { appPromotion: { + /** + * The admin was set + * + * # Arguments + * * AccountId: ID of the admin + **/ SetAdmin: AugmentedEvent; + /** + * Staking was performed + * + * # Arguments + * * AccountId: ID of the staker + * * Balance : staking amount + **/ Stake: AugmentedEvent; + /** + * Staking recalculation was performed + * + * # Arguments + * * AccountId: ID of the staker. + * * Balance : recalculation base + * * Balance : total income + **/ StakingRecalculation: AugmentedEvent; + /** + * Unstaking was performed + * + * # Arguments + * * AccountId: ID of the staker + * * Balance : unstaking amount + **/ Unstake: AugmentedEvent; /** * Generic event --- a/tests/src/interfaces/augment-api-query.ts +++ b/tests/src/interfaces/augment-api-query.ts @@ -20,13 +20,10 @@ appPromotion: { admin: AugmentedQuery Observable>, []> & QueryableStorageEntry; /** - * 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 Observable>>, []> & QueryableStorageEntry; - /** - * Amount of tokens pending unstake per user per block. - **/ pendingUnstake: AugmentedQuery Observable>>, [u32]> & QueryableStorageEntry; /** * Amount of tokens staked by account in the blocknumber. --- 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 */ --- a/tests/src/interfaces/lookup.ts +++ b/tests/src/interfaces/lookup.ts @@ -3115,7 +3115,7 @@ * Lookup416: pallet_app_promotion::pallet::Error **/ PalletAppPromotionError: { - _enum: ['AdminNotSet', 'NoPermission', 'NotSufficientFunds', 'PendingForBlockOverflow', 'InvalidArgument'] + _enum: ['AdminNotSet', 'NoPermission', 'NotSufficientFunds', 'PendingForBlockOverflow', 'SponsorNotSet', 'IncorrectLockedBalanceOperation'] }, /** * Lookup419: pallet_evm::pallet::Error --- 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) */ -- gitstuff