git.delta.rocks / unique-network / refs/commits / 83c9d6351207

difftreelog

feat speedup inflation pallet

Grigoriy Simonov2023-11-15parent: #aea35c0.patch.diff
in: master

4 files changed

modifiedjs-packages/tests/creditFeesToTreasury.seqtest.tsdiffbeforeafterboth
before · js-packages/tests/creditFeesToTreasury.seqtest.ts
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 type {IKeyringPair} from '@polkadot/types/types';18import {ApiPromise} from '@polkadot/api';19import {usingPlaygrounds, expect, itSub} from './util/index.js';20import type {u32} from '@polkadot/types-codec';2122const TREASURY = '5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z';23const saneMinimumFee = 0.05;24const saneMaximumFee = 0.5;25const createCollectionDeposit = 100;2627// Skip the inflation block pauses if the block is close to inflation block28// until the inflation happens29/*eslint no-async-promise-executor: "off"*/30function skipInflationBlock(api: ApiPromise): Promise<void> {31  const promise = new Promise<void>(async (resolve) => {32    const inflationBlockInterval = api.consts.inflation.inflationBlockInterval as u32;33    const blockInterval = inflationBlockInterval.toNumber();34    const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {35      const currentBlock = head.number.toNumber();36      if(currentBlock % blockInterval < blockInterval - 10) {37        unsubscribe();38        resolve();39      } else {40        console.log(`Skipping inflation block, current block: ${currentBlock}`);41      }42    });43  });4445  return promise;46}4748describe('integration test: Fees must be credited to Treasury:', () => {49  let alice: IKeyringPair;50  let bob: IKeyringPair;5152  before(async () => {53    await usingPlaygrounds(async (helper, privateKey) => {54      const donor = await privateKey({url: import.meta.url});55      [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);56    });57  });5859  itSub('Total issuance does not change', async ({helper}) => {60    const api = helper.getApi();61    await skipInflationBlock(api);62    await helper.wait.newBlocks(1);6364    const totalBefore = (await helper.callRpc('api.query.balances.totalIssuance', [])).toBigInt();6566    await helper.balance.transferToSubstrate(alice, bob.address, 1n);6768    const totalAfter = (await helper.callRpc('api.query.balances.totalIssuance', [])).toBigInt();6970    expect(totalAfter).to.be.equal(totalBefore);71  });7273  itSub('Sender balance decreased by fee+sent amount, Treasury balance increased by fee', async ({helper}) => {74    await skipInflationBlock(helper.getApi());75    await helper.wait.newBlocks(1);7677    const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);78    const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);7980    const amount = 1n;81    await helper.balance.transferToSubstrate(alice, bob.address, amount);8283    const treasuryBalanceAfter = await helper.balance.getSubstrate(TREASURY);84    const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);8586    const fee = aliceBalanceBefore - aliceBalanceAfter - amount;87    const treasuryIncrease = treasuryBalanceAfter - treasuryBalanceBefore;8889    expect(treasuryIncrease).to.be.equal(fee);90  });9192  itSub('Treasury balance increased by failed tx fee', async ({helper}) => {93    const api = helper.getApi();94    await helper.wait.newBlocks(1);9596    const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);97    const bobBalanceBefore = await helper.balance.getSubstrate(bob.address);9899    await expect(helper.signTransaction(bob, api.tx.balances.forceSetBalance(alice.address, 0))).to.be.rejected;100101    const treasuryBalanceAfter = await helper.balance.getSubstrate(TREASURY);102    const bobBalanceAfter = await helper.balance.getSubstrate(bob.address);103104    const fee = bobBalanceBefore - bobBalanceAfter;105    const treasuryIncrease = treasuryBalanceAfter - treasuryBalanceBefore;106107    expect(treasuryIncrease).to.be.equal(fee);108  });109110  itSub('NFT Transactions also send fees to Treasury', async ({helper}) => {111    await skipInflationBlock(helper.getApi());112    await helper.wait.newBlocks(1);113114    const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);115    const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);116117    await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});118119    const treasuryBalanceAfter = await helper.balance.getSubstrate(TREASURY);120    const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);121    const fee = aliceBalanceBefore - aliceBalanceAfter;122    const treasuryIncrease = treasuryBalanceAfter - treasuryBalanceBefore;123124    expect(treasuryIncrease).to.be.equal(fee);125  });126127  itSub('Fees are sane', async ({helper}) => {128    const unique = helper.balance.getOneTokenNominal();129    await skipInflationBlock(helper.getApi());130    await helper.wait.newBlocks(1);131132    const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);133134    await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});135136    const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);137    const fee = aliceBalanceBefore - aliceBalanceAfter;138139    expect(fee / unique < BigInt(Math.ceil(saneMaximumFee + createCollectionDeposit))).to.be.true;140    expect(fee / unique < BigInt(Math.ceil(saneMinimumFee  + createCollectionDeposit))).to.be.true;141  });142143  itSub('NFT Transfer fee is close to 0.1 Unique', async ({helper}) => {144    await skipInflationBlock(helper.getApi());145    await helper.wait.newBlocks(1);146147    const collection = await helper.nft.mintCollection(alice, {148      name: 'test',149      description: 'test',150      tokenPrefix: 'test',151    });152    // const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');153    const token = await collection.mintToken(alice, {Substrate: alice.address});154155    const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);156    await token.transfer(alice, {Substrate: bob.address});157    const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);158159    const fee = Number(aliceBalanceBefore - aliceBalanceAfter) / Number(helper.balance.getOneTokenNominal());160    const expectedTransferFee = 0.1;161    // fee drifts because of NextFeeMultiplier162    const tolerance = 0.001;163164    expect(Math.abs(fee - expectedTransferFee)).to.be.lessThan(tolerance);165  });166});
after · js-packages/tests/creditFeesToTreasury.seqtest.ts
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 type {IKeyringPair} from '@polkadot/types/types';18import {ApiPromise} from '@polkadot/api';19import {usingPlaygrounds, expect, itSub} from './util/index.js';20import type {u32} from '@polkadot/types-codec';2122const TREASURY = '5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z';23const saneMinimumFee = 0.05;24const saneMaximumFee = 0.5;25const createCollectionDeposit = 100;2627// Skip the inflation block pauses if the block is close to inflation block28// until the inflation happens29/*eslint no-async-promise-executor: "off"*/30function skipInflationBlock(api: ApiPromise): Promise<void> {31  const promise = new Promise<void>(async (resolve) => {32    const inflationBlockInterval = api.consts.inflation.inflationBlockInterval as u32;33    const blockInterval = inflationBlockInterval.toNumber();34    const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {35      const currentBlock = head.number.toNumber();36      if(currentBlock % blockInterval < blockInterval - 2) {37        unsubscribe();38        resolve();39      } else {40        console.log(`Skipping inflation block, current block: ${currentBlock}`);41      }42    });43  });4445  return promise;46}4748describe('integration test: Fees must be credited to Treasury:', () => {49  let alice: IKeyringPair;50  let bob: IKeyringPair;5152  before(async () => {53    await usingPlaygrounds(async (helper, privateKey) => {54      const donor = await privateKey({url: import.meta.url});55      [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);56    });57  });5859  itSub('Total issuance does not change', async ({helper}) => {60    const api = helper.getApi();61    await skipInflationBlock(api);62    await helper.wait.newBlocks(1);6364    const totalBefore = (await helper.callRpc('api.query.balances.totalIssuance', [])).toBigInt();6566    await helper.balance.transferToSubstrate(alice, bob.address, 1n);6768    const totalAfter = (await helper.callRpc('api.query.balances.totalIssuance', [])).toBigInt();6970    expect(totalAfter).to.be.equal(totalBefore);71  });7273  itSub('Sender balance decreased by fee+sent amount, Treasury balance increased by fee', async ({helper}) => {74    await skipInflationBlock(helper.getApi());75    await helper.wait.newBlocks(1);7677    const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);78    const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);7980    const amount = 1n;81    await helper.balance.transferToSubstrate(alice, bob.address, amount);8283    const treasuryBalanceAfter = await helper.balance.getSubstrate(TREASURY);84    const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);8586    const fee = aliceBalanceBefore - aliceBalanceAfter - amount;87    const treasuryIncrease = treasuryBalanceAfter - treasuryBalanceBefore;8889    expect(treasuryIncrease).to.be.equal(fee);90  });9192  itSub('Treasury balance increased by failed tx fee', async ({helper}) => {93    const api = helper.getApi();94    await helper.wait.newBlocks(1);9596    const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);97    const bobBalanceBefore = await helper.balance.getSubstrate(bob.address);9899    await expect(helper.signTransaction(bob, api.tx.balances.forceSetBalance(alice.address, 0))).to.be.rejected;100101    const treasuryBalanceAfter = await helper.balance.getSubstrate(TREASURY);102    const bobBalanceAfter = await helper.balance.getSubstrate(bob.address);103104    const fee = bobBalanceBefore - bobBalanceAfter;105    const treasuryIncrease = treasuryBalanceAfter - treasuryBalanceBefore;106107    expect(treasuryIncrease).to.be.equal(fee);108  });109110  itSub('NFT Transactions also send fees to Treasury', async ({helper}) => {111    await skipInflationBlock(helper.getApi());112    await helper.wait.newBlocks(1);113114    const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);115    const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);116117    await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});118119    const treasuryBalanceAfter = await helper.balance.getSubstrate(TREASURY);120    const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);121    const fee = aliceBalanceBefore - aliceBalanceAfter;122    const treasuryIncrease = treasuryBalanceAfter - treasuryBalanceBefore;123124    expect(treasuryIncrease).to.be.equal(fee);125  });126127  itSub('Fees are sane', async ({helper}) => {128    const unique = helper.balance.getOneTokenNominal();129    await skipInflationBlock(helper.getApi());130    await helper.wait.newBlocks(1);131132    const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);133134    await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});135136    const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);137    const fee = aliceBalanceBefore - aliceBalanceAfter;138139    expect(fee / unique < BigInt(Math.ceil(saneMaximumFee + createCollectionDeposit))).to.be.true;140    expect(fee / unique < BigInt(Math.ceil(saneMinimumFee  + createCollectionDeposit))).to.be.true;141  });142143  itSub('NFT Transfer fee is close to 0.1 Unique', async ({helper}) => {144    await skipInflationBlock(helper.getApi());145    await helper.wait.newBlocks(1);146147    const collection = await helper.nft.mintCollection(alice, {148      name: 'test',149      description: 'test',150      tokenPrefix: 'test',151    });152    // const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');153    const token = await collection.mintToken(alice, {Substrate: alice.address});154155    const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);156    await token.transfer(alice, {Substrate: bob.address});157    const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);158159    const fee = Number(aliceBalanceBefore - aliceBalanceAfter) / Number(helper.balance.getOneTokenNominal());160    const expectedTransferFee = 0.1;161    // fee drifts because of NextFeeMultiplier162    const tolerance = 0.001;163164    expect(Math.abs(fee - expectedTransferFee)).to.be.lessThan(tolerance);165  });166});
modifiedjs-packages/tests/inflation.seqtest.tsdiffbeforeafterboth
--- a/js-packages/tests/inflation.seqtest.ts
+++ b/js-packages/tests/inflation.seqtest.ts
@@ -17,6 +17,8 @@
 import type {IKeyringPair} from '@polkadot/types/types';
 import {expect, itSub, usingPlaygrounds} from './util/index.js';
 
