difftreelog
Use only getAccounts method
in: master
to make sure: there are no any active stakes before each test
1 file changed
tests/src/sub/appPromotion/appPromotion.test.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {19 itSub, usingPlaygrounds, Pallets, requirePalletsOrSkip, LOCKING_PERIOD, UNLOCKING_PERIOD,20} from '../../util';21import {DevUniqueHelper} from '../../util/playgrounds/unique.dev';22import {itEth, expect, SponsoringMode} from '../../eth/util';2324let donor: IKeyringPair;25let palletAdmin: IKeyringPair;26let nominal: bigint;27let palletAddress: string;28let accounts: IKeyringPair[];29let usedAccounts: IKeyringPair[] = [];3031function getAccount(accountsNumber: number) {32 const accs = accounts.splice(0, accountsNumber);33 usedAccounts.push(...accs);34 return accs;35}36// App promotion periods:37// LOCKING_PERIOD = 12 blocks of relay38// UNLOCKING_PERIOD = 6 blocks of parachain3940describe('App promotion', () => {41 before(async function () {42 await usingPlaygrounds(async (helper, privateKey) => {43 requirePalletsOrSkip(this, helper, [Pallets.AppPromotion]);44 donor = await privateKey({url: import.meta.url});45 palletAddress = helper.arrange.calculatePalletAddress('appstake');46 palletAdmin = await privateKey('//PromotionAdmin');47 nominal = helper.balance.getOneTokenNominal();4849 const accountBalances = new Array(200).fill(1000n);50 accounts = await helper.arrange.createAccounts(accountBalances, donor); // create accounts-pool to speed up tests51 });52 });5354 afterEach(async () => {55 await usingPlaygrounds(async (helper) => {56 let unstakeTxs = [];57 for (const account of usedAccounts) {58 if (unstakeTxs.length === 3) {59 await Promise.all(unstakeTxs);60 unstakeTxs = [];61 }62 unstakeTxs.push(helper.staking.unstakeAll(account));63 }64 await Promise.all(unstakeTxs);65 usedAccounts = [];66 });67 });6869 describe('stake extrinsic', () => {70 itSub('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {71 const [staker, recepient] = getAccount(2);72 const totalStakedBefore = await helper.staking.getTotalStaked();7374 // Minimum stake amount is 100:75 await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;76 await helper.staking.stake(staker, 100n * nominal);7778 // Staker balance is: miscFrozen: 100, feeFrozen: 100, reserved: 0n...79 // ...so he can not transfer 90080 expect(await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});81 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: 100n * nominal, reasons: 'All'}]);82 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');8384 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);85 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);86 // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo?87 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased888990 await helper.staking.stake(staker, 200n * nominal);91 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);92 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});93 expect(totalStakedPerBlock[0].amount).to.equal(100n * nominal);94 expect(totalStakedPerBlock[1].amount).to.equal(200n * nominal);95 });9697 [98 {unstake: 'unstakeAll' as const},99 {unstake: 'unstakePartial' as const},100 ].map(testCase => {101 itSub('should allow to create maximum 10 stakes for account', async ({helper}) => {102 const [staker] = await helper.arrange.createAccounts([2000n], donor);103 const ONE_STAKE = 100n * nominal;104 for (let i = 0; i < 10; i++) {105 await helper.staking.stake(staker, ONE_STAKE);106 }107108 // can have 10 stakes109 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);110 expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);111112 await expect(helper.staking.stake(staker, ONE_STAKE)).to.be.rejectedWith('appPromotion.NoPermission');113114 // After unstake can stake again115116 // CASE 1: unstakeAll117 if (testCase.unstake === 'unstakeAll') {118 await helper.staking.unstakeAll(staker);119 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);120 await helper.staking.stake(staker, 100n * nominal);121 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);122 }123 // CASE 2: unstakePartial124 else {125 await helper.staking.unstakePartial(staker, ONE_STAKE);126 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);127 await helper.staking.stake(staker, 100n * nominal);128 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(10);129 await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');130 await helper.staking.unstakePartial(staker, 150n * nominal);131 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);132 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(850n * nominal);133 }134 });135 });136137 itSub('should allow to stake() if balance is locked with different id', async ({helper}) => {138 const [staker] = getAccount(1);139140 // staker has tokens locked with vesting id:141 await helper.balance.vestedTransfer(donor, staker.address, {start: 0n, period: 1n, periodCount: 1n, perPeriod: 200n * nominal});142 expect(await helper.balance.getSubstrateFull(staker.address))143 .to.deep.contain({free: 1200n * nominal, miscFrozen: 200n * nominal, feeFrozen: 200n * nominal, reserved: 0n});144145 // Locked balance can be staked. staker can stake 1200 tokens (minus fee):146 await helper.staking.stake(staker, 1000n * nominal);147 await helper.staking.stake(staker, 199n * nominal);148 // check balances149 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}, {id: 'appstake', amount: 1199n * nominal, reasons: 'All'}]);150 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 1199n * nominal, feeFrozen: 1199n * nominal});151 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(1199n);152 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(1199n * nominal);153154 // staker can unstake155 await helper.staking.unstakeAll(staker);156 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1199n * nominal);157 const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});158 await helper.wait.forParachainBlockNumber(pendingUnstake.block);159160 // check balances161 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}]);162 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 200n * nominal, feeFrozen: 200n * nominal});163 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(1199n);164 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);165166 // staker can transfer balances now167 await helper.balance.transferToSubstrate(staker, donor.address, 900n * nominal);168 });169170 itSub('should not allow to stake(), if stake amount is more than total free balance minus locked by staking', async ({helper}) => {171 const [staker] = getAccount(1);172173 // Can't stake full balance because Alice needs to pay some fee174 await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected; // With('Arithmetic')175 await helper.staking.stake(staker, 500n * nominal);176177 // Can't stake 500 tkn because Alice has Less than 500 transferable;178 await expect(helper.staking.stake(staker, 500n * nominal)).to.be.rejected; // With('Arithmetic');179 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);180 });181182 itSub('for different accounts in one block is possible', async ({helper}) => {183 const crowd = getAccount(4);184185 const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));186 await expect(Promise.all(crowdStartsToStake)).to.be.fulfilled;187188 const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));189 expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);190 });191 });192193 describe('Unstaking', () => {194 [195 {method: 'unstakeAll' as const},196 {method: 'unstakePartial' as const},197 ].map(testCase => {198 itSub(`[${testCase.method}] should move tokens to "pendingUnstake" and subtract it from totalStaked`, async ({helper}) => {199 const [staker, recepient] = getAccount(2);200 const totalStakedBefore = await helper.staking.getTotalStaked();201 const STAKE_AMOUNT = 900n * nominal;202203 await helper.staking.stake(staker, STAKE_AMOUNT);204 testCase.method === 'unstakeAll'205 ? await helper.staking.unstakeAll(staker)206 : await helper.staking.unstakePartial(staker, STAKE_AMOUNT);207208 // Right after unstake tokens are still locked209 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);210 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: STAKE_AMOUNT, reasons: 'All'}]);211 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: STAKE_AMOUNT, feeFrozen: STAKE_AMOUNT});212 // Staker can not transfer213 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');214 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(STAKE_AMOUNT);215 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);216 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);217 });218 });219220 [221 {method: 'unstakeAll' as const},222 {method: 'unstakePartial' as const},223 ].map(testCase => {224 itSub(`[${testCase.method}] should unlock balance after unlocking period ends and remove it from "pendingUnstake"`, async ({helper}) => {225 const [staker] = getAccount(1);226 await helper.staking.stake(staker, 100n * nominal);227 testCase.method === 'unstakeAll'228 ? await helper.staking.unstakeAll(staker)229 : await helper.staking.unstakePartial(staker, 100n * nominal);230 const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});231232 // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n233 await helper.wait.forParachainBlockNumber(pendingUnstake.block);234 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});235 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);236237 // staker can transfer:238 await helper.balance.transferToSubstrate(staker, donor.address, 998n * nominal);239 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);240 });241 });242243 [244 {method: 'unstakeAll' as const},245 {method: 'unstakePartial' as const},246 ].map(testCase => {247 itSub(`[${testCase.method}] should successfully unstake multiple stakes`, async ({helper}) => {248 const [staker] = getAccount(1);249 await helper.staking.stake(staker, 100n * nominal);250 await helper.staking.stake(staker, 200n * nominal);251 await helper.staking.stake(staker, 300n * nominal);252253 // staked: [100, 200, 300]; unstaked: 0254 let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});255 let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});256 let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});257 expect(totalPendingUnstake).to.be.deep.equal(0n);258 expect(pendingUnstake).to.be.deep.equal([]);259 expect(stakes[0].amount).to.equal(100n * nominal);260 expect(stakes[1].amount).to.equal(200n * nominal);261 expect(stakes[2].amount).to.equal(300n * nominal);262263 // Can unstake multiple stakes264 testCase.method === 'unstakeAll'265 ? await helper.staking.unstakeAll(staker)266 : await helper.staking.unstakePartial(staker, 600n * nominal);267268 pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});269 totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});270 stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});271 expect(totalPendingUnstake).to.be.equal(600n * nominal);272 expect(stakes).to.be.deep.equal([]);273 expect(pendingUnstake[0].amount).to.equal(600n * nominal);274275 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 600n * nominal, miscFrozen: 600n * nominal});276 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);277 await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);278 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});279 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);280 });281 });282283 [284 {method: 'unstakeAll' as const},285 {method: 'unstakePartial' as const},286 ].map(testCase => {287 itSub(`[${testCase.method}] should not have any effects if no active stakes`, async ({helper}) => {288 const [staker] = getAccount(1);289290 // unstake has no effect if no stakes at all291 testCase.method === 'unstakeAll'292 ? await helper.staking.unstakeAll(staker)293 : await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');294295 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);296 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper297298 // TODO stake() unstake() waitUnstaked() unstake();299300 // can't unstake if there are only pendingUnstakes301 await helper.staking.stake(staker, 100n * nominal);302303 if (testCase.method === 'unstakeAll') {304 await helper.staking.unstakeAll(staker);305 await helper.staking.unstakeAll(staker);306 } else {307 await helper.staking.unstakePartial(staker, 100n * nominal);308 await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');309 }310311 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);312 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);313 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);314 });315 });316317 [318 {method: 'unstakeAll' as const},319 {method: 'unstakePartial' as const},320 ].map(testCase => {321 itSub(`[${testCase.method}] should create different pending-unlock for each unlocking stake`, async ({helper}) => {322 const [staker] = getAccount(1);323 await helper.staking.stake(staker, 100n * nominal);324 testCase.method === 'unstakeAll'325 ? await helper.staking.unstakeAll(staker)326 : await helper.staking.unstakePartial(staker, 100n * nominal);327 await helper.staking.stake(staker, 120n * nominal);328 testCase.method === 'unstakeAll'329 ? await helper.staking.unstakeAll(staker)330 : await helper.staking.unstakePartial(staker, 120n * nominal);331332 const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});333 expect(unstakingPerBlock).has.length(2);334 expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);335 expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);336 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.equal(0);337 });338 });339340 [341 {method: 'unstakeAll' as const},342 {method: 'unstakePartial' as const},343 ].map(testCase => {344 itSub(`[${testCase.method}] should be possible for 3 accounts in one block`, async ({helper}) => {345 const stakers = getAccount(3);346347 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));348 await Promise.all(stakers.map(staker => {349 return testCase.method === 'unstakeAll'350 ? helper.staking.unstakeAll(staker)351 : helper.staking.unstakePartial(staker, 100n * nominal);352 }));353354 await Promise.all(stakers.map(async (staker) => {355 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);356 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);357 }));358 });359 });360361 itSub('should not be possible for more than 3 accounts in one block', async ({helper}) => {362 if (!await helper.arrange.isDevNode()) {363 const stakers = getAccount(10);364365 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));366 const unstakingResults = await Promise.allSettled(stakers.map((staker, i) => {367 return i % 2 === 0368 ? helper.staking.unstakeAll(staker)369 : helper.staking.unstakePartial(staker, 100n * nominal);370 }));371372 const successfulUnstakes = unstakingResults.filter(result => result.status === 'fulfilled');373 expect(successfulUnstakes).to.have.length(3);374 }375 });376377 itSub('Cannot partially unstake more than staked', async ({helper}) => {378 const [staker] = getAccount(1);379 // Staker stakes 300:380 await helper.staking.stake(staker, 100n * nominal);381 await helper.staking.stake(staker, 200n * nominal);382383 // cannot usntake 300.00000...1384 await expect(helper.staking.unstakePartial(staker, 300n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');385 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(2);386387 await helper.staking.unstakePartial(staker, 150n * nominal);388 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);389 await expect(helper.staking.unstakePartial(staker, 150n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');390 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);391392 // nothing broken, can unstake full amount:393 await helper.staking.unstakePartial(staker, 150n * nominal);394 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(0);395 });396397 itSub('Can partially unstake arbitrary amount', async ({helper}) => {398 const [staker] = getAccount(1);399 await helper.staking.stake(staker, 100n * nominal);400 await helper.staking.stake(staker, 200n * nominal);401402 // 0. Staker cannot unstake negative amount403 await expect(helper.staking.unstakePartial(staker, -1n)).to.be.rejected;404405 // 1. Staker can unstake 0 wei406 await helper.staking.unstakePartial(staker, 0n);407 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);408 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal);409 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);410411 // 2. Staker can unstake 1 wei412 await helper.staking.unstakePartial(staker, 1n);413 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);414 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal - 1n);415 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1n);416 // 2.1 The oldest stake decreased:417 let [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});418 expect(stake1.amount).to.eq(100n * nominal - 1n);419 expect(stake2.amount).to.eq(200n * nominal);420421 // 3. Staker can unstake all but 1 wei422 await helper.staking.unstakePartial(staker, 100n * nominal - 2n);423 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);424 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(200n * nominal + 1n);425 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(100n * nominal - 1n);426 [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});427 expect(stake1.amount).to.eq(1n);428 expect(stake2.amount).to.eq(200n * nominal);429 });430431 itSub('can mix different type of unstakes', async ({helper}) => {432 const [staker] = getAccount(1);433 await helper.staking.stake(staker, 100n * nominal);434 await helper.staking.stake(staker, 200n * nominal);435436 await helper.staking.unstakePartial(staker, 50n * nominal);437 await helper.staking.unstakeAll(staker);438 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);439 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);440 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(300n * nominal);441442 const [_unstake1, unstake2] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});443 await helper.wait.forParachainBlockNumber(unstake2.block);444445 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([]);446 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});447 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(999n);448 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);449 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);450 expect(await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).to.deep.eq([]);451 });452 });453454 describe('collection sponsoring', () => {455 itSub('should actually sponsor transactions', async ({helper}) => {456 const api = helper.getApi();457 const [collectionOwner, tokenSender, receiver] = getAccount(3);458 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});459 const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});460 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));461 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);462463 await token.transfer(tokenSender, {Substrate: receiver.address});464 expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});465 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);466467 // senders balance the same, transaction has sponsored468 expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);469 expect (palletBalanceBefore > palletBalanceAfter).to.be.true;470 });471472 itSub('can not be set by non admin', async ({helper}) => {473 const api = helper.getApi();474 const [collectionOwner, nonAdmin] = getAccount(2);475476 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});477478 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;479 expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');480 });481482 itSub('should set pallet address as confirmed admin', async ({helper}) => {483 const api = helper.getApi();484 const [collectionOwner, oldSponsor] = getAccount(2);485486 // Can set sponsoring for collection without sponsor487 const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});488 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;489 expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});490491 // Can set sponsoring for collection with unconfirmed sponsor492 const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});493 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});494 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;495 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});496497 // Can set sponsoring for collection with confirmed sponsor498 const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});499 await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);500 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;501 expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});502 });503504 itSub('can be overwritten by collection owner', async ({helper}) => {505 const api = helper.getApi();506 const [collectionOwner, newSponsor] = getAccount(2);507 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});508 const collectionId = collection.collectionId;509510 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;511512 // Collection limits still can be changed by the owner513 expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;514 expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);515 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});516517 // Collection sponsor can be changed too518 expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;519 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});520 });521522 itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {523 const api = helper.getApi();524 const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};525 const collectionWithLimits = await helper.nft.mintCollection(getAccount(1)[0], {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});526527 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;528 expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);529 });530531 itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {532 const api = helper.getApi();533 const [collectionOwner] = getAccount(1);534535 // collection has never existed536 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;537 // collection has been burned538 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});539 await collection.burn(collectionOwner);540541 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;542 });543 });544545 describe('stopSponsoringCollection', () => {546 itSub('can not be called by non-admin', async ({helper}) => {547 const api = helper.getApi();548 const [collectionOwner, nonAdmin] = getAccount(2);549 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});550551 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;552553 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;554 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});555 });556557 itSub('should set sponsoring as disabled', async ({helper}) => {558 const api = helper.getApi();559 const [collectionOwner, recepient] = getAccount(2);560 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});561 const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});562563 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));564 await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId));565566 expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');567568 // Transactions are not sponsored anymore:569 const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);570 await token.transfer(collectionOwner, {Substrate: recepient.address});571 const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);572 expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);573 });574575 itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {576 const api = helper.getApi();577 const [collectionOwner] = getAccount(1);578 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});579 await collection.confirmSponsorship(collectionOwner);580581 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;582583 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});584 });585586 itSub('should reject transaction if collection does not exist', async ({helper}) => {587 const [collectionOwner] = getAccount(1);588 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});589590 await collection.burn(collectionOwner);591 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');592 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');593 });594 });595596 describe('contract sponsoring', () => {597 itEth('should set palletes address as a sponsor', async ({helper}) => {598 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();599 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);600 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);601602 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);603604 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;605 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);606 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({607 confirmed: {608 substrate: palletAddress,609 },610 });611 });612613 itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {614 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();615 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);616 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);617618 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;619620 // Contract is self sponsored621 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.be.deep.equal({622 confirmed: {623 ethereum: flipper.options.address.toLowerCase(),624 },625 });626627 // set promotion sponsoring628 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);629630 // new sponsor is pallet address631 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;632 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);633 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({634 confirmed: {635 substrate: palletAddress,636 },637 });638 });639640 itEth('can be overwritten by contract owner', async ({helper}) => {641 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();642 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);643 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);644645 // contract sponsored by pallet646 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);647648 // owner sets self sponsoring649 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;650651 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;652 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);653 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({654 confirmed: {655 ethereum: flipper.options.address.toLowerCase(),656 },657 });658 });659660 itEth('can not be set by non admin', async ({helper}) => {661 const [nonAdmin] = getAccount(1);662 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();663 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);664 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);665666 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;667668 // nonAdmin calls sponsorContract669 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');670671 // contract still self-sponsored672 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({673 confirmed: {674 ethereum: flipper.options.address.toLowerCase(),675 },676 });677 });678679 itEth('should actually sponsor transactions', async ({helper}) => {680 // Contract caller681 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);682 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);683684 // Deploy flipper685 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();686 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);687 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);688689 // Owner sets to sponsor every tx690 await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});691 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});692 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);693694 // Set promotion to the Flipper695 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);696697 // Caller calls Flipper698 await flipper.methods.flip().send({from: caller});699 expect(await flipper.methods.getValue().call()).to.be.true;700701 // The contracts and caller balances have not changed702 const callerBalance = await helper.balance.getEthereum(caller);703 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);704 expect(callerBalance).to.be.equal(1000n * nominal);705 expect(1000n * nominal === contractBalanceAfter).to.be.true;706707 // The pallet balance has decreased708 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);709 expect(palletBalanceAfter < palletBalanceBefore).to.be.true;710 });711 });712713 describe('stopSponsoringContract', () => {714 itEth('should remove pallet address from contract sponsors', async ({helper}) => {715 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);716 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();717 const flipper = await helper.eth.deployFlipper(contractOwner);718 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address);719 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);720721 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});722 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);723 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);724725 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;726 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);727 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({728 disabled: null,729 });730731 await flipper.methods.flip().send({from: caller});732 expect(await flipper.methods.getValue().call()).to.be.true;733734 const callerBalance = await helper.balance.getEthereum(caller);735 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);736737 // caller payed for call738 expect(1000n * nominal > callerBalance).to.be.true;739 expect(contractBalanceAfter).to.be.equal(100n * nominal);740 });741742 itEth('can not be called by non-admin', async ({helper}) => {743 const [nonAdmin] = getAccount(1);744 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();745 const flipper = await helper.eth.deployFlipper(contractOwner);746747 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);748 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]))749 .to.be.rejectedWith(/appPromotion\.NoPermission/);750 });751752 itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {753 const [nonAdmin] = getAccount(1);754 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();755 const flipper = await helper.eth.deployFlipper(contractOwner);756 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);757 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;758759 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');760 });761 });762763 describe('payoutStakers', () => {764 itSub('can not be called by non admin', async ({helper}) => {765 const [nonAdmin] = getAccount(1);766 await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');767 });768769 itSub('should increase total staked', async ({helper}) => {770 const [staker] = getAccount(1);771 const totalStakedBefore = await helper.staking.getTotalStaked();772 await helper.staking.stake(staker, 100n * nominal);773774 // Wait for rewards and pay775 const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});776 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));777 const totalPayout = (await helper.admin.payoutStakers(palletAdmin, 100)).reduce((prev, payout) => prev + payout.payout, 0n);778779 const totalStakedAfter = await helper.staking.getTotalStaked();780 expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);781 // staker can unstake782 await helper.staking.unstakeAll(staker);783 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal));784 });785786 itSub('should credit 0.05% for staking period', async ({helper}) => {787 const [staker] = getAccount(1);788789 await waitPromotionPeriodDoesntEnd(helper);790791 await helper.staking.stake(staker, 100n * nominal);792 await helper.staking.stake(staker, 200n * nominal);793794 // wait rewards are available:795 const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});796 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));797798 const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)!.payout;799 expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal));800801 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});802 const income1 = calculateIncome(100n * nominal);803 const income2 = calculateIncome(200n * nominal);804 expect(totalStakedPerBlock[0].amount).to.equal(income1);805 expect(totalStakedPerBlock[1].amount).to.equal(income2);806807 const stakerBalance = await helper.balance.getSubstrateFull(staker.address);808 expect(stakerBalance).to.contain({miscFrozen: income1 + income2, feeFrozen: income1 + income2, reserved: 0n});809 expect(stakerBalance.free / nominal).to.eq(999n);810 });811812 itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {813 const [staker] = getAccount(1);814815 await helper.staking.stake(staker, 100n * nominal);816 // wait for two rewards are available:817 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});818 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);819820 await helper.admin.payoutStakers(palletAdmin, 100);821 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});822 const frozenBalanceShouldBe = calculateIncome(100n * nominal, 2);823 expect(stake.amount).to.be.equal(frozenBalanceShouldBe);824825 const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);826827 expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});828 });829830 itSub('should not be credited for pending-unstaked tokens', async ({helper}) => {831 // staker unstakes before rewards been payed832 const [staker] = getAccount(1);833 await helper.staking.stake(staker, 100n * nominal);834 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});835 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);836 await helper.staking.unstakeAll(staker);837838 // so he did not receive any rewards839 const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);840 await helper.admin.payoutStakers(palletAdmin, 100);841 const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);842843 expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);844 });845846 itSub('should bring compound interest', async ({helper}) => {847 const [staker] = getAccount(1);848849 await helper.staking.stake(staker, 100n * nominal);850851 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});852 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));853854 await helper.admin.payoutStakers(palletAdmin, 100);855 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});856 expect(stake.amount).to.equal(calculateIncome(100n * nominal));857858 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);859 await helper.admin.payoutStakers(palletAdmin, 100);860 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});861 expect(stake.amount).to.equal(calculateIncome(100n * nominal, 2));862 });863864 itSub('can calculate reward for tiny stake', async ({helper}) => {865 const [staker] = getAccount(1);866 await helper.staking.stake(staker, 100n * nominal);867 await helper.staking.stake(staker, 100n * nominal);868 await helper.staking.unstakePartial(staker, 100n * nominal - 1n);869870 const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});871 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));872873 const stakerPayout = await payUntilRewardFor(staker.address, helper);874 expect(stakerPayout.stake).to.eq(100n * nominal + 1n);875 });876877 itSub('can eventually pay all rewards', async ({helper}) => {878 const stakers = getAccount(30);879 // Create 30 stakes:880 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));881882 let unstakingTxs = [];883 for (const staker of stakers) {884 if (unstakingTxs.length == 3) {885 await Promise.all(unstakingTxs);886 unstakingTxs = [];887 }888 unstakingTxs.push(helper.staking.unstakePartial(staker, 100n * nominal - 1n));889 }890891 const [staker] = getAccount(1);892 await helper.staking.stake(staker, 100n * nominal);893 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});894 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));895896 let payouts;897 do {898 payouts = await helper.admin.payoutStakers(palletAdmin, 20);899 } while (payouts.length !== 0);900 });901 });902903 describe('events', () => {904 [905 {method: 'unstakePartial' as const},906 {method: 'unstakeAll' as const},907 ].map(testCase => {908 itSub(testCase.method, async ({helper}) => {909 const unstakeParams = testCase.method === 'unstakePartial'910 ? [100n * nominal - 1n]911 : [];912 const [staker] = getAccount(1);913 await helper.staking.stake(staker, 100n * nominal);914 await helper.staking.stake(staker, 200n * nominal);915 const {result} = await helper.executeExtrinsic(staker, `api.tx.appPromotion.${testCase.method}`, unstakeParams);916917 const event = result.events.find(e => e.event.section === 'appPromotion' && e.event.method === 'Unstake');918 const unstakerEvents = event?.event.data[0].toString();919 const unstakedEvents = BigInt(event?.event.data[1].toString());920 expect(unstakerEvents).to.eq(staker.address);921 expect(unstakedEvents).to.eq(testCase.method === 'unstakeAll' ? 300n * nominal : 100n * nominal - 1n);922 });923 });924925 itSub('stake', async ({helper}) => {926 const [staker] = getAccount(1);927 const {result} = await helper.executeExtrinsic(staker, 'api.tx.appPromotion.stake', [100n * nominal]);928929 const event = result.events.find(e => e.event.section === 'appPromotion' && e.event.method === 'Stake');930 const stakerEvents = event?.event.data[0].toString();931 const stakedEvents = BigInt(event?.event.data[1].toString());932 expect(stakerEvents).to.eq(staker.address);933 expect(stakedEvents).to.eq(100n * nominal);934 });935936 // Flaky937 itSub.skip('payoutStakers', async ({helper}) => {938 const [staker1, staker2] = getAccount(2);939 const STAKE1 = 100n * nominal;940 const STAKE2 = 200n * nominal;941 await helper.staking.stake(staker1, STAKE1);942 await helper.staking.stake(staker2, STAKE2);943944 const [stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker2.address});945 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));946947 const results = await helper.admin.payoutStakers(palletAdmin, 100);948 const stakersEvents = results.filter(ev => ev.staker === staker1.address || ev.staker === staker2.address);949 expect(stakersEvents).has.length(2);950 expect(stakersEvents).has.not.ordered.members([951 {staker: staker1.address, stake: STAKE1, payout: calculateIncome(STAKE1) - STAKE1},952 {staker: staker2.address, stake: STAKE2, payout: calculateIncome(STAKE2) - STAKE2},953 ]);954 });955 });956});957958959// Sometimes is is required to make a cycle in order for the payment to be calculated for a specific account960async function payUntilRewardFor(account: string, helper: DevUniqueHelper) {961 for (let i = 0; i < 3; i++) {962 const payouts = await helper.admin.payoutStakers(palletAdmin, 100);963 const accountPayout = payouts.find(p => p.staker === account);964 if (accountPayout) return accountPayout;965 }966 throw Error(`Cannot find payout for ${account}`);967}968969function calculateIncome(base: bigint, iter = 0, calcPeriod: bigint = UNLOCKING_PERIOD): bigint {970 const DAY = 7200n;971 const ACCURACY = 1_000_000_000n;972 // 5n / 10_000n = 0.05% p/day973 const income = base + base * (ACCURACY * (calcPeriod * 5n) / (10_000n * DAY)) / ACCURACY ;974975 if (iter > 1) {976 return calculateIncome(income, iter - 1, calcPeriod);977 } else return income;978}979980function rewardAvailableInBlock(stakedInBlock: bigint) {981 if (stakedInBlock % LOCKING_PERIOD === 0n) return stakedInBlock + LOCKING_PERIOD;982 return (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);983}984985// Wait while promotion period less than specified block, to avoid boundary cases986// 0 if this should be the beginning of the period.987async function waitPromotionPeriodDoesntEnd(helper: DevUniqueHelper, waitBlockLessThan = LOCKING_PERIOD / 3n) {988 const relayBlockNumber = (await helper.callRpc('api.query.parachainSystem.validationData', [])).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();989 const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;990991 if (currentPeriodBlock > waitBlockLessThan) {992 await helper.wait.forRelayBlockNumber(BigInt(relayBlockNumber) + LOCKING_PERIOD - currentPeriodBlock);993 }994}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {19 itSub, usingPlaygrounds, Pallets, requirePalletsOrSkip, LOCKING_PERIOD, UNLOCKING_PERIOD,20} from '../../util';21import {DevUniqueHelper} from '../../util/playgrounds/unique.dev';22import {itEth, expect, SponsoringMode} from '../../eth/util';2324let donor: IKeyringPair;25let palletAdmin: IKeyringPair;26let nominal: bigint;27let palletAddress: string;28let accounts: IKeyringPair[];29let usedAccounts: IKeyringPair[] = [];3031async function getAccounts(accountsNumber: number, balance?: bigint) {32 let accs: IKeyringPair[] = [];33 if (balance) {34 await usingPlaygrounds(async (helper) => {35 accs = await helper.arrange.createAccounts(new Array(accountsNumber).fill(balance), donor);36 });37 } else {38 accs = accounts.splice(0, accountsNumber);39 }40 usedAccounts.push(...accs);41 return accs;42}43// App promotion periods:44// LOCKING_PERIOD = 12 blocks of relay45// UNLOCKING_PERIOD = 6 blocks of parachain4647describe('App promotion', () => {48 before(async function () {49 await usingPlaygrounds(async (helper, privateKey) => {50 requirePalletsOrSkip(this, helper, [Pallets.AppPromotion]);51 donor = await privateKey({url: import.meta.url});52 palletAddress = helper.arrange.calculatePalletAddress('appstake');53 palletAdmin = await privateKey('//PromotionAdmin');54 nominal = helper.balance.getOneTokenNominal();5556 const accountBalances = new Array(200).fill(1000n);57 accounts = await helper.arrange.createAccounts(accountBalances, donor); // create accounts-pool to speed up tests58 });59 });6061 afterEach(async () => {62 await usingPlaygrounds(async (helper) => {63 let unstakeTxs = [];64 for (const account of usedAccounts) {65 if (unstakeTxs.length === 3) {66 await Promise.all(unstakeTxs);67 unstakeTxs = [];68 }69 unstakeTxs.push(helper.staking.unstakeAll(account));70 }71 await Promise.all(unstakeTxs);72 usedAccounts = [];73 expect(await helper.staking.getTotalStaked()).to.eq(0n); // there are no active stakes after each test74 });75 });7677 describe('stake extrinsic', () => {78 itSub('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {79 const [staker, recepient] = await getAccounts(2);80 const totalStakedBefore = await helper.staking.getTotalStaked();8182 // Minimum stake amount is 100:83 await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;84 await helper.staking.stake(staker, 100n * nominal);8586 // Staker balance is: miscFrozen: 100, feeFrozen: 100, reserved: 0n...87 // ...so he can not transfer 90088 expect(await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});89 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: 100n * nominal, reasons: 'All'}]);90 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');9192 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);93 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);94 // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo?95 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased969798 await helper.staking.stake(staker, 200n * nominal);99 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);100 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});101 expect(totalStakedPerBlock[0].amount).to.equal(100n * nominal);102 expect(totalStakedPerBlock[1].amount).to.equal(200n * nominal);103 });104105 [106 {unstake: 'unstakeAll' as const},107 {unstake: 'unstakePartial' as const},108 ].map(testCase => {109 itSub(`[${testCase.unstake}] should allow to create maximum 10 stakes for account`, async ({helper}) => {110 const [staker] = await getAccounts(1, 2000n);111 const ONE_STAKE = 100n * nominal;112 for (let i = 0; i < 10; i++) {113 await helper.staking.stake(staker, ONE_STAKE);114 }115116 // can have 10 stakes117 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);118 expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);119120 await expect(helper.staking.stake(staker, ONE_STAKE)).to.be.rejectedWith('appPromotion.NoPermission');121122 // After unstake can stake again123124 // CASE 1: unstakeAll125 if (testCase.unstake === 'unstakeAll') {126 await helper.staking.unstakeAll(staker);127 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);128 await helper.staking.stake(staker, 100n * nominal);129 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);130 }131 // CASE 2: unstakePartial132 else {133 await helper.staking.unstakePartial(staker, ONE_STAKE);134 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);135 await helper.staking.stake(staker, 100n * nominal);136 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(10);137 await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');138 await helper.staking.unstakePartial(staker, 150n * nominal);139 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);140 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(850n * nominal);141 }142 });143 });144145 itSub('should allow to stake() if balance is locked with different id', async ({helper}) => {146 const [staker] = await getAccounts(1);147148 // staker has tokens locked with vesting id:149 await helper.balance.vestedTransfer(donor, staker.address, {start: 0n, period: 1n, periodCount: 1n, perPeriod: 200n * nominal});150 expect(await helper.balance.getSubstrateFull(staker.address))151 .to.deep.contain({free: 1200n * nominal, miscFrozen: 200n * nominal, feeFrozen: 200n * nominal, reserved: 0n});152153 // Locked balance can be staked. staker can stake 1200 tokens (minus fee):154 await helper.staking.stake(staker, 1000n * nominal);155 await helper.staking.stake(staker, 199n * nominal);156 // check balances157 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}, {id: 'appstake', amount: 1199n * nominal, reasons: 'All'}]);158 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 1199n * nominal, feeFrozen: 1199n * nominal});159 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(1199n);160 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(1199n * nominal);161162 // staker can unstake163 await helper.staking.unstakeAll(staker);164 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1199n * nominal);165 const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});166 await helper.wait.forParachainBlockNumber(pendingUnstake.block);167168 // check balances169 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}]);170 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 200n * nominal, feeFrozen: 200n * nominal});171 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(1199n);172 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);173174 // staker can transfer balances now175 await helper.balance.transferToSubstrate(staker, donor.address, 900n * nominal);176 });177178 itSub('should not allow to stake(), if stake amount is more than total free balance minus locked by staking', async ({helper}) => {179 const [staker] = await getAccounts(1);180181 // Can't stake full balance because Alice needs to pay some fee182 await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected; // With('Arithmetic')183 await helper.staking.stake(staker, 500n * nominal);184185 // Can't stake 500 tkn because Alice has Less than 500 transferable;186 await expect(helper.staking.stake(staker, 500n * nominal)).to.be.rejected; // With('Arithmetic');187 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);188 });189190 itSub('for different accounts in one block is possible', async ({helper}) => {191 const crowd = await getAccounts(4);192193 const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));194 await expect(Promise.all(crowdStartsToStake)).to.be.fulfilled;195196 const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));197 expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);198 });199 });200201 describe('Unstaking', () => {202 [203 {method: 'unstakeAll' as const},204 {method: 'unstakePartial' as const},205 ].map(testCase => {206 itSub(`[${testCase.method}] should move tokens to "pendingUnstake" and subtract it from totalStaked`, async ({helper}) => {207 const [staker, recepient] = await getAccounts(2);208 const totalStakedBefore = await helper.staking.getTotalStaked();209 const STAKE_AMOUNT = 900n * nominal;210211 await helper.staking.stake(staker, STAKE_AMOUNT);212 testCase.method === 'unstakeAll'213 ? await helper.staking.unstakeAll(staker)214 : await helper.staking.unstakePartial(staker, STAKE_AMOUNT);215216 // Right after unstake tokens are still locked217 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);218 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: STAKE_AMOUNT, reasons: 'All'}]);219 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: STAKE_AMOUNT, feeFrozen: STAKE_AMOUNT});220 // Staker can not transfer221 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');222 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(STAKE_AMOUNT);223 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);224 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);225 });226 });227228 [229 {method: 'unstakeAll' as const},230 {method: 'unstakePartial' as const},231 ].map(testCase => {232 itSub(`[${testCase.method}] should unlock balance after unlocking period ends and remove it from "pendingUnstake"`, async ({helper}) => {233 const [staker] = await getAccounts(1);234 await helper.staking.stake(staker, 100n * nominal);235 testCase.method === 'unstakeAll'236 ? await helper.staking.unstakeAll(staker)237 : await helper.staking.unstakePartial(staker, 100n * nominal);238 const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});239240 // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n241 await helper.wait.forParachainBlockNumber(pendingUnstake.block);242 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});243 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);244245 // staker can transfer:246 await helper.balance.transferToSubstrate(staker, donor.address, 998n * nominal);247 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);248 });249 });250251 [252 {method: 'unstakeAll' as const},253 {method: 'unstakePartial' as const},254 ].map(testCase => {255 itSub(`[${testCase.method}] should successfully unstake multiple stakes`, async ({helper}) => {256 const [staker] = await getAccounts(1);257 await helper.staking.stake(staker, 100n * nominal);258 await helper.staking.stake(staker, 200n * nominal);259 await helper.staking.stake(staker, 300n * nominal);260261 // staked: [100, 200, 300]; unstaked: 0262 let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});263 let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});264 let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});265 expect(totalPendingUnstake).to.be.deep.equal(0n);266 expect(pendingUnstake).to.be.deep.equal([]);267 expect(stakes[0].amount).to.equal(100n * nominal);268 expect(stakes[1].amount).to.equal(200n * nominal);269 expect(stakes[2].amount).to.equal(300n * nominal);270271 // Can unstake multiple stakes272 testCase.method === 'unstakeAll'273 ? await helper.staking.unstakeAll(staker)274 : await helper.staking.unstakePartial(staker, 600n * nominal);275276 pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});277 totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});278 stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});279 expect(totalPendingUnstake).to.be.equal(600n * nominal);280 expect(stakes).to.be.deep.equal([]);281 expect(pendingUnstake[0].amount).to.equal(600n * nominal);282283 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 600n * nominal, miscFrozen: 600n * nominal});284 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);285 await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);286 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});287 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);288 });289 });290291 [292 {method: 'unstakeAll' as const},293 {method: 'unstakePartial' as const},294 ].map(testCase => {295 itSub(`[${testCase.method}] should not have any effects if no active stakes`, async ({helper}) => {296 const [staker] = await getAccounts(1);297298 // unstake has no effect if no stakes at all299 testCase.method === 'unstakeAll'300 ? await helper.staking.unstakeAll(staker)301 : await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');302303 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);304 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper305306 // TODO stake() unstake() waitUnstaked() unstake();307308 // can't unstake if there are only pendingUnstakes309 await helper.staking.stake(staker, 100n * nominal);310311 if (testCase.method === 'unstakeAll') {312 await helper.staking.unstakeAll(staker);313 await helper.staking.unstakeAll(staker);314 } else {315 await helper.staking.unstakePartial(staker, 100n * nominal);316 await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');317 }318319 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);320 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);321 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);322 });323 });324325 [326 {method: 'unstakeAll' as const},327 {method: 'unstakePartial' as const},328 ].map(testCase => {329 itSub(`[${testCase.method}] should create different pending-unlock for each unlocking stake`, async ({helper}) => {330 const [staker] = await getAccounts(1);331 await helper.staking.stake(staker, 100n * nominal);332 testCase.method === 'unstakeAll'333 ? await helper.staking.unstakeAll(staker)334 : await helper.staking.unstakePartial(staker, 100n * nominal);335 await helper.staking.stake(staker, 120n * nominal);336 testCase.method === 'unstakeAll'337 ? await helper.staking.unstakeAll(staker)338 : await helper.staking.unstakePartial(staker, 120n * nominal);339340 const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});341 expect(unstakingPerBlock).has.length(2);342 expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);343 expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);344 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.equal(0);345 });346 });347348 [349 {method: 'unstakeAll' as const},350 {method: 'unstakePartial' as const},351 ].map(testCase => {352 itSub(`[${testCase.method}] should be possible for 3 accounts in one block`, async ({helper}) => {353 const stakers = await getAccounts(3);354355 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));356 await Promise.all(stakers.map(staker => {357 return testCase.method === 'unstakeAll'358 ? helper.staking.unstakeAll(staker)359 : helper.staking.unstakePartial(staker, 100n * nominal);360 }));361362 await Promise.all(stakers.map(async (staker) => {363 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);364 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);365 }));366 });367 });368369 itSub('should not be possible for more than 3 accounts in one block', async ({helper}) => {370 if (!await helper.arrange.isDevNode()) {371 const stakers = await getAccounts(10);372373 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));374 const unstakingResults = await Promise.allSettled(stakers.map((staker, i) => {375 return i % 2 === 0376 ? helper.staking.unstakeAll(staker)377 : helper.staking.unstakePartial(staker, 100n * nominal);378 }));379380 const successfulUnstakes = unstakingResults.filter(result => result.status === 'fulfilled');381 expect(successfulUnstakes).to.have.length(3);382 }383 });384385 itSub('Cannot partially unstake more than staked', async ({helper}) => {386 const [staker] = await getAccounts(1);387 // Staker stakes 300:388 await helper.staking.stake(staker, 100n * nominal);389 await helper.staking.stake(staker, 200n * nominal);390391 // cannot usntake 300.00000...1392 await expect(helper.staking.unstakePartial(staker, 300n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');393 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(2);394395 await helper.staking.unstakePartial(staker, 150n * nominal);396 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);397 await expect(helper.staking.unstakePartial(staker, 150n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');398 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);399400 // nothing broken, can unstake full amount:401 await helper.staking.unstakePartial(staker, 150n * nominal);402 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(0);403 });404405 itSub('Can partially unstake arbitrary amount', async ({helper}) => {406 const [staker] = await getAccounts(1);407 await helper.staking.stake(staker, 100n * nominal);408 await helper.staking.stake(staker, 200n * nominal);409410 // 0. Staker cannot unstake negative amount411 await expect(helper.staking.unstakePartial(staker, -1n)).to.be.rejected;412413 // 1. Staker can unstake 0 wei414 await helper.staking.unstakePartial(staker, 0n);415 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);416 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal);417 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);418419 // 2. Staker can unstake 1 wei420 await helper.staking.unstakePartial(staker, 1n);421 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);422 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal - 1n);423 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1n);424 // 2.1 The oldest stake decreased:425 let [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});426 expect(stake1.amount).to.eq(100n * nominal - 1n);427 expect(stake2.amount).to.eq(200n * nominal);428429 // 3. Staker can unstake all but 1 wei430 await helper.staking.unstakePartial(staker, 100n * nominal - 2n);431 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);432 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(200n * nominal + 1n);433 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(100n * nominal - 1n);434 [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});435 expect(stake1.amount).to.eq(1n);436 expect(stake2.amount).to.eq(200n * nominal);437 });438439 itSub('can mix different type of unstakes', async ({helper}) => {440 const [staker] = await getAccounts(1);441 await helper.staking.stake(staker, 100n * nominal);442 await helper.staking.stake(staker, 200n * nominal);443444 await helper.staking.unstakePartial(staker, 50n * nominal);445 await helper.staking.unstakeAll(staker);446 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);447 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);448 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(300n * nominal);449450 const [_unstake1, unstake2] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});451 await helper.wait.forParachainBlockNumber(unstake2.block);452453 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([]);454 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});455 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(999n);456 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);457 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);458 expect(await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).to.deep.eq([]);459 });460 });461462 describe('collection sponsoring', () => {463 itSub('should actually sponsor transactions', async ({helper}) => {464 const api = helper.getApi();465 const [collectionOwner, tokenSender, receiver] = await getAccounts(3);466 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});467 const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});468 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));469 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);470471 await token.transfer(tokenSender, {Substrate: receiver.address});472 expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});473 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);474475 // senders balance the same, transaction has sponsored476 expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);477 expect (palletBalanceBefore > palletBalanceAfter).to.be.true;478 });479480 itSub('can not be set by non admin', async ({helper}) => {481 const api = helper.getApi();482 const [collectionOwner, nonAdmin] = await getAccounts(2);483484 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});485486 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;487 expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');488 });489490 itSub('should set pallet address as confirmed admin', async ({helper}) => {491 const api = helper.getApi();492 const [collectionOwner, oldSponsor] = await getAccounts(2);493494 // Can set sponsoring for collection without sponsor495 const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});496 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;497 expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});498499 // Can set sponsoring for collection with unconfirmed sponsor500 const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});501 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});502 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;503 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});504505 // Can set sponsoring for collection with confirmed sponsor506 const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});507 await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);508 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;509 expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});510 });511512 itSub('can be overwritten by collection owner', async ({helper}) => {513 const api = helper.getApi();514 const [collectionOwner, newSponsor] = await getAccounts(2);515 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});516 const collectionId = collection.collectionId;517518 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;519520 // Collection limits still can be changed by the owner521 expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;522 expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);523 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});524525 // Collection sponsor can be changed too526 expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;527 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});528 });529530 itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {531 const [owner] = await getAccounts(1);532 const api = helper.getApi();533 const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};534 const collectionWithLimits = await helper.nft.mintCollection(owner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});535536 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;537 expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);538 });539540 itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {541 const api = helper.getApi();542 const [collectionOwner] = await getAccounts(1);543544 // collection has never existed545 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;546 // collection has been burned547 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});548 await collection.burn(collectionOwner);549550 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;551 });552 });553554 describe('stopSponsoringCollection', () => {555 itSub('can not be called by non-admin', async ({helper}) => {556 const api = helper.getApi();557 const [collectionOwner, nonAdmin] = await getAccounts(2);558 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});559560 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;561562 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;563 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});564 });565566 itSub('should set sponsoring as disabled', async ({helper}) => {567 const api = helper.getApi();568 const [collectionOwner, recepient] = await getAccounts(2);569 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});570 const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});571572 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));573 await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId));574575 expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');576577 // Transactions are not sponsored anymore:578 const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);579 await token.transfer(collectionOwner, {Substrate: recepient.address});580 const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);581 expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);582 });583584 itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {585 const api = helper.getApi();586 const [collectionOwner] = await getAccounts(1);587 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});588 await collection.confirmSponsorship(collectionOwner);589590 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;591592 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});593 });594595 itSub('should reject transaction if collection does not exist', async ({helper}) => {596 const [collectionOwner] = await getAccounts(1);597 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});598599 await collection.burn(collectionOwner);600 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');601 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');602 });603 });604605 describe('contract sponsoring', () => {606 itEth('should set palletes address as a sponsor', async ({helper}) => {607 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();608 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);609 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);610611 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);612613 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;614 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);615 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({616 confirmed: {617 substrate: palletAddress,618 },619 });620 });621622 itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {623 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();624 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);625 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);626627 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;628629 // Contract is self sponsored630 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.be.deep.equal({631 confirmed: {632 ethereum: flipper.options.address.toLowerCase(),633 },634 });635636 // set promotion sponsoring637 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);638639 // new sponsor is pallet address640 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;641 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);642 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({643 confirmed: {644 substrate: palletAddress,645 },646 });647 });648649 itEth('can be overwritten by contract owner', async ({helper}) => {650 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();651 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);652 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);653654 // contract sponsored by pallet655 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);656657 // owner sets self sponsoring658 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;659660 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;661 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);662 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({663 confirmed: {664 ethereum: flipper.options.address.toLowerCase(),665 },666 });667 });668669 itEth('can not be set by non admin', async ({helper}) => {670 const [nonAdmin] = await getAccounts(1);671 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();672 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);673 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);674675 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;676677 // nonAdmin calls sponsorContract678 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');679680 // contract still self-sponsored681 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({682 confirmed: {683 ethereum: flipper.options.address.toLowerCase(),684 },685 });686 });687688 itEth('should actually sponsor transactions', async ({helper}) => {689 // Contract caller690 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);691 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);692693 // Deploy flipper694 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();695 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);696 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);697698 // Owner sets to sponsor every tx699 await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});700 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});701 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);702703 // Set promotion to the Flipper704 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);705706 // Caller calls Flipper707 await flipper.methods.flip().send({from: caller});708 expect(await flipper.methods.getValue().call()).to.be.true;709710 // The contracts and caller balances have not changed711 const callerBalance = await helper.balance.getEthereum(caller);712 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);713 expect(callerBalance).to.be.equal(1000n * nominal);714 expect(1000n * nominal === contractBalanceAfter).to.be.true;715716 // The pallet balance has decreased717 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);718 expect(palletBalanceAfter < palletBalanceBefore).to.be.true;719 });720 });721722 describe('stopSponsoringContract', () => {723 itEth('should remove pallet address from contract sponsors', async ({helper}) => {724 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);725 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();726 const flipper = await helper.eth.deployFlipper(contractOwner);727 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address);728 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);729730 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});731 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);732 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);733734 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;735 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);736 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({737 disabled: null,738 });739740 await flipper.methods.flip().send({from: caller});741 expect(await flipper.methods.getValue().call()).to.be.true;742743 const callerBalance = await helper.balance.getEthereum(caller);744 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);745746 // caller payed for call747 expect(1000n * nominal > callerBalance).to.be.true;748 expect(contractBalanceAfter).to.be.equal(100n * nominal);749 });750751 itEth('can not be called by non-admin', async ({helper}) => {752 const [nonAdmin] = await getAccounts(1);753 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();754 const flipper = await helper.eth.deployFlipper(contractOwner);755756 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);757 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]))758 .to.be.rejectedWith(/appPromotion\.NoPermission/);759 });760761 itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {762 const [nonAdmin] = await getAccounts(1);763 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();764 const flipper = await helper.eth.deployFlipper(contractOwner);765 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);766 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;767768 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');769 });770 });771772 describe('payoutStakers', () => {773 itSub('can not be called by non admin', async ({helper}) => {774 const [nonAdmin] = await getAccounts(1);775 await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');776 });777778 itSub('should increase total staked', async ({helper}) => {779 const [staker] = await getAccounts(1);780 const totalStakedBefore = await helper.staking.getTotalStaked();781 await helper.staking.stake(staker, 100n * nominal);782783 // Wait for rewards and pay784 const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});785 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));786 const totalPayout = (await helper.admin.payoutStakers(palletAdmin, 100)).reduce((prev, payout) => prev + payout.payout, 0n);787788 const totalStakedAfter = await helper.staking.getTotalStaked();789 expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);790 // staker can unstake791 await helper.staking.unstakeAll(staker);792 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal));793 });794795 itSub('should credit 0.05% for staking period', async ({helper}) => {796 const [staker] = await getAccounts(1);797798 await waitPromotionPeriodDoesntEnd(helper);799800 await helper.staking.stake(staker, 100n * nominal);801 await helper.staking.stake(staker, 200n * nominal);802803 // wait rewards are available:804 const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});805 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));806807 const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)!.payout;808 expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal));809810 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});811 const income1 = calculateIncome(100n * nominal);812 const income2 = calculateIncome(200n * nominal);813 expect(totalStakedPerBlock[0].amount).to.equal(income1);814 expect(totalStakedPerBlock[1].amount).to.equal(income2);815816 const stakerBalance = await helper.balance.getSubstrateFull(staker.address);817 expect(stakerBalance).to.contain({miscFrozen: income1 + income2, feeFrozen: income1 + income2, reserved: 0n});818 expect(stakerBalance.free / nominal).to.eq(999n);819 });820821 itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {822 const [staker] = await getAccounts(1);823824 await helper.staking.stake(staker, 100n * nominal);825 // wait for two rewards are available:826 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});827 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);828829 await helper.admin.payoutStakers(palletAdmin, 100);830 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});831 const frozenBalanceShouldBe = calculateIncome(100n * nominal, 2);832 expect(stake.amount).to.be.equal(frozenBalanceShouldBe);833834 const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);835836 expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});837 });838839 itSub('should not be credited for pending-unstaked tokens', async ({helper}) => {840 // staker unstakes before rewards been payed841 const [staker] = await getAccounts(1);842 await helper.staking.stake(staker, 100n * nominal);843 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});844 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);845 await helper.staking.unstakeAll(staker);846847 // so he did not receive any rewards848 const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);849 await helper.admin.payoutStakers(palletAdmin, 100);850 const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);851852 expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);853 });854855 itSub('should bring compound interest', async ({helper}) => {856 const [staker] = await getAccounts(1);857858 await helper.staking.stake(staker, 100n * nominal);859860 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});861 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));862863 await helper.admin.payoutStakers(palletAdmin, 100);864 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});865 expect(stake.amount).to.equal(calculateIncome(100n * nominal));866867 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);868 await helper.admin.payoutStakers(palletAdmin, 100);869 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});870 expect(stake.amount).to.equal(calculateIncome(100n * nominal, 2));871 });872873 itSub('can calculate reward for tiny stake', async ({helper}) => {874 const [staker] = await getAccounts(1);875 await helper.staking.stake(staker, 100n * nominal);876 await helper.staking.stake(staker, 100n * nominal);877 await helper.staking.unstakePartial(staker, 100n * nominal - 1n);878879 const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});880 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));881882 const stakerPayout = await payUntilRewardFor(staker.address, helper);883 expect(stakerPayout.stake).to.eq(100n * nominal + 1n);884 });885886 itSub('can eventually pay all rewards', async ({helper}) => {887 const stakers = await getAccounts(30);888 // Create 30 stakes:889 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));890891 let unstakingTxs = [];892 for (const staker of stakers) {893 if (unstakingTxs.length == 3) {894 await Promise.all(unstakingTxs);895 unstakingTxs = [];896 }897 unstakingTxs.push(helper.staking.unstakePartial(staker, 100n * nominal - 1n));898 }899900 const [staker] = await getAccounts(1);901 await helper.staking.stake(staker, 100n * nominal);902 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});903 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));904905 let payouts;906 do {907 payouts = await helper.admin.payoutStakers(palletAdmin, 20);908 } while (payouts.length !== 0);909 });910 });911912 describe('events', () => {913 [914 {method: 'unstakePartial' as const},915 {method: 'unstakeAll' as const},916 ].map(testCase => {917 itSub(testCase.method, async ({helper}) => {918 const unstakeParams = testCase.method === 'unstakePartial'919 ? [100n * nominal - 1n]920 : [];921 const [staker] = await getAccounts(1);922 await helper.staking.stake(staker, 100n * nominal);923 await helper.staking.stake(staker, 200n * nominal);924 const {result} = await helper.executeExtrinsic(staker, `api.tx.appPromotion.${testCase.method}`, unstakeParams);925926 const event = result.events.find(e => e.event.section === 'appPromotion' && e.event.method === 'Unstake');927 const unstakerEvents = event?.event.data[0].toString();928 const unstakedEvents = BigInt(event?.event.data[1].toString());929 expect(unstakerEvents).to.eq(staker.address);930 expect(unstakedEvents).to.eq(testCase.method === 'unstakeAll' ? 300n * nominal : 100n * nominal - 1n);931 });932 });933934 itSub('stake', async ({helper}) => {935 const [staker] = await getAccounts(1);936 const {result} = await helper.executeExtrinsic(staker, 'api.tx.appPromotion.stake', [100n * nominal]);937938 const event = result.events.find(e => e.event.section === 'appPromotion' && e.event.method === 'Stake');939 const stakerEvents = event?.event.data[0].toString();940 const stakedEvents = BigInt(event?.event.data[1].toString());941 expect(stakerEvents).to.eq(staker.address);942 expect(stakedEvents).to.eq(100n * nominal);943 });944945 // Flaky946 itSub.skip('payoutStakers', async ({helper}) => {947 const [staker1, staker2] = await getAccounts(2);948 const STAKE1 = 100n * nominal;949 const STAKE2 = 200n * nominal;950 await helper.staking.stake(staker1, STAKE1);951 await helper.staking.stake(staker2, STAKE2);952953 const [stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker2.address});954 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));955956 const results = await helper.admin.payoutStakers(palletAdmin, 100);957 const stakersEvents = results.filter(ev => ev.staker === staker1.address || ev.staker === staker2.address);958 expect(stakersEvents).has.length(2);959 expect(stakersEvents).has.not.ordered.members([960 {staker: staker1.address, stake: STAKE1, payout: calculateIncome(STAKE1) - STAKE1},961 {staker: staker2.address, stake: STAKE2, payout: calculateIncome(STAKE2) - STAKE2},962 ]);963 });964 });965});966967968// Sometimes is is required to make a cycle in order for the payment to be calculated for a specific account969async function payUntilRewardFor(account: string, helper: DevUniqueHelper) {970 for (let i = 0; i < 3; i++) {971 const payouts = await helper.admin.payoutStakers(palletAdmin, 100);972 const accountPayout = payouts.find(p => p.staker === account);973 if (accountPayout) return accountPayout;974 }975 throw Error(`Cannot find payout for ${account}`);976}977978function calculateIncome(base: bigint, iter = 0, calcPeriod: bigint = UNLOCKING_PERIOD): bigint {979 const DAY = 7200n;980 const ACCURACY = 1_000_000_000n;981 // 5n / 10_000n = 0.05% p/day982 const income = base + base * (ACCURACY * (calcPeriod * 5n) / (10_000n * DAY)) / ACCURACY ;983984 if (iter > 1) {985 return calculateIncome(income, iter - 1, calcPeriod);986 } else return income;987}988989function rewardAvailableInBlock(stakedInBlock: bigint) {990 if (stakedInBlock % LOCKING_PERIOD === 0n) return stakedInBlock + LOCKING_PERIOD;991 return (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);992}993994// Wait while promotion period less than specified block, to avoid boundary cases995// 0 if this should be the beginning of the period.996async function waitPromotionPeriodDoesntEnd(helper: DevUniqueHelper, waitBlockLessThan = LOCKING_PERIOD / 3n) {997 const relayBlockNumber = (await helper.callRpc('api.query.parachainSystem.validationData', [])).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();998 const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;9991000 if (currentPeriodBlock > waitBlockLessThan) {1001 await helper.wait.forRelayBlockNumber(BigInt(relayBlockNumber) + LOCKING_PERIOD - currentPeriodBlock);1002 }1003}