git.delta.rocks / unique-network / refs/commits / 313d9317ef02

difftreelog

test fix integration

Yaroslav Bolyukin2023-05-31parent: #8545aff.patch.diff
in: master

6 files changed

modifiedtests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/contractSponsoring.test.ts
+++ b/tests/src/eth/contractSponsoring.test.ts
@@ -516,7 +516,7 @@
     const owner = await helper.eth.createAccountWithBalance(donor);
     const sponsor = await helper.eth.createAccountWithBalance(donor);
     const user = await helper.eth.createAccountWithBalance(donor);
-    const helpers = await helper.ethNativeContract.contractHelpers(owner);
+    const helpers = helper.ethNativeContract.contractHelpers(owner);
 
     const testContract = await deployTestContract(helper, owner);
 
@@ -531,10 +531,10 @@
     await helpers.methods.setSponsoringFeeLimit(testContract.options.address, 2_000_000n * gasPrice).send();
 
     const originalUserBalance = await helper.balance.getEthereum(user);
-    await testContract.methods.test(100).send({from: user, gas: 2_000_000});
+    await testContract.methods.test(100).send({from: user, gas: 2_000_000, maxFeePerGas: gasPrice.toString()});
     expect(await helper.balance.getEthereum(user)).to.be.equal(originalUserBalance);
 
-    await testContract.methods.test(100).send({from: user, gas: 2_100_000});
+    await testContract.methods.test(100).send({from: user, gas: 2_100_000, maxFeePerGas: gasPrice.toString()});
     expect(await helper.balance.getEthereum(user)).to.not.be.equal(originalUserBalance);
   });
 
modifiedtests/src/eth/ethFeesAreCorrect.test.tsdiffbeforeafterboth
--- a/tests/src/eth/ethFeesAreCorrect.test.ts
+++ b/tests/src/eth/ethFeesAreCorrect.test.ts
@@ -41,10 +41,10 @@
     const {tokenId: tokenB} = await collection.mintToken(minter, {Ethereum: aliceEth});
 
     const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
-    const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
     const balanceBeforeWeb3Transfer = await helper.balance.getEthereum(owner);
-    await contract.methods.transfer(receiver, tokenA).send({from: owner});
+    await contract.methods.transfer(receiver, tokenA).send({from: owner, maxFeePerGas: (await helper.eth.getGasPrice()).toString()});
     const balanceAfterWeb3Transfer = await helper.balance.getEthereum(owner);
     const web3Diff = balanceBeforeWeb3Transfer - balanceAfterWeb3Transfer;
 
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -674,7 +674,7 @@
       requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
 
       donor = await privateKey({url: import.meta.url});
-      [alice] = await helper.arrange.createAccounts([20n], donor);
+      [alice] = await helper.arrange.createAccounts([1000n], donor);
     });
   });
 
@@ -699,7 +699,7 @@
       },
     );
 
-    const contract = await helper.ethNativeContract.collectionById(collection.collectionId, 'rft', caller);
+    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'rft', caller);
     const name = await contract.methods.name().call();
     expect(name).to.equal('Leviathan');
   });
