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
--- 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<Self::AccountId>
 			+ ReservableCurrency<Self::AccountId>;
 
+		/// Type for interacting with collections
 		type CollectionHandler: CollectionHandler<
 			AccountId = Self::AccountId,
 			CollectionId = CollectionId,
 		>;
 
+		/// Type for interacting with conrtacts
 		type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;
 
+		/// ID for treasury
 		type TreasuryAccountId: Get<Self::AccountId>;
 
 		/// The app's pallet id, used for deriving its sovereign account ID.
@@ -106,15 +106,18 @@
 		/// In relay blocks.
 		#[pallet::constant]
 		type RecalculationInterval: Get<Self::BlockNumber>;
-		/// In relay blocks.
+
+		/// In parachain blocks.
 		#[pallet::constant]
 		type PendingInterval: Get<Self::BlockNumber>;
 
+		/// Rate of return for interval in blocks defined in `RecalculationInterval`.
 		#[pallet::constant]
-		type Nominal: Get<BalanceOf<Self>>;
+		type IntervalIncome: Get<Perbill>;
 
+		/// Decimals for the `Currency`.
 		#[pallet::constant]
-		type IntervalIncome: Get<Perbill>;
+		type Nominal: Get<BalanceOf<Self>>;
 
 		/// 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<T: Config> {
+		/// 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<T>,
 		),
+		
+		/// Staking was performed
+		///
+		/// # Arguments
+		/// * AccountId: ID of the staker
+		/// * Balance : staking amount
 		Stake(T::AccountId, BalanceOf<T>),
+		
+		/// Unstaking was performed
+		///
+		/// # Arguments
+		/// * AccountId: ID of the staker
+		/// * Balance : unstaking amount
 		Unstake(T::AccountId, BalanceOf<T>),
+		
+		/// The admin was set
+		///
+		/// # Arguments
+		/// * AccountId: ID of the admin
 		SetAdmin(T::AccountId),
 	}
 
 	#[pallet::error]
 	pub enum Error<T> {
-		/// 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<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
+		/// 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
 			<T as frame_system::Config>::BlockNumber: From<u32>,
@@ -242,15 +274,13 @@
 			);
 
 			ensure!(
-				amount >= Into::<BalanceOf<T>>::into(100u128) * T::Nominal::get(),
+				amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),
 				ArithmeticError::Underflow
 			);
 
 			let balance =
 				<<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);
 
-			// ensure!(balance >= amount, ArithmeticError::Underflow);
-
 			<<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(
 				&staker_id,
 				amount,
@@ -325,7 +355,7 @@
 
 			<PendingUnstake<T>>::insert(block, pendings);
 
-			Self::unlock_balance_unchecked(&staker_id, total_staked);
+			Self::unlock_balance(&staker_id, total_staked)?;
 
 			<T::Currency as ReservableCurrency<T::AccountId>>::reserve(&staker_id, total_staked)?;
 
@@ -400,8 +430,9 @@
 			);
 
 			ensure!(
-				T::ContractHandler::sponsor(contract_id)?.ok_or(<Error<T>>::SponsorNotSet)?
-					== T::CrossAccountId::from_sub(Self::account_id()),
+				T::ContractHandler::sponsor(contract_id)?
+					.ok_or(<Error<T>>::SponsorNotSet)?
+					.as_sub() == &Self::account_id(),
 				<Error<T>>::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::<T>::default());
-			// 	let amount_acc = RefCell::new(BalanceOf::<T>::default());
-
-			// 	let flush_stake = || -> DispatchResult {
-			// 		if let Some(last_id) = &*last_id.borrow() {
-			// 			if !income_acc.borrow().is_zero() {
-			// 				<T::Currency as Currency<T::AccountId>>::transfer(
-			// 					&T::TreasuryAccountId::get(),
-			// 					last_id,
-			// 					*income_acc.borrow(),
-			// 					ExistenceRequirement::KeepAlive,
-			// 				)
-			// 				.and_then(|_| {
-			// 					Self::add_lock_balance(last_id, *income_acc.borrow());
-			// 					<TotalStaked<T>>::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::<T>::default();
-			// 			*amount_acc.borrow_mut() = BalanceOf::<T>::default();
-			// 		}
-			// 		Ok(())
-			// 	};
-
-			// 	while let Some((
-			// 		(current_id, staked_block),
-			// 		(amount, next_recalc_block_for_stake),
-			// 	)) = storage_iterator.next()
-			// 	{
-			// 		if stakers_number == 0 {
-			// 			NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));
-			// 			break;
-			// 		}
-			// 		stakers_number -= 1;
-			// 		if last_id.borrow().as_ref() != Some(&current_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(
-			// 				&current_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<T>) {
-		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<T>) -> DispatchResult {
+		let locked_balance = Self::get_locked_balance(staker)
+			.map(|l| l.amount)
+			.ok_or(<Error<T>>::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<T>) -> DispatchResult {
@@ -745,6 +718,9 @@
 where
 	<<T as Config>::Currency as Currency<T::AccountId>>::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<T::CrossAccountId>) -> BalanceOf<T> {
 		staker.map_or(
 			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
19 interface AugmentedQueries<ApiType extends ApiTypes> {19 interface AugmentedQueries<ApiType extends ApiTypes> {
20 appPromotion: {20 appPromotion: {
21 admin: AugmentedQuery<ApiType, () => Observable<Option<AccountId32>>, []> & QueryableStorageEntry<ApiType, []>;21 admin: AugmentedQuery<ApiType, () => Observable<Option<AccountId32>>, []> & QueryableStorageEntry<ApiType, []>;
22 /**22 /**
23 * Stores hash a record for which the last revenue recalculation was performed.23 * Stores a key for record for which the next revenue recalculation would be performed.
24 * If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.24 * If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.
25 **/25 **/
26 nextCalculatedRecord: AugmentedQuery<ApiType, () => Observable<Option<ITuple<[AccountId32, u32]>>>, []> & QueryableStorageEntry<ApiType, []>;26 nextCalculatedRecord: AugmentedQuery<ApiType, () => Observable<Option<ITuple<[AccountId32, u32]>>>, []> & QueryableStorageEntry<ApiType, []>;
27 /**
28 * Amount of tokens pending unstake per user per block.
29 **/
30 pendingUnstake: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Vec<ITuple<[AccountId32, u128]>>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;27 pendingUnstake: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Vec<ITuple<[AccountId32, u128]>>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
31 /**28 /**
32 * Amount of tokens staked by account in the blocknumber.29 * 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) */