difftreelog
Merge branch 'feature/app-staking' of github.com:UniqueNetwork/unique-chain into feature/app-staking
in: master
7 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -250,14 +250,17 @@
mod app_promotion_unique_rpc {
use super::*;
-
+
#[rpc(server)]
#[async_trait]
pub trait AppPromotionApi<BlockHash, BlockNumber, CrossAccountId, AccountId> {
/// Returns the total amount of staked tokens.
#[method(name = "appPromotion_totalStaked")]
- fn total_staked(&self, staker: Option<CrossAccountId>, at: Option<BlockHash>)
- -> Result<String>;
+ fn total_staked(
+ &self,
+ staker: Option<CrossAccountId>,
+ at: Option<BlockHash>,
+ ) -> Result<String>;
///Returns the total amount of staked tokens per block when staked.
#[method(name = "appPromotion_totalStakedPerBlock")]
@@ -269,8 +272,11 @@
/// Returns the total amount locked by staking tokens.
#[method(name = "appPromotion_totalStakingLocked")]
- fn total_staking_locked(&self, staker: CrossAccountId, at: Option<BlockHash>)
- -> Result<String>;
+ fn total_staking_locked(
+ &self,
+ staker: CrossAccountId,
+ at: Option<BlockHash>,
+ ) -> Result<String>;
/// Returns the total amount of tokens pending withdrawal from staking.
#[method(name = "appPromotion_pendingUnstake")]
@@ -570,8 +576,12 @@
}
impl<C, Block, BlockNumber, CrossAccountId, AccountId>
- app_promotion_unique_rpc::AppPromotionApiServer<<Block as BlockT>::Hash, BlockNumber, CrossAccountId, AccountId>
- for AppPromotion<C, Block>
+ app_promotion_unique_rpc::AppPromotionApiServer<
+ <Block as BlockT>::Hash,
+ BlockNumber,
+ CrossAccountId,
+ AccountId,
+ > for AppPromotion<C, Block>
where
Block: BlockT,
BlockNumber: Decode + Member + AtLeast32BitUnsigned,
node/rpc/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/>.1617use sp_runtime::traits::BlakeTwo256;18use fc_rpc::{19 EthBlockDataCacheTask, OverrideHandle, RuntimeApiStorageOverride, SchemaV1Override,20 StorageOverride, SchemaV2Override, SchemaV3Override,21};22use jsonrpsee::RpcModule;23use fc_rpc_core::types::{FilterPool, FeeHistoryCache};24use fp_storage::EthereumStorageSchema;25use sc_client_api::{26 backend::{AuxStore, StorageProvider},27 client::BlockchainEvents,28 StateBackend, Backend,29};30use sc_finality_grandpa::{31 FinalityProofProvider, GrandpaJustificationStream, SharedAuthoritySet, SharedVoterState,32};33use sc_network::NetworkService;34use sc_rpc::SubscriptionTaskExecutor;35pub use sc_rpc_api::DenyUnsafe;36use sc_transaction_pool::{ChainApi, Pool};37use sp_api::ProvideRuntimeApi;38use sp_block_builder::BlockBuilder;39use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};40use sc_service::TransactionPool;41use std::{collections::BTreeMap, sync::Arc};4243use up_common::types::opaque::{Hash, AccountId, RuntimeInstance, Index, Block, BlockNumber, Balance};4445// RMRK46use up_data_structs::{47 RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,48 RmrkPartType, RmrkTheme,49};5051/// Extra dependencies for GRANDPA52pub struct GrandpaDeps<B> {53 /// Voting round info.54 pub shared_voter_state: SharedVoterState,55 /// Authority set info.56 pub shared_authority_set: SharedAuthoritySet<Hash, BlockNumber>,57 /// Receives notifications about justification events from Grandpa.58 pub justification_stream: GrandpaJustificationStream<Block>,59 /// Executor to drive the subscription manager in the Grandpa RPC handler.60 pub subscription_executor: SubscriptionTaskExecutor,61 /// Finality proof provider.62 pub finality_provider: Arc<FinalityProofProvider<B, Block>>,63}6465/// Full client dependencies.66pub struct FullDeps<C, P, SC, CA: ChainApi> {67 /// The client instance to use.68 pub client: Arc<C>,69 /// Transaction pool instance.70 pub pool: Arc<P>,71 /// Graph pool instance.72 pub graph: Arc<Pool<CA>>,73 /// The SelectChain Strategy74 pub select_chain: SC,75 /// The Node authority flag76 pub is_authority: bool,77 /// Whether to enable dev signer78 pub enable_dev_signer: bool,79 /// Network service80 pub network: Arc<NetworkService<Block, Hash>>,81 /// Whether to deny unsafe calls82 pub deny_unsafe: DenyUnsafe,83 /// EthFilterApi pool.84 pub filter_pool: Option<FilterPool>,85 /// Backend.86 pub backend: Arc<fc_db::Backend<Block>>,87 /// Maximum number of logs in a query.88 pub max_past_logs: u32,89 /// Maximum fee history cache size.90 pub fee_history_limit: u64,91 /// Fee history cache.92 pub fee_history_cache: FeeHistoryCache,93 /// Cache for Ethereum block data.94 pub block_data_cache: Arc<EthBlockDataCacheTask<Block>>,95}9697pub fn overrides_handle<C, BE, R>(client: Arc<C>) -> Arc<OverrideHandle<Block>>98where99 C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,100 C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,101 C: Send + Sync + 'static,102 C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,103 C::Api:104 up_rpc::UniqueApi<Block, BlockNumber, <R as RuntimeInstance>::CrossAccountId, AccountId>,105 BE: Backend<Block> + 'static,106 BE::State: StateBackend<BlakeTwo256>,107 R: RuntimeInstance + Send + Sync + 'static,108{109 let mut overrides_map = BTreeMap::new();110 overrides_map.insert(111 EthereumStorageSchema::V1,112 Box::new(SchemaV1Override::new(client.clone()))113 as Box<dyn StorageOverride<_> + Send + Sync>,114 );115 overrides_map.insert(116 EthereumStorageSchema::V2,117 Box::new(SchemaV2Override::new(client.clone()))118 as Box<dyn StorageOverride<_> + Send + Sync>,119 );120 overrides_map.insert(121 EthereumStorageSchema::V3,122 Box::new(SchemaV3Override::new(client.clone()))123 as Box<dyn StorageOverride<_> + Send + Sync>,124 );125126 Arc::new(OverrideHandle {127 schemas: overrides_map,128 fallback: Box::new(RuntimeApiStorageOverride::new(client)),129 })130}131132/// Instantiate all Full RPC extensions.133pub fn create_full<C, P, SC, CA, R, A, B>(134 deps: FullDeps<C, P, SC, CA>,135 subscription_task_executor: SubscriptionTaskExecutor,136) -> Result<RpcModule<()>, Box<dyn std::error::Error + Send + Sync>>137where138 C: ProvideRuntimeApi<Block> + StorageProvider<Block, B> + AuxStore,139 C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,140 C: Send + Sync + 'static,141 C: BlockchainEvents<Block>,142 C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,143 C::Api: BlockBuilder<Block>,144 // C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,145 C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,146 C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,147 C::Api: fp_rpc::ConvertTransactionRuntimeApi<Block>,148 C::Api:149 up_rpc::UniqueApi<Block, BlockNumber, <R as RuntimeInstance>::CrossAccountId, AccountId>,150 C::Api: app_promotion_rpc::AppPromotionApi<Block, BlockNumber, <R as RuntimeInstance>::CrossAccountId, AccountId>,151 C::Api: rmrk_rpc::RmrkApi<152 Block,153 AccountId,154 RmrkCollectionInfo<AccountId>,155 RmrkInstanceInfo<AccountId>,156 RmrkResourceInfo,157 RmrkPropertyInfo,158 RmrkBaseInfo<AccountId>,159 RmrkPartType,160 RmrkTheme,161 >,162 B: sc_client_api::Backend<Block> + Send + Sync + 'static,163 B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,164 P: TransactionPool<Block = Block> + 'static,165 CA: ChainApi<Block = Block> + 'static,166 R: RuntimeInstance + Send + Sync + 'static,167 <R as RuntimeInstance>::CrossAccountId: serde::Serialize,168 for<'de> <R as RuntimeInstance>::CrossAccountId: serde::Deserialize<'de>,169{170 use fc_rpc::{171 Eth, EthApiServer, EthDevSigner, EthFilter, EthFilterApiServer, EthPubSub,172 EthPubSubApiServer, EthSigner, Net, NetApiServer, Web3, Web3ApiServer,173 };174 use uc_rpc::{UniqueApiServer, Unique};175 use uc_rpc::{AppPromotionApiServer, AppPromotion};176177 #[cfg(not(feature = "unique-runtime"))]178 use uc_rpc::{RmrkApiServer, Rmrk};179180 // use pallet_contracts_rpc::{Contracts, ContractsApi};181 use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};182 use substrate_frame_rpc_system::{System, SystemApiServer};183184 let mut io = RpcModule::new(());185 let FullDeps {186 client,187 pool,188 graph,189 select_chain: _,190 fee_history_limit,191 fee_history_cache,192 block_data_cache,193 enable_dev_signer,194 is_authority,195 network,196 deny_unsafe,197 filter_pool,198 backend,199 max_past_logs,200 } = deps;201202 io.merge(System::new(Arc::clone(&client), Arc::clone(&pool), deny_unsafe).into_rpc())?;203 io.merge(TransactionPayment::new(Arc::clone(&client)).into_rpc())?;204205 // io.extend_with(ContractsApi::to_delegate(Contracts::new(client.clone())));206207 let mut signers = Vec::new();208 if enable_dev_signer {209 signers.push(Box::new(EthDevSigner::new()) as Box<dyn EthSigner>);210 }211212 let overrides = overrides_handle::<_, _, R>(client.clone());213214 io.merge(215 Eth::new(216 client.clone(),217 pool.clone(),218 graph,219 Some(<R as RuntimeInstance>::get_transaction_converter()),220 network.clone(),221 signers,222 overrides.clone(),223 backend.clone(),224 is_authority,225 block_data_cache.clone(),226 fee_history_cache,227 fee_history_limit,228 )229 .into_rpc(),230 )?;231232 io.merge(Unique::new(client.clone()).into_rpc())?;233234 #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]235 io.merge(AppPromotion::new(client.clone()).into_rpc())?;236237 #[cfg(not(feature = "unique-runtime"))]238 io.merge(Rmrk::new(client.clone()).into_rpc())?;239240 if let Some(filter_pool) = filter_pool {241 io.merge(242 EthFilter::new(243 client.clone(),244 backend,245 filter_pool,246 500_usize, // max stored filters247 max_past_logs,248 block_data_cache,249 )250 .into_rpc(),251 )?;252 }253254 io.merge(255 Net::new(256 client.clone(),257 network.clone(),258 // Whether to format the `peer_count` response as Hex (default) or not.259 true,260 )261 .into_rpc(),262 )?;263264 io.merge(Web3::new(client.clone()).into_rpc())?;265266 io.merge(267 EthPubSub::new(pool, client, network, subscription_task_executor, overrides).into_rpc(),268 )?;269270 Ok(io)271}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/>.1617use sp_runtime::traits::BlakeTwo256;18use fc_rpc::{19 EthBlockDataCacheTask, OverrideHandle, RuntimeApiStorageOverride, SchemaV1Override,20 StorageOverride, SchemaV2Override, SchemaV3Override,21};22use jsonrpsee::RpcModule;23use fc_rpc_core::types::{FilterPool, FeeHistoryCache};24use fp_storage::EthereumStorageSchema;25use sc_client_api::{26 backend::{AuxStore, StorageProvider},27 client::BlockchainEvents,28 StateBackend, Backend,29};30use sc_finality_grandpa::{31 FinalityProofProvider, GrandpaJustificationStream, SharedAuthoritySet, SharedVoterState,32};33use sc_network::NetworkService;34use sc_rpc::SubscriptionTaskExecutor;35pub use sc_rpc_api::DenyUnsafe;36use sc_transaction_pool::{ChainApi, Pool};37use sp_api::ProvideRuntimeApi;38use sp_block_builder::BlockBuilder;39use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};40use sc_service::TransactionPool;41use std::{collections::BTreeMap, sync::Arc};4243use up_common::types::opaque::{Hash, AccountId, RuntimeInstance, Index, Block, BlockNumber, Balance};4445// RMRK46use up_data_structs::{47 RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,48 RmrkPartType, RmrkTheme,49};5051/// Extra dependencies for GRANDPA52pub struct GrandpaDeps<B> {53 /// Voting round info.54 pub shared_voter_state: SharedVoterState,55 /// Authority set info.56 pub shared_authority_set: SharedAuthoritySet<Hash, BlockNumber>,57 /// Receives notifications about justification events from Grandpa.58 pub justification_stream: GrandpaJustificationStream<Block>,59 /// Executor to drive the subscription manager in the Grandpa RPC handler.60 pub subscription_executor: SubscriptionTaskExecutor,61 /// Finality proof provider.62 pub finality_provider: Arc<FinalityProofProvider<B, Block>>,63}6465/// Full client dependencies.66pub struct FullDeps<C, P, SC, CA: ChainApi> {67 /// The client instance to use.68 pub client: Arc<C>,69 /// Transaction pool instance.70 pub pool: Arc<P>,71 /// Graph pool instance.72 pub graph: Arc<Pool<CA>>,73 /// The SelectChain Strategy74 pub select_chain: SC,75 /// The Node authority flag76 pub is_authority: bool,77 /// Whether to enable dev signer78 pub enable_dev_signer: bool,79 /// Network service80 pub network: Arc<NetworkService<Block, Hash>>,81 /// Whether to deny unsafe calls82 pub deny_unsafe: DenyUnsafe,83 /// EthFilterApi pool.84 pub filter_pool: Option<FilterPool>,85 /// Backend.86 pub backend: Arc<fc_db::Backend<Block>>,87 /// Maximum number of logs in a query.88 pub max_past_logs: u32,89 /// Maximum fee history cache size.90 pub fee_history_limit: u64,91 /// Fee history cache.92 pub fee_history_cache: FeeHistoryCache,93 /// Cache for Ethereum block data.94 pub block_data_cache: Arc<EthBlockDataCacheTask<Block>>,95}9697pub fn overrides_handle<C, BE, R>(client: Arc<C>) -> Arc<OverrideHandle<Block>>98where99 C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,100 C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,101 C: Send + Sync + 'static,102 C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,103 C::Api:104 up_rpc::UniqueApi<Block, BlockNumber, <R as RuntimeInstance>::CrossAccountId, AccountId>,105 BE: Backend<Block> + 'static,106 BE::State: StateBackend<BlakeTwo256>,107 R: RuntimeInstance + Send + Sync + 'static,108{109 let mut overrides_map = BTreeMap::new();110 overrides_map.insert(111 EthereumStorageSchema::V1,112 Box::new(SchemaV1Override::new(client.clone()))113 as Box<dyn StorageOverride<_> + Send + Sync>,114 );115 overrides_map.insert(116 EthereumStorageSchema::V2,117 Box::new(SchemaV2Override::new(client.clone()))118 as Box<dyn StorageOverride<_> + Send + Sync>,119 );120 overrides_map.insert(121 EthereumStorageSchema::V3,122 Box::new(SchemaV3Override::new(client.clone()))123 as Box<dyn StorageOverride<_> + Send + Sync>,124 );125126 Arc::new(OverrideHandle {127 schemas: overrides_map,128 fallback: Box::new(RuntimeApiStorageOverride::new(client)),129 })130}131132/// Instantiate all Full RPC extensions.133pub fn create_full<C, P, SC, CA, R, A, B>(134 deps: FullDeps<C, P, SC, CA>,135 subscription_task_executor: SubscriptionTaskExecutor,136) -> Result<RpcModule<()>, Box<dyn std::error::Error + Send + Sync>>137where138 C: ProvideRuntimeApi<Block> + StorageProvider<Block, B> + AuxStore,139 C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,140 C: Send + Sync + 'static,141 C: BlockchainEvents<Block>,142 C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,143 C::Api: BlockBuilder<Block>,144 // C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,145 C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,146 C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,147 C::Api: fp_rpc::ConvertTransactionRuntimeApi<Block>,148 C::Api:149 up_rpc::UniqueApi<Block, BlockNumber, <R as RuntimeInstance>::CrossAccountId, AccountId>,150 C::Api: app_promotion_rpc::AppPromotionApi<151 Block,152 BlockNumber,153 <R as RuntimeInstance>::CrossAccountId,154 AccountId,155 >,156 C::Api: rmrk_rpc::RmrkApi<157 Block,158 AccountId,159 RmrkCollectionInfo<AccountId>,160 RmrkInstanceInfo<AccountId>,161 RmrkResourceInfo,162 RmrkPropertyInfo,163 RmrkBaseInfo<AccountId>,164 RmrkPartType,165 RmrkTheme,166 >,167 B: sc_client_api::Backend<Block> + Send + Sync + 'static,168 B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,169 P: TransactionPool<Block = Block> + 'static,170 CA: ChainApi<Block = Block> + 'static,171 R: RuntimeInstance + Send + Sync + 'static,172 <R as RuntimeInstance>::CrossAccountId: serde::Serialize,173 for<'de> <R as RuntimeInstance>::CrossAccountId: serde::Deserialize<'de>,174{175 use fc_rpc::{176 Eth, EthApiServer, EthDevSigner, EthFilter, EthFilterApiServer, EthPubSub,177 EthPubSubApiServer, EthSigner, Net, NetApiServer, Web3, Web3ApiServer,178 };179 use uc_rpc::{UniqueApiServer, Unique};180 use uc_rpc::{AppPromotionApiServer, AppPromotion};181182 #[cfg(not(feature = "unique-runtime"))]183 use uc_rpc::{RmrkApiServer, Rmrk};184185 // use pallet_contracts_rpc::{Contracts, ContractsApi};186 use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};187 use substrate_frame_rpc_system::{System, SystemApiServer};188189 let mut io = RpcModule::new(());190 let FullDeps {191 client,192 pool,193 graph,194 select_chain: _,195 fee_history_limit,196 fee_history_cache,197 block_data_cache,198 enable_dev_signer,199 is_authority,200 network,201 deny_unsafe,202 filter_pool,203 backend,204 max_past_logs,205 } = deps;206207 io.merge(System::new(Arc::clone(&client), Arc::clone(&pool), deny_unsafe).into_rpc())?;208 io.merge(TransactionPayment::new(Arc::clone(&client)).into_rpc())?;209210 // io.extend_with(ContractsApi::to_delegate(Contracts::new(client.clone())));211212 let mut signers = Vec::new();213 if enable_dev_signer {214 signers.push(Box::new(EthDevSigner::new()) as Box<dyn EthSigner>);215 }216217 let overrides = overrides_handle::<_, _, R>(client.clone());218219 io.merge(220 Eth::new(221 client.clone(),222 pool.clone(),223 graph,224 Some(<R as RuntimeInstance>::get_transaction_converter()),225 network.clone(),226 signers,227 overrides.clone(),228 backend.clone(),229 is_authority,230 block_data_cache.clone(),231 fee_history_cache,232 fee_history_limit,233 )234 .into_rpc(),235 )?;236237 io.merge(Unique::new(client.clone()).into_rpc())?;238239 #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]240 io.merge(AppPromotion::new(client.clone()).into_rpc())?;241242 #[cfg(not(feature = "unique-runtime"))]243 io.merge(Rmrk::new(client.clone()).into_rpc())?;244245 if let Some(filter_pool) = filter_pool {246 io.merge(247 EthFilter::new(248 client.clone(),249 backend,250 filter_pool,251 500_usize, // max stored filters252 max_past_logs,253 block_data_cache,254 )255 .into_rpc(),256 )?;257 }258259 io.merge(260 Net::new(261 client.clone(),262 network.clone(),263 // Whether to format the `peer_count` response as Hex (default) or not.264 true,265 )266 .into_rpc(),267 )?;268269 io.merge(Web3::new(client.clone()).into_rpc())?;270271 io.merge(272 EthPubSub::new(pool, client, network, subscription_task_executor, overrides).into_rpc(),273 )?;274275 Ok(io)276}pallets/app-promotion/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/benchmarking.rs
+++ b/pallets/app-promotion/src/benchmarking.rs
@@ -39,13 +39,13 @@
T::BlockNumber: From<u32> + Into<u32>,
<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>
}
- start_app_promotion {
+ // start_app_promotion {
- } : {PromototionPallet::<T>::start_app_promotion(RawOrigin::Root.into(), None)?}
+ // } : {PromototionPallet::<T>::start_app_promotion(RawOrigin::Root.into(), None)?}
- stop_app_promotion{
- PromototionPallet::<T>::start_app_promotion(RawOrigin::Root.into(), Some(25.into()))?;
- } : {PromototionPallet::<T>::stop_app_promotion(RawOrigin::Root.into())?}
+ // stop_app_promotion{
+ // PromototionPallet::<T>::start_app_promotion(RawOrigin::Root.into(), Some(25.into()))?;
+ // } : {PromototionPallet::<T>::stop_app_promotion(RawOrigin::Root.into())?}
set_admin_address {
let pallet_admin = account::<T::AccountId>("admin", 0, SEED);
@@ -58,6 +58,10 @@
PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;
let _ = <T as Config>::Currency::make_free_balance_be(&pallet_admin, Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
let staker: T::AccountId = account("caller", 0, SEED);
+ let stakers: Vec<T::AccountId> = (0..100).map(|index| account("staker", index, SEED)).collect();
+ stakers.iter().for_each(|staker| {
+ <T as Config>::Currency::make_free_balance_be(&staker, Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
+ });
let _ = <T as Config>::Currency::make_free_balance_be(&staker, Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
let _ = PromototionPallet::<T>::stake(RawOrigin::Signed(staker.clone()).into(), share * <T as Config>::Currency::total_balance(&staker))?;
} : {PromototionPallet::<T>::payout_stakers(RawOrigin::Signed(pallet_admin.clone()).into(), Some(1))?}
@@ -70,9 +74,9 @@
unstake {
let caller = account::<T::AccountId>("caller", 0, SEED);
- let share = Perbill::from_rational(1u32, 10);
+ let share = Perbill::from_rational(1u32, 20);
let _ = <T as Config>::Currency::make_free_balance_be(&caller, Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
- let _ = PromototionPallet::<T>::stake(RawOrigin::Signed(caller.clone()).into(), share * <T as Config>::Currency::total_balance(&caller))?;
+ (0..10).map(|_| PromototionPallet::<T>::stake(RawOrigin::Signed(caller.clone()).into(), share * <T as Config>::Currency::total_balance(&caller))).collect::<Result<Vec<_>, _>>()?;
} : {PromototionPallet::<T>::unstake(RawOrigin::Signed(caller.clone()).into())?}
pallets/app-promotion/src/lib.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -36,7 +36,12 @@
pub mod types;
pub mod weights;
-use sp_std::{vec::Vec, iter::Sum, borrow::ToOwned};
+use sp_std::{
+ vec::{Vec},
+ vec,
+ iter::Sum,
+ borrow::ToOwned,
+};
use sp_core::H160;
use codec::EncodeLike;
use pallet_balances::BalanceLock;
@@ -63,6 +68,9 @@
ArithmeticError,
};
+pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";
+const PENDING_LIMIT_PER_BLOCK: u32 = 3;
+
type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
@@ -71,18 +79,20 @@
// const WEEK: u32 = 7 * DAY;
// const TWO_WEEK: u32 = 2 * WEEK;
// const YEAR: u32 = DAY * 365;
-
-pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";
#[frame_support::pallet]
pub mod pallet {
use super::*;
- use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId};
+ use frame_support::{
+ Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,
+ traits::ReservableCurrency,
+ };
use frame_system::pallet_prelude::*;
#[pallet::config]
pub trait Config: frame_system::Config + pallet_evm::account::Config {
- type Currency: ExtendedLockableCurrency<Self::AccountId>;
+ type Currency: ExtendedLockableCurrency<Self::AccountId>
+ + ReservableCurrency<Self::AccountId>;
type CollectionHandler: CollectionHandler<
AccountId = Self::AccountId,
@@ -149,6 +159,7 @@
NoPermission,
/// Insufficient funds to perform an action
NotSufficientFounds,
+ PendingForBlockOverflow,
/// An error related to the fact that an invalid argument was passed to perform an action
InvalidArgument,
}
@@ -175,25 +186,33 @@
StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;
/// Amount of tokens pending unstake per user per block.
+ // #[pallet::storage]
+ // pub type PendingUnstake<T: Config> = StorageNMap<
+ // Key = (
+ // Key<Blake2_128Concat, T::AccountId>,
+ // Key<Twox64Concat, T::BlockNumber>,
+ // ),
+ // Value = BalanceOf<T>,
+ // QueryKind = ValueQuery,
+ // >;
#[pallet::storage]
- pub type PendingUnstake<T: Config> = StorageNMap<
- Key = (
- Key<Blake2_128Concat, T::AccountId>,
- Key<Twox64Concat, T::BlockNumber>,
- ),
- Value = BalanceOf<T>,
- QueryKind = ValueQuery,
+ pub type PendingUnstake<T: Config> = StorageMap<
+ _,
+ Twox64Concat,
+ T::BlockNumber,
+ BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,
+ ValueQuery,
>;
/// A block when app-promotion has started .I think this is redundant, because we only need `NextInterestBlock`.
#[pallet::storage]
pub type StartBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
- /// Next target block when interest is recalculated
- #[pallet::storage]
- #[pallet::getter(fn get_interest_block)]
- pub type NextInterestBlock<T: Config> =
- StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
+ // /// Next target block when interest is recalculated
+ // #[pallet::storage]
+ // #[pallet::getter(fn get_interest_block)]
+ // pub type NextInterestBlock<T: Config> =
+ // StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
/// Stores hash a record for which the last revenue recalculation was performed.
/// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.
@@ -204,59 +223,26 @@
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
- fn on_initialize(current_block: T::BlockNumber) -> Weight
+ fn on_initialize(current_block_number: T::BlockNumber) -> Weight
where
<T as frame_system::Config>::BlockNumber: From<u32>,
{
let mut consumed_weight = 0;
- // let mut add_weight = |reads, writes, weight| {
- // consumed_weight += T::DbWeight::get().reads_writes(reads, writes);
- // consumed_weight += weight;
- // };
+ let mut add_weight = |reads, writes, weight| {
+ consumed_weight += T::DbWeight::get().reads_writes(reads, writes);
+ consumed_weight += weight;
+ };
- let current_relay_block = T::RelayBlockNumberProvider::current_block_number();
- PendingUnstake::<T>::iter()
- .filter_map(|((staker, block), amount)| {
- if block <= current_relay_block {
- Some((staker, block, amount))
- } else {
- None
- }
- })
- .for_each(|(staker, block, amount)| {
- Self::unlock_balance_unchecked(&staker, amount);
- <PendingUnstake<T>>::remove((staker, block));
- });
+ let block_pending = PendingUnstake::<T>::take(current_block_number);
- // let next_interest_block = Self::get_interest_block();
- // let current_relay_block = T::RelayBlockNumberProvider::current_block_number();
- // if next_interest_block != 0.into() && current_relay_block >= next_interest_block {
- // let mut acc = <BalanceOf<T>>::default();
- // let mut base_acc = <BalanceOf<T>>::default();
+ add_weight(0, 1, 0);
- // NextInterestBlock::<T>::set(
- // NextInterestBlock::<T>::get() + T::RecalculationInterval::get(),
- // );
- // add_weight(0, 1, 0);
-
- // Staked::<T>::iter()
- // .filter(|((_, block), _)| {
- // *block + T::RecalculationInterval::get() <= current_relay_block
- // })
- // .for_each(|((staker, block), amount)| {
- // Self::recalculate_stake(&staker, block, amount, &mut acc);
- // add_weight(0, 0, T::WeightInfo::recalculate_stake());
- // base_acc += amount;
- // });
- // <TotalStaked<T>>::get()
- // .checked_add(&acc)
- // .map(|res| <TotalStaked<T>>::set(res));
+ if !block_pending.is_empty() {
+ block_pending.into_iter().for_each(|(staker, amount)| {
+ <T::Currency as ReservableCurrency<T::AccountId>>::unreserve(&staker, amount);
+ });
+ }
- // Self::deposit_event(Event::StakingRecalculation(base_acc, acc));
- // add_weight(0, 1, 0);
- // } else {
- // add_weight(1, 0, 0)
- // };
consumed_weight
}
}
@@ -275,44 +261,44 @@
Ok(())
}
- #[pallet::weight(T::WeightInfo::start_app_promotion())]
- pub fn start_app_promotion(
- origin: OriginFor<T>,
- promotion_start_relay_block: Option<T::BlockNumber>,
- ) -> DispatchResult
- where
- <T as frame_system::Config>::BlockNumber: From<u32>,
- {
- ensure_root(origin)?;
+ // #[pallet::weight(T::WeightInfo::start_app_promotion())]
+ // pub fn start_app_promotion(
+ // origin: OriginFor<T>,
+ // promotion_start_relay_block: Option<T::BlockNumber>,
+ // ) -> DispatchResult
+ // where
+ // <T as frame_system::Config>::BlockNumber: From<u32>,
+ // {
+ // ensure_root(origin)?;
- // Start app-promotion mechanics if it has not been yet initialized
- if <StartBlock<T>>::get() == 0u32.into() {
- let start_block = promotion_start_relay_block
- .unwrap_or(T::RelayBlockNumberProvider::current_block_number());
+ // // Start app-promotion mechanics if it has not been yet initialized
+ // if <StartBlock<T>>::get() == 0u32.into() {
+ // let start_block = promotion_start_relay_block
+ // .unwrap_or(T::RelayBlockNumberProvider::current_block_number());
- // Set promotion global start block
- <StartBlock<T>>::set(start_block);
+ // // Set promotion global start block
+ // <StartBlock<T>>::set(start_block);
- <NextInterestBlock<T>>::set(start_block + T::RecalculationInterval::get());
- }
+ // <NextInterestBlock<T>>::set(start_block + T::RecalculationInterval::get());
+ // }
- Ok(())
- }
+ // Ok(())
+ // }
- #[pallet::weight(T::WeightInfo::stop_app_promotion())]
- pub fn stop_app_promotion(origin: OriginFor<T>) -> DispatchResult
- where
- <T as frame_system::Config>::BlockNumber: From<u32>,
- {
- ensure_root(origin)?;
+ // #[pallet::weight(T::WeightInfo::stop_app_promotion())]
+ // pub fn stop_app_promotion(origin: OriginFor<T>) -> DispatchResult
+ // where
+ // <T as frame_system::Config>::BlockNumber: From<u32>,
+ // {
+ // ensure_root(origin)?;
- if <StartBlock<T>>::get() != 0u32.into() {
- <StartBlock<T>>::set(T::BlockNumber::default());
- <NextInterestBlock<T>>::set(T::BlockNumber::default());
- }
+ // if <StartBlock<T>>::get() != 0u32.into() {
+ // <StartBlock<T>>::set(T::BlockNumber::default());
+ // <NextInterestBlock<T>>::set(T::BlockNumber::default());
+ // }
- Ok(())
- }
+ // Ok(())
+ // }
#[pallet::weight(T::WeightInfo::stake())]
pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {
@@ -369,6 +355,10 @@
#[pallet::weight(T::WeightInfo::unstake())]
pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {
let staker_id = ensure_signed(staker)?;
+ let block = <frame_system::Pallet<T>>::block_number() + T::PendingInterval::get();
+ let mut pendings = <PendingUnstake<T>>::get(block);
+
+ ensure!(pendings.is_full(), Error::<T>::PendingForBlockOverflow);
let mut total_stakes = 0u64;
@@ -382,15 +372,17 @@
if total_staked.is_zero() {
return Ok(None.into());
}
- let block =
- T::RelayBlockNumberProvider::current_block_number() + T::PendingInterval::get();
- <PendingUnstake<T>>::insert(
- (&staker_id, block),
- <PendingUnstake<T>>::get((&staker_id, block))
- .checked_add(&total_staked)
- .ok_or(ArithmeticError::Overflow)?,
- );
+ pendings
+ .try_push((staker_id.clone(), total_staked))
+ .map_err(|_| Error::<T>::PendingForBlockOverflow)?;
+
+ <PendingUnstake<T>>::insert(block, pendings);
+
+ Self::unlock_balance_unchecked(&staker_id, total_staked);
+
+ <T::Currency as ReservableCurrency<T::AccountId>>::reserve(&staker_id, total_staked)?;
+
TotalStaked::<T>::set(
TotalStaked::<T>::get()
.checked_sub(&total_staked)
@@ -671,17 +663,37 @@
<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,
{
pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {
- staker.map_or(PendingUnstake::<T>::iter_values().sum(), |s| {
- PendingUnstake::<T>::iter_prefix_values((s.as_sub(),)).sum()
- })
+ staker.map_or(
+ PendingUnstake::<T>::iter_values()
+ .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))
+ .sum(),
+ |s| {
+ PendingUnstake::<T>::iter_values()
+ .flatten()
+ .filter_map(|(id, amount)| {
+ if id == *s.as_sub() {
+ Some(amount)
+ } else {
+ None
+ }
+ })
+ .sum()
+ },
+ )
}
pub fn cross_id_pending_unstake_per_block(
staker: T::CrossAccountId,
) -> Vec<(T::BlockNumber, BalanceOf<T>)> {
- let mut unsorted_res = PendingUnstake::<T>::iter_prefix((staker.as_sub(),))
- .into_iter()
- .collect::<Vec<_>>();
+ let mut unsorted_res = vec![];
+ PendingUnstake::<T>::iter().for_each(|(block, pendings)| {
+ pendings.into_iter().for_each(|(id, amount)| {
+ if id == *staker.as_sub() {
+ unsorted_res.push((block, amount));
+ };
+ })
+ });
+
unsorted_res.sort_by_key(|(block, _)| *block);
unsorted_res
}
pallets/app-promotion/src/tests.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/tests.rs
+++ b/pallets/app-promotion/src/tests.rs
@@ -16,20 +16,20 @@
#![cfg(test)]
#![allow(clippy::from_over_into)]
-use crate as pallet_promotion;
+// use crate as pallet_promotion;
-use frame_benchmarking::{add_benchmark, BenchmarkBatch};
-use frame_support::{
- assert_ok, parameter_types,
- traits::{Currency, OnInitialize, Everything, ConstU32},
-};
-use frame_system::RawOrigin;
-use sp_core::H256;
-use sp_runtime::{
- traits::{BlakeTwo256, BlockNumberProvider, IdentityLookup},
- testing::Header,
- Perbill, Perquintill,
-};
+// use frame_benchmarking::{add_benchmark, BenchmarkBatch};
+// use frame_support::{
+// assert_ok, parameter_types,
+// traits::{Currency, OnInitialize, Everything, ConstU32},
+// };
+// use frame_system::RawOrigin;
+// use sp_core::H256;
+// use sp_runtime::{
+// traits::{BlakeTwo256, BlockNumberProvider, IdentityLookup},
+// testing::Header,
+// Perbill, Perquintill,
+// };
// type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
// type Block = frame_system::mocking::MockBlock<Test>;
@@ -127,24 +127,24 @@
// } )
// }
-#[test]
-fn test_perbill() {
- const ONE_UNIQE: u128 = 1_000_000_000_000_000_000;
- const SECONDS_TO_BLOCK: u32 = 12;
- const DAY: u32 = 60 * 60 * 24 / SECONDS_TO_BLOCK;
- const RECALCULATION_INTERVAL: u32 = 10;
- let day_rate = Perbill::from_rational(5u64, 10_000);
- let interval_rate =
- Perbill::from_rational::<u64>(RECALCULATION_INTERVAL.into(), DAY.into()) * day_rate;
- println!("{:?}", interval_rate * ONE_UNIQE + ONE_UNIQE);
- println!("{:?}", day_rate * ONE_UNIQE);
- println!("{:?}", Perbill::one() * ONE_UNIQE);
- println!("{:?}", ONE_UNIQE);
- let mut next_iters = ONE_UNIQE + interval_rate * ONE_UNIQE;
- next_iters += interval_rate * next_iters;
- println!("{:?}", next_iters);
- let day_income = day_rate * ONE_UNIQE;
- let interval_income = interval_rate * ONE_UNIQE;
- let ratio = day_income / interval_income;
- println!("{:?} || {:?}", ratio, DAY / RECALCULATION_INTERVAL);
-}
+// #[test]
+// fn test_perbill() {
+// const ONE_UNIQE: u128 = 1_000_000_000_000_000_000;
+// const SECONDS_TO_BLOCK: u32 = 12;
+// const DAY: u32 = 60 * 60 * 24 / SECONDS_TO_BLOCK;
+// const RECALCULATION_INTERVAL: u32 = 10;
+// let day_rate = Perbill::from_rational(5u64, 10_000);
+// let interval_rate =
+// Perbill::from_rational::<u64>(RECALCULATION_INTERVAL.into(), DAY.into()) * day_rate;
+// println!("{:?}", interval_rate * ONE_UNIQE + ONE_UNIQE);
+// println!("{:?}", day_rate * ONE_UNIQE);
+// println!("{:?}", Perbill::one() * ONE_UNIQE);
+// println!("{:?}", ONE_UNIQE);
+// let mut next_iters = ONE_UNIQE + interval_rate * ONE_UNIQE;
+// next_iters += interval_rate * next_iters;
+// println!("{:?}", next_iters);
+// let day_income = day_rate * ONE_UNIQE;
+// let interval_income = interval_rate * ONE_UNIQE;
+// let ratio = day_income / interval_income;
+// println!("{:?} || {:?}", ratio, DAY / RECALCULATION_INTERVAL);
+// }
pallets/app-promotion/src/weights.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/weights.rs
+++ b/pallets/app-promotion/src/weights.rs
@@ -3,7 +3,7 @@
//! Autogenerated weights for pallet_app_promotion
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-08-31, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! DATE: 2022-09-01, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
// Executed Command:
@@ -34,8 +34,6 @@
/// Weight functions needed for pallet_app_promotion.
pub trait WeightInfo {
- fn start_app_promotion() -> Weight;
- fn stop_app_promotion() -> Weight;
fn set_admin_address() -> Weight;
fn payout_stakers() -> Weight;
fn stake() -> Weight;
@@ -49,24 +47,9 @@
/// Weights for pallet_app_promotion using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
- // Storage: Promotion StartBlock (r:1 w:1)
- // Storage: ParachainSystem ValidationData (r:1 w:0)
- // Storage: Promotion NextInterestBlock (r:0 w:1)
- fn start_app_promotion() -> Weight {
- (3_995_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(2 as Weight))
- .saturating_add(T::DbWeight::get().writes(2 as Weight))
- }
- // Storage: Promotion StartBlock (r:1 w:1)
- // Storage: Promotion NextInterestBlock (r:0 w:1)
- fn stop_app_promotion() -> Weight {
- (3_623_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(1 as Weight))
- .saturating_add(T::DbWeight::get().writes(2 as Weight))
- }
// Storage: Promotion Admin (r:0 w:1)
fn set_admin_address() -> Weight {
- (1_203_000 as Weight)
+ (515_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Promotion Admin (r:1 w:0)
@@ -74,54 +57,56 @@
// Storage: Promotion NextCalculatedRecord (r:1 w:1)
// Storage: Promotion Staked (r:2 w:0)
fn payout_stakers() -> Weight {
- (10_859_000 as Weight)
+ (8_475_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: System Account (r:1 w:1)
+ // Storage: Promotion StakesPerAccount (r:1 w:1)
// Storage: Balances Locks (r:1 w:1)
// Storage: ParachainSystem ValidationData (r:1 w:0)
// Storage: Promotion Staked (r:1 w:1)
// Storage: Promotion TotalStaked (r:1 w:1)
fn stake() -> Weight {
- (14_789_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(5 as Weight))
- .saturating_add(T::DbWeight::get().writes(4 as Weight))
+ (12_266_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(6 as Weight))
+ .saturating_add(T::DbWeight::get().writes(5 as Weight))
}
// Storage: Promotion Staked (r:2 w:1)
// Storage: ParachainSystem ValidationData (r:1 w:0)
// Storage: Promotion PendingUnstake (r:1 w:1)
// Storage: Promotion TotalStaked (r:1 w:1)
+ // Storage: Promotion StakesPerAccount (r:0 w:1)
fn unstake() -> Weight {
- (16_889_000 as Weight)
+ (10_663_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
- .saturating_add(T::DbWeight::get().writes(3 as Weight))
+ .saturating_add(T::DbWeight::get().writes(4 as Weight))
}
// Storage: Promotion Admin (r:1 w:0)
// Storage: Common CollectionById (r:1 w:1)
fn sponsor_collection() -> Weight {
- (18_377_000 as Weight)
+ (10_879_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Promotion Admin (r:1 w:0)
// Storage: Common CollectionById (r:1 w:1)
fn stop_sponsoring_collection() -> Weight {
- (13_989_000 as Weight)
+ (10_548_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Promotion Admin (r:1 w:0)
// Storage: EvmContractHelpers Sponsoring (r:0 w:1)
fn sponsor_contract() -> Weight {
- (4_162_000 as Weight)
+ (2_130_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Promotion Admin (r:1 w:0)
// Storage: EvmContractHelpers Sponsoring (r:1 w:1)
fn stop_sponsoring_contract() -> Weight {
- (5_457_000 as Weight)
+ (3_509_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
@@ -129,24 +114,9 @@
// For backwards compatibility and tests
impl WeightInfo for () {
- // Storage: Promotion StartBlock (r:1 w:1)
- // Storage: ParachainSystem ValidationData (r:1 w:0)
- // Storage: Promotion NextInterestBlock (r:0 w:1)
- fn start_app_promotion() -> Weight {
- (3_995_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(2 as Weight))
- .saturating_add(RocksDbWeight::get().writes(2 as Weight))
- }
- // Storage: Promotion StartBlock (r:1 w:1)
- // Storage: Promotion NextInterestBlock (r:0 w:1)
- fn stop_app_promotion() -> Weight {
- (3_623_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(1 as Weight))
- .saturating_add(RocksDbWeight::get().writes(2 as Weight))
- }
// Storage: Promotion Admin (r:0 w:1)
fn set_admin_address() -> Weight {
- (1_203_000 as Weight)
+ (515_000 as Weight)
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Promotion Admin (r:1 w:0)
@@ -154,54 +124,56 @@
// Storage: Promotion NextCalculatedRecord (r:1 w:1)
// Storage: Promotion Staked (r:2 w:0)
fn payout_stakers() -> Weight {
- (10_859_000 as Weight)
+ (8_475_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: System Account (r:1 w:1)
+ // Storage: Promotion StakesPerAccount (r:1 w:1)
// Storage: Balances Locks (r:1 w:1)
// Storage: ParachainSystem ValidationData (r:1 w:0)
// Storage: Promotion Staked (r:1 w:1)
// Storage: Promotion TotalStaked (r:1 w:1)
fn stake() -> Weight {
- (14_789_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(5 as Weight))
- .saturating_add(RocksDbWeight::get().writes(4 as Weight))
+ (12_266_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(6 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(5 as Weight))
}
// Storage: Promotion Staked (r:2 w:1)
// Storage: ParachainSystem ValidationData (r:1 w:0)
// Storage: Promotion PendingUnstake (r:1 w:1)
// Storage: Promotion TotalStaked (r:1 w:1)
+ // Storage: Promotion StakesPerAccount (r:0 w:1)
fn unstake() -> Weight {
- (16_889_000 as Weight)
+ (10_663_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
- .saturating_add(RocksDbWeight::get().writes(3 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
// Storage: Promotion Admin (r:1 w:0)
// Storage: Common CollectionById (r:1 w:1)
fn sponsor_collection() -> Weight {
- (18_377_000 as Weight)
+ (10_879_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Promotion Admin (r:1 w:0)
// Storage: Common CollectionById (r:1 w:1)
fn stop_sponsoring_collection() -> Weight {
- (13_989_000 as Weight)
+ (10_548_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Promotion Admin (r:1 w:0)
// Storage: EvmContractHelpers Sponsoring (r:0 w:1)
fn sponsor_contract() -> Weight {
- (4_162_000 as Weight)
+ (2_130_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Promotion Admin (r:1 w:0)
// Storage: EvmContractHelpers Sponsoring (r:1 w:1)
fn stop_sponsoring_contract() -> Weight {
- (5_457_000 as Weight)
+ (3_509_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -197,11 +197,11 @@
#[cfg(feature = "app-promotion")]
return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked(staker).unwrap_or_default());
}
-
+
fn total_staked_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {
#[cfg(not(feature = "app-promotion"))]
return unsupported!();
-
+
#[cfg(feature = "app-promotion")]
return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked_per_block(staker));
}
@@ -209,7 +209,7 @@
fn total_staking_locked(staker: CrossAccountId) -> Result<u128, DispatchError> {
#[cfg(not(feature = "app-promotion"))]
return unsupported!();
-
+
#[cfg(feature = "app-promotion")]
return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_locked_balance(staker));
}
@@ -217,7 +217,7 @@
fn pending_unstake(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {
#[cfg(not(feature = "app-promotion"))]
return unsupported!();
-
+
#[cfg(feature = "app-promotion")]
return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake(staker));
}
@@ -225,7 +225,7 @@
fn pending_unstake_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {
#[cfg(not(feature = "app-promotion"))]
return unsupported!();
-
+
#[cfg(feature = "app-promotion")]
return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake_per_block(staker))
}