git.delta.rocks / unique-network / refs/commits / 32f66f7e1404

difftreelog

Merge pull request #1017 from UniqueNetwork/feature/speedup-inflation-pallet

Yaroslav Bolyukin2023-11-16parents: #aea35c0 #cc9eeb2.patch.diff
in: master

11 files changed

modified.docker/Dockerfile-chain-devdiffbeforeafterboth
--- a/.docker/Dockerfile-chain-dev
+++ b/.docker/Dockerfile-chain-dev
@@ -21,7 +21,7 @@
 
 WORKDIR /dev_chain
 
-RUN cargo build --profile integration-tests --features=${NETWORK}-runtime
+RUN cargo build --profile integration-tests --features=${NETWORK}-runtime,fast-inflation
 RUN echo "$NETWORK"
 
-CMD cargo run --profile integration-tests --features=${NETWORK}-runtime -- --dev -linfo --rpc-cors=all --unsafe-rpc-external
+CMD cargo run --profile integration-tests --features=${NETWORK}-runtime,fast-inflation -- --dev -linfo --rpc-cors=all --unsafe-rpc-external
modified.docker/Dockerfile-uniquediffbeforeafterboth
--- a/.docker/Dockerfile-unique
+++ b/.docker/Dockerfile-unique
@@ -47,7 +47,7 @@
     --mount=type=cache,target=/unique_parachain/unique-chain/target \
     cd unique-chain && \
     echo "Using runtime features '$RUNTIME_FEATURES'" && \
-    CARGO_INCREMENTAL=0 cargo build --profile integration-tests --features="$RUNTIME_FEATURES" --locked && \
+    CARGO_INCREMENTAL=0 cargo build --profile integration-tests --features=fast-inflation,"$RUNTIME_FEATURES" --locked && \
     mv ./target/integration-tests/unique-collator /unique_parachain/unique-chain/ && \
     cd target/integration-tests/wbuild && find . -name "*.wasm" -exec sh -c 'mkdir -p "../../../wasm/$(dirname {})"; cp {} "../../../wasm/{}"' \;
 
modified.docker/docker-compose.gov.j2diffbeforeafterboth
--- a/.docker/docker-compose.gov.j2
+++ b/.docker/docker-compose.gov.j2
@@ -21,4 +21,4 @@
       options:
         max-size: "1m"
         max-file: "3"
-    command: cargo run --profile integration-tests --features={{ NETWORK }}-runtime,gov-test-timings -- --dev -linfo --rpc-cors=all --unsafe-rpc-external
+    command: cargo run --profile integration-tests --features={{ NETWORK }}-runtime,gov-test-timings,fast-inflation -- --dev -linfo --rpc-cors=all --unsafe-rpc-external
modifiedjs-packages/tests/creditFeesToTreasury.seqtest.tsdiffbeforeafterboth
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 - (blockInterval / 5)) {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/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/js-packages/tests/eth/util/playgrounds/unique.dev.ts
+++ b/js-packages/tests/eth/util/playgrounds/unique.dev.ts
@@ -460,7 +460,7 @@
 
   fromCollectionId(collectionId: number): string {
     if(collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');
-    return (web3 as any).utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);
+    return web3.default.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);
   }
 
   extractTokenId(address: string): { collectionId: number, tokenId: number } {
@@ -590,8 +590,8 @@
 
   connectWeb3(wsEndpoint: string) {
     if(this.web3 !== null) return;
-    this.web3Provider = new (web3 as any).providers.WebsocketProvider(wsEndpoint);
-    this.web3 = new (web3 as any)(this.web3Provider);
+    this.web3Provider = new web3.default.providers.WebsocketProvider(wsEndpoint);
+    this.web3 = new web3.default(this.web3Provider);
   }
 
   override async disconnect() {
modifiedjs-packages/tests/inflation.seqtest.tsdiffbeforeafterboth
--- a/js-packages/tests/inflation.seqtest.ts
+++ b/js-packages/tests/inflation.seqtest.ts
@@ -17,13 +17,19 @@
 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;
 
   before(async () => {
-    await usingPlaygrounds(async (_, privateKey) => {
+    await usingPlaygrounds(async (helper, privateKey) => {
       superuser = await privateKey('//Alice');
+      const api = helper.getApi();
+
+      const relayBlock = (await api.query.parachainSystem.lastRelayChainBlockNumber()).toNumber();
+      await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [helper.constructApiCall('api.tx.inflation.startInflation', [relayBlock])])).to.not.be.rejected;
     });
   });
 
@@ -36,10 +42,6 @@
     // Make sure superuser can't start inflation without explicit sudo
     await expect(helper.executeExtrinsic(superuser, 'api.tx.inflation.startInflation', [1])).to.be.rejectedWith(/BadOrigin/);
 
-    // Start inflation on relay block 1 (Alice is sudo)
-    const tx = helper.constructApiCall('api.tx.inflation.startInflation', [1]);
-    await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [tx])).to.not.be.rejected;
-
     const blockInterval = (helper.getApi().consts.inflation.inflationBlockInterval as any).toBigInt();
     const totalIssuanceStart = ((await helper.callRpc('api.query.inflation.startingYearTotalIssuance', [])) as any).toBigInt();
     const blockInflation = (await helper.callRpc('api.query.inflation.blockInflation', []) as any).toBigInt();
@@ -55,4 +57,22 @@
 
     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();
+    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 + 1);
+
+    const treasuryBalanceAfter = await helper.balance.getSubstrate(TREASURY);
+    expect(Number(treasuryBalanceAfter)).to.be.eqls(Number(treasuryBalanceBefore + blockInflation));
+  });
 });
modifiedpallets/inflation/Cargo.tomldiffbeforeafterboth
--- a/pallets/inflation/Cargo.toml
+++ b/pallets/inflation/Cargo.toml
@@ -27,6 +27,7 @@
 	'sp-std/std',
 ]
 try-runtime = ["frame-support/try-runtime"]
+fast-inflation = []
 
 [dependencies]
 parity-scale-codec = { workspace = true }
modifiedruntime/common/config/pallets/mod.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -101,8 +101,14 @@
 	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;
 }
 
+// every time per how many blocks inflation is applied
+#[cfg(feature = "fast-inflation")]
+parameter_types! {
+	pub const InflationBlockInterval: BlockNumber = 10;
+}
+#[cfg(not(feature = "fast-inflation"))]
 parameter_types! {
-	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied
+	pub const InflationBlockInterval: BlockNumber = 100;
 }
 
 /// Pallet-inflation needs block number in on_initialize, where there is no `validation_data` exists yet
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -232,6 +232,7 @@
 preimage = []
 refungible = []
 session-test-timings = []
+fast-inflation = []
 
 ################################################################################
 # local dependencies
modifiedruntime/quartz/Cargo.tomldiffbeforeafterboth
--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -221,6 +221,7 @@
 preimage = []
 refungible = []
 session-test-timings = []
+fast-inflation = []
 
 ################################################################################
 # local dependencies
modifiedruntime/unique/Cargo.tomldiffbeforeafterboth
--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -224,6 +224,7 @@
 preimage = []
 refungible = []
 session-test-timings = []
+fast-inflation = []
 
 ################################################################################
 # local dependencies