--- a/client/rpc/src/lib.rs +++ b/client/rpc/src/lib.rs @@ -418,47 +418,27 @@ } } -pub struct Unique { - client: Arc, - _marker: std::marker::PhantomData

, -} - -impl Unique { - pub fn new(client: Arc) -> Self { - Self { - client, - _marker: Default::default(), +macro_rules! define_struct_for_server_api { + ($name:ident) => { + pub struct $name { + client: Arc, + _marker: std::marker::PhantomData

, } - } -} - -pub struct AppPromotion { - client: Arc, - _marker: std::marker::PhantomData

, -} - -impl AppPromotion { - pub fn new(client: Arc) -> Self { - Self { - client, - _marker: Default::default(), + + impl $name { + pub fn new(client: Arc) -> Self { + Self { + client, + _marker: Default::default(), + } + } } - } -} - -pub struct Rmrk { - client: Arc, - _marker: std::marker::PhantomData

, + }; } -impl Rmrk { - pub fn new(client: Arc) -> 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::>(), unique_api); - pass_method!(total_staking_locked(staker: CrossAccountId) -> String => |v| v.to_string(), unique_api); - pass_method!(pending_unstake(staker: Option) -> String => |v| v.to_string(), unique_api); + .collect::>(), app_promotion_api); + pass_method!(total_staking_locked(staker: CrossAccountId) -> String => |v| v.to_string(), app_promotion_api); + pass_method!(pending_unstake(staker: Option) -> 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::>(), unique_api); + .collect::>(), app_promotion_api); } #[allow(deprecated)] --- a/node/rpc/src/lib.rs +++ b/node/rpc/src/lib.rs @@ -38,7 +38,6 @@ use sp_block_builder::BlockBuilder; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; use sc_service::TransactionPool; -use uc_rpc::AppPromotion; use std::{collections::BTreeMap, sync::Arc}; use up_common::types::opaque::{Hash, AccountId, RuntimeInstance, Index, Block, BlockNumber, Balance}; @@ -237,7 +236,7 @@ io.merge(Unique::new(client.clone()).into_rpc())?; - // #[cfg(not(feature = "unique-runtime"))] + #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))] io.merge(AppPromotion::new(client.clone()).into_rpc())?; #[cfg(not(feature = "unique-runtime"))] --- 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)]); }); --- 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 Observable>, []> & QueryableStorageEntry; /** - * 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 Observable>, []> & QueryableStorageEntry; + nextCalculatedRecord: AugmentedQuery Observable>>, []> & QueryableStorageEntry; /** * Next target block when interest is recalculated **/ @@ -530,6 +530,10 @@ **/ staked: AugmentedQuery Observable>, [AccountId32, u32]> & QueryableStorageEntry; /** + * Amount of stakes for an Account + **/ + stakesPerAccount: AugmentedQuery Observable, [AccountId32]> & QueryableStorageEntry; + /** * A block when app-promotion has started .I think this is redundant, because we only need `NextInterestBlock`. **/ startBlock: AugmentedQuery Observable, []> & QueryableStorageEntry;