difftreelog
test(appPromotion) read freezes instead of locks
in: master
2 files 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[] = [];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 // Make sure previousCalculatedRecord is None to avoid problem with payout stakers;75 await helper.admin.payoutStakers(palletAdmin, 100);76 expect((await helper.getApi().query.appPromotion.previousCalculatedRecord() as any).isNone).to.be.true;77 });78 });7980 describe('stake extrinsic', () => {81 itSub('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {82 const [staker, recepient] = await getAccounts(2);83 const totalStakedBefore = await helper.staking.getTotalStaked();8485 // Minimum stake amount is 100:86 await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;87 await helper.staking.stake(staker, 100n * nominal);8889 // Staker balance is: frozen: 100, reserved: 0n...90 // ...so he can not transfer 90091 expect(await helper.balance.getSubstrateFull(staker.address)).to.contain({frozen: 100n * nominal, reserved: 0n});92 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: 100n * nominal, reasons: 'All'}]);93 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejectedWith(/^Token: Frozen$/);9495 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);96 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);97 // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo?98 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased99100101 await helper.staking.stake(staker, 200n * nominal);102 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);103 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});104 expect(totalStakedPerBlock[0].amount).to.equal(100n * nominal);105 expect(totalStakedPerBlock[1].amount).to.equal(200n * nominal);106 });107108 [109 {unstake: 'unstakeAll' as const},110 {unstake: 'unstakePartial' as const},111 ].map(testCase => {112 itSub(`[${testCase.unstake}] should allow to create maximum 10 stakes for account`, async ({helper}) => {113 const [staker] = await getAccounts(1, 2000n);114 const ONE_STAKE = 100n * nominal;115 for (let i = 0; i < 10; i++) {116 await helper.staking.stake(staker, ONE_STAKE);117 }118119 // can have 10 stakes120 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);121 expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);122123 await expect(helper.staking.stake(staker, ONE_STAKE)).to.be.rejectedWith('appPromotion.NoPermission');124125 // After unstake can stake again126127 // CASE 1: unstakeAll128 if (testCase.unstake === 'unstakeAll') {129 await helper.staking.unstakeAll(staker);130 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);131 await helper.staking.stake(staker, 100n * nominal);132 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);133 }134 // CASE 2: unstakePartial135 else {136 await helper.staking.unstakePartial(staker, ONE_STAKE);137 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);138 await helper.staking.stake(staker, 100n * nominal);139 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(10);140 await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');141 await helper.staking.unstakePartial(staker, 150n * nominal);142 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);143 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(850n * nominal);144 }145 });146 });147148 itSub('should allow to stake() if balance is locked with different id', async ({helper}) => {149 const [staker] = await getAccounts(1);150151 // staker has tokens locked with vesting id:152 await helper.balance.vestedTransfer(donor, staker.address, {start: 0n, period: 1n, periodCount: 1n, perPeriod: 200n * nominal});153 expect(await helper.balance.getSubstrateFull(staker.address))154 .to.deep.contain({free: 1200n * nominal, frozen: 200n * nominal, reserved: 0n});155156 // Locked balance can be staked. staker can stake 1200 tokens (minus fee):157 await helper.staking.stake(staker, 1000n * nominal);158 await helper.staking.stake(staker, 199n * nominal);159 // check balances160 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}, {id: 'appstake', amount: 1199n * nominal, reasons: 'All'}]);161 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 1199n * nominal});162 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(1199n);163 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(1199n * nominal);164165 // staker can unstake166 await helper.staking.unstakeAll(staker);167 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1199n * nominal);168 const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});169 await helper.wait.forParachainBlockNumber(pendingUnstake.block);170171 // check balances172 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}]);173 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 200n * nominal});174 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(1199n);175 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);176177 // staker can transfer balances now178 await helper.balance.transferToSubstrate(staker, donor.address, 900n * nominal);179 });180181 itSub('should not allow to stake(), if stake amount is more than total free balance minus locked by staking', async ({helper}) => {182 const [staker] = await getAccounts(1);183184 // Can't stake full balance because Alice needs to pay some fee185 await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected; // With('Arithmetic')186 await helper.staking.stake(staker, 500n * nominal);187188 // Can't stake 500 tkn because Alice has Less than 500 transferable;189 await expect(helper.staking.stake(staker, 500n * nominal)).to.be.rejected; // With('Arithmetic');190 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);191 });192193 itSub('for different accounts in one block is possible', async ({helper}) => {194 const crowd = await getAccounts(4);195196 const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));197 await expect(Promise.all(crowdStartsToStake)).to.be.fulfilled;198199 const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));200 expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);201 });202 });203204 describe('Unstaking', () => {205 [206 {method: 'unstakeAll' as const},207 {method: 'unstakePartial' as const},208 ].map(testCase => {209 itSub(`[${testCase.method}] should move tokens to "pendingUnstake" and subtract it from totalStaked`, async ({helper}) => {210 const [staker, recepient] = await getAccounts(2);211 const totalStakedBefore = await helper.staking.getTotalStaked();212 const STAKE_AMOUNT = 900n * nominal;213214 await helper.staking.stake(staker, STAKE_AMOUNT);215 testCase.method === 'unstakeAll'216 ? await helper.staking.unstakeAll(staker)217 : await helper.staking.unstakePartial(staker, STAKE_AMOUNT);218219 // Right after unstake tokens are still locked220 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);221 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: STAKE_AMOUNT, reasons: 'All'}]);222 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: STAKE_AMOUNT});223 // Staker can not transfer224 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith(/^Token: Frozen$/);225 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(STAKE_AMOUNT);226 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);227 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);228 });229 });230231 [232 {method: 'unstakeAll' as const},233 {method: 'unstakePartial' as const},234 ].map(testCase => {235 itSub(`[${testCase.method}] should unlock balance after unlocking period ends and remove it from "pendingUnstake"`, async ({helper}) => {236 const [staker] = await getAccounts(1);237 await helper.staking.stake(staker, 100n * nominal);238 testCase.method === 'unstakeAll'239 ? await helper.staking.unstakeAll(staker)240 : await helper.staking.unstakePartial(staker, 100n * nominal);241 const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});242243 // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n244 await helper.wait.forParachainBlockNumber(pendingUnstake.block);245 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 0n});246 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);247248 // staker can transfer:249 await helper.balance.transferToSubstrate(staker, donor.address, 998n * nominal);250 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);251 });252 });253254 [255 {method: 'unstakeAll' as const},256 {method: 'unstakePartial' as const},257 ].map(testCase => {258 itSub(`[${testCase.method}] should successfully unstake multiple stakes`, async ({helper}) => {259 const [staker] = await getAccounts(1);260 await helper.staking.stake(staker, 100n * nominal);261 await helper.staking.stake(staker, 200n * nominal);262 await helper.staking.stake(staker, 300n * nominal);263264 // staked: [100, 200, 300]; unstaked: 0265 let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});266 let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});267 let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});268 expect(totalPendingUnstake).to.be.deep.equal(0n);269 expect(pendingUnstake).to.be.deep.equal([]);270 expect(stakes[0].amount).to.equal(100n * nominal);271 expect(stakes[1].amount).to.equal(200n * nominal);272 expect(stakes[2].amount).to.equal(300n * nominal);273274 // Can unstake multiple stakes275 testCase.method === 'unstakeAll'276 ? await helper.staking.unstakeAll(staker)277 : await helper.staking.unstakePartial(staker, 600n * nominal);278279 pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});280 totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});281 stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});282 expect(totalPendingUnstake).to.be.equal(600n * nominal);283 expect(stakes).to.be.deep.equal([]);284 expect(pendingUnstake[0].amount).to.equal(600n * nominal);285286 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 600n * nominal});287 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);288 await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);289 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 0n});290 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);291 });292 });293294 [295 {method: 'unstakeAll' as const},296 {method: 'unstakePartial' as const},297 ].map(testCase => {298 itSub(`[${testCase.method}] should not have any effects if no active stakes`, async ({helper}) => {299 const [staker] = await getAccounts(1);300301 // unstake has no effect if no stakes at all302 testCase.method === 'unstakeAll'303 ? await helper.staking.unstakeAll(staker)304 : await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');305306 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);307 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper308309 // TODO stake() unstake() waitUnstaked() unstake();310311 // can't unstake if there are only pendingUnstakes312 await helper.staking.stake(staker, 100n * nominal);313314 if (testCase.method === 'unstakeAll') {315 await helper.staking.unstakeAll(staker);316 await helper.staking.unstakeAll(staker);317 } else {318 await helper.staking.unstakePartial(staker, 100n * nominal);319 await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');320 }321322 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);323 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);324 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);325 });326 });327328 [329 {method: 'unstakeAll' as const},330 {method: 'unstakePartial' as const},331 ].map(testCase => {332 itSub(`[${testCase.method}] should create different pending-unlock for each unlocking stake`, async ({helper}) => {333 const [staker] = await getAccounts(1);334 await helper.staking.stake(staker, 100n * nominal);335 testCase.method === 'unstakeAll'336 ? await helper.staking.unstakeAll(staker)337 : await helper.staking.unstakePartial(staker, 100n * nominal);338 await helper.staking.stake(staker, 120n * nominal);339 testCase.method === 'unstakeAll'340 ? await helper.staking.unstakeAll(staker)341 : await helper.staking.unstakePartial(staker, 120n * nominal);342343 const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});344 expect(unstakingPerBlock).has.length(2);345 expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);346 expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);347 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.equal(0);348 });349 });350351 [352 {method: 'unstakeAll' as const},353 {method: 'unstakePartial' as const},354 ].map(testCase => {355 itSub(`[${testCase.method}] should be possible for 3 accounts in one block`, async ({helper}) => {356 const stakers = await getAccounts(3);357358 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));359 await Promise.all(stakers.map(staker => {360 return testCase.method === 'unstakeAll'361 ? helper.staking.unstakeAll(staker)362 : helper.staking.unstakePartial(staker, 100n * nominal);363 }));364365 await Promise.all(stakers.map(async (staker) => {366 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);367 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);368 }));369 });370 });371372 itSub('should not be possible for more than 3 accounts in one block', async ({helper}) => {373 if (!await helper.arrange.isDevNode()) {374 const stakers = await getAccounts(10);375376 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));377 const unstakingResults = await Promise.allSettled(stakers.map((staker, i) => {378 return i % 2 === 0379 ? helper.staking.unstakeAll(staker)380 : helper.staking.unstakePartial(staker, 100n * nominal);381 }));382383 const successfulUnstakes = unstakingResults.filter(result => result.status === 'fulfilled');384 expect(successfulUnstakes).to.have.length(3);385 }386 });387388 itSub('Cannot partially unstake more than staked', async ({helper}) => {389 const [staker] = await getAccounts(1);390 // Staker stakes 300:391 await helper.staking.stake(staker, 100n * nominal);392 await helper.staking.stake(staker, 200n * nominal);393394 // cannot usntake 300.00000...1395 await expect(helper.staking.unstakePartial(staker, 300n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');396 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(2);397398 await helper.staking.unstakePartial(staker, 150n * nominal);399 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);400 await expect(helper.staking.unstakePartial(staker, 150n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');401 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);402403 // nothing broken, can unstake full amount:404 await helper.staking.unstakePartial(staker, 150n * nominal);405 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(0);406 });407408 itSub('Can partially unstake arbitrary amount', async ({helper}) => {409 const [staker] = await getAccounts(1);410 await helper.staking.stake(staker, 100n * nominal);411 await helper.staking.stake(staker, 200n * nominal);412413 // 0. Staker cannot unstake negative amount414 await expect(helper.staking.unstakePartial(staker, -1n)).to.be.rejected;415416 // 1. Staker can unstake 0 wei417 await helper.staking.unstakePartial(staker, 0n);418 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);419 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal);420 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);421422 // 2. Staker can unstake 1 wei423 await helper.staking.unstakePartial(staker, 1n);424 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);425 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal - 1n);426 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1n);427 // 2.1 The oldest stake decreased:428 let [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});429 expect(stake1.amount).to.eq(100n * nominal - 1n);430 expect(stake2.amount).to.eq(200n * nominal);431432 // 3. Staker can unstake all but 1 wei433 await helper.staking.unstakePartial(staker, 100n * nominal - 2n);434 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);435 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(200n * nominal + 1n);436 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(100n * nominal - 1n);437 [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});438 expect(stake1.amount).to.eq(1n);439 expect(stake2.amount).to.eq(200n * nominal);440 });441442 itSub('can mix different type of unstakes', async ({helper}) => {443 const [staker] = await getAccounts(1);444 await helper.staking.stake(staker, 100n * nominal);445 await helper.staking.stake(staker, 200n * nominal);446447 await helper.staking.unstakePartial(staker, 50n * nominal);448 await helper.staking.unstakeAll(staker);449 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);450 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);451 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(300n * nominal);452453 const [_unstake1, unstake2] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});454 await helper.wait.forParachainBlockNumber(unstake2.block);455456 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([]);457 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 0n});458 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(999n);459 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);460 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);461 expect(await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).to.deep.eq([]);462 });463 });464465 describe('collection sponsoring', () => {466 itSub('should actually sponsor transactions', async ({helper}) => {467 const api = helper.getApi();468 const [collectionOwner, tokenSender, receiver] = await getAccounts(3);469 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});470 const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});471 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));472 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);473474 await token.transfer(tokenSender, {Substrate: receiver.address});475 expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});476 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);477478 // senders balance the same, transaction has sponsored479 expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);480 expect (palletBalanceBefore > palletBalanceAfter).to.be.true;481 });482483 itSub('can not be set by non admin', async ({helper}) => {484 const api = helper.getApi();485 const [collectionOwner, nonAdmin] = await getAccounts(2);486487 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});488489 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;490 expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');491 });492493 itSub('should set pallet address as confirmed admin', async ({helper}) => {494 const api = helper.getApi();495 const [collectionOwner, oldSponsor] = await getAccounts(2);496497 // Can set sponsoring for collection without sponsor498 const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});499 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;500 expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});501502 // Can set sponsoring for collection with unconfirmed sponsor503 const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});504 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});505 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;506 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});507508 // Can set sponsoring for collection with confirmed sponsor509 const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});510 await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);511 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;512 expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});513 });514515 itSub('can be overwritten by collection owner', async ({helper}) => {516 const api = helper.getApi();517 const [collectionOwner, newSponsor] = await getAccounts(2);518 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});519 const collectionId = collection.collectionId;520521 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;522523 // Collection limits still can be changed by the owner524 expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;525 expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);526 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});527528 // Collection sponsor can be changed too529 expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;530 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});531 });532533 itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {534 const [owner] = await getAccounts(1);535 const api = helper.getApi();536 const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};537 const collectionWithLimits = await helper.nft.mintCollection(owner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});538539 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;540 expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);541 });542543 itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {544 const api = helper.getApi();545 const [collectionOwner] = await getAccounts(1);546547 // collection has never existed548 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;549 // collection has been burned550 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});551 await collection.burn(collectionOwner);552553 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;554 });555 });556557 describe('stopSponsoringCollection', () => {558 itSub('can not be called by non-admin', async ({helper}) => {559 const api = helper.getApi();560 const [collectionOwner, nonAdmin] = await getAccounts(2);561 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});562563 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;564565 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;566 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});567 });568569 itSub('should set sponsoring as disabled', async ({helper}) => {570 const api = helper.getApi();571 const [collectionOwner, recepient] = await getAccounts(2);572 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});573 const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});574575 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));576 await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId));577578 expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');579580 // Transactions are not sponsored anymore:581 const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);582 await token.transfer(collectionOwner, {Substrate: recepient.address});583 const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);584 expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);585 });586587 itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {588 const api = helper.getApi();589 const [collectionOwner] = await getAccounts(1);590 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});591 await collection.confirmSponsorship(collectionOwner);592593 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;594595 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});596 });597598 itSub('should reject transaction if collection does not exist', async ({helper}) => {599 const [collectionOwner] = await getAccounts(1);600 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});601602 await collection.burn(collectionOwner);603 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');604 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');605 });606 });607608 describe('contract sponsoring', () => {609 itEth('should set palletes address as a sponsor', async ({helper}) => {610 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();611 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);612 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);613614 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);615616 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;617 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);618 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({619 confirmed: {620 substrate: palletAddress,621 },622 });623 });624625 itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {626 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();627 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);628 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);629630 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;631632 // Contract is self sponsored633 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.be.deep.equal({634 confirmed: {635 ethereum: flipper.options.address.toLowerCase(),636 },637 });638639 // set promotion sponsoring640 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);641642 // new sponsor is pallet address643 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;644 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);645 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({646 confirmed: {647 substrate: palletAddress,648 },649 });650 });651652 itEth('can be overwritten by contract owner', async ({helper}) => {653 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();654 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);655 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);656657 // contract sponsored by pallet658 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);659660 // owner sets self sponsoring661 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;662663 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;664 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);665 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({666 confirmed: {667 ethereum: flipper.options.address.toLowerCase(),668 },669 });670 });671672 itEth('can not be set by non admin', async ({helper}) => {673 const [nonAdmin] = await getAccounts(1);674 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();675 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);676 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);677678 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;679680 // nonAdmin calls sponsorContract681 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');682683 // contract still self-sponsored684 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({685 confirmed: {686 ethereum: flipper.options.address.toLowerCase(),687 },688 });689 });690691 itEth('should actually sponsor transactions', async ({helper}) => {692 // Contract caller693 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);694 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);695696 // Deploy flipper697 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();698 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);699 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);700701 // Owner sets to sponsor every tx702 await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});703 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});704 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);705706 // Set promotion to the Flipper707 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);708709 // Caller calls Flipper710 await flipper.methods.flip().send({from: caller});711 expect(await flipper.methods.getValue().call()).to.be.true;712713 // The contracts and caller balances have not changed714 const callerBalance = await helper.balance.getEthereum(caller);715 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);716 expect(callerBalance).to.be.equal(1000n * nominal);717 expect(1000n * nominal === contractBalanceAfter).to.be.true;718719 // The pallet balance has decreased720 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);721 expect(palletBalanceAfter < palletBalanceBefore).to.be.true;722 });723 });724725 describe('stopSponsoringContract', () => {726 itEth('should remove pallet address from contract sponsors', async ({helper}) => {727 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);728 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();729 const flipper = await helper.eth.deployFlipper(contractOwner);730 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address);731 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);732733 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});734 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);735 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);736737 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;738 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);739 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({740 disabled: null,741 });742743 await flipper.methods.flip().send({from: caller});744 expect(await flipper.methods.getValue().call()).to.be.true;745746 const callerBalance = await helper.balance.getEthereum(caller);747 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);748749 // caller payed for call750 expect(1000n * nominal > callerBalance).to.be.true;751 expect(contractBalanceAfter).to.be.equal(100n * nominal);752 });753754 itEth('can not be called by non-admin', async ({helper}) => {755 const [nonAdmin] = await getAccounts(1);756 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();757 const flipper = await helper.eth.deployFlipper(contractOwner);758759 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);760 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]))761 .to.be.rejectedWith(/appPromotion\.NoPermission/);762 });763764 itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {765 const [nonAdmin] = await getAccounts(1);766 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();767 const flipper = await helper.eth.deployFlipper(contractOwner);768 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);769 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;770771 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');772 });773 });774775 describe('payoutStakers', () => {776 itSub('can not be called by non admin', async ({helper}) => {777 const [nonAdmin] = await getAccounts(1);778 await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');779 });780781 itSub('should increase total staked', async ({helper}) => {782 const [staker] = await getAccounts(1);783 const totalStakedBefore = await helper.staking.getTotalStaked();784 await helper.staking.stake(staker, 100n * nominal);785786 // Wait for rewards and pay787 const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});788 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));789790 const payout = await helper.admin.payoutStakers(palletAdmin, 100);791 const totalPayout = payout.reduce((prev, payout) => prev + payout.payout, 0n);792 const stakerReward = payout.find(p => p.staker === staker.address);793794 expect(stakerReward?.payout).to.eq(calculateIncome(100n * nominal) - (100n * nominal));795796 const totalStakedAfter = await helper.staking.getTotalStaked();797 expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);798 // staker can unstake799 await helper.staking.unstakeAll(staker);800 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal));801 });802803 itSub('should credit 0.05% for staking period', async ({helper}) => {804 const [staker] = await getAccounts(1);805806 await waitPromotionPeriodDoesntEnd(helper);807808 await helper.staking.stake(staker, 100n * nominal);809 await helper.staking.stake(staker, 200n * nominal);810811 // wait rewards are available:812 const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});813 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));814815 const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)!.payout;816 expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal));817818 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});819 const income1 = calculateIncome(100n * nominal);820 const income2 = calculateIncome(200n * nominal);821 expect(totalStakedPerBlock[0].amount).to.equal(income1);822 expect(totalStakedPerBlock[1].amount).to.equal(income2);823824 const stakerBalance = await helper.balance.getSubstrateFull(staker.address);825 expect(stakerBalance).to.contain({frozen: income1 + income2, reserved: 0n});826 expect(stakerBalance.free / nominal).to.eq(999n);827 });828829 itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {830 const [staker] = await getAccounts(1);831832 await helper.staking.stake(staker, 100n * nominal);833 // wait for two rewards are available:834 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});835 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);836837 await helper.admin.payoutStakers(palletAdmin, 100);838 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});839 const frozenBalanceShouldBe = calculateIncome(100n * nominal, 2);840 expect(stake.amount).to.be.equal(frozenBalanceShouldBe);841842 const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);843844 expect(stakerFullBalance).to.contain({reserved: 0n, frozen: frozenBalanceShouldBe});845 });846847 itSub('should not be credited for pending-unstaked tokens', async ({helper}) => {848 // staker unstakes before rewards been payed849 const [staker] = await getAccounts(1);850 await helper.staking.stake(staker, 100n * nominal);851 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});852 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);853 await helper.staking.unstakeAll(staker);854855 // so he did not receive any rewards856 const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);857 await helper.admin.payoutStakers(palletAdmin, 100);858 const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);859860 expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);861 });862863 itSub('should bring compound interest', async ({helper}) => {864 const [staker] = await getAccounts(1);865866 await helper.staking.stake(staker, 100n * nominal);867868 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});869 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));870871 await helper.admin.payoutStakers(palletAdmin, 100);872 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});873 expect(stake.amount).to.equal(calculateIncome(100n * nominal));874875 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);876 await helper.admin.payoutStakers(palletAdmin, 100);877 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});878 expect(stake.amount).to.equal(calculateIncome(100n * nominal, 2));879 });880881 itSub('can calculate reward for tiny stake', async ({helper}) => {882 const [staker] = await getAccounts(1);883 await helper.staking.stake(staker, 100n * nominal);884 await helper.staking.stake(staker, 100n * nominal);885 await helper.staking.unstakePartial(staker, 100n * nominal - 1n);886887 const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});888 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));889890 const stakerPayout = await payUntilRewardFor(staker.address, helper);891 expect(stakerPayout.stake).to.eq(100n * nominal + 1n);892 });893894 itSub('can eventually pay all rewards', async ({helper}) => {895 const stakers = await getAccounts(30);896 // Create 30 stakes:897 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));898899 let unstakingTxs = [];900 for (const staker of stakers) {901 if (unstakingTxs.length == 3) {902 await Promise.all(unstakingTxs);903 unstakingTxs = [];904 }905 unstakingTxs.push(helper.staking.unstakePartial(staker, 100n * nominal - 1n));906 }907908 const [staker] = await getAccounts(1);909 await helper.staking.stake(staker, 100n * nominal);910 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});911 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));912913 let payouts;914 do {915 payouts = await helper.admin.payoutStakers(palletAdmin, 20);916 } while (payouts.length !== 0);917 });918 });919920 describe('events', () => {921 [922 {method: 'unstakePartial' as const},923 {method: 'unstakeAll' as const},924 ].map(testCase => {925 itSub(testCase.method, async ({helper}) => {926 const unstakeParams: [] | [bigint] = testCase.method === 'unstakePartial'927 ? [100n * nominal - 1n]928 : [];929 const [staker] = await getAccounts(1);930 await helper.staking.stake(staker, 100n * nominal);931 await helper.staking.stake(staker, 200n * nominal);932 const {result} = await helper.executeExtrinsic(staker, `api.tx.appPromotion.${testCase.method}`, unstakeParams);933934 const event = result.events.find(e => e.event.section === 'appPromotion' && e.event.method === 'Unstake');935 const unstakerEvents = event?.event.data[0].toString();936 const unstakedEvents = BigInt(event?.event.data[1].toString());937 expect(unstakerEvents).to.eq(staker.address);938 expect(unstakedEvents).to.eq(testCase.method === 'unstakeAll' ? 300n * nominal : 100n * nominal - 1n);939 });940 });941942 itSub('stake', async ({helper}) => {943 const [staker] = await getAccounts(1);944 const {result} = await helper.executeExtrinsic(staker, 'api.tx.appPromotion.stake', [100n * nominal]);945946 const event = result.events.find(e => e.event.section === 'appPromotion' && e.event.method === 'Stake');947 const stakerEvents = event?.event.data[0].toString();948 const stakedEvents = BigInt(event?.event.data[1].toString());949 expect(stakerEvents).to.eq(staker.address);950 expect(stakedEvents).to.eq(100n * nominal);951 });952953 // Flaky954 itSub.skip('payoutStakers', async ({helper}) => {955 const [staker1, staker2] = await getAccounts(2);956 const STAKE1 = 100n * nominal;957 const STAKE2 = 200n * nominal;958 await helper.staking.stake(staker1, STAKE1);959 await helper.staking.stake(staker2, STAKE2);960961 const [stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker2.address});962 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));963964 const results = await helper.admin.payoutStakers(palletAdmin, 100);965 const stakersEvents = results.filter(ev => ev.staker === staker1.address || ev.staker === staker2.address);966 expect(stakersEvents).has.length(2);967 expect(stakersEvents).has.not.ordered.members([968 {staker: staker1.address, stake: STAKE1, payout: calculateIncome(STAKE1) - STAKE1},969 {staker: staker2.address, stake: STAKE2, payout: calculateIncome(STAKE2) - STAKE2},970 ]);971 });972 });973});974975976// Sometimes is is required to make a cycle in order for the payment to be calculated for a specific account977async function payUntilRewardFor(account: string, helper: DevUniqueHelper) {978 for (let i = 0; i < 3; i++) {979 const payouts = await helper.admin.payoutStakers(palletAdmin, 100);980 const accountPayout = payouts.find(p => p.staker === account);981 if (accountPayout) return accountPayout;982 }983 throw Error(`Cannot find payout for ${account}`);984}985986function calculateIncome(base: bigint, iter = 0, calcPeriod: bigint = UNLOCKING_PERIOD): bigint {987 const DAY = 7200n;988 const ACCURACY = 1_000_000_000n;989 // 5n / 10_000n = 0.05% p/day990 const income = base + base * (ACCURACY * (calcPeriod * 5n) / (10_000n * DAY)) / ACCURACY ;991992 if (iter > 1) {993 return calculateIncome(income, iter - 1, calcPeriod);994 } else return income;995}996997function rewardAvailableInBlock(stakedInBlock: bigint) {998 if (stakedInBlock % LOCKING_PERIOD === 0n) return stakedInBlock + LOCKING_PERIOD;999 return (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);1000}10011002// Wait while promotion period less than specified block, to avoid boundary cases1003// 0 if this should be the beginning of the period.1004async function waitPromotionPeriodDoesntEnd(helper: DevUniqueHelper, waitBlockLessThan = LOCKING_PERIOD / 3n) {1005 const relayBlockNumber = (await helper.callRpc('api.query.parachainSystem.validationData', [])).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();1006 const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;10071008 if (currentPeriodBlock > waitBlockLessThan) {1009 await helper.wait.forRelayBlockNumber(BigInt(relayBlockNumber) + LOCKING_PERIOD - currentPeriodBlock);1010 }1011}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 // Make sure previousCalculatedRecord is None to avoid problem with payout stakers;75 await helper.admin.payoutStakers(palletAdmin, 100);76 expect((await helper.getApi().query.appPromotion.previousCalculatedRecord() as any).isNone).to.be.true;77 });78 });7980 describe('stake extrinsic', () => {81 itSub('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {82 const [staker, recepient] = await getAccounts(2);83 const totalStakedBefore = await helper.staking.getTotalStaked();8485 // Minimum stake amount is 100:86 await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;87 await helper.staking.stake(staker, 100n * nominal);8889 // Staker balance is: frozen: 100, reserved: 0n...90 // ...so he can not transfer 90091 expect(await helper.balance.getSubstrateFull(staker.address)).to.contain({frozen: 100n * nominal, reserved: 0n});92 expect(await helper.balance.getFrozen(staker.address)).to.deep.eq([{id: 'appstake', amount: 100n * nominal}]);93 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejectedWith(/^Token: Frozen$/);9495 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);96 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);97 // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo?98 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased99100101 await helper.staking.stake(staker, 200n * nominal);102 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);103 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});104 expect(totalStakedPerBlock[0].amount).to.equal(100n * nominal);105 expect(totalStakedPerBlock[1].amount).to.equal(200n * nominal);106 });107108 [109 {unstake: 'unstakeAll' as const},110 {unstake: 'unstakePartial' as const},111 ].map(testCase => {112 itSub(`[${testCase.unstake}] should allow to create maximum 10 stakes for account`, async ({helper}) => {113 const [staker] = await getAccounts(1, 2000n);114 const ONE_STAKE = 100n * nominal;115 for (let i = 0; i < 10; i++) {116 await helper.staking.stake(staker, ONE_STAKE);117 }118119 // can have 10 stakes120 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);121 expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);122123 await expect(helper.staking.stake(staker, ONE_STAKE)).to.be.rejectedWith('appPromotion.NoPermission');124125 // After unstake can stake again126127 // CASE 1: unstakeAll128 if (testCase.unstake === 'unstakeAll') {129 await helper.staking.unstakeAll(staker);130 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);131 await helper.staking.stake(staker, 100n * nominal);132 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);133 }134 // CASE 2: unstakePartial135 else {136 await helper.staking.unstakePartial(staker, ONE_STAKE);137 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);138 await helper.staking.stake(staker, 100n * nominal);139 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(10);140 await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');141 await helper.staking.unstakePartial(staker, 150n * nominal);142 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);143 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(850n * nominal);144 }145 });146 });147148 itSub('should allow to stake() if balance is locked with different id', async ({helper}) => {149 const [staker] = await getAccounts(1);150151 // staker has tokens locked with vesting id:152 await helper.balance.vestedTransfer(donor, staker.address, {start: 0n, period: 1n, periodCount: 1n, perPeriod: 200n * nominal});153 expect(await helper.balance.getSubstrateFull(staker.address))154 .to.deep.contain({free: 1200n * nominal, frozen: 200n * nominal, reserved: 0n});155156 // Locked balance can be staked. staker can stake 1200 tokens (minus fee):157 await helper.staking.stake(staker, 1000n * nominal);158 await helper.staking.stake(staker, 199n * nominal);159 // check balances160 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}]);161 expect(await helper.balance.getFrozen(staker.address)).to.deep.eq([{id: 'appstake', amount: 1199n * nominal}]);162 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 1199n * nominal});163 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(1199n);164 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(1199n * nominal);165166 // staker can unstake167 await helper.staking.unstakeAll(staker);168 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1199n * nominal);169 const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});170 await helper.wait.forParachainBlockNumber(pendingUnstake.block);171172 // check balances173 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}]);174 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 200n * nominal});175 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(1199n);176 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);177178 // staker can transfer balances now179 await helper.balance.transferToSubstrate(staker, donor.address, 900n * nominal);180 });181182 itSub('should not allow to stake(), if stake amount is more than total free balance minus locked by staking', async ({helper}) => {183 const [staker] = await getAccounts(1);184185 // Can't stake full balance because Alice needs to pay some fee186 await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected; // With('Arithmetic')187 await helper.staking.stake(staker, 500n * nominal);188189 // Can't stake 500 tkn because Alice has Less than 500 transferable;190 await expect(helper.staking.stake(staker, 500n * nominal)).to.be.rejected; // With('Arithmetic');191 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);192 });193194 itSub('for different accounts in one block is possible', async ({helper}) => {195 const crowd = await getAccounts(4);196197 const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));198 await expect(Promise.all(crowdStartsToStake)).to.be.fulfilled;199200 const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));201 expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);202 });203 });204205 describe('Unstaking', () => {206 [207 {method: 'unstakeAll' as const},208 {method: 'unstakePartial' as const},209 ].map(testCase => {210 itSub(`[${testCase.method}] should move tokens to "pendingUnstake" and subtract it from totalStaked`, async ({helper}) => {211 const [staker, recepient] = await getAccounts(2);212 const totalStakedBefore = await helper.staking.getTotalStaked();213 const STAKE_AMOUNT = 900n * nominal;214215 await helper.staking.stake(staker, STAKE_AMOUNT);216 testCase.method === 'unstakeAll'217 ? await helper.staking.unstakeAll(staker)218 : await helper.staking.unstakePartial(staker, STAKE_AMOUNT);219220 // Right after unstake tokens are still locked221 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);222 expect(await helper.balance.getFrozen(staker.address)).to.deep.eq([{id: 'appstake', amount: STAKE_AMOUNT}]);223 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: STAKE_AMOUNT});224 // Staker can not transfer225 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith(/^Token: Frozen$/);226 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(STAKE_AMOUNT);227 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);228 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);229 });230 });231232 [233 {method: 'unstakeAll' as const},234 {method: 'unstakePartial' as const},235 ].map(testCase => {236 itSub(`[${testCase.method}] should unlock balance after unlocking period ends and remove it from "pendingUnstake"`, async ({helper}) => {237 const [staker] = await getAccounts(1);238 await helper.staking.stake(staker, 100n * nominal);239 testCase.method === 'unstakeAll'240 ? await helper.staking.unstakeAll(staker)241 : await helper.staking.unstakePartial(staker, 100n * nominal);242 const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});243244 // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n245 await helper.wait.forParachainBlockNumber(pendingUnstake.block);246 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 0n});247 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);248249 // staker can transfer:250 await helper.balance.transferToSubstrate(staker, donor.address, 998n * nominal);251 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);252 });253 });254255 [256 {method: 'unstakeAll' as const},257 {method: 'unstakePartial' as const},258 ].map(testCase => {259 itSub(`[${testCase.method}] should successfully unstake multiple stakes`, async ({helper}) => {260 const [staker] = await getAccounts(1);261 await helper.staking.stake(staker, 100n * nominal);262 await helper.staking.stake(staker, 200n * nominal);263 await helper.staking.stake(staker, 300n * nominal);264265 // staked: [100, 200, 300]; unstaked: 0266 let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});267 let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});268 let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});269 expect(totalPendingUnstake).to.be.deep.equal(0n);270 expect(pendingUnstake).to.be.deep.equal([]);271 expect(stakes[0].amount).to.equal(100n * nominal);272 expect(stakes[1].amount).to.equal(200n * nominal);273 expect(stakes[2].amount).to.equal(300n * nominal);274275 // Can unstake multiple stakes276 testCase.method === 'unstakeAll'277 ? await helper.staking.unstakeAll(staker)278 : await helper.staking.unstakePartial(staker, 600n * nominal);279280 pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});281 totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});282 stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});283 expect(totalPendingUnstake).to.be.equal(600n * nominal);284 expect(stakes).to.be.deep.equal([]);285 expect(pendingUnstake[0].amount).to.equal(600n * nominal);286287 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 600n * nominal});288 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);289 await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);290 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 0n});291 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);292 });293 });294295 [296 {method: 'unstakeAll' as const},297 {method: 'unstakePartial' as const},298 ].map(testCase => {299 itSub(`[${testCase.method}] should not have any effects if no active stakes`, async ({helper}) => {300 const [staker] = await getAccounts(1);301302 // unstake has no effect if no stakes at all303 testCase.method === 'unstakeAll'304 ? await helper.staking.unstakeAll(staker)305 : await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');306307 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);308 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper309310 // TODO stake() unstake() waitUnstaked() unstake();311312 // can't unstake if there are only pendingUnstakes313 await helper.staking.stake(staker, 100n * nominal);314315 if (testCase.method === 'unstakeAll') {316 await helper.staking.unstakeAll(staker);317 await helper.staking.unstakeAll(staker);318 } else {319 await helper.staking.unstakePartial(staker, 100n * nominal);320 await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');321 }322323 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);324 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);325 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);326 });327 });328329 [330 {method: 'unstakeAll' as const},331 {method: 'unstakePartial' as const},332 ].map(testCase => {333 itSub(`[${testCase.method}] should create different pending-unlock for each unlocking stake`, async ({helper}) => {334 const [staker] = await getAccounts(1);335 await helper.staking.stake(staker, 100n * nominal);336 testCase.method === 'unstakeAll'337 ? await helper.staking.unstakeAll(staker)338 : await helper.staking.unstakePartial(staker, 100n * nominal);339 await helper.staking.stake(staker, 120n * nominal);340 testCase.method === 'unstakeAll'341 ? await helper.staking.unstakeAll(staker)342 : await helper.staking.unstakePartial(staker, 120n * nominal);343344 const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});345 expect(unstakingPerBlock).has.length(2);346 expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);347 expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);348 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.equal(0);349 });350 });351352 [353 {method: 'unstakeAll' as const},354 {method: 'unstakePartial' as const},355 ].map(testCase => {356 itSub(`[${testCase.method}] should be possible for 3 accounts in one block`, async ({helper}) => {357 const stakers = await getAccounts(3);358359 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));360 await Promise.all(stakers.map(staker => {361 return testCase.method === 'unstakeAll'362 ? helper.staking.unstakeAll(staker)363 : helper.staking.unstakePartial(staker, 100n * nominal);364 }));365366 await Promise.all(stakers.map(async (staker) => {367 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);368 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);369 }));370 });371 });372373 itSub('should not be possible for more than 3 accounts in one block', async ({helper}) => {374 if (!await helper.arrange.isDevNode()) {375 const stakers = await getAccounts(10);376377 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));378 const unstakingResults = await Promise.allSettled(stakers.map((staker, i) => {379 return i % 2 === 0380 ? helper.staking.unstakeAll(staker)381 : helper.staking.unstakePartial(staker, 100n * nominal);382 }));383384 const successfulUnstakes = unstakingResults.filter(result => result.status === 'fulfilled');385 expect(successfulUnstakes).to.have.length(3);386 }387 });388389 itSub('Cannot partially unstake more than staked', async ({helper}) => {390 const [staker] = await getAccounts(1);391 // Staker stakes 300:392 await helper.staking.stake(staker, 100n * nominal);393 await helper.staking.stake(staker, 200n * nominal);394395 // cannot usntake 300.00000...1396 await expect(helper.staking.unstakePartial(staker, 300n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');397 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(2);398399 await helper.staking.unstakePartial(staker, 150n * nominal);400 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);401 await expect(helper.staking.unstakePartial(staker, 150n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');402 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);403404 // nothing broken, can unstake full amount:405 await helper.staking.unstakePartial(staker, 150n * nominal);406 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(0);407 });408409 itSub('Can partially unstake arbitrary amount', async ({helper}) => {410 const [staker] = await getAccounts(1);411 await helper.staking.stake(staker, 100n * nominal);412 await helper.staking.stake(staker, 200n * nominal);413414 // 0. Staker cannot unstake negative amount415 await expect(helper.staking.unstakePartial(staker, -1n)).to.be.rejected;416417 // 1. Staker can unstake 0 wei418 await helper.staking.unstakePartial(staker, 0n);419 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);420 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal);421 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);422423 // 2. Staker can unstake 1 wei424 await helper.staking.unstakePartial(staker, 1n);425 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);426 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal - 1n);427 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1n);428 // 2.1 The oldest stake decreased:429 let [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});430 expect(stake1.amount).to.eq(100n * nominal - 1n);431 expect(stake2.amount).to.eq(200n * nominal);432433 // 3. Staker can unstake all but 1 wei434 await helper.staking.unstakePartial(staker, 100n * nominal - 2n);435 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);436 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(200n * nominal + 1n);437 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(100n * nominal - 1n);438 [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});439 expect(stake1.amount).to.eq(1n);440 expect(stake2.amount).to.eq(200n * nominal);441 });442443 itSub('can mix different type of unstakes', async ({helper}) => {444 const [staker] = await getAccounts(1);445 await helper.staking.stake(staker, 100n * nominal);446 await helper.staking.stake(staker, 200n * nominal);447448 await helper.staking.unstakePartial(staker, 50n * nominal);449 await helper.staking.unstakeAll(staker);450 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);451 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);452 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(300n * nominal);453454 const [_unstake1, unstake2] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});455 await helper.wait.forParachainBlockNumber(unstake2.block);456457 expect(await helper.balance.getFrozen(staker.address)).to.deep.eq([]);458 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 0n});459 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(999n);460 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);461 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);462 expect(await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).to.deep.eq([]);463 });464 });465466 describe('collection sponsoring', () => {467 itSub('should actually sponsor transactions', async ({helper}) => {468 const api = helper.getApi();469 const [collectionOwner, tokenSender, receiver] = await getAccounts(3);470 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});471 const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});472 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));473 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);474475 await token.transfer(tokenSender, {Substrate: receiver.address});476 expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});477 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);478479 // senders balance the same, transaction has sponsored480 expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);481 expect (palletBalanceBefore > palletBalanceAfter).to.be.true;482 });483484 itSub('can not be set by non admin', async ({helper}) => {485 const api = helper.getApi();486 const [collectionOwner, nonAdmin] = await getAccounts(2);487488 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});489490 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;491 expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');492 });493494 itSub('should set pallet address as confirmed admin', async ({helper}) => {495 const api = helper.getApi();496 const [collectionOwner, oldSponsor] = await getAccounts(2);497498 // Can set sponsoring for collection without sponsor499 const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});500 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;501 expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});502503 // Can set sponsoring for collection with unconfirmed sponsor504 const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});505 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});506 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;507 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});508509 // Can set sponsoring for collection with confirmed sponsor510 const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});511 await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);512 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;513 expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});514 });515516 itSub('can be overwritten by collection owner', async ({helper}) => {517 const api = helper.getApi();518 const [collectionOwner, newSponsor] = await getAccounts(2);519 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});520 const collectionId = collection.collectionId;521522 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;523524 // Collection limits still can be changed by the owner525 expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;526 expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);527 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});528529 // Collection sponsor can be changed too530 expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;531 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});532 });533534 itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {535 const [owner] = await getAccounts(1);536 const api = helper.getApi();537 const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};538 const collectionWithLimits = await helper.nft.mintCollection(owner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});539540 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;541 expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);542 });543544 itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {545 const api = helper.getApi();546 const [collectionOwner] = await getAccounts(1);547548 // collection has never existed549 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;550 // collection has been burned551 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});552 await collection.burn(collectionOwner);553554 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;555 });556 });557558 describe('stopSponsoringCollection', () => {559 itSub('can not be called by non-admin', async ({helper}) => {560 const api = helper.getApi();561 const [collectionOwner, nonAdmin] = await getAccounts(2);562 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});563564 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;565566 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;567 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});568 });569570 itSub('should set sponsoring as disabled', async ({helper}) => {571 const api = helper.getApi();572 const [collectionOwner, recepient] = await getAccounts(2);573 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});574 const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});575576 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));577 await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId));578579 expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');580581 // Transactions are not sponsored anymore:582 const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);583 await token.transfer(collectionOwner, {Substrate: recepient.address});584 const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);585 expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);586 });587588 itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {589 const api = helper.getApi();590 const [collectionOwner] = await getAccounts(1);591 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});592 await collection.confirmSponsorship(collectionOwner);593594 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;595596 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});597 });598599 itSub('should reject transaction if collection does not exist', async ({helper}) => {600 const [collectionOwner] = await getAccounts(1);601 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});602603 await collection.burn(collectionOwner);604 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');605 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');606 });607 });608609 describe('contract sponsoring', () => {610 itEth('should set palletes address as a sponsor', async ({helper}) => {611 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();612 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);613 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);614615 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);616617 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;618 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);619 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({620 confirmed: {621 substrate: palletAddress,622 },623 });624 });625626 itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {627 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();628 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);629 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);630631 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;632633 // Contract is self sponsored634 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.be.deep.equal({635 confirmed: {636 ethereum: flipper.options.address.toLowerCase(),637 },638 });639640 // set promotion sponsoring641 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);642643 // new sponsor is pallet address644 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;645 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);646 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({647 confirmed: {648 substrate: palletAddress,649 },650 });651 });652653 itEth('can be overwritten by contract owner', async ({helper}) => {654 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();655 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);656 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);657658 // contract sponsored by pallet659 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);660661 // owner sets self sponsoring662 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;663664 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;665 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);666 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({667 confirmed: {668 ethereum: flipper.options.address.toLowerCase(),669 },670 });671 });672673 itEth('can not be set by non admin', async ({helper}) => {674 const [nonAdmin] = await getAccounts(1);675 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();676 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);677 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);678679 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;680681 // nonAdmin calls sponsorContract682 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');683684 // contract still self-sponsored685 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({686 confirmed: {687 ethereum: flipper.options.address.toLowerCase(),688 },689 });690 });691692 itEth('should actually sponsor transactions', async ({helper}) => {693 // Contract caller694 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);695 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);696697 // Deploy flipper698 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();699 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);700 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);701702 // Owner sets to sponsor every tx703 await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});704 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});705 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);706707 // Set promotion to the Flipper708 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);709710 // Caller calls Flipper711 await flipper.methods.flip().send({from: caller});712 expect(await flipper.methods.getValue().call()).to.be.true;713714 // The contracts and caller balances have not changed715 const callerBalance = await helper.balance.getEthereum(caller);716 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);717 expect(callerBalance).to.be.equal(1000n * nominal);718 expect(1000n * nominal === contractBalanceAfter).to.be.true;719720 // The pallet balance has decreased721 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);722 expect(palletBalanceAfter < palletBalanceBefore).to.be.true;723 });724 });725726 describe('stopSponsoringContract', () => {727 itEth('should remove pallet address from contract sponsors', async ({helper}) => {728 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);729 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();730 const flipper = await helper.eth.deployFlipper(contractOwner);731 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address);732 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);733734 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});735 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);736 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);737738 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;739 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);740 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({741 disabled: null,742 });743744 await flipper.methods.flip().send({from: caller});745 expect(await flipper.methods.getValue().call()).to.be.true;746747 const callerBalance = await helper.balance.getEthereum(caller);748 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);749750 // caller payed for call751 expect(1000n * nominal > callerBalance).to.be.true;752 expect(contractBalanceAfter).to.be.equal(100n * nominal);753 });754755 itEth('can not be called by non-admin', async ({helper}) => {756 const [nonAdmin] = await getAccounts(1);757 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();758 const flipper = await helper.eth.deployFlipper(contractOwner);759760 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);761 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]))762 .to.be.rejectedWith(/appPromotion\.NoPermission/);763 });764765 itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {766 const [nonAdmin] = await getAccounts(1);767 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();768 const flipper = await helper.eth.deployFlipper(contractOwner);769 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);770 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;771772 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');773 });774 });775776 describe('payoutStakers', () => {777 itSub('can not be called by non admin', async ({helper}) => {778 const [nonAdmin] = await getAccounts(1);779 await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');780 });781782 itSub('should increase total staked', async ({helper}) => {783 const [staker] = await getAccounts(1);784 const totalStakedBefore = await helper.staking.getTotalStaked();785 await helper.staking.stake(staker, 100n * nominal);786787 // Wait for rewards and pay788 const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});789 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));790791 const payout = await helper.admin.payoutStakers(palletAdmin, 100);792 const totalPayout = payout.reduce((prev, payout) => prev + payout.payout, 0n);793 const stakerReward = payout.find(p => p.staker === staker.address);794795 expect(stakerReward?.payout).to.eq(calculateIncome(100n * nominal) - (100n * nominal));796797 const totalStakedAfter = await helper.staking.getTotalStaked();798 expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);799 // staker can unstake800 await helper.staking.unstakeAll(staker);801 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal));802 });803804 itSub('should credit 0.05% for staking period', async ({helper}) => {805 const [staker] = await getAccounts(1);806807 await waitPromotionPeriodDoesntEnd(helper);808809 await helper.staking.stake(staker, 100n * nominal);810 await helper.staking.stake(staker, 200n * nominal);811812 // wait rewards are available:813 const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});814 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));815816 const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)!.payout;817 expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal));818819 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});820 const income1 = calculateIncome(100n * nominal);821 const income2 = calculateIncome(200n * nominal);822 expect(totalStakedPerBlock[0].amount).to.equal(income1);823 expect(totalStakedPerBlock[1].amount).to.equal(income2);824825 const stakerBalance = await helper.balance.getSubstrateFull(staker.address);826 expect(stakerBalance).to.contain({frozen: income1 + income2, reserved: 0n});827 expect(stakerBalance.free / nominal).to.eq(999n);828 });829830 itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {831 const [staker] = await getAccounts(1);832833 await helper.staking.stake(staker, 100n * nominal);834 // wait for two rewards are available:835 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});836 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);837838 await helper.admin.payoutStakers(palletAdmin, 100);839 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});840 const frozenBalanceShouldBe = calculateIncome(100n * nominal, 2);841 expect(stake.amount).to.be.equal(frozenBalanceShouldBe);842843 const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);844845 expect(stakerFullBalance).to.contain({reserved: 0n, frozen: frozenBalanceShouldBe});846 });847848 itSub('should not be credited for pending-unstaked tokens', async ({helper}) => {849 // staker unstakes before rewards been payed850 const [staker] = await getAccounts(1);851 await helper.staking.stake(staker, 100n * nominal);852 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});853 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);854 await helper.staking.unstakeAll(staker);855856 // so he did not receive any rewards857 const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);858 await helper.admin.payoutStakers(palletAdmin, 100);859 const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);860861 expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);862 });863864 itSub('should bring compound interest', async ({helper}) => {865 const [staker] = await getAccounts(1);866867 await helper.staking.stake(staker, 100n * nominal);868869 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});870 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));871872 await helper.admin.payoutStakers(palletAdmin, 100);873 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});874 expect(stake.amount).to.equal(calculateIncome(100n * nominal));875876 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);877 await helper.admin.payoutStakers(palletAdmin, 100);878 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});879 expect(stake.amount).to.equal(calculateIncome(100n * nominal, 2));880 });881882 itSub('can calculate reward for tiny stake', async ({helper}) => {883 const [staker] = await getAccounts(1);884 await helper.staking.stake(staker, 100n * nominal);885 await helper.staking.stake(staker, 100n * nominal);886 await helper.staking.unstakePartial(staker, 100n * nominal - 1n);887888 const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});889 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));890891 const stakerPayout = await payUntilRewardFor(staker.address, helper);892 expect(stakerPayout.stake).to.eq(100n * nominal + 1n);893 });894895 itSub('can eventually pay all rewards', async ({helper}) => {896 const stakers = await getAccounts(30);897 // Create 30 stakes:898 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));899900 let unstakingTxs = [];901 for (const staker of stakers) {902 if (unstakingTxs.length == 3) {903 await Promise.all(unstakingTxs);904 unstakingTxs = [];905 }906 unstakingTxs.push(helper.staking.unstakePartial(staker, 100n * nominal - 1n));907 }908909 const [staker] = await getAccounts(1);910 await helper.staking.stake(staker, 100n * nominal);911 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});912 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));913914 let payouts;915 do {916 payouts = await helper.admin.payoutStakers(palletAdmin, 20);917 } while (payouts.length !== 0);918 });919 });920921 describe('events', () => {922 [923 {method: 'unstakePartial' as const},924 {method: 'unstakeAll' as const},925 ].map(testCase => {926 itSub(testCase.method, async ({helper}) => {927 const unstakeParams: [] | [bigint] = testCase.method === 'unstakePartial'928 ? [100n * nominal - 1n]929 : [];930 const [staker] = await getAccounts(1);931 await helper.staking.stake(staker, 100n * nominal);932 await helper.staking.stake(staker, 200n * nominal);933 const {result} = await helper.executeExtrinsic(staker, `api.tx.appPromotion.${testCase.method}`, unstakeParams);934935 const event = result.events.find(e => e.event.section === 'appPromotion' && e.event.method === 'Unstake');936 const unstakerEvents = event?.event.data[0].toString();937 const unstakedEvents = BigInt(event?.event.data[1].toString());938 expect(unstakerEvents).to.eq(staker.address);939 expect(unstakedEvents).to.eq(testCase.method === 'unstakeAll' ? 300n * nominal : 100n * nominal - 1n);940 });941 });942943 itSub('stake', async ({helper}) => {944 const [staker] = await getAccounts(1);945 const {result} = await helper.executeExtrinsic(staker, 'api.tx.appPromotion.stake', [100n * nominal]);946947 const event = result.events.find(e => e.event.section === 'appPromotion' && e.event.method === 'Stake');948 const stakerEvents = event?.event.data[0].toString();949 const stakedEvents = BigInt(event?.event.data[1].toString());950 expect(stakerEvents).to.eq(staker.address);951 expect(stakedEvents).to.eq(100n * nominal);952 });953954 // Flaky955 itSub.skip('payoutStakers', async ({helper}) => {956 const [staker1, staker2] = await getAccounts(2);957 const STAKE1 = 100n * nominal;958 const STAKE2 = 200n * nominal;959 await helper.staking.stake(staker1, STAKE1);960 await helper.staking.stake(staker2, STAKE2);961962 const [stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker2.address});963 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));964965 const results = await helper.admin.payoutStakers(palletAdmin, 100);966 const stakersEvents = results.filter(ev => ev.staker === staker1.address || ev.staker === staker2.address);967 expect(stakersEvents).has.length(2);968 expect(stakersEvents).has.not.ordered.members([969 {staker: staker1.address, stake: STAKE1, payout: calculateIncome(STAKE1) - STAKE1},970 {staker: staker2.address, stake: STAKE2, payout: calculateIncome(STAKE2) - STAKE2},971 ]);972 });973 });974});975976977// Sometimes is is required to make a cycle in order for the payment to be calculated for a specific account978async function payUntilRewardFor(account: string, helper: DevUniqueHelper) {979 for (let i = 0; i < 3; i++) {980 const payouts = await helper.admin.payoutStakers(palletAdmin, 100);981 const accountPayout = payouts.find(p => p.staker === account);982 if (accountPayout) return accountPayout;983 }984 throw Error(`Cannot find payout for ${account}`);985}986987function calculateIncome(base: bigint, iter = 0, calcPeriod: bigint = UNLOCKING_PERIOD): bigint {988 const DAY = 7200n;989 const ACCURACY = 1_000_000_000n;990 // 5n / 10_000n = 0.05% p/day991 const income = base + base * (ACCURACY * (calcPeriod * 5n) / (10_000n * DAY)) / ACCURACY ;992993 if (iter > 1) {994 return calculateIncome(income, iter - 1, calcPeriod);995 } else return income;996}997998function rewardAvailableInBlock(stakedInBlock: bigint) {999 if (stakedInBlock % LOCKING_PERIOD === 0n) return stakedInBlock + LOCKING_PERIOD;1000 return (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);1001}10021003// Wait while promotion period less than specified block, to avoid boundary cases1004// 0 if this should be the beginning of the period.1005async function waitPromotionPeriodDoesntEnd(helper: DevUniqueHelper, waitBlockLessThan = LOCKING_PERIOD / 3n) {1006 const relayBlockNumber = (await helper.callRpc('api.query.parachainSystem.validationData', [])).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();1007 const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;10081009 if (currentPeriodBlock > waitBlockLessThan) {1010 await helper.wait.forRelayBlockNumber(BigInt(relayBlockNumber) + LOCKING_PERIOD - currentPeriodBlock);1011 }1012}tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -7,11 +7,8 @@
import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';
import {SignerOptions} from '@polkadot/api/types/submittable';
-import '../../interfaces/augment-api-tx';
+import '../../interfaces/augment-api';
import {AugmentedSubmittables} from '@polkadot/api-base/types/submittable';
-import {RpcInterface} from '@polkadot/rpc-core/types';
-import {QueryableStorage} from '@polkadot/api-base/types/storage';
-import {DecoratedRpc} from '@polkadot/api-base/types/rpc';
import {ApiInterfaceEvents} from '@polkadot/api/types';
import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';
import {IKeyringPair} from '@polkadot/types/types';
@@ -50,7 +47,7 @@
} from './types';
import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';
import type {Vec} from '@polkadot/types-codec';
-import {FrameSystemEventRecord} from '@polkadot/types/lookup';
+import {FrameSystemEventRecord, PalletBalancesIdAmount} from '@polkadot/types/lookup';
export class CrossAccountId {
Substrate!: TSubstrateAccount;
@@ -379,15 +376,6 @@
type Get2<T, P extends string, E> =
P extends `${infer Key}.${infer Key2}` ? Key extends keyof T ? Key2 extends keyof T[Key] ? T[Key][Key2] : E : E : E;
type ForceFunction<T> = T extends (...args: any) => any ? T : (...args: any) => Invalid<'not a function'>;
-type ReturnTypeWithArgs<T extends (...args: any[]) => any, ARGS_T> =
- Extract<
- T extends { (...args: infer A1): infer R1; (...args: infer A2): infer R2; (...args: infer A3): infer R3; (...args: infer A4): infer R4; } ? [A1, R1] | [A2, R2] | [A3, R3] | [A4, R4] :
- T extends { (...args: infer A1): infer R1; (...args: infer A2): infer R2; (...args: infer A3): infer R3; } ? [A1, R1] | [A2, R2] | [A3, R3] :
- T extends { (...args: infer A1): infer R1; (...args: infer A2): infer R2; } ? [A1, R1] | [A2, R2] :
- T extends { (...args: infer A1): infer R1; } ? [A1, R1] :
- never,
- [ARGS_T, any]
- >[1]
export class ChainHelperBase {
helperBase: any;
@@ -677,12 +665,12 @@
async executeExtrinsic<
E extends string,
V extends (
-...args: any) => any = ForceFunction<
- Get2<
- AugmentedSubmittables<'promise'>,
- E, (...args: any) => Invalid<'not found'>
+ ...args: any) => any = ForceFunction<
+ Get2<
+ AugmentedSubmittables<'promise'>,
+ E, (...args: any) => Invalid<'not found'>
+ >
>
- >
>(
sender: TSigner,
extrinsic: `api.tx.${E}`,
@@ -1756,9 +1744,7 @@
children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);
}
- return children.toJSON().map((x: any) => {
- return {collectionId: x.collection, tokenId: x.token};
- });
+ return children.toJSON().map((x: any) => ({collectionId: x.collection, tokenId: x.token}));
}
/**
@@ -2409,9 +2395,13 @@
return total.toBigInt();
}
- async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {
+ async getLocked(address: TSubstrateAccount): Promise<[{ id: string, amount: bigint, reason: string }]> {
const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();
- return locks.map((lock: any) => { return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons}; });
+ return locks.map((lock: any) => ({id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons}));
+ }
+ async getFrozen(address: TSubstrateAccount): Promise<{ id: string, amount: bigint }[]> {
+ const locks = await this.helper.api!.query.balances.freezes(address);
+ return locks.map(lock => ({id: lock.id.toString(), amount: lock.amount.toBigInt()}));
}
}
@@ -2508,12 +2498,22 @@
* Get locked balances
* @param address substrate address
* @returns locked balances with reason via api.query.balances.locks
+ * @deprecated all the methods should switch to getFrozen
*/
getLocked(address: TSubstrateAccount) {
return this.subBalanceGroup.getLocked(address);
}
/**
+ * Get frozen balances
+ * @param address substrate address
+ * @returns locked balances with reason via api.query.balances.locks
+ */
+ getFrozen(address: TSubstrateAccount) {
+ return this.subBalanceGroup.getFrozen(address);
+ }
+
+ /**
* Get ethereum address balance
* @param address ethereum address
* @example getEthereum("0x9F0583DbB855d...")