1234567891011121314151617import {IKeyringPair} from '@polkadot/types/types';18import {19 normalizeAccountId,20 getModuleNames,21 Pallets,22} from './util/helpers';23import {itSub, usingPlaygrounds} from './util/playgrounds';24import {encodeAddress} from '@polkadot/util-crypto';25import {stringToU8a} from '@polkadot/util';26import {SponsoringMode} from './eth/util/helpers';27import {DevUniqueHelper} from './util/playgrounds/unique.dev';28import {itEth, expect} from './eth/util/playgrounds';2930let alice: IKeyringPair;31let palletAdmin: IKeyringPair;32let nominal: bigint;33const palletAddress = calculatePalleteAddress('appstake');34let accounts: IKeyringPair[] = [];35const LOCKING_PERIOD = 20n; 36const UNLOCKING_PERIOD = 10n; 37const rewardAvailableInBlock = (stakedInBlock: bigint) => {38 if (stakedInBlock % LOCKING_PERIOD === 0n) return stakedInBlock + 20n;39 return (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);40};4142describe('App promotion', () => {43 before(async function () {44 await usingPlaygrounds(async (helper, privateKey) => {45 if (!getModuleNames(helper.api!).includes(Pallets.AppPromotion)) this.skip();46 alice = privateKey('//Alice');47 palletAdmin = privateKey('//Charlie'); 48 await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));49 nominal = helper.balance.getOneTokenNominal();50 await helper.balance.transferToSubstrate(alice, palletAdmin.address, 1000n * nominal);51 await helper.balance.transferToSubstrate(alice, palletAddress, 1000n * nominal);52 accounts = await helper.arrange.createCrowd(100, 1000n, alice); 53 });54 });5556 describe('stake extrinsic', () => { 57 itSub('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {58 const [staker, recepient] = [accounts.pop()!, accounts.pop()!];59 const totalStakedBefore = await helper.staking.getTotalStaked();60 61 62 await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;63 await helper.staking.stake(staker, 100n * nominal);64 65 66 67 expect (await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});68 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');69 70 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);71 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);72 73 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); 74 75 76 await helper.staking.stake(staker, 200n * nominal);77 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);78 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});79 expect(totalStakedPerBlock[0].amount).to.equal(100n * nominal);80 expect(totalStakedPerBlock[1].amount).to.equal(200n * nominal);81 });82 83 itSub('should allow to create maximum 10 stakes for account', async ({helper}) => {84 const [staker] = await helper.arrange.createAccounts([2000n], alice);85 for (let i = 0; i < 10; i++) {86 await helper.staking.stake(staker, 100n * nominal);87 }88 89 90 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);91 expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);92 93 await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');94 95 96 await helper.staking.unstake(staker);97 await helper.staking.stake(staker, 100n * nominal);98 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);99 });100 101 itSub('should reject transaction if stake amount is more than total free balance minus frozen', async ({helper}) => {102 const staker = accounts.pop()!;103 104 105 await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected;106 await helper.staking.stake(staker, 500n * nominal);107 108 109 await expect(helper.staking.stake(staker, 500n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions'); 110 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);111 });112 113 itSub('for different accounts in one block is possible', async ({helper}) => {114 const crowd = [accounts.pop()!, accounts.pop()!, accounts.pop()!, accounts.pop()!];115 116 const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));117 await expect(Promise.all(crowdStartsToStake)).to.be.fulfilled;118 119 const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));120 expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);121 });122 });123 124 describe('unstake extrinsic', () => { 125 itSub('should change balance state from "frozen" to "reserved", add it to "pendingUnstake" map, and subtract it from totalStaked', async ({helper}) => {126 const [staker, recepient] = [accounts.pop()!, accounts.pop()!];127 const totalStakedBefore = await helper.staking.getTotalStaked();128 await helper.staking.stake(staker, 900n * nominal);129 await helper.staking.unstake(staker);130 131 132 133 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 900n * nominal, miscFrozen: 0n, feeFrozen: 0n});134 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.InsufficientBalance');135 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(900n * nominal);136 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);137 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);138 });139 140 itSub('should unlock balance after unlocking period ends and remove it from "pendingUnstake"', async ({helper}) => {141 const staker = accounts.pop()!;142 await helper.staking.stake(staker, 100n * nominal);143 await helper.staking.unstake(staker);144 const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});145 146 147 await helper.wait.forParachainBlockNumber(pendingUnstake.block);148 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});149 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);150 151 152 await helper.balance.transferToSubstrate(staker, alice.address, 998n * nominal);153 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);154 });155 156 itSub('should successfully unstake multiple stakes', async ({helper}) => {157 const staker = accounts.pop()!;158 await helper.staking.stake(staker, 100n * nominal);159 await helper.staking.stake(staker, 200n * nominal);160 await helper.staking.stake(staker, 300n * nominal);161 162 163 let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});164 let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});165 let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});166 expect(totalPendingUnstake).to.be.deep.equal(0n);167 expect(pendingUnstake).to.be.deep.equal([]);168 expect(stakes[0].amount).to.equal(100n * nominal);169 expect(stakes[1].amount).to.equal(200n * nominal);170 expect(stakes[2].amount).to.equal(300n * nominal);171 172 173 await helper.staking.unstake(staker);174 pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});175 totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});176 stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});177 expect(totalPendingUnstake).to.be.equal(600n * nominal);178 expect(stakes).to.be.deep.equal([]);179 expect(pendingUnstake[0].amount).to.equal(600n * nominal);180 181 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 600n * nominal, feeFrozen: 0n, miscFrozen: 0n});182 await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);183 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});184 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);185 });186 187 itSub('should not have any effects if no active stakes', async ({helper}) => {188 const staker = accounts.pop()!;189 190 191 await helper.staking.unstake(staker);192 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);193 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); 194 195 196 197 198 await helper.staking.stake(staker, 100n * nominal);199 await helper.staking.unstake(staker);200 await helper.staking.unstake(staker);201 202 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);203 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);204 });205 206 itSub('should keep different unlocking block for each unlocking stake', async ({helper}) => {207 const staker = accounts.pop()!;208 await helper.staking.stake(staker, 100n * nominal);209 await helper.staking.unstake(staker);210 await helper.staking.stake(staker, 120n * nominal);211 await helper.staking.unstake(staker);212 213 const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});214 expect(unstakingPerBlock).has.length(2);215 expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);216 expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);217 });218 219 itSub('should be possible for different accounts in one block', async ({helper}) => {220 const stakers = [accounts.pop()!, accounts.pop()!, accounts.pop()!];221 222 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));223 await Promise.all(stakers.map(staker => helper.staking.unstake(staker)));224 225 await Promise.all(stakers.map(async (staker) => {226 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);227 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);228 }));229 });230 });231 232 describe('admin adress', () => {233 itSub('can be set by sudo only', async ({helper}) => {234 const nonAdmin = accounts.pop()!;235 236 await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.rejected;237 await expect(helper.signTransaction(nonAdmin, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.rejected;238 239 240 await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;241 });242 243 itSub('can be any valid CrossAccountId', async ({helper}) => {244 245 246 const account = accounts.pop()!;247 const ethAccount = helper.address.substrateToEth(account.address); 248 249 await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.fulfilled;250 await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;251 252 253 const collection = await helper.nft.mintCollection(account, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});254 await expect(helper.signTransaction(account, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;255 });256 257 itSub('can be reassigned', async ({helper}) => {258 const [oldAdmin, newAdmin, collectionOwner] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];259 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});260 261 await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(oldAdmin))))).to.be.fulfilled;262 await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(newAdmin))))).to.be.fulfilled;263 await expect(helper.signTransaction(oldAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;264 265 await expect(helper.signTransaction(newAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;266 });267 });268 269 describe('collection sponsoring', () => {270 before(async function () {271 await usingPlaygrounds(async (helper) => {272 const tx = helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address}));273 await helper.signTransaction(alice, tx);274 });275 });276 277 itSub('should actually sponsor transactions', async ({helper}) => {278 const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];279 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});280 const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});281 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));282 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);283 284 await token.transfer(tokenSender, {Substrate: receiver.address});285 expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});286 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);287 288 289 expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);290 expect (palletBalanceBefore > palletBalanceAfter).to.be.true;291 });292 293 itSub('can not be set by non admin', async ({helper}) => {294 const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];295 296 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});297 298 await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;299 expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');300 });301 302 itSub('should set pallet address as confirmed admin', async ({helper}) => {303 const [collectionOwner, oldSponsor] = [accounts.pop()!, accounts.pop()!];304 305 306 const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});307 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;308 expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});309 310 311 const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});312 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});313 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;314 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});315 316 317 const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});318 await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);319 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;320 expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});321 });322 323 itSub('can be overwritten by collection owner', async ({helper}) => { 324 const [collectionOwner, newSponsor] = [accounts.pop()!, accounts.pop()!];325 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});326 const collectionId = collection.collectionId;327 328 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;329 330 331 expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;332 expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);333 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});334 335 336 expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;337 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});338 });339 340 itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {341 const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};342 const collectionWithLimits = await helper.nft.mintCollection(alice, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});343 344 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;345 expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);346 });347 348 itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {349 const collectionOwner = accounts.pop()!;350 351 352 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;353 354 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});355 await collection.burn(collectionOwner);356 357 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;358 });359 });360 361 describe('stopSponsoringCollection', () => {362 itSub('can not be called by non-admin', async ({helper}) => { 363 const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];364 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});365 366 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;367 368 await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;369 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});370 });371 372 itSub('should set sponsoring as disabled', async ({helper}) => {373 const [collectionOwner, recepient] = [accounts.pop()!, accounts.pop()!];374 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});375 const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});376 377 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));378 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId));379 380 expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');381 382 383 const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);384 await token.transfer(collectionOwner, {Substrate: recepient.address});385 const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);386 expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);387 });388 389 itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {390 const collectionOwner = accounts.pop()!;391 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});392 await collection.confirmSponsorship(collectionOwner);393 394 await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;395 396 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});397 });398 399 itSub('should reject transaction if collection does not exist', async ({helper}) => { 400 const collectionOwner = accounts.pop()!;401 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});402 403 await collection.burn(collectionOwner);404 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');405 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');406 });407 });408 409 describe('contract sponsoring', () => {410 itEth('should set palletes address as a sponsor', async ({helper}) => {411 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();412 const flipper = await helper.eth.deployFlipper(contractOwner); 413 const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);414 415 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);416 417 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true; 418 expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner); 419 expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({420 confirmed: {421 substrate: palletAddress,422 },423 });424 });425 426 itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {427 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();428 const flipper = await helper.eth.deployFlipper(contractOwner); 429 const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);430 431 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;432 433 434 expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.be.deep.equal({435 confirmed: {436 ethereum: flipper.options.address.toLowerCase(),437 },438 });439 440 441 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);442 443 444 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true; 445 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner); 446 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({447 confirmed: {448 substrate: palletAddress,449 },450 });451 });452 453 itEth('can be overwritten by contract owner', async ({helper}) => {454 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();455 const flipper = await helper.eth.deployFlipper(contractOwner); 456 const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);457 458 459 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);460 461 462 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;463 464 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true; 465 expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner); 466 expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({467 confirmed: {468 ethereum: flipper.options.address.toLowerCase(),469 },470 });471 });472 473 itEth('can not be set by non admin', async ({helper}) => {474 const nonAdmin = accounts.pop()!;475 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();476 const flipper = await helper.eth.deployFlipper(contractOwner); 477 const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);478 479 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;480 481 482 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');483 484 485 expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({486 confirmed: {487 ethereum: flipper.options.address.toLowerCase(),488 },489 });490 });491 492 itEth('should actually sponsor transactions', async ({helper}) => {493 494 const caller = await helper.eth.createAccountWithBalance(alice, 1000n);495 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);496 497 498 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();499 const flipper = await helper.eth.deployFlipper(contractOwner); 500 const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);501 502 503 await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});504 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});505 await helper.eth.transferBalanceFromSubstrate(alice, flipper.options.address, 1000n); 506 507 508 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorContract(flipper.options.address));509 510 511 await flipper.methods.flip().send({from: caller});512 expect(await flipper.methods.getValue().call()).to.be.true;513 514 515 const callerBalance = await helper.balance.getEthereum(caller);516 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);517 expect(callerBalance).to.be.equal(1000n * nominal);518 expect(1000n * nominal === contractBalanceAfter).to.be.true;519 520 521 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);522 expect(palletBalanceAfter < palletBalanceBefore).to.be.true;523 });524 });525 526 describe('stopSponsoringContract', () => { 527 itEth('should remove pallet address from contract sponsors', async ({helper}) => {528 const caller = await helper.eth.createAccountWithBalance(alice, 1000n);529 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();530 const flipper = await helper.eth.deployFlipper(contractOwner);531 await helper.eth.transferBalanceFromSubstrate(alice, flipper.options.address);532 const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);533 534 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});535 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);536 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);537 538 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false; 539 expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner); 540 expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({541 disabled: null,542 });543 544 await flipper.methods.flip().send({from: caller});545 expect(await flipper.methods.getValue().call()).to.be.true;546 547 const callerBalance = await helper.balance.getEthereum(caller);548 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);549 550 551 expect(1000n * nominal > callerBalance).to.be.true;552 expect(contractBalanceAfter).to.be.equal(1000n * nominal);553 });554 555 itEth('can not be called by non-admin', async ({helper}) => {556 const nonAdmin = accounts.pop()!;557 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();558 const flipper = await helper.eth.deployFlipper(contractOwner);559 560 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);561 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]))562 .to.be.rejectedWith(/appPromotion\.NoPermission/);563 });564 565 itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {566 const nonAdmin = accounts.pop()!;567 const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();568 const flipper = await helper.eth.deployFlipper(contractOwner);569 const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);570 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;571 572 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');573 });574 });575 576 describe('rewards', () => {577 itSub('can not be called by non admin', async ({helper}) => {578 const nonAdmin = accounts.pop()!;579 await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');580 });581 582 itSub('should increase total staked', async ({helper}) => {583 const staker = accounts.pop()!;584 const totalStakedBefore = await helper.staking.getTotalStaked();585 await helper.staking.stake(staker, 100n * nominal);586 587 588 const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});589 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));590 const totalPayout = (await helper.admin.payoutStakers(palletAdmin, 100)).reduce((prev, payout) => prev + payout.payout, 0n);591 592 const totalStakedAfter = await helper.staking.getTotalStaked();593 expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);594 595 await helper.staking.unstake(staker);596 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal, 10n));597 });598 599 itSub('should credit 0.05% for staking period', async ({helper}) => { 600 const staker = accounts.pop()!;601 602 await waitPromotionPeriodDoesntEnd(helper);603 604 await helper.staking.stake(staker, 100n * nominal);605 await helper.staking.stake(staker, 200n * nominal);606 607 608 const [_, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});609 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));610 611 const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)?.payout;612 expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal, 10n));613 614 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});615 expect(totalStakedPerBlock[0].amount).to.equal(calculateIncome(100n * nominal, 10n));616 expect(totalStakedPerBlock[1].amount).to.equal(calculateIncome(200n * nominal, 10n));617 });618 619 itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {620 const staker = accounts.pop()!;621 622 await helper.staking.stake(staker, 100n * nominal);623 624 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});625 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);626 627 await helper.admin.payoutStakers(palletAdmin, 100);628 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});629 const frozenBalanceShouldBe = calculateIncome(100n * nominal, 10n, 2);630 expect(stake.amount).to.be.equal(frozenBalanceShouldBe);631 632 const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);633 634 expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});635 });636 637 itSub('should not be credited for unstaked (reserved) balance', async ({helper}) => {638 639 const staker = accounts.pop()!;640 await helper.staking.stake(staker, 100n * nominal);641 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});642 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);643 await helper.staking.unstake(staker);644 645 646 const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);647 await helper.admin.payoutStakers(palletAdmin, 100);648 const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);649 650 expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);651 });652 653 itSub('should bring compound interest', async ({helper}) => {654 const staker = accounts.pop()!;655 656 await helper.staking.stake(staker, 100n * nominal);657 658 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});659 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));660 661 await helper.admin.payoutStakers(palletAdmin, 100);662 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});663 expect(stake.amount).to.equal(calculateIncome(100n * nominal, 10n));664 665 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);666 await helper.admin.payoutStakers(palletAdmin, 100);667 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});668 expect(stake.amount).to.equal(calculateIncome(100n * nominal, 10n, 2));669 });670 671 itSub.skip('can be paid 1000 rewards in a time', async ({helper}) => {672 673 const oneHundredStakers = await helper.arrange.createCrowd(100, 1050n, alice);674 675 676 for (let i = 0; i < 10; i++) {677 await Promise.all(oneHundredStakers.map(staker => helper.staking.stake(staker, 100n * nominal)));678 }679 await helper.wait.newBlocks(40);680 await helper.admin.payoutStakers(palletAdmin, 100);681 });682 683 itSub.skip('can handle 40.000 rewards', async ({helper}) => {684 const [donor] = await helper.arrange.createAccounts([7_000_000n], alice);685 const crowdStakes = async () => {686 687 const crowd = await helper.arrange.createCrowd(500, 300n, donor);688 await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));689 await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));690 691 };692 693 for (let i = 0; i < 40; i++) {694 await crowdStakes();695 }696 697 698 });699 });700});701702function calculatePalleteAddress(palletId: any) {703 const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));704 return encodeAddress(address);705}706707function calculateIncome(base: bigint, calcPeriod: bigint, iter = 0): bigint {708 const DAY = 7200n;709 const ACCURACY = 1_000_000_000n;710 const income = base + base * (ACCURACY * (calcPeriod * 5n) / (10_000n * DAY)) / ACCURACY ;711 712 if (iter > 1) {713 return calculateIncome(income, calcPeriod, iter - 1);714 } else return income;715}716717718719async function waitPromotionPeriodDoesntEnd(helper: DevUniqueHelper, waitBlockLessThan = LOCKING_PERIOD / 3n) {720 const relayBlockNumber = (await helper.api!.query.parachainSystem.validationData()).value.relayParentNumber.toNumber(); 721 const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;722723 if (currentPeriodBlock > waitBlockLessThan) {724 await helper.wait.forRelayBlockNumber(BigInt(relayBlockNumber) + LOCKING_PERIOD - currentPeriodBlock);725 }726}