difftreelog
feature(runtime): app promoi rate is changed
in: master
4 files changed
js-packages/tests/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 type {IKeyringPair} from '@polkadot/types/types';18import {19 itSub, usingPlaygrounds, Pallets, requirePalletsOrSkip, LOCKING_PERIOD, UNLOCKING_PERIOD,20} from '../../util/index.js';21import {DevUniqueHelper} from '@unique/playgrounds/unique.dev.js';22import {itEth, expect, SponsoringMode} from '../../eth/util/index.js';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');5455 nominal = helper.balance.getOneTokenNominal();5657 const accountBalances = new Array(200).fill(1000n);58 accounts = await helper.arrange.createAccounts(accountBalances, donor); // create accounts-pool to speed up tests59 });60 });6162 afterEach(async () => {63 await usingPlaygrounds(async (helper) => {64 let unstakeTxs = [];65 for(const account of usedAccounts) {66 if(unstakeTxs.length === 3) {67 await Promise.all(unstakeTxs);68 unstakeTxs = [];69 }70 unstakeTxs.push(helper.staking.unstakeAll(account));71 }72 await Promise.all(unstakeTxs);73 usedAccounts = [];74 expect(await helper.staking.getTotalStaked()).to.eq(0n); // there are no active stakes after each test75 // Make sure previousCalculatedRecord is None to avoid problem with payout stakers;76 await helper.admin.payoutStakers(palletAdmin, 100);77 expect((await helper.getApi().query.appPromotion.previousCalculatedRecord() as any).isNone).to.be.true;78 });79 });8081 describe('stake extrinsic', () => {82 itSub('should "freeze" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {83 const [staker, recepient] = await getAccounts(2);84 const totalStakedBefore = await helper.staking.getTotalStaked();8586 // Minimum stake amount is 100:87 await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;88 await helper.staking.stake(staker, 100n * nominal);8990 // Staker balance is: frozen: 100, reserved: 0n...91 // ...so he can not transfer 90092 expect(await helper.balance.getSubstrateFull(staker.address)).to.contain({frozen: 100n * nominal, reserved: 0n});93 expect(await helper.balance.getFrozen(staker.address)).to.deep.eq([{id: 'appstakeappstake', amount: 100n * nominal}]);94 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejectedWith(/^Token: Frozen$/);9596 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);97 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);98 // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo?99 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased100101 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 });147 // TODO: Now AppPromo makes freezes. Probably this test should be changed\removed.148 itSub.skip('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: 'appstakeappstake', 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: 'appstakeappstake', 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 => testCase.method === 'unstakeAll'361 ? helper.staking.unstakeAll(staker)362 : helper.staking.unstakePartial(staker, 100n * nominal)));363364 await Promise.all(stakers.map(async (staker) => {365 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);366 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);367 }));368 });369 });370371 itSub('should not be possible for more than 3 accounts in one block', async ({helper}) => {372 if(!await helper.arrange.isDevNode()) {373 const stakers = await getAccounts(10);374375 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));376 const unstakingResults = await Promise.allSettled(stakers.map((staker, i) => i % 2 === 0377 ? helper.staking.unstakeAll(staker)378 : helper.staking.unstakePartial(staker, 100n * nominal)));379380 const successfulUnstakes = unstakingResults.filter(result => result.status === 'fulfilled');381 expect(successfulUnstakes).to.have.length(3);382 }383 });384385 itSub('Cannot partially unstake more than staked', async ({helper}) => {386 const [staker] = await getAccounts(1);387 // Staker stakes 300:388 await helper.staking.stake(staker, 100n * nominal);389 await helper.staking.stake(staker, 200n * nominal);390391 // cannot usntake 300.00000...1392 await expect(helper.staking.unstakePartial(staker, 300n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');393 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(2);394395 await helper.staking.unstakePartial(staker, 150n * nominal);396 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);397 await expect(helper.staking.unstakePartial(staker, 150n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');398 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);399400 // nothing broken, can unstake full amount:401 await helper.staking.unstakePartial(staker, 150n * nominal);402 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(0);403 });404405 itSub('Can partially unstake arbitrary amount', async ({helper}) => {406 const [staker] = await getAccounts(1);407 await helper.staking.stake(staker, 100n * nominal);408 await helper.staking.stake(staker, 200n * nominal);409410 // 0. Staker cannot unstake negative amount411 await expect(helper.staking.unstakePartial(staker, -1n)).to.be.rejected;412413 // 1. Staker can unstake 0 wei414 await helper.staking.unstakePartial(staker, 0n);415 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);416 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal);417 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);418419 // 2. Staker can unstake 1 wei420 await helper.staking.unstakePartial(staker, 1n);421 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);422 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal - 1n);423 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1n);424 // 2.1 The oldest stake decreased:425 let [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});426 expect(stake1.amount).to.eq(100n * nominal - 1n);427 expect(stake2.amount).to.eq(200n * nominal);428429 // 3. Staker can unstake all but 1 wei430 await helper.staking.unstakePartial(staker, 100n * nominal - 2n);431 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);432 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(200n * nominal + 1n);433 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(100n * nominal - 1n);434 [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});435 expect(stake1.amount).to.eq(1n);436 expect(stake2.amount).to.eq(200n * nominal);437 });438439 itSub('can mix different type of unstakes', async ({helper}) => {440 const [staker] = await getAccounts(1);441 await helper.staking.stake(staker, 100n * nominal);442 await helper.staking.stake(staker, 200n * nominal);443444 await helper.staking.unstakePartial(staker, 50n * nominal);445 await helper.staking.unstakeAll(staker);446 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);447 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);448 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(300n * nominal);449450 const [_unstake1, unstake2] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});451 await helper.wait.forParachainBlockNumber(unstake2.block);452453 expect(await helper.balance.getFrozen(staker.address)).to.deep.eq([]);454 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 0n});455 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(999n);456 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);457 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);458 expect(await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).to.deep.eq([]);459 });460 });461462 describe('collection sponsoring', () => {463 itSub('should actually sponsor transactions', async ({helper}) => {464 const api = helper.getApi();465 const [collectionOwner, tokenSender, receiver] = await getAccounts(3);466 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});467 const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});468 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));469 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);470471 await token.transfer(tokenSender, {Substrate: receiver.address});472 expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});473 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);474475 // senders balance the same, transaction has sponsored476 expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);477 expect (palletBalanceBefore > palletBalanceAfter).to.be.true;478 });479480 itSub('can not be set by non admin', async ({helper}) => {481 const api = helper.getApi();482 const [collectionOwner, nonAdmin] = await getAccounts(2);483484 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});485486 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;487 expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');488 });489490 itSub('should set pallet address as confirmed admin', async ({helper}) => {491 const api = helper.getApi();492 const [collectionOwner, oldSponsor] = await getAccounts(2);493494 // Can set sponsoring for collection without sponsor495 const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});496 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;497 expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});498499 // Can set sponsoring for collection with unconfirmed sponsor500 const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: {Substrate: oldSponsor.address}});501 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});502 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;503 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});504505 // Can set sponsoring for collection with confirmed sponsor506 const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: {Substrate: oldSponsor.address}});507 await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);508 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;509 expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});510 });511512 itSub('can be overwritten by collection owner', async ({helper}) => {513 const api = helper.getApi();514 const [collectionOwner, newSponsor] = await getAccounts(2);515 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});516 const collectionId = collection.collectionId;517518 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;519520 // Collection limits still can be changed by the owner521 expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;522 expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);523 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});524525 // Collection sponsor can be changed too526 expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;527 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});528 });529530 itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {531 const [owner] = await getAccounts(1);532 const api = helper.getApi();533 const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};534 const collectionWithLimits = await helper.nft.mintCollection(owner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});535536 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;537 expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);538 });539540 itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {541 const api = helper.getApi();542 const [collectionOwner] = await getAccounts(1);543544 // collection has never existed545 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;546 // collection has been burned547 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});548 await collection.burn(collectionOwner);549550 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;551 });552 });553554 describe('stopSponsoringCollection', () => {555 itSub('can not be called by non-admin', async ({helper}) => {556 const api = helper.getApi();557 const [collectionOwner, nonAdmin] = await getAccounts(2);558 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});559560 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;561562 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;563 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});564 });565566 itSub('should set sponsoring as disabled', async ({helper}) => {567 const api = helper.getApi();568 const [collectionOwner, recepient] = await getAccounts(2);569 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});570 const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});571572 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));573 await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId));574575 expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');576577 // Transactions are not sponsored anymore:578 const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);579 await token.transfer(collectionOwner, {Substrate: recepient.address});580 const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);581 expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);582 });583584 itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {585 const api = helper.getApi();586 const [collectionOwner] = await getAccounts(1);587 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: {Substrate: collectionOwner.address}});588 await collection.confirmSponsorship(collectionOwner);589590 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;591592 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});593 });594595 itSub('should reject transaction if collection does not exist', async ({helper}) => {596 const [collectionOwner] = await getAccounts(1);597 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});598599 await collection.burn(collectionOwner);600 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');601 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');602 });603 });604605 describe('contract sponsoring', () => {606 itEth('should set palletes address as a sponsor', async ({helper}) => {607 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();608 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);609 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);610611 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);612613 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;614 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);615 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({616 confirmed: {617 substrate: palletAddress,618 },619 });620 });621622 itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {623 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();624 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);625 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);626627 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;628629 // Contract is self sponsored630 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.be.deep.equal({631 confirmed: {632 ethereum: flipper.options.address.toLowerCase(),633 },634 });635636 // set promotion sponsoring637 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);638639 // new sponsor is pallet address640 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;641 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);642 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({643 confirmed: {644 substrate: palletAddress,645 },646 });647 });648649 itEth('can be overwritten by contract owner', async ({helper}) => {650 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();651 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);652 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);653654 // contract sponsored by pallet655 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);656657 // owner sets self sponsoring658 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;659660 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;661 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);662 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({663 confirmed: {664 ethereum: flipper.options.address.toLowerCase(),665 },666 });667 });668669 itEth('can not be set by non admin', async ({helper}) => {670 const [nonAdmin] = await getAccounts(1);671 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();672 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);673 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);674675 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;676677 // nonAdmin calls sponsorContract678 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');679680 // contract still self-sponsored681 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({682 confirmed: {683 ethereum: flipper.options.address.toLowerCase(),684 },685 });686 });687688 itEth('should actually sponsor transactions', async ({helper}) => {689 // Contract caller690 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);691 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);692693 // Deploy flipper694 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();695 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);696 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);697698 // Owner sets to sponsor every tx699 await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});700 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});701 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);702703 // Set promotion to the Flipper704 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);705706 // Caller calls Flipper707 await flipper.methods.flip().send({from: caller});708 expect(await flipper.methods.getValue().call()).to.be.true;709710 // The contracts and caller balances have not changed711 const callerBalance = await helper.balance.getEthereum(caller);712 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);713 expect(callerBalance).to.be.equal(1000n * nominal);714 expect(1000n * nominal === contractBalanceAfter).to.be.true;715716 // The pallet balance has decreased717 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);718 expect(palletBalanceAfter < palletBalanceBefore).to.be.true;719 });720 });721722 describe('stopSponsoringContract', () => {723 itEth('should remove pallet address from contract sponsors', async ({helper}) => {724 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);725 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();726 const flipper = await helper.eth.deployFlipper(contractOwner);727 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address);728 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);729730 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});731 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);732 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);733734 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;735 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);736 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({737 disabled: null,738 });739740 await flipper.methods.flip().send({from: caller});741 expect(await flipper.methods.getValue().call()).to.be.true;742743 const callerBalance = await helper.balance.getEthereum(caller);744 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);745746 // caller payed for call747 expect(1000n * nominal > callerBalance).to.be.true;748 expect(contractBalanceAfter).to.be.equal(100n * nominal);749 });750751 itEth('can not be called by non-admin', async ({helper}) => {752 const [nonAdmin] = await getAccounts(1);753 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();754 const flipper = await helper.eth.deployFlipper(contractOwner);755756 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);757 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]))758 .to.be.rejectedWith(/appPromotion\.NoPermission/);759 });760761 itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {762 const [nonAdmin] = await getAccounts(1);763 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();764 const flipper = await helper.eth.deployFlipper(contractOwner);765 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);766 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;767768 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');769 });770 });771772 describe('payoutStakers', () => {773 itSub('can not be called by non admin', async ({helper}) => {774 const [nonAdmin] = await getAccounts(1);775 await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');776 });777778 itSub('should increase total staked', async ({helper}) => {779 const [staker] = await getAccounts(1);780 const totalStakedBefore = await helper.staking.getTotalStaked();781 await helper.staking.stake(staker, 100n * nominal);782783 // Wait for rewards and pay784 const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});785 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));786787 const payout = await helper.admin.payoutStakers(palletAdmin, 100);788 const totalPayout = payout.reduce((prev, payout) => prev + payout.payout, 0n);789 const stakerReward = payout.find(p => p.staker === staker.address);790791 expect(stakerReward?.payout).to.eq(calculateIncome(100n * nominal) - (100n * nominal));792793 const totalStakedAfter = await helper.staking.getTotalStaked();794 expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);795 // staker can unstake796 await helper.staking.unstakeAll(staker);797 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal));798 });799800 itSub('should credit 0.05% for staking period', async ({helper}) => {801 const [staker] = await getAccounts(1);802803 await waitPromotionPeriodDoesntEnd(helper);804805 await helper.staking.stake(staker, 100n * nominal);806 await helper.staking.stake(staker, 200n * nominal);807808 // wait rewards are available:809 const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});810 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));811812 const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)!.payout;813 expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal));814815 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});816 const income1 = calculateIncome(100n * nominal);817 const income2 = calculateIncome(200n * nominal);818 expect(totalStakedPerBlock[0].amount).to.equal(income1);819 expect(totalStakedPerBlock[1].amount).to.equal(income2);820821 const stakerBalance = await helper.balance.getSubstrateFull(staker.address);822 expect(stakerBalance).to.contain({frozen: income1 + income2, reserved: 0n});823 expect(stakerBalance.free / nominal).to.eq(999n);824 });825826 itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {827 const [staker] = await getAccounts(1);828829 await helper.staking.stake(staker, 100n * nominal);830 // wait for two rewards are available:831 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});832 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);833834 await helper.admin.payoutStakers(palletAdmin, 100);835 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});836 const frozenBalanceShouldBe = calculateIncome(100n * nominal, 2);837 expect(stake.amount).to.be.equal(frozenBalanceShouldBe);838839 const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);840841 expect(stakerFullBalance).to.contain({reserved: 0n, frozen: frozenBalanceShouldBe});842 });843844 itSub('should not be credited for pending-unstaked tokens', async ({helper}) => {845 // staker unstakes before rewards been payed846 const [staker] = await getAccounts(1);847 await helper.staking.stake(staker, 100n * nominal);848 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});849 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);850 await helper.staking.unstakeAll(staker);851852 // so he did not receive any rewards853 const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);854 await helper.admin.payoutStakers(palletAdmin, 100);855 const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);856857 expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);858 });859860 itSub('should bring compound interest', async ({helper}) => {861 const [staker] = await getAccounts(1);862863 await helper.staking.stake(staker, 100n * nominal);864865 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});866 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));867868 await helper.admin.payoutStakers(palletAdmin, 100);869 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});870 expect(stake.amount).to.equal(calculateIncome(100n * nominal));871872 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);873 await helper.admin.payoutStakers(palletAdmin, 100);874 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});875 expect(stake.amount).to.equal(calculateIncome(100n * nominal, 2));876 });877878 itSub('can calculate reward for tiny stake', async ({helper}) => {879 const [staker] = await getAccounts(1);880 await helper.staking.stake(staker, 100n * nominal);881 await helper.staking.stake(staker, 100n * nominal);882 await helper.staking.unstakePartial(staker, 100n * nominal - 1n);883884 const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});885 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));886887 const stakerPayout = await payUntilRewardFor(staker.address, helper);888 expect(stakerPayout.stake).to.eq(100n * nominal + 1n);889 });890891 itSub('can eventually pay all rewards', async ({helper}) => {892 const stakers = await getAccounts(30);893 // Create 30 stakes:894 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));895896 let unstakingTxs = [];897 for(const staker of stakers) {898 if(unstakingTxs.length == 3) {899 await Promise.all(unstakingTxs);900 unstakingTxs = [];901 }902 unstakingTxs.push(helper.staking.unstakePartial(staker, 100n * nominal - 1n));903 }904905 const [staker] = await getAccounts(1);906 await helper.staking.stake(staker, 100n * nominal);907 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});908 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));909910 let payouts;911 do {912 payouts = await helper.admin.payoutStakers(palletAdmin, 20);913 } while(payouts.length !== 0);914 });915 });916917 describe('events', () => {918 [919 {method: 'unstakePartial' as const},920 {method: 'unstakeAll' as const},921 ].map(testCase => {922 itSub(testCase.method, async ({helper}) => {923 const unstakeParams: [] | [bigint] = testCase.method === 'unstakePartial'924 ? [100n * nominal - 1n]925 : [];926 const [staker] = await getAccounts(1);927 await helper.staking.stake(staker, 100n * nominal);928 await helper.staking.stake(staker, 200n * nominal);929 const {result} = await helper.executeExtrinsic(staker, `api.tx.appPromotion.${testCase.method}`, unstakeParams);930931 const event = result.events.find(e => e.event.section === 'appPromotion' && e.event.method === 'Unstake');932 const unstakerEvents = event?.event.data[0].toString();933 const unstakedEvents = BigInt(event?.event.data[1].toString());934 expect(unstakerEvents).to.eq(staker.address);935 expect(unstakedEvents).to.eq(testCase.method === 'unstakeAll' ? 300n * nominal : 100n * nominal - 1n);936 });937 });938939 itSub('stake', async ({helper}) => {940 const [staker] = await getAccounts(1);941 const {result} = await helper.executeExtrinsic(staker, 'api.tx.appPromotion.stake', [100n * nominal]);942943 const event = result.events.find(e => e.event.section === 'appPromotion' && e.event.method === 'Stake');944 const stakerEvents = event?.event.data[0].toString();945 const stakedEvents = BigInt(event?.event.data[1].toString());946 expect(stakerEvents).to.eq(staker.address);947 expect(stakedEvents).to.eq(100n * nominal);948 });949950 // Flaky951 itSub.skip('payoutStakers', async ({helper}) => {952 const [staker1, staker2] = await getAccounts(2);953 const STAKE1 = 100n * nominal;954 const STAKE2 = 200n * nominal;955 await helper.staking.stake(staker1, STAKE1);956 await helper.staking.stake(staker2, STAKE2);957958 const [stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker2.address});959 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));960961 const results = await helper.admin.payoutStakers(palletAdmin, 100);962 const stakersEvents = results.filter(ev => ev.staker === staker1.address || ev.staker === staker2.address);963 expect(stakersEvents).has.length(2);964 expect(stakersEvents).has.not.ordered.members([965 {staker: staker1.address, stake: STAKE1, payout: calculateIncome(STAKE1) - STAKE1},966 {staker: staker2.address, stake: STAKE2, payout: calculateIncome(STAKE2) - STAKE2},967 ]);968 });969 });970});971972973// Sometimes is is required to make a cycle in order for the payment to be calculated for a specific account974async function payUntilRewardFor(account: string, helper: DevUniqueHelper) {975 for(let i = 0; i < 3; i++) {976 const payouts = await helper.admin.payoutStakers(palletAdmin, 100);977 const accountPayout = payouts.find(p => p.staker === account);978 if(accountPayout) return accountPayout;979 }980 throw Error(`Cannot find payout for ${account}`);981}982983function calculateIncome(base: bigint, iter = 0, calcPeriod: bigint = UNLOCKING_PERIOD): bigint {984 const DAY = 7200n;985 const ACCURACY = 1_000_000_000n;986 // 5n / 10_000n = 0.05% p/day987 const income = base + base * (ACCURACY * (calcPeriod * 453_256n) / (1_000_000_000n * DAY)) / ACCURACY ;988989 if(iter > 1) {990 return calculateIncome(income, iter - 1, calcPeriod);991 } else return income;992}993994function rewardAvailableInBlock(stakedInBlock: bigint) {995 if(stakedInBlock % LOCKING_PERIOD === 0n) return stakedInBlock + LOCKING_PERIOD;996 return (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);997}998999// Wait while promotion period less than specified block, to avoid boundary cases1000// 0 if this should be the beginning of the period.1001async function waitPromotionPeriodDoesntEnd(helper: DevUniqueHelper, waitBlockLessThan = LOCKING_PERIOD / 3n) {1002 const relayBlockNumber = (await helper.callRpc('api.query.parachainSystem.validationData', [])).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();1003 const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;10041005 if(currentPeriodBlock > waitBlockLessThan) {1006 await helper.wait.forRelayBlockNumber(BigInt(relayBlockNumber) + LOCKING_PERIOD - currentPeriodBlock);1007 }1008}pallets/collator-selection/src/mock.rsdiffbeforeafterboth--- a/pallets/collator-selection/src/mock.rs
+++ b/pallets/collator-selection/src/mock.rs
@@ -208,7 +208,7 @@
pub const DefaultWeightToFeeCoefficient: u64 = 100_000;
pub const DefaultMinGasPrice: u64 = 100_000;
pub const MaxXcmAllowedLocations: u32 = 16;
- pub AppPromotionDailyRate: Perbill = Perbill::from_rational(5u32, 10_000);
+ pub AppPromotionDailyRate: Perbill = Perbill::from_rational(453_256u64, 1_000_000_000u64);
pub const DayRelayBlocks: u32 = 1;
pub const LicenceBondIdentifier: [u8; 16] = *b"licenceidentifie";
}
runtime/common/config/pallets/app_promotion.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/app_promotion.rs
+++ b/runtime/common/config/pallets/app_promotion.rs
@@ -15,12 +15,12 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
use frame_support::{parameter_types, PalletId};
-use sp_arithmetic::Perbill;
use up_common::{
constants::{DAYS, RELAY_DAYS, UNIQUE},
types::Balance,
};
+use super::AppPromotionDailyRate;
use crate::{
runtime_common::config::pallets::{RelayChainBlockNumberProvider, TreasuryAccountId},
Balances, BlockNumber, EvmContractHelpers, Maintenance, Runtime, RuntimeEvent, Unique,
@@ -32,7 +32,6 @@
pub const PendingInterval: BlockNumber = 7 * DAYS;
pub const Nominal: Balance = UNIQUE;
pub const HoldAndFreezeIdentifier: [u8; 16] = *b"appstakeappstake";
- pub IntervalIncome: Perbill = Perbill::from_rational(5u32, 10_000);
pub MaintenanceMode: bool = Maintenance::is_enabled();
}
@@ -47,7 +46,7 @@
type RecalculationInterval = RecalculationInterval;
type PendingInterval = PendingInterval;
type Nominal = Nominal;
- type IntervalIncome = IntervalIncome;
+ type IntervalIncome = AppPromotionDailyRate;
type RuntimeEvent = RuntimeEvent;
type FreezeIdentifier = HoldAndFreezeIdentifier;
type IsMaintenanceModeEnabled = MaintenanceMode;
runtime/common/config/pallets/mod.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -151,7 +151,7 @@
}
parameter_types! {
- pub AppPromotionDailyRate: Perbill = Perbill::from_rational(5u32, 10_000);
+ pub AppPromotionDailyRate: Perbill = Perbill::from_rational(453_256u64, 1_000_000_000u64);
pub const MaxCollators: u32 = MAX_COLLATORS;
pub const LicenseBond: Balance = GENESIS_LICENSE_BOND;