difftreelog
fix untstake
in: master
4 files changed
client/rpc/src/lib.rsdiffbeforeafterboth418 }418 }419}419}420420421pub struct Unique<C, P> {421macro_rules! define_struct_for_server_api {422 client: Arc<C>,422 ($name:ident) => {423 _marker: std::marker::PhantomData<P>,423 pub struct $name<C, P> {424}424 client: Arc<C>,425425 _marker: std::marker::PhantomData<P>,426 }427 426impl<C, P> Unique<C, P> {428 impl<C, P> $name<C, P> {427 pub fn new(client: Arc<C>) -> Self {429 pub fn new(client: Arc<C>) -> Self {428 Self {430 Self {429 client,431 client,430 _marker: Default::default(),432 _marker: Default::default(),431 }433 }432 }434 }433}435 }434436 };435pub struct AppPromotion<C, P> {437}436 client: Arc<C>,438437 _marker: std::marker::PhantomData<P>,439define_struct_for_server_api!(Unique);438}439440impl<C, P> AppPromotion<C, P> {440define_struct_for_server_api!(AppPromotion);441 pub fn new(client: Arc<C>) -> Self {442 Self {443 client,444 _marker: Default::default(),445 }446 }447}448449pub struct Rmrk<C, P> {450 client: Arc<C>,451 _marker: std::marker::PhantomData<P>,452}453454impl<C, P> Rmrk<C, P> {441define_struct_for_server_api!(Rmrk);455 pub fn new(client: Arc<C>) -> Self {456 Self {457 client,458 _marker: Default::default(),459 }460 }461}462442463macro_rules! pass_method {443macro_rules! pass_method {464 (444 (615 |v| v595 |v| v616 .into_iter()596 .into_iter()617 .map(|(b, a)| (b, a.to_string()))597 .map(|(b, a)| (b, a.to_string()))618 .collect::<Vec<_>>(), unique_api);598 .collect::<Vec<_>>(), app_promotion_api);619 pass_method!(total_staking_locked(staker: CrossAccountId) -> String => |v| v.to_string(), unique_api);599 pass_method!(total_staking_locked(staker: CrossAccountId) -> String => |v| v.to_string(), app_promotion_api);620 pass_method!(pending_unstake(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), unique_api);600 pass_method!(pending_unstake(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), app_promotion_api);621 pass_method!(pending_unstake_per_block(staker: CrossAccountId) -> Vec<(BlockNumber, String)> =>601 pass_method!(pending_unstake_per_block(staker: CrossAccountId) -> Vec<(BlockNumber, String)> =>622 |v| v602 |v| v623 .into_iter()603 .into_iter()624 .map(|(b, a)| (b, a.to_string()))604 .map(|(b, a)| (b, a.to_string()))625 .collect::<Vec<_>>(), unique_api);605 .collect::<Vec<_>>(), app_promotion_api);626}606}627607628#[allow(deprecated)]608#[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.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, []>;