modifiedtests/src/maintenance.seqtest.tsdiffbeforeafterboth
before · tests/src/maintenance.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 {IKeyringPair} from '@polkadot/types/types';18import {ApiPromise} from '@polkadot/api';19import {expect, itSched, itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds} from './util';20import {itEth} from './eth/util';21import {UniqueHelper} from './util/playgrounds/unique';2223async function maintenanceEnabled(api: ApiPromise): Promise<boolean> {24  return (await api.query.maintenance.enabled()).toJSON() as boolean;25}2627describe('Integration Test: Maintenance Functionality', () => {28  let superuser: IKeyringPair;29  let donor: IKeyringPair;30  let bob: IKeyringPair;3132  before(async function() {33    await usingPlaygrounds(async (helper, privateKey) => {34      requirePalletsOrSkip(this, helper, [Pallets.Maintenance]);35      superuser = await privateKey('//Alice');36      donor = await privateKey({url: import.meta.url});37      [bob] = await helper.arrange.createAccounts([10000n], donor);3839    });40  });4142  describe('Maintenance Mode', () => {43    before(async function() {44      await usingPlaygrounds(async (helper) => {45        if (await maintenanceEnabled(helper.getApi())) {46          console.warn('\tMaintenance mode was left enabled BEFORE the test suite! Disabling it now.');47          await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', [])).to.be.fulfilled;48        }49      });50    });5152    itSub('Allows superuser to enable and disable maintenance mode - and disallows anyone else', async ({helper}) => {53      // Make sure non-sudo can't enable maintenance mode54      await expect(helper.executeExtrinsic(superuser, 'api.tx.maintenance.enable', []), 'on commoner enabling MM')55        .to.be.rejectedWith(/BadOrigin/);5657      // Set maintenance mode58      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);59      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;6061      // Make sure non-sudo can't disable maintenance mode62      await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.disable', []), 'on commoner disabling MM')63        .to.be.rejectedWith(/BadOrigin/);6465      // Disable maintenance mode66      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);67      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;68    });6970    itSub('MM blocks unique pallet calls', async ({helper}) => {71      // Can create an NFT collection before enabling the MM72      const nftCollection = await helper.nft.mintCollection(bob, {73        tokenPropertyPermissions: [{74          key: 'test', permission: {75            collectionAdmin: true,76            tokenOwner: true,77            mutable: true,78          },79        }],80      });8182      // Can mint an NFT before enabling the MM83      const nft = await nftCollection.mintToken(bob);8485      // Can create an FT collection before enabling the MM86      const ftCollection = await helper.ft.mintCollection(superuser);8788      // Can mint an FT before enabling the MM89      await expect(ftCollection.mint(superuser)).to.be.fulfilled;9091      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);92      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;9394      // Unable to create a collection when the MM is enabled95      await expect(helper.nft.mintCollection(superuser), 'cudo forbidden stuff')96        .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);9798      // Unable to set token properties when the MM is enabled99      await expect(nft.setProperties(100        bob,101        [{key: 'test', value: 'test-val'}],102      )).to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);103104      // Unable to mint an NFT when the MM is enabled105      await expect(nftCollection.mintToken(superuser))106        .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);107108      // Unable to mint an FT when the MM is enabled109      await expect(ftCollection.mint(superuser))110        .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);111112      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);113      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;114115      // Can create a collection after disabling the MM116      await expect(helper.nft.mintCollection(bob), 'MM is disabled, the collection should be created').to.be.fulfilled;117118      // Can set token properties after disabling the MM119      await nft.setProperties(bob, [{key: 'test', value: 'test-val'}]);120121      // Can mint an NFT after disabling the MM122      await nftCollection.mintToken(bob);123124      // Can mint an FT after disabling the MM125      await ftCollection.mint(superuser);126    });127128    itSub.ifWithPallets('MM blocks unique pallet calls (Re-Fungible)', [Pallets.ReFungible], async ({helper}) => {129      // Can create an RFT collection before enabling the MM130      const rftCollection = await helper.rft.mintCollection(superuser);131132      // Can mint an RFT before enabling the MM133      await expect(rftCollection.mintToken(superuser)).to.be.fulfilled;134135      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);136      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;137138      // Unable to mint an RFT when the MM is enabled139      await expect(rftCollection.mintToken(superuser))140        .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);141142      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);143      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;144145      // Can mint an RFT after disabling the MM146      await rftCollection.mintToken(superuser);147    });148149    itSub('MM allows native token transfers and RPC calls', async ({helper}) => {150      // We can use RPC before the MM is enabled151      const totalCount = await helper.collection.getTotalCount();152153      // We can transfer funds before the MM is enabled154      await expect(helper.balance.transferToSubstrate(superuser, bob.address, 2n)).to.be.fulfilled;155156      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);157      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;158159      // RPCs work while in maintenance160      expect(await helper.collection.getTotalCount()).to.be.deep.equal(totalCount);161162      // We still able to transfer funds163      await expect(helper.balance.transferToSubstrate(bob, superuser.address, 1n)).to.be.fulfilled;164165      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);166      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;167168      // RPCs work after maintenance169      expect(await helper.collection.getTotalCount()).to.be.deep.equal(totalCount);170171      // Transfers work after maintenance172      await expect(helper.balance.transferToSubstrate(bob, superuser.address, 1n)).to.be.fulfilled;173    });174175    itSched.ifWithPallets('MM blocks scheduled calls and the scheduler itself', [Pallets.Scheduler], async (scheduleKind, {helper}) => {176      const collection = await helper.nft.mintCollection(bob);177178      const nftBeforeMM = await collection.mintToken(bob);179      const nftDuringMM = await collection.mintToken(bob);180      const nftAfterMM = await collection.mintToken(bob);181182      const [183        scheduledIdBeforeMM,184        scheduledIdDuringMM,185        scheduledIdBunkerThroughMM,186        scheduledIdAttemptDuringMM,187        scheduledIdAfterMM,188      ] = scheduleKind == 'named'189        ? helper.arrange.makeScheduledIds(5)190        : new Array(5);191192      const blocksToWait = 6;193194      // Scheduling works before the maintenance195      await nftBeforeMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdBeforeMM})196        .transfer(bob, {Substrate: superuser.address});197198      await helper.wait.newBlocks(blocksToWait + 1);199      expect(await nftBeforeMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});200201      // Schedule a transaction that should occur *during* the maintenance202      await nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdDuringMM})203        .transfer(bob, {Substrate: superuser.address});204205      // Schedule a transaction that should occur *after* the maintenance206      await nftDuringMM.scheduleAfter(blocksToWait * 2, {scheduledId: scheduledIdBunkerThroughMM})207        .transfer(bob, {Substrate: superuser.address});208209      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);210      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;211212      await helper.wait.newBlocks(blocksToWait + 1);213      // The owner should NOT change since the scheduled transaction should be rejected214      expect(await nftDuringMM.getOwner()).to.be.deep.equal({Substrate: bob.address});215216      // Any attempts to schedule a tx during the MM should be rejected217      await expect(nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAttemptDuringMM})218        .transfer(bob, {Substrate: superuser.address}))219        .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);220221      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);222      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;223224      // Scheduling works after the maintenance225      await nftAfterMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAfterMM})226        .transfer(bob, {Substrate: superuser.address});227228      await helper.wait.newBlocks(blocksToWait + 1);229230      expect(await nftAfterMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});231      // The owner of the token scheduled for transaction *before* maintenance should now change *after* maintenance232      expect(await nftDuringMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});233    });234235    itEth('Disallows Ethereum transactions to execute while in maintenance', async ({helper}) => {236      const owner = await helper.eth.createAccountWithBalance(donor);237      const receiver = helper.eth.createAccount();238239      const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'A', 'B', 'C', '');240241      // Set maintenance mode242      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);243      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;244245      const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);246      const tokenId = await contract.methods.nextTokenId().call();247      expect(tokenId).to.be.equal('1');248249      await expect(contract.methods.mintWithTokenURI(receiver, 'Test URI').send())250        .to.be.rejectedWith(/Returned error: unknown error/);251252      await expect(contract.methods.ownerOf(tokenId).call()).rejectedWith(/token not found/);253254      // Disable maintenance mode255      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);256      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;257    });258259    itSub('Allows to enable and disable MM repeatedly', async ({helper}) => {260      // Set maintenance mode261      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);262      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);263      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;264265      // Disable maintenance mode266      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);267      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);268      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;269    });270271    afterEach(async () => {272      await usingPlaygrounds(async helper => {273        if (helper.fetchMissingPalletNames([Pallets.Maintenance]).length != 0) return;274        if (await maintenanceEnabled(helper.getApi())) {275          console.warn('\tMaintenance mode was left enabled AFTER a test has finished! Be careful. Disabling it now.');276          await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);277        }278        expect(await maintenanceEnabled(helper.getApi()), 'Disastrous! Exited the test suite with maintenance mode on.').to.be.false;279      });280    });281  });282283  describe('Preimage Execution', () => {284    const preimageHashes: string[] = [];285286    async function notePreimage(helper: UniqueHelper, preimage: any): Promise<string> {287      const result = await helper.preimage.notePreimage(bob, preimage);288      const events = result.result.events.filter(x => x.event.method === 'Noted' && x.event.section === 'preimage');289      const preimageHash = events[0].event.data[0].toHuman();290      return preimageHash;291    }292293    before(async function() {294      await usingPlaygrounds(async (helper) => {295        requirePalletsOrSkip(this, helper, [Pallets.Preimage, Pallets.Maintenance]);296297        // create a preimage to be operated with in the tests298        const randomAccounts = await helper.arrange.createCrowd(10, 0n, superuser);299        const randomIdentities = randomAccounts.map((acc, i) => [300          acc.address, {301            deposit: 0n,302            judgements: [],303            info: {304              display: {305                raw: `Random Account #${i}`,306              },307            },308          },309        ]);310        const preimage = helper.constructApiCall('api.tx.identity.forceInsertIdentities', [randomIdentities]).method.toHex();311        preimageHashes.push(await notePreimage(helper, preimage));312      });313    });314315    itSub('Successfully executes call in a preimage', async ({helper}) => {316      const result = await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [317        preimageHashes[0], {refTime: 10000000000, proofSize: 10000},318      ])).to.be.fulfilled;319320      // preimage is executed, and an appropriate event is present321      const events = result.result.events.filter((x: any) => x.event.method === 'IdentitiesInserted' && x.event.section === 'identity');322      expect(events.length).to.be.equal(1);323324      // the preimage goes back to being unrequested325      expect(await helper.preimage.getPreimageInfo(preimageHashes[0])).to.have.property('unrequested');326    });327328    itSub('Does not allow execution of a preimage that would fail', async ({helper}) => {329      const [zeroAccount] = await helper.arrange.createAccounts([0n], superuser);330331      const preimage = helper.constructApiCall('api.tx.balances.forceTransfer', [332        {Id: zeroAccount.address}, {Id: superuser.address}, 1000n,333      ]).method.toHex();334      const preimageHash = await notePreimage(helper, preimage);335      preimageHashes.push(preimageHash);336337      await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [338        preimageHash, {refTime: 10000000000, proofSize: 10000},339      ])).to.be.rejectedWith(/^Token: FundsUnavailable$/);340    });341342    itSub('Does not allow preimage execution with non-root', async ({helper}) => {343      await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.executePreimage', [344        preimageHashes[0], {refTime: 10000000000, proofSize: 10000},345      ])).to.be.rejectedWith(/BadOrigin/);346    });347348    itSub('Does not allow execution of non-existent preimages', async ({helper}) => {349      await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [350        '0x1010101010101010101010101010101010101010101010101010101010101010', {refTime: 10000000000, proofSize: 10000},351      ])).to.be.rejectedWith(/Unavailable/);352    });353354    itSub('Does not allow preimage execution with less than minimum weights', async ({helper}) => {355      await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [356        preimageHashes[0], {refTime: 1000, proofSize: 100},357      ])).to.be.rejectedWith(/Exhausted/);358    });359360    after(async function() {361      await usingPlaygrounds(async (helper) => {362        if (helper.fetchMissingPalletNames([Pallets.Preimage, Pallets.Maintenance]).length != 0) return;363364        for (const hash of preimageHashes) {365          await helper.preimage.unnotePreimage(bob, hash);366        }367      });368    });369  });370});
modifiedtests/src/pallet-presence.test.tsdiffbeforeafterboth
--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -24,6 +24,7 @@
   'timestamp',
   'transactionpayment',
   'treasury',
+  'statetriemigration',
   'structure',
   'system',
   'vesting',
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -591,8 +591,11 @@
                   const errorMeta = dispatchError.registry.findMetaError(modErr);
 
                   moduleError = `${errorMeta.section}.${errorMeta.name}`;
+                } else if (dispatchError.isToken) {
+                  moduleError = `Token: ${dispatchError.asToken}`;
                 } else {
-                  moduleError = dispatchError.toHuman();
+                  // May be [object Object] in case of unhandled non-unit enum
+                  moduleError = `Misc: ${dispatchError.toHuman()}`;
                 }
               } else {
                 this.logger.log(result, this.logger.level.ERROR);
@@ -3480,6 +3483,8 @@
         } else if (data.asErr.isToken) {
           throw new Error(`Token: ${data.asErr.asToken}`);
         }
+        // May be [object Object] in case of unhandled non-unit enum
+        throw new Error(`Misc: ${data.asErr.toHuman()}`);
       }
       return result;
     }