+const TREASURY = '5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z';
+
 // todo:playgrounds requires sudo, look into on the later stage
 describe('integration test: Inflation', () => {
   let superuser: IKeyringPair;
@@ -55,4 +57,23 @@
 
     expect(Math.abs(Number(expectedInflation))).to.be.lessThanOrEqual(tolerance);
   });
+
+  itSub('Inflation happens after inflation block interval', async ({helper}) => {
+    const api = helper.getApi();
+    const blockInterval = await api.consts.inflation.inflationBlockInterval.toNumber();
+
+    const relayBlock = (await api.query.parachainSystem.lastRelayChainBlockNumber()).toNumber();
+    await helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [helper.constructApiCall('api.tx.inflation.startInflation', [relayBlock])]);
+    const blockInflation = (await helper.callRpc('api.query.inflation.blockInflation', []) as any).toBigInt();
+    const startBlock = (relayBlock + blockInterval) - (relayBlock % blockInterval) + 1;
+
+    await helper.wait.forRelayBlockNumber(startBlock);
+
+    const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);
+
+    await helper.wait.forRelayBlockNumber(startBlock + blockInterval);
+
+    const treasuryBalanceAfter = await helper.balance.getSubstrate(TREASURY);
+    expect(Number(treasuryBalanceAfter)).to.be.eqls(Number(treasuryBalanceBefore + blockInflation));
+  });
 });
modifiedpallets/inflation/src/tests.rsdiffbeforeafterboth
--- a/pallets/inflation/src/tests.rs
+++ b/pallets/inflation/src/tests.rs
@@ -106,7 +106,7 @@
 
 parameter_types! {
 	pub TreasuryAccountId: u64 = 1234;
-	pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied
+	pub const InflationBlockInterval: u32 = 10; // every time per how many blocks inflation is applied
 	pub static MockBlockNumberProvider: u32 = 0;
 }
 
modifiedruntime/common/config/pallets/mod.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -102,7 +102,7 @@
 }
 
 parameter_types! {
-	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied
+	pub const InflationBlockInterval: BlockNumber = 10; // every time per how many blocks inflation is applied
 }
 
 /// Pallet-inflation needs block number in on_initialize, where there is no `validation_data` exists yet