difftreelog
fix clippy warnings
in: master
36 files changed
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -110,7 +110,7 @@
/// Helper function to generate a crypto pair from seed
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
- TPublic::Pair::from_string(&format!("//{}", seed), None)
+ TPublic::Pair::from_string(&format!("//{seed}"), None)
.expect("static values are valid; qed")
.public()
}
node/cli/src/command.rsdiffbeforeafterboth--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -83,7 +83,7 @@
"" | "local" => Box::new(chain_spec::local_testnet_config()),
path => {
let path = std::path::PathBuf::from(path);
- let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path.clone())?)
+ let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path)?)
as Box<dyn sc_service::ChainSpec>;
match chain_spec.runtime_id() {
@@ -352,7 +352,7 @@
&polkadot_cli,
config.tokio_handle.clone(),
)
- .map_err(|err| format!("Relay chain argument error: {}", err))?;
+ .map_err(|err| format!("Relay chain argument error: {err}"))?;
cmd.run(config, polkadot_config)
})
@@ -464,7 +464,7 @@
runner.run_node_until_exit(|config| async move {
let hwbench = if !cli.no_hardware_benchmarks {
config.database.path().map(|database_path| {
- let _ = std::fs::create_dir_all(&database_path);
+ let _ = std::fs::create_dir_all(database_path);
sc_sysinfo::gather_hwbench(Some(database_path))
})
} else {
@@ -513,7 +513,7 @@
let state_version =
RelayChainCli::native_runtime_version(&config.chain_spec).state_version();
let block: Block = generate_genesis_block(&*config.chain_spec, state_version)
- .map_err(|e| format!("{:?}", e))?;
+ .map_err(|e| format!("{e:?}"))?;
let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));
let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));
@@ -522,7 +522,7 @@
&polkadot_cli,
config.tokio_handle.clone(),
)
- .map_err(|err| format!("Relay chain argument error: {}", err))?;
+ .map_err(|err| format!("Relay chain argument error: {err}"))?;
info!("Parachain id: {:?}", para_id);
info!("Parachain Account: {}", parachain_account);
node/cli/src/service.rsdiffbeforeafterboth--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -698,7 +698,7 @@
{
let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
- let block_import = ParachainBlockImport::new(client.clone(), backend.clone());
+ let block_import = ParachainBlockImport::new(client.clone(), backend);
cumulus_client_consensus_aura::import_queue::<
sp_consensus_aura::sr25519::AuthorityPair,
@@ -709,7 +709,7 @@
_,
>(cumulus_client_consensus_aura::ImportQueueParams {
block_import,
- client: client.clone(),
+ client,
create_inherent_data_providers: move |_, _| async move {
let time = sp_timestamp::InherentDataProvider::from_system_time();
@@ -787,7 +787,7 @@
telemetry.clone(),
);
- let block_import = ParachainBlockImport::new(client.clone(), backend.clone());
+ let block_import = ParachainBlockImport::new(client.clone(), backend);
Ok(AuraConsensus::build::<
sp_consensus_aura::sr25519::AuthorityPair,
@@ -864,7 +864,7 @@
ExecutorDispatch: NativeExecutionDispatch + 'static,
{
Ok(sc_consensus_manual_seal::import_queue(
- Box::new(client.clone()),
+ Box::new(client),
&task_manager.spawn_essential_handle(),
config.prometheus_registry(),
))
@@ -956,7 +956,7 @@
let collator = config.role.is_authority();
- let select_chain = maybe_select_chain.clone();
+ let select_chain = maybe_select_chain;
if collator {
let block_import =
node/rpc/src/lib.rsdiffbeforeafterboth--- a/node/rpc/src/lib.rs
+++ b/node/rpc/src/lib.rs
@@ -289,7 +289,7 @@
io.merge(
Net::new(
client.clone(),
- network.clone(),
+ network,
// Whether to format the `peer_count` response as Hex (default) or not.
true,
)
pallets/app-promotion/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # App Promotion pallet18//!19//! The pallet implements the mechanics of staking and sponsoring collections/contracts.20//!21//! - [`Config`]22//! - [`Pallet`]23//! - [`Error`]24//! - [`Event`]25//!26//! ## Overview27//! The App Promotion pallet allows fund holders to stake at a certain daily rate of return.28//! The mechanics implemented in the pallet allow it to act as a sponsor for collections / contracts,29//! the list of which is set by the pallet administrator.30//!31//!32//! ## Interface33//! The pallet provides interfaces for funds, collection/contract operations (see [types] module).3435//!36//! ### Dispatchable Functions37//! - [`set_admin_address`][`Pallet::set_admin_address`] - sets an address as the the admin.38//! - [`stake`][`Pallet::stake`] - stakes the amount of native tokens.39//! - [`unstake`][`Pallet::unstake`] - unstakes all stakes.40//! - [`sponsor_collection`][`Pallet::sponsor_collection`] - sets the pallet to be the sponsor for the collection.41//! - [`stop_sponsoring_collection`][`Pallet::stop_sponsoring_collection`] - removes the pallet as the sponsor for the collection.42//! - [`sponsor_contract`][`Pallet::sponsor_contract`] - sets the pallet to be the sponsor for the contract.43//! - [`stop_sponsoring_contract`][`Pallet::stop_sponsoring_contract`] - removes the pallet as the sponsor for the contract.44//! - [`payout_stakers`][`Pallet::payout_stakers`] - recalculates interest for the specified number of stakers.45//!4647// #![recursion_limit = "1024"]48#![cfg_attr(not(feature = "std"), no_std)]4950#[cfg(feature = "runtime-benchmarks")]51mod benchmarking;5253pub mod types;54pub mod weights;5556use sp_std::{57 vec::{Vec},58 vec,59 iter::Sum,60 borrow::ToOwned,61 cell::RefCell,62};63use sp_core::H160;64use codec::EncodeLike;65use pallet_balances::BalanceLock;66pub use types::*;6768use up_data_structs::CollectionId;6970use frame_support::{71 dispatch::{DispatchResult},72 traits::{73 Get, LockableCurrency,74 tokens::Balance,75 fungible::{Inspect, InspectFreeze, Mutate, MutateFreeze},76 },77 ensure, BoundedVec,78};7980use weights::WeightInfo;8182pub use pallet::*;83use pallet_evm::account::CrossAccountId;84use sp_runtime::{85 Perbill,86 traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},87 ArithmeticError, DispatchError,88};8990pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";9192const PENDING_LIMIT_PER_BLOCK: u32 = 3;9394type BalanceOf<T> =95 <<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;9697#[frame_support::pallet]98pub mod pallet {99 use super::*;100 use frame_support::{101 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId, weights::Weight,102 };103 use frame_system::pallet_prelude::*;104 use sp_runtime::DispatchError;105106 #[pallet::config]107 pub trait Config:108 frame_system::Config + pallet_evm::Config + pallet_configuration::Config109 {110 /// Type to interact with the native token111 type Currency: MutateFreeze<Self::AccountId>112 + Mutate<Self::AccountId>113 + ExtendedLockableCurrency<114 Self::AccountId,115 Balance = <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,116 >;117118 /// Type for interacting with collections119 type CollectionHandler: CollectionHandler<120 AccountId = Self::AccountId,121 CollectionId = CollectionId,122 >;123124 /// Type for interacting with conrtacts125 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;126127 /// `AccountId` for treasury128 type TreasuryAccountId: Get<Self::AccountId>;129130 /// The app's pallet id, used for deriving its sovereign account address.131 #[pallet::constant]132 type PalletId: Get<PalletId>;133134 /// Freeze identifier used by the pallet135 #[pallet::constant]136 type FreezeIdentifier: Get<137 <<Self as Config>::Currency as InspectFreeze<Self::AccountId>>::Id,138 >;139140 /// In relay blocks.141 #[pallet::constant]142 type RecalculationInterval: Get<Self::BlockNumber>;143144 /// In parachain blocks.145 #[pallet::constant]146 type PendingInterval: Get<Self::BlockNumber>;147148 /// Rate of return for interval in blocks defined in `RecalculationInterval`.149 #[pallet::constant]150 type IntervalIncome: Get<Perbill>;151152 /// Decimals for the `Currency`.153 #[pallet::constant]154 type Nominal: Get<BalanceOf<Self>>;155156 /// Maintenance mode status.157 type IsMaintenanceModeEnabled: Get<bool>;158159 /// Weight information for extrinsics in this pallet.160 type WeightInfo: WeightInfo;161162 // The relay block number provider163 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;164165 /// Events compatible with [`frame_system::Config::Event`].166 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;167 }168169 #[pallet::pallet]170 pub struct Pallet<T>(_);171172 #[pallet::event]173 #[pallet::generate_deposit(pub(super) fn deposit_event)]174 pub enum Event<T: Config> {175 /// Staking recalculation was performed176 ///177 /// # Arguments178 /// * AccountId: account of the staker.179 /// * Balance : recalculation base180 /// * Balance : total income181 StakingRecalculation(182 /// An recalculated staker183 T::AccountId,184 /// Base on which interest is calculated185 BalanceOf<T>,186 /// Amount of accrued interest187 BalanceOf<T>,188 ),189190 /// Staking was performed191 ///192 /// # Arguments193 /// * AccountId: account of the staker194 /// * Balance : staking amount195 Stake(T::AccountId, BalanceOf<T>),196197 /// Unstaking was performed198 ///199 /// # Arguments200 /// * AccountId: account of the staker201 /// * Balance : unstaking amount202 Unstake(T::AccountId, BalanceOf<T>),203204 /// The admin was set205 ///206 /// # Arguments207 /// * AccountId: account address of the admin208 SetAdmin(T::AccountId),209 }210211 #[pallet::error]212 pub enum Error<T> {213 /// Error due to action requiring admin to be set.214 AdminNotSet,215 /// No permission to perform an action.216 NoPermission,217 /// Insufficient funds to perform an action.218 NotSufficientFunds,219 /// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.220 PendingForBlockOverflow,221 /// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.222 SponsorNotSet,223 /// Errors caused by insufficient staked balance.224 InsufficientStakedBalance,225 /// Errors caused by incorrect state of a staker in context of the pallet.226 InconsistencyState,227 }228229 /// Stores the total staked amount.230 #[pallet::storage]231 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;232233 /// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.234 #[pallet::storage]235 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;236237 /// Stores the amount of tokens staked by account in the blocknumber.238 ///239 /// * **Key1** - Staker account.240 /// * **Key2** - Relay block number when the stake was made.241 /// * **(Balance, BlockNumber)** - Balance of the stake.242 /// The number of the relay block in which we must perform the interest recalculation243 #[pallet::storage]244 pub type Staked<T: Config> = StorageNMap<245 Key = (246 Key<Blake2_128Concat, T::AccountId>,247 Key<Twox64Concat, T::BlockNumber>,248 ),249 Value = (BalanceOf<T>, T::BlockNumber),250 QueryKind = ValueQuery,251 >;252253 /// Stores number of stake records for an `Account`.254 ///255 /// * **Key** - Staker account.256 /// * **Value** - Amount of stakes.257 #[pallet::storage]258 pub type StakesPerAccount<T: Config> =259 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;260261 /// Pending unstake records for an `Account`.262 ///263 /// * **Key** - Staker account.264 /// * **Value** - Amount of stakes.265 #[pallet::storage]266 pub type PendingUnstake<T: Config> = StorageMap<267 _,268 Twox64Concat,269 T::BlockNumber,270 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,271 ValueQuery,272 >;273274 /// Stores a key for record for which the revenue recalculation was performed.275 /// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.276 #[pallet::storage]277 #[pallet::getter(fn get_next_calculated_record)]278 pub type PreviousCalculatedRecord<T: Config> =279 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;280281 #[pallet::hooks]282 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {283 /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize284 /// implies the execution of a strictly limited number of relatively lightweight operations.285 /// A separate benchmark has been implemented to scale the weight depending on the number of pendings.286 fn on_initialize(current_block_number: T::BlockNumber) -> Weight287 where288 <T as frame_system::Config>::BlockNumber: From<u32>,289 {290 if T::IsMaintenanceModeEnabled::get() {291 return T::DbWeight::get().reads_writes(1, 0);292 }293294 let block_pending = PendingUnstake::<T>::take(current_block_number);295 let counter = block_pending.len() as u32;296297 if !block_pending.is_empty() {298 block_pending.into_iter().for_each(|(staker, amount)| {299 Self::get_frozen_balance(&staker).map(|b| {300 let new_state = b.checked_sub(&amount).unwrap_or_default();301302 // In this case, setting a new state for the frozen funds cannot fail303 // because the state change goes in the direction of decreasing the frozen funds304 // and the validity of this transition is ensured by the fact305 // that we cannot (in the current implementation) unfreeze more funds306 // than were originally frozen by the pallet. Either way, `on_initialize()` cannot fail.307 Self::set_freeze_unchecked(&staker, new_state);308 });309 });310 }311312 <T as Config>::WeightInfo::on_initialize(counter)313 }314 }315316 #[pallet::call]317 impl<T: Config> Pallet<T>318 where319 T::BlockNumber: From<u32> + Into<u32>,320 <<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,321 {322 /// Sets an address as the the admin.323 ///324 /// # Permissions325 ///326 /// * Sudo327 ///328 /// # Arguments329 ///330 /// * `admin`: account of the new admin.331 #[pallet::call_index(0)]332 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]333 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {334 ensure_root(origin)?;335336 <Admin<T>>::set(Some(admin.as_sub().to_owned()));337338 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));339340 Ok(())341 }342343 /// Stakes the amount of native tokens.344 /// Sets `amount` to the locked state.345 /// The maximum number of stakes for a staker is 10.346 ///347 /// # Arguments348 ///349 /// * `amount`: in native tokens.350 #[pallet::call_index(1)]351 #[pallet::weight(<T as Config>::WeightInfo::stake())]352 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {353 let staker_id = ensure_signed(staker)?;354355 ensure!(356 StakesPerAccount::<T>::get(&staker_id) < 10,357 Error::<T>::NoPermission358 );359360 ensure!(361 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),362 ArithmeticError::Underflow363 );364 let config = <PalletConfiguration<T>>::get();365366 let balance = <<T as Config>::Currency as Inspect<T::AccountId>>::balance(&staker_id);367368 // checks that we can freeze `amount` on the `staker` account.369 ensure!(370 amount371 <= match Self::get_frozen_balance(&staker_id) {372 Some(frozen_by_pallet) => balance373 .checked_sub(&frozen_by_pallet)374 .ok_or(ArithmeticError::Underflow)?,375 None => balance,376 },377 ArithmeticError::Underflow378 );379380 Self::add_freeze_balance(&staker_id, amount)?;381382 let block_number = T::RelayBlockNumberProvider::current_block_number();383384 // Calculation of the number of recalculation periods,385 // after how much the first interest calculation should be performed for the stake386 let recalculate_after_interval: T::BlockNumber =387 if block_number % config.recalculation_interval == 0u32.into() {388 1u32.into()389 } else {390 2u32.into()391 };392393 // Сalculation of the number of the relay block394 // in which it is necessary to accrue remuneration for the stake.395 let recalc_block = (block_number / config.recalculation_interval396 + recalculate_after_interval)397 * config.recalculation_interval;398399 <Staked<T>>::insert((&staker_id, block_number), {400 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));401 balance_and_recalc_block.0 = balance_and_recalc_block402 .0403 .checked_add(&amount)404 .ok_or(ArithmeticError::Overflow)?;405 balance_and_recalc_block.1 = recalc_block;406 balance_and_recalc_block407 });408409 <TotalStaked<T>>::set(410 <TotalStaked<T>>::get()411 .checked_add(&amount)412 .ok_or(ArithmeticError::Overflow)?,413 );414415 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);416417 Self::deposit_event(Event::Stake(staker_id, amount));418419 Ok(())420 }421422 /// Unstakes all stakes.423 /// After the end of `PendingInterval` this sum becomes completely424 /// free for further use.425 #[pallet::call_index(2)]426 #[pallet::weight(<T as Config>::WeightInfo::unstake_all())]427 pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {428 let staker_id = ensure_signed(staker)?;429430 Self::unstake_all_internal(staker_id)431 }432433 /// Unstakes the amount of balance for the staker.434 /// After the end of `PendingInterval` this sum becomes completely435 /// free for further use.436 ///437 /// # Arguments438 ///439 /// * `staker`: staker account.440 /// * `amount`: amount of unstaked funds.441 #[pallet::call_index(8)]442 #[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]443 pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {444 let staker_id = ensure_signed(staker)?;445446 Self::unstake_partial_internal(staker_id, amount)447 }448449 /// Sets the pallet to be the sponsor for the collection.450 ///451 /// # Permissions452 ///453 /// * Pallet admin454 ///455 /// # Arguments456 ///457 /// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`458 #[pallet::call_index(3)]459 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]460 pub fn sponsor_collection(461 admin: OriginFor<T>,462 collection_id: CollectionId,463 ) -> DispatchResult {464 let admin_id = ensure_signed(admin)?;465 ensure!(466 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,467 Error::<T>::NoPermission468 );469470 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)471 }472473 /// Removes the pallet as the sponsor for the collection.474 /// Returns [`NoPermission`][`Error::NoPermission`]475 /// if the pallet wasn't the sponsor.476 ///477 /// # Permissions478 ///479 /// * Pallet admin480 ///481 /// # Arguments482 ///483 /// * `collection_id`: ID of the collection that is sponsored by `pallet_id`484 #[pallet::call_index(4)]485 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]486 pub fn stop_sponsoring_collection(487 admin: OriginFor<T>,488 collection_id: CollectionId,489 ) -> DispatchResult {490 let admin_id = ensure_signed(admin)?;491492 ensure!(493 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,494 Error::<T>::NoPermission495 );496497 ensure!(498 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?499 == Self::account_id(),500 <Error<T>>::NoPermission501 );502 T::CollectionHandler::remove_collection_sponsor(collection_id)503 }504505 /// Sets the pallet to be the sponsor for the contract.506 ///507 /// # Permissions508 ///509 /// * Pallet admin510 ///511 /// # Arguments512 ///513 /// * `contract_id`: the contract address that will be sponsored by `pallet_id`514 #[pallet::call_index(5)]515 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]516 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {517 let admin_id = ensure_signed(admin)?;518519 ensure!(520 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,521 Error::<T>::NoPermission522 );523524 T::ContractHandler::set_sponsor(525 T::CrossAccountId::from_sub(Self::account_id()),526 contract_id,527 )528 }529530 /// Removes the pallet as the sponsor for the contract.531 /// Returns [`NoPermission`][`Error::NoPermission`]532 /// if the pallet wasn't the sponsor.533 ///534 /// # Permissions535 ///536 /// * Pallet admin537 ///538 /// # Arguments539 ///540 /// * `contract_id`: the contract address that is sponsored by `pallet_id`541 #[pallet::call_index(6)]542 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]543 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {544 let admin_id = ensure_signed(admin)?;545546 ensure!(547 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,548 Error::<T>::NoPermission549 );550551 ensure!(552 T::ContractHandler::sponsor(contract_id)?553 .ok_or(<Error<T>>::SponsorNotSet)?554 .as_sub() == &Self::account_id(),555 <Error<T>>::NoPermission556 );557 T::ContractHandler::remove_contract_sponsor(contract_id)558 }559560 /// Recalculates interest for the specified number of stakers.561 /// If all stakers are not recalculated, the next call of the extrinsic562 /// will continue the recalculation, from those stakers for whom this563 /// was not perform in last call.564 ///565 /// # Permissions566 ///567 /// * Pallet admin568 ///569 /// # Arguments570 ///571 /// * `stakers_number`: the number of stakers for which recalculation will be performed572 #[pallet::call_index(7)]573 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]574 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {575 let admin_id = ensure_signed(admin)?;576577 ensure!(578 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,579 Error::<T>::NoPermission580 );581 let config = <PalletConfiguration<T>>::get();582583 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);584585 ensure!(586 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,587 Error::<T>::NoPermission588 );589590 // calculate the number of the current recalculation block,591 // this is necessary in order to understand which stakers we should calculate interest592 let current_recalc_block = Self::get_current_recalc_block(593 T::RelayBlockNumberProvider::current_block_number(),594 &config,595 );596597 // calculate the number of the next recalculation block,598 // this value is set for the stakers to whom the recalculation will be performed599 let next_recalc_block = current_recalc_block + config.recalculation_interval;600601 let mut storage_iterator = Self::get_next_calculated_key()602 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));603604 PreviousCalculatedRecord::<T>::set(None);605606 {607 // Address handled in the last payout loop iteration (below)608 let last_id = RefCell::new(None);609 // Block number (as a part of the key) for which calculation was performed in the last payout loop iteration610 let mut last_staked_calculated_block = Default::default();611 // Reward balance for the address in the iteration612 let income_acc = RefCell::new(BalanceOf::<T>::default());613 // Staked balance for the address in the iteration (before stake is recalculated)614 let amount_acc = RefCell::new(BalanceOf::<T>::default());615616 // This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout617 // loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout618 // loop switches to handling the next staker address:619 // 1. Transfer full reward amount to the payee620 // 2. Lock the reward in staking lock621 // 3. Update TotalStaked amount622 // 4. Issue StakingRecalculation event623 let flush_stake = || -> DispatchResult {624 if let Some(last_id) = &*last_id.borrow() {625 if !income_acc.borrow().is_zero() {626 // TO-DO: When moving to ED>0, reconsider the value of preservation627 <<T as Config>::Currency as Mutate<T::AccountId>>::transfer(628 &T::TreasuryAccountId::get(),629 last_id,630 *income_acc.borrow(),631 frame_support::traits::tokens::Preservation::Protect,632 )?;633634 Self::add_freeze_balance(last_id, *income_acc.borrow())?;635 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {636 *staked = staked637 .checked_add(&*income_acc.borrow())638 .ok_or(ArithmeticError::Overflow)?;639 Ok(())640 })?;641642 Self::deposit_event(Event::StakingRecalculation(643 last_id.clone(),644 *amount_acc.borrow(),645 *income_acc.borrow(),646 ));647 }648649 *income_acc.borrow_mut() = BalanceOf::<T>::default();650 *amount_acc.borrow_mut() = BalanceOf::<T>::default();651 }652 Ok(())653 };654655 // Reward payment loop. Should loop for no more than config.max_stakers_per_calculation656 // iterations in one extrinsic call657 //658 // stakers_number - keeps the remaining number of iterations (staker addresses to handle)659 // next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out660 // income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)661 while let Some((662 (current_id, staked_block),663 (amount, next_recalc_block_for_stake),664 )) = storage_iterator.next()665 {666 // last_id is not equal current_id when we switch to handling a new staker address667 // or just start handling the very first address. In the latter case last_id will be None and668 // flush_stake will do nothing669 if last_id.borrow().as_ref() != Some(¤t_id) {670 if stakers_number > 0 {671 flush_stake()?;672 *last_id.borrow_mut() = Some(current_id.clone());673 stakers_number -= 1;674 }675 // Break out if we reached the address limit676 else {677 if let Some(staker) = &*last_id.borrow() {678 // Save the last calculated record to pick up in the next extrinsic call679 PreviousCalculatedRecord::<T>::set(Some((680 staker.clone(),681 last_staked_calculated_block,682 )));683 }684 break;685 };686 };687688 // Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount689 if current_recalc_block >= next_recalc_block_for_stake {690 *amount_acc.borrow_mut() += amount;691 Self::recalculate_and_insert_stake(692 ¤t_id,693 staked_block,694 next_recalc_block,695 amount,696 ((current_recalc_block - next_recalc_block_for_stake)697 / config.recalculation_interval)698 .into() + 1,699 &mut *income_acc.borrow_mut(),700 );701 }702 last_staked_calculated_block = staked_block;703 }704 flush_stake()?;705 }706707 Ok(())708 }709710 /// Migrates lock state into freeze one711 ///712 /// # Permissions713 ///714 /// * Sudo715 ///716 /// # Arguments717 ///718 /// * `origin`: Must be `Root`.719 /// * `stakers`: Accounts to be upgraded.720 #[pallet::call_index(9)]721 #[pallet::weight(T::DbWeight::get().reads_writes(2, 2) * stakers.len() as u64)]722 pub fn upgrade_accounts(723 origin: OriginFor<T>,724 stakers: Vec<T::AccountId>,725 ) -> DispatchResult {726 ensure_root(origin)?;727728 stakers729 .into_iter()730 .try_for_each(|s| -> Result<_, DispatchError> {731 if let Some(BalanceLock { amount, .. }) = Self::get_locked_balance(&s) {732 if Self::get_frozen_balance(&s).is_some() {733 return Err(Error::<T>::InconsistencyState.into());734 }735736 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(737 LOCK_IDENTIFIER,738 &s,739 );740741 Self::set_freeze_with_result(&s, amount)?;742 Ok(())743 } else {744 Ok(())745 }746 })?;747748 Ok(())749 }750751 /// Called for blocks that, for some reason, have not been unstacked752 ///753 /// # Permissions754 ///755 /// * Sudo756 ///757 /// # Arguments758 ///759 /// * `origin`: Must be `Root`.760 /// * `pending_blocks`: Block numbers that will be processed.761 #[pallet::call_index(10)]762 #[pallet::weight(<T as Config>::WeightInfo::on_initialize(PENDING_LIMIT_PER_BLOCK*pending_blocks.len() as u32))]763 pub fn force_unstake(764 origin: OriginFor<T>,765 pending_blocks: Vec<T::BlockNumber>,766 ) -> DispatchResult {767 ensure_root(origin)?;768769 ensure!(770 pending_blocks771 .iter()772 .all(|b| *b < <frame_system::Pallet<T>>::block_number()),773 <Error<T>>::NoPermission774 );775776 let mut pendings =777 Vec::with_capacity(PENDING_LIMIT_PER_BLOCK as usize * pending_blocks.len());778 pending_blocks779 .into_iter()780 .for_each(|b| pendings.append(&mut PendingUnstake::<T>::take(b).into_inner()));781782 pendings783 .into_iter()784 .try_for_each(|(staker, amount)| -> Result<(), DispatchError> {785 if let Some(b) = Self::get_frozen_balance(&staker) {786 let new_state = b.checked_sub(&amount).unwrap_or_default();787 Self::set_freeze_with_result(&staker, new_state)?;788 }789790 Ok(())791 })?;792793 Ok(())794 }795 }796}797798impl<T: Config> Pallet<T> {799 /// The account address of the app promotion pot.800 ///801 /// This actually does computation. If you need to keep using it, then make sure you cache the802 /// value and only call this once.803 pub fn account_id() -> T::AccountId {804 T::PalletId::get().into_account_truncating()805 }806807 /// Unstakes the balance for the staker.808 ///809 /// - `staker`: staker account.810 /// - `amount`: amount of unstaked funds.811 fn unstake_partial_internal(812 staker_id: T::AccountId,813 unstaked_balance: BalanceOf<T>,814 ) -> DispatchResult {815 if unstaked_balance == Default::default() {816 return Ok(());817 }818819 let config = <PalletConfiguration<T>>::get();820821 // calculate block number where the sum would be free822 let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;823824 let mut pendings = <PendingUnstake<T>>::get(unpending_block);825826 // checks that we can do unstake in the block827 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);828829 let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();830831 let total_staked = stakes832 .iter()833 .fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {834 acc + *balance835 });836837 ensure!(838 unstaked_balance <= total_staked,839 <Error<T>>::InsufficientStakedBalance840 );841842 <TotalStaked<T>>::set(843 <TotalStaked<T>>::get()844 .checked_sub(&unstaked_balance)845 .ok_or(ArithmeticError::Underflow)?,846 );847848 stakes.sort_by_key(|(block, _)| *block);849850 let mut acc_amount = unstaked_balance;851 let mut will_deleted_stakes_count = 0u8;852853 let changed_stakes = stakes854 .into_iter()855 .map_while(|(block, (balance_per_block, _))| {856 if acc_amount == <BalanceOf<T>>::default() {857 return None;858 }859 if acc_amount < balance_per_block {860 let res = (block, balance_per_block - acc_amount);861 acc_amount = <BalanceOf<T>>::default();862 return Some(res);863 } else {864 acc_amount -= balance_per_block;865 will_deleted_stakes_count += 1;866 return Some((block, <BalanceOf<T>>::default()));867 }868 })869 .collect::<Vec<_>>();870871 pendings872 .try_push((staker_id.clone(), unstaked_balance))873 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;874875 StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {876 *stakes = stakes877 .checked_sub(will_deleted_stakes_count)878 .ok_or(ArithmeticError::Underflow)?;879 Ok(())880 })?;881882 changed_stakes883 .into_iter()884 .for_each(|(staked_block, current_stake_state)| {885 if current_stake_state == Default::default() {886 <Staked<T>>::remove((&staker_id, staked_block));887 } else {888 <Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {889 *old_stake_state = current_stake_state890 });891 }892 });893894 <PendingUnstake<T>>::insert(unpending_block, pendings);895896 Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));897898 Ok(())899 }900901 /// Adds the balance to frozen by the pallet.902 ///903 /// - `staker`: staker account.904 /// - `amount`: amount of added frozen funds.905 fn add_freeze_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {906 Self::get_frozen_balance(staker)907 .unwrap_or_default()908 .checked_add(&amount)909 .map(|freeze| Self::set_freeze_with_result(staker, freeze))910 .ok_or::<DispatchError>(ArithmeticError::Overflow.into())?911 }912913 /// Sets the new state of a balance frozen by the pallet.914 ///915 /// - `staker`: staker account.916 /// - `amount`: amount of frozen funds.917 fn set_freeze_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {918 let _ = Self::set_freeze_with_result(staker, amount);919 }920921 /// Sets the new state of a balance frozen by the pallet.922 ///923 /// - `staker`: staker account.924 /// - `amount`: amount of frozen funds.925 fn set_freeze_with_result(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {926 if amount.is_zero() {927 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(928 &T::FreezeIdentifier::get(),929 &staker,930 )931 } else {932 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(933 &T::FreezeIdentifier::get(),934 staker,935 amount,936 )937 }938 }939940 /// Returns the balance locked by the pallet for the staker.941 ///942 /// - `staker`: staker account.943 pub fn get_locked_balance(944 staker: impl EncodeLike<T::AccountId>,945 ) -> Option<BalanceLock<BalanceOf<T>>> {946 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)947 .into_iter()948 .find(|l| l.id == LOCK_IDENTIFIER)949 }950951 /// Returns the balance frozen by the pallet for the staker.952 ///953 /// - `staker`: staker account.954 pub fn get_frozen_balance(staker: &T::AccountId) -> Option<BalanceOf<T>> {955 let res = <<T as Config>::Currency as InspectFreeze<T::AccountId>>::balance_frozen(956 &T::FreezeIdentifier::get(),957 staker,958 );959960 if res == Zero::zero() {961 None962 } else {963 Some(res)964 }965 }966967 /// Returns the total staked balance for the staker.968 ///969 /// - `staker`: staker account.970 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {971 let staked = Staked::<T>::iter_prefix((staker,))972 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {973 acc + amount974 });975 if staked != <BalanceOf<T>>::default() {976 Some(staked)977 } else {978 None979 }980 }981982 /// Returns all relay block numbers when stake was made,983 /// the amount of the stake.984 ///985 /// - `staker`: staker account.986 pub fn total_staked_by_id_per_block(987 staker: impl EncodeLike<T::AccountId>,988 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {989 let mut staked = Staked::<T>::iter_prefix((staker,))990 .map(|(block, (amount, _))| (block, amount))991 .collect::<Vec<_>>();992 staked.sort_by_key(|(block, _)| *block);993 if !staked.is_empty() {994 Some(staked)995 } else {996 None997 }998 }9991000 /// Returns the total staked balance for the staker.1001 /// If `staker` is `None`, returns the total amount staked.1002 /// - `staker`: staker account.1003 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {1004 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {1005 Self::total_staked_by_id(s.as_sub())1006 })1007 }10081009 /// Returns all relay block numbers when stake was made,1010 /// the amount of the stake.1011 ///1012 /// - `staker`: staker account.1013 pub fn cross_id_total_staked_per_block(1014 staker: T::CrossAccountId,1015 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1016 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()1017 }10181019 fn recalculate_and_insert_stake(1020 staker: &T::AccountId,1021 staked_block: T::BlockNumber,1022 next_recalc_block: T::BlockNumber,1023 base: BalanceOf<T>,1024 iters: u32,1025 income_acc: &mut BalanceOf<T>,1026 ) {1027 let income = Self::calculate_income(base, iters);10281029 base.checked_add(&income).map(|res| {1030 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1031 *income_acc += income;1032 });1033 }10341035 fn calculate_income<I>(base: I, iters: u32) -> I1036 where1037 I: EncodeLike<BalanceOf<T>> + Balance,1038 {1039 let config = <PalletConfiguration<T>>::get();1040 let mut income = base;10411042 (0..iters).for_each(|_| income += config.interval_income * income);10431044 income - base1045 }10461047 /// Get relay block number rounded down to multiples of config.recalculation_interval.1048 /// We need it to reward stakers in integer parts of recalculation_interval1049 fn get_current_recalc_block(1050 current_relay_block: T::BlockNumber,1051 config: &PalletConfiguration<T>,1052 ) -> T::BlockNumber {1053 (current_relay_block / config.recalculation_interval) * config.recalculation_interval1054 }10551056 fn get_next_calculated_key() -> Option<Vec<u8>> {1057 Self::get_next_calculated_record().map(Staked::<T>::hashed_key_for)1058 }1059}10601061impl<T: Config> Pallet<T>1062where1063 <<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum,1064{1065 /// Returns the amount reserved by the pending.1066 /// If `staker` is `None`, returns the total pending.1067 ///1068 /// -`staker`: staker account.1069 ///1070 /// Since user funds are not transferred anywhere by staking, overflow protection is provided1071 /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,1072 /// the staker must have more funds on his account than the maximum set for `Balance` type.1073 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1074 staker.map_or(1075 PendingUnstake::<T>::iter_values()1076 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1077 .sum(),1078 |s| {1079 PendingUnstake::<T>::iter_values()1080 .flatten()1081 .filter_map(|(id, amount)| {1082 if id == *s.as_sub() {1083 Some(amount)1084 } else {1085 None1086 }1087 })1088 .sum()1089 },1090 )1091 }10921093 /// Returns all parachain block numbers when unreserve is expected,1094 /// the amount of the unreserved funds.1095 ///1096 /// - `staker`: staker account.1097 pub fn cross_id_pending_unstake_per_block(1098 staker: T::CrossAccountId,1099 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1100 let mut unsorted_res = vec![];1101 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1102 pendings.into_iter().for_each(|(id, amount)| {1103 if id == *staker.as_sub() {1104 unsorted_res.push((block, amount));1105 };1106 })1107 });11081109 unsorted_res.sort_by_key(|(block, _)| *block);1110 unsorted_res1111 }11121113 fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1114 let config = <PalletConfiguration<T>>::get();11151116 // calculate block number where the sum would be free1117 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;11181119 let mut pendings = <PendingUnstake<T>>::get(block);11201121 // checks that we can do unstake in the block1122 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);11231124 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1125 .map(|(_, (amount, _))| amount)1126 .sum();11271128 if total_staked.is_zero() {1129 return Ok(());1130 }11311132 pendings1133 .try_push((staker_id.clone(), total_staked))1134 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;11351136 <PendingUnstake<T>>::insert(block, pendings);11371138 TotalStaked::<T>::set(1139 TotalStaked::<T>::get()1140 .checked_sub(&total_staked)1141 .ok_or(ArithmeticError::Underflow)?,1142 );11431144 StakesPerAccount::<T>::remove(&staker_id);11451146 Self::deposit_event(Event::Unstake(staker_id, total_staked));11471148 Ok(())1149 }1150}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # App Promotion pallet18//!19//! The pallet implements the mechanics of staking and sponsoring collections/contracts.20//!21//! - [`Config`]22//! - [`Pallet`]23//! - [`Error`]24//! - [`Event`]25//!26//! ## Overview27//! The App Promotion pallet allows fund holders to stake at a certain daily rate of return.28//! The mechanics implemented in the pallet allow it to act as a sponsor for collections / contracts,29//! the list of which is set by the pallet administrator.30//!31//!32//! ## Interface33//! The pallet provides interfaces for funds, collection/contract operations (see [types] module).3435//!36//! ### Dispatchable Functions37//! - [`set_admin_address`][`Pallet::set_admin_address`] - sets an address as the the admin.38//! - [`stake`][`Pallet::stake`] - stakes the amount of native tokens.39//! - [`unstake`][`Pallet::unstake`] - unstakes all stakes.40//! - [`sponsor_collection`][`Pallet::sponsor_collection`] - sets the pallet to be the sponsor for the collection.41//! - [`stop_sponsoring_collection`][`Pallet::stop_sponsoring_collection`] - removes the pallet as the sponsor for the collection.42//! - [`sponsor_contract`][`Pallet::sponsor_contract`] - sets the pallet to be the sponsor for the contract.43//! - [`stop_sponsoring_contract`][`Pallet::stop_sponsoring_contract`] - removes the pallet as the sponsor for the contract.44//! - [`payout_stakers`][`Pallet::payout_stakers`] - recalculates interest for the specified number of stakers.45//!4647// #![recursion_limit = "1024"]48#![cfg_attr(not(feature = "std"), no_std)]4950#[cfg(feature = "runtime-benchmarks")]51mod benchmarking;5253pub mod types;54pub mod weights;5556use sp_std::{57 vec::{Vec},58 vec,59 iter::Sum,60 borrow::ToOwned,61 cell::RefCell,62};63use sp_core::H160;64use codec::EncodeLike;65use pallet_balances::BalanceLock;66pub use types::*;6768use up_data_structs::CollectionId;6970use frame_support::{71 dispatch::{DispatchResult},72 traits::{73 Get, LockableCurrency,74 tokens::Balance,75 fungible::{Inspect, InspectFreeze, Mutate, MutateFreeze},76 },77 ensure, BoundedVec,78};7980use weights::WeightInfo;8182pub use pallet::*;83use pallet_evm::account::CrossAccountId;84use sp_runtime::{85 Perbill,86 traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},87 ArithmeticError, DispatchError,88};8990pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";9192const PENDING_LIMIT_PER_BLOCK: u32 = 3;9394type BalanceOf<T> =95 <<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;9697#[frame_support::pallet]98pub mod pallet {99 use super::*;100 use frame_support::{101 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId, weights::Weight,102 };103 use frame_system::pallet_prelude::*;104 use sp_runtime::DispatchError;105106 #[pallet::config]107 pub trait Config:108 frame_system::Config + pallet_evm::Config + pallet_configuration::Config109 {110 /// Type to interact with the native token111 type Currency: MutateFreeze<Self::AccountId>112 + Mutate<Self::AccountId>113 + ExtendedLockableCurrency<114 Self::AccountId,115 Balance = <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,116 >;117118 /// Type for interacting with collections119 type CollectionHandler: CollectionHandler<120 AccountId = Self::AccountId,121 CollectionId = CollectionId,122 >;123124 /// Type for interacting with conrtacts125 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;126127 /// `AccountId` for treasury128 type TreasuryAccountId: Get<Self::AccountId>;129130 /// The app's pallet id, used for deriving its sovereign account address.131 #[pallet::constant]132 type PalletId: Get<PalletId>;133134 /// Freeze identifier used by the pallet135 #[pallet::constant]136 type FreezeIdentifier: Get<137 <<Self as Config>::Currency as InspectFreeze<Self::AccountId>>::Id,138 >;139140 /// In relay blocks.141 #[pallet::constant]142 type RecalculationInterval: Get<Self::BlockNumber>;143144 /// In parachain blocks.145 #[pallet::constant]146 type PendingInterval: Get<Self::BlockNumber>;147148 /// Rate of return for interval in blocks defined in `RecalculationInterval`.149 #[pallet::constant]150 type IntervalIncome: Get<Perbill>;151152 /// Decimals for the `Currency`.153 #[pallet::constant]154 type Nominal: Get<BalanceOf<Self>>;155156 /// Maintenance mode status.157 type IsMaintenanceModeEnabled: Get<bool>;158159 /// Weight information for extrinsics in this pallet.160 type WeightInfo: WeightInfo;161162 // The relay block number provider163 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;164165 /// Events compatible with [`frame_system::Config::Event`].166 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;167 }168169 #[pallet::pallet]170 pub struct Pallet<T>(_);171172 #[pallet::event]173 #[pallet::generate_deposit(pub(super) fn deposit_event)]174 pub enum Event<T: Config> {175 /// Staking recalculation was performed176 ///177 /// # Arguments178 /// * AccountId: account of the staker.179 /// * Balance : recalculation base180 /// * Balance : total income181 StakingRecalculation(182 /// An recalculated staker183 T::AccountId,184 /// Base on which interest is calculated185 BalanceOf<T>,186 /// Amount of accrued interest187 BalanceOf<T>,188 ),189190 /// Staking was performed191 ///192 /// # Arguments193 /// * AccountId: account of the staker194 /// * Balance : staking amount195 Stake(T::AccountId, BalanceOf<T>),196197 /// Unstaking was performed198 ///199 /// # Arguments200 /// * AccountId: account of the staker201 /// * Balance : unstaking amount202 Unstake(T::AccountId, BalanceOf<T>),203204 /// The admin was set205 ///206 /// # Arguments207 /// * AccountId: account address of the admin208 SetAdmin(T::AccountId),209 }210211 #[pallet::error]212 pub enum Error<T> {213 /// Error due to action requiring admin to be set.214 AdminNotSet,215 /// No permission to perform an action.216 NoPermission,217 /// Insufficient funds to perform an action.218 NotSufficientFunds,219 /// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.220 PendingForBlockOverflow,221 /// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.222 SponsorNotSet,223 /// Errors caused by insufficient staked balance.224 InsufficientStakedBalance,225 /// Errors caused by incorrect state of a staker in context of the pallet.226 InconsistencyState,227 }228229 /// Stores the total staked amount.230 #[pallet::storage]231 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;232233 /// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.234 #[pallet::storage]235 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;236237 /// Stores the amount of tokens staked by account in the blocknumber.238 ///239 /// * **Key1** - Staker account.240 /// * **Key2** - Relay block number when the stake was made.241 /// * **(Balance, BlockNumber)** - Balance of the stake.242 /// The number of the relay block in which we must perform the interest recalculation243 #[pallet::storage]244 pub type Staked<T: Config> = StorageNMap<245 Key = (246 Key<Blake2_128Concat, T::AccountId>,247 Key<Twox64Concat, T::BlockNumber>,248 ),249 Value = (BalanceOf<T>, T::BlockNumber),250 QueryKind = ValueQuery,251 >;252253 /// Stores number of stake records for an `Account`.254 ///255 /// * **Key** - Staker account.256 /// * **Value** - Amount of stakes.257 #[pallet::storage]258 pub type StakesPerAccount<T: Config> =259 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;260261 /// Pending unstake records for an `Account`.262 ///263 /// * **Key** - Staker account.264 /// * **Value** - Amount of stakes.265 #[pallet::storage]266 pub type PendingUnstake<T: Config> = StorageMap<267 _,268 Twox64Concat,269 T::BlockNumber,270 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,271 ValueQuery,272 >;273274 /// Stores a key for record for which the revenue recalculation was performed.275 /// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.276 #[pallet::storage]277 #[pallet::getter(fn get_next_calculated_record)]278 pub type PreviousCalculatedRecord<T: Config> =279 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;280281 #[pallet::hooks]282 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {283 /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize284 /// implies the execution of a strictly limited number of relatively lightweight operations.285 /// A separate benchmark has been implemented to scale the weight depending on the number of pendings.286 fn on_initialize(current_block_number: T::BlockNumber) -> Weight287 where288 <T as frame_system::Config>::BlockNumber: From<u32>,289 {290 if T::IsMaintenanceModeEnabled::get() {291 return T::DbWeight::get().reads_writes(1, 0);292 }293294 let block_pending = PendingUnstake::<T>::take(current_block_number);295 let counter = block_pending.len() as u32;296297 if !block_pending.is_empty() {298 block_pending.into_iter().for_each(|(staker, amount)| {299 if let Some(b) = Self::get_frozen_balance(&staker) {300 let new_state = b.checked_sub(&amount).unwrap_or_default();301302 // In this case, setting a new state for the frozen funds cannot fail303 // because the state change goes in the direction of decreasing the frozen funds304 // and the validity of this transition is ensured by the fact305 // that we cannot (in the current implementation) unfreeze more funds306 // than were originally frozen by the pallet. Either way, `on_initialize()` cannot fail.307 Self::set_freeze_unchecked(&staker, new_state);308 };309 });310 }311312 <T as Config>::WeightInfo::on_initialize(counter)313 }314 }315316 #[pallet::call]317 impl<T: Config> Pallet<T>318 where319 T::BlockNumber: From<u32> + Into<u32>,320 <<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,321 {322 /// Sets an address as the the admin.323 ///324 /// # Permissions325 ///326 /// * Sudo327 ///328 /// # Arguments329 ///330 /// * `admin`: account of the new admin.331 #[pallet::call_index(0)]332 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]333 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {334 ensure_root(origin)?;335336 <Admin<T>>::set(Some(admin.as_sub().to_owned()));337338 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));339340 Ok(())341 }342343 /// Stakes the amount of native tokens.344 /// Sets `amount` to the locked state.345 /// The maximum number of stakes for a staker is 10.346 ///347 /// # Arguments348 ///349 /// * `amount`: in native tokens.350 #[pallet::call_index(1)]351 #[pallet::weight(<T as Config>::WeightInfo::stake())]352 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {353 let staker_id = ensure_signed(staker)?;354355 ensure!(356 StakesPerAccount::<T>::get(&staker_id) < 10,357 Error::<T>::NoPermission358 );359360 ensure!(361 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),362 ArithmeticError::Underflow363 );364 let config = <PalletConfiguration<T>>::get();365366 let balance = <<T as Config>::Currency as Inspect<T::AccountId>>::balance(&staker_id);367368 // checks that we can freeze `amount` on the `staker` account.369 ensure!(370 amount371 <= match Self::get_frozen_balance(&staker_id) {372 Some(frozen_by_pallet) => balance373 .checked_sub(&frozen_by_pallet)374 .ok_or(ArithmeticError::Underflow)?,375 None => balance,376 },377 ArithmeticError::Underflow378 );379380 Self::add_freeze_balance(&staker_id, amount)?;381382 let block_number = T::RelayBlockNumberProvider::current_block_number();383384 // Calculation of the number of recalculation periods,385 // after how much the first interest calculation should be performed for the stake386 let recalculate_after_interval: T::BlockNumber =387 if block_number % config.recalculation_interval == 0u32.into() {388 1u32.into()389 } else {390 2u32.into()391 };392393 // Сalculation of the number of the relay block394 // in which it is necessary to accrue remuneration for the stake.395 let recalc_block = (block_number / config.recalculation_interval396 + recalculate_after_interval)397 * config.recalculation_interval;398399 <Staked<T>>::insert((&staker_id, block_number), {400 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));401 balance_and_recalc_block.0 = balance_and_recalc_block402 .0403 .checked_add(&amount)404 .ok_or(ArithmeticError::Overflow)?;405 balance_and_recalc_block.1 = recalc_block;406 balance_and_recalc_block407 });408409 <TotalStaked<T>>::set(410 <TotalStaked<T>>::get()411 .checked_add(&amount)412 .ok_or(ArithmeticError::Overflow)?,413 );414415 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);416417 Self::deposit_event(Event::Stake(staker_id, amount));418419 Ok(())420 }421422 /// Unstakes all stakes.423 /// After the end of `PendingInterval` this sum becomes completely424 /// free for further use.425 #[pallet::call_index(2)]426 #[pallet::weight(<T as Config>::WeightInfo::unstake_all())]427 pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {428 let staker_id = ensure_signed(staker)?;429430 Self::unstake_all_internal(staker_id)431 }432433 /// Unstakes the amount of balance for the staker.434 /// After the end of `PendingInterval` this sum becomes completely435 /// free for further use.436 ///437 /// # Arguments438 ///439 /// * `staker`: staker account.440 /// * `amount`: amount of unstaked funds.441 #[pallet::call_index(8)]442 #[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]443 pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {444 let staker_id = ensure_signed(staker)?;445446 Self::unstake_partial_internal(staker_id, amount)447 }448449 /// Sets the pallet to be the sponsor for the collection.450 ///451 /// # Permissions452 ///453 /// * Pallet admin454 ///455 /// # Arguments456 ///457 /// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`458 #[pallet::call_index(3)]459 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]460 pub fn sponsor_collection(461 admin: OriginFor<T>,462 collection_id: CollectionId,463 ) -> DispatchResult {464 let admin_id = ensure_signed(admin)?;465 ensure!(466 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,467 Error::<T>::NoPermission468 );469470 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)471 }472473 /// Removes the pallet as the sponsor for the collection.474 /// Returns [`NoPermission`][`Error::NoPermission`]475 /// if the pallet wasn't the sponsor.476 ///477 /// # Permissions478 ///479 /// * Pallet admin480 ///481 /// # Arguments482 ///483 /// * `collection_id`: ID of the collection that is sponsored by `pallet_id`484 #[pallet::call_index(4)]485 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]486 pub fn stop_sponsoring_collection(487 admin: OriginFor<T>,488 collection_id: CollectionId,489 ) -> DispatchResult {490 let admin_id = ensure_signed(admin)?;491492 ensure!(493 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,494 Error::<T>::NoPermission495 );496497 ensure!(498 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?499 == Self::account_id(),500 <Error<T>>::NoPermission501 );502 T::CollectionHandler::remove_collection_sponsor(collection_id)503 }504505 /// Sets the pallet to be the sponsor for the contract.506 ///507 /// # Permissions508 ///509 /// * Pallet admin510 ///511 /// # Arguments512 ///513 /// * `contract_id`: the contract address that will be sponsored by `pallet_id`514 #[pallet::call_index(5)]515 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]516 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {517 let admin_id = ensure_signed(admin)?;518519 ensure!(520 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,521 Error::<T>::NoPermission522 );523524 T::ContractHandler::set_sponsor(525 T::CrossAccountId::from_sub(Self::account_id()),526 contract_id,527 )528 }529530 /// Removes the pallet as the sponsor for the contract.531 /// Returns [`NoPermission`][`Error::NoPermission`]532 /// if the pallet wasn't the sponsor.533 ///534 /// # Permissions535 ///536 /// * Pallet admin537 ///538 /// # Arguments539 ///540 /// * `contract_id`: the contract address that is sponsored by `pallet_id`541 #[pallet::call_index(6)]542 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]543 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {544 let admin_id = ensure_signed(admin)?;545546 ensure!(547 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,548 Error::<T>::NoPermission549 );550551 ensure!(552 T::ContractHandler::sponsor(contract_id)?553 .ok_or(<Error<T>>::SponsorNotSet)?554 .as_sub() == &Self::account_id(),555 <Error<T>>::NoPermission556 );557 T::ContractHandler::remove_contract_sponsor(contract_id)558 }559560 /// Recalculates interest for the specified number of stakers.561 /// If all stakers are not recalculated, the next call of the extrinsic562 /// will continue the recalculation, from those stakers for whom this563 /// was not perform in last call.564 ///565 /// # Permissions566 ///567 /// * Pallet admin568 ///569 /// # Arguments570 ///571 /// * `stakers_number`: the number of stakers for which recalculation will be performed572 #[pallet::call_index(7)]573 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]574 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {575 let admin_id = ensure_signed(admin)?;576577 ensure!(578 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,579 Error::<T>::NoPermission580 );581 let config = <PalletConfiguration<T>>::get();582583 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);584585 ensure!(586 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,587 Error::<T>::NoPermission588 );589590 // calculate the number of the current recalculation block,591 // this is necessary in order to understand which stakers we should calculate interest592 let current_recalc_block = Self::get_current_recalc_block(593 T::RelayBlockNumberProvider::current_block_number(),594 &config,595 );596597 // calculate the number of the next recalculation block,598 // this value is set for the stakers to whom the recalculation will be performed599 let next_recalc_block = current_recalc_block + config.recalculation_interval;600601 let storage_iterator =602 Self::get_next_calculated_key().map_or(Staked::<T>::iter(), Staked::<T>::iter_from);603604 PreviousCalculatedRecord::<T>::set(None);605606 {607 // Address handled in the last payout loop iteration (below)608 let last_id = RefCell::new(None);609 // Block number (as a part of the key) for which calculation was performed in the last payout loop iteration610 let mut last_staked_calculated_block = Default::default();611 // Reward balance for the address in the iteration612 let income_acc = RefCell::new(BalanceOf::<T>::default());613 // Staked balance for the address in the iteration (before stake is recalculated)614 let amount_acc = RefCell::new(BalanceOf::<T>::default());615616 // This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout617 // loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout618 // loop switches to handling the next staker address:619 // 1. Transfer full reward amount to the payee620 // 2. Lock the reward in staking lock621 // 3. Update TotalStaked amount622 // 4. Issue StakingRecalculation event623 let flush_stake = || -> DispatchResult {624 if let Some(last_id) = &*last_id.borrow() {625 if !income_acc.borrow().is_zero() {626 // TO-DO: When moving to ED>0, reconsider the value of preservation627 <<T as Config>::Currency as Mutate<T::AccountId>>::transfer(628 &T::TreasuryAccountId::get(),629 last_id,630 *income_acc.borrow(),631 frame_support::traits::tokens::Preservation::Protect,632 )?;633634 Self::add_freeze_balance(last_id, *income_acc.borrow())?;635 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {636 *staked = staked637 .checked_add(&*income_acc.borrow())638 .ok_or(ArithmeticError::Overflow)?;639 Ok(())640 })?;641642 Self::deposit_event(Event::StakingRecalculation(643 last_id.clone(),644 *amount_acc.borrow(),645 *income_acc.borrow(),646 ));647 }648649 *income_acc.borrow_mut() = BalanceOf::<T>::default();650 *amount_acc.borrow_mut() = BalanceOf::<T>::default();651 }652 Ok(())653 };654655 // Reward payment loop. Should loop for no more than config.max_stakers_per_calculation656 // iterations in one extrinsic call657 //658 // stakers_number - keeps the remaining number of iterations (staker addresses to handle)659 // next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out660 // income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)661 for ((current_id, staked_block), (amount, next_recalc_block_for_stake)) in662 storage_iterator663 {664 // last_id is not equal current_id when we switch to handling a new staker address665 // or just start handling the very first address. In the latter case last_id will be None and666 // flush_stake will do nothing667 if last_id.borrow().as_ref() != Some(¤t_id) {668 if stakers_number > 0 {669 flush_stake()?;670 *last_id.borrow_mut() = Some(current_id.clone());671 stakers_number -= 1;672 }673 // Break out if we reached the address limit674 else {675 if let Some(staker) = &*last_id.borrow() {676 // Save the last calculated record to pick up in the next extrinsic call677 PreviousCalculatedRecord::<T>::set(Some((678 staker.clone(),679 last_staked_calculated_block,680 )));681 }682 break;683 };684 };685686 // Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount687 if current_recalc_block >= next_recalc_block_for_stake {688 *amount_acc.borrow_mut() += amount;689 Self::recalculate_and_insert_stake(690 ¤t_id,691 staked_block,692 next_recalc_block,693 amount,694 ((current_recalc_block - next_recalc_block_for_stake)695 / config.recalculation_interval)696 .into() + 1,697 &mut *income_acc.borrow_mut(),698 );699 }700 last_staked_calculated_block = staked_block;701 }702 flush_stake()?;703 }704705 Ok(())706 }707708 /// Migrates lock state into freeze one709 ///710 /// # Permissions711 ///712 /// * Sudo713 ///714 /// # Arguments715 ///716 /// * `origin`: Must be `Root`.717 /// * `stakers`: Accounts to be upgraded.718 #[pallet::call_index(9)]719 #[pallet::weight(T::DbWeight::get().reads_writes(2, 2) * stakers.len() as u64)]720 pub fn upgrade_accounts(721 origin: OriginFor<T>,722 stakers: Vec<T::AccountId>,723 ) -> DispatchResult {724 ensure_root(origin)?;725726 stakers727 .into_iter()728 .try_for_each(|s| -> Result<_, DispatchError> {729 if let Some(BalanceLock { amount, .. }) = Self::get_locked_balance(&s) {730 if Self::get_frozen_balance(&s).is_some() {731 return Err(Error::<T>::InconsistencyState.into());732 }733734 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(735 LOCK_IDENTIFIER,736 &s,737 );738739 Self::set_freeze_with_result(&s, amount)?;740 Ok(())741 } else {742 Ok(())743 }744 })?;745746 Ok(())747 }748749 /// Called for blocks that, for some reason, have not been unstacked750 ///751 /// # Permissions752 ///753 /// * Sudo754 ///755 /// # Arguments756 ///757 /// * `origin`: Must be `Root`.758 /// * `pending_blocks`: Block numbers that will be processed.759 #[pallet::call_index(10)]760 #[pallet::weight(<T as Config>::WeightInfo::on_initialize(PENDING_LIMIT_PER_BLOCK*pending_blocks.len() as u32))]761 pub fn force_unstake(762 origin: OriginFor<T>,763 pending_blocks: Vec<T::BlockNumber>,764 ) -> DispatchResult {765 ensure_root(origin)?;766767 ensure!(768 pending_blocks769 .iter()770 .all(|b| *b < <frame_system::Pallet<T>>::block_number()),771 <Error<T>>::NoPermission772 );773774 let mut pendings =775 Vec::with_capacity(PENDING_LIMIT_PER_BLOCK as usize * pending_blocks.len());776 pending_blocks777 .into_iter()778 .for_each(|b| pendings.append(&mut PendingUnstake::<T>::take(b).into_inner()));779780 pendings781 .into_iter()782 .try_for_each(|(staker, amount)| -> Result<(), DispatchError> {783 if let Some(b) = Self::get_frozen_balance(&staker) {784 let new_state = b.checked_sub(&amount).unwrap_or_default();785 Self::set_freeze_with_result(&staker, new_state)?;786 }787788 Ok(())789 })?;790791 Ok(())792 }793 }794}795796impl<T: Config> Pallet<T> {797 /// The account address of the app promotion pot.798 ///799 /// This actually does computation. If you need to keep using it, then make sure you cache the800 /// value and only call this once.801 pub fn account_id() -> T::AccountId {802 T::PalletId::get().into_account_truncating()803 }804805 /// Unstakes the balance for the staker.806 ///807 /// - `staker`: staker account.808 /// - `amount`: amount of unstaked funds.809 fn unstake_partial_internal(810 staker_id: T::AccountId,811 unstaked_balance: BalanceOf<T>,812 ) -> DispatchResult {813 if unstaked_balance == Default::default() {814 return Ok(());815 }816817 let config = <PalletConfiguration<T>>::get();818819 // calculate block number where the sum would be free820 let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;821822 let mut pendings = <PendingUnstake<T>>::get(unpending_block);823824 // checks that we can do unstake in the block825 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);826827 let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();828829 let total_staked = stakes830 .iter()831 .fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {832 acc + *balance833 });834835 ensure!(836 unstaked_balance <= total_staked,837 <Error<T>>::InsufficientStakedBalance838 );839840 <TotalStaked<T>>::set(841 <TotalStaked<T>>::get()842 .checked_sub(&unstaked_balance)843 .ok_or(ArithmeticError::Underflow)?,844 );845846 stakes.sort_by_key(|(block, _)| *block);847848 let mut acc_amount = unstaked_balance;849 let mut will_deleted_stakes_count = 0u8;850851 let changed_stakes = stakes852 .into_iter()853 .map_while(|(block, (balance_per_block, _))| {854 if acc_amount == <BalanceOf<T>>::default() {855 return None;856 }857 if acc_amount < balance_per_block {858 let res = (block, balance_per_block - acc_amount);859 acc_amount = <BalanceOf<T>>::default();860 Some(res)861 } else {862 acc_amount -= balance_per_block;863 will_deleted_stakes_count += 1;864 Some((block, <BalanceOf<T>>::default()))865 }866 })867 .collect::<Vec<_>>();868869 pendings870 .try_push((staker_id.clone(), unstaked_balance))871 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;872873 StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {874 *stakes = stakes875 .checked_sub(will_deleted_stakes_count)876 .ok_or(ArithmeticError::Underflow)?;877 Ok(())878 })?;879880 changed_stakes881 .into_iter()882 .for_each(|(staked_block, current_stake_state)| {883 if current_stake_state == Default::default() {884 <Staked<T>>::remove((&staker_id, staked_block));885 } else {886 <Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {887 *old_stake_state = current_stake_state888 });889 }890 });891892 <PendingUnstake<T>>::insert(unpending_block, pendings);893894 Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));895896 Ok(())897 }898899 /// Adds the balance to frozen by the pallet.900 ///901 /// - `staker`: staker account.902 /// - `amount`: amount of added frozen funds.903 fn add_freeze_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {904 Self::get_frozen_balance(staker)905 .unwrap_or_default()906 .checked_add(&amount)907 .map(|freeze| Self::set_freeze_with_result(staker, freeze))908 .ok_or::<DispatchError>(ArithmeticError::Overflow.into())?909 }910911 /// Sets the new state of a balance frozen by the pallet.912 ///913 /// - `staker`: staker account.914 /// - `amount`: amount of frozen funds.915 fn set_freeze_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {916 let _ = Self::set_freeze_with_result(staker, amount);917 }918919 /// Sets the new state of a balance frozen by the pallet.920 ///921 /// - `staker`: staker account.922 /// - `amount`: amount of frozen funds.923 fn set_freeze_with_result(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {924 if amount.is_zero() {925 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(926 &T::FreezeIdentifier::get(),927 staker,928 )929 } else {930 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(931 &T::FreezeIdentifier::get(),932 staker,933 amount,934 )935 }936 }937938 /// Returns the balance locked by the pallet for the staker.939 ///940 /// - `staker`: staker account.941 pub fn get_locked_balance(942 staker: impl EncodeLike<T::AccountId>,943 ) -> Option<BalanceLock<BalanceOf<T>>> {944 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)945 .into_iter()946 .find(|l| l.id == LOCK_IDENTIFIER)947 }948949 /// Returns the balance frozen by the pallet for the staker.950 ///951 /// - `staker`: staker account.952 pub fn get_frozen_balance(staker: &T::AccountId) -> Option<BalanceOf<T>> {953 let res = <<T as Config>::Currency as InspectFreeze<T::AccountId>>::balance_frozen(954 &T::FreezeIdentifier::get(),955 staker,956 );957958 if res == Zero::zero() {959 None960 } else {961 Some(res)962 }963 }964965 /// Returns the total staked balance for the staker.966 ///967 /// - `staker`: staker account.968 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {969 let staked = Staked::<T>::iter_prefix((staker,))970 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {971 acc + amount972 });973 if staked != <BalanceOf<T>>::default() {974 Some(staked)975 } else {976 None977 }978 }979980 /// Returns all relay block numbers when stake was made,981 /// the amount of the stake.982 ///983 /// - `staker`: staker account.984 pub fn total_staked_by_id_per_block(985 staker: impl EncodeLike<T::AccountId>,986 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {987 let mut staked = Staked::<T>::iter_prefix((staker,))988 .map(|(block, (amount, _))| (block, amount))989 .collect::<Vec<_>>();990 staked.sort_by_key(|(block, _)| *block);991 if !staked.is_empty() {992 Some(staked)993 } else {994 None995 }996 }997998 /// Returns the total staked balance for the staker.999 /// If `staker` is `None`, returns the total amount staked.1000 /// - `staker`: staker account.1001 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {1002 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {1003 Self::total_staked_by_id(s.as_sub())1004 })1005 }10061007 /// Returns all relay block numbers when stake was made,1008 /// the amount of the stake.1009 ///1010 /// - `staker`: staker account.1011 pub fn cross_id_total_staked_per_block(1012 staker: T::CrossAccountId,1013 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1014 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()1015 }10161017 fn recalculate_and_insert_stake(1018 staker: &T::AccountId,1019 staked_block: T::BlockNumber,1020 next_recalc_block: T::BlockNumber,1021 base: BalanceOf<T>,1022 iters: u32,1023 income_acc: &mut BalanceOf<T>,1024 ) {1025 let income = Self::calculate_income(base, iters);10261027 if let Some(res) = base.checked_add(&income) {1028 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1029 *income_acc += income;1030 };1031 }10321033 fn calculate_income<I>(base: I, iters: u32) -> I1034 where1035 I: EncodeLike<BalanceOf<T>> + Balance,1036 {1037 let config = <PalletConfiguration<T>>::get();1038 let mut income = base;10391040 (0..iters).for_each(|_| income += config.interval_income * income);10411042 income - base1043 }10441045 /// Get relay block number rounded down to multiples of config.recalculation_interval.1046 /// We need it to reward stakers in integer parts of recalculation_interval1047 fn get_current_recalc_block(1048 current_relay_block: T::BlockNumber,1049 config: &PalletConfiguration<T>,1050 ) -> T::BlockNumber {1051 (current_relay_block / config.recalculation_interval) * config.recalculation_interval1052 }10531054 fn get_next_calculated_key() -> Option<Vec<u8>> {1055 Self::get_next_calculated_record().map(Staked::<T>::hashed_key_for)1056 }1057}10581059impl<T: Config> Pallet<T>1060where1061 <<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum,1062{1063 /// Returns the amount reserved by the pending.1064 /// If `staker` is `None`, returns the total pending.1065 ///1066 /// -`staker`: staker account.1067 ///1068 /// Since user funds are not transferred anywhere by staking, overflow protection is provided1069 /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,1070 /// the staker must have more funds on his account than the maximum set for `Balance` type.1071 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1072 staker.map_or(1073 PendingUnstake::<T>::iter_values()1074 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1075 .sum(),1076 |s| {1077 PendingUnstake::<T>::iter_values()1078 .flatten()1079 .filter_map(|(id, amount)| {1080 if id == *s.as_sub() {1081 Some(amount)1082 } else {1083 None1084 }1085 })1086 .sum()1087 },1088 )1089 }10901091 /// Returns all parachain block numbers when unreserve is expected,1092 /// the amount of the unreserved funds.1093 ///1094 /// - `staker`: staker account.1095 pub fn cross_id_pending_unstake_per_block(1096 staker: T::CrossAccountId,1097 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1098 let mut unsorted_res = vec![];1099 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1100 pendings.into_iter().for_each(|(id, amount)| {1101 if id == *staker.as_sub() {1102 unsorted_res.push((block, amount));1103 };1104 })1105 });11061107 unsorted_res.sort_by_key(|(block, _)| *block);1108 unsorted_res1109 }11101111 fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1112 let config = <PalletConfiguration<T>>::get();11131114 // calculate block number where the sum would be free1115 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;11161117 let mut pendings = <PendingUnstake<T>>::get(block);11181119 // checks that we can do unstake in the block1120 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);11211122 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1123 .map(|(_, (amount, _))| amount)1124 .sum();11251126 if total_staked.is_zero() {1127 return Ok(());1128 }11291130 pendings1131 .try_push((staker_id.clone(), total_staked))1132 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;11331134 <PendingUnstake<T>>::insert(block, pendings);11351136 TotalStaked::<T>::set(1137 TotalStaked::<T>::get()1138 .checked_sub(&total_staked)1139 .ok_or(ArithmeticError::Underflow)?,1140 );11411142 StakesPerAccount::<T>::remove(&staker_id);11431144 Self::deposit_event(Event::Unstake(staker_id, total_staked));11451146 Ok(())1147 }1148}pallets/app-promotion/src/types.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/types.rs
+++ b/pallets/app-promotion/src/types.rs
@@ -149,16 +149,16 @@
Self {
recalculation_interval: config
.recalculation_interval
- .unwrap_or_else(|| T::RecalculationInterval::get()),
+ .unwrap_or_else(T::RecalculationInterval::get),
pending_interval: config
.pending_interval
- .unwrap_or_else(|| T::PendingInterval::get()),
+ .unwrap_or_else(T::PendingInterval::get),
interval_income: config
.interval_income
- .unwrap_or_else(|| T::IntervalIncome::get()),
+ .unwrap_or_else(T::IntervalIncome::get),
max_stakers_per_calculation: config
.max_stakers_per_calculation
- .unwrap_or_else(|| MAX_NUMBER_PAYOUTS),
+ .unwrap_or(MAX_NUMBER_PAYOUTS),
}
}
}
pallets/balances-adapter/src/lib.rsdiffbeforeafterboth--- a/pallets/balances-adapter/src/lib.rs
+++ b/pallets/balances-adapter/src/lib.rs
@@ -31,6 +31,12 @@
}
}
+impl<T: Config> Default for NativeFungibleHandle<T> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl<T: Config> WithRecorder<T> for NativeFungibleHandle<T> {
fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {
&self.0
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -136,7 +136,7 @@
fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {
let key = evm_coder::types::String::from_utf8(from.key.into())
- .map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {}", e)))?;
+ .map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {e}")))?;
let value = evm_coder::types::Bytes(from.value.to_vec());
Ok(Property { key, value })
}
@@ -201,10 +201,7 @@
pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {
Self {
field,
- value: match value {
- Some(value) => Some(value.into()),
- None => None,
- },
+ value: value.map(|value| value.into()),
}
}
/// Whether the field contains a value.
@@ -222,8 +219,7 @@
.ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;
let value = Some(value.try_into().map_err(|error| {
Self::Error::Revert(format!(
- "can't convert value to u32 \"{}\" because: \"{error}\"",
- value
+ "can't convert value to u32 \"{value}\" because: \"{error}\""
))
})?);
@@ -249,10 +245,8 @@
limits.sponsored_data_size = value;
}
CollectionLimitField::SponsoredDataRateLimit => {
- limits.sponsored_data_rate_limit = match value {
- Some(value) => Some(up_data_structs::SponsoringRateLimit::Blocks(value)),
- None => None,
- };
+ limits.sponsored_data_rate_limit =
+ value.map(up_data_structs::SponsoringRateLimit::Blocks);
}
CollectionLimitField::TokenLimit => {
limits.token_limit = value;
@@ -454,9 +448,9 @@
}
}
-impl Into<up_data_structs::AccessMode> for AccessMode {
- fn into(self) -> up_data_structs::AccessMode {
- match self {
+impl From<AccessMode> for up_data_structs::AccessMode {
+ fn from(value: AccessMode) -> Self {
+ match value {
AccessMode::Normal => up_data_structs::AccessMode::Normal,
AccessMode::AllowList => up_data_structs::AccessMode::AllowList,
}
pallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -260,9 +260,9 @@
message: Some(msg), ..
}) => ExError::Revert(msg.into()),
DispatchError::Module(ModuleError { index, error, .. }) => {
- ExError::Revert(format!("error {:?} in pallet {}", error, index))
+ ExError::Revert(format!("error {error:?} in pallet {index}"))
}
- e => ExError::Revert(format!("substrate error: {:?}", e)),
+ e => ExError::Revert(format!("substrate error: {e:?}")),
}
}
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -184,10 +184,9 @@
/// @param contractAddress The contract for which a sponsor is requested.
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
fn sponsor(&self, contract_address: Address) -> Result<Option<eth::CrossAddress>> {
- Ok(match Pallet::<T>::get_sponsor(contract_address) {
- Some(ref value) => Some(eth::CrossAddress::from_sub_cross_account::<T>(value)),
- None => None,
- })
+ Ok(Pallet::<T>::get_sponsor(contract_address)
+ .as_ref()
+ .map(eth::CrossAddress::from_sub_cross_account::<T>))
}
/// Check tat contract has confirmed sponsor.
@@ -275,7 +274,7 @@
self.recorder().consume_sstore()?;
<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;
- <Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into())
+ <Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit)
.map_err(dispatch_to_evm::<T>)?;
Ok(())
}
pallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/lib.rs
+++ b/pallets/evm-contract-helpers/src/lib.rs
@@ -376,7 +376,7 @@
<SponsoringMode<T>>::get(contract)
.or_else(|| {
#[allow(deprecated)]
- <SelfSponsoring<T>>::get(contract).then(|| SponsoringModeT::Allowlisted)
+ <SelfSponsoring<T>>::get(contract).then_some(SponsoringModeT::Allowlisted)
})
.unwrap_or_default()
}
@@ -410,7 +410,7 @@
/// Is user added to allowlist, or he is owner of specified contract
pub fn allowed(contract: H160, user: H160) -> bool {
- <Allowlist<T>>::get(&contract, &user) || <Owner<T>>::get(&contract) == user
+ <Allowlist<T>>::get(contract, user) || <Owner<T>>::get(contract) == user
}
/// Toggle contract allowlist access
@@ -425,7 +425,7 @@
/// Throw error if user is not allowed to reconfigure target contract
pub fn ensure_owner(contract: H160, user: H160) -> DispatchResult {
- ensure!(<Owner<T>>::get(&contract) == user, Error::<T>::NoPermission);
+ ensure!(<Owner<T>>::get(contract) == user, Error::<T>::NoPermission);
Ok(())
}
}
pallets/evm-migration/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-migration/src/lib.rs
+++ b/pallets/evm-migration/src/lib.rs
@@ -78,7 +78,7 @@
pub fn begin(origin: OriginFor<T>, address: H160) -> DispatchResult {
ensure_root(origin)?;
ensure!(
- <PalletEvm<T>>::is_account_empty(&address) && !<MigrationPending<T>>::get(&address),
+ <PalletEvm<T>>::is_account_empty(&address) && !<MigrationPending<T>>::get(address),
<Error<T>>::AccountNotEmpty,
);
@@ -97,12 +97,12 @@
) -> DispatchResult {
ensure_root(origin)?;
ensure!(
- <MigrationPending<T>>::get(&address),
+ <MigrationPending<T>>::get(address),
<Error<T>>::AccountIsNotMigrating,
);
for (k, v) in data {
- <pallet_evm::AccountStorages<T>>::insert(&address, k, v);
+ <pallet_evm::AccountStorages<T>>::insert(address, k, v);
}
Ok(())
}
@@ -115,11 +115,11 @@
pub fn finish(origin: OriginFor<T>, address: H160, code: Vec<u8>) -> DispatchResult {
ensure_root(origin)?;
ensure!(
- <MigrationPending<T>>::get(&address),
+ <MigrationPending<T>>::get(address),
<Error<T>>::AccountIsNotMigrating,
);
- <pallet_evm::AccountCodes<T>>::insert(&address, code);
+ <pallet_evm::AccountCodes<T>>::insert(address, code);
<MigrationPending<T>>::remove(address);
Ok(())
}
@@ -166,7 +166,7 @@
pub struct OnMethodCall<T>(PhantomData<T>);
impl<T: Config> pallet_evm::OnMethodCall<T> for OnMethodCall<T> {
fn is_reserved(contract: &H160) -> bool {
- <MigrationPending<T>>::get(&contract)
+ <MigrationPending<T>>::get(contract)
}
fn is_used(_contract: &H160) -> bool {
pallets/foreign-assets/src/impl_fungibles.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/impl_fungibles.rs
+++ b/pallets/foreign-assets/src/impl_fungibles.rs
@@ -333,7 +333,7 @@
&Value::new(0),
)?;
- Ok(amount.into())
+ Ok(amount)
}
}
}
pallets/foreign-assets/src/lib.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -161,7 +161,7 @@
fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {
log::trace!(target: "fassets::get_currency_id", "call");
- Pallet::<T>::location_to_currency_ids(multi_location).map(|id| AssetIds::ForeignAssetId(id))
+ Pallet::<T>::location_to_currency_ids(multi_location).map(AssetIds::ForeignAssetId)
}
}
@@ -378,7 +378,7 @@
foreign_asset_id,
|maybe_location| -> DispatchResult {
ensure!(maybe_location.is_none(), Error::<T>::MultiLocationExisted);
- *maybe_location = Some(location.clone());
+ *maybe_location = Some(*location);
AssetMetadatas::<T>::try_mutate(
AssetIds::ForeignAssetId(foreign_asset_id),
@@ -422,7 +422,7 @@
// modify location
if location != old_multi_locations {
- LocationToCurrencyIds::<T>::remove(old_multi_locations.clone());
+ LocationToCurrencyIds::<T>::remove(*old_multi_locations);
LocationToCurrencyIds::<T>::try_mutate(
location,
|maybe_currency_ids| -> DispatchResult {
@@ -437,7 +437,7 @@
)?;
}
*maybe_asset_metadatas = Some(metadata.clone());
- *old_multi_locations = location.clone();
+ *old_multi_locations = *location;
Ok(())
},
)
pallets/identity/src/types.rsdiffbeforeafterboth--- a/pallets/identity/src/types.rs
+++ b/pallets/identity/src/types.rs
@@ -104,7 +104,7 @@
Data::Raw(ref x) => {
let l = x.len().min(32);
let mut r = vec![l as u8 + 1; l + 1];
- r[1..].copy_from_slice(&x[..l as usize]);
+ r[1..].copy_from_slice(&x[..l]);
r
}
Data::BlakeTwo256(ref h) => once(34u8).chain(h.iter().cloned()).collect(),
@@ -287,7 +287,7 @@
fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
let field = u64::decode(input)?;
Ok(Self(
- <BitFlags<IdentityField>>::from_bits(field as u64).map_err(|_| "invalid value")?,
+ <BitFlags<IdentityField>>::from_bits(field).map_err(|_| "invalid value")?,
))
}
}
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -20,6 +20,8 @@
//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.
extern crate alloc;
+
+use alloc::string::ToString;
use core::{
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
@@ -356,8 +358,7 @@
.transpose()
.map_err(|e| {
Error::Revert(alloc::format!(
- "Can not convert value \"baseURI\" to string with error \"{}\"",
- e
+ "Can not convert value \"baseURI\" to string with error \"{e}\""
))
})?;
@@ -675,7 +676,7 @@
.try_into()
.map_err(|_| "token uri is too long")?,
})
- .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+ .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
<Pallet<T>>::create_item(
self,
@@ -717,7 +718,7 @@
.map(Clone::clone)
.ok_or_else(|| {
let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();
- Error::Revert(alloc::format!("No permission for key {}", key))
+ Error::Revert(alloc::format!("No permission for key {key}"))
})?;
Ok(a)
}
@@ -752,14 +753,14 @@
/// @param tokenId Id for the token.
#[solidity(hide)]
fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {
- Self::owner_of_cross(&self, token_id)
+ Self::owner_of_cross(self, token_id)
}
/// Returns the owner (in cross format) of the token.
///
/// @param tokenId Id for the token.
fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {
- Self::token_owner(&self, token_id.try_into()?)
+ Self::token_owner(self, token_id.try_into()?)
.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))
.map_err(|_| Error::Revert("token not found".into()))
}
@@ -789,7 +790,7 @@
.collect::<Result<Vec<_>>>()?;
<Self as CommonCollectionOperations<T>>::token_properties(
- &self,
+ self,
token_id.try_into()?,
if keys.is_empty() { None } else { Some(keys) },
)
@@ -1021,7 +1022,7 @@
.try_into()
.map_err(|_| "token uri is too long")?,
})
- .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+ .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
data.push(CreateItemData::<T> {
properties,
@@ -1056,7 +1057,7 @@
.map(eth::Property::try_into)
.collect::<Result<Vec<_>>>()?
.try_into()
- .map_err(|_| Error::Revert(alloc::format!("too many properties")))?;
+ .map_err(|_| Error::Revert("too many properties".to_string()))?;
let caller = T::CrossAccountId::from_eth(caller);
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -166,10 +166,7 @@
#[pallet::config]
pub trait Config:
- frame_system::Config
- + pallet_common::Config
- + pallet_structure::Config
- + pallet_evm::Config
+ frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config
{
type WeightInfo: WeightInfo;
}
@@ -860,13 +857,7 @@
<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);
- <TokenData<T>>::insert(
- (collection.id, token),
- ItemData {
- owner: to.clone(),
- ..token_data
- },
- );
+ <TokenData<T>>::insert((collection.id, token), ItemData { owner: to.clone() });
if let Some(balance_to) = balance_to {
// from != to
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -21,6 +21,7 @@
extern crate alloc;
+use alloc::string::ToString;
use core::{
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
@@ -353,8 +354,7 @@
.transpose()
.map_err(|e| {
Error::Revert(alloc::format!(
- "Can not convert value \"baseURI\" to string with error \"{}\"",
- e
+ "Can not convert value \"baseURI\" to string with error \"{e}\""
))
})?;
@@ -482,8 +482,8 @@
.recorder
.weight_calls_budget(<StructureWeight<T>>::find_parent());
- let balance = balance(&self, token, &from)?;
- ensure_single_owner(&self, token, balance)?;
+ let balance = balance(self, token, &from)?;
+ ensure_single_owner(self, token, balance)?;
<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)
.map_err(dispatch_to_evm::<T>)?;
@@ -575,8 +575,8 @@
let caller = T::CrossAccountId::from_eth(caller);
let token = token_id.try_into()?;
- let balance = balance(&self, token, &caller)?;
- ensure_single_owner(&self, token, balance)?;
+ let balance = balance(self, token, &caller)?;
+ ensure_single_owner(self, token, balance)?;
<Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;
Ok(())
@@ -622,7 +622,7 @@
return Err("item id should be next".into());
}
- let users = [(to.clone(), 1)]
+ let users = [(to, 1)]
.into_iter()
.collect::<BTreeMap<_, _>>()
.try_into()
@@ -706,9 +706,9 @@
.try_into()
.map_err(|_| "token uri is too long")?,
})
- .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+ .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
- let users = [(to.clone(), 1)]
+ let users = [(to, 1)]
.into_iter()
.collect::<BTreeMap<_, _>>()
.try_into()
@@ -750,7 +750,7 @@
.map(Clone::clone)
.ok_or_else(|| {
let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();
- Error::Revert(alloc::format!("No permission for key {}", key))
+ Error::Revert(alloc::format!("No permission for key {key}"))
})?;
Ok(a)
}
@@ -785,14 +785,14 @@
/// @param tokenId Id for the token.
#[solidity(hide)]
fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {
- Self::owner_of_cross(&self, token_id)
+ Self::owner_of_cross(self, token_id)
}
/// Returns the owner (in cross format) of the token.
///
/// @param tokenId Id for the token.
fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {
- Self::token_owner(&self, token_id.try_into()?)
+ Self::token_owner(self, token_id.try_into()?)
.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))
.or_else(|err| match err {
TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),
@@ -827,7 +827,7 @@
.collect::<Result<Vec<_>>>()?;
<Self as CommonCollectionOperations<T>>::token_properties(
- &self,
+ self,
token_id.try_into()?,
if keys.is_empty() { None } else { Some(keys) },
)
@@ -1004,7 +1004,7 @@
}
expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
}
- let users = [(to.clone(), 1)]
+ let users = [(to, 1)]
.into_iter()
.collect::<BTreeMap<_, _>>()
.try_into()
@@ -1046,7 +1046,7 @@
.weight_calls_budget(<StructureWeight<T>>::find_parent());
let mut data = Vec::with_capacity(tokens.len());
- let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]
+ let users: BoundedBTreeMap<_, _, _> = [(to, 1)]
.into_iter()
.collect::<BTreeMap<_, _>>()
.try_into()
@@ -1067,7 +1067,7 @@
.try_into()
.map_err(|_| "token uri is too long")?,
})
- .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+ .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
let create_item_data = CreateItemData::<T> {
users: users.clone(),
@@ -1103,7 +1103,7 @@
.map(eth::Property::try_into)
.collect::<Result<Vec<_>>>()?
.try_into()
- .map_err(|_| Error::Revert(alloc::format!("too many properties")))?;
+ .map_err(|_| Error::Revert("too many properties".to_string()))?;
let caller = T::CrossAccountId::from_eth(caller);
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1124,7 +1124,7 @@
if collection.ignores_token_restrictions(spender) {
return Ok(Self::compute_allowance_decrease(
- collection, token, from, &spender, amount,
+ collection, token, from, spender, amount,
));
}
@@ -1143,7 +1143,7 @@
return Ok(None);
}
- let allowance = Self::compute_allowance_decrease(collection, token, from, &spender, amount);
+ let allowance = Self::compute_allowance_decrease(collection, token, from, spender, amount);
if allowance.is_some() {
return Ok(allowance);
}
pallets/scheduler-v2/src/lib.rsdiffbeforeafterboth--- a/pallets/scheduler-v2/src/lib.rs
+++ b/pallets/scheduler-v2/src/lib.rs
@@ -969,7 +969,7 @@
call: ScheduledCall<T>,
) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
// ensure id it is unique
- if Lookup::<T>::contains_key(&id) {
+ if Lookup::<T>::contains_key(id) {
return Err(Error::<T>::FailedToSchedule.into());
}
pallets/structure/src/lib.rsdiffbeforeafterboth--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -280,7 +280,7 @@
) -> DispatchResultWithPostInfo {
let dispatch = T::CollectionDispatch::dispatch(collection)?;
let dispatch = dispatch.as_dyn();
- dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)
+ dispatch.burn_item_recursively(from, token, self_budget, breadth_budget)
}
/// Check if `token` indirectly owned by `user`
@@ -396,7 +396,7 @@
account: &T::CrossAccountId,
action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,
) -> DispatchResult {
- if is_collection(&account.as_eth()) {
+ if is_collection(account.as_eth()) {
fail!(<Error<T>>::CantNestTokenUnderCollection);
}
let Some((collection, token)) = T::CrossTokenAddressMapping::address_to_token(account) else {
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -113,13 +113,9 @@
let collection_helpers_address =
T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id = T::CollectionDispatch::create(
- caller.clone(),
- collection_helpers_address,
- data,
- Default::default(),
- )
- .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ let collection_id =
+ T::CollectionDispatch::create(caller, collection_helpers_address, data, Default::default())
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
}
@@ -132,8 +128,7 @@
.expect("Collection creation price should be convertible to u128");
if value != creation_price {
return Err(format!(
- "Sent amount not equals to collection creation price ({0})",
- creation_price
+ "Sent amount not equals to collection creation price ({creation_price})",
)
.into());
}
@@ -383,8 +378,7 @@
map_eth_to_id(&collection_address)
.map(|id| id.0)
.ok_or(Error::Revert(format!(
- "failed to convert address {} into collectionId.",
- collection_address
+ "failed to convert address {collection_address} into collectionId."
)))
}
}
@@ -422,5 +416,5 @@
generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);
fn error_field_too_long(feild: &str, bound: usize) -> Error {
- Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))
+ Error::Revert(format!("{feild} is too long. Max length is {bound}."))
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -507,7 +507,7 @@
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let new_owner = T::CrossAccountId::from_sub(new_owner);
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.change_owner(sender, new_owner.clone())
+ target_collection.change_owner(sender, new_owner)
}
/// Add an admin to a collection.
@@ -667,7 +667,7 @@
/// * `owner`: Address of the initial owner of the item.
/// * `data`: Token data describing the item to store on chain.
#[pallet::call_index(11)]
- #[pallet::weight(T::CommonWeightInfo::create_item(&data))]
+ #[pallet::weight(T::CommonWeightInfo::create_item(data))]
pub fn create_item(
origin: OriginFor<T>,
collection_id: CollectionId,
@@ -701,7 +701,7 @@
/// * `owner`: Address of the initial owner of the tokens.
/// * `items_data`: Vector of data describing each item to be created.
#[pallet::call_index(12)]
- #[pallet::weight(T::CommonWeightInfo::create_multiple_items(&items_data))]
+ #[pallet::weight(T::CommonWeightInfo::create_multiple_items(items_data))]
pub fn create_multiple_items(
origin: OriginFor<T>,
collection_id: CollectionId,
@@ -889,7 +889,7 @@
/// * `collection_id`: ID of the collection to which the tokens would belong.
/// * `data`: Explicit item creation data.
#[pallet::call_index(18)]
- #[pallet::weight(T::CommonWeightInfo::create_multiple_items_ex(&data))]
+ #[pallet::weight(T::CommonWeightInfo::create_multiple_items_ex(data))]
pub fn create_multiple_items_ex(
origin: OriginFor<T>,
collection_id: CollectionId,
@@ -1313,7 +1313,7 @@
collection_id: CollectionId,
) -> DispatchResult {
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.force_set_sponsor(sponsor.clone())
+ target_collection.force_set_sponsor(sponsor)
}
/// Force remove `sponsor` for `collection`.
primitives/data-structs/src/bounded.rsdiffbeforeafterboth--- a/primitives/data-structs/src/bounded.rs
+++ b/primitives/data-structs/src/bounded.rs
@@ -63,7 +63,7 @@
V: fmt::Debug,
{
use core::fmt::Debug;
- (&v as &Vec<V>).fmt(f)
+ (v as &Vec<V>).fmt(f)
}
#[cfg(feature = "serde1")]
@@ -114,7 +114,7 @@
V: fmt::Debug,
{
use core::fmt::Debug;
- (&v as &BTreeMap<K, V>).fmt(f)
+ (v as &BTreeMap<K, V>).fmt(f)
}
#[cfg(feature = "serde1")]
@@ -157,5 +157,5 @@
K: fmt::Debug + Ord,
{
use core::fmt::Debug;
- (&v as &BTreeSet<K>).fmt(f)
+ (v as &BTreeSet<K>).fmt(f)
}
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -536,7 +536,7 @@
type Target = Vec<u8>;
fn deref(&self) -> &Self::Target {
- return &self.0;
+ &self.0
}
}
@@ -816,6 +816,11 @@
Self(Default::default())
}
}
+impl Default for OwnerRestrictedSet {
+ fn default() -> Self {
+ Self::new()
+ }
+}
impl core::ops::Deref for OwnerRestrictedSet {
type Target = OwnerRestrictedSetInner;
fn deref(&self) -> &Self::Target {
@@ -1098,9 +1103,9 @@
pub value: PropertyValue,
}
-impl Into<(PropertyKey, PropertyValue)> for Property {
- fn into(self) -> (PropertyKey, PropertyValue) {
- (self.key, self.value)
+impl From<Property> for (PropertyKey, PropertyValue) {
+ fn from(value: Property) -> Self {
+ (value.key, value.value)
}
}
@@ -1116,9 +1121,9 @@
pub permission: PropertyPermission,
}
-impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {
- fn into(self) -> (PropertyKey, PropertyPermission) {
- (self.key, self.permission)
+impl From<PropertyKeyPermission> for (PropertyKey, PropertyPermission) {
+ fn from(value: PropertyKeyPermission) -> Self {
+ (value.key, value.permission)
}
}
@@ -1415,7 +1420,7 @@
value: Self::Value,
) -> Result<Option<Self::Value>, PropertiesError> {
let key_size = scoped_slice_size(scope, &key);
- let value_size = slice_size(&value) as u32;
+ let value_size = slice_size(&value);
if self.consumed_space + value_size + key_size > S && !cfg!(feature = "runtime-benchmarks")
{
@@ -1425,7 +1430,7 @@
let old_value = self.map.try_scoped_set(scope, key, value)?;
if let Some(old_value) = old_value.as_ref() {
- let old_value_size = slice_size(&old_value);
+ let old_value_size = slice_size(old_value);
self.consumed_space = self.consumed_space.saturating_sub(old_value_size) + value_size;
} else {
self.consumed_space += key_size + value_size;
runtime/common/config/xcm/foreignassets.rsdiffbeforeafterboth--- a/runtime/common/config/xcm/foreignassets.rs
+++ b/runtime/common/config/xcm/foreignassets.rs
@@ -65,7 +65,7 @@
return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));
}
- match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {
+ match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(*id) {
Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {
ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))
}
@@ -206,9 +206,7 @@
return Some(AssetIds::NativeAssetId(NativeCurrency::Parent));
}
- if let Some(currency_id) =
- XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location.clone())
- {
+ if let Some(currency_id) = XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location) {
return Some(currency_id);
}
runtime/common/ethereum/precompiles/mod.rsdiffbeforeafterboth--- a/runtime/common/ethereum/precompiles/mod.rs
+++ b/runtime/common/ethereum/precompiles/mod.rs
@@ -37,6 +37,16 @@
[hash(1), hash(20482)]
}
}
+
+impl<R> Default for UniquePrecompiles<R>
+where
+ R: pallet_evm::Config,
+{
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl<R> PrecompileSet for UniquePrecompiles<R>
where
R: pallet_evm::Config,
runtime/common/ethereum/precompiles/sr25519.rsdiffbeforeafterboth--- a/runtime/common/ethereum/precompiles/sr25519.rs
+++ b/runtime/common/ethereum/precompiles/sr25519.rs
@@ -64,7 +64,7 @@
// Parse arguments
let public: sr25519::Public =
- sr25519::Public::unchecked_from(input.read::<H256>(gasometer)?).into();
+ sr25519::Public::unchecked_from(input.read::<H256>(gasometer)?);
let signature_bytes: Vec<u8> = input.read::<Bytes>(gasometer)?.into();
let message: Vec<u8> = input.read::<Bytes>(gasometer)?.into();
runtime/common/ethereum/precompiles/utils/data.rsdiffbeforeafterboth--- a/runtime/common/ethereum/precompiles/utils/data.rs
+++ b/runtime/common/ethereum/precompiles/utils/data.rs
@@ -60,7 +60,7 @@
}
impl Into<Vec<u8>> for Bytes {
- fn into(self: Self) -> Vec<u8> {
+ fn into(self) -> Vec<u8> {
self.0
}
}
runtime/common/ethereum/precompiles/utils/mod.rsdiffbeforeafterboth--- a/runtime/common/ethereum/precompiles/utils/mod.rs
+++ b/runtime/common/ethereum/precompiles/utils/mod.rs
@@ -73,7 +73,6 @@
}
}
- #[must_use]
/// Check that a function call is compatible with the context it is
/// called into.
pub fn check_function_modifier(
runtime/common/ethereum/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -78,7 +78,7 @@
let token_id: TokenId = token_id.try_into().ok()?;
withdraw_set_token_property::<T>(
&collection,
- &who,
+ who,
&token_id,
key.len() + value.len(),
)
@@ -88,7 +88,7 @@
ERC721UniqueExtensionsCall::Transfer { token_id, .. },
) => {
let token_id: TokenId = token_id.try_into().ok()?;
- withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)
+ withdraw_transfer::<T>(&collection, who, &token_id).map(|()| sponsor)
}
UniqueNFTCall::ERC721UniqueMintable(
ERC721UniqueMintableCall::Mint { .. }
@@ -97,7 +97,7 @@
| ERC721UniqueMintableCall::MintWithTokenUriCheckId { .. },
) => withdraw_create_item::<T>(
&collection,
- &who,
+ who,
&CreateItemData::NFT(CreateNftData::default()),
)
.map(|()| sponsor),
runtime/common/ethereum/sponsoring/refungible.rsdiffbeforeafterboth--- a/runtime/common/ethereum/sponsoring/refungible.rs
+++ b/runtime/common/ethereum/sponsoring/refungible.rs
@@ -16,7 +16,6 @@
//! Implements EVM sponsoring logic via TransactionValidityHack
-use core::convert::TryInto;
use pallet_common::CollectionHandle;
use pallet_evm::account::CrossAccountId;
use pallet_fungible::Config as FungibleConfig;
@@ -95,7 +94,7 @@
..
} => {
let token_id = TokenId::try_from(token_id).ok()?;
- withdraw_set_token_property::<T>(&collection, &who, &token_id, key.len() + value.len())
+ withdraw_set_token_property::<T>(&collection, who, &token_id, key.len() + value.len())
}
}
}
@@ -242,7 +241,7 @@
MintCross { .. } => withdraw_create_item::<T>(
&collection,
- &who,
+ who,
&CreateItemData::NFT(CreateNftData::default()),
),
@@ -250,7 +249,7 @@
| TransferFromCross { token_id, .. }
| Transfer { token_id, .. } => {
let token_id = TokenId::try_from(token_id).ok()?;
- withdraw_transfer::<T>(&collection, &who, &token_id)
+ withdraw_transfer::<T>(&collection, who, &token_id)
}
}
}
@@ -275,7 +274,7 @@
| MintWithTokenUri { .. }
| MintWithTokenUriCheckId { .. } => withdraw_create_item::<T>(
&collection,
- &who,
+ who,
&CreateItemData::NFT(CreateNftData::default()),
),
}
@@ -311,18 +310,15 @@
Transfer { .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
- let token_id = token_id.try_into().ok()?;
- withdraw_transfer::<T>(&handle, &who, &token_id)
+ withdraw_transfer::<T>(&handle, who, &token_id)
}
TransferFrom { from, .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
- let token_id = token_id.try_into().ok()?;
let from = T::CrossAccountId::from_eth(from);
withdraw_transfer::<T>(&handle, &from, &token_id)
}
Approve { .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
- let token_id = token_id.try_into().ok()?;
withdraw_approve::<T>(&handle, who.as_sub(), &token_id)
}
}
@@ -351,13 +347,11 @@
TransferCross { .. } | TransferFromCross { .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
- let token_id = token_id.try_into().ok()?;
- withdraw_transfer::<T>(&handle, &who, &token_id)
+ withdraw_transfer::<T>(&handle, who, &token_id)
}
ApproveCross { .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
- let token_id = token_id.try_into().ok()?;
withdraw_approve::<T>(&handle, who.as_sub(), &token_id)
}
}
runtime/common/mod.rsdiffbeforeafterboth--- a/runtime/common/mod.rs
+++ b/runtime/common/mod.rs
@@ -204,10 +204,7 @@
&[],
);
- let should_upgrade = match version {
- None => true,
- Some(_) => false,
- };
+ let should_upgrade = version.is_none();
if should_upgrade {
log::info!(
@@ -220,7 +217,7 @@
.cloned()
.filter_map(|authority_id| {
weight.saturating_accrue(<Runtime as frame_system::Config>::DbWeight::get().reads_writes(1, 1));
- let vec = authority_id.clone().to_raw_vec();
+ let vec = authority_id.to_raw_vec();
let slice = vec.as_slice();
let array: Option<[u8; 32]> = match slice.try_into() {
Ok(a) => Some(a),
@@ -248,20 +245,20 @@
.into_iter()
.map(|(acc, aura)| {
(
- acc.clone(), // account id
- acc, // validator id
- SessionKeys { aura: aura.clone() }, // session keys
+ acc.clone(), // account id
+ acc, // validator id
+ SessionKeys { aura }, // session keys
)
})
.collect::<Vec<_>>();
- for (account, val, keys) in keys.iter().cloned() {
+ for (account, val, keys) in keys.iter() {
for id in <Runtime as pallet_session::Config>::Keys::key_ids() {
- <pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), &val)
+ <pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), val)
}
- <pallet_session::NextKeys<Runtime>>::insert(&val, &keys);
+ <pallet_session::NextKeys<Runtime>>::insert(val, keys);
// todo exercise caution, the following is taken from genesis
- if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(&account)
+ if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(account)
.is_err()
{
log::warn!(
@@ -271,7 +268,7 @@
// genesis) so it's really not a big deal and we assume that the user wants to
// do this since it's the only way a non-endowed account can contain a session
// key.
- frame_system::Pallet::<Runtime>::inc_providers(&account);
+ frame_system::Pallet::<Runtime>::inc_providers(account);
}
}
runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -84,7 +84,7 @@
fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {
let budget = up_data_structs::budget::Value::new(10);
- Ok(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?)
+ <pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)
}
fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {
Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))
runtime/common/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/sponsoring.rs
+++ b/runtime/common/sponsoring.rs
@@ -240,7 +240,7 @@
withdraw_set_token_property(
&collection,
&T::CrossAccountId::from_sub(who.clone()),
- &token_id,
+ token_id,
// No overflow may happen, as data larger than usize can't reach here
properties.iter().map(|p| p.key.len() + p.value.len()).sum(),
)
test-pallets/utils/src/lib.rsdiffbeforeafterboth--- a/test-pallets/utils/src/lib.rs
+++ b/test-pallets/utils/src/lib.rs
@@ -170,7 +170,7 @@
fn ensure_origin_and_enabled(origin: OriginFor<T>) -> DispatchResult {
ensure_signed(origin)?;
<Enabled<T>>::get()
- .then(|| ())
+ .then_some(())
.ok_or(<Error<T>>::TestPalletDisabled.into())
}
}