difftreelog
Fix test: fix create accounts script for devnode
in: master
- add waiter for create accounts script - wrap promotion tests in global describe to avoid accounts creation for each describe
2 files changed
tests/src/app-promotion.test.tsdiffbeforeafterboth--- a/tests/src/app-promotion.test.ts
+++ b/tests/src/app-promotion.test.ts
@@ -36,691 +36,664 @@
const UNLOCKING_PERIOD = 10n; // 10 blocks of parachain
const rewardAvailableInBlock = (stakedInBlock: bigint) => (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);
-const beforeEach = async (context: Mocha.Context) => {
- await usingPlaygrounds(async (helper, privateKey) => {
- if (!getModuleNames(helper.api!).includes(Pallets.AppPromotion)) context.skip();
- alice = privateKey('//Alice');
- palletAdmin = privateKey('//Charlie'); // TODO use custom address
- await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
- nominal = helper.balance.getOneTokenNominal();
- await helper.balance.transferToSubstrate(alice, palletAdmin.address, 1000n * nominal);
- await helper.balance.transferToSubstrate(alice, palletAddress, 1000n * nominal);
- accounts = await helper.arrange.createCrowd(100, 1000n, alice); // create accounts-pool to speed up tests
- });
-};
-
-describe('app-promotions.stake extrinsic', () => {
+describe('App promotion', () => {
before(async function () {
- await beforeEach(this);
+ await usingPlaygrounds(async (helper, privateKey) => {
+ if (!getModuleNames(helper.api!).includes(Pallets.AppPromotion)) this.skip();
+ alice = privateKey('//Alice');
+ palletAdmin = privateKey('//Charlie'); // TODO use custom address
+ await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
+ nominal = helper.balance.getOneTokenNominal();
+ await helper.balance.transferToSubstrate(alice, palletAdmin.address, 1000n * nominal);
+ await helper.balance.transferToSubstrate(alice, palletAddress, 1000n * nominal);
+ accounts = await helper.arrange.createCrowd(100, 1000n, alice); // create accounts-pool to speed up tests
+ });
});
- itSub('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {
- const [staker, recepient] = [accounts.pop()!, accounts.pop()!];
- const totalStakedBefore = await helper.staking.getTotalStaked();
-
- // Minimum stake amount is 100:
- await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;
- await helper.staking.stake(staker, 100n * nominal);
-
- // Staker balance is: miscFrozen: 100, feeFrozen: 100, reserved: 0n...
- // ...so he can not transfer 900
- 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.rejectedWith('balances.LiquidityRestrictions');
+ describe('stake extrinsic', () => {
+ itSub('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {
+ const [staker, recepient] = [accounts.pop()!, accounts.pop()!];
+ const totalStakedBefore = await helper.staking.getTotalStaked();
+
+ // Minimum stake amount is 100:
+ await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;
+ await helper.staking.stake(staker, 100n * nominal);
+
+ // Staker balance is: miscFrozen: 100, feeFrozen: 100, reserved: 0n...
+ // ...so he can not transfer 900
+ 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.rejectedWith('balances.LiquidityRestrictions');
+
+ 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?
+ expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased
+
+
+ await helper.staking.stake(staker, 200n * nominal);
+ expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);
+ const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ expect(totalStakedPerBlock[0].amount).to.equal(100n * nominal);
+ expect(totalStakedPerBlock[1].amount).to.equal(200n * nominal);
+ });
+
+ itSub('should allow to create maximum 10 stakes for account', async ({helper}) => {
+ const [staker] = await helper.arrange.createAccounts([2000n], alice);
+ for (let i = 0; i < 10; i++) {
+ await helper.staking.stake(staker, 100n * 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.rejectedWith('appPromotion.NoPermission');
+
+ // 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);
+ });
- 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?
- expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased
-
+ itSub('should reject transaction if stake amount is more than total free balance minus frozen', async ({helper}) => {
+ const staker = accounts.pop()!;
+
+ // Can't stake full balance because Alice needs to pay some fee
+ await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected;
+ await helper.staking.stake(staker, 500n * nominal);
+
+ // Can't stake 500 tkn because Alice has Less than 500 transferable;
+ await expect(helper.staking.stake(staker, 500n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');
+ expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);
+ });
- await helper.staking.stake(staker, 200n * nominal);
- expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);
- const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
- expect(totalStakedPerBlock[0].amount).to.equal(100n * nominal);
- expect(totalStakedPerBlock[1].amount).to.equal(200n * nominal);
+ itSub('for different accounts in one block is possible', async ({helper}) => {
+ const crowd = [accounts.pop()!, accounts.pop()!, accounts.pop()!, accounts.pop()!];
+
+ const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));
+ await expect(Promise.all(crowdStartsToStake)).to.be.fulfilled;
+
+ const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));
+ expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);
+ });
});
-
- itSub('should allow to create maximum 10 stakes for account', async ({helper}) => {
- const [staker] = await helper.arrange.createAccounts([2000n], alice);
- for (let i = 0; i < 10; i++) {
+
+ describe('unstake extrinsic', () => {
+ itSub('should change balance state from "frozen" to "reserved", add it to "pendingUnstake" map, and subtract it from totalStaked', async ({helper}) => {
+ const [staker, recepient] = [accounts.pop()!, accounts.pop()!];
+ const totalStakedBefore = await helper.staking.getTotalStaked();
+ await helper.staking.stake(staker, 900n * nominal);
+ await helper.staking.unstake(staker);
+
+ // Right after unstake balance is reserved
+ // Staker can not transfer
+ expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 900n * nominal, miscFrozen: 0n, feeFrozen: 0n});
+ await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.InsufficientBalance');
+ expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(900n * nominal);
+ expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
+ expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);
+ });
+
+ itSub('should unlock balance after unlocking period ends and remove it from "pendingUnstake"', async ({helper}) => {
+ const staker = accounts.pop()!;
await helper.staking.stake(staker, 100n * 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.rejectedWith('appPromotion.NoPermission');
-
- // 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);
- });
+ await helper.staking.unstake(staker);
+ const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
- itSub('should reject transaction if stake amount is more than total free balance minus frozen', async ({helper}) => {
- const staker = accounts.pop()!;
-
- // Can't stake full balance because Alice needs to pay some fee
- await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected;
- await helper.staking.stake(staker, 500n * nominal);
-
- // Can't stake 500 tkn because Alice has Less than 500 transferable;
- await expect(helper.staking.stake(staker, 500n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');
- expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);
- });
+ // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n
+ await helper.wait.forParachainBlockNumber(pendingUnstake.block);
+ 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);
- itSub('for different accounts in one block is possible', async ({helper}) => {
- const crowd = [accounts.pop()!, accounts.pop()!, accounts.pop()!, accounts.pop()!];
-
- const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));
- await expect(Promise.all(crowdStartsToStake)).to.be.fulfilled;
-
- const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));
- expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);
- });
-});
-
-describe('unstake balance extrinsic', () => {
- before(async function () {
- await beforeEach(this);
- });
-
- itSub('should change balance state from "frozen" to "reserved", add it to "pendingUnstake" map, and subtract it from totalStaked', async ({helper}) => {
- const [staker, recepient] = [accounts.pop()!, accounts.pop()!];
- const totalStakedBefore = await helper.staking.getTotalStaked();
- await helper.staking.stake(staker, 900n * nominal);
- await helper.staking.unstake(staker);
-
- // Right after unstake balance is reserved
- // Staker can not transfer
- expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 900n * nominal, miscFrozen: 0n, feeFrozen: 0n});
- await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.InsufficientBalance');
- expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(900n * nominal);
- expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
- expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);
- });
-
- itSub('should unlock balance after unlocking period ends and remove it from "pendingUnstake"', async ({helper}) => {
- const staker = accounts.pop()!;
- await helper.staking.stake(staker, 100n * nominal);
- await helper.staking.unstake(staker);
- const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
-
- // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n
- await helper.wait.forParachainBlockNumber(pendingUnstake.block);
- 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:
- await helper.balance.transferToSubstrate(staker, alice.address, 998n * nominal);
- expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);
- });
-
- itSub('should successfully unstake multiple stakes', async ({helper}) => {
- const staker = accounts.pop()!;
- await helper.staking.stake(staker, 100n * nominal);
- await helper.staking.stake(staker, 200n * nominal);
- await helper.staking.stake(staker, 300n * nominal);
-
- // staked: [100, 200, 300]; unstaked: 0
- let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
- let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
- let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
- expect(totalPendingUnstake).to.be.deep.equal(0n);
- expect(pendingUnstake).to.be.deep.equal([]);
- expect(stakes[0].amount).to.equal(100n * nominal);
- expect(stakes[1].amount).to.equal(200n * nominal);
- expect(stakes[2].amount).to.equal(300n * nominal);
-
- // Can unstake multiple stakes
- await helper.staking.unstake(staker);
- pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
- totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
- stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
- expect(totalPendingUnstake).to.be.equal(600n * nominal);
- expect(stakes).to.be.deep.equal([]);
- expect(pendingUnstake[0].amount).to.equal(600n * nominal);
-
- expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 600n * nominal, feeFrozen: 0n, miscFrozen: 0n});
- await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);
- 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);
- });
-
- itSub('should not have any effects if no active stakes', async ({helper}) => {
- const staker = accounts.pop()!;
-
- // 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.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper
-
- // TODO stake() unstake() waitUnstaked() unstake();
-
- // can't unstake if there are only pendingUnstakes
- await helper.staking.stake(staker, 100n * nominal);
- await helper.staking.unstake(staker);
- await helper.staking.unstake(staker);
-
- expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
- expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
- });
-
- itSub('should keep different unlocking block for each unlocking stake', async ({helper}) => {
- const staker = accounts.pop()!;
- await helper.staking.stake(staker, 100n * nominal);
- await helper.staking.unstake(staker);
- await helper.staking.stake(staker, 120n * nominal);
- await helper.staking.unstake(staker);
-
- const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
- expect(unstakingPerBlock).has.length(2);
- expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);
- expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);
- });
-
- itSub('should be possible for different accounts in one block', async ({helper}) => {
- const stakers = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
-
- await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
- await Promise.all(stakers.map(staker => helper.staking.unstake(staker)));
-
- await Promise.all(stakers.map(async (staker) => {
+ // staker can transfer:
+ await helper.balance.transferToSubstrate(staker, alice.address, 998n * nominal);
+ expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);
+ });
+
+ itSub('should successfully unstake multiple stakes', async ({helper}) => {
+ const staker = accounts.pop()!;
+ await helper.staking.stake(staker, 100n * nominal);
+ await helper.staking.stake(staker, 200n * nominal);
+ await helper.staking.stake(staker, 300n * nominal);
+
+ // staked: [100, 200, 300]; unstaked: 0
+ let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
+ let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
+ let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ expect(totalPendingUnstake).to.be.deep.equal(0n);
+ expect(pendingUnstake).to.be.deep.equal([]);
+ expect(stakes[0].amount).to.equal(100n * nominal);
+ expect(stakes[1].amount).to.equal(200n * nominal);
+ expect(stakes[2].amount).to.equal(300n * nominal);
+
+ // Can unstake multiple stakes
+ await helper.staking.unstake(staker);
+ pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
+ totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
+ stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ expect(totalPendingUnstake).to.be.equal(600n * nominal);
+ expect(stakes).to.be.deep.equal([]);
+ expect(pendingUnstake[0].amount).to.equal(600n * nominal);
+
+ expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 600n * nominal, feeFrozen: 0n, miscFrozen: 0n});
+ await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);
+ 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);
+ });
+
+ itSub('should not have any effects if no active stakes', async ({helper}) => {
+ const staker = accounts.pop()!;
+
+ // 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.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper
+
+ // TODO stake() unstake() waitUnstaked() unstake();
+
+ // can't unstake if there are only pendingUnstakes
+ await helper.staking.stake(staker, 100n * nominal);
+ await helper.staking.unstake(staker);
+ await helper.staking.unstake(staker);
+
expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
- }));
- });
-});
-
-describe('Admin adress', () => {
- before(async function () {
- await beforeEach(this);
- });
-
- itSub('can be set by sudo only', async ({helper}) => {
- const nonAdmin = accounts.pop()!;
- // nonAdmin can not set admin not from himself nor as a sudo
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.rejected;
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.rejected;
-
- // Alice can
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
- });
+ });
+
+ itSub('should keep different unlocking block for each unlocking stake', async ({helper}) => {
+ const staker = accounts.pop()!;
+ await helper.staking.stake(staker, 100n * nominal);
+ await helper.staking.unstake(staker);
+ await helper.staking.stake(staker, 120n * nominal);
+ await helper.staking.unstake(staker);
- itSub('can be any valid CrossAccountId', async ({helper}) => {
- // We are not going to set an eth address as a sponsor,
- // but we do want to check, it doesn't break anything;
- const account = accounts.pop()!;
- const ethAccount = helper.address.substrateToEth(account.address);
- // Alice sets Ethereum address as a sudo. Then Substrate address back...
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.fulfilled;
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
-
- // ...It doesn't break anything;
- const collection = await helper.nft.mintCollection(account, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
- await expect(helper.signTransaction(account, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
- });
-
- itSub('can be reassigned', async ({helper}) => {
- const [oldAdmin, newAdmin, collectionOwner] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
- const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
-
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(oldAdmin))))).to.be.fulfilled;
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(newAdmin))))).to.be.fulfilled;
- await expect(helper.signTransaction(oldAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
-
- await expect(helper.signTransaction(newAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
- });
-});
-
-describe('App-promotion collection sponsoring', () => {
- before(async function () {
- await beforeEach(this);
- await usingPlaygrounds(async (helper) => {
- const tx = helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address}));
- await helper.signTransaction(alice, tx);
+ const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
+ expect(unstakingPerBlock).has.length(2);
+ expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);
+ expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);
});
- });
-
- itSub('should actually sponsor transactions', async ({helper}) => {
- const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
- const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});
- const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));
- const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);
-
- await token.transfer(tokenSender, {Substrate: receiver.address});
- expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});
- const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);
-
- // senders balance the same, transaction has sponsored
- expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);
- expect (palletBalanceBefore > palletBalanceAfter).to.be.true;
- });
-
- itSub('can not be set by non admin', async ({helper}) => {
- const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];
-
- const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
-
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
- expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');
- });
-
- itSub('should set pallet address as confirmed admin', async ({helper}) => {
- const [collectionOwner, oldSponsor] = [accounts.pop()!, accounts.pop()!];
-
- // Can set sponsoring for collection without sponsor
- const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;
- expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
-
- // Can set sponsoring for collection with unconfirmed sponsor
- const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
- expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;
- expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
-
- // Can set sponsoring for collection with confirmed sponsor
- const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
- await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;
- expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
- });
-
- itSub('can be overwritten by collection owner', async ({helper}) => {
- const [collectionOwner, newSponsor] = [accounts.pop()!, accounts.pop()!];
- const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
- const collectionId = collection.collectionId;
-
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;
-
- // Collection limits still can be changed by the owner
- expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;
- expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);
- expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
-
- // Collection sponsor can be changed too
- expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;
- expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});
- });
- itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {
- const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};
- const collectionWithLimits = await helper.nft.mintCollection(alice, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});
-
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;
- expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);
- });
+ itSub('should be possible for different accounts in one block', async ({helper}) => {
+ const stakers = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
- itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {
- const collectionOwner = accounts.pop()!;
-
- // collection has never existed
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;
- // collection has been burned
- const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
- await collection.burn(collectionOwner);
-
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
- });
-});
-
-describe('app-promotion stopSponsoringCollection', () => {
- before(async function () {
- await beforeEach(this);
+ await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
+ await Promise.all(stakers.map(staker => helper.staking.unstake(staker)));
+
+ await Promise.all(stakers.map(async (staker) => {
+ expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
+ expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
+ }));
+ });
});
-
- itSub('can not be called by non-admin', async ({helper}) => {
- const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];
- const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
-
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
-
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
- expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
- });
-
- itSub('should set sponsoring as disabled', async ({helper}) => {
- const [collectionOwner, recepient] = [accounts.pop()!, accounts.pop()!];
- const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});
- const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});
-
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId));
-
- expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');
-
- // Transactions are not sponsored anymore:
- const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);
- await token.transfer(collectionOwner, {Substrate: recepient.address});
- const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);
- expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);
- });
-
- itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {
- const collectionOwner = accounts.pop()!;
- const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});
- await collection.confirmSponsorship(collectionOwner);
-
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
-
- expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});
- });
-
- itSub('should reject transaction if collection does not exist', async ({helper}) => {
- const collectionOwner = accounts.pop()!;
- const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
-
- await collection.burn(collectionOwner);
- await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');
- await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');
- });
-});
-
-describe('app-promotion contract sponsoring', () => {
- before(async function () {
- await beforeEach(this);
- });
-
- itEth('should set palletes address as a sponsor', async ({helper}) => {
- const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
- const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
- const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
-
- await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);
+
+ describe('admin adress', () => {
+ itSub('can be set by sudo only', async ({helper}) => {
+ const nonAdmin = accounts.pop()!;
+ // nonAdmin can not set admin not from himself nor as a sudo
+ await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.rejected;
+ await expect(helper.signTransaction(nonAdmin, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.rejected;
+
+ // Alice can
+ await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
+ });
- expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;
- expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
- expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
- confirmed: {
- substrate: palletAddress,
- },
+ itSub('can be any valid CrossAccountId', async ({helper}) => {
+ // We are not going to set an eth address as a sponsor,
+ // but we do want to check, it doesn't break anything;
+ const account = accounts.pop()!;
+ const ethAccount = helper.address.substrateToEth(account.address);
+ // Alice sets Ethereum address as a sudo. Then Substrate address back...
+ await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.fulfilled;
+ await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
+
+ // ...It doesn't break anything;
+ const collection = await helper.nft.mintCollection(account, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
+ await expect(helper.signTransaction(account, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+ });
+
+ itSub('can be reassigned', async ({helper}) => {
+ const [oldAdmin, newAdmin, collectionOwner] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
+ const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
+
+ await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(oldAdmin))))).to.be.fulfilled;
+ await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(newAdmin))))).to.be.fulfilled;
+ await expect(helper.signTransaction(oldAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+
+ await expect(helper.signTransaction(newAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
});
});
-
- itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {
- const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
- const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
- const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
-
- await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;
-
- // Contract is self sponsored
- expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.be.deep.equal({
- confirmed: {
- ethereum: flipper.options.address.toLowerCase(),
- },
+
+ describe('collection sponsoring', () => {
+ before(async function () {
+ await usingPlaygrounds(async (helper) => {
+ const tx = helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address}));
+ await helper.signTransaction(alice, tx);
+ });
});
-
- // set promotion sponsoring
- await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);
-
- // new sponsor is pallet address
- expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;
- expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);
- expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({
- confirmed: {
- substrate: palletAddress,
- },
+
+ itSub('should actually sponsor transactions', async ({helper}) => {
+ const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
+ const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});
+ const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});
+ await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));
+ const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);
+
+ await token.transfer(tokenSender, {Substrate: receiver.address});
+ expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});
+ const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);
+
+ // senders balance the same, transaction has sponsored
+ expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);
+ expect (palletBalanceBefore > palletBalanceAfter).to.be.true;
});
- });
-
- itEth('can be overwritten by contract owner', async ({helper}) => {
- const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
- const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
- const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
-
- // contract sponsored by pallet
- await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);
-
- // owner sets self sponsoring
- await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
-
- expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;
- expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
- expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
- confirmed: {
- ethereum: flipper.options.address.toLowerCase(),
- },
+
+ itSub('can not be set by non admin', async ({helper}) => {
+ const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];
+
+ const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
+
+ await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+ expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');
});
- });
-
- itEth('can not be set by non admin', async ({helper}) => {
- const nonAdmin = accounts.pop()!;
- const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
- const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
- const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
-
- await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;
-
- // nonAdmin calls sponsorContract
- await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');
-
- // contract still self-sponsored
- expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
- confirmed: {
- ethereum: flipper.options.address.toLowerCase(),
- },
+
+ itSub('should set pallet address as confirmed admin', async ({helper}) => {
+ const [collectionOwner, oldSponsor] = [accounts.pop()!, accounts.pop()!];
+
+ // Can set sponsoring for collection without sponsor
+ const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;
+ expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
+
+ // Can set sponsoring for collection with unconfirmed sponsor
+ const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
+ expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;
+ expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
+
+ // Can set sponsoring for collection with confirmed sponsor
+ const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
+ await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;
+ expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
});
- });
-
- itEth('should actually sponsor transactions', async ({helper}) => {
- // Contract caller
- const caller = await helper.eth.createAccountWithBalance(alice, 1000n);
- const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);
+
+ itSub('can be overwritten by collection owner', async ({helper}) => {
+ const [collectionOwner, newSponsor] = [accounts.pop()!, accounts.pop()!];
+ const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
+ const collectionId = collection.collectionId;
+
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;
- // Deploy flipper
- const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
- const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
- const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+ // Collection limits still can be changed by the owner
+ expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;
+ expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);
+ expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
+
+ // Collection sponsor can be changed too
+ expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;
+ expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});
+ });
- // Owner sets to sponsor every tx
- await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});
- await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});
- await helper.eth.transferBalanceFromSubstrate(alice, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);
-
- // Set promotion to the Flipper
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorContract(flipper.options.address));
-
- // Caller calls Flipper
- await flipper.methods.flip().send({from: caller});
- expect(await flipper.methods.getValue().call()).to.be.true;
-
- // The contracts and caller balances have not changed
- const callerBalance = await helper.balance.getEthereum(caller);
- const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);
- expect(callerBalance).to.be.equal(1000n * nominal);
- expect(1000n * nominal === contractBalanceAfter).to.be.true;
-
- // The pallet balance has decreased
- const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);
- expect(palletBalanceAfter < palletBalanceBefore).to.be.true;
- });
-});
-
-describe('app-promotion stopSponsoringContract', () => {
- before(async function () {
- await beforeEach(this);
- });
-
- itEth('should remove pallet address from contract sponsors', async ({helper}) => {
- const caller = await helper.eth.createAccountWithBalance(alice, 1000n);
- const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
- const flipper = await helper.eth.deployFlipper(contractOwner);
- await helper.eth.transferBalanceFromSubstrate(alice, flipper.options.address);
- const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
-
- await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});
- await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);
- await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);
-
- expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;
- expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
- expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
- disabled: null,
+ itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {
+ const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};
+ const collectionWithLimits = await helper.nft.mintCollection(alice, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});
+
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;
+ expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);
});
-
- await flipper.methods.flip().send({from: caller});
- expect(await flipper.methods.getValue().call()).to.be.true;
-
- const callerBalance = await helper.balance.getEthereum(caller);
- const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);
-
- // caller payed for call
- expect(1000n * nominal > callerBalance).to.be.true;
- expect(contractBalanceAfter).to.be.equal(1000n * nominal);
- });
-
- itEth('can not be called by non-admin', async ({helper}) => {
- const nonAdmin = accounts.pop()!;
- const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
- const flipper = await helper.eth.deployFlipper(contractOwner);
-
- await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);
- const stopSponsoringResult = await helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]);
- expect(stopSponsoringResult.status).to.equal('Fail');
- expect(stopSponsoringResult.moduleError).to.equal('appPromotion.NoPermission');
- });
-
- itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {
- const nonAdmin = accounts.pop()!;
- const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
- const flipper = await helper.eth.deployFlipper(contractOwner);
- const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
- await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;
-
- await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');
- });
-});
-
-describe('app-promotion rewards', () => {
- before(async function () {
- await beforeEach(this);
- });
-
- itSub('can not be called by non admin', async ({helper}) => {
- const nonAdmin = accounts.pop()!;
- await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');
- });
-
- itSub('should increase total staked', async ({helper}) => {
- const staker = accounts.pop()!;
- const totalStakedBefore = await helper.staking.getTotalStaked();
- await helper.staking.stake(staker, 100n * nominal);
-
- // Wait for rewards and pay
- const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
- await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));
- const totalPayout = (await helper.admin.payoutStakers(palletAdmin, 100)).reduce((prev, payout) => prev + payout.payout, 0n);
-
- const totalStakedAfter = await helper.staking.getTotalStaked();
- expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);
- // staker can unstake
- await helper.staking.unstake(staker);
- expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal, 10n));
- });
-
- itSub('should credit 0.05% for staking period', async ({helper}) => {
- const staker = accounts.pop()!;
-
- await waitPromotionPeriodDoesntEnd(helper);
-
- await helper.staking.stake(staker, 100n * nominal);
- await helper.staking.stake(staker, 200n * nominal);
-
- // wait rewards are available:
- const [_, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
- await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));
-
- const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)?.payout;
- expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal, 10n));
-
- const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
- expect(totalStakedPerBlock[0].amount).to.equal(calculateIncome(100n * nominal, 10n));
- expect(totalStakedPerBlock[1].amount).to.equal(calculateIncome(200n * nominal, 10n));
- });
-
- itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {
- const staker = accounts.pop()!;
-
- await helper.staking.stake(staker, 100n * nominal);
- // wait for two rewards are available:
- let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
- await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);
-
- await helper.admin.payoutStakers(palletAdmin, 100);
- [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
- const frozenBalanceShouldBe = calculateIncome(100n * nominal, 10n, 2);
- expect(stake.amount).to.be.equal(frozenBalanceShouldBe);
-
- const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);
-
- expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});
+
+ itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {
+ const collectionOwner = accounts.pop()!;
+
+ // collection has never existed
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;
+ // collection has been burned
+ const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
+ await collection.burn(collectionOwner);
+
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+ });
});
- itSub('should not be credited for unstaked (reserved) balance', async ({helper}) => {
- // staker unstakes before rewards has been payed
- const staker = accounts.pop()!;
- await helper.staking.stake(staker, 100n * nominal);
- const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
- await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);
- await helper.staking.unstake(staker);
-
- // so he did not receive any rewards
- const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);
- await helper.admin.payoutStakers(palletAdmin, 100);
- const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);
-
- expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);
+ describe('stopSponsoringCollection', () => {
+ itSub('can not be called by non-admin', async ({helper}) => {
+ const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];
+ const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
+
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
+
+ await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
+ expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
+ });
+
+ itSub('should set sponsoring as disabled', async ({helper}) => {
+ const [collectionOwner, recepient] = [accounts.pop()!, accounts.pop()!];
+ const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});
+ const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});
+
+ await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));
+ await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId));
+
+ expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');
+
+ // Transactions are not sponsored anymore:
+ const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);
+ await token.transfer(collectionOwner, {Substrate: recepient.address});
+ const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);
+ expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);
+ });
+
+ itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {
+ const collectionOwner = accounts.pop()!;
+ const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});
+ await collection.confirmSponsorship(collectionOwner);
+
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
+
+ expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});
+ });
+
+ itSub('should reject transaction if collection does not exist', async ({helper}) => {
+ const collectionOwner = accounts.pop()!;
+ const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
+
+ await collection.burn(collectionOwner);
+ await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');
+ await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');
+ });
});
- itSub('should bring compound interest', async ({helper}) => {
- const staker = accounts.pop()!;
-
- await helper.staking.stake(staker, 100n * nominal);
-
- let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
- await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));
+ describe('contract sponsoring', () => {
+ itEth('should set palletes address as a sponsor', async ({helper}) => {
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
+ const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+
+ await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);
- await helper.admin.payoutStakers(palletAdmin, 100);
- [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
- expect(stake.amount).to.equal(calculateIncome(100n * nominal, 10n));
+ expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;
+ expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
+ expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ confirmed: {
+ substrate: palletAddress,
+ },
+ });
+ });
+
+ itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
+ const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+
+ await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;
+
+ // Contract is self sponsored
+ expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.be.deep.equal({
+ confirmed: {
+ ethereum: flipper.options.address.toLowerCase(),
+ },
+ });
+
+ // set promotion sponsoring
+ await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);
+
+ // new sponsor is pallet address
+ expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;
+ expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);
+ expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({
+ confirmed: {
+ substrate: palletAddress,
+ },
+ });
+ });
+
+ itEth('can be overwritten by contract owner', async ({helper}) => {
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
+ const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+
+ // contract sponsored by pallet
+ await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);
+
+ // owner sets self sponsoring
+ await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
+
+ expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;
+ expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
+ expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ confirmed: {
+ ethereum: flipper.options.address.toLowerCase(),
+ },
+ });
+ });
+
+ itEth('can not be set by non admin', async ({helper}) => {
+ const nonAdmin = accounts.pop()!;
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
+ const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+
+ await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;
+
+ // nonAdmin calls sponsorContract
+ await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');
+
+ // contract still self-sponsored
+ expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ confirmed: {
+ ethereum: flipper.options.address.toLowerCase(),
+ },
+ });
+ });
+
+ itEth('should actually sponsor transactions', async ({helper}) => {
+ // Contract caller
+ const caller = await helper.eth.createAccountWithBalance(alice, 1000n);
+ const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);
+
+ // Deploy flipper
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
+ const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
- await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);
- await helper.admin.payoutStakers(palletAdmin, 100);
- [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
- expect(stake.amount).to.equal(calculateIncome(100n * nominal, 10n, 2));
+ // Owner sets to sponsor every tx
+ await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});
+ await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});
+ await helper.eth.transferBalanceFromSubstrate(alice, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);
+
+ // Set promotion to the Flipper
+ await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorContract(flipper.options.address));
+
+ // Caller calls Flipper
+ await flipper.methods.flip().send({from: caller});
+ expect(await flipper.methods.getValue().call()).to.be.true;
+
+ // The contracts and caller balances have not changed
+ const callerBalance = await helper.balance.getEthereum(caller);
+ const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);
+ expect(callerBalance).to.be.equal(1000n * nominal);
+ expect(1000n * nominal === contractBalanceAfter).to.be.true;
+
+ // The pallet balance has decreased
+ const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);
+ expect(palletBalanceAfter < palletBalanceBefore).to.be.true;
+ });
});
-
- itSub.skip('can be paid 1000 rewards in a time', async ({helper}) => {
- // all other stakes should be unstaked
- const oneHundredStakers = await helper.arrange.createCrowd(100, 1050n, alice);
-
- // stakers stakes 10 times each
- for (let i = 0; i < 10; i++) {
- await Promise.all(oneHundredStakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
- }
- await helper.wait.newBlocks(40);
- await helper.admin.payoutStakers(palletAdmin, 100);
+
+ describe('stopSponsoringContract', () => {
+ itEth('should remove pallet address from contract sponsors', async ({helper}) => {
+ const caller = await helper.eth.createAccountWithBalance(alice, 1000n);
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner);
+ await helper.eth.transferBalanceFromSubstrate(alice, flipper.options.address);
+ const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+
+ await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});
+ await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);
+ await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);
+
+ expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;
+ expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
+ expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ disabled: null,
+ });
+
+ await flipper.methods.flip().send({from: caller});
+ expect(await flipper.methods.getValue().call()).to.be.true;
+
+ const callerBalance = await helper.balance.getEthereum(caller);
+ const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);
+
+ // caller payed for call
+ expect(1000n * nominal > callerBalance).to.be.true;
+ expect(contractBalanceAfter).to.be.equal(1000n * nominal);
+ });
+
+ itEth('can not be called by non-admin', async ({helper}) => {
+ const nonAdmin = accounts.pop()!;
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner);
+
+ await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);
+ const stopSponsoringResult = await helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]);
+ expect(stopSponsoringResult.status).to.equal('Fail');
+ expect(stopSponsoringResult.moduleError).to.equal('appPromotion.NoPermission');
+ });
+
+ itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {
+ const nonAdmin = accounts.pop()!;
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner);
+ const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+ await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;
+
+ await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');
+ });
});
-
- itSub.skip('can handle 40.000 rewards', async ({helper}) => {
- const [donor] = await helper.arrange.createAccounts([7_000_000n], alice);
- const crowdStakes = async () => {
- // each account in the crowd stakes 2 times
- const crowd = await helper.arrange.createCrowd(500, 300n, donor);
- await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));
- await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));
- //
- };
-
- for (let i = 0; i < 40; i++) {
- await crowdStakes();
- }
-
- // TODO pay rewards for some period
+
+ describe('rewards', () => {
+ itSub('can not be called by non admin', async ({helper}) => {
+ const nonAdmin = accounts.pop()!;
+ await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');
+ });
+
+ itSub('should increase total staked', async ({helper}) => {
+ const staker = accounts.pop()!;
+ const totalStakedBefore = await helper.staking.getTotalStaked();
+ await helper.staking.stake(staker, 100n * nominal);
+
+ // Wait for rewards and pay
+ const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));
+ const totalPayout = (await helper.admin.payoutStakers(palletAdmin, 100)).reduce((prev, payout) => prev + payout.payout, 0n);
+
+ const totalStakedAfter = await helper.staking.getTotalStaked();
+ expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);
+ // staker can unstake
+ await helper.staking.unstake(staker);
+ expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal, 10n));
+ });
+
+ itSub('should credit 0.05% for staking period', async ({helper}) => {
+ const staker = accounts.pop()!;
+
+ await waitPromotionPeriodDoesntEnd(helper);
+
+ await helper.staking.stake(staker, 100n * nominal);
+ await helper.staking.stake(staker, 200n * nominal);
+
+ // wait rewards are available:
+ const [_, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));
+
+ const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)?.payout;
+ expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal, 10n));
+
+ const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ expect(totalStakedPerBlock[0].amount).to.equal(calculateIncome(100n * nominal, 10n));
+ expect(totalStakedPerBlock[1].amount).to.equal(calculateIncome(200n * nominal, 10n));
+ });
+
+ itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {
+ const staker = accounts.pop()!;
+
+ await helper.staking.stake(staker, 100n * nominal);
+ // wait for two rewards are available:
+ let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);
+
+ await helper.admin.payoutStakers(palletAdmin, 100);
+ [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ const frozenBalanceShouldBe = calculateIncome(100n * nominal, 10n, 2);
+ expect(stake.amount).to.be.equal(frozenBalanceShouldBe);
+
+ const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);
+
+ expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});
+ });
+
+ itSub('should not be credited for unstaked (reserved) balance', async ({helper}) => {
+ // staker unstakes before rewards has been payed
+ const staker = accounts.pop()!;
+ await helper.staking.stake(staker, 100n * nominal);
+ const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);
+ await helper.staking.unstake(staker);
+
+ // so he did not receive any rewards
+ const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);
+ await helper.admin.payoutStakers(palletAdmin, 100);
+ const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);
+
+ expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);
+ });
+
+ itSub('should bring compound interest', async ({helper}) => {
+ const staker = accounts.pop()!;
+
+ await helper.staking.stake(staker, 100n * nominal);
+
+ let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));
+
+ await helper.admin.payoutStakers(palletAdmin, 100);
+ [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ expect(stake.amount).to.equal(calculateIncome(100n * nominal, 10n));
+
+ await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);
+ await helper.admin.payoutStakers(palletAdmin, 100);
+ [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ expect(stake.amount).to.equal(calculateIncome(100n * nominal, 10n, 2));
+ });
+
+ itSub.skip('can be paid 1000 rewards in a time', async ({helper}) => {
+ // all other stakes should be unstaked
+ const oneHundredStakers = await helper.arrange.createCrowd(100, 1050n, alice);
+
+ // stakers stakes 10 times each
+ for (let i = 0; i < 10; i++) {
+ await Promise.all(oneHundredStakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
+ }
+ await helper.wait.newBlocks(40);
+ await helper.admin.payoutStakers(palletAdmin, 100);
+ });
+
+ itSub.skip('can handle 40.000 rewards', async ({helper}) => {
+ const [donor] = await helper.arrange.createAccounts([7_000_000n], alice);
+ const crowdStakes = async () => {
+ // each account in the crowd stakes 2 times
+ const crowd = await helper.arrange.createCrowd(500, 300n, donor);
+ await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));
+ await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));
+ //
+ };
+
+ for (let i = 0; i < 40; i++) {
+ await crowdStakes();
+ }
+
+ // TODO pay rewards for some period
+ });
});
});
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}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:') || 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;63 admin: AdminGroup;6465 constructor(logger: { log: (msg: any, level: any) => void, level: any }) {66 super(logger);67 this.arrange = new ArrangeGroup(this);68 this.wait = new WaitGroup(this);69 this.admin = new AdminGroup(this);70 }7172 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {73 const wsProvider = new WsProvider(wsEndpoint);74 this.api = new ApiPromise({75 provider: wsProvider,76 signedExtensions: {77 ContractHelpers: {78 extrinsic: {},79 payload: {},80 },81 FakeTransactionFinalizer: {82 extrinsic: {},83 payload: {},84 },85 },86 rpc: {87 unique: defs.unique.rpc,88 appPromotion: defs.appPromotion.rpc,89 rmrk: defs.rmrk.rpc,90 eth: {91 feeHistory: {92 description: 'Dummy',93 params: [],94 type: 'u8',95 },96 maxPriorityFeePerGas: {97 description: 'Dummy',98 params: [],99 type: 'u8',100 },101 },102 },103 });104 await this.api.isReadyOrError;105 this.network = await UniqueHelper.detectNetwork(this.api);106 }107}108109class ArrangeGroup {110 helper: UniqueHelper;111112 constructor(helper: UniqueHelper) {113 this.helper = helper;114 }115116 /**117 * Generates accounts with the specified UNQ token balance 118 * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.119 * @param donor donor account for balances120 * @returns array of newly created accounts121 * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 122 */123 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {124 let nonce = await this.helper.chain.getNonce(donor.address);125 const ss58Format = this.helper.chain.getChainProperties().ss58Format;126 const tokenNominal = this.helper.balance.getOneTokenNominal();127 const transactions = [];128 const accounts: IKeyringPair[] = [];129 for (const balance of balances) {130 const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);131 accounts.push(recipient);132 if (balance !== 0n) {133 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);134 transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));135 nonce++;136 }137 }138139 await Promise.all(transactions).catch(_e => {});140 141 //#region TODO remove this region, when nonce problem will be solved142 const checkBalances = async () => {143 let isSuccess = true;144 for (let i = 0; i < balances.length; i++) {145 const balance = await this.helper.balance.getSubstrate(accounts[i].address);146 if (balance !== balances[i] * tokenNominal) {147 isSuccess = false;148 break;149 }150 }151 return isSuccess;152 };153154 let accountsCreated = false;155 // checkBalances retry up to 5 blocks156 for (let index = 0; index < 5; index++) {157 accountsCreated = await checkBalances();158 if(accountsCreated) break;159 160 }161162 if (!accountsCreated) throw Error('Accounts generation failed');163 //#endregion164165 return accounts;166 };167168 // TODO combine this method and createAccounts into one169 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => { 170 const createAsManyAsCan = async () => {171 let transactions: any = [];172 const accounts: IKeyringPair[] = [];173 let nonce = await this.helper.chain.getNonce(donor.address);174 const tokenNominal = this.helper.balance.getOneTokenNominal();175 for (let i = 0; i < accountsToCreate; i++) {176 if (i === 500) { // if there are too many accounts to create177 await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 178 transactions = []; //179 nonce = await this.helper.chain.getNonce(donor.address); // update nonce 180 }181 const recepient = this.helper.util.fromSeed(mnemonicGenerate());182 accounts.push(recepient);183 if (withBalance !== 0n) {184 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);185 transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));186 nonce++;187 }188 }189 190 const fullfilledAccounts = [];191 await Promise.allSettled(transactions);192 for (const account of accounts) {193 const accountBalance = await this.helper.balance.getSubstrate(account.address);194 if (accountBalance === withBalance * tokenNominal) {195 fullfilledAccounts.push(account);196 }197 }198 return fullfilledAccounts;199 };200201 202 const crowd: IKeyringPair[] = [];203 // do up to 5 retries204 for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {205 const asManyAsCan = await createAsManyAsCan();206 crowd.push(...asManyAsCan);207 accountsToCreate -= asManyAsCan.length;208 }209210 if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);211212 return crowd;213 };214215 isDevNode = async () => {216 const block1 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(1));217 const block2 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(2));218 const findCreationDate = async (block: any) => {219 const humanBlock = block.toHuman();220 let date;221 humanBlock.block.extrinsics.forEach((ext: any) => {222 if(ext.method.section === 'timestamp') {223 date = Number(ext.method.args.now.replaceAll(',', ''));224 }225 });226 return date;227 };228 const block1date = await findCreationDate(block1);229 const block2date = await findCreationDate(block2);230 if(block2date! - block1date! < 9000) return true;231 };232}233234class WaitGroup {235 helper: UniqueHelper;236237 constructor(helper: UniqueHelper) {238 this.helper = helper;239 }240241 /**242 * Wait for specified bnumber of blocks243 * @param blocksCount number of blocks to wait244 * @returns 245 */246 async newBlocks(blocksCount = 1): Promise<void> {247 // eslint-disable-next-line no-async-promise-executor248 const promise = new Promise<void>(async (resolve) => {249 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {250 if (blocksCount > 0) {251 blocksCount--;252 } else {253 unsubscribe();254 resolve();255 }256 });257 });258 return promise;259 }260261 async forParachainBlockNumber(blockNumber: bigint) {262 // eslint-disable-next-line no-async-promise-executor263 return new Promise<void>(async (resolve) => {264 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(async (data: any) => {265 if (data.number.toNumber() >= blockNumber) {266 unsubscribe();267 resolve();268 }269 });270 });271 }272 273 async forRelayBlockNumber(blockNumber: bigint) {274 // eslint-disable-next-line no-async-promise-executor275 return new Promise<void>(async (resolve) => {276 const unsubscribe = await this.helper.api!.query.parachainSystem.validationData(async (data: any) => {277 if (data.value.relayParentNumber.toNumber() >= blockNumber) {278 // @ts-ignore279 unsubscribe();280 resolve();281 }282 });283 });284 }285}286287class AdminGroup {288 helper: UniqueHelper;289290 constructor(helper: UniqueHelper) {291 this.helper = helper;292 }293294 async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {295 const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);296 return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {297 return {298 staker: e.event.data[0].toString(),299 stake: e.event.data[1].toBigInt(),300 payout: e.event.data[2].toBigInt(),301 };302 });303 }304}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:') || 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;63 admin: AdminGroup;6465 constructor(logger: { log: (msg: any, level: any) => void, level: any }) {66 super(logger);67 this.arrange = new ArrangeGroup(this);68 this.wait = new WaitGroup(this);69 this.admin = new AdminGroup(this);70 }7172 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {73 const wsProvider = new WsProvider(wsEndpoint);74 this.api = new ApiPromise({75 provider: wsProvider,76 signedExtensions: {77 ContractHelpers: {78 extrinsic: {},79 payload: {},80 },81 FakeTransactionFinalizer: {82 extrinsic: {},83 payload: {},84 },85 },86 rpc: {87 unique: defs.unique.rpc,88 appPromotion: defs.appPromotion.rpc,89 rmrk: defs.rmrk.rpc,90 eth: {91 feeHistory: {92 description: 'Dummy',93 params: [],94 type: 'u8',95 },96 maxPriorityFeePerGas: {97 description: 'Dummy',98 params: [],99 type: 'u8',100 },101 },102 },103 });104 await this.api.isReadyOrError;105 this.network = await UniqueHelper.detectNetwork(this.api);106 }107}108109class ArrangeGroup {110 helper: UniqueHelper;111112 constructor(helper: UniqueHelper) {113 this.helper = helper;114 }115116 /**117 * Generates accounts with the specified UNQ token balance 118 * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.119 * @param donor donor account for balances120 * @returns array of newly created accounts121 * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 122 */123 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {124 let nonce = await this.helper.chain.getNonce(donor.address);125 const wait = new WaitGroup(this.helper);126 const ss58Format = this.helper.chain.getChainProperties().ss58Format;127 const tokenNominal = this.helper.balance.getOneTokenNominal();128 const transactions = [];129 const accounts: IKeyringPair[] = [];130 for (const balance of balances) {131 const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);132 accounts.push(recipient);133 if (balance !== 0n) {134 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);135 transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));136 nonce++;137 }138 }139140 await Promise.all(transactions).catch(_e => {});141 142 //#region TODO remove this region, when nonce problem will be solved143 const checkBalances = async () => {144 let isSuccess = true;145 for (let i = 0; i < balances.length; i++) {146 const balance = await this.helper.balance.getSubstrate(accounts[i].address);147 if (balance !== balances[i] * tokenNominal) {148 isSuccess = false;149 break;150 }151 }152 return isSuccess;153 };154155 let accountsCreated = false;156 // checkBalances retry up to 5 blocks157 for (let index = 0; index < 5; index++) {158 accountsCreated = await checkBalances();159 if(accountsCreated) break;160 await wait.newBlocks(1);161 }162163 if (!accountsCreated) throw Error('Accounts generation failed');164 //#endregion165166 return accounts;167 };168169 // TODO combine this method and createAccounts into one170 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => { 171 const createAsManyAsCan = async () => {172 let transactions: any = [];173 const accounts: IKeyringPair[] = [];174 let nonce = await this.helper.chain.getNonce(donor.address);175 const tokenNominal = this.helper.balance.getOneTokenNominal();176 for (let i = 0; i < accountsToCreate; i++) {177 if (i === 500) { // if there are too many accounts to create178 await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 179 transactions = []; //180 nonce = await this.helper.chain.getNonce(donor.address); // update nonce 181 }182 const recepient = this.helper.util.fromSeed(mnemonicGenerate());183 accounts.push(recepient);184 if (withBalance !== 0n) {185 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);186 transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));187 nonce++;188 }189 }190 191 const fullfilledAccounts = [];192 await Promise.allSettled(transactions);193 for (const account of accounts) {194 const accountBalance = await this.helper.balance.getSubstrate(account.address);195 if (accountBalance === withBalance * tokenNominal) {196 fullfilledAccounts.push(account);197 }198 }199 return fullfilledAccounts;200 };201202 203 const crowd: IKeyringPair[] = [];204 // do up to 5 retries205 for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {206 const asManyAsCan = await createAsManyAsCan();207 crowd.push(...asManyAsCan);208 accountsToCreate -= asManyAsCan.length;209 }210211 if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);212213 return crowd;214 };215216 isDevNode = async () => {217 const block1 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(1));218 const block2 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(2));219 const findCreationDate = async (block: any) => {220 const humanBlock = block.toHuman();221 let date;222 humanBlock.block.extrinsics.forEach((ext: any) => {223 if(ext.method.section === 'timestamp') {224 date = Number(ext.method.args.now.replaceAll(',', ''));225 }226 });227 return date;228 };229 const block1date = await findCreationDate(block1);230 const block2date = await findCreationDate(block2);231 if(block2date! - block1date! < 9000) return true;232 };233}234235class WaitGroup {236 helper: UniqueHelper;237238 constructor(helper: UniqueHelper) {239 this.helper = helper;240 }241242 /**243 * Wait for specified bnumber of blocks244 * @param blocksCount number of blocks to wait245 * @returns 246 */247 async newBlocks(blocksCount = 1): Promise<void> {248 // eslint-disable-next-line no-async-promise-executor249 const promise = new Promise<void>(async (resolve) => {250 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {251 if (blocksCount > 0) {252 blocksCount--;253 } else {254 unsubscribe();255 resolve();256 }257 });258 });259 return promise;260 }261262 async forParachainBlockNumber(blockNumber: bigint) {263 // eslint-disable-next-line no-async-promise-executor264 return new Promise<void>(async (resolve) => {265 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(async (data: any) => {266 if (data.number.toNumber() >= blockNumber) {267 unsubscribe();268 resolve();269 }270 });271 });272 }273 274 async forRelayBlockNumber(blockNumber: bigint) {275 // eslint-disable-next-line no-async-promise-executor276 return new Promise<void>(async (resolve) => {277 const unsubscribe = await this.helper.api!.query.parachainSystem.validationData(async (data: any) => {278 if (data.value.relayParentNumber.toNumber() >= blockNumber) {279 // @ts-ignore280 unsubscribe();281 resolve();282 }283 });284 });285 }286}287288class AdminGroup {289 helper: UniqueHelper;290291 constructor(helper: UniqueHelper) {292 this.helper = helper;293 }294295 async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {296 const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);297 return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {298 return {299 staker: e.event.data[0].toString(),300 stake: e.event.data[1].toBigInt(),301 payout: e.event.data[2].toBigInt(),302 };303 });304 }305}