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.rsdiffbeforeafterboth--- 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"))]
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.tsdiffbeforeafterboth6import '@polkadot/api-base/types/storage';6import '@polkadot/api-base/types/storage';778import type { ApiTypes, AugmentedQuery, QueryableStorageEntry } from '@polkadot/api-base/types';8import type { ApiTypes, AugmentedQuery, QueryableStorageEntry } from '@polkadot/api-base/types';9import type { BTreeMap, Bytes, Option, U256, U8aFixed, Vec, bool, u128, u16, u32, u64 } from '@polkadot/types-codec';9import type { BTreeMap, Bytes, Option, U256, U8aFixed, Vec, bool, u128, u16, u32, u64, u8 } from '@polkadot/types-codec';10import type { AnyNumber, ITuple } from '@polkadot/types-codec/types';10import type { AnyNumber, ITuple } from '@polkadot/types-codec/types';11import type { AccountId32, H160, H256 } from '@polkadot/types/interfaces/runtime';11import type { AccountId32, H160, H256 } from '@polkadot/types/interfaces/runtime';12import 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';12import 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';512 };512 };513 promotion: {513 promotion: {514 admin: AugmentedQuery<ApiType, () => Observable<Option<AccountId32>>, []> & QueryableStorageEntry<ApiType, []>;514 admin: AugmentedQuery<ApiType, () => Observable<Option<AccountId32>>, []> & QueryableStorageEntry<ApiType, []>;515 /**515 /**516 * Stores the address of the staker for which the last revenue recalculation was performed.516 * Stores hash a record for which the last revenue recalculation was performed.517 * If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.517 * If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.518 **/518 **/519 lastCalcucaltedStaker: AugmentedQuery<ApiType, () => Observable<Option<AccountId32>>, []> & QueryableStorageEntry<ApiType, []>;519 nextCalculatedRecord: AugmentedQuery<ApiType, () => Observable<Option<ITuple<[AccountId32, u32]>>>, []> & QueryableStorageEntry<ApiType, []>;520 /**520 /**521 * Next target block when interest is recalculated521 * Next target block when interest is recalculated522 **/522 **/529 * Amount of tokens staked by account in the blocknumber.529 * Amount of tokens staked by account in the blocknumber.530 **/530 **/531 staked: AugmentedQuery<ApiType, (arg1: AccountId32 | string | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<ITuple<[u128, u32]>>, [AccountId32, u32]> & QueryableStorageEntry<ApiType, [AccountId32, u32]>;531 staked: AugmentedQuery<ApiType, (arg1: AccountId32 | string | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<ITuple<[u128, u32]>>, [AccountId32, u32]> & QueryableStorageEntry<ApiType, [AccountId32, u32]>;532 /**533 * Amount of stakes for an Account534 **/535 stakesPerAccount: AugmentedQuery<ApiType, (arg: AccountId32 | string | Uint8Array) => Observable<u8>, [AccountId32]> & QueryableStorageEntry<ApiType, [AccountId32]>;532 /**536 /**533 * A block when app-promotion has started .I think this is redundant, because we only need `NextInterestBlock`.537 * A block when app-promotion has started .I think this is redundant, because we only need `NextInterestBlock`.534 **/538 **/