git.delta.rocks / unique-network / refs/commits / 280815c7a88b

difftreelog

Merge pull request #592 from UniqueNetwork/test/app-promotion-refactor

Yaroslav Bolyukin2022-09-16parents: #3bbb454 #e8822f1.patch.diff
in: master
Test/app promotion refactor

10 files changed

modified.docker/Dockerfile-chain-devdiffbeforeafterboth
1FROM ubuntu:20.041FROM ubuntu:20.04
22
3ARG RUST_TOOLCHAIN=
4ARG FEATURE=
5
3ENV DEBIAN_FRONTEND=noninteractive6ENV DEBIAN_FRONTEND=noninteractive
4ENV TZ=Etc/UTC7ENV TZ=Etc/UTC
5
6RUN apt-get update && apt-get install -y git curl libssl-dev llvm pkg-config libclang-dev clang git make cmake8ENV FEATURE=$FEATURE
7
8ENV CARGO_HOME="/cargo-home"9ENV CARGO_HOME="/cargo-home"
9ENV PATH="/cargo-home/bin:$PATH"10ENV PATH="/cargo-home/bin:$PATH"
1011
11RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none12RUN echo "$FEATURE\n" && echo "$RUST_TOOLCHAIN\n"
1213
13ARG RUST_TOOLCHAIN=14RUN apt-get update && apt-get install -y git curl libssl-dev llvm pkg-config libclang-dev clang git make cmake
15
14ARG FEATURE=16RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
1517
16RUN rustup toolchain uninstall $(rustup toolchain list) && \18RUN rustup toolchain uninstall $(rustup toolchain list) && \
17 rustup toolchain install $RUST_TOOLCHAIN && \19 rustup toolchain install $RUST_TOOLCHAIN && \
24WORKDIR /dev_chain26WORKDIR /dev_chain
2527
26RUN cargo build --release28RUN cargo build --release
29RUN echo "$FEATURE"
2730
28CMD cargo run --release --features=$FEATURE -- --dev -linfo --unsafe-ws-external --rpc-cors=all --unsafe-rpc-external31CMD cargo run --release --features=$FEATURE -- --dev -linfo --unsafe-ws-external --rpc-cors=all --unsafe-rpc-external
2932
modified.docker/docker-compose.tmp-dev.j2diffbeforeafterboth
18 options:18 options:
19 max-size: "1m"19 max-size: "1m"
20 max-file: "3"20 max-file: "3"
21 command: cargo run --release --features=$FEATURE -- --dev -linfo --unsafe-ws-external --rpc-cors=all --unsafe-rpc-external21 command: cargo run --release --features={{ FEATURE }} -- --dev -linfo --unsafe-ws-external --rpc-cors=all --unsafe-rpc-external
2222
modified.github/workflows/dev-build-tests_v2.ymldiffbeforeafterboth
96 if: always() # run this step always96 if: always() # run this step always
97 run: docker-compose -f ".docker/docker-compose-dev.yaml" -f ".docker/docker-compose.${{ matrix.network }}.yml" down97 run: docker-compose -f ".docker/docker-compose-dev.yaml" -f ".docker/docker-compose.${{ matrix.network }}.yml" down
9898
99 - name: Remove builder cache
100 if: always() # run this step always
101 run: |
102 docker builder prune -f -a
103 docker system prune -f
104 docker image prune -f -a
modifiedtests/src/adminTransferAndBurn.test.tsdiffbeforeafterboth
2424
25let donor: IKeyringPair;25let donor: IKeyringPair;
26
27before(async () => {
28 await usingPlaygrounds(async (_, privateKey) => {
29 donor = privateKey('//Alice');
30 });
31});
3226
33describe('Integration Test: ownerCanTransfer allows admins to use only transferFrom/burnFrom:', () => {27describe('Integration Test: ownerCanTransfer allows admins to use only transferFrom/burnFrom:', () => {
34 let alice: IKeyringPair;28 let alice: IKeyringPair;
35 let bob: IKeyringPair;29 let bob: IKeyringPair;
36 let charlie: IKeyringPair;30 let charlie: IKeyringPair;
3731
38 before(async () => {32 before(async () => {
39 await usingPlaygrounds(async (helper) => {33 await usingPlaygrounds(async (helper, privateKey) => {
34 donor = privateKey('//Alice');
40 [alice, bob, charlie] = await helper.arrange.createAccounts([10n, 10n, 10n], donor);35 [alice, bob, charlie] = await helper.arrange.createAccounts([10n, 10n, 10n], donor);
41 });36 });
42 });37 });
modifiedtests/src/allowLists.test.tsdiffbeforeafterboth
2424
25let donor: IKeyringPair;25let donor: IKeyringPair;
26
27before(async () => {
28 await usingPlaygrounds(async (_, privateKey) => {
29 donor = privateKey('//Alice');
30 });
31});
3226
33let alice: IKeyringPair;27let alice: IKeyringPair;
34let bob: IKeyringPair;28let bob: IKeyringPair;
37describe('Integration Test ext. Allow list tests', () => {31describe('Integration Test ext. Allow list tests', () => {
3832
39 before(async () => {33 before(async () => {
40 await usingPlaygrounds(async (helper) => {34 await usingPlaygrounds(async (helper, privateKey) => {
35 donor = privateKey('//Alice');
41 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);36 [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
42 });37 });
43 });38 });
modifiedtests/src/app-promotion.test.tsdiffbeforeafterboth
20 getModuleNames,20 getModuleNames,
21 Pallets,21 Pallets,
22} from './util/helpers';22} from './util/helpers';
23
24import chai from 'chai';23import {itSub, usingPlaygrounds} from './util/playgrounds';
25import chaiAsPromised from 'chai-as-promised';
26import {usingPlaygrounds} from './util/playgrounds';
27
28import {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';
3429
35let 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 relay
41const UNLOCKING_PERIOD = 10n; // 20 blocks of parachain36const UNLOCKING_PERIOD = 10n; // 10 blocks of parachain
42const rewardAvailableInBlock = (stakedInBlock: bigint) => (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);37const rewardAvailableInBlock = (stakedInBlock: bigint) => (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);
4338
44const 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 address
49 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 tests
54 });
55};
56
57describe('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 address
45 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 tests
50 });
60 });51 });
6152
62 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 900
73 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
87
88 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 stakes
96 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 again
102 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 fee
113 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
134
135describe('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 });
139
140 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 reserved
148 // 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
156
157 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: 0n
165 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
174
175 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: 0
183 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 stakes
191 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
206
207 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 all
212 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 helper
215191
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 pendingUnstakes
219 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
227
228 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
242
243 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
257
258describe('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 });
262
263 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 sudo
267 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 can
271 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
290
291 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
304
305describe('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
313
314 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 sponsored
327 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
331
332 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
342
343 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 sponsor
348 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 sponsor
353 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 sponsor
359 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
365
366 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 owner
375 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 too
380 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 existed
400 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 burned
402 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
409
410describe('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 });
414
415 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
426
427 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
445
446 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
457
458 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
469
470describe('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 });
474
475 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
492
493 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 sponsored
502 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 sponsoring
509 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 address
512 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
521
522 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 pallet
529 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 sponsoring
532 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
543
544 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 sponsorContract
554 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 caller
566
567 });491 const caller = await helper.eth.createAccountWithBalance(alice, 1000n);
568 });
569 });
570
571 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 flipper
574 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 tx
577 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 Flipper
505 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorContract(flipper.options.address));
506
507 // Caller calls Flipper
582 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 changed
585 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);
587
588 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 decreased
518 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);
519 expect(palletBalanceAfter < palletBalanceBefore).to.be.true;
590 });520 });
591 });521 });
592});522
593
594describe('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 });
598
599 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 call
623 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
627
628 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
638
639 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
651
652describe('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 });
656
657 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
663
664 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 pay
671 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);
677
678 // staker can unstake592 // staker can unstake
679 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
683
684 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
703
704 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 payed
727 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 rewards
734 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
761
762 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 unstaked
764 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 each
768 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
775
776 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 times
783 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 period
792 });696 });
793 });697 });
modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
199 `);199 `);
200 }200 }
201
202 async deployFlipper(signer: string): Promise<Contract> {
203 return await this.helper.ethContract.deployByCode(signer, 'Flipper', `
204 // SPDX-License-Identifier: UNLICENSED
205 pragma solidity ^0.8.6;
206
207 contract Flipper {
208 bool value = false;
209 function flip() public {
210 value = !value;
211 }
212 function getValue() public view returns (bool) {
213 return value;
214 }
215 }
216 `);
217 }
201}218}
202 219
203
modifiedtests/src/util/playgrounds/types.tsdiffbeforeafterboth
147 feeFrozen: bigint147 feeFrozen: bigint
148}148}
149
150export interface IStakingInfo {
151 block: bigint,
152 amount: bigint,
153}
149154
150export type TSubstrateAccount = string;155export type TSubstrateAccount = string;
151export type TEthereumAccount = string;156export type TEthereumAccount = string;
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
60 */60 */
61 arrange: ArrangeGroup;61 arrange: ArrangeGroup;
62 wait: WaitGroup;62 wait: WaitGroup;
63 admin: AdminGroup;
6364
64 constructor(logger: { log: (msg: any, level: any) => void, level: any }) {65 constructor(logger: { log: (msg: any, level: any) => void, level: any }) {
65 super(logger);66 super(logger);
66 this.arrange = new ArrangeGroup(this);67 this.arrange = new ArrangeGroup(this);
67 this.wait = new WaitGroup(this);68 this.wait = new WaitGroup(this);
69 this.admin = new AdminGroup(this);
68 }70 }
6971
70 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {72 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {
120 */122 */
121 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {123 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {
122 let nonce = await this.helper.chain.getNonce(donor.address);124 let nonce = await this.helper.chain.getNonce(donor.address);
125 const wait = new WaitGroup(this.helper);
123 const ss58Format = this.helper.chain.getChainProperties().ss58Format;126 const ss58Format = this.helper.chain.getChainProperties().ss58Format;
124 const tokenNominal = this.helper.balance.getOneTokenNominal();127 const tokenNominal = this.helper.balance.getOneTokenNominal();
125 const transactions = [];128 const transactions = [];
154 for (let index = 0; index < 5; index++) {157 for (let index = 0; index < 5; index++) {
155 accountsCreated = await checkBalances();158 accountsCreated = await checkBalances();
156 if(accountsCreated) break;159 if(accountsCreated) break;
157 160 await wait.newBlocks(1);
158 }161 }
159162
160 if (!accountsCreated) throw Error('Accounts generation failed');163 if (!accountsCreated) throw Error('Accounts generation failed');
282 }285 }
283}286}
287
288class AdminGroup {
289 helper: UniqueHelper;
290
291 constructor(helper: UniqueHelper) {
292 this.helper = helper;
293 }
294
295 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}
284306
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
9import {ApiInterfaceEvents} from '@polkadot/api/types';9import {ApiInterfaceEvents} from '@polkadot/api/types';
10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';
11import {IKeyringPair} from '@polkadot/types/types';11import {IKeyringPair} from '@polkadot/types/types';
12import {IApiListeners, IBlock, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';12import {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';
1313
14export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {14export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {
15 const address = {} as ICrossAccountId;15 const address = {} as ICrossAccountId;
2029 return 1;2029 return 1;
2030 }2030 }
20312031
2032 /**
2033 * Get total staked amount for address
2034 * @param address substrate or ethereum address
2035 * @returns total staked amount
2036 */
2032 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2037 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {
2033 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2038 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();
2034 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2039 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();
2035 }2040 }
20362041
2042 /**
2043 * Get total staked per block
2044 * @param address substrate or ethereum address
2045 * @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
2046 */
2037 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<bigint[][]> {2047 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {
2048 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);
2038 return (await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2049 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {
2050 return {
2051 block: block.toBigInt(),
2052 amount: amount.toBigInt(),
2053 };
2054 });
2039 }2055 }
20402056
2057 /**
2058 * Get total pending unstake amount for address
2059 * @param address substrate or ethereum address
2060 * @returns total pending unstake amount
2061 */
2041 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2062 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {
2042 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2063 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();
2043 }2064 }
20442065
2066 /**
2067 * Get pending unstake amount per block for address
2068 * @param address substrate or ethereum address
2069 * @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
2070 */
2045 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<bigint[][]> {2071 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {
2072 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);
2046 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2073 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {
2074 return {
2075 block: block.toBigInt(),
2076 amount: amount.toBigInt(),
2077 };
2078 });
2079 return result;
2047 }2080 }
2048}2081}
20492082