difftreelog
test run eslint --fix
in: master
20 files changed
tests/src/benchmarks/mintFee/index.tsdiffbeforeafterboth--- a/tests/src/benchmarks/mintFee/index.ts
+++ b/tests/src/benchmarks/mintFee/index.ts
@@ -222,9 +222,7 @@
await collection.mintToken(
donor,
{Substrate: susbstrateReceiver.address},
- PROPERTIES.slice(0, setup.propertiesNumber).map((p) => {
- return {key: p.key, value: Buffer.from(p.value).toString()};
- }),
+ PROPERTIES.slice(0, setup.propertiesNumber).map((p) => ({key: p.key, value: Buffer.from(p.value).toString()})),
);
},
);
tests/src/benchmarks/opsFee/index.tsdiffbeforeafterboth--- a/tests/src/benchmarks/opsFee/index.ts
+++ b/tests/src/benchmarks/opsFee/index.ts
@@ -379,7 +379,7 @@
res['setCollectionProperties'].substrate = convertToTokens((await helper.arrange.calculcateFee(
{Substrate: donor.address},
() => collection.setProperties(donor, PROPERTIES.slice(0, 1)
- .map(p => { return {key: p.key, value: p.value.toString()}; })),
+ .map(p => ({key: p.key, value: p.value.toString()}))),
)));
res['deleteCollectionProperties'].substrate = convertToTokens((await helper.arrange.calculcateFee(
@@ -755,7 +755,7 @@
res['setCollectionProperties'].substrate = convertToTokens((await helper.arrange.calculcateFee(
{Substrate: donor.address},
() => collection.setProperties(donor, PROPERTIES.slice(0, 1)
- .map(p => { return {key: p.key, value: p.value.toString()}; })),
+ .map(p => ({key: p.key, value: p.value.toString()}))),
)));
res['deleteCollectionProperties'].substrate = convertToTokens((await helper.arrange.calculcateFee(
tests/src/benchmarks/utils/common.tsdiffbeforeafterboth--- a/tests/src/benchmarks/utils/common.ts
+++ b/tests/src/benchmarks/utils/common.ts
@@ -5,32 +5,26 @@
export const PROPERTIES = Array(40)
.fill(0)
- .map((_, i) => {
- return {
- key: `key_${i}`,
- value: Uint8Array.from(Buffer.from(`value_${i}`)),
- };
- });
+ .map((_, i) => ({
+ key: `key_${i}`,
+ value: Uint8Array.from(Buffer.from(`value_${i}`)),
+ }));
export const SUBS_PROPERTIES = Array(40)
.fill(0)
- .map((_, i) => {
- return {
- key: `key_${i}`,
- value: `value_${i}`,
- };
- });
+ .map((_, i) => ({
+ key: `key_${i}`,
+ value: `value_${i}`,
+ }));
-export const PERMISSIONS: ITokenPropertyPermission[] = PROPERTIES.map((p) => {
- return {
- key: p.key,
- permission: {
- tokenOwner: true,
- collectionAdmin: true,
- mutable: true,
- },
- };
-});
+export const PERMISSIONS: ITokenPropertyPermission[] = PROPERTIES.map((p) => ({
+ key: p.key,
+ permission: {
+ tokenOwner: true,
+ collectionAdmin: true,
+ mutable: true,
+ },
+}));
export function convertToTokens(value: bigint, nominal = 1000_000_000_000_000_000n): number {
return Number((value * 1000n) / nominal) / 1000;
tests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionAdmin.test.ts
+++ b/tests/src/eth/collectionAdmin.test.ts
@@ -76,9 +76,7 @@
// 2. Expect methods.collectionAdmins == api.rpc.unique.adminlist
let adminListEth = await collectionEvm.methods.collectionAdmins().call();
- adminListEth = adminListEth.map((element: IEthCrossAccountId) => {
- return helper.address.convertCrossAccountFromEthCrossAccount(element);
- });
+ adminListEth = adminListEth.map((element: IEthCrossAccountId) => helper.address.convertCrossAccountFromEthCrossAccount(element));
expect(adminListRpc).to.be.like(adminListEth);
// 3. check isOwnerOrAdminCross returns true:
tests/src/eth/collectionProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionProperties.test.ts
+++ b/tests/src/eth/collectionProperties.test.ts
@@ -181,17 +181,11 @@
const propertyPermissions = data2?.raw.tokenPropertyPermissions;
expect(propertyPermissions?.length).to.equal(2);
- expect(propertyPermissions.find((tpp: ITokenPropertyPermission) => {
- return tpp.key === 'URI' && tpp.permission.mutable && tpp.permission.collectionAdmin && !tpp.permission.tokenOwner;
- })).to.be.not.null;
+ expect(propertyPermissions.find((tpp: ITokenPropertyPermission) => tpp.key === 'URI' && tpp.permission.mutable && tpp.permission.collectionAdmin && !tpp.permission.tokenOwner)).to.be.not.null;
- expect(propertyPermissions.find((tpp: ITokenPropertyPermission) => {
- return tpp.key === 'URISuffix' && tpp.permission.mutable && tpp.permission.collectionAdmin && !tpp.permission.tokenOwner;
- })).to.be.not.null;
+ expect(propertyPermissions.find((tpp: ITokenPropertyPermission) => tpp.key === 'URISuffix' && tpp.permission.mutable && tpp.permission.collectionAdmin && !tpp.permission.tokenOwner)).to.be.not.null;
- expect(data2?.raw.properties?.find((property: IProperty) => {
- return property.key === 'baseURI' && property.value === BASE_URI;
- })).to.be.not.null;
+ expect(data2?.raw.properties?.find((property: IProperty) => property.key === 'baseURI' && property.value === BASE_URI)).to.be.not.null;
const token1Result = await contract.methods.mint(bruh).send();
const tokenId1 = token1Result.events.Transfer.returnValues.tokenId;
tests/src/eth/evmCoder.test.tsdiffbeforeafterboth--- a/tests/src/eth/evmCoder.test.ts
+++ b/tests/src/eth/evmCoder.test.ts
@@ -17,8 +17,7 @@
import {IKeyringPair} from '@polkadot/types/types';
import {itEth, expect, usingEthPlaygrounds} from './util';
-const getContractSource = (collectionAddress: string, contractAddress: string): string => {
- return `
+const getContractSource = (collectionAddress: string, contractAddress: string): string => `
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ITest {
@@ -51,7 +50,6 @@
}
}
`;
-};
describe('Evm Coder tests', () => {
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -102,17 +102,15 @@
const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(receiverSub);
// const receiverCross = helper.ethCrossAccount.fromKeyringPair(bob);
- const properties = Array(5).fill(0).map((_, i) => { return {key: `key_${i}`, value: Buffer.from(`value_${i}`)}; });
+ const properties = Array(5).fill(0).map((_, i) => ({key: `key_${i}`, value: Buffer.from(`value_${i}`)}));
const permissions: ITokenPropertyPermission[] = properties
- .map(p => {
- return {
- key: p.key, permission: {
- tokenOwner: false,
- collectionAdmin: true,
- mutable: false,
- },
- };
- });
+ .map(p => ({
+ key: p.key, permission: {
+ tokenOwner: false,
+ collectionAdmin: true,
+ mutable: false,
+ },
+ }));
const collection = await helper.nft.mintCollection(minter, {
tokenPrefix: 'ethp',
@@ -146,7 +144,7 @@
expect(tokenId).to.be.equal(expectedTokenId);
expect(await contract.methods.properties(tokenId, []).call()).to.be.like(properties
- .map(p => { return helper.ethProperty.property(p.key, p.value.toString()); }));
+ .map(p => helper.ethProperty.property(p.key, p.value.toString())));
expect(await helper.nft.getTokenOwner(collection.collectionId, tokenId))
.to.deep.eq(testCase === 'ethereum' ? {Ethereum: receiverEth.toLowerCase()} : {Substrate: receiverSub.address});
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -46,12 +46,11 @@
const receiverSub = bob;
const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(receiverSub);
- const properties = Array(5).fill(0).map((_, i) => { return {key: `key_${i}`, value: Buffer.from(`value_${i}`)}; });
- const permissions: ITokenPropertyPermission[] = properties.map(p => { return {key: p.key, permission: {
+ const properties = Array(5).fill(0).map((_, i) => ({key: `key_${i}`, value: Buffer.from(`value_${i}`)}));
+ const permissions: ITokenPropertyPermission[] = properties.map(p => ({key: p.key, permission: {
tokenOwner: false,
collectionAdmin: true,
- mutable: false}};
- });
+ mutable: false}}));
const collection = await helper.rft.mintCollection(minter, {
@@ -86,7 +85,7 @@
expect(tokenId).to.be.equal(expectedTokenId);
expect(await contract.methods.properties(tokenId, []).call()).to.be.like(properties
- .map(p => { return helper.ethProperty.property(p.key, p.value.toString()); }));
+ .map(p => helper.ethProperty.property(p.key, p.value.toString())));
expect(await helper.nft.getTokenOwner(collection.collectionId, tokenId))
.to.deep.eq(testCase === 'ethereum' ? {Ethereum: receiverEth.toLowerCase()} : {Substrate: receiverSub.address});
tests/src/eth/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/tokenProperties.test.ts
+++ b/tests/src/eth/tokenProperties.test.ts
@@ -241,10 +241,10 @@
itEth.ifWithPallets(`Can be multiple set/read for ${testCase.mode}`, testCase.requiredPallets, async({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const properties = Array(5).fill(0).map((_, i) => { return {key: `key_${i}`, value: Buffer.from(`value_${i}`)}; });
- const permissions: ITokenPropertyPermission[] = properties.map(p => { return {key: p.key, permission: {tokenOwner: true,
+ const properties = Array(5).fill(0).map((_, i) => ({key: `key_${i}`, value: Buffer.from(`value_${i}`)}));
+ const permissions: ITokenPropertyPermission[] = properties.map(p => ({key: p.key, permission: {tokenOwner: true,
collectionAdmin: true,
- mutable: true}}; });
+ mutable: true}}));
const collection = await helper[testCase.mode].mintCollection(alice, {
tokenPrefix: 'ethp',
@@ -267,10 +267,10 @@
await contract.methods.setProperties(token.tokenId, properties).send({from: caller});
const values = await token.getProperties(properties.map(p => p.key));
- expect(values).to.be.deep.equal(properties.map(p => { return {key: p.key, value: p.value.toString()}; }));
+ expect(values).to.be.deep.equal(properties.map(p => ({key: p.key, value: p.value.toString()})));
expect(await contract.methods.properties(token.tokenId, []).call()).to.be.like(properties
- .map(p => { return helper.ethProperty.property(p.key, p.value.toString()); }));
+ .map(p => helper.ethProperty.property(p.key, p.value.toString())));
expect(await contract.methods.properties(token.tokenId, [properties[0].key]).call())
.to.be.like([helper.ethProperty.property(properties[0].key, properties[0].value.toString())]);
tests/src/fungible.test.tsdiffbeforeafterboth--- a/tests/src/fungible.test.ts
+++ b/tests/src/fungible.test.ts
@@ -46,7 +46,7 @@
itSub('RPC method tokenOnewrs for fungible collection and token', async ({helper}) => {
const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
- const facelessCrowd = (await helper.arrange.createAccounts(Array(7).fill(0n), donor)).map(keyring => {return {Substrate: keyring.address};});
+ const facelessCrowd = (await helper.arrange.createAccounts(Array(7).fill(0n), donor)).map(keyring => ({Substrate: keyring.address}));
const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
tests/src/getPropertiesRpc.test.tsdiffbeforeafterboth--- a/tests/src/getPropertiesRpc.test.ts
+++ b/tests/src/getPropertiesRpc.test.ts
@@ -48,17 +48,13 @@
describe('query properties RPC', () => {
let alice: IKeyringPair;
- const mintCollection = async (helper: UniqueHelper) => {
- return await helper.nft.mintCollection(alice, {
- tokenPrefix: 'prps',
- properties: collectionProps,
- tokenPropertyPermissions: tokenPropPermissions,
- });
- };
+ const mintCollection = async (helper: UniqueHelper) => await helper.nft.mintCollection(alice, {
+ tokenPrefix: 'prps',
+ properties: collectionProps,
+ tokenPropertyPermissions: tokenPropPermissions,
+ });
- const mintToken = async (collection: UniqueNFTCollection) => {
- return await collection.mintToken(alice, {Substrate: alice.address}, tokenProps);
- };
+ const mintToken = async (collection: UniqueNFTCollection) => await collection.mintToken(alice, {Substrate: alice.address}, tokenProps);
before(async () => {
tests/src/nesting/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/tokenProperties.test.ts
+++ b/tests/src/nesting/tokenProperties.test.ts
@@ -44,7 +44,7 @@
async function mintCollectionWithAllPermissionsAndToken(helper: UniqueHelper, mode: 'NFT' | 'RFT'): Promise<[UniqueNFToken | UniqueRFToken, bigint]> {
const collection = await (mode == 'NFT' ? helper.nft : helper.rft).mintCollection(alice, {
tokenPropertyPermissions: permissions.flatMap(({permission, signers}, i) =>
- signers.map(signer => {return {key: `${i+1}_${signer.address}`, permission};})),
+ signers.map(signer => ({key: `${i+1}_${signer.address}`, permission}))),
});
return mode == 'NFT' ? [await collection.mintToken(alice), 1n] : [await collection.mintToken(alice, 100n as any), 100n];
}
@@ -201,7 +201,7 @@
const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
const collectionB = await helper.nft.mintCollection(alice, {
tokenPropertyPermissions: permissions.flatMap(({permission, signers}, i) =>
- signers.map(signer => {return {key: `${i+1}_${signer.address}`, permission};})),
+ signers.map(signer => ({key: `${i+1}_${signer.address}`, permission}))),
});
const targetToken = await collectionA.mintToken(alice);
const nestedToken = await collectionB.mintToken(alice, targetToken.nestingAccount());
@@ -239,7 +239,7 @@
const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
const collectionB = await helper.nft.mintCollection(alice, {
tokenPropertyPermissions: permissions.flatMap(({permission, signers}, i) =>
- signers.map(signer => {return {key: `${i+1}_${signer.address}`, permission};})),
+ signers.map(signer => ({key: `${i+1}_${signer.address}`, permission}))),
});
const targetToken = await collectionA.mintToken(alice);
const nestedToken = await collectionB.mintToken(alice, targetToken.nestingAccount());
@@ -284,7 +284,7 @@
const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
const collectionB = await helper.nft.mintCollection(alice, {
tokenPropertyPermissions: permissions.flatMap(({permission, signers}, i) =>
- signers.map(signer => {return {key: `${i+1}_${signer.address}`, permission};})),
+ signers.map(signer => ({key: `${i+1}_${signer.address}`, permission}))),
});
const targetToken = await collectionA.mintToken(alice);
const nestedToken = await collectionB.mintToken(alice, targetToken.nestingAccount());
@@ -477,7 +477,7 @@
async function mintCollectionWithAllPermissionsAndToken(helper: UniqueHelper, mode: 'NFT' | 'RFT'): Promise<[UniqueNFToken | UniqueRFToken, bigint]> {
const collection = await (mode == 'NFT' ? helper.nft : helper.rft).mintCollection(alice, {
- tokenPropertyPermissions: constitution.map(({permission}, i) => {return {key: `${i+1}`, permission};}),
+ tokenPropertyPermissions: constitution.map(({permission}, i) => ({key: `${i+1}`, permission})),
});
return mode == 'NFT' ? [await collection.mintToken(alice), 1n] : [await collection.mintToken(alice, 100n as any), 100n];
}
tests/src/refungible.test.tsdiffbeforeafterboth--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -64,7 +64,7 @@
itSub('RPC method tokenOwners for refungible collection and token', async ({helper}) => {
const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
- const facelessCrowd = (await helper.arrange.createAccounts(Array(7).fill(0n), donor)).map(keyring => {return {Substrate: keyring.address};});
+ const facelessCrowd = (await helper.arrange.createAccounts(Array(7).fill(0n), donor)).map(keyring => ({Substrate: keyring.address}));
const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
tests/src/rpc.test.tsdiffbeforeafterboth--- a/tests/src/rpc.test.ts
+++ b/tests/src/rpc.test.ts
@@ -40,7 +40,7 @@
// Set-up a few token owners of all stripes
const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
const facelessCrowd = (await helper.arrange.createAccounts([0n, 0n, 0n, 0n, 0n, 0n, 0n], donor))
- .map(i => {return {Substrate: i.address};});
+ .map(i => ({Substrate: i.address}));
const collection = await helper.ft.mintCollection(alice, {name: 'RPC-2', tokenPrefix: 'RPC'});
// mint some maximum (u128) amounts of tokens possible
tests/src/sub/appPromotion/appPromotion.test.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {19 itSub, usingPlaygrounds, Pallets, requirePalletsOrSkip, LOCKING_PERIOD, UNLOCKING_PERIOD,20} from '../../util';21import {DevUniqueHelper} from '../../util/playgrounds/unique.dev';22import {itEth, expect, SponsoringMode} from '../../eth/util';2324let donor: IKeyringPair;25let palletAdmin: IKeyringPair;26let nominal: bigint;27let palletAddress: string;28let accounts: IKeyringPair[];29let usedAccounts: IKeyringPair[] = [];3031async function getAccounts(accountsNumber: number, balance?: bigint) {32 let accs: IKeyringPair[] = [];33 if (balance) {34 await usingPlaygrounds(async (helper) => {35 accs = await helper.arrange.createAccounts(new Array(accountsNumber).fill(balance), donor);36 });37 } else {38 accs = accounts.splice(0, accountsNumber);39 }40 usedAccounts.push(...accs);41 return accs;42}43// App promotion periods:44// LOCKING_PERIOD = 12 blocks of relay45// UNLOCKING_PERIOD = 6 blocks of parachain4647describe('App promotion', () => {48 before(async function () {49 await usingPlaygrounds(async (helper, privateKey) => {50 requirePalletsOrSkip(this, helper, [Pallets.AppPromotion]);51 donor = await privateKey({url: import.meta.url});52 palletAddress = helper.arrange.calculatePalletAddress('appstake');53 palletAdmin = await privateKey('//PromotionAdmin');54 nominal = helper.balance.getOneTokenNominal();5556 const accountBalances = new Array(200).fill(1000n);57 accounts = await helper.arrange.createAccounts(accountBalances, donor); // create accounts-pool to speed up tests58 });59 });6061 afterEach(async () => {62 await usingPlaygrounds(async (helper) => {63 let unstakeTxs = [];64 for (const account of usedAccounts) {65 if (unstakeTxs.length === 3) {66 await Promise.all(unstakeTxs);67 unstakeTxs = [];68 }69 unstakeTxs.push(helper.staking.unstakeAll(account));70 }71 await Promise.all(unstakeTxs);72 usedAccounts = [];73 expect(await helper.staking.getTotalStaked()).to.eq(0n); // there are no active stakes after each test74 // Make sure previousCalculatedRecord is None to avoid problem with payout stakers;75 await helper.admin.payoutStakers(palletAdmin, 100);76 expect((await helper.getApi().query.appPromotion.previousCalculatedRecord() as any).isNone).to.be.true;77 });78 });7980 describe('stake extrinsic', () => {81 itSub('should "freeze" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {82 const [staker, recepient] = await getAccounts(2);83 const totalStakedBefore = await helper.staking.getTotalStaked();8485 // Minimum stake amount is 100:86 await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;87 await helper.staking.stake(staker, 100n * nominal);8889 // Staker balance is: frozen: 100, reserved: 0n...90 // ...so he can not transfer 90091 expect(await helper.balance.getSubstrateFull(staker.address)).to.contain({frozen: 100n * nominal, reserved: 0n});92 expect(await helper.balance.getFrozen(staker.address)).to.deep.eq([{id: 'appstakeappstake', amount: 100n * nominal}]);93 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejectedWith(/^Token: Frozen$/);9495 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);96 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);97 // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo?98 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased99100101 await helper.staking.stake(staker, 200n * nominal);102 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);103 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});104 expect(totalStakedPerBlock[0].amount).to.equal(100n * nominal);105 expect(totalStakedPerBlock[1].amount).to.equal(200n * nominal);106 });107108 [109 {unstake: 'unstakeAll' as const},110 {unstake: 'unstakePartial' as const},111 ].map(testCase => {112 itSub(`[${testCase.unstake}] should allow to create maximum 10 stakes for account`, async ({helper}) => {113 const [staker] = await getAccounts(1, 2000n);114 const ONE_STAKE = 100n * nominal;115 for (let i = 0; i < 10; i++) {116 await helper.staking.stake(staker, ONE_STAKE);117 }118119 // can have 10 stakes120 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);121 expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);122123 await expect(helper.staking.stake(staker, ONE_STAKE)).to.be.rejectedWith('appPromotion.NoPermission');124125 // After unstake can stake again126127 // CASE 1: unstakeAll128 if (testCase.unstake === 'unstakeAll') {129 await helper.staking.unstakeAll(staker);130 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);131 await helper.staking.stake(staker, 100n * nominal);132 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);133 }134 // CASE 2: unstakePartial135 else {136 await helper.staking.unstakePartial(staker, ONE_STAKE);137 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);138 await helper.staking.stake(staker, 100n * nominal);139 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(10);140 await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');141 await helper.staking.unstakePartial(staker, 150n * nominal);142 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);143 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(850n * nominal);144 }145 });146 });147 // 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 => {361 return testCase.method === 'unstakeAll'362 ? helper.staking.unstakeAll(staker)363 : helper.staking.unstakePartial(staker, 100n * nominal);364 }));365366 await Promise.all(stakers.map(async (staker) => {367 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);368 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);369 }));370 });371 });372373 itSub('should not be possible for more than 3 accounts in one block', async ({helper}) => {374 if (!await helper.arrange.isDevNode()) {375 const stakers = await getAccounts(10);376377 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));378 const unstakingResults = await Promise.allSettled(stakers.map((staker, i) => {379 return i % 2 === 0380 ? helper.staking.unstakeAll(staker)381 : helper.staking.unstakePartial(staker, 100n * nominal);382 }));383384 const successfulUnstakes = unstakingResults.filter(result => result.status === 'fulfilled');385 expect(successfulUnstakes).to.have.length(3);386 }387 });388389 itSub('Cannot partially unstake more than staked', async ({helper}) => {390 const [staker] = await getAccounts(1);391 // Staker stakes 300:392 await helper.staking.stake(staker, 100n * nominal);393 await helper.staking.stake(staker, 200n * nominal);394395 // cannot usntake 300.00000...1396 await expect(helper.staking.unstakePartial(staker, 300n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');397 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(2);398399 await helper.staking.unstakePartial(staker, 150n * nominal);400 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);401 await expect(helper.staking.unstakePartial(staker, 150n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');402 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);403404 // nothing broken, can unstake full amount:405 await helper.staking.unstakePartial(staker, 150n * nominal);406 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(0);407 });408409 itSub('Can partially unstake arbitrary amount', async ({helper}) => {410 const [staker] = await getAccounts(1);411 await helper.staking.stake(staker, 100n * nominal);412 await helper.staking.stake(staker, 200n * nominal);413414 // 0. Staker cannot unstake negative amount415 await expect(helper.staking.unstakePartial(staker, -1n)).to.be.rejected;416417 // 1. Staker can unstake 0 wei418 await helper.staking.unstakePartial(staker, 0n);419 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);420 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal);421 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);422423 // 2. Staker can unstake 1 wei424 await helper.staking.unstakePartial(staker, 1n);425 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);426 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal - 1n);427 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1n);428 // 2.1 The oldest stake decreased:429 let [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});430 expect(stake1.amount).to.eq(100n * nominal - 1n);431 expect(stake2.amount).to.eq(200n * nominal);432433 // 3. Staker can unstake all but 1 wei434 await helper.staking.unstakePartial(staker, 100n * nominal - 2n);435 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);436 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(200n * nominal + 1n);437 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(100n * nominal - 1n);438 [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});439 expect(stake1.amount).to.eq(1n);440 expect(stake2.amount).to.eq(200n * nominal);441 });442443 itSub('can mix different type of unstakes', async ({helper}) => {444 const [staker] = await getAccounts(1);445 await helper.staking.stake(staker, 100n * nominal);446 await helper.staking.stake(staker, 200n * nominal);447448 await helper.staking.unstakePartial(staker, 50n * nominal);449 await helper.staking.unstakeAll(staker);450 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);451 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);452 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(300n * nominal);453454 const [_unstake1, unstake2] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});455 await helper.wait.forParachainBlockNumber(unstake2.block);456457 expect(await helper.balance.getFrozen(staker.address)).to.deep.eq([]);458 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 0n});459 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(999n);460 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);461 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);462 expect(await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).to.deep.eq([]);463 });464 });465466 describe('collection sponsoring', () => {467 itSub('should actually sponsor transactions', async ({helper}) => {468 const api = helper.getApi();469 const [collectionOwner, tokenSender, receiver] = await getAccounts(3);470 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});471 const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});472 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));473 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);474475 await token.transfer(tokenSender, {Substrate: receiver.address});476 expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});477 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);478479 // senders balance the same, transaction has sponsored480 expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);481 expect (palletBalanceBefore > palletBalanceAfter).to.be.true;482 });483484 itSub('can not be set by non admin', async ({helper}) => {485 const api = helper.getApi();486 const [collectionOwner, nonAdmin] = await getAccounts(2);487488 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});489490 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;491 expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');492 });493494 itSub('should set pallet address as confirmed admin', async ({helper}) => {495 const api = helper.getApi();496 const [collectionOwner, oldSponsor] = await getAccounts(2);497498 // Can set sponsoring for collection without sponsor499 const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});500 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;501 expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});502503 // Can set sponsoring for collection with unconfirmed sponsor504 const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});505 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});506 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;507 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});508509 // Can set sponsoring for collection with confirmed sponsor510 const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});511 await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);512 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;513 expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});514 });515516 itSub('can be overwritten by collection owner', async ({helper}) => {517 const api = helper.getApi();518 const [collectionOwner, newSponsor] = await getAccounts(2);519 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});520 const collectionId = collection.collectionId;521522 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;523524 // Collection limits still can be changed by the owner525 expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;526 expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);527 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});528529 // Collection sponsor can be changed too530 expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;531 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});532 });533534 itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {535 const [owner] = await getAccounts(1);536 const api = helper.getApi();537 const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};538 const collectionWithLimits = await helper.nft.mintCollection(owner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});539540 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;541 expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);542 });543544 itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {545 const api = helper.getApi();546 const [collectionOwner] = await getAccounts(1);547548 // collection has never existed549 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;550 // collection has been burned551 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});552 await collection.burn(collectionOwner);553554 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;555 });556 });557558 describe('stopSponsoringCollection', () => {559 itSub('can not be called by non-admin', async ({helper}) => {560 const api = helper.getApi();561 const [collectionOwner, nonAdmin] = await getAccounts(2);562 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});563564 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;565566 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;567 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});568 });569570 itSub('should set sponsoring as disabled', async ({helper}) => {571 const api = helper.getApi();572 const [collectionOwner, recepient] = await getAccounts(2);573 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});574 const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});575576 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));577 await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId));578579 expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');580581 // Transactions are not sponsored anymore:582 const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);583 await token.transfer(collectionOwner, {Substrate: recepient.address});584 const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);585 expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);586 });587588 itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {589 const api = helper.getApi();590 const [collectionOwner] = await getAccounts(1);591 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});592 await collection.confirmSponsorship(collectionOwner);593594 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;595596 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});597 });598599 itSub('should reject transaction if collection does not exist', async ({helper}) => {600 const [collectionOwner] = await getAccounts(1);601 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});602603 await collection.burn(collectionOwner);604 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');605 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');606 });607 });608609 describe('contract sponsoring', () => {610 itEth('should set palletes address as a sponsor', async ({helper}) => {611 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();612 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);613 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);614615 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);616617 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;618 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);619 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({620 confirmed: {621 substrate: palletAddress,622 },623 });624 });625626 itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {627 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();628 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);629 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);630631 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;632633 // Contract is self sponsored634 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.be.deep.equal({635 confirmed: {636 ethereum: flipper.options.address.toLowerCase(),637 },638 });639640 // set promotion sponsoring641 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);642643 // new sponsor is pallet address644 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;645 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);646 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({647 confirmed: {648 substrate: palletAddress,649 },650 });651 });652653 itEth('can be overwritten by contract owner', async ({helper}) => {654 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();655 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);656 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);657658 // contract sponsored by pallet659 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);660661 // owner sets self sponsoring662 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;663664 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;665 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);666 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({667 confirmed: {668 ethereum: flipper.options.address.toLowerCase(),669 },670 });671 });672673 itEth('can not be set by non admin', async ({helper}) => {674 const [nonAdmin] = await getAccounts(1);675 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();676 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);677 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);678679 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;680681 // nonAdmin calls sponsorContract682 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');683684 // contract still self-sponsored685 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({686 confirmed: {687 ethereum: flipper.options.address.toLowerCase(),688 },689 });690 });691692 itEth('should actually sponsor transactions', async ({helper}) => {693 // Contract caller694 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);695 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);696697 // Deploy flipper698 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();699 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);700 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);701702 // Owner sets to sponsor every tx703 await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});704 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});705 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);706707 // Set promotion to the Flipper708 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);709710 // Caller calls Flipper711 await flipper.methods.flip().send({from: caller});712 expect(await flipper.methods.getValue().call()).to.be.true;713714 // The contracts and caller balances have not changed715 const callerBalance = await helper.balance.getEthereum(caller);716 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);717 expect(callerBalance).to.be.equal(1000n * nominal);718 expect(1000n * nominal === contractBalanceAfter).to.be.true;719720 // The pallet balance has decreased721 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);722 expect(palletBalanceAfter < palletBalanceBefore).to.be.true;723 });724 });725726 describe('stopSponsoringContract', () => {727 itEth('should remove pallet address from contract sponsors', async ({helper}) => {728 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);729 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();730 const flipper = await helper.eth.deployFlipper(contractOwner);731 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address);732 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);733734 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});735 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);736 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);737738 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;739 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);740 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({741 disabled: null,742 });743744 await flipper.methods.flip().send({from: caller});745 expect(await flipper.methods.getValue().call()).to.be.true;746747 const callerBalance = await helper.balance.getEthereum(caller);748 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);749750 // caller payed for call751 expect(1000n * nominal > callerBalance).to.be.true;752 expect(contractBalanceAfter).to.be.equal(100n * nominal);753 });754755 itEth('can not be called by non-admin', async ({helper}) => {756 const [nonAdmin] = await getAccounts(1);757 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();758 const flipper = await helper.eth.deployFlipper(contractOwner);759760 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);761 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]))762 .to.be.rejectedWith(/appPromotion\.NoPermission/);763 });764765 itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {766 const [nonAdmin] = await getAccounts(1);767 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();768 const flipper = await helper.eth.deployFlipper(contractOwner);769 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);770 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;771772 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');773 });774 });775776 describe('payoutStakers', () => {777 itSub('can not be called by non admin', async ({helper}) => {778 const [nonAdmin] = await getAccounts(1);779 await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');780 });781782 itSub('should increase total staked', async ({helper}) => {783 const [staker] = await getAccounts(1);784 const totalStakedBefore = await helper.staking.getTotalStaked();785 await helper.staking.stake(staker, 100n * nominal);786787 // Wait for rewards and pay788 const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});789 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));790791 const payout = await helper.admin.payoutStakers(palletAdmin, 100);792 const totalPayout = payout.reduce((prev, payout) => prev + payout.payout, 0n);793 const stakerReward = payout.find(p => p.staker === staker.address);794795 expect(stakerReward?.payout).to.eq(calculateIncome(100n * nominal) - (100n * nominal));796797 const totalStakedAfter = await helper.staking.getTotalStaked();798 expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);799 // staker can unstake800 await helper.staking.unstakeAll(staker);801 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal));802 });803804 itSub('should credit 0.05% for staking period', async ({helper}) => {805 const [staker] = await getAccounts(1);806807 await waitPromotionPeriodDoesntEnd(helper);808809 await helper.staking.stake(staker, 100n * nominal);810 await helper.staking.stake(staker, 200n * nominal);811812 // wait rewards are available:813 const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});814 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));815816 const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)!.payout;817 expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal));818819 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});820 const income1 = calculateIncome(100n * nominal);821 const income2 = calculateIncome(200n * nominal);822 expect(totalStakedPerBlock[0].amount).to.equal(income1);823 expect(totalStakedPerBlock[1].amount).to.equal(income2);824825 const stakerBalance = await helper.balance.getSubstrateFull(staker.address);826 expect(stakerBalance).to.contain({frozen: income1 + income2, reserved: 0n});827 expect(stakerBalance.free / nominal).to.eq(999n);828 });829830 itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {831 const [staker] = await getAccounts(1);832833 await helper.staking.stake(staker, 100n * nominal);834 // wait for two rewards are available:835 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});836 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);837838 await helper.admin.payoutStakers(palletAdmin, 100);839 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});840 const frozenBalanceShouldBe = calculateIncome(100n * nominal, 2);841 expect(stake.amount).to.be.equal(frozenBalanceShouldBe);842843 const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);844845 expect(stakerFullBalance).to.contain({reserved: 0n, frozen: frozenBalanceShouldBe});846 });847848 itSub('should not be credited for pending-unstaked tokens', async ({helper}) => {849 // staker unstakes before rewards been payed850 const [staker] = await getAccounts(1);851 await helper.staking.stake(staker, 100n * nominal);852 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});853 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);854 await helper.staking.unstakeAll(staker);855856 // so he did not receive any rewards857 const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);858 await helper.admin.payoutStakers(palletAdmin, 100);859 const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);860861 expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);862 });863864 itSub('should bring compound interest', async ({helper}) => {865 const [staker] = await getAccounts(1);866867 await helper.staking.stake(staker, 100n * nominal);868869 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});870 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));871872 await helper.admin.payoutStakers(palletAdmin, 100);873 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});874 expect(stake.amount).to.equal(calculateIncome(100n * nominal));875876 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);877 await helper.admin.payoutStakers(palletAdmin, 100);878 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});879 expect(stake.amount).to.equal(calculateIncome(100n * nominal, 2));880 });881882 itSub('can calculate reward for tiny stake', async ({helper}) => {883 const [staker] = await getAccounts(1);884 await helper.staking.stake(staker, 100n * nominal);885 await helper.staking.stake(staker, 100n * nominal);886 await helper.staking.unstakePartial(staker, 100n * nominal - 1n);887888 const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});889 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));890891 const stakerPayout = await payUntilRewardFor(staker.address, helper);892 expect(stakerPayout.stake).to.eq(100n * nominal + 1n);893 });894895 itSub('can eventually pay all rewards', async ({helper}) => {896 const stakers = await getAccounts(30);897 // Create 30 stakes:898 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));899900 let unstakingTxs = [];901 for (const staker of stakers) {902 if (unstakingTxs.length == 3) {903 await Promise.all(unstakingTxs);904 unstakingTxs = [];905 }906 unstakingTxs.push(helper.staking.unstakePartial(staker, 100n * nominal - 1n));907 }908909 const [staker] = await getAccounts(1);910 await helper.staking.stake(staker, 100n * nominal);911 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});912 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));913914 let payouts;915 do {916 payouts = await helper.admin.payoutStakers(palletAdmin, 20);917 } while (payouts.length !== 0);918 });919 });920921 describe('events', () => {922 [923 {method: 'unstakePartial' as const},924 {method: 'unstakeAll' as const},925 ].map(testCase => {926 itSub(testCase.method, async ({helper}) => {927 const unstakeParams: [] | [bigint] = testCase.method === 'unstakePartial'928 ? [100n * nominal - 1n]929 : [];930 const [staker] = await getAccounts(1);931 await helper.staking.stake(staker, 100n * nominal);932 await helper.staking.stake(staker, 200n * nominal);933 const {result} = await helper.executeExtrinsic(staker, `api.tx.appPromotion.${testCase.method}`, unstakeParams);934935 const event = result.events.find(e => e.event.section === 'appPromotion' && e.event.method === 'Unstake');936 const unstakerEvents = event?.event.data[0].toString();937 const unstakedEvents = BigInt(event?.event.data[1].toString());938 expect(unstakerEvents).to.eq(staker.address);939 expect(unstakedEvents).to.eq(testCase.method === 'unstakeAll' ? 300n * nominal : 100n * nominal - 1n);940 });941 });942943 itSub('stake', async ({helper}) => {944 const [staker] = await getAccounts(1);945 const {result} = await helper.executeExtrinsic(staker, 'api.tx.appPromotion.stake', [100n * nominal]);946947 const event = result.events.find(e => e.event.section === 'appPromotion' && e.event.method === 'Stake');948 const stakerEvents = event?.event.data[0].toString();949 const stakedEvents = BigInt(event?.event.data[1].toString());950 expect(stakerEvents).to.eq(staker.address);951 expect(stakedEvents).to.eq(100n * nominal);952 });953954 // Flaky955 itSub.skip('payoutStakers', async ({helper}) => {956 const [staker1, staker2] = await getAccounts(2);957 const STAKE1 = 100n * nominal;958 const STAKE2 = 200n * nominal;959 await helper.staking.stake(staker1, STAKE1);960 await helper.staking.stake(staker2, STAKE2);961962 const [stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker2.address});963 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));964965 const results = await helper.admin.payoutStakers(palletAdmin, 100);966 const stakersEvents = results.filter(ev => ev.staker === staker1.address || ev.staker === staker2.address);967 expect(stakersEvents).has.length(2);968 expect(stakersEvents).has.not.ordered.members([969 {staker: staker1.address, stake: STAKE1, payout: calculateIncome(STAKE1) - STAKE1},970 {staker: staker2.address, stake: STAKE2, payout: calculateIncome(STAKE2) - STAKE2},971 ]);972 });973 });974});975976977// Sometimes is is required to make a cycle in order for the payment to be calculated for a specific account978async function payUntilRewardFor(account: string, helper: DevUniqueHelper) {979 for (let i = 0; i < 3; i++) {980 const payouts = await helper.admin.payoutStakers(palletAdmin, 100);981 const accountPayout = payouts.find(p => p.staker === account);982 if (accountPayout) return accountPayout;983 }984 throw Error(`Cannot find payout for ${account}`);985}986987function calculateIncome(base: bigint, iter = 0, calcPeriod: bigint = UNLOCKING_PERIOD): bigint {988 const DAY = 7200n;989 const ACCURACY = 1_000_000_000n;990 // 5n / 10_000n = 0.05% p/day991 const income = base + base * (ACCURACY * (calcPeriod * 5n) / (10_000n * DAY)) / ACCURACY ;992993 if (iter > 1) {994 return calculateIncome(income, iter - 1, calcPeriod);995 } else return income;996}997998function rewardAvailableInBlock(stakedInBlock: bigint) {999 if (stakedInBlock % LOCKING_PERIOD === 0n) return stakedInBlock + LOCKING_PERIOD;1000 return (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);1001}10021003// Wait while promotion period less than specified block, to avoid boundary cases1004// 0 if this should be the beginning of the period.1005async function waitPromotionPeriodDoesntEnd(helper: DevUniqueHelper, waitBlockLessThan = LOCKING_PERIOD / 3n) {1006 const relayBlockNumber = (await helper.callRpc('api.query.parachainSystem.validationData', [])).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();1007 const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;10081009 if (currentPeriodBlock > waitBlockLessThan) {1010 await helper.wait.forRelayBlockNumber(BigInt(relayBlockNumber) + LOCKING_PERIOD - currentPeriodBlock);1011 }1012}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {19 itSub, usingPlaygrounds, Pallets, requirePalletsOrSkip, LOCKING_PERIOD, UNLOCKING_PERIOD,20} from '../../util';21import {DevUniqueHelper} from '../../util/playgrounds/unique.dev';22import {itEth, expect, SponsoringMode} from '../../eth/util';2324let donor: IKeyringPair;25let palletAdmin: IKeyringPair;26let nominal: bigint;27let palletAddress: string;28let accounts: IKeyringPair[];29let usedAccounts: IKeyringPair[] = [];3031async function getAccounts(accountsNumber: number, balance?: bigint) {32 let accs: IKeyringPair[] = [];33 if (balance) {34 await usingPlaygrounds(async (helper) => {35 accs = await helper.arrange.createAccounts(new Array(accountsNumber).fill(balance), donor);36 });37 } else {38 accs = accounts.splice(0, accountsNumber);39 }40 usedAccounts.push(...accs);41 return accs;42}43// App promotion periods:44// LOCKING_PERIOD = 12 blocks of relay45// UNLOCKING_PERIOD = 6 blocks of parachain4647describe('App promotion', () => {48 before(async function () {49 await usingPlaygrounds(async (helper, privateKey) => {50 requirePalletsOrSkip(this, helper, [Pallets.AppPromotion]);51 donor = await privateKey({url: import.meta.url});52 palletAddress = helper.arrange.calculatePalletAddress('appstake');53 palletAdmin = await privateKey('//PromotionAdmin');54 nominal = helper.balance.getOneTokenNominal();5556 const accountBalances = new Array(200).fill(1000n);57 accounts = await helper.arrange.createAccounts(accountBalances, donor); // create accounts-pool to speed up tests58 });59 });6061 afterEach(async () => {62 await usingPlaygrounds(async (helper) => {63 let unstakeTxs = [];64 for (const account of usedAccounts) {65 if (unstakeTxs.length === 3) {66 await Promise.all(unstakeTxs);67 unstakeTxs = [];68 }69 unstakeTxs.push(helper.staking.unstakeAll(account));70 }71 await Promise.all(unstakeTxs);72 usedAccounts = [];73 expect(await helper.staking.getTotalStaked()).to.eq(0n); // there are no active stakes after each test74 // Make sure previousCalculatedRecord is None to avoid problem with payout stakers;75 await helper.admin.payoutStakers(palletAdmin, 100);76 expect((await helper.getApi().query.appPromotion.previousCalculatedRecord() as any).isNone).to.be.true;77 });78 });7980 describe('stake extrinsic', () => {81 itSub('should "freeze" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {82 const [staker, recepient] = await getAccounts(2);83 const totalStakedBefore = await helper.staking.getTotalStaked();8485 // Minimum stake amount is 100:86 await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;87 await helper.staking.stake(staker, 100n * nominal);8889 // Staker balance is: frozen: 100, reserved: 0n...90 // ...so he can not transfer 90091 expect(await helper.balance.getSubstrateFull(staker.address)).to.contain({frozen: 100n * nominal, reserved: 0n});92 expect(await helper.balance.getFrozen(staker.address)).to.deep.eq([{id: 'appstakeappstake', amount: 100n * nominal}]);93 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejectedWith(/^Token: Frozen$/);9495 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);96 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);97 // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo?98 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased99100101 await helper.staking.stake(staker, 200n * nominal);102 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);103 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});104 expect(totalStakedPerBlock[0].amount).to.equal(100n * nominal);105 expect(totalStakedPerBlock[1].amount).to.equal(200n * nominal);106 });107108 [109 {unstake: 'unstakeAll' as const},110 {unstake: 'unstakePartial' as const},111 ].map(testCase => {112 itSub(`[${testCase.unstake}] should allow to create maximum 10 stakes for account`, async ({helper}) => {113 const [staker] = await getAccounts(1, 2000n);114 const ONE_STAKE = 100n * nominal;115 for (let i = 0; i < 10; i++) {116 await helper.staking.stake(staker, ONE_STAKE);117 }118119 // can have 10 stakes120 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);121 expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);122123 await expect(helper.staking.stake(staker, ONE_STAKE)).to.be.rejectedWith('appPromotion.NoPermission');124125 // After unstake can stake again126127 // CASE 1: unstakeAll128 if (testCase.unstake === 'unstakeAll') {129 await helper.staking.unstakeAll(staker);130 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);131 await helper.staking.stake(staker, 100n * nominal);132 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);133 }134 // CASE 2: unstakePartial135 else {136 await helper.staking.unstakePartial(staker, ONE_STAKE);137 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);138 await helper.staking.stake(staker, 100n * nominal);139 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(10);140 await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');141 await helper.staking.unstakePartial(staker, 150n * nominal);142 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);143 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(850n * nominal);144 }145 });146 });147 // 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: oldSponsor.address});501 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});502 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;503 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});504505 // Can set sponsoring for collection with confirmed sponsor506 const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});507 await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);508 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;509 expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});510 });511512 itSub('can be overwritten by collection owner', async ({helper}) => {513 const api = helper.getApi();514 const [collectionOwner, newSponsor] = await getAccounts(2);515 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});516 const collectionId = collection.collectionId;517518 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;519520 // Collection limits still can be changed by the owner521 expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;522 expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);523 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});524525 // Collection sponsor can be changed too526 expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;527 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});528 });529530 itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {531 const [owner] = await getAccounts(1);532 const api = helper.getApi();533 const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};534 const collectionWithLimits = await helper.nft.mintCollection(owner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});535536 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;537 expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);538 });539540 itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {541 const api = helper.getApi();542 const [collectionOwner] = await getAccounts(1);543544 // collection has never existed545 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;546 // collection has been burned547 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});548 await collection.burn(collectionOwner);549550 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;551 });552 });553554 describe('stopSponsoringCollection', () => {555 itSub('can not be called by non-admin', async ({helper}) => {556 const api = helper.getApi();557 const [collectionOwner, nonAdmin] = await getAccounts(2);558 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});559560 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;561562 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;563 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});564 });565566 itSub('should set sponsoring as disabled', async ({helper}) => {567 const api = helper.getApi();568 const [collectionOwner, recepient] = await getAccounts(2);569 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});570 const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});571572 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));573 await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId));574575 expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');576577 // Transactions are not sponsored anymore:578 const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);579 await token.transfer(collectionOwner, {Substrate: recepient.address});580 const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);581 expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);582 });583584 itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {585 const api = helper.getApi();586 const [collectionOwner] = await getAccounts(1);587 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});588 await collection.confirmSponsorship(collectionOwner);589590 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;591592 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});593 });594595 itSub('should reject transaction if collection does not exist', async ({helper}) => {596 const [collectionOwner] = await getAccounts(1);597 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});598599 await collection.burn(collectionOwner);600 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');601 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');602 });603 });604605 describe('contract sponsoring', () => {606 itEth('should set palletes address as a sponsor', async ({helper}) => {607 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();608 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);609 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);610611 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);612613 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;614 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);615 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({616 confirmed: {617 substrate: palletAddress,618 },619 });620 });621622 itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {623 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();624 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);625 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);626627 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;628629 // Contract is self sponsored630 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.be.deep.equal({631 confirmed: {632 ethereum: flipper.options.address.toLowerCase(),633 },634 });635636 // set promotion sponsoring637 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);638639 // new sponsor is pallet address640 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;641 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);642 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({643 confirmed: {644 substrate: palletAddress,645 },646 });647 });648649 itEth('can be overwritten by contract owner', async ({helper}) => {650 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();651 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);652 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);653654 // contract sponsored by pallet655 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);656657 // owner sets self sponsoring658 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;659660 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;661 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);662 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({663 confirmed: {664 ethereum: flipper.options.address.toLowerCase(),665 },666 });667 });668669 itEth('can not be set by non admin', async ({helper}) => {670 const [nonAdmin] = await getAccounts(1);671 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();672 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);673 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);674675 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;676677 // nonAdmin calls sponsorContract678 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');679680 // contract still self-sponsored681 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({682 confirmed: {683 ethereum: flipper.options.address.toLowerCase(),684 },685 });686 });687688 itEth('should actually sponsor transactions', async ({helper}) => {689 // Contract caller690 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);691 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);692693 // Deploy flipper694 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();695 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);696 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);697698 // Owner sets to sponsor every tx699 await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});700 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});701 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);702703 // Set promotion to the Flipper704 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);705706 // Caller calls Flipper707 await flipper.methods.flip().send({from: caller});708 expect(await flipper.methods.getValue().call()).to.be.true;709710 // The contracts and caller balances have not changed711 const callerBalance = await helper.balance.getEthereum(caller);712 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);713 expect(callerBalance).to.be.equal(1000n * nominal);714 expect(1000n * nominal === contractBalanceAfter).to.be.true;715716 // The pallet balance has decreased717 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);718 expect(palletBalanceAfter < palletBalanceBefore).to.be.true;719 });720 });721722 describe('stopSponsoringContract', () => {723 itEth('should remove pallet address from contract sponsors', async ({helper}) => {724 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);725 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();726 const flipper = await helper.eth.deployFlipper(contractOwner);727 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address);728 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);729730 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});731 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);732 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);733734 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;735 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);736 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({737 disabled: null,738 });739740 await flipper.methods.flip().send({from: caller});741 expect(await flipper.methods.getValue().call()).to.be.true;742743 const callerBalance = await helper.balance.getEthereum(caller);744 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);745746 // caller payed for call747 expect(1000n * nominal > callerBalance).to.be.true;748 expect(contractBalanceAfter).to.be.equal(100n * nominal);749 });750751 itEth('can not be called by non-admin', async ({helper}) => {752 const [nonAdmin] = await getAccounts(1);753 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();754 const flipper = await helper.eth.deployFlipper(contractOwner);755756 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);757 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]))758 .to.be.rejectedWith(/appPromotion\.NoPermission/);759 });760761 itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {762 const [nonAdmin] = await getAccounts(1);763 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();764 const flipper = await helper.eth.deployFlipper(contractOwner);765 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);766 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;767768 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');769 });770 });771772 describe('payoutStakers', () => {773 itSub('can not be called by non admin', async ({helper}) => {774 const [nonAdmin] = await getAccounts(1);775 await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');776 });777778 itSub('should increase total staked', async ({helper}) => {779 const [staker] = await getAccounts(1);780 const totalStakedBefore = await helper.staking.getTotalStaked();781 await helper.staking.stake(staker, 100n * nominal);782783 // Wait for rewards and pay784 const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});785 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));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 * 5n) / (10_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}tests/src/util/index.tsdiffbeforeafterboth--- a/tests/src/util/index.ts
+++ b/tests/src/util/index.ts
@@ -19,13 +19,9 @@
chai.use(chaiSubset);
export const expect = chai.expect;
-const getTestHash = (filename: string) => {
- return crypto.createHash('md5').update(filename).digest('hex');
-};
+const getTestHash = (filename: string) => crypto.createHash('md5').update(filename).digest('hex');
-export const getTestSeed = (filename: string) => {
- return `//Alice+${getTestHash(filename)}`;
-};
+export const getTestSeed = (filename: string) => `//Alice+${getTestHash(filename)}`;
async function usingPlaygroundsGeneral<T extends ChainHelperBase>(helperType: new(logger: ILogger) => T, url: string, code: (helper: T, privateKey: (seed: string | {filename?: string, url?: string, ignoreFundsPresence?: boolean}) => Promise<IKeyringPair>) => Promise<void>) {
const silentConsole = new SilentConsole();
@@ -65,49 +61,27 @@
}
}
-export const usingPlaygrounds = (code: (helper: DevUniqueHelper, privateKey: (seed: string | {filename?: string, url?: string, ignoreFundsPresence?: boolean}) => Promise<IKeyringPair>) => Promise<void>, url: string = config.substrateUrl) => {
- return usingPlaygroundsGeneral<DevUniqueHelper>(DevUniqueHelper, url, code);
-};
+export const usingPlaygrounds = (code: (helper: DevUniqueHelper, privateKey: (seed: string | {filename?: string, url?: string, ignoreFundsPresence?: boolean}) => Promise<IKeyringPair>) => Promise<void>, url: string = config.substrateUrl) => usingPlaygroundsGeneral<DevUniqueHelper>(DevUniqueHelper, url, code);
-export const usingWestmintPlaygrounds = (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
- return usingPlaygroundsGeneral<DevWestmintHelper>(DevWestmintHelper, url, code);
-};
+export const usingWestmintPlaygrounds = (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevWestmintHelper>(DevWestmintHelper, url, code);
-export const usingStateminePlaygrounds = (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
- return usingPlaygroundsGeneral<DevStatemineHelper>(DevWestmintHelper, url, code);
-};
+export const usingStateminePlaygrounds = (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevStatemineHelper>(DevWestmintHelper, url, code);
-export const usingStatemintPlaygrounds = (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
- return usingPlaygroundsGeneral<DevStatemintHelper>(DevWestmintHelper, url, code);
-};
+export const usingStatemintPlaygrounds = (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevStatemintHelper>(DevWestmintHelper, url, code);
-export const usingRelayPlaygrounds = (url: string, code: (helper: DevRelayHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
- return usingPlaygroundsGeneral<DevRelayHelper>(DevRelayHelper, url, code);
-};
+export const usingRelayPlaygrounds = (url: string, code: (helper: DevRelayHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevRelayHelper>(DevRelayHelper, url, code);
-export const usingAcalaPlaygrounds = (url: string, code: (helper: DevAcalaHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
- return usingPlaygroundsGeneral<DevAcalaHelper>(DevAcalaHelper, url, code);
-};
+export const usingAcalaPlaygrounds = (url: string, code: (helper: DevAcalaHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevAcalaHelper>(DevAcalaHelper, url, code);
-export const usingKaruraPlaygrounds = (url: string, code: (helper: DevKaruraHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
- return usingPlaygroundsGeneral<DevKaruraHelper>(DevAcalaHelper, url, code);
-};
+export const usingKaruraPlaygrounds = (url: string, code: (helper: DevKaruraHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevKaruraHelper>(DevAcalaHelper, url, code);
-export const usingMoonbeamPlaygrounds = (url: string, code: (helper: DevMoonbeamHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
- return usingPlaygroundsGeneral<DevMoonbeamHelper>(DevMoonbeamHelper, url, code);
-};
+export const usingMoonbeamPlaygrounds = (url: string, code: (helper: DevMoonbeamHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevMoonbeamHelper>(DevMoonbeamHelper, url, code);
-export const usingMoonriverPlaygrounds = (url: string, code: (helper: DevMoonbeamHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
- return usingPlaygroundsGeneral<DevMoonriverHelper>(DevMoonriverHelper, url, code);
-};
+export const usingMoonriverPlaygrounds = (url: string, code: (helper: DevMoonbeamHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevMoonriverHelper>(DevMoonriverHelper, url, code);
-export const usingAstarPlaygrounds = (url: string, code: (helper: DevAstarHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
- return usingPlaygroundsGeneral<DevAstarHelper>(DevAstarHelper, url, code);
-};
+export const usingAstarPlaygrounds = (url: string, code: (helper: DevAstarHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevAstarHelper>(DevAstarHelper, url, code);
-export const usingShidenPlaygrounds = (url: string, code: (helper: DevShidenHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
- return usingPlaygroundsGeneral<DevShidenHelper>(DevShidenHelper, url, code);
-};
+export const usingShidenPlaygrounds = (url: string, code: (helper: DevShidenHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevShidenHelper>(DevShidenHelper, url, code);
export const MINIMUM_DONOR_FUND = 100_000n;
export const DONOR_FUNDING = 2_000_000n;
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -771,9 +771,7 @@
// <<< Referendum voting <<<
// Wait the proposal to pass
- await this.helper.wait.expectEvent(3, Event.Democracy.Passed, event => {
- return event.referendumIndex() == referendumIndex;
- });
+ await this.helper.wait.expectEvent(3, Event.Democracy.Passed, event => event.referendumIndex() == referendumIndex);
await this.helper.wait.newBlocks(1);
@@ -924,7 +922,7 @@
event<T extends IEventHelper>(
maxBlocksToWait: number,
eventHelperType: new () => T,
- filter: (_: T) => boolean = () => { return true; },
+ filter: (_: T) => boolean = () => true,
) {
// eslint-disable-next-line no-async-promise-executor
const promise = new Promise<T | null>(async (resolve) => {
@@ -970,7 +968,7 @@
async expectEvent<T extends IEventHelper>(
maxBlocksToWait: number,
eventHelperType: new () => T,
- filter: (e: T) => boolean = () => { return true; },
+ filter: (e: T) => boolean = () => true,
) {
const e = await this.event(maxBlocksToWait, eventHelperType, filter);
if (e == null) {
@@ -1077,9 +1075,7 @@
async startCapture() {
this.stopCapture();
this.unsubscribe = (await this.helper.getApi().query.system.events((eventRecords: FrameSystemEventRecord[]) => {
- const newEvents = eventRecords.filter(r => {
- return r.event.section == this.eventSection && r.event.method == this.eventMethod;
- });
+ const newEvents = eventRecords.filter(r => r.event.section == this.eventSection && r.event.method == this.eventMethod);
this.events.push(...newEvents);
})) as any;
@@ -1105,12 +1101,10 @@
async payoutStakers(signer: IKeyringPair, stakersToPayout: number): Promise<{staker: string, stake: bigint, payout: bigint}[]> {
const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);
- return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {
- return {
- staker: e.event.data[0].toString(),
- stake: e.event.data[1].toBigInt(),
- payout: e.event.data[2].toBigInt(),
- };
- });
+ return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => ({
+ staker: e.event.data[0].toString(),
+ stake: e.event.data[1].toBigInt(),
+ payout: e.event.data[2].toBigInt(),
+ }));
}
}
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -2395,7 +2395,7 @@
return total.toBigInt();
}
- async getLocked(address: TSubstrateAccount): Promise<[{ id: string, amount: bigint, reason: string }]> {
+ async getLocked(address: TSubstrateAccount): Promise<{ id: string, amount: bigint, reason: string }[]> {
const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();
return locks.map((lock: any) => ({id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons}));
}
@@ -2581,14 +2581,12 @@
*/
async getVestingSchedules(address: TSubstrateAccount): Promise<{ start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }[]> {
const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();
- return schedule.map((schedule: any) => {
- return {
- start: BigInt(schedule.start),
- period: BigInt(schedule.period),
- periodCount: BigInt(schedule.periodCount),
- perPeriod: BigInt(schedule.perPeriod),
- };
- });
+ return schedule.map((schedule: any) => ({
+ start: BigInt(schedule.start),
+ period: BigInt(schedule.period),
+ periodCount: BigInt(schedule.periodCount),
+ perPeriod: BigInt(schedule.perPeriod),
+ }));
}
/**
@@ -2804,12 +2802,10 @@
*/
async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {
const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);
- return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {
- return {
- block: block.toBigInt(),
- amount: amount.toBigInt(),
- };
- });
+ return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => ({
+ block: block.toBigInt(),
+ amount: amount.toBigInt(),
+ }));
}
/**
@@ -2828,12 +2824,10 @@
*/
async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {
const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);
- const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {
- return {
- block: block.toBigInt(),
- amount: amount.toBigInt(),
- };
- });
+ const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => ({
+ block: block.toBigInt(),
+ amount: amount.toBigInt(),
+ }));
return result;
}
}
tests/src/xcm/xcmQuartz.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmQuartz.test.ts
+++ b/tests/src/xcm/xcmQuartz.test.ts
@@ -682,10 +682,8 @@
maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramSent.messageHash()
- && event.outcome().isFailedToTransactAsset;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramSent.messageHash()
+ && event.outcome().isFailedToTransactAsset);
targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(targetAccountBalance).to.be.equal(0n);
@@ -765,10 +763,8 @@
maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramFullIdSent.messageHash()
- && event.outcome().isUntrustedReserveLocation;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramFullIdSent.messageHash()
+ && event.outcome().isUntrustedReserveLocation);
let accountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(accountBalance).to.be.equal(0n);
@@ -780,10 +776,8 @@
maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramHereIdSent.messageHash()
- && event.outcome().isUntrustedReserveLocation;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramHereIdSent.messageHash()
+ && event.outcome().isUntrustedReserveLocation);
accountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(accountBalance).to.be.equal(0n);
@@ -858,10 +852,8 @@
});
const expectFailedToTransact = async (helper: DevUniqueHelper, messageSent: any) => {
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == messageSent.messageHash()
- && event.outcome().isFailedToTransactAsset;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == messageSent.messageHash()
+ && event.outcome().isFailedToTransactAsset);
};
itSub('Quartz rejects KAR tokens from Karura', async ({helper}) => {
@@ -1172,10 +1164,8 @@
maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramSent.messageHash()
- && event.outcome().isFailedToTransactAsset;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramSent.messageHash()
+ && event.outcome().isFailedToTransactAsset);
targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(targetAccountBalance).to.be.equal(0n);
@@ -1263,10 +1253,8 @@
maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramFullIdSent.messageHash()
- && event.outcome().isUntrustedReserveLocation;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramFullIdSent.messageHash()
+ && event.outcome().isUntrustedReserveLocation);
let accountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(accountBalance).to.be.equal(0n);
@@ -1282,10 +1270,8 @@
maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramHereIdSent.messageHash()
- && event.outcome().isUntrustedReserveLocation;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramHereIdSent.messageHash()
+ && event.outcome().isUntrustedReserveLocation);
accountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(accountBalance).to.be.equal(0n);
@@ -1544,10 +1530,8 @@
maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramSent.messageHash()
- && event.outcome().isFailedToTransactAsset;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramSent.messageHash()
+ && event.outcome().isFailedToTransactAsset);
targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(targetAccountBalance).to.be.equal(0n);
@@ -1627,10 +1611,8 @@
maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramFullIdSent.messageHash()
- && event.outcome().isUntrustedReserveLocation;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramFullIdSent.messageHash()
+ && event.outcome().isUntrustedReserveLocation);
let accountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(accountBalance).to.be.equal(0n);
@@ -1642,10 +1624,8 @@
maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramHereIdSent.messageHash()
- && event.outcome().isUntrustedReserveLocation;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramHereIdSent.messageHash()
+ && event.outcome().isUntrustedReserveLocation);
accountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(accountBalance).to.be.equal(0n);
tests/src/xcm/xcmUnique.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmUnique.test.ts
+++ b/tests/src/xcm/xcmUnique.test.ts
@@ -684,10 +684,8 @@
maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramSent.messageHash()
- && event.outcome().isFailedToTransactAsset;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramSent.messageHash()
+ && event.outcome().isFailedToTransactAsset);
targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(targetAccountBalance).to.be.equal(0n);
@@ -767,10 +765,8 @@
maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramFullIdSent.messageHash()
- && event.outcome().isUntrustedReserveLocation;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramFullIdSent.messageHash()
+ && event.outcome().isUntrustedReserveLocation);
let accountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(accountBalance).to.be.equal(0n);
@@ -782,10 +778,8 @@
maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramHereIdSent.messageHash()
- && event.outcome().isUntrustedReserveLocation;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramHereIdSent.messageHash()
+ && event.outcome().isUntrustedReserveLocation);
accountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(accountBalance).to.be.equal(0n);
@@ -860,10 +854,8 @@
});
const expectFailedToTransact = async (helper: DevUniqueHelper, messageSent: any) => {
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == messageSent.messageHash()
- && event.outcome().isFailedToTransactAsset;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == messageSent.messageHash()
+ && event.outcome().isFailedToTransactAsset);
};
itSub('Unique rejects ACA tokens from Acala', async ({helper}) => {
@@ -1175,10 +1167,8 @@
maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramSent.messageHash()
- && event.outcome().isFailedToTransactAsset;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramSent.messageHash()
+ && event.outcome().isFailedToTransactAsset);
targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(targetAccountBalance).to.be.equal(0n);
@@ -1266,10 +1256,8 @@
maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramFullIdSent.messageHash()
- && event.outcome().isUntrustedReserveLocation;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramFullIdSent.messageHash()
+ && event.outcome().isUntrustedReserveLocation);
let accountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(accountBalance).to.be.equal(0n);
@@ -1285,10 +1273,8 @@
maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramHereIdSent.messageHash()
- && event.outcome().isUntrustedReserveLocation;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramHereIdSent.messageHash()
+ && event.outcome().isUntrustedReserveLocation);
accountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(accountBalance).to.be.equal(0n);
@@ -1546,10 +1532,8 @@
maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramSent.messageHash()
- && event.outcome().isFailedToTransactAsset;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramSent.messageHash()
+ && event.outcome().isFailedToTransactAsset);
targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(targetAccountBalance).to.be.equal(0n);
@@ -1629,10 +1613,8 @@
maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramFullIdSent.messageHash()
- && event.outcome().isUntrustedReserveLocation;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramFullIdSent.messageHash()
+ && event.outcome().isUntrustedReserveLocation);
let accountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(accountBalance).to.be.equal(0n);
@@ -1644,10 +1626,8 @@
maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
});
- await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {
- return event.messageHash() == maliciousXcmProgramHereIdSent.messageHash()
- && event.outcome().isUntrustedReserveLocation;
- });
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash() == maliciousXcmProgramHereIdSent.messageHash()
+ && event.outcome().isUntrustedReserveLocation);
accountBalance = await helper.balance.getSubstrate(targetAccount.address);
expect(accountBalance).to.be.equal(0n);