difftreelog
Tests: fix flakyness
in: master
3 files changed
tests/src/app-promotion.test.tsdiffbeforeafterboth--- a/tests/src/app-promotion.test.ts
+++ b/tests/src/app-promotion.test.ts
@@ -37,6 +37,9 @@
let nominal: bigint;
const palletAddress = calculatePalleteAddress('appstake');
let accounts: IKeyringPair[] = [];
+const LOCKING_PERIOD = 20n; // 20 blocks of relay
+const UNLOCKING_PERIOD = 10n; // 20 blocks of parachain
+const rewardAvailableInBlock = (stakedInBlock: bigint) => (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);
before(async function () {
await usingPlaygrounds(async (helper, privateKeyWrapper) => {
@@ -66,7 +69,6 @@
expect (await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});
await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejected;
- expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(100n * nominal);
expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);
expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
// it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo?
@@ -74,7 +76,6 @@
await helper.staking.stake(staker, 200n * nominal);
- expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(300n * nominal);
expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);
expect((await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map((x) => x[1])).to.be.deep.equal([100n * nominal, 200n * nominal]);
});
@@ -83,7 +84,6 @@
it('should allow to create maximum 10 stakes for account', async () => {
await usingPlaygrounds(async (helper) => {
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);
}
@@ -147,14 +147,14 @@
});
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);
await helper.staking.unstake(staker);
+ const unstakedInBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address}))[0][0];
// Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n
- await waitForRelayBlock(helper.api!, 20);
+ await helper.wait.forParachainBlockNumber(unstakedInBlock);
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);
@@ -181,6 +181,7 @@
// Can unstake multiple stakes
await helper.staking.unstake(staker);
+ const unstakingBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address}))[0][0];
pendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
unstakedPerBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).map(stake => stake[1]);
stakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(stake => stake[1]);
@@ -189,7 +190,7 @@
expect(unstakedPerBlock).to.be.deep.equal([600n * nominal]);
expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 600n * nominal, feeFrozen: 0n, miscFrozen: 0n});
- await waitForRelayBlock(helper.api!, 20);
+ await helper.wait.forParachainBlockNumber(unstakingBlock);
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);
});
@@ -202,7 +203,6 @@
// unstake has no effect if no stakes at all
await helper.staking.unstake(staker);
expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);
- expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(0n);
expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper
// TODO stake() unstake() waitUnstaked() unstake();
@@ -213,7 +213,6 @@
await helper.staking.unstake(staker);
expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
- expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(100n * nominal);
expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
});
});
@@ -246,8 +245,6 @@
}));
});
});
-
- // TODO for different accounts in one block is possible
});
describe('Admin adress', () => {
@@ -636,13 +633,16 @@
});
it('should credit 0.05% for staking period', async () => {
- // TODO flaky test
await usingPlaygrounds(async helper => {
const staker = accounts.pop()!;
await helper.staking.stake(staker, 100n * nominal);
await helper.staking.stake(staker, 200n * nominal);
- await waitForRelayBlock(helper.api!, 30);
+
+ // wair rewards are available:
+ const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[1][0];
+ await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock));
+
await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
const totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);
@@ -651,21 +651,20 @@
});
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()!;
await helper.staking.stake(staker, 100n * nominal);
- await helper.staking.stake(staker, 200n * nominal);
+ // wait for two rewards are available:
+ const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[0][0];
+ await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock) + LOCKING_PERIOD);
- await waitForRelayBlock(helper.api!, 55);
await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.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));
+ const frozenBalanceShouldBe = calculateIncome(100n * nominal, 10n, 2);
+ expect(stakedPerBlock[0][1]).to.be.equal(frozenBalanceShouldBe);
const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);
- const frozenBalanceShouldBe = calculateIncome(300n * nominal, 10n, 2);
expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});
});
@@ -673,7 +672,7 @@
it('should not be credited for unstaked (reserved) balance', async () => {
await usingPlaygrounds(async helper => {
- // staker unstakes before rewards has been initialized
+ // staker unstakes before rewards has been payed
const staker = accounts.pop()!;
await helper.staking.stake(staker, 100n * nominal);
await waitForRelayBlock(helper.api!, 40);
@@ -709,6 +708,12 @@
});
});
+ it('can be paid 1000 rewards in a time', async () => {
+ await usingPlaygrounds(async (helper) => {
+ expect.fail('Test not implemented');
+ });
+ });
+
it.skip('can handle 40.000 rewards', async () => {
await usingPlaygrounds(async (helper) => {
const [donor] = await helper.arrange.createAccounts([7_000_000n], alice);
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {mnemonicGenerate} from '@polkadot/util-crypto';5import {UniqueHelper} from './unique';6import {ApiPromise, WsProvider} from '@polkadot/api';7import * as defs from '../../interfaces/definitions';8import {IKeyringPair} from '@polkadot/types/types';91011export class SilentLogger {12 log(_msg: any, _level: any): void { }13 level = {14 ERROR: 'ERROR' as const,15 WARNING: 'WARNING' as const,16 INFO: 'INFO' as const,17 };18}192021export class SilentConsole {22 // TODO: Remove, this is temporary: Filter unneeded API output23 // (Jaco promised it will be removed in the next version)24 consoleErr: any;25 consoleLog: any;26 consoleWarn: any;2728 constructor() {29 this.consoleErr = console.error;30 this.consoleLog = console.log;31 this.consoleWarn = console.warn;32 }3334 enable() { 35 const outFn = (printer: any) => (...args: any[]) => {36 for (const arg of args) {37 if (typeof arg !== 'string')38 continue;39 if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis: UniqueApi/2, RmrkApi/1') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')40 return;41 }42 printer(...args);43 };44 45 console.error = outFn(this.consoleErr.bind(console));46 console.log = outFn(this.consoleLog.bind(console));47 console.warn = outFn(this.consoleWarn.bind(console));48 }4950 disable() {51 console.error = this.consoleErr;52 console.log = this.consoleLog;53 console.warn = this.consoleWarn;54 }55}565758export class DevUniqueHelper extends UniqueHelper {59 /**60 * Arrange methods for tests61 */62 arrange: ArrangeGroup;6364 constructor(logger: { log: (msg: any, level: any) => void, level: any }) {65 super(logger);66 this.arrange = new ArrangeGroup(this);67 }6869 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {70 const wsProvider = new WsProvider(wsEndpoint);71 this.api = new ApiPromise({72 provider: wsProvider,73 signedExtensions: {74 ContractHelpers: {75 extrinsic: {},76 payload: {},77 },78 FakeTransactionFinalizer: {79 extrinsic: {},80 payload: {},81 },82 },83 rpc: {84 unique: defs.unique.rpc,85 appPromotion: defs.appPromotion.rpc,86 rmrk: defs.rmrk.rpc,87 eth: {88 feeHistory: {89 description: 'Dummy',90 params: [],91 type: 'u8',92 },93 maxPriorityFeePerGas: {94 description: 'Dummy',95 params: [],96 type: 'u8',97 },98 },99 },100 });101 await this.api.isReadyOrError;102 this.network = await UniqueHelper.detectNetwork(this.api);103 }104}105106class ArrangeGroup {107 helper: UniqueHelper;108109 constructor(helper: UniqueHelper) {110 this.helper = helper;111 }112113 /**114 * Generates accounts with the specified UNQ token balance 115 * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.116 * @param donor donor account for balances117 * @returns array of newly created accounts118 * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 119 */120 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {121 let nonce = await this.helper.chain.getNonce(donor.address);122 const tokenNominal = this.helper.balance.getOneTokenNominal();123 const transactions = [];124 const accounts: IKeyringPair[] = [];125 for (const balance of balances) {126 const recepient = this.helper.util.fromSeed(mnemonicGenerate());127 accounts.push(recepient);128 if (balance !== 0n) {129 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, balance * tokenNominal]);130 transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));131 nonce++;132 }133 }134135 await Promise.all(transactions).catch(_e => {});136 137 //#region TODO remove this region, when nonce problem will be solved138 const checkBalances = async () => {139 let isSuccess = true;140 for (let i = 0; i < balances.length; i++) {141 const balance = await this.helper.balance.getSubstrate(accounts[i].address);142 if (balance !== balances[i] * tokenNominal) {143 isSuccess = false;144 break;145 }146 }147 return isSuccess;148 };149150 let accountsCreated = false;151 // checkBalances retry up to 5 blocks152 for (let index = 0; index < 5; index++) {153 accountsCreated = await checkBalances();154 if(accountsCreated) break;155 await this.waitNewBlocks(1);156 }157158 if (!accountsCreated) throw Error('Accounts generation failed');159 //#endregion160161 return accounts;162 };163164 // TODO combine this method and createAccounts into one165 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {166 let transactions: any = [];167 const accounts: IKeyringPair[] = [];168169 const createAsManyAsCan = async () => {170 let nonce = await this.helper.chain.getNonce(donor.address);171 const tokenNominal = this.helper.balance.getOneTokenNominal();172 for (let i = 0; i < accountsToCreate; i++) {173 if (i === 500) { // if there are too many accounts to create174 await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 175 transactions = []; //176 nonce = await this.helper.chain.getNonce(donor.address); // update nonce 177 }178 const recepient = this.helper.util.fromSeed(mnemonicGenerate());179 accounts.push(recepient);180 if (withBalance !== 0n) {181 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);182 transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));183 nonce++;184 }185 }186 187 const fullfilledAccounts = [];188 await Promise.allSettled(transactions);189 for (const account of accounts) {190 const accountBalance = await this.helper.balance.getSubstrate(account.address);191 if (accountBalance === withBalance * tokenNominal) {192 fullfilledAccounts.push(account);193 }194 }195 return fullfilledAccounts;196 };197198 199 const crowd: IKeyringPair[] = [];200 // do up to 5 retries201 for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {202 const asManyAsCan = await createAsManyAsCan();203 crowd.push(...asManyAsCan);204 accountsToCreate -= asManyAsCan.length;205 }206207 if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);208209 return crowd;210 };211212 isDevNode = async () => {213 const block1 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(1));214 const block2 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(2));215 const findCreationDate = async (block: any) => {216 const humanBlock = block.toHuman();217 let date;218 humanBlock.block.extrinsics.forEach((ext: any) => {219 if(ext.method.section === 'timestamp') {220 date = Number(ext.method.args.now.replaceAll(',', ''));221 }222 });223 return date;224 };225 const block1date = await findCreationDate(block1);226 const block2date = await findCreationDate(block2);227 if(block2date! - block1date! < 9000) return true;228 };229230 /**231 * Wait for specified bnumber of blocks232 * @param blocksCount number of blocks to wait233 * @returns 234 */235 async waitNewBlocks(blocksCount = 1): Promise<void> {236 // eslint-disable-next-line no-async-promise-executor237 const promise = new Promise<void>(async (resolve) => {238 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {239 if (blocksCount > 0) {240 blocksCount--;241 } else {242 unsubscribe();243 resolve();244 }245 });246 });247 return promise;248 }249}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {mnemonicGenerate} from '@polkadot/util-crypto';5import {UniqueHelper} from './unique';6import {ApiPromise, WsProvider} from '@polkadot/api';7import * as defs from '../../interfaces/definitions';8import {IKeyringPair} from '@polkadot/types/types';91011export class SilentLogger {12 log(_msg: any, _level: any): void { }13 level = {14 ERROR: 'ERROR' as const,15 WARNING: 'WARNING' as const,16 INFO: 'INFO' as const,17 };18}1920export class SilentConsole {21 // TODO: Remove, this is temporary: Filter unneeded API output22 // (Jaco promised it will be removed in the next version)23 consoleErr: any;24 consoleLog: any;25 consoleWarn: any;2627 constructor() {28 this.consoleErr = console.error;29 this.consoleLog = console.log;30 this.consoleWarn = console.warn;31 }3233 enable() { 34 const outFn = (printer: any) => (...args: any[]) => {35 for (const arg of args) {36 if (typeof arg !== 'string')37 continue;38 if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis: UniqueApi/2, RmrkApi/1') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')39 return;40 }41 printer(...args);42 };43 44 console.error = outFn(this.consoleErr.bind(console));45 console.log = outFn(this.consoleLog.bind(console));46 console.warn = outFn(this.consoleWarn.bind(console));47 }4849 disable() {50 console.error = this.consoleErr;51 console.log = this.consoleLog;52 console.warn = this.consoleWarn;53 }54}555657export class DevUniqueHelper extends UniqueHelper {58 /**59 * Arrange methods for tests60 */61 arrange: ArrangeGroup;62 wait: WaitGroup;6364 constructor(logger: { log: (msg: any, level: any) => void, level: any }) {65 super(logger);66 this.arrange = new ArrangeGroup(this);67 this.wait = new WaitGroup(this);68 }6970 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {71 const wsProvider = new WsProvider(wsEndpoint);72 this.api = new ApiPromise({73 provider: wsProvider,74 signedExtensions: {75 ContractHelpers: {76 extrinsic: {},77 payload: {},78 },79 FakeTransactionFinalizer: {80 extrinsic: {},81 payload: {},82 },83 },84 rpc: {85 unique: defs.unique.rpc,86 appPromotion: defs.appPromotion.rpc,87 rmrk: defs.rmrk.rpc,88 eth: {89 feeHistory: {90 description: 'Dummy',91 params: [],92 type: 'u8',93 },94 maxPriorityFeePerGas: {95 description: 'Dummy',96 params: [],97 type: 'u8',98 },99 },100 },101 });102 await this.api.isReadyOrError;103 this.network = await UniqueHelper.detectNetwork(this.api);104 }105}106107class ArrangeGroup {108 helper: UniqueHelper;109110 constructor(helper: UniqueHelper) {111 this.helper = helper;112 }113114 /**115 * Generates accounts with the specified UNQ token balance 116 * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.117 * @param donor donor account for balances118 * @returns array of newly created accounts119 * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 120 */121 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {122 let nonce = await this.helper.chain.getNonce(donor.address);123 const tokenNominal = this.helper.balance.getOneTokenNominal();124 const transactions = [];125 const accounts: IKeyringPair[] = [];126 for (const balance of balances) {127 const recepient = this.helper.util.fromSeed(mnemonicGenerate());128 accounts.push(recepient);129 if (balance !== 0n) {130 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, balance * tokenNominal]);131 transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));132 nonce++;133 }134 }135136 await Promise.all(transactions).catch(_e => {});137 138 //#region TODO remove this region, when nonce problem will be solved139 const checkBalances = async () => {140 let isSuccess = true;141 for (let i = 0; i < balances.length; i++) {142 const balance = await this.helper.balance.getSubstrate(accounts[i].address);143 if (balance !== balances[i] * tokenNominal) {144 isSuccess = false;145 break;146 }147 }148 return isSuccess;149 };150151 let accountsCreated = false;152 // checkBalances retry up to 5 blocks153 for (let index = 0; index < 5; index++) {154 accountsCreated = await checkBalances();155 if(accountsCreated) break;156 157 }158159 if (!accountsCreated) throw Error('Accounts generation failed');160 //#endregion161162 return accounts;163 };164165 // TODO combine this method and createAccounts into one166 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => { 167 const createAsManyAsCan = async () => {168 let transactions: any = [];169 const accounts: IKeyringPair[] = [];170 let nonce = await this.helper.chain.getNonce(donor.address);171 const tokenNominal = this.helper.balance.getOneTokenNominal();172 for (let i = 0; i < accountsToCreate; i++) {173 if (i === 500) { // if there are too many accounts to create174 await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 175 transactions = []; //176 nonce = await this.helper.chain.getNonce(donor.address); // update nonce 177 }178 const recepient = this.helper.util.fromSeed(mnemonicGenerate());179 accounts.push(recepient);180 if (withBalance !== 0n) {181 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);182 transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));183 nonce++;184 }185 }186 187 const fullfilledAccounts = [];188 await Promise.allSettled(transactions);189 for (const account of accounts) {190 const accountBalance = await this.helper.balance.getSubstrate(account.address);191 if (accountBalance === withBalance * tokenNominal) {192 fullfilledAccounts.push(account);193 }194 }195 return fullfilledAccounts;196 };197198 199 const crowd: IKeyringPair[] = [];200 // do up to 5 retries201 for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {202 const asManyAsCan = await createAsManyAsCan();203 crowd.push(...asManyAsCan);204 accountsToCreate -= asManyAsCan.length;205 }206207 if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);208209 return crowd;210 };211212 isDevNode = async () => {213 const block1 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(1));214 const block2 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(2));215 const findCreationDate = async (block: any) => {216 const humanBlock = block.toHuman();217 let date;218 humanBlock.block.extrinsics.forEach((ext: any) => {219 if(ext.method.section === 'timestamp') {220 date = Number(ext.method.args.now.replaceAll(',', ''));221 }222 });223 return date;224 };225 const block1date = await findCreationDate(block1);226 const block2date = await findCreationDate(block2);227 if(block2date! - block1date! < 9000) return true;228 };229}230231class WaitGroup {232 helper: UniqueHelper;233234 constructor(helper: UniqueHelper) {235 this.helper = helper;236 }237238 /**239 * Wait for specified bnumber of blocks240 * @param blocksCount number of blocks to wait241 * @returns 242 */243 async newBlocks(blocksCount = 1): Promise<void> {244 // eslint-disable-next-line no-async-promise-executor245 const promise = new Promise<void>(async (resolve) => {246 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {247 if (blocksCount > 0) {248 blocksCount--;249 } else {250 unsubscribe();251 resolve();252 }253 });254 });255 return promise;256 }257258 async forParachainBlockNumber(blockNumber: bigint) {259 return new Promise<void>(async (resolve) => {260 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(async (data: any) => {261 if (data.number.toNumber() >= blockNumber) {262 unsubscribe();263 resolve();264 }265 });266 });267 }268 269 async forRelayBlockNumber(blockNumber: bigint) {270 return new Promise<void>(async (resolve) => {271 const unsubscribe = await this.helper.api!.query.parachainSystem.validationData(async (data: any) => {272 if (data.value.relayParentNumber.toNumber() >= blockNumber) {273 unsubscribe();274 resolve();275 }276 });277 });278 }279}tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -1980,16 +1980,16 @@
* @param signer keyring of signer
* @param amountToUnstake amount of tokens to unstake
* @param label extra label for log
- * @returns
+ * @returns block number where balances will be unlocked
*/
- async unstake(signer: TSigner, label?: string): Promise<boolean> {
+ async unstake(signer: TSigner, label?: string): Promise<number> {
if(typeof label === 'undefined') label = `${signer.address}`;
const unstakeResult = await this.helper.executeExtrinsic(
signer, 'api.tx.appPromotion.unstake',
[], true,
);
- // TODO extract info from unstakeResult
- return true;
+ // TODO extract block number fron events
+ return 1;
}
async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {
@@ -1997,10 +1997,6 @@
return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();
}
- async getTotalStakingLocked(address: ICrossAccountId): Promise<bigint> {
- return (await this.helper.callRpc('api.rpc.appPromotion.totalStakingLocked', [address])).toBigInt();
- }
-
async getTotalStakedPerBlock(address: ICrossAccountId): Promise<bigint[][]> {
return (await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);
}
@@ -2447,4 +2443,4 @@
async burn(signer: TSigner, amount=1n) {
return await this.collection.burnToken(signer, this.tokenId, amount);
}
-}
\ No newline at end of file
+}