difftreelog
Merge pull request #592 from UniqueNetwork/test/app-promotion-refactor
in: master
Test/app promotion refactor
10 files changed
.docker/Dockerfile-chain-devdiffbeforeafterboth--- a/.docker/Dockerfile-chain-dev
+++ b/.docker/Dockerfile-chain-dev
@@ -1,17 +1,19 @@
FROM ubuntu:20.04
+ARG RUST_TOOLCHAIN=
+ARG FEATURE=
+
ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=Etc/UTC
-
-RUN apt-get update && apt-get install -y git curl libssl-dev llvm pkg-config libclang-dev clang git make cmake
-
+ENV FEATURE=$FEATURE
ENV CARGO_HOME="/cargo-home"
ENV PATH="/cargo-home/bin:$PATH"
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
+RUN echo "$FEATURE\n" && echo "$RUST_TOOLCHAIN\n"
-ARG RUST_TOOLCHAIN=
-ARG FEATURE=
+RUN apt-get update && apt-get install -y git curl libssl-dev llvm pkg-config libclang-dev clang git make cmake
+
+RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
RUN rustup toolchain uninstall $(rustup toolchain list) && \
rustup toolchain install $RUST_TOOLCHAIN && \
@@ -24,5 +26,6 @@
WORKDIR /dev_chain
RUN cargo build --release
+RUN echo "$FEATURE"
CMD cargo run --release --features=$FEATURE -- --dev -linfo --unsafe-ws-external --rpc-cors=all --unsafe-rpc-external
.docker/docker-compose.tmp-dev.j2diffbeforeafterboth--- a/.docker/docker-compose.tmp-dev.j2
+++ b/.docker/docker-compose.tmp-dev.j2
@@ -18,4 +18,4 @@
options:
max-size: "1m"
max-file: "3"
- command: cargo run --release --features=$FEATURE -- --dev -linfo --unsafe-ws-external --rpc-cors=all --unsafe-rpc-external
+ command: cargo run --release --features={{ FEATURE }} -- --dev -linfo --unsafe-ws-external --rpc-cors=all --unsafe-rpc-external
.github/workflows/dev-build-tests_v2.ymldiffbeforeafterboth--- a/.github/workflows/dev-build-tests_v2.yml
+++ b/.github/workflows/dev-build-tests_v2.yml
@@ -95,3 +95,10 @@
- name: Stop running containers
if: always() # run this step always
run: docker-compose -f ".docker/docker-compose-dev.yaml" -f ".docker/docker-compose.${{ matrix.network }}.yml" down
+
+ - name: Remove builder cache
+ if: always() # run this step always
+ run: |
+ docker builder prune -f -a
+ docker system prune -f
+ docker image prune -f -a
\ No newline at end of file
tests/src/adminTransferAndBurn.test.tsdiffbeforeafterboth--- a/tests/src/adminTransferAndBurn.test.ts
+++ b/tests/src/adminTransferAndBurn.test.ts
@@ -24,19 +24,14 @@
let donor: IKeyringPair;
-before(async () => {
- await usingPlaygrounds(async (_, privateKey) => {
- donor = privateKey('//Alice');
- });
-});
-
describe('Integration Test: ownerCanTransfer allows admins to use only transferFrom/burnFrom:', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
let charlie: IKeyringPair;
before(async () => {
- await usingPlaygrounds(async (helper) => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ donor = privateKey('//Alice');
[alice, bob, charlie] = await helper.arrange.createAccounts([10n, 10n, 10n], donor);
});
});
tests/src/allowLists.test.tsdiffbeforeafterboth--- a/tests/src/allowLists.test.ts
+++ b/tests/src/allowLists.test.ts
@@ -24,12 +24,6 @@
let donor: IKeyringPair;
-before(async () => {
- await usingPlaygrounds(async (_, privateKey) => {
- donor = privateKey('//Alice');
- });
-});
-
let alice: IKeyringPair;
let bob: IKeyringPair;
let charlie: IKeyringPair;
@@ -37,7 +31,8 @@
describe('Integration Test ext. Allow list tests', () => {
before(async () => {
- await usingPlaygrounds(async (helper) => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ donor = privateKey('//Alice');
[alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
});
});
tests/src/app-promotion.test.tsdiffbeforeafterboth20 getModuleNames,20 getModuleNames,21 Pallets,21 Pallets,22} from './util/helpers';22} from './util/helpers';2324import chai from 'chai';23import {itSub, usingPlaygrounds} from './util/playgrounds';25import chaiAsPromised from 'chai-as-promised';26import {usingPlaygrounds} from './util/playgrounds';2728import {encodeAddress} from '@polkadot/util-crypto';24import {encodeAddress} from '@polkadot/util-crypto';29import {stringToU8a} from '@polkadot/util';25import {stringToU8a} from '@polkadot/util';30import {SponsoringMode, contractHelpers, createEthAccountWithBalance, deployFlipper, itWeb3, transferBalanceToEth} from './eth/util/helpers';26import {SponsoringMode} from './eth/util/helpers';31import {DevUniqueHelper} from './util/playgrounds/unique.dev';27import {DevUniqueHelper} from './util/playgrounds/unique.dev';32chai.use(chaiAsPromised);33const expect = chai.expect;28import {itEth, expect} from './eth/util/playgrounds';342935let alice: IKeyringPair;30let alice: IKeyringPair;36let palletAdmin: IKeyringPair;31let palletAdmin: IKeyringPair;37let nominal: bigint;32let nominal: bigint;38const palletAddress = calculatePalleteAddress('appstake');33const palletAddress = calculatePalleteAddress('appstake');39let accounts: IKeyringPair[] = [];34let accounts: IKeyringPair[] = [];40const LOCKING_PERIOD = 20n; // 20 blocks of relay35const LOCKING_PERIOD = 20n; // 20 blocks of relay41const UNLOCKING_PERIOD = 10n; // 20 blocks of parachain36const UNLOCKING_PERIOD = 10n; // 10 blocks of parachain42const rewardAvailableInBlock = (stakedInBlock: bigint) => (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);37const rewardAvailableInBlock = (stakedInBlock: bigint) => (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);433844const beforeEach = async (context: Mocha.Context) => {45 await usingPlaygrounds(async (helper, privateKey) => {46 if (!getModuleNames(helper.api!).includes(Pallets.AppPromotion)) context.skip();47 alice = privateKey('//Alice');48 palletAdmin = privateKey('//Charlie'); // TODO use custom address49 await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));50 nominal = helper.balance.getOneTokenNominal();51 await helper.balance.transferToSubstrate(alice, palletAdmin.address, 1000n * nominal);52 await helper.balance.transferToSubstrate(alice, palletAddress, 1000n * nominal);53 accounts = await helper.arrange.createCrowd(100, 1000n, alice); // create accounts-pool to speed up tests54 });55};5657describe('app-promotions.stake extrinsic', () => {39describe('App promotion', () => {58 before(async function () {40 before(async function () {59 await beforeEach(this);41 await usingPlaygrounds(async (helper, privateKey) => {42 if (!getModuleNames(helper.api!).includes(Pallets.AppPromotion)) this.skip();43 alice = privateKey('//Alice');44 palletAdmin = privateKey('//Charlie'); // TODO use custom address45 await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));46 nominal = helper.balance.getOneTokenNominal();47 await helper.balance.transferToSubstrate(alice, palletAdmin.address, 1000n * nominal);48 await helper.balance.transferToSubstrate(alice, palletAddress, 1000n * nominal);49 accounts = await helper.arrange.createCrowd(100, 1000n, alice); // create accounts-pool to speed up tests50 });60 });51 });615262 it('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async () => {53 describe('stake extrinsic', () => { 63 await usingPlaygrounds(async (helper) => {54 itSub('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {64 const [staker, recepient] = [accounts.pop()!, accounts.pop()!];55 const [staker, recepient] = [accounts.pop()!, accounts.pop()!];65 const totalStakedBefore = await helper.staking.getTotalStaked();56 const totalStakedBefore = await helper.staking.getTotalStaked();6657 67 // Minimum stake amount is 100:58 // Minimum stake amount is 100:68 await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.eventually.rejected;59 await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;69 await helper.staking.stake(staker, 100n * nominal);60 await helper.staking.stake(staker, 100n * nominal);7061 71 // Staker balance is: miscFrozen: 100, feeFrozen: 100, reserved: 0n...62 // Staker balance is: miscFrozen: 100, feeFrozen: 100, reserved: 0n...72 // ...so he can not transfer 90063 // ...so he can not transfer 90073 expect (await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});64 expect (await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});74 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejected;65 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');75 66 76 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);67 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);77 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);68 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);78 // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo? 69 // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo? 79 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased 70 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased 8071 81 72 82 await helper.staking.stake(staker, 200n * nominal);73 await helper.staking.stake(staker, 200n * nominal);83 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);74 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);84 expect((await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map((x) => x[1])).to.be.deep.equal([100n * nominal, 200n * nominal]);75 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});76 expect(totalStakedPerBlock[0].amount).to.equal(100n * nominal);77 expect(totalStakedPerBlock[1].amount).to.equal(200n * nominal);85 });78 });86 });79 8788 it('should allow to create maximum 10 stakes for account', async () => {80 itSub('should allow to create maximum 10 stakes for account', async ({helper}) => {89 await usingPlaygrounds(async (helper) => {90 const [staker] = await helper.arrange.createAccounts([2000n], alice);81 const [staker] = await helper.arrange.createAccounts([2000n], alice);91 for (let i = 0; i < 10; i++) {82 for (let i = 0; i < 10; i++) {92 await helper.staking.stake(staker, 100n * nominal);83 await helper.staking.stake(staker, 100n * nominal);93 }84 }9485 95 // can have 10 stakes86 // can have 10 stakes96 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);87 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);97 expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);88 expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);9889 99 await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejected;90 await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');10091 101 // After unstake can stake again92 // After unstake can stake again102 await helper.staking.unstake(staker);93 await helper.staking.unstake(staker);103 await helper.staking.stake(staker, 100n * nominal);94 await helper.staking.stake(staker, 100n * nominal);104 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);95 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);105 });96 });106 });97 107 108 it('should reject transaction if stake amount is more than total free balance minus frozen', async () => {98 itSub('should reject transaction if stake amount is more than total free balance minus frozen', async ({helper}) => {109 await usingPlaygrounds(async helper => { 110 const staker = accounts.pop()!;99 const staker = accounts.pop()!;111100 112 // Can't stake full balance because Alice needs to pay some fee101 // Can't stake full balance because Alice needs to pay some fee113 await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.eventually.rejected;102 await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected;114 await helper.staking.stake(staker, 500n * nominal);103 await helper.staking.stake(staker, 500n * nominal);115104 116 // Can't stake 500 tkn because Alice has Less than 500 transferable;105 // Can't stake 500 tkn because Alice has Less than 500 transferable;117 await expect(helper.staking.stake(staker, 500n * nominal)).to.be.eventually.rejected; 106 await expect(helper.staking.stake(staker, 500n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions'); 118 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);107 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);119 });108 });120 });109 121 122 it('for different accounts in one block is possible', async () => {110 itSub('for different accounts in one block is possible', async ({helper}) => {123 await usingPlaygrounds(async helper => {124 const crowd = [accounts.pop()!, accounts.pop()!, accounts.pop()!, accounts.pop()!];111 const crowd = [accounts.pop()!, accounts.pop()!, accounts.pop()!, accounts.pop()!];125 112 126 const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));113 const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));127 await expect(Promise.all(crowdStartsToStake)).to.be.eventually.fulfilled;114 await expect(Promise.all(crowdStartsToStake)).to.be.fulfilled;128115 129 const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));116 const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));130 expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);117 expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);131 });118 });132 });119 });133});120 134135describe('unstake balance extrinsic', () => { 121 describe('unstake extrinsic', () => { 136 before(async function () {122 itSub('should change balance state from "frozen" to "reserved", add it to "pendingUnstake" map, and subtract it from totalStaked', async ({helper}) => {137 await beforeEach(this);138 });139140 it('should change balance state from "frozen" to "reserved", add it to "pendingUnstake" map, and subtract it from totalStaked', async () => {141 await usingPlaygrounds(async helper => {142 const [staker, recepient] = [accounts.pop()!, accounts.pop()!];123 const [staker, recepient] = [accounts.pop()!, accounts.pop()!];143 const totalStakedBefore = await helper.staking.getTotalStaked();124 const totalStakedBefore = await helper.staking.getTotalStaked();144 await helper.staking.stake(staker, 900n * nominal);125 await helper.staking.stake(staker, 900n * nominal);145 await helper.staking.unstake(staker);126 await helper.staking.unstake(staker);146127 147 // Right after unstake balance is reserved128 // Right after unstake balance is reserved148 // Staker can not transfer 129 // Staker can not transfer 149 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 900n * nominal, miscFrozen: 0n, feeFrozen: 0n});130 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 900n * nominal, miscFrozen: 0n, feeFrozen: 0n});150 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejected;131 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.InsufficientBalance');151 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(900n * nominal);132 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(900n * nominal);152 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);133 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);153 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);134 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);154 });135 });155 });136 156157 it('should unlock balance after unlocking period ends and remove it from "pendingUnstake"', async () => {137 itSub('should unlock balance after unlocking period ends and remove it from "pendingUnstake"', async ({helper}) => {158 await usingPlaygrounds(async (helper) => {159 const staker = accounts.pop()!;138 const staker = accounts.pop()!;160 await helper.staking.stake(staker, 100n * nominal);139 await helper.staking.stake(staker, 100n * nominal);161 await helper.staking.unstake(staker);140 await helper.staking.unstake(staker);162 const unstakedInBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address}))[0][0];141 const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});163142 164 // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n143 // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n165 await helper.wait.forParachainBlockNumber(unstakedInBlock);144 await helper.wait.forParachainBlockNumber(pendingUnstake.block);166 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});145 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});167 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);146 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);168147 169 // staker can transfer:148 // staker can transfer:170 await helper.balance.transferToSubstrate(staker, alice.address, 998n * nominal);149 await helper.balance.transferToSubstrate(staker, alice.address, 998n * nominal);171 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);150 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);172 });151 });173 });152 174175 it('should successfully unstake multiple stakes', async () => {153 itSub('should successfully unstake multiple stakes', async ({helper}) => {176 await usingPlaygrounds(async helper => {177 const staker = accounts.pop()!;154 const staker = accounts.pop()!;178 await helper.staking.stake(staker, 100n * nominal);155 await helper.staking.stake(staker, 100n * nominal);179 await helper.staking.stake(staker, 200n * nominal);156 await helper.staking.stake(staker, 200n * nominal);180 await helper.staking.stake(staker, 300n * nominal);157 await helper.staking.stake(staker, 300n * nominal);181158 182 // staked: [100, 200, 300]; unstaked: 0159 // staked: [100, 200, 300]; unstaked: 0183 let pendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});160 let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});184 let unstakedPerBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).map(stake => stake[1]);161 let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});185 let stakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(stake => stake[1]);162 let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});186 expect(pendingUnstake).to.be.deep.equal(0n);163 expect(totalPendingUnstake).to.be.deep.equal(0n);187 expect(unstakedPerBlock).to.be.deep.equal([]);164 expect(pendingUnstake).to.be.deep.equal([]);188 expect(stakedPerBlock).to.be.deep.equal([100n * nominal, 200n * nominal, 300n * nominal]);165 expect(stakes[0].amount).to.equal(100n * nominal);166 expect(stakes[1].amount).to.equal(200n * nominal);167 expect(stakes[2].amount).to.equal(300n * nominal);189 168 190 // Can unstake multiple stakes169 // Can unstake multiple stakes191 await helper.staking.unstake(staker);170 await helper.staking.unstake(staker);192 const unstakingBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address}))[0][0];171 pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});193 pendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});172 totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});194 unstakedPerBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).map(stake => stake[1]);173 stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});195 stakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(stake => stake[1]);196 expect(pendingUnstake).to.be.equal(600n * nominal);174 expect(totalPendingUnstake).to.be.equal(600n * nominal);197 expect(stakedPerBlock).to.be.deep.equal([]);175 expect(stakes).to.be.deep.equal([]);198 expect(unstakedPerBlock).to.be.deep.equal([600n * nominal]);176 expect(pendingUnstake[0].amount).to.equal(600n * nominal);199177 200 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 600n * nominal, feeFrozen: 0n, miscFrozen: 0n});178 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 600n * nominal, feeFrozen: 0n, miscFrozen: 0n});201 await helper.wait.forParachainBlockNumber(unstakingBlock);179 await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);202 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});180 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});203 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);181 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);204 });182 });205 });183 206207 it('should not have any effects if no active stakes', async () => {184 itSub('should not have any effects if no active stakes', async ({helper}) => {208 await usingPlaygrounds(async (helper) => {209 const staker = accounts.pop()!;185 const staker = accounts.pop()!;210 186 211 // unstake has no effect if no stakes at all187 // unstake has no effect if no stakes at all212 await helper.staking.unstake(staker);188 await helper.staking.unstake(staker);213 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);189 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);214 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper190 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper215191 216 // TODO stake() unstake() waitUnstaked() unstake();192 // TODO stake() unstake() waitUnstaked() unstake();217193 218 // can't unstake if there are only pendingUnstakes194 // can't unstake if there are only pendingUnstakes219 await helper.staking.stake(staker, 100n * nominal);195 await helper.staking.stake(staker, 100n * nominal);220 await helper.staking.unstake(staker);196 await helper.staking.unstake(staker);221 await helper.staking.unstake(staker);197 await helper.staking.unstake(staker);222198 223 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);199 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);224 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);200 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);225 });201 });226 });202 227228 it('should keep different unlocking block for each unlocking stake', async () => {203 itSub('should keep different unlocking block for each unlocking stake', async ({helper}) => {229 await usingPlaygrounds(async (helper) => {230 const staker = accounts.pop()!;204 const staker = accounts.pop()!;231 await helper.staking.stake(staker, 100n * nominal);205 await helper.staking.stake(staker, 100n * nominal);232 await helper.staking.unstake(staker);206 await helper.staking.unstake(staker);233 await helper.staking.stake(staker, 120n * nominal);207 await helper.staking.stake(staker, 120n * nominal);234 await helper.staking.unstake(staker);208 await helper.staking.unstake(staker);235209 236 const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});210 const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});237 expect(unstakingPerBlock).has.length(2);211 expect(unstakingPerBlock).has.length(2);238 expect(unstakingPerBlock[0][1]).to.equal(100n * nominal);212 expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);239 expect(unstakingPerBlock[1][1]).to.equal(120n * nominal);213 expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);240 });214 });241 });215 242243 it('should be possible for different accounts in one block', async () => {216 itSub('should be possible for different accounts in one block', async ({helper}) => {244 await usingPlaygrounds(async (helper) => {245 const stakers = [accounts.pop()!, accounts.pop()!, accounts.pop()!];217 const stakers = [accounts.pop()!, accounts.pop()!, accounts.pop()!];246218 247 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));219 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));248 await Promise.all(stakers.map(staker => helper.staking.unstake(staker)));220 await Promise.all(stakers.map(staker => helper.staking.unstake(staker)));249221 250 await Promise.all(stakers.map(async (staker) => {222 await Promise.all(stakers.map(async (staker) => {251 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);223 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);252 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);224 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);253 }));225 }));254 });226 });255 });227 });256});228 257258describe('Admin adress', () => {229 describe('admin adress', () => {259 before(async function () {230 itSub('can be set by sudo only', async ({helper}) => {260 await beforeEach(this);261 });262263 it('can be set by sudo only', async () => {264 await usingPlaygrounds(async (helper) => {265 const nonAdmin = accounts.pop()!;231 const nonAdmin = accounts.pop()!;266 // nonAdmin can not set admin not from himself nor as a sudo232 // nonAdmin can not set admin not from himself nor as a sudo267 await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.eventually.rejected;233 await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.rejected;268 await expect(helper.signTransaction(nonAdmin, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.eventually.rejected;234 await expect(helper.signTransaction(nonAdmin, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.rejected;269235 270 // Alice can236 // Alice can271 await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.eventually.fulfilled;237 await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;272 });238 });273 });239 274 275 it('can be any valid CrossAccountId', async () => {240 itSub('can be any valid CrossAccountId', async ({helper}) => {276 // We are not going to set an eth address as a sponsor,241 // We are not going to set an eth address as a sponsor,277 // but we do want to check, it doesn't break anything;242 // but we do want to check, it doesn't break anything;278 await usingPlaygrounds(async (helper) => {279 const account = accounts.pop()!;243 const account = accounts.pop()!;280 const ethAccount = helper.address.substrateToEth(account.address); 244 const ethAccount = helper.address.substrateToEth(account.address); 281 // Alice sets Ethereum address as a sudo. Then Substrate address back...245 // Alice sets Ethereum address as a sudo. Then Substrate address back...282 await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.eventually.fulfilled;246 await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.fulfilled;283 await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.eventually.fulfilled;247 await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;284 248 285 // ...It doesn't break anything;249 // ...It doesn't break anything;286 const collection = await helper.nft.mintCollection(account, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});250 const collection = await helper.nft.mintCollection(account, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});287 await expect(helper.signTransaction(account, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;251 await expect(helper.signTransaction(account, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;288 });252 });289 });253 290291 it('can be reassigned', async () => {254 itSub('can be reassigned', async ({helper}) => {292 await usingPlaygrounds(async (helper) => {293 const [oldAdmin, newAdmin, collectionOwner] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];255 const [oldAdmin, newAdmin, collectionOwner] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];294 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});256 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});295 257 296 await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(oldAdmin))))).to.be.eventually.fulfilled;258 await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(oldAdmin))))).to.be.fulfilled;297 await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(newAdmin))))).to.be.eventually.fulfilled;259 await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(newAdmin))))).to.be.fulfilled;298 await expect(helper.signTransaction(oldAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;260 await expect(helper.signTransaction(oldAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;299 261 300 await expect(helper.signTransaction(newAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.fulfilled;262 await expect(helper.signTransaction(newAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;301 });263 });302 });264 });303});265 304305describe('App-promotion collection sponsoring', () => {266 describe('collection sponsoring', () => {306 before(async function () {267 before(async function () {307 await beforeEach(this);268 await usingPlaygrounds(async (helper) => {308 await usingPlaygrounds(async (helper) => {309 const tx = helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address}));269 const tx = helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address}));310 await helper.signTransaction(alice, tx);270 await helper.signTransaction(alice, tx);271 });311 });272 });312 });273 313314 it('should actually sponsor transactions', async () => {274 itSub('should actually sponsor transactions', async ({helper}) => {315 await usingPlaygrounds(async (helper) => {316 const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];275 const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];317 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});276 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});318 const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});277 const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});319 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));278 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));320 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);279 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);321280 322 await token.transfer(tokenSender, {Substrate: receiver.address});281 await token.transfer(tokenSender, {Substrate: receiver.address});323 expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});282 expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});324 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);283 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);325284 326 // senders balance the same, transaction has sponsored285 // senders balance the same, transaction has sponsored327 expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);286 expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);328 expect (palletBalanceBefore > palletBalanceAfter).to.be.true;287 expect (palletBalanceBefore > palletBalanceAfter).to.be.true;329 });288 });330 });289 331332 it('can not be set by non admin', async () => {290 itSub('can not be set by non admin', async ({helper}) => {333 await usingPlaygrounds(async (helper) => {334 const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];291 const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];335292 336 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});293 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});337 294 338 await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;295 await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;339 expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');296 expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');340 });297 });341 });298 342343 it('should set pallet address as confirmed admin', async () => {299 itSub('should set pallet address as confirmed admin', async ({helper}) => {344 await usingPlaygrounds(async (helper) => {345 const [collectionOwner, oldSponsor] = [accounts.pop()!, accounts.pop()!];300 const [collectionOwner, oldSponsor] = [accounts.pop()!, accounts.pop()!];346 301 347 // Can set sponsoring for collection without sponsor302 // Can set sponsoring for collection without sponsor348 const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});303 const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});349 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.eventually.fulfilled;304 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;350 expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});305 expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});351306 352 // Can set sponsoring for collection with unconfirmed sponsor307 // Can set sponsoring for collection with unconfirmed sponsor353 const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});308 const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});354 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});309 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});355 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.eventually.fulfilled;310 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;356 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});311 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});357312 358 // Can set sponsoring for collection with confirmed sponsor313 // Can set sponsoring for collection with confirmed sponsor359 const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});314 const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});360 await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);315 await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);361 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.eventually.fulfilled;316 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;362 expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});317 expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});363 });318 });364 });319 365366 it('can be overwritten by collection owner', async () => { 320 itSub('can be overwritten by collection owner', async ({helper}) => { 367 await usingPlaygrounds(async (helper) => {368 const [collectionOwner, newSponsor] = [accounts.pop()!, accounts.pop()!];321 const [collectionOwner, newSponsor] = [accounts.pop()!, accounts.pop()!];369 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});322 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});370 const collectionId = collection.collectionId;323 const collectionId = collection.collectionId;371 324 372 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionId))).to.be.eventually.fulfilled;325 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;373 326 374 // Collection limits still can be changed by the owner327 // Collection limits still can be changed by the owner375 expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;328 expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;376 expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);329 expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);377 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});330 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});378331 379 // Collection sponsor can be changed too332 // Collection sponsor can be changed too380 expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;333 expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;381 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});334 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});382 });335 });383 });336 384 385 it('should not overwrite collection limits set by the owner earlier', async () => {337 itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {386 await usingPlaygrounds(async (helper) => {387 const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};338 const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};388 const collectionWithLimits = await helper.nft.mintCollection(alice, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});339 const collectionWithLimits = await helper.nft.mintCollection(alice, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});389340 390 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.eventually.fulfilled;341 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;391 expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);342 expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);392 });343 });393 });344 394 395 it('should reject transaction if collection doesn\'t exist', async () => {345 itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {396 await usingPlaygrounds(async (helper) => {397 const collectionOwner = accounts.pop()!;346 const collectionOwner = accounts.pop()!;398 347 399 // collection has never existed348 // collection has never existed400 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(999999999))).to.be.eventually.rejected;349 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;401 // collection has been burned350 // collection has been burned402 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});351 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});403 await collection.burn(collectionOwner);352 await collection.burn(collectionOwner);404353 405 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;354 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;406 });355 });407 });356 });408});357 409410describe('app-promotion stopSponsoringCollection', () => {358 describe('stopSponsoringCollection', () => {411 before(async function () {359 itSub('can not be called by non-admin', async ({helper}) => { 412 await beforeEach(this);413 });414415 it('can not be called by non-admin', async () => { 416 await usingPlaygrounds(async (helper) => {417 const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];360 const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];418 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});361 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});419 362 420 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.fulfilled;363 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;421 364 422 await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;365 await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;423 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});366 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});424 });367 });425 });368 426427 it('should set sponsoring as disabled', async () => {369 itSub('should set sponsoring as disabled', async ({helper}) => {428 await usingPlaygrounds(async (helper) => {429 const [collectionOwner, recepient] = [accounts.pop()!, accounts.pop()!];370 const [collectionOwner, recepient] = [accounts.pop()!, accounts.pop()!];430 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});371 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});431 const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});372 const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});432 373 433 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));374 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));434 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId));375 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId));435 376 436 expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');377 expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');437378 438 // Transactions are not sponsored anymore:379 // Transactions are not sponsored anymore:439 const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);380 const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);440 await token.transfer(collectionOwner, {Substrate: recepient.address});381 await token.transfer(collectionOwner, {Substrate: recepient.address});441 const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);382 const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);442 expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);383 expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);443 });384 });444 });385 445446 it('should not affect collection which is not sponsored by pallete', async () => {386 itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {447 await usingPlaygrounds(async (helper) => {448 const collectionOwner = accounts.pop()!;387 const collectionOwner = accounts.pop()!;449 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});388 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});450 await collection.confirmSponsorship(collectionOwner);389 await collection.confirmSponsorship(collectionOwner);451 390 452 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;391 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;453 392 454 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});393 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});455 });394 });456 });395 457458 it('should reject transaction if collection does not exist', async () => { 396 itSub('should reject transaction if collection does not exist', async ({helper}) => { 459 await usingPlaygrounds(async (helper) => {460 const collectionOwner = accounts.pop()!;397 const collectionOwner = accounts.pop()!;461 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});398 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});462 399 463 await collection.burn(collectionOwner);400 await collection.burn(collectionOwner);464 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;401 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');465 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(999999999))).to.be.eventually.rejected;402 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');466 });403 });467 });404 });468});405 469470describe('app-promotion contract sponsoring', () => {406 describe('contract sponsoring', () => {471 before(async function () {407 itEth('should set palletes address as a sponsor', async ({helper}) => {472 await beforeEach(this);473 });474475 itWeb3('should set palletes address as a sponsor', async ({api, web3, privateKeyWrapper}) => {476 await usingPlaygrounds(async (helper) => {408 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();477 const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();478 const flipper = await deployFlipper(web3, contractOwner);409 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);479 const contractMethods = contractHelpers(web3, contractOwner);410 const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);480411 481 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));412 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);482 413 483 expect(await contractMethods.methods.hasSponsor(flipper.options.address).call()).to.be.true; 414 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true; 484 expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner); 415 expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner); 485 expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({416 expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({486 confirmed: {417 confirmed: {487 substrate: palletAddress,418 substrate: palletAddress,488 },419 },489 });420 });490 });421 });491 });422 492493 itWeb3('should overwrite sponsoring mode and existed sponsor', async ({api, web3, privateKeyWrapper}) => {423 itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {494 await usingPlaygrounds(async (helper) => {424 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();495 const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();496 const flipper = await deployFlipper(web3, contractOwner);425 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);497 const contractMethods = contractHelpers(web3, contractOwner);426 const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);498427 499 await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;428 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;500429 501 // Contract is self sponsored430 // Contract is self sponsored502 expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.be.deep.equal({431 expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.be.deep.equal({503 confirmed: {432 confirmed: {504 ethereum: flipper.options.address.toLowerCase(),433 ethereum: flipper.options.address.toLowerCase(),505 },434 },506 });435 });507436 508 // set promotion sponsoring437 // set promotion sponsoring509 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));438 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);510439 511 // new sponsor is pallet address440 // new sponsor is pallet address512 expect(await contractMethods.methods.hasSponsor(flipper.options.address).call()).to.be.true; 441 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true; 513 expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner); 442 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner); 514 expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({443 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({515 confirmed: {444 confirmed: {516 substrate: palletAddress,445 substrate: palletAddress,517 },446 },518 });447 });519 });448 });520 });449 521522 itWeb3('can be overwritten by contract owner', async ({api, web3, privateKeyWrapper}) => {450 itEth('can be overwritten by contract owner', async ({helper}) => {523 await usingPlaygrounds(async (helper) => { 451 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();524 const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();525 const flipper = await deployFlipper(web3, contractOwner);452 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);526 const contractMethods = contractHelpers(web3, contractOwner);453 const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);527454 528 // contract sponsored by pallet455 // contract sponsored by pallet529 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));456 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);530457 531 // owner sets self sponsoring458 // owner sets self sponsoring532 await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;459 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;533460 534 expect(await contractMethods.methods.hasSponsor(flipper.options.address).call()).to.be.true; 461 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true; 535 expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner); 462 expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner); 536 expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({463 expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({537 confirmed: {464 confirmed: {538 ethereum: flipper.options.address.toLowerCase(),465 ethereum: flipper.options.address.toLowerCase(),539 },466 },540 });467 });541 });468 });542 });469 543544 itWeb3('can not be set by non admin', async ({api, web3, privateKeyWrapper}) => {470 itEth('can not be set by non admin', async ({helper}) => {545 await usingPlaygrounds(async (helper) => { 546 const nonAdmin = accounts.pop()!;471 const nonAdmin = accounts.pop()!;547 const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();472 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();548 const flipper = await deployFlipper(web3, contractOwner);473 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);549 const contractMethods = contractHelpers(web3, contractOwner);474 const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);550475 551 await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;476 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;552477 553 // nonAdmin calls sponsorContract478 // nonAdmin calls sponsorContract554 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address))).to.be.rejected;479 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');555480 556 // contract still self-sponsored 481 // contract still self-sponsored 557 expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({482 expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({558 confirmed: {483 confirmed: {559 ethereum: flipper.options.address.toLowerCase(),484 ethereum: flipper.options.address.toLowerCase(),560 },485 },561 });486 });562 });487 });563488 564 itWeb3('should be rejected for non-contract address', async ({api, web3, privateKeyWrapper}) => {489 itEth('should actually sponsor transactions', async ({helper}) => {565 await usingPlaygrounds(async (helper) => {490 // Contract caller566567 });491 const caller = await helper.eth.createAccountWithBalance(alice, 1000n);568 });569 });570571 itWeb3('should actually sponsor transactions', async ({api, web3, privateKeyWrapper}) => {492 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);572 await usingPlaygrounds(async (helper) => { 493 573 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);494 // Deploy flipper574 const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();495 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();575 const flipper = await deployFlipper(web3, contractOwner);496 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);576 const contractHelper = contractHelpers(web3, contractOwner);497 const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);498 499 // Owner sets to sponsor every tx577 await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});500 await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});578 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});501 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});579 await transferBalanceToEth(api, alice, flipper.options.address, 1000n);502 await helper.eth.transferBalanceFromSubstrate(alice, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);580503 581 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));504 // Set promotion to the Flipper505 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorContract(flipper.options.address));506 507 // Caller calls Flipper582 await flipper.methods.flip().send({from: caller});508 await flipper.methods.flip().send({from: caller});583 expect(await flipper.methods.getValue().call()).to.be.true;509 expect(await flipper.methods.getValue().call()).to.be.true;584510 511 // The contracts and caller balances have not changed585 const callerBalance = await helper.balance.getEthereum(caller);512 const callerBalance = await helper.balance.getEthereum(caller);586 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);513 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);587588 expect(callerBalance).to.be.equal(1000n * nominal);514 expect(callerBalance).to.be.equal(1000n * nominal);589 expect(1000n * nominal > contractBalanceAfter).to.be.true;515 expect(1000n * nominal === contractBalanceAfter).to.be.true;516 517 // The pallet balance has decreased518 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);519 expect(palletBalanceAfter < palletBalanceBefore).to.be.true;590 });520 });591 });521 });592});522 593594describe('app-promotion stopSponsoringContract', () => { 523 describe('stopSponsoringContract', () => { 595 before(async function () {524 itEth('should remove pallet address from contract sponsors', async ({helper}) => {596 await beforeEach(this);597 });598599 itWeb3('should remove pallet address from contract sponsors', async ({api, web3, privateKeyWrapper}) => {600 await usingPlaygrounds(async (helper) => { 525 const caller = await helper.eth.createAccountWithBalance(alice, 1000n);601 const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);602 const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();526 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();603 const flipper = await deployFlipper(web3, contractOwner);527 const flipper = await helper.eth.deployFlipper(contractOwner);604 await transferBalanceToEth(api, alice, flipper.options.address);528 await helper.eth.transferBalanceFromSubstrate(alice, flipper.options.address);605 const contractHelper = contractHelpers(web3, contractOwner);529 const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);530 606 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});531 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});607 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));532 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);608 await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringContract(flipper.options.address));533 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);609534 610 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false; 535 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false; 611 expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner); 536 expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner); 612 expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({537 expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({613 disabled: null,538 disabled: null,614 });539 });615540 616 await flipper.methods.flip().send({from: caller});541 await flipper.methods.flip().send({from: caller});617 expect(await flipper.methods.getValue().call()).to.be.true;542 expect(await flipper.methods.getValue().call()).to.be.true;618543 619 const callerBalance = await helper.balance.getEthereum(caller);544 const callerBalance = await helper.balance.getEthereum(caller);620 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);545 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);621546 622 // caller payed for call547 // caller payed for call623 expect(1000n * nominal > callerBalance).to.be.true;548 expect(1000n * nominal > callerBalance).to.be.true;624 expect(contractBalanceAfter).to.be.equal(1000n * nominal);549 expect(contractBalanceAfter).to.be.equal(1000n * nominal);625 });550 });626 });551 627628 itWeb3('can not be called by non-admin', async ({api, web3, privateKeyWrapper}) => {552 itEth('can not be called by non-admin', async ({helper}) => {629 await usingPlaygrounds(async (helper) => { 630 const nonAdmin = accounts.pop()!;553 const nonAdmin = accounts.pop()!;631 const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();554 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();632 const flipper = await deployFlipper(web3, contractOwner);555 const flipper = await helper.eth.deployFlipper(contractOwner);633556 634 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));557 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);635 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringContract(flipper.options.address))).to.be.rejected;558 const stopSponsoringResult = await helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]);559 expect(stopSponsoringResult.status).to.equal('Fail');560 expect(stopSponsoringResult.moduleError).to.equal('appPromotion.NoPermission');636 });561 });637 });562 638639 itWeb3('should not affect a contract which is not sponsored by pallete', async ({api, web3, privateKeyWrapper}) => {563 itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {640 await usingPlaygrounds(async (helper) => { 641 const nonAdmin = accounts.pop()!;564 const nonAdmin = accounts.pop()!;642 const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();565 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();643 const flipper = await deployFlipper(web3, contractOwner);566 const flipper = await helper.eth.deployFlipper(contractOwner);644 const contractHelper = contractHelpers(web3, contractOwner);567 const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);645 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;568 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;646569 647 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringContract(flipper.options.address))).to.be.rejected;570 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');648 });571 });649 });572 });650});573 651652describe('app-promotion rewards', () => {574 describe('rewards', () => {653 before(async function () {575 itSub('can not be called by non admin', async ({helper}) => {654 await beforeEach(this);655 });656657 it('can not be called by non admin', async () => {658 await usingPlaygrounds(async (helper) => {659 const nonAdmin = accounts.pop()!;576 const nonAdmin = accounts.pop()!;660 await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.payoutStakers(100))).to.be.rejected;577 await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');661 });578 });662 });579 663664 it('should increase total staked', async() => {580 itSub('should increase total staked', async ({helper}) => {665 await usingPlaygrounds(async (helper) => {666 const staker = accounts.pop()!;581 const staker = accounts.pop()!;667 const totalStakedBefore = await helper.staking.getTotalStaked();582 const totalStakedBefore = await helper.staking.getTotalStaked();668 await helper.staking.stake(staker, 100n * nominal);583 await helper.staking.stake(staker, 100n * nominal);669584 670 // Wait for rewards and pay585 // Wait for rewards and pay671 const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[0][0];586 const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});672 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock));587 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));673 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));588 const totalPayout = (await helper.admin.payoutStakers(palletAdmin, 100)).reduce((prev, payout) => prev + payout.payout, 0n);674589 675 const totalStakedAfter = await helper.staking.getTotalStaked();590 const totalStakedAfter = await helper.staking.getTotalStaked();676 expect(totalStakedAfter >= totalStakedBefore + calculateIncome(100n * nominal, 10n)).to.be.true;591 expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);677678 // staker can unstake592 // staker can unstake679 await helper.staking.unstake(staker);593 await helper.staking.unstake(staker);680 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal, 10n));594 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal, 10n));681 });595 });682 });596 683684 it('should credit 0.05% for staking period', async () => { 597 itSub('should credit 0.05% for staking period', async ({helper}) => { 685 await usingPlaygrounds(async helper => {686 const staker = accounts.pop()!;598 const staker = accounts.pop()!;687599 688 await waitPromotionPeriodDoesntEnd(helper);600 await waitPromotionPeriodDoesntEnd(helper);689 601 690 await helper.staking.stake(staker, 100n * nominal);602 await helper.staking.stake(staker, 100n * nominal);691 await helper.staking.stake(staker, 200n * nominal);603 await helper.staking.stake(staker, 200n * nominal);692604 693 // wait rewards are available:605 // wait rewards are available:694 const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[1][0];606 const [_, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});695 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock));607 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));696608 697 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));609 const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)?.payout;698610 expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal, 10n));611 699 const totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);612 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});700 expect(totalStakedPerBlock).to.be.deep.equal([calculateIncome(100n * nominal, 10n), calculateIncome(200n * nominal, 10n)]);613 expect(totalStakedPerBlock[0].amount).to.equal(calculateIncome(100n * nominal, 10n));614 expect(totalStakedPerBlock[1].amount).to.equal(calculateIncome(200n * nominal, 10n));701 });615 });702 });616 703704 it('shoud be paid for more than one period if payments was missed', async () => {617 itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {705 await usingPlaygrounds(async (helper) => {706 const staker = accounts.pop()!;618 const staker = accounts.pop()!;707619 708 await helper.staking.stake(staker, 100n * nominal);620 await helper.staking.stake(staker, 100n * nominal);709 // wait for two rewards are available:621 // wait for two rewards are available:710 const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[0][0];622 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});711 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock) + LOCKING_PERIOD);623 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);712624 713 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));625 await helper.admin.payoutStakers(palletAdmin, 100);714 const stakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});626 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});715 const frozenBalanceShouldBe = calculateIncome(100n * nominal, 10n, 2);627 const frozenBalanceShouldBe = calculateIncome(100n * nominal, 10n, 2);716 expect(stakedPerBlock[0][1]).to.be.equal(frozenBalanceShouldBe);628 expect(stake.amount).to.be.equal(frozenBalanceShouldBe);717629 718 const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);630 const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);719631 720 expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});632 expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});721 });633 });722 });634 723 724 it('should not be credited for unstaked (reserved) balance', async () => {635 itSub('should not be credited for unstaked (reserved) balance', async ({helper}) => {725 await usingPlaygrounds(async helper => {726 // staker unstakes before rewards has been payed636 // staker unstakes before rewards has been payed727 const staker = accounts.pop()!;637 const staker = accounts.pop()!;728 await helper.staking.stake(staker, 100n * nominal);638 await helper.staking.stake(staker, 100n * nominal);729 const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[0][0];639 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});730 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock) + LOCKING_PERIOD);640 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);731 await helper.staking.unstake(staker);641 await helper.staking.unstake(staker);732 642 733 // so he did not receive any rewards643 // so he did not receive any rewards734 const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);644 const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);735 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));645 await helper.admin.payoutStakers(palletAdmin, 100);736 const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);646 const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);737647 738 expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);648 expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);739 });649 });740 });650 741 742 it('should bring compound interest', async () => {651 itSub('should bring compound interest', async ({helper}) => {743 await usingPlaygrounds(async helper => {744 const staker = accounts.pop()!;652 const staker = accounts.pop()!;745 653 746 await helper.staking.stake(staker, 100n * nominal);654 await helper.staking.stake(staker, 100n * nominal);747655 748 const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[0][0];656 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});749 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock));657 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));750 658 751 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));659 await helper.admin.payoutStakers(palletAdmin, 100);752 let totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);660 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});753 expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n)]);661 expect(stake.amount).to.equal(calculateIncome(100n * nominal, 10n));754 662 755 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock) + LOCKING_PERIOD);663 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);756 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));664 await helper.admin.payoutStakers(palletAdmin, 100);757 totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);665 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});758 expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n, 2)]); 666 expect(stake.amount).to.equal(calculateIncome(100n * nominal, 10n, 2));759 });667 });760 });668 761762 it.skip('can be paid 1000 rewards in a time', async () => {669 itSub.skip('can be paid 1000 rewards in a time', async ({helper}) => {763 // all other stakes should be unstaked670 // all other stakes should be unstaked764 await usingPlaygrounds(async (helper) => {765 const oneHundredStakers = await helper.arrange.createCrowd(100, 1050n, alice);671 const oneHundredStakers = await helper.arrange.createCrowd(100, 1050n, alice);766672 767 // stakers stakes 10 times each673 // stakers stakes 10 times each768 for (let i = 0; i < 10; i++) {674 for (let i = 0; i < 10; i++) {769 await Promise.all(oneHundredStakers.map(staker => helper.staking.stake(staker, 100n * nominal)));675 await Promise.all(oneHundredStakers.map(staker => helper.staking.stake(staker, 100n * nominal)));770 }676 }771 await helper.wait.newBlocks(40);677 await helper.wait.newBlocks(40);772 const result = await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));678 await helper.admin.payoutStakers(palletAdmin, 100);773 });679 });774 });680 775776 it.skip('can handle 40.000 rewards', async () => {681 itSub.skip('can handle 40.000 rewards', async ({helper}) => {777 await usingPlaygrounds(async (helper) => {778 const [donor] = await helper.arrange.createAccounts([7_000_000n], alice);682 const [donor] = await helper.arrange.createAccounts([7_000_000n], alice);779 const crowdStakes = async () => {683 const crowdStakes = async () => {780 // each account in the crowd stakes 2 times684 // each account in the crowd stakes 2 times783 await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));687 await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));784 // 688 // 785 };689 };786690 787 for (let i = 0; i < 40; i++) {691 for (let i = 0; i < 40; i++) {788 await crowdStakes();692 await crowdStakes();789 }693 }790694 791 // TODO pay rewards for some period695 // TODO pay rewards for some period792 });696 });793 });697 });tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -198,8 +198,24 @@
}
`);
}
-}
-
+
+ async deployFlipper(signer: string): Promise<Contract> {
+ return await this.helper.ethContract.deployByCode(signer, 'Flipper', `
+ // SPDX-License-Identifier: UNLICENSED
+ pragma solidity ^0.8.6;
+
+ contract Flipper {
+ bool value = false;
+ function flip() public {
+ value = !value;
+ }
+ function getValue() public view returns (bool) {
+ return value;
+ }
+ }
+ `);
+ }
+}
class EthAddressGroup extends EthGroupBase {
extractCollectionId(address: string): number {
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -147,6 +147,11 @@
feeFrozen: bigint
}
+export interface IStakingInfo {
+ block: bigint,
+ amount: bigint,
+}
+
export type TSubstrateAccount = string;
export type TEthereumAccount = string;
export type TApiAllowedListeners = 'connected' | 'disconnected' | 'error' | 'ready' | 'decorated';
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -60,11 +60,13 @@
*/
arrange: ArrangeGroup;
wait: WaitGroup;
+ admin: AdminGroup;
constructor(logger: { log: (msg: any, level: any) => void, level: any }) {
super(logger);
this.arrange = new ArrangeGroup(this);
this.wait = new WaitGroup(this);
+ this.admin = new AdminGroup(this);
}
async connect(wsEndpoint: string, _listeners?: any): Promise<void> {
@@ -120,6 +122,7 @@
*/
createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {
let nonce = await this.helper.chain.getNonce(donor.address);
+ const wait = new WaitGroup(this.helper);
const ss58Format = this.helper.chain.getChainProperties().ss58Format;
const tokenNominal = this.helper.balance.getOneTokenNominal();
const transactions = [];
@@ -154,7 +157,7 @@
for (let index = 0; index < 5; index++) {
accountsCreated = await checkBalances();
if(accountsCreated) break;
-
+ await wait.newBlocks(1);
}
if (!accountsCreated) throw Error('Accounts generation failed');
@@ -281,3 +284,22 @@
});
}
}
+
+class AdminGroup {
+ helper: UniqueHelper;
+
+ constructor(helper: UniqueHelper) {
+ this.helper = helper;
+ }
+
+ async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {
+ const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);
+ return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {
+ return {
+ staker: e.event.data[0].toString(),
+ stake: e.event.data[1].toBigInt(),
+ payout: e.event.data[2].toBigInt(),
+ };
+ });
+ }
+}
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -9,7 +9,7 @@
import {ApiInterfaceEvents} from '@polkadot/api/types';
import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';
import {IKeyringPair} from '@polkadot/types/types';
-import {IApiListeners, IBlock, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';
+import {IApiListeners, IBlock, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';
export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {
const address = {} as ICrossAccountId;
@@ -2029,21 +2029,54 @@
return 1;
}
+ /**
+ * Get total staked amount for address
+ * @param address substrate or ethereum address
+ * @returns total staked amount
+ */
async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {
if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();
return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();
}
- async getTotalStakedPerBlock(address: ICrossAccountId): Promise<bigint[][]> {
- return (await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);
+ /**
+ * Get total staked per block
+ * @param address substrate or ethereum address
+ * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block
+ */
+ async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {
+ const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);
+ return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {
+ return {
+ block: block.toBigInt(),
+ amount: amount.toBigInt(),
+ };
+ });
}
+ /**
+ * Get total pending unstake amount for address
+ * @param address substrate or ethereum address
+ * @returns total pending unstake amount
+ */
async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {
return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();
}
- async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<bigint[][]> {
- return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);
+ /**
+ * Get pending unstake amount per block for address
+ * @param address substrate or ethereum address
+ * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block
+ */
+ async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {
+ const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);
+ const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {
+ return {
+ block: block.toBigInt(),
+ amount: amount.toBigInt(),
+ };
+ });
+ return result;
}
}