difftreelog
fix untstake
in: master
4 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -418,47 +418,27 @@
}
}
-pub struct Unique<C, P> {
- client: Arc<C>,
- _marker: std::marker::PhantomData<P>,
-}
-
-impl<C, P> Unique<C, P> {
- pub fn new(client: Arc<C>) -> Self {
- Self {
- client,
- _marker: Default::default(),
+macro_rules! define_struct_for_server_api {
+ ($name:ident) => {
+ pub struct $name<C, P> {
+ client: Arc<C>,
+ _marker: std::marker::PhantomData<P>,
}
- }
-}
-
-pub struct AppPromotion<C, P> {
- client: Arc<C>,
- _marker: std::marker::PhantomData<P>,
-}
-
-impl<C, P> AppPromotion<C, P> {
- pub fn new(client: Arc<C>) -> Self {
- Self {
- client,
- _marker: Default::default(),
+
+ impl<C, P> $name<C, P> {
+ pub fn new(client: Arc<C>) -> Self {
+ Self {
+ client,
+ _marker: Default::default(),
+ }
+ }
}
- }
-}
-
-pub struct Rmrk<C, P> {
- client: Arc<C>,
- _marker: std::marker::PhantomData<P>,
+ };
}
-impl<C, P> Rmrk<C, P> {
- pub fn new(client: Arc<C>) -> Self {
- Self {
- client,
- _marker: Default::default(),
- }
- }
-}
+define_struct_for_server_api!(Unique);
+define_struct_for_server_api!(AppPromotion);
+define_struct_for_server_api!(Rmrk);
macro_rules! pass_method {
(
@@ -615,14 +595,14 @@
|v| v
.into_iter()
.map(|(b, a)| (b, a.to_string()))
- .collect::<Vec<_>>(), unique_api);
- pass_method!(total_staking_locked(staker: CrossAccountId) -> String => |v| v.to_string(), unique_api);
- pass_method!(pending_unstake(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), unique_api);
+ .collect::<Vec<_>>(), app_promotion_api);
+ pass_method!(total_staking_locked(staker: CrossAccountId) -> String => |v| v.to_string(), app_promotion_api);
+ pass_method!(pending_unstake(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), app_promotion_api);
pass_method!(pending_unstake_per_block(staker: CrossAccountId) -> Vec<(BlockNumber, String)> =>
|v| v
.into_iter()
.map(|(b, a)| (b, a.to_string()))
- .collect::<Vec<_>>(), unique_api);
+ .collect::<Vec<_>>(), app_promotion_api);
}
#[allow(deprecated)]
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 uc_rpc::AppPromotion;42use std::{collections::BTreeMap, sync::Arc};4344use up_common::types::opaque::{Hash, AccountId, RuntimeInstance, Index, Block, BlockNumber, Balance};4546// RMRK47use up_data_structs::{48 RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,49 RmrkPartType, RmrkTheme,50};5152/// Extra dependencies for GRANDPA53pub struct GrandpaDeps<B> {54 /// Voting round info.55 pub shared_voter_state: SharedVoterState,56 /// Authority set info.57 pub shared_authority_set: SharedAuthoritySet<Hash, BlockNumber>,58 /// Receives notifications about justification events from Grandpa.59 pub justification_stream: GrandpaJustificationStream<Block>,60 /// Executor to drive the subscription manager in the Grandpa RPC handler.61 pub subscription_executor: SubscriptionTaskExecutor,62 /// Finality proof provider.63 pub finality_provider: Arc<FinalityProofProvider<B, Block>>,64}6566/// Full client dependencies.67pub struct FullDeps<C, P, SC, CA: ChainApi> {68 /// The client instance to use.69 pub client: Arc<C>,70 /// Transaction pool instance.71 pub pool: Arc<P>,72 /// Graph pool instance.73 pub graph: Arc<Pool<CA>>,74 /// The SelectChain Strategy75 pub select_chain: SC,76 /// The Node authority flag77 pub is_authority: bool,78 /// Whether to enable dev signer79 pub enable_dev_signer: bool,80 /// Network service81 pub network: Arc<NetworkService<Block, Hash>>,82 /// Whether to deny unsafe calls83 pub deny_unsafe: DenyUnsafe,84 /// EthFilterApi pool.85 pub filter_pool: Option<FilterPool>,86 /// Backend.87 pub backend: Arc<fc_db::Backend<Block>>,88 /// Maximum number of logs in a query.89 pub max_past_logs: u32,90 /// Maximum fee history cache size.91 pub fee_history_limit: u64,92 /// Fee history cache.93 pub fee_history_cache: FeeHistoryCache,94 /// Cache for Ethereum block data.95 pub block_data_cache: Arc<EthBlockDataCacheTask<Block>>,96}9798pub fn overrides_handle<C, BE, R>(client: Arc<C>) -> Arc<OverrideHandle<Block>>99where100 C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,101 C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,102 C: Send + Sync + 'static,103 C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,104 C::Api:105 up_rpc::UniqueApi<Block, BlockNumber, <R as RuntimeInstance>::CrossAccountId, AccountId>,106 BE: Backend<Block> + 'static,107 BE::State: StateBackend<BlakeTwo256>,108 R: RuntimeInstance + Send + Sync + 'static,109{110 let mut overrides_map = BTreeMap::new();111 overrides_map.insert(112 EthereumStorageSchema::V1,113 Box::new(SchemaV1Override::new(client.clone()))114 as Box<dyn StorageOverride<_> + Send + Sync>,115 );116 overrides_map.insert(117 EthereumStorageSchema::V2,118 Box::new(SchemaV2Override::new(client.clone()))119 as Box<dyn StorageOverride<_> + Send + Sync>,120 );121 overrides_map.insert(122 EthereumStorageSchema::V3,123 Box::new(SchemaV3Override::new(client.clone()))124 as Box<dyn StorageOverride<_> + Send + Sync>,125 );126127 Arc::new(OverrideHandle {128 schemas: overrides_map,129 fallback: Box::new(RuntimeApiStorageOverride::new(client)),130 })131}132133/// Instantiate all Full RPC extensions.134pub fn create_full<C, P, SC, CA, R, A, B>(135 deps: FullDeps<C, P, SC, CA>,136 subscription_task_executor: SubscriptionTaskExecutor,137) -> Result<RpcModule<()>, Box<dyn std::error::Error + Send + Sync>>138where139 C: ProvideRuntimeApi<Block> + StorageProvider<Block, B> + AuxStore,140 C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,141 C: Send + Sync + 'static,142 C: BlockchainEvents<Block>,143 C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,144 C::Api: BlockBuilder<Block>,145 // C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,146 C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,147 C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,148 C::Api: fp_rpc::ConvertTransactionRuntimeApi<Block>,149 C::Api:150 up_rpc::UniqueApi<Block, BlockNumber, <R as RuntimeInstance>::CrossAccountId, AccountId>,151 C::Api: app_promotion_rpc::AppPromotionApi<152 Block,153 BlockNumber,154 <R as RuntimeInstance>::CrossAccountId,155 AccountId,156 >,157 C::Api: rmrk_rpc::RmrkApi<158 Block,159 AccountId,160 RmrkCollectionInfo<AccountId>,161 RmrkInstanceInfo<AccountId>,162 RmrkResourceInfo,163 RmrkPropertyInfo,164 RmrkBaseInfo<AccountId>,165 RmrkPartType,166 RmrkTheme,167 >,168 B: sc_client_api::Backend<Block> + Send + Sync + 'static,169 B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,170 P: TransactionPool<Block = Block> + 'static,171 CA: ChainApi<Block = Block> + 'static,172 R: RuntimeInstance + Send + Sync + 'static,173 <R as RuntimeInstance>::CrossAccountId: serde::Serialize,174 for<'de> <R as RuntimeInstance>::CrossAccountId: serde::Deserialize<'de>,175{176 use fc_rpc::{177 Eth, EthApiServer, EthDevSigner, EthFilter, EthFilterApiServer, EthPubSub,178 EthPubSubApiServer, EthSigner, Net, NetApiServer, Web3, Web3ApiServer,179 };180 use uc_rpc::{UniqueApiServer, Unique};181 use uc_rpc::{AppPromotionApiServer, AppPromotion};182183 #[cfg(not(feature = "unique-runtime"))]184 use uc_rpc::{RmrkApiServer, Rmrk};185186 // use pallet_contracts_rpc::{Contracts, ContractsApi};187 use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};188 use substrate_frame_rpc_system::{System, SystemApiServer};189190 let mut io = RpcModule::new(());191 let FullDeps {192 client,193 pool,194 graph,195 select_chain: _,196 fee_history_limit,197 fee_history_cache,198 block_data_cache,199 enable_dev_signer,200 is_authority,201 network,202 deny_unsafe,203 filter_pool,204 backend,205 max_past_logs,206 } = deps;207208 io.merge(System::new(Arc::clone(&client), Arc::clone(&pool), deny_unsafe).into_rpc())?;209 io.merge(TransactionPayment::new(Arc::clone(&client)).into_rpc())?;210211 // io.extend_with(ContractsApi::to_delegate(Contracts::new(client.clone())));212213 let mut signers = Vec::new();214 if enable_dev_signer {215 signers.push(Box::new(EthDevSigner::new()) as Box<dyn EthSigner>);216 }217218 let overrides = overrides_handle::<_, _, R>(client.clone());219220 io.merge(221 Eth::new(222 client.clone(),223 pool.clone(),224 graph,225 Some(<R as RuntimeInstance>::get_transaction_converter()),226 network.clone(),227 signers,228 overrides.clone(),229 backend.clone(),230 is_authority,231 block_data_cache.clone(),232 fee_history_cache,233 fee_history_limit,234 )235 .into_rpc(),236 )?;237238 io.merge(Unique::new(client.clone()).into_rpc())?;239240 // #[cfg(not(feature = "unique-runtime"))]241 io.merge(AppPromotion::new(client.clone()).into_rpc())?;242243 #[cfg(not(feature = "unique-runtime"))]244 io.merge(Rmrk::new(client.clone()).into_rpc())?;245246 if let Some(filter_pool) = filter_pool {247 io.merge(248 EthFilter::new(249 client.clone(),250 backend,251 filter_pool,252 500_usize, // max stored filters253 max_past_logs,254 block_data_cache,255 )256 .into_rpc(),257 )?;258 }259260 io.merge(261 Net::new(262 client.clone(),263 network.clone(),264 // Whether to format the `peer_count` response as Hex (default) or not.265 true,266 )267 .into_rpc(),268 )?;269270 io.merge(Web3::new(client.clone()).into_rpc())?;271272 io.merge(273 EthPubSub::new(pool, client, network, subscription_task_executor, overrides).into_rpc(),274 )?;275276 Ok(io)277}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}tests/src/app-promotion.test.tsdiffbeforeafterboth--- a/tests/src/app-promotion.test.ts
+++ b/tests/src/app-promotion.test.ts
@@ -35,7 +35,6 @@
let alice: IKeyringPair;
let palletAdmin: IKeyringPair;
let nominal: bigint;
-let promotionStartBlock: number | null = null;
const palletAddress = calculatePalleteAddress('appstake');
let accounts: IKeyringPair[] = [];
@@ -51,6 +50,7 @@
if (!promotionStartBlock) {
promotionStartBlock = (await helper.api!.query.parachainSystem.lastRelayChainBlockNumber()).toNumber();
}
+ await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.startAppPromotion(promotionStartBlock!)));
accounts = await helper.arrange.createCrowd(100, 1000n, alice); // create accounts-pool to speed up tests
});
});
@@ -89,16 +89,24 @@
});
});
- it('should allow to stake with nonce', async () => {
+ it('should allow to create maximum 10 stakes for account', async () => {
await usingPlaygrounds(async (helper) => {
- const staker = accounts.pop()!;
- const transactions = [];
- for (let nonce = 0; nonce < 9; nonce++) {
- transactions.push(helper.signTransaction(staker, helper.api?.tx.promotion.stake(100n * nominal), 'Staker stakes with nonce', {nonce}));
+ const [staker] = await helper.arrange.createAccounts([2000n], alice);
+ console.log(staker.address);
+ for (let i = 0; i < 10; i++) {
+ await helper.staking.stake(staker, 100n * nominal);
}
- await Promise.allSettled(transactions);
- expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(900n * nominal);
+ // can have 10 stakes
+ expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);
+ expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);
+
+ await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejected;
+
+ // After unstake can stake again
+ await helper.staking.unstake(staker);
+ await helper.staking.stake(staker, 100n * nominal);
+ expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);
});
});
@@ -127,10 +135,6 @@
expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);
});
});
-
- it('should allow to create maximum 10 stakes for account', async () => {
-
- });
});
describe('unstake balance extrinsic', () => {
@@ -151,7 +155,8 @@
});
});
- it('should unlock balance after unlocking period ends and subtract it from "pendingUnstake"', async () => {
+ it('should unlock balance after unlocking period ends and remove it from "pendingUnstake"', async () => {
+ // TODO Flaky test
await usingPlaygrounds(async (helper) => {
const staker = accounts.pop()!;
await helper.staking.stake(staker, 100n * nominal);
@@ -159,7 +164,7 @@
// Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n
await waitForRelayBlock(helper.api!, 20);
- expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n * nominal, miscFrozen: 0n, feeFrozen: 0n});
+ expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});
expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
// staker can transfer:
@@ -192,7 +197,7 @@
expect(stakedPerBlock).to.be.deep.equal([]);
expect(unstakedPerBlock).to.be.deep.equal([600n * nominal]);
- expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 600n * nominal, miscFrozen: 600n * nominal});
+ expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 600n * nominal, feeFrozen: 0n, miscFrozen: 0n});
await waitForRelayBlock(helper.api!, 20);
expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});
expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
@@ -635,7 +640,7 @@
it('can not be called by non admin', async () => {
await usingPlaygrounds(async (helper) => {
const nonAdmin = accounts.pop()!;
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.payoutStakers(50))).to.be.rejected;
+ await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.payoutStakers(100))).to.be.rejected;
});
});
@@ -647,7 +652,7 @@
await helper.staking.stake(staker, 100n * nominal);
await helper.staking.stake(staker, 200n * nominal);
await waitForRelayBlock(helper.api!, 30);
- await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));
+ await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(100));
const totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);
expect(totalStakedPerBlock).to.be.deep.equal([calculateIncome(100n * nominal, 10n), calculateIncome(200n * nominal, 10n)]);
@@ -655,6 +660,7 @@
});
it('shoud be paid for more than one period if payments was missed', async () => {
+ // TODO flaky test
await usingPlaygrounds(async (helper) => {
const staker = accounts.pop()!;
@@ -662,7 +668,7 @@
await helper.staking.stake(staker, 200n * nominal);
await waitForRelayBlock(helper.api!, 55);
- await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));
+ await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(100));
const stakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
expect(stakedPerBlock[0][1]).to.be.equal(calculateIncome(100n * nominal, 10n, 2));
expect(stakedPerBlock[1][1]).to.be.equal(calculateIncome(200n * nominal, 10n, 2));
@@ -675,9 +681,19 @@
});
it('should not be credited for unstaked (reserved) balance', async () => {
- expect.fail('Test not implemented');
await usingPlaygrounds(async helper => {
+ // staker unstakes before rewards has been initialized
const staker = accounts.pop()!;
+ await helper.staking.stake(staker, 100n * nominal);
+ await waitForRelayBlock(helper.api!, 40);
+ await helper.staking.unstake(staker);
+
+ // so he did not receive any rewards
+ const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);
+ await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(100));
+ const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);
+
+ expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);
});
});
@@ -691,12 +707,12 @@
await helper.staking.stake(staker, 300n * nominal);
await waitForRelayBlock(helper.api!, 34);
- await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));
+ await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(100));
let totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);
expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n), calculateIncome(200n * nominal, 10n), calculateIncome(300n * nominal, 10n)]);
await waitForRelayBlock(helper.api!, 20);
- await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));
+ await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(100));
totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);
expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n, 2), calculateIncome(200n * nominal, 10n, 2), calculateIncome(300n * nominal, 10n, 2)]);
});
tests/src/interfaces/augment-api-query.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-query.ts
+++ b/tests/src/interfaces/augment-api-query.ts
@@ -6,7 +6,7 @@
import '@polkadot/api-base/types/storage';
import type { ApiTypes, AugmentedQuery, QueryableStorageEntry } from '@polkadot/api-base/types';
-import type { BTreeMap, Bytes, Option, U256, U8aFixed, Vec, bool, u128, u16, u32, u64 } from '@polkadot/types-codec';
+import type { BTreeMap, Bytes, Option, U256, U8aFixed, Vec, bool, u128, u16, u32, u64, u8 } from '@polkadot/types-codec';
import type { AnyNumber, ITuple } from '@polkadot/types-codec/types';
import type { AccountId32, H160, H256 } from '@polkadot/types/interfaces/runtime';
import type { CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmpQueueInboundChannelDetails, CumulusPalletXcmpQueueOutboundChannelDetails, CumulusPalletXcmpQueueQueueConfigData, EthereumBlock, EthereumLog, EthereumReceiptReceiptV3, EthereumTransactionTransactionV2, FpRpcTransactionStatus, FrameSupportWeightsPerDispatchClassU64, FrameSystemAccountInfo, FrameSystemEventRecord, FrameSystemLastRuntimeUpgradeInfo, FrameSystemPhase, OrmlVestingVestingSchedule, PalletBalancesAccountData, PalletBalancesBalanceLock, PalletBalancesReleases, PalletBalancesReserveData, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmContractHelpersSponsoringModeT, PalletNonfungibleItemData, PalletRefungibleItemData, PalletTransactionPaymentReleases, PalletTreasuryProposal, PalletUniqueSchedulerScheduledV3, PhantomTypeUpDataStructs, PolkadotCorePrimitivesOutboundHrmpMessage, PolkadotPrimitivesV2AbridgedHostConfiguration, PolkadotPrimitivesV2PersistedValidationData, PolkadotPrimitivesV2UpgradeRestriction, SpRuntimeDigest, SpTrieStorageProof, UpDataStructsCollection, UpDataStructsCollectionStats, UpDataStructsProperties, UpDataStructsPropertiesMapPropertyPermission, UpDataStructsPropertyPermission, UpDataStructsPropertyScope, UpDataStructsSponsorshipStateBasicCrossAccountIdRepr, UpDataStructsTokenChild } from '@polkadot/types/lookup';
@@ -513,10 +513,10 @@
promotion: {
admin: AugmentedQuery<ApiType, () => Observable<Option<AccountId32>>, []> & QueryableStorageEntry<ApiType, []>;
/**
- * Stores the address of the staker for which the last revenue recalculation was performed.
+ * 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.
**/
- lastCalcucaltedStaker: AugmentedQuery<ApiType, () => Observable<Option<AccountId32>>, []> & QueryableStorageEntry<ApiType, []>;
+ nextCalculatedRecord: AugmentedQuery<ApiType, () => Observable<Option<ITuple<[AccountId32, u32]>>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Next target block when interest is recalculated
**/
@@ -530,6 +530,10 @@
**/
staked: AugmentedQuery<ApiType, (arg1: AccountId32 | string | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<ITuple<[u128, u32]>>, [AccountId32, u32]> & QueryableStorageEntry<ApiType, [AccountId32, u32]>;
/**
+ * Amount of stakes for an Account
+ **/
+ stakesPerAccount: AugmentedQuery<ApiType, (arg: AccountId32 | string | Uint8Array) => Observable<u8>, [AccountId32]> & QueryableStorageEntry<ApiType, [AccountId32]>;
+ /**
* A block when app-promotion has started .I think this is redundant, because we only need `NextInterestBlock`.
**/
startBlock: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;