1234567891011121314151617import {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}4344454647describe('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); 58 });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); 74 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 86 await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;87 await helper.staking.stake(staker, 100n * nominal);8889 90 91 expect(await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 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('balances.LiquidityRestrictions');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 98 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); 99100101 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 120 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 126127 128 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 135 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 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, miscFrozen: 200n * nominal, feeFrozen: 200n * nominal, reserved: 0n});155156 157 await helper.staking.stake(staker, 1000n * nominal);158 await helper.staking.stake(staker, 199n * nominal);159 160 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, miscFrozen: 1199n * nominal, feeFrozen: 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 166 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 172 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, miscFrozen: 200n * nominal, feeFrozen: 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 178 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 185 await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected; 186 await helper.staking.stake(staker, 500n * nominal);187188 189 await expect(helper.staking.stake(staker, 500n * nominal)).to.be.rejected; 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 220 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, miscFrozen: STAKE_AMOUNT, feeFrozen: STAKE_AMOUNT});223 224 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');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 244 await helper.wait.forParachainBlockNumber(pendingUnstake.block);245 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});246 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);247248 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 265 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 275 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, feeFrozen: 600n * nominal, miscFrozen: 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, feeFrozen: 0n, miscFrozen: 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 302 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); 308309 310311 312 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 391 await helper.staking.stake(staker, 100n * nominal);392 await helper.staking.stake(staker, 200n * nominal);393394 395 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 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 414 await expect(helper.staking.unstakePartial(staker, -1n)).to.be.rejected;415416 417 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 423 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 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 433 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, miscFrozen: 0n, feeFrozen: 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 479 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 498 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 503 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 509 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 524 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 529 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 548 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;549 550 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 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); 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); 628 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);629630 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;631632 633 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 640 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);641642 643 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); 655 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);656657 658 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);659660 661 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); 676 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);677678 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;679680 681 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');682683 684 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 693 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);694 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);695696 697 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();698 const flipper = await helper.eth.deployFlipper(contractOwner); 699 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);700701 702 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); 705706 707 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);708709 710 await flipper.methods.flip().send({from: caller});711 expect(await flipper.methods.getValue().call()).to.be.true;712713 714 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 720 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 750 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 787 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 799 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 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({miscFrozen: income1 + income2, feeFrozen: 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 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, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});845 });846847 itSub('should not be credited for pending-unstaked tokens', async ({helper}) => {848 849 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 856 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 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 = 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 954 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});974975976977async 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 990 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}1001100210031004async function waitPromotionPeriodDoesntEnd(helper: DevUniqueHelper, waitBlockLessThan = LOCKING_PERIOD / 3n) {1005 const relayBlockNumber = (await helper.callRpc('api.query.parachainSystem.validationData', [])).value.relayParentNumber.toNumber(); 1006 const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;10071008 if (currentPeriodBlock > waitBlockLessThan) {1009 await helper.wait.forRelayBlockNumber(BigInt(relayBlockNumber) + LOCKING_PERIOD - currentPeriodBlock);1010 }1011}