git.delta.rocks / unique-network / refs/commits / 56575de5acb6

difftreelog

refactor Rename module in extrinsic

Trubnikov Sergey2022-09-02parent: #5b36ad8.patch.diff
in: master

13 files changed

modifiedprimitives/app_promotion_rpc/src/lib.rsdiffbeforeafterboth
--- a/primitives/app_promotion_rpc/src/lib.rs
+++ b/primitives/app_promotion_rpc/src/lib.rs
@@ -16,11 +16,6 @@
 
 #![cfg_attr(not(feature = "std"), no_std)]
 
-use up_data_structs::{
-	CollectionId, TokenId, RpcCollection, CollectionStats, CollectionLimits, Property,
-	PropertyKeyPermission, TokenData, TokenChild,
-};
-
 use sp_std::vec::Vec;
 use codec::Decode;
 use sp_runtime::{
modifiedruntime/common/construct_runtime/mod.rsdiffbeforeafterboth
--- a/runtime/common/construct_runtime/mod.rs
+++ b/runtime/common/construct_runtime/mod.rs
@@ -78,7 +78,7 @@
                 RmrkEquip: pallet_proxy_rmrk_equip::{Pallet, Call, Storage, Event<T>} = 72,
 
                 #[runtimes(opal)]
-                Promotion: pallet_app_promotion::{Pallet, Call, Storage, Event<T>} = 73,
+                AppPromotion: pallet_app_promotion::{Pallet, Call, Storage, Event<T>} = 73,
 
                 // Frontier
                 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,
modifiedtests/src/app-promotion.test.tsdiffbeforeafterboth
--- a/tests/src/app-promotion.test.ts
+++ b/tests/src/app-promotion.test.ts
@@ -38,29 +38,20 @@
 const palletAddress = calculatePalleteAddress('appstake');
 let accounts: IKeyringPair[] = [];
 
-before(async function () {
-  await usingPlaygrounds(async (helper, privateKeyWrapper) => {
-    if (!getModuleNames(helper.api!).includes(Pallets.AppPromotion)) this.skip();
-    alice = privateKeyWrapper('//Alice');
-    palletAdmin = privateKeyWrapper('//Charlie'); // TODO use custom address
-    await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Substrate: palletAdmin.address})));
-    nominal = helper.balance.getOneTokenNominal();
-    await helper.balance.transferToSubstrate(alice, palletAdmin.address, 1000n * nominal);
-    await helper.balance.transferToSubstrate(alice, palletAddress, 1000n * nominal);
-    if (!promotionStartBlock) {
-      promotionStartBlock = (await helper.api!.query.parachainSystem.lastRelayChainBlockNumber()).toNumber();
-    }
-    await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.startAppPromotion(promotionStartBlock!)));
-    accounts = await helper.arrange.createCrowd(100, 1000n, alice); // create accounts-pool to speed up tests
-  });
-});
-
-after(async function () {
-  await usingPlaygrounds(async (helper) => {
+describe('app-promotions.stake extrinsic', () => {
+  before(async function () {
+    await usingPlaygrounds(async (helper, privateKeyWrapper) => {
+      if (!getModuleNames(helper.api!).includes(Pallets.AppPromotion)) this.skip();
+      alice = privateKeyWrapper('//Alice');
+      palletAdmin = privateKeyWrapper('//Charlie'); // TODO use custom address
+      await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
+      nominal = helper.balance.getOneTokenNominal();
+      await helper.balance.transferToSubstrate(alice, palletAdmin.address, 1000n * nominal);
+      await helper.balance.transferToSubstrate(alice, palletAddress, 1000n * nominal);
+      accounts = await helper.arrange.createCrowd(100, 1000n, alice); // create accounts-pool to speed up tests
+    });
   });
-});
 
-describe('app-promotions.stake extrinsic', () => {
   it('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async () => {
     await usingPlaygrounds(async (helper) => {
       const [staker, recepient] = [accounts.pop()!, accounts.pop()!];
@@ -264,11 +255,11 @@
     await usingPlaygrounds(async (helper) => {
       const nonAdmin = accounts.pop()!;
       // nonAdmin can not set admin not from himself nor as a sudo
-      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.eventually.rejected;
-      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.eventually.rejected;
+      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.eventually.rejected;
+      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.eventually.rejected;
 
       // Alice can
-      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.eventually.fulfilled;
+      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.eventually.fulfilled;
     });
   });
   
@@ -279,12 +270,12 @@
       const account = accounts.pop()!;
       const ethAccount = helper.address.substrateToEth(account.address); 
       // Alice sets Ethereum address as a sudo. Then Substrate address back...
-      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Ethereum: ethAccount})))).to.be.eventually.fulfilled;
-      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.eventually.fulfilled;
+      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.eventually.fulfilled;
+      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.eventually.fulfilled;
       
       // ...It doesn't break anything;
       const collection = await helper.nft.mintCollection(account, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
-      await expect(helper.signTransaction(account, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;
+      await expect(helper.signTransaction(account, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;
     });
   });
 
@@ -293,11 +284,11 @@
       const [oldAdmin, newAdmin, collectionOwner] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
       const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
       
-      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress(normalizeAccountId(oldAdmin))))).to.be.eventually.fulfilled;
-      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress(normalizeAccountId(newAdmin))))).to.be.eventually.fulfilled;
-      await expect(helper.signTransaction(oldAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;
+      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(oldAdmin))))).to.be.eventually.fulfilled;
+      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(newAdmin))))).to.be.eventually.fulfilled;
+      await expect(helper.signTransaction(oldAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;
       
-      await expect(helper.signTransaction(newAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.fulfilled;
+      await expect(helper.signTransaction(newAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.fulfilled;
     });
   });
 });
@@ -305,7 +296,7 @@
 describe('App-promotion collection sponsoring', () => {
   before(async function () {
     await usingPlaygrounds(async (helper) => {
-      const tx = helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Substrate: palletAdmin.address}));
+      const tx = helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address}));
       await helper.signTransaction(alice, tx);
     });
   });
@@ -315,7 +306,7 @@
       const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
       const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});
       const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});
-      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId));
+      await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));
       const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);
 
       await token.transfer(tokenSender, {Substrate: receiver.address});
@@ -334,7 +325,7 @@
 
       const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
       
-      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;
+      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;
       expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');
     });
   });
@@ -345,19 +336,19 @@
       
       // Can set sponsoring for collection without sponsor
       const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});
-      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.eventually.fulfilled;
+      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.eventually.fulfilled;
       expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
 
       // Can set sponsoring for collection with unconfirmed sponsor
       const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
       expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});
-      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.eventually.fulfilled;
+      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.eventually.fulfilled;
       expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
 
       // Can set sponsoring for collection with confirmed sponsor
       const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
       await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);
-      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.eventually.fulfilled;
+      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.eventually.fulfilled;
       expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
     });
   });
@@ -368,7 +359,7 @@
       const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
       const collectionId = collection.collectionId;
       
-      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collectionId))).to.be.eventually.fulfilled;
+      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionId))).to.be.eventually.fulfilled;
       
       // Collection limits still can be changed by the owner
       expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;
@@ -386,7 +377,7 @@
       const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};
       const collectionWithLimits = await helper.nft.mintCollection(alice, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});
 
-      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.eventually.fulfilled;
+      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.eventually.fulfilled;
       expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);
     });
   });
@@ -396,12 +387,12 @@
       const collectionOwner = accounts.pop()!;
       
       // collection has never existed
-      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(999999999))).to.be.eventually.rejected;
+      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(999999999))).to.be.eventually.rejected;
       // collection has been burned
       const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
       await collection.burn(collectionOwner);
 
-      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;
+      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;
     });
   });
 });
@@ -412,9 +403,9 @@
       const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];
       const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
       
-      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.fulfilled;
+      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.fulfilled;
       
-      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;
+      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;
       expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
     });
   });
@@ -425,8 +416,8 @@
       const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});
       const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});
       
-      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId));
-      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.stopSponsoringCollection(collection.collectionId));
+      await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));
+      await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId));
       
       expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');
 
@@ -444,7 +435,7 @@
       const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});
       await collection.confirmSponsorship(collectionOwner);
       
-      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;
+      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;
       
       expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});
     });
@@ -456,8 +447,8 @@
       const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
       
       await collection.burn(collectionOwner);
-      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;
-      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.stopSponsoringCollection(999999999))).to.be.eventually.rejected;
+      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;
+      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(999999999))).to.be.eventually.rejected;
     });
   });
 });
@@ -469,7 +460,7 @@
       const flipper = await deployFlipper(web3, contractOwner);
       const contractMethods = contractHelpers(web3, contractOwner);
 
-      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));
+      await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorConract(flipper.options.address));
       
       expect(await contractMethods.methods.hasSponsor(flipper.options.address).call()).to.be.true;  
       expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);  
@@ -497,7 +488,7 @@
       });
 
       // set promotion sponsoring
-      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));
+      await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorConract(flipper.options.address));
 
       // new sponsor is pallet address
       expect(await contractMethods.methods.hasSponsor(flipper.options.address).call()).to.be.true;  
@@ -517,7 +508,7 @@
       const contractMethods = contractHelpers(web3, contractOwner);
 
       // contract sponsored by pallet
-      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));
+      await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorConract(flipper.options.address));
 
       // owner sets self sponsoring
       await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
@@ -542,7 +533,7 @@
       await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
 
       // nonAdmin calls sponsorConract
-      await expect(helper.signTransaction(nonAdmin, api.tx.promotion.sponsorConract(flipper.options.address))).to.be.rejected;
+      await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorConract(flipper.options.address))).to.be.rejected;
 
       // contract still self-sponsored 
       expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
@@ -569,7 +560,7 @@
       await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});
       await transferBalanceToEth(api, alice, flipper.options.address, 1000n);
 
-      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));
+      await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorConract(flipper.options.address));
       await flipper.methods.flip().send({from: caller});
       expect(await flipper.methods.getValue().call()).to.be.true;
 
@@ -591,8 +582,8 @@
       await transferBalanceToEth(api, alice, flipper.options.address);
       const contractHelper = contractHelpers(web3, contractOwner);
       await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});
-      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));
-      await helper.signTransaction(palletAdmin, api.tx.promotion.stopSponsoringContract(flipper.options.address));
+      await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorConract(flipper.options.address));
+      await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringContract(flipper.options.address));
 
       expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;  
       expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);  
@@ -618,8 +609,8 @@
       const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
       const flipper = await deployFlipper(web3, contractOwner);
 
-      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));
-      await expect(helper.signTransaction(nonAdmin, api.tx.promotion.stopSponsoringContract(flipper.options.address))).to.be.rejected;
+      await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorConract(flipper.options.address));
+      await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringContract(flipper.options.address))).to.be.rejected;
     });
   });
 
@@ -631,7 +622,7 @@
       const contractHelper = contractHelpers(web3, contractOwner);
       await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
 
-      await expect(helper.signTransaction(nonAdmin, api.tx.promotion.stopSponsoringContract(flipper.options.address))).to.be.rejected;
+      await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringContract(flipper.options.address))).to.be.rejected;
     });
   });
 });
@@ -640,7 +631,7 @@
   it('can not be called by non admin', async () => {
     await usingPlaygrounds(async (helper) => {
       const nonAdmin = accounts.pop()!;
-      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.payoutStakers(100))).to.be.rejected;
+      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.payoutStakers(100))).to.be.rejected;
     });
   });
 
@@ -652,7 +643,7 @@
       await helper.staking.stake(staker, 100n * nominal);
       await helper.staking.stake(staker, 200n * nominal);
       await waitForRelayBlock(helper.api!, 30);
-      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(100));
+      await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
 
       const totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);
       expect(totalStakedPerBlock).to.be.deep.equal([calculateIncome(100n * nominal, 10n), calculateIncome(200n * nominal, 10n)]);
@@ -668,7 +659,7 @@
       await helper.staking.stake(staker, 200n * nominal);
 
       await waitForRelayBlock(helper.api!, 55);
-      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(100));
+      await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
       const stakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
       expect(stakedPerBlock[0][1]).to.be.equal(calculateIncome(100n * nominal, 10n, 2));
       expect(stakedPerBlock[1][1]).to.be.equal(calculateIncome(200n * nominal, 10n, 2));
@@ -707,12 +698,12 @@
       await helper.staking.stake(staker, 300n * nominal);
       
       await waitForRelayBlock(helper.api!, 34);
-      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(100));
+      await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
       let totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);
       expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n), calculateIncome(200n * nominal, 10n), calculateIncome(300n * nominal, 10n)]);
       
       await waitForRelayBlock(helper.api!, 20);
-      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(100));
+      await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
       totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);
       expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n, 2), calculateIncome(200n * nominal, 10n, 2), calculateIncome(300n * nominal, 10n, 2)]);      
     });
modifiedtests/src/interfaces/augment-api-consts.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-consts.ts
+++ b/tests/src/interfaces/augment-api-consts.ts
@@ -15,6 +15,30 @@
 
 declare module '@polkadot/api-base/types/consts' {
   interface AugmentedConsts<ApiType extends ApiTypes> {
+    appPromotion: {
+      /**
+       * In chain blocks.
+       **/
+      day: u32 & AugmentedConst<ApiType>;
+      intervalIncome: Perbill & AugmentedConst<ApiType>;
+      nominal: u128 & AugmentedConst<ApiType>;
+      /**
+       * The app's pallet id, used for deriving its sovereign account ID.
+       **/
+      palletId: FrameSupportPalletId & AugmentedConst<ApiType>;
+      /**
+       * In relay blocks.
+       **/
+      pendingInterval: u32 & AugmentedConst<ApiType>;
+      /**
+       * In relay blocks.
+       **/
+      recalculationInterval: u32 & AugmentedConst<ApiType>;
+      /**
+       * Generic const
+       **/
+      [key: string]: Codec;
+    };
     balances: {
       /**
        * The minimum amount required to keep an account open.
@@ -61,30 +85,6 @@
        * Number of blocks that pass between treasury balance updates due to inflation
        **/
       inflationBlockInterval: u32 & AugmentedConst<ApiType>;
-      /**
-       * Generic const
-       **/
-      [key: string]: Codec;
-    };
-    promotion: {
-      /**
-       * In chain blocks.
-       **/
-      day: u32 & AugmentedConst<ApiType>;
-      intervalIncome: Perbill & AugmentedConst<ApiType>;
-      nominal: u128 & AugmentedConst<ApiType>;
-      /**
-       * The app's pallet id, used for deriving its sovereign account ID.
-       **/
-      palletId: FrameSupportPalletId & AugmentedConst<ApiType>;
-      /**
-       * In relay blocks.
-       **/
-      pendingInterval: u32 & AugmentedConst<ApiType>;
-      /**
-       * In relay blocks.
-       **/
-      recalculationInterval: u32 & AugmentedConst<ApiType>;
       /**
        * Generic const
        **/
modifiedtests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -11,6 +11,29 @@
 
 declare module '@polkadot/api-base/types/errors' {
   interface AugmentedErrors<ApiType extends ApiTypes> {
+    appPromotion: {
+      /**
+       * Error due to action requiring admin to be set
+       **/
+      AdminNotSet: AugmentedError<ApiType>;
+      /**
+       * An error related to the fact that an invalid argument was passed to perform an action
+       **/
+      InvalidArgument: AugmentedError<ApiType>;
+      /**
+       * No permission to perform an action
+       **/
+      NoPermission: AugmentedError<ApiType>;
+      /**
+       * Insufficient funds to perform an action
+       **/
+      NotSufficientFounds: AugmentedError<ApiType>;
+      PendingForBlockOverflow: AugmentedError<ApiType>;
+      /**
+       * Generic error
+       **/
+      [key: string]: AugmentedError<ApiType>;
+    };
     balances: {
       /**
        * Beneficiary account must pre-exist
@@ -430,28 +453,6 @@
        * The message's weight could not be determined.
        **/
       UnweighableMessage: AugmentedError<ApiType>;
-      /**
-       * Generic error
-       **/
-      [key: string]: AugmentedError<ApiType>;
-    };
-    promotion: {
-      /**
-       * Error due to action requiring admin to be set
-       **/
-      AdminNotSet: AugmentedError<ApiType>;
-      /**
-       * An error related to the fact that an invalid argument was passed to perform an action
-       **/
-      InvalidArgument: AugmentedError<ApiType>;
-      /**
-       * No permission to perform an action
-       **/
-      NoPermission: AugmentedError<ApiType>;
-      /**
-       * Insufficient funds to perform an action
-       **/
-      NotSufficientFounds: AugmentedError<ApiType>;
       /**
        * Generic error
        **/
modifiedtests/src/interfaces/augment-api-events.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-events.ts
+++ b/tests/src/interfaces/augment-api-events.ts
@@ -15,6 +15,13 @@
 
 declare module '@polkadot/api-base/types/events' {
   interface AugmentedEvents<ApiType extends ApiTypes> {
+    appPromotion: {
+      StakingRecalculation: AugmentedEvent<ApiType, [AccountId32, u128, u128]>;
+      /**
+       * Generic event
+       **/
+      [key: string]: AugmentedEvent<ApiType>;
+    };
     balances: {
       /**
        * A balance was set by root.
@@ -355,13 +362,6 @@
        * \[ destination, result \]
        **/
       VersionChangeNotified: AugmentedEvent<ApiType, [XcmV1MultiLocation, u32]>;
-      /**
-       * Generic event
-       **/
-      [key: string]: AugmentedEvent<ApiType>;
-    };
-    promotion: {
-      StakingRecalculation: AugmentedEvent<ApiType, [AccountId32, u128, u128]>;
       /**
        * Generic event
        **/
modifiedtests/src/interfaces/augment-api-query.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-query.ts
+++ b/tests/src/interfaces/augment-api-query.ts
@@ -17,6 +17,35 @@
 
 declare module '@polkadot/api-base/types/storage' {
   interface AugmentedQueries<ApiType extends ApiTypes> {
+    appPromotion: {
+      admin: AugmentedQuery<ApiType, () => Observable<Option<AccountId32>>, []> & QueryableStorageEntry<ApiType, []>;
+      /**
+       * Stores hash a record for which the last revenue recalculation was performed.
+       * If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.
+       **/
+      nextCalculatedRecord: AugmentedQuery<ApiType, () => Observable<Option<ITuple<[AccountId32, u32]>>>, []> & QueryableStorageEntry<ApiType, []>;
+      /**
+       * Amount of tokens pending unstake per user per block.
+       **/
+      pendingUnstake: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Vec<ITuple<[AccountId32, u128]>>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
+      /**
+       * Amount of tokens staked by account in the blocknumber.
+       **/
+      staked: AugmentedQuery<ApiType, (arg1: AccountId32 | string | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<ITuple<[u128, u32]>>, [AccountId32, u32]> & QueryableStorageEntry<ApiType, [AccountId32, u32]>;
+      /**
+       * Amount of stakes for an Account
+       **/
+      stakesPerAccount: AugmentedQuery<ApiType, (arg: AccountId32 | string | Uint8Array) => Observable<u8>, [AccountId32]> & QueryableStorageEntry<ApiType, [AccountId32]>;
+      /**
+       * A block when app-promotion has started .I think this is redundant, because we only need `NextInterestBlock`.
+       **/
+      startBlock: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
+      totalStaked: AugmentedQuery<ApiType, () => Observable<u128>, []> & QueryableStorageEntry<ApiType, []>;
+      /**
+       * Generic query
+       **/
+      [key: string]: QueryableStorageEntry<ApiType>;
+    };
     balances: {
       /**
        * The Balances pallet example of storing the balance of an account.
@@ -505,39 +534,6 @@
        * in the trie.
        **/
       validationData: AugmentedQuery<ApiType, () => Observable<Option<PolkadotPrimitivesV2PersistedValidationData>>, []> & QueryableStorageEntry<ApiType, []>;
-      /**
-       * Generic query
-       **/
-      [key: string]: QueryableStorageEntry<ApiType>;
-    };
-    promotion: {
-      admin: AugmentedQuery<ApiType, () => Observable<Option<AccountId32>>, []> & QueryableStorageEntry<ApiType, []>;
-      /**
-       * Stores hash a record for which the last revenue recalculation was performed.
-       * If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.
-       **/
-      nextCalculatedRecord: AugmentedQuery<ApiType, () => Observable<Option<ITuple<[AccountId32, u32]>>>, []> & QueryableStorageEntry<ApiType, []>;
-      /**
-       * Next target block when interest is recalculated
-       **/
-      nextInterestBlock: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
-      /**
-       * Amount of tokens pending unstake per user per block.
-       **/
-      pendingUnstake: AugmentedQuery<ApiType, (arg1: AccountId32 | string | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<u128>, [AccountId32, u32]> & QueryableStorageEntry<ApiType, [AccountId32, u32]>;
-      /**
-       * Amount of tokens staked by account in the blocknumber.
-       **/
-      staked: AugmentedQuery<ApiType, (arg1: AccountId32 | string | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<ITuple<[u128, u32]>>, [AccountId32, u32]> & QueryableStorageEntry<ApiType, [AccountId32, u32]>;
-      /**
-       * Amount of stakes for an Account
-       **/
-      stakesPerAccount: AugmentedQuery<ApiType, (arg: AccountId32 | string | Uint8Array) => Observable<u8>, [AccountId32]> & QueryableStorageEntry<ApiType, [AccountId32]>;
-      /**
-       * A block when app-promotion has started .I think this is redundant, because we only need `NextInterestBlock`.
-       **/
-      startBlock: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
-      totalStaked: AugmentedQuery<ApiType, () => Observable<u128>, []> & QueryableStorageEntry<ApiType, []>;
       /**
        * Generic query
        **/
modifiedtests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -17,6 +17,20 @@
 
 declare module '@polkadot/api-base/types/submittable' {
   interface AugmentedSubmittables<ApiType extends ApiTypes> {
+    appPromotion: {
+      payoutStakers: AugmentedSubmittable<(stakersNumber: Option<u8> | null | Uint8Array | u8 | AnyNumber) => SubmittableExtrinsic<ApiType>, [Option<u8>]>;
+      setAdminAddress: AugmentedSubmittable<(admin: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletEvmAccountBasicCrossAccountIdRepr]>;
+      sponsorCollection: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32]>;
+      sponsorConract: AugmentedSubmittable<(contractId: H160 | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [H160]>;
+      stake: AugmentedSubmittable<(amount: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u128]>;
+      stopSponsoringCollection: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32]>;
+      stopSponsoringContract: AugmentedSubmittable<(contractId: H160 | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [H160]>;
+      unstake: AugmentedSubmittable<() => SubmittableExtrinsic<ApiType>, []>;
+      /**
+       * Generic tx
+       **/
+      [key: string]: SubmittableExtrinsicFunction<ApiType>;
+    };
     balances: {
       /**
        * Exactly as `transfer`, except the origin must be root and the source account may be
@@ -370,22 +384,6 @@
        * fees.
        **/
       teleportAssets: AugmentedSubmittable<(dest: XcmVersionedMultiLocation | { V0: any } | { V1: any } | string | Uint8Array, beneficiary: XcmVersionedMultiLocation | { V0: any } | { V1: any } | string | Uint8Array, assets: XcmVersionedMultiAssets | { V0: any } | { V1: any } | string | Uint8Array, feeAssetItem: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [XcmVersionedMultiLocation, XcmVersionedMultiLocation, XcmVersionedMultiAssets, u32]>;
-      /**
-       * Generic tx
-       **/
-      [key: string]: SubmittableExtrinsicFunction<ApiType>;
-    };
-    promotion: {
-      payoutStakers: AugmentedSubmittable<(stakersNumber: Option<u8> | null | Uint8Array | u8 | AnyNumber) => SubmittableExtrinsic<ApiType>, [Option<u8>]>;
-      setAdminAddress: AugmentedSubmittable<(admin: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletEvmAccountBasicCrossAccountIdRepr]>;
-      sponsorCollection: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32]>;
-      sponsorConract: AugmentedSubmittable<(contractId: H160 | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [H160]>;
-      stake: AugmentedSubmittable<(amount: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u128]>;
-      startAppPromotion: AugmentedSubmittable<(promotionStartRelayBlock: Option<u32> | null | Uint8Array | u32 | AnyNumber) => SubmittableExtrinsic<ApiType>, [Option<u32>]>;
-      stopAppPromotion: AugmentedSubmittable<() => SubmittableExtrinsic<ApiType>, []>;
-      stopSponsoringCollection: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32]>;
-      stopSponsoringContract: AugmentedSubmittable<(contractId: H160 | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [H160]>;
-      unstake: AugmentedSubmittable<() => SubmittableExtrinsic<ApiType>, []>;
       /**
        * Generic tx
        **/
modifiedtests/src/interfaces/default/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -812,11 +812,6 @@
   readonly asSetAdminAddress: {
     readonly admin: PalletEvmAccountBasicCrossAccountIdRepr;
   } & Struct;
-  readonly isStartAppPromotion: boolean;
-  readonly asStartAppPromotion: {
-    readonly promotionStartRelayBlock: Option<u32>;
-  } & Struct;
-  readonly isStopAppPromotion: boolean;
   readonly isStake: boolean;
   readonly asStake: {
     readonly amount: u128;
@@ -842,7 +837,7 @@
   readonly asPayoutStakers: {
     readonly stakersNumber: Option<u8>;
   } & Struct;
-  readonly type: 'SetAdminAddress' | 'StartAppPromotion' | 'StopAppPromotion' | 'Stake' | 'Unstake' | 'SponsorCollection' | 'StopSponsoringCollection' | 'SponsorConract' | 'StopSponsoringContract' | 'PayoutStakers';
+  readonly type: 'SetAdminAddress' | 'Stake' | 'Unstake' | 'SponsorCollection' | 'StopSponsoringCollection' | 'SponsorConract' | 'StopSponsoringContract' | 'PayoutStakers';
 }
 
 /** @name PalletAppPromotionError */
@@ -850,8 +845,9 @@
   readonly isAdminNotSet: boolean;
   readonly isNoPermission: boolean;
   readonly isNotSufficientFounds: boolean;
+  readonly isPendingForBlockOverflow: boolean;
   readonly isInvalidArgument: boolean;
-  readonly type: 'AdminNotSet' | 'NoPermission' | 'NotSufficientFounds' | 'InvalidArgument';
+  readonly type: 'AdminNotSet' | 'NoPermission' | 'NotSufficientFounds' | 'PendingForBlockOverflow' | 'InvalidArgument';
 }
 
 /** @name PalletAppPromotionEvent */
modifiedtests/src/interfaces/lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -2460,10 +2460,6 @@
       set_admin_address: {
         admin: 'PalletEvmAccountBasicCrossAccountIdRepr',
       },
-      start_app_promotion: {
-        promotionStartRelayBlock: 'Option<u32>',
-      },
-      stop_app_promotion: 'Null',
       stake: {
         amount: 'u128',
       },
@@ -3103,19 +3099,19 @@
     _enum: ['PermissionError', 'NoAvailableBaseId', 'NoAvailablePartId', 'BaseDoesntExist', 'NeedsDefaultThemeFirst', 'PartDoesntExist', 'NoEquippableOnFixedPart']
   },
   /**
-   * Lookup412: pallet_app_promotion::pallet::Error<T>
+   * Lookup415: pallet_app_promotion::pallet::Error<T>
    **/
   PalletAppPromotionError: {
-    _enum: ['AdminNotSet', 'NoPermission', 'NotSufficientFounds', 'InvalidArgument']
+    _enum: ['AdminNotSet', 'NoPermission', 'NotSufficientFounds', 'PendingForBlockOverflow', 'InvalidArgument']
   },
   /**
-   * Lookup415: pallet_evm::pallet::Error<T>
+   * Lookup418: pallet_evm::pallet::Error<T>
    **/
   PalletEvmError: {
     _enum: ['BalanceLow', 'FeeOverflow', 'PaymentOverflow', 'WithdrawFailed', 'GasPriceTooLow', 'InvalidNonce']
   },
   /**
-   * Lookup418: fp_rpc::TransactionStatus
+   * Lookup421: fp_rpc::TransactionStatus
    **/
   FpRpcTransactionStatus: {
     transactionHash: 'H256',
@@ -3127,11 +3123,11 @@
     logsBloom: 'EthbloomBloom'
   },
   /**
-   * Lookup420: ethbloom::Bloom
+   * Lookup423: ethbloom::Bloom
    **/
   EthbloomBloom: '[u8;256]',
   /**
-   * Lookup422: ethereum::receipt::ReceiptV3
+   * Lookup425: ethereum::receipt::ReceiptV3
    **/
   EthereumReceiptReceiptV3: {
     _enum: {
@@ -3141,7 +3137,7 @@
     }
   },
   /**
-   * Lookup423: ethereum::receipt::EIP658ReceiptData
+   * Lookup426: ethereum::receipt::EIP658ReceiptData
    **/
   EthereumReceiptEip658ReceiptData: {
     statusCode: 'u8',
@@ -3150,7 +3146,7 @@
     logs: 'Vec<EthereumLog>'
   },
   /**
-   * Lookup424: ethereum::block::Block<ethereum::transaction::TransactionV2>
+   * Lookup427: ethereum::block::Block<ethereum::transaction::TransactionV2>
    **/
   EthereumBlock: {
     header: 'EthereumHeader',
@@ -3158,7 +3154,7 @@
     ommers: 'Vec<EthereumHeader>'
   },
   /**
-   * Lookup425: ethereum::header::Header
+   * Lookup428: ethereum::header::Header
    **/
   EthereumHeader: {
     parentHash: 'H256',
@@ -3178,23 +3174,23 @@
     nonce: 'EthereumTypesHashH64'
   },
   /**
-   * Lookup426: ethereum_types::hash::H64
+   * Lookup429: ethereum_types::hash::H64
    **/
   EthereumTypesHashH64: '[u8;8]',
   /**
-   * Lookup431: pallet_ethereum::pallet::Error<T>
+   * Lookup434: pallet_ethereum::pallet::Error<T>
    **/
   PalletEthereumError: {
     _enum: ['InvalidSignature', 'PreLogExists']
   },
   /**
-   * Lookup432: pallet_evm_coder_substrate::pallet::Error<T>
+   * Lookup435: pallet_evm_coder_substrate::pallet::Error<T>
    **/
   PalletEvmCoderSubstrateError: {
     _enum: ['OutOfGas', 'OutOfFund']
   },
   /**
-   * Lookup433: up_data_structs::SponsorshipState<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+   * Lookup436: up_data_structs::SponsorshipState<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
    **/
   UpDataStructsSponsorshipStateBasicCrossAccountIdRepr: {
     _enum: {
@@ -3204,25 +3200,25 @@
     }
   },
   /**
-   * Lookup434: pallet_evm_contract_helpers::SponsoringModeT
+   * Lookup437: pallet_evm_contract_helpers::SponsoringModeT
    **/
   PalletEvmContractHelpersSponsoringModeT: {
     _enum: ['Disabled', 'Allowlisted', 'Generous']
   },
   /**
-   * Lookup436: pallet_evm_contract_helpers::pallet::Error<T>
+   * Lookup439: pallet_evm_contract_helpers::pallet::Error<T>
    **/
   PalletEvmContractHelpersError: {
     _enum: ['NoPermission', 'NoPendingSponsor']
   },
   /**
-   * Lookup437: pallet_evm_migration::pallet::Error<T>
+   * Lookup440: pallet_evm_migration::pallet::Error<T>
    **/
   PalletEvmMigrationError: {
     _enum: ['AccountNotEmpty', 'AccountIsNotMigrating']
   },
   /**
-   * Lookup439: sp_runtime::MultiSignature
+   * Lookup442: sp_runtime::MultiSignature
    **/
   SpRuntimeMultiSignature: {
     _enum: {
@@ -3232,43 +3228,43 @@
     }
   },
   /**
-   * Lookup440: sp_core::ed25519::Signature
+   * Lookup443: sp_core::ed25519::Signature
    **/
   SpCoreEd25519Signature: '[u8;64]',
   /**
-   * Lookup442: sp_core::sr25519::Signature
+   * Lookup445: sp_core::sr25519::Signature
    **/
   SpCoreSr25519Signature: '[u8;64]',
   /**
-   * Lookup443: sp_core::ecdsa::Signature
+   * Lookup446: sp_core::ecdsa::Signature
    **/
   SpCoreEcdsaSignature: '[u8;65]',
   /**
-   * Lookup446: frame_system::extensions::check_spec_version::CheckSpecVersion<T>
+   * Lookup449: frame_system::extensions::check_spec_version::CheckSpecVersion<T>
    **/
   FrameSystemExtensionsCheckSpecVersion: 'Null',
   /**
-   * Lookup447: frame_system::extensions::check_genesis::CheckGenesis<T>
+   * Lookup450: frame_system::extensions::check_genesis::CheckGenesis<T>
    **/
   FrameSystemExtensionsCheckGenesis: 'Null',
   /**
-   * Lookup450: frame_system::extensions::check_nonce::CheckNonce<T>
+   * Lookup453: frame_system::extensions::check_nonce::CheckNonce<T>
    **/
   FrameSystemExtensionsCheckNonce: 'Compact<u32>',
   /**
-   * Lookup451: frame_system::extensions::check_weight::CheckWeight<T>
+   * Lookup454: frame_system::extensions::check_weight::CheckWeight<T>
    **/
   FrameSystemExtensionsCheckWeight: 'Null',
   /**
-   * Lookup452: pallet_template_transaction_payment::ChargeTransactionPayment<opal_runtime::Runtime>
+   * Lookup455: pallet_template_transaction_payment::ChargeTransactionPayment<opal_runtime::Runtime>
    **/
   PalletTemplateTransactionPaymentChargeTransactionPayment: 'Compact<u128>',
   /**
-   * Lookup453: opal_runtime::Runtime
+   * Lookup456: opal_runtime::Runtime
    **/
   OpalRuntimeRuntime: 'Null',
   /**
-   * Lookup454: pallet_ethereum::FakeTransactionFinalizer<opal_runtime::Runtime>
+   * Lookup457: pallet_ethereum::FakeTransactionFinalizer<opal_runtime::Runtime>
    **/
   PalletEthereumFakeTransactionFinalizer: 'Null'
 };
modifiedtests/src/interfaces/types-lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -2665,11 +2665,6 @@
     readonly asSetAdminAddress: {
       readonly admin: PalletEvmAccountBasicCrossAccountIdRepr;
     } & Struct;
-    readonly isStartAppPromotion: boolean;
-    readonly asStartAppPromotion: {
-      readonly promotionStartRelayBlock: Option<u32>;
-    } & Struct;
-    readonly isStopAppPromotion: boolean;
     readonly isStake: boolean;
     readonly asStake: {
       readonly amount: u128;
@@ -2695,7 +2690,7 @@
     readonly asPayoutStakers: {
       readonly stakersNumber: Option<u8>;
     } & Struct;
-    readonly type: 'SetAdminAddress' | 'StartAppPromotion' | 'StopAppPromotion' | 'Stake' | 'Unstake' | 'SponsorCollection' | 'StopSponsoringCollection' | 'SponsorConract' | 'StopSponsoringContract' | 'PayoutStakers';
+    readonly type: 'SetAdminAddress' | 'Stake' | 'Unstake' | 'SponsorCollection' | 'StopSponsoringCollection' | 'SponsorConract' | 'StopSponsoringContract' | 'PayoutStakers';
   }
 
   /** @name PalletEvmCall (306) */
@@ -3291,16 +3286,17 @@
     readonly type: 'PermissionError' | 'NoAvailableBaseId' | 'NoAvailablePartId' | 'BaseDoesntExist' | 'NeedsDefaultThemeFirst' | 'PartDoesntExist' | 'NoEquippableOnFixedPart';
   }
 
-  /** @name PalletAppPromotionError (412) */
+  /** @name PalletAppPromotionError (415) */
   interface PalletAppPromotionError extends Enum {
     readonly isAdminNotSet: boolean;
     readonly isNoPermission: boolean;
     readonly isNotSufficientFounds: boolean;
+    readonly isPendingForBlockOverflow: boolean;
     readonly isInvalidArgument: boolean;
-    readonly type: 'AdminNotSet' | 'NoPermission' | 'NotSufficientFounds' | 'InvalidArgument';
+    readonly type: 'AdminNotSet' | 'NoPermission' | 'NotSufficientFounds' | 'PendingForBlockOverflow' | 'InvalidArgument';
   }
 
-  /** @name PalletEvmError (415) */
+  /** @name PalletEvmError (418) */
   interface PalletEvmError extends Enum {
     readonly isBalanceLow: boolean;
     readonly isFeeOverflow: boolean;
@@ -3311,7 +3307,7 @@
     readonly type: 'BalanceLow' | 'FeeOverflow' | 'PaymentOverflow' | 'WithdrawFailed' | 'GasPriceTooLow' | 'InvalidNonce';
   }
 
-  /** @name FpRpcTransactionStatus (418) */
+  /** @name FpRpcTransactionStatus (421) */
   interface FpRpcTransactionStatus extends Struct {
     readonly transactionHash: H256;
     readonly transactionIndex: u32;
@@ -3322,10 +3318,10 @@
     readonly logsBloom: EthbloomBloom;
   }
 
-  /** @name EthbloomBloom (420) */
+  /** @name EthbloomBloom (423) */
   interface EthbloomBloom extends U8aFixed {}
 
-  /** @name EthereumReceiptReceiptV3 (422) */
+  /** @name EthereumReceiptReceiptV3 (425) */
   interface EthereumReceiptReceiptV3 extends Enum {
     readonly isLegacy: boolean;
     readonly asLegacy: EthereumReceiptEip658ReceiptData;
@@ -3336,7 +3332,7 @@
     readonly type: 'Legacy' | 'Eip2930' | 'Eip1559';
   }
 
-  /** @name EthereumReceiptEip658ReceiptData (423) */
+  /** @name EthereumReceiptEip658ReceiptData (426) */
   interface EthereumReceiptEip658ReceiptData extends Struct {
     readonly statusCode: u8;
     readonly usedGas: U256;
@@ -3344,14 +3340,14 @@
     readonly logs: Vec<EthereumLog>;
   }
 
-  /** @name EthereumBlock (424) */
+  /** @name EthereumBlock (427) */
   interface EthereumBlock extends Struct {
     readonly header: EthereumHeader;
     readonly transactions: Vec<EthereumTransactionTransactionV2>;
     readonly ommers: Vec<EthereumHeader>;
   }
 
-  /** @name EthereumHeader (425) */
+  /** @name EthereumHeader (428) */
   interface EthereumHeader extends Struct {
     readonly parentHash: H256;
     readonly ommersHash: H256;
@@ -3370,24 +3366,24 @@
     readonly nonce: EthereumTypesHashH64;
   }
 
-  /** @name EthereumTypesHashH64 (426) */
+  /** @name EthereumTypesHashH64 (429) */
   interface EthereumTypesHashH64 extends U8aFixed {}
 
-  /** @name PalletEthereumError (431) */
+  /** @name PalletEthereumError (434) */
   interface PalletEthereumError extends Enum {
     readonly isInvalidSignature: boolean;
     readonly isPreLogExists: boolean;
     readonly type: 'InvalidSignature' | 'PreLogExists';
   }
 
-  /** @name PalletEvmCoderSubstrateError (432) */
+  /** @name PalletEvmCoderSubstrateError (435) */
   interface PalletEvmCoderSubstrateError extends Enum {
     readonly isOutOfGas: boolean;
     readonly isOutOfFund: boolean;
     readonly type: 'OutOfGas' | 'OutOfFund';
   }
 
-  /** @name UpDataStructsSponsorshipStateBasicCrossAccountIdRepr (433) */
+  /** @name UpDataStructsSponsorshipStateBasicCrossAccountIdRepr (436) */
   interface UpDataStructsSponsorshipStateBasicCrossAccountIdRepr extends Enum {
     readonly isDisabled: boolean;
     readonly isUnconfirmed: boolean;
@@ -3397,7 +3393,7 @@
     readonly type: 'Disabled' | 'Unconfirmed' | 'Confirmed';
   }
 
-  /** @name PalletEvmContractHelpersSponsoringModeT (434) */
+  /** @name PalletEvmContractHelpersSponsoringModeT (437) */
   interface PalletEvmContractHelpersSponsoringModeT extends Enum {
     readonly isDisabled: boolean;
     readonly isAllowlisted: boolean;
@@ -3405,21 +3401,21 @@
     readonly type: 'Disabled' | 'Allowlisted' | 'Generous';
   }
 
-  /** @name PalletEvmContractHelpersError (436) */
+  /** @name PalletEvmContractHelpersError (439) */
   interface PalletEvmContractHelpersError extends Enum {
     readonly isNoPermission: boolean;
     readonly isNoPendingSponsor: boolean;
     readonly type: 'NoPermission' | 'NoPendingSponsor';
   }
 
-  /** @name PalletEvmMigrationError (437) */
+  /** @name PalletEvmMigrationError (440) */
   interface PalletEvmMigrationError extends Enum {
     readonly isAccountNotEmpty: boolean;
     readonly isAccountIsNotMigrating: boolean;
     readonly type: 'AccountNotEmpty' | 'AccountIsNotMigrating';
   }
 
-  /** @name SpRuntimeMultiSignature (439) */
+  /** @name SpRuntimeMultiSignature (442) */
   interface SpRuntimeMultiSignature extends Enum {
     readonly isEd25519: boolean;
     readonly asEd25519: SpCoreEd25519Signature;
@@ -3430,34 +3426,34 @@
     readonly type: 'Ed25519' | 'Sr25519' | 'Ecdsa';
   }
 
-  /** @name SpCoreEd25519Signature (440) */
+  /** @name SpCoreEd25519Signature (443) */
   interface SpCoreEd25519Signature extends U8aFixed {}
 
-  /** @name SpCoreSr25519Signature (442) */
+  /** @name SpCoreSr25519Signature (445) */
   interface SpCoreSr25519Signature extends U8aFixed {}
 
-  /** @name SpCoreEcdsaSignature (443) */
+  /** @name SpCoreEcdsaSignature (446) */
   interface SpCoreEcdsaSignature extends U8aFixed {}
 
-  /** @name FrameSystemExtensionsCheckSpecVersion (446) */
+  /** @name FrameSystemExtensionsCheckSpecVersion (449) */
   type FrameSystemExtensionsCheckSpecVersion = Null;
 
-  /** @name FrameSystemExtensionsCheckGenesis (447) */
+  /** @name FrameSystemExtensionsCheckGenesis (450) */
   type FrameSystemExtensionsCheckGenesis = Null;
 
-  /** @name FrameSystemExtensionsCheckNonce (450) */
+  /** @name FrameSystemExtensionsCheckNonce (453) */
   interface FrameSystemExtensionsCheckNonce extends Compact<u32> {}
 
-  /** @name FrameSystemExtensionsCheckWeight (451) */
+  /** @name FrameSystemExtensionsCheckWeight (454) */
   type FrameSystemExtensionsCheckWeight = Null;
 
-  /** @name PalletTemplateTransactionPaymentChargeTransactionPayment (452) */
+  /** @name PalletTemplateTransactionPaymentChargeTransactionPayment (455) */
   interface PalletTemplateTransactionPaymentChargeTransactionPayment extends Compact<u128> {}
 
-  /** @name OpalRuntimeRuntime (453) */
+  /** @name OpalRuntimeRuntime (456) */
   type OpalRuntimeRuntime = Null;
 
-  /** @name PalletEthereumFakeTransactionFinalizer (454) */
+  /** @name PalletEthereumFakeTransactionFinalizer (457) */
   type PalletEthereumFakeTransactionFinalizer = Null;
 
 } // declare module
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.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 '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';31import {Context} from 'mocha';3233chai.use(chaiAsPromised);34const expect = chai.expect;3536export type CrossAccountId = {37  Substrate: string,38} | {39  Ethereum: string,40};414243export enum Pallets {44  Inflation = 'inflation',45  RmrkCore = 'rmrkcore',46  RmrkEquip = 'rmrkequip',47  ReFungible = 'refungible',48  Fungible = 'fungible',49  NFT = 'nonfungible',50  Scheduler = 'scheduler',51  AppPromotion = 'promotion',52}5354export async function isUnique(): Promise<boolean> {55  return usingApi(async api => {56    const chain = await api.rpc.system.chain();5758    return chain.eq('UNIQUE');59  });60}6162export async function isQuartz(): Promise<boolean> {63  return usingApi(async api => {64    const chain = await api.rpc.system.chain();65    66    return chain.eq('QUARTZ');67  });68}6970let modulesNames: any;71export function getModuleNames(api: ApiPromise): string[] {72  if (typeof modulesNames === 'undefined') 73    modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());74  return modulesNames;75}7677export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {78  return await usingApi(async api => {79    const pallets = getModuleNames(api);8081    return requiredPallets.filter(p => !pallets.includes(p));82  });83}8485export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {86  return (await missingRequiredPallets(requiredPallets)).length == 0;87}8889export async function requirePallets(mocha: Context, requiredPallets: string[]) {90  const missingPallets = await missingRequiredPallets(requiredPallets);9192  if (missingPallets.length > 0) {93    const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;94    const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;95    const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9697    console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);9899    mocha.skip();100  }101}102103export function bigIntToSub(api: ApiPromise, number: bigint) {104  return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();105}106107export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {108  if (typeof input === 'string') {109    if (input.length >= 47) {110      return {Substrate: input};111    } else if (input.length === 42 && input.startsWith('0x')) {112      return {Ethereum: input.toLowerCase()};113    } else if (input.length === 40 && !input.startsWith('0x')) {114      return {Ethereum: '0x' + input.toLowerCase()};115    } else {116      throw new Error(`Unknown address format: "${input}"`);117    }118  }119  if ('address' in input) {120    return {Substrate: input.address};121  }122  if ('Ethereum' in input) {123    return {124      Ethereum: input.Ethereum.toLowerCase(),125    };126  } else if ('ethereum' in input) {127    return {128      Ethereum: (input as any).ethereum.toLowerCase(),129    };130  } else if ('Substrate' in input) {131    return input;132  } else if ('substrate' in input) {133    return {134      Substrate: (input as any).substrate,135    };136  }137138  // AccountId139  return {Substrate: input.toString()};140}141export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {142  input = normalizeAccountId(input);143  if ('Substrate' in input) {144    return input.Substrate;145  } else {146    return evmToAddress(input.Ethereum);147  }148}149150export const U128_MAX = (1n << 128n) - 1n;151152const MICROUNIQUE = 1_000_000_000_000n;153const MILLIUNIQUE = 1_000n * MICROUNIQUE;154const CENTIUNIQUE = 10n * MILLIUNIQUE;155export const UNIQUE = 100n * CENTIUNIQUE;156157interface GenericResult<T> {158  success: boolean;159  data: T | null;160}161162interface CreateCollectionResult {163  success: boolean;164  collectionId: number;165}166167interface CreateItemResult {168  success: boolean;169  collectionId: number;170  itemId: number;171  recipient?: CrossAccountId;172  amount?: number;173}174175interface DestroyItemResult {176  success: boolean;177  collectionId: number;178  itemId: number;179  owner: CrossAccountId;180  amount: number;181}182183interface TransferResult {184  collectionId: number;185  itemId: number;186  sender?: CrossAccountId;187  recipient?: CrossAccountId;188  value: bigint;189}190191interface IReFungibleOwner {192  fraction: BN;193  owner: number[];194}195196interface IGetMessage {197  checkMsgUnqMethod: string;198  checkMsgTrsMethod: string;199  checkMsgSysMethod: string;200}201202export interface IFungibleTokenDataType {203  value: number;204}205206export interface IChainLimits {207  collectionNumbersLimit: number;208  accountTokenOwnershipLimit: number;209  collectionsAdminsLimit: number;210  customDataLimit: number;211  nftSponsorTransferTimeout: number;212  fungibleSponsorTransferTimeout: number;213  refungibleSponsorTransferTimeout: number;214  //offchainSchemaLimit: number;215  //constOnChainSchemaLimit: number;216}217218export interface IReFungibleTokenDataType {219  owner: IReFungibleOwner[];220}221222export function uniqueEventMessage(events: EventRecord[]): IGetMessage {223  let checkMsgUnqMethod = '';224  let checkMsgTrsMethod = '';225  let checkMsgSysMethod = '';226  events.forEach(({event: {method, section}}) => {227    if (section === 'common') {228      checkMsgUnqMethod = method;229    } else if (section === 'treasury') {230      checkMsgTrsMethod = method;231    } else if (section === 'system') {232      checkMsgSysMethod = method;233    } else { return null; }234  });235  const result: IGetMessage = {236    checkMsgUnqMethod,237    checkMsgTrsMethod,238    checkMsgSysMethod,239  };240  return result;241}242243export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {244  const event = events.find(r => check(r.event));245  if (!event) return;246  return event.event as T;247}248249export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;250export function getGenericResult<T>(251  events: EventRecord[],252  expectSection: string,253  expectMethod: string,254  extractAction: (data: GenericEventData) => T255): GenericResult<T>;256257export function getGenericResult<T>(258  events: EventRecord[],259  expectSection?: string,260  expectMethod?: string,261  extractAction?: (data: GenericEventData) => T,262): GenericResult<T> {263  let success = false;264  let successData = null;265266  events.forEach(({event: {data, method, section}}) => {267    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);268    if (method === 'ExtrinsicSuccess') {269      success = true;270    } else if ((expectSection == section) && (expectMethod == method)) {271      successData = extractAction!(data as any);272    }273  });274275  const result: GenericResult<T> = {276    success,277    data: successData,278  };279  return result;280}281282export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {283  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));284  const result: CreateCollectionResult = {285    success: genericResult.success,286    collectionId: genericResult.data ?? 0,287  };288  return result;289}290291export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {292  const results: CreateItemResult[] = [];293  294  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {295    const collectionId = parseInt(data[0].toString(), 10);296    const itemId = parseInt(data[1].toString(), 10);297    const recipient = normalizeAccountId(data[2].toJSON() as any);298    const amount = parseInt(data[3].toString(), 10);299300    const itemRes: CreateItemResult = {301      success: true,302      collectionId,303      itemId,304      recipient,305      amount,306    };307308    results.push(itemRes);309    return results;310  });311312  if (!genericResult.success) return [];313  return results;314}315316export function getCreateItemResult(events: EventRecord[]): CreateItemResult {317  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));318  319  if (genericResult.data == null) 320    return {321      success: genericResult.success,322      collectionId: 0,323      itemId: 0,324      amount: 0,325    };326  else 327    return {328      success: genericResult.success,329      collectionId: genericResult.data[0] as number,330      itemId: genericResult.data[1] as number,331      recipient: normalizeAccountId(genericResult.data![2] as any),332      amount: genericResult.data[3] as number,333    };334}335336export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {337  const results: DestroyItemResult[] = [];338  339  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {340    const collectionId = parseInt(data[0].toString(), 10);341    const itemId = parseInt(data[1].toString(), 10);342    const owner = normalizeAccountId(data[2].toJSON() as any);343    const amount = parseInt(data[3].toString(), 10);344345    const itemRes: DestroyItemResult = {346      success: true,347      collectionId,348      itemId,349      owner,350      amount,351    };352353    results.push(itemRes);354    return results;355  });356357  if (!genericResult.success) return [];358  return results;359}360361export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {362  for (const {event} of events) {363    if (api.events.common.Transfer.is(event)) {364      const [collection, token, sender, recipient, value] = event.data;365      return {366        collectionId: collection.toNumber(),367        itemId: token.toNumber(),368        sender: normalizeAccountId(sender.toJSON() as any),369        recipient: normalizeAccountId(recipient.toJSON() as any),370        value: value.toBigInt(),371      };372    }373  }374  throw new Error('no transfer event');375}376377interface Nft {378  type: 'NFT';379}380381interface Fungible {382  type: 'Fungible';383  decimalPoints: number;384}385386interface ReFungible {387  type: 'ReFungible';388}389390export type CollectionMode = Nft | Fungible | ReFungible;391392export type Property = {393  key: any,394  value: any,395};396397type Permission = {398  mutable: boolean;399  collectionAdmin: boolean;400  tokenOwner: boolean;401}402403type PropertyPermission = {404  key: any;405  permission: Permission;406}407408export type CreateCollectionParams = {409  mode: CollectionMode,410  name: string,411  description: string,412  tokenPrefix: string,413  properties?: Array<Property>,414  propPerm?: Array<PropertyPermission>415};416417const defaultCreateCollectionParams: CreateCollectionParams = {418  description: 'description',419  mode: {type: 'NFT'},420  name: 'name',421  tokenPrefix: 'prefix',422};423424export async function425createCollection(426  api: ApiPromise,427  sender: IKeyringPair,428  params: Partial<CreateCollectionParams> = {},429): Promise<CreateCollectionResult> {430  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};431432  let modeprm = {};433  if (mode.type === 'NFT') {434    modeprm = {nft: null};435  } else if (mode.type === 'Fungible') {436    modeprm = {fungible: mode.decimalPoints};437  } else if (mode.type === 'ReFungible') {438    modeprm = {refungible: null};439  }440441  const tx = api.tx.unique.createCollectionEx({442    name: strToUTF16(name),443    description: strToUTF16(description),444    tokenPrefix: strToUTF16(tokenPrefix),445    mode: modeprm as any,446  });447  const events = await executeTransaction(api, sender, tx);448  return getCreateCollectionResult(events);449}450451export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {452  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};453454  let collectionId = 0;455  await usingApi(async (api, privateKeyWrapper) => {456    // Get number of collections before the transaction457    const collectionCountBefore = await getCreatedCollectionCount(api);458459    // Run the CreateCollection transaction460    const alicePrivateKey = privateKeyWrapper('//Alice');461462    const result = await createCollection(api, alicePrivateKey, params);463464    // Get number of collections after the transaction465    const collectionCountAfter = await getCreatedCollectionCount(api);466467    // Get the collection468    const collection = await queryCollectionExpectSuccess(api, result.collectionId);469470    // What to expect471    // tslint:disable-next-line:no-unused-expression472    expect(result.success).to.be.true;473    expect(result.collectionId).to.be.equal(collectionCountAfter);474    // tslint:disable-next-line:no-unused-expression475    expect(collection).to.be.not.null;476    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');477    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));478    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);479    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);480    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);481482    collectionId = result.collectionId;483  });484485  return collectionId;486}487488export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {489  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};490491  let collectionId = 0;492  await usingApi(async (api, privateKeyWrapper) => {493    // Get number of collections before the transaction494    const collectionCountBefore = await getCreatedCollectionCount(api);495496    // Run the CreateCollection transaction497    const alicePrivateKey = privateKeyWrapper('//Alice');498499    let modeprm = {};500    if (mode.type === 'NFT') {501      modeprm = {nft: null};502    } else if (mode.type === 'Fungible') {503      modeprm = {fungible: mode.decimalPoints};504    } else if (mode.type === 'ReFungible') {505      modeprm = {refungible: null};506    }507508    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});509    const events = await submitTransactionAsync(alicePrivateKey, tx);510    const result = getCreateCollectionResult(events);511512    // Get number of collections after the transaction513    const collectionCountAfter = await getCreatedCollectionCount(api);514515    // Get the collection516    const collection = await queryCollectionExpectSuccess(api, result.collectionId);517518    // What to expect519    // tslint:disable-next-line:no-unused-expression520    expect(result.success).to.be.true;521    expect(result.collectionId).to.be.equal(collectionCountAfter);522    // tslint:disable-next-line:no-unused-expression523    expect(collection).to.be.not.null;524    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');525    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));526    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);527    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);528    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);529530531    collectionId = result.collectionId;532  });533534  return collectionId;535}536537export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {538  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};539540  await usingApi(async (api, privateKeyWrapper) => {541    // Get number of collections before the transaction542    const collectionCountBefore = await getCreatedCollectionCount(api);543544    // Run the CreateCollection transaction545    const alicePrivateKey = privateKeyWrapper('//Alice');546547    let modeprm = {};548    if (mode.type === 'NFT') {549      modeprm = {nft: null};550    } else if (mode.type === 'Fungible') {551      modeprm = {fungible: mode.decimalPoints};552    } else if (mode.type === 'ReFungible') {553      modeprm = {refungible: null};554    }555556    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});557    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;558559560    // Get number of collections after the transaction561    const collectionCountAfter = await getCreatedCollectionCount(api);562563    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');564  });565}566567export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {568  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};569570  let modeprm = {};571  if (mode.type === 'NFT') {572    modeprm = {nft: null};573  } else if (mode.type === 'Fungible') {574    modeprm = {fungible: mode.decimalPoints};575  } else if (mode.type === 'ReFungible') {576    modeprm = {refungible: null};577  }578579  await usingApi(async (api, privateKeyWrapper) => {580    // Get number of collections before the transaction581    const collectionCountBefore = await getCreatedCollectionCount(api);582583    // Run the CreateCollection transaction584    const alicePrivateKey = privateKeyWrapper('//Alice');585    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});586    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;587588    // Get number of collections after the transaction589    const collectionCountAfter = await getCreatedCollectionCount(api);590591    // What to expect592    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');593  });594}595596export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {597  let bal = 0n;598  let unused;599  do {600    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;601    unused = privateKeyWrapper(`//${randomSeed}`);602    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();603  } while (bal !== 0n);604  return unused;605}606607export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {608  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();609}610611export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {612  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));613}614615export async function findNotExistingCollection(api: ApiPromise): Promise<number> {616  const totalNumber = await getCreatedCollectionCount(api);617  const newCollection: number = totalNumber + 1;618  return newCollection;619}620621function getDestroyResult(events: EventRecord[]): boolean {622  let success = false;623  events.forEach(({event: {method}}) => {624    if (method == 'ExtrinsicSuccess') {625      success = true;626    }627  });628  return success;629}630631export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {632  await usingApi(async (api, privateKeyWrapper) => {633    // Run the DestroyCollection transaction634    const alicePrivateKey = privateKeyWrapper(senderSeed);635    const tx = api.tx.unique.destroyCollection(collectionId);636    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;637  });638}639640export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {641  await usingApi(async (api, privateKeyWrapper) => {642    // Run the DestroyCollection transaction643    const alicePrivateKey = privateKeyWrapper(senderSeed);644    const tx = api.tx.unique.destroyCollection(collectionId);645    const events = await submitTransactionAsync(alicePrivateKey, tx);646    const result = getDestroyResult(events);647    expect(result).to.be.true;648649    // What to expect650    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;651  });652}653654export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {655  await usingApi(async (api) => {656    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);657    const events = await submitTransactionAsync(sender, tx);658    const result = getGenericResult(events);659660    expect(result.success).to.be.true;661  });662}663664export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {665  await usingApi(async(api) => {666    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);667    const events = await submitTransactionAsync(sender, tx);668    const result = getGenericResult(events);669670    expect(result.success).to.be.true;671  });672};673674export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {675  await usingApi(async (api) => {676    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);677    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;678    const result = getGenericResult(events);679680    expect(result.success).to.be.false;681  });682}683684export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {685  await usingApi(async (api, privateKeyWrapper) => {686687    // Run the transaction688    const senderPrivateKey = privateKeyWrapper(sender);689    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);690    const events = await submitTransactionAsync(senderPrivateKey, tx);691    const result = getGenericResult(events);692693    // Get the collection694    const collection = await queryCollectionExpectSuccess(api, collectionId);695696    // What to expect697    expect(result.success).to.be.true;698    expect(collection.sponsorship.toJSON()).to.deep.equal({699      unconfirmed: sponsor,700    });701  });702}703704export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {705  await usingApi(async (api, privateKeyWrapper) => {706707    // Run the transaction708    const alicePrivateKey = privateKeyWrapper(sender);709    const tx = api.tx.unique.removeCollectionSponsor(collectionId);710    const events = await submitTransactionAsync(alicePrivateKey, tx);711    const result = getGenericResult(events);712713    // Get the collection714    const collection = await queryCollectionExpectSuccess(api, collectionId);715716    // What to expect717    expect(result.success).to.be.true;718    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});719  });720}721722export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {723  await usingApi(async (api, privateKeyWrapper) => {724725    // Run the transaction726    const alicePrivateKey = privateKeyWrapper(senderSeed);727    const tx = api.tx.unique.removeCollectionSponsor(collectionId);728    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;729  });730}731732export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {733  await usingApi(async (api, privateKeyWrapper) => {734735    // Run the transaction736    const alicePrivateKey = privateKeyWrapper(senderSeed);737    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);738    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;739  });740}741742export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {743  await usingApi(async (api, privateKeyWrapper) => {744745    // Run the transaction746    const sender = privateKeyWrapper(senderSeed);747    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);748  });749}750751export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {752  await usingApi(async (api, privateKeyWrapper) => {753754    // Run the transaction755    const tx = api.tx.unique.confirmSponsorship(collectionId);756    const events = await submitTransactionAsync(sender, tx);757    const result = getGenericResult(events);758759    // Get the collection760    const collection = await queryCollectionExpectSuccess(api, collectionId);761762    // What to expect763    expect(result.success).to.be.true;764    expect(collection.sponsorship.toJSON()).to.be.deep.equal({765      confirmed: sender.address,766    });767  });768}769770771export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {772  await usingApi(async (api, privateKeyWrapper) => {773774    // Run the transaction775    const sender = privateKeyWrapper(senderSeed);776    const tx = api.tx.unique.confirmSponsorship(collectionId);777    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;778  });779}780781export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {782  await usingApi(async (api) => {783    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);784    const events = await submitTransactionAsync(sender, tx);785    const result = getGenericResult(events);786787    expect(result.success).to.be.true;788  });789}790791export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {792  await usingApi(async (api) => {793    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);794    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;795    const result = getGenericResult(events);796797    expect(result.success).to.be.false;798  });799}800801export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {802803  await usingApi(async (api) => {804805    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);806    const events = await submitTransactionAsync(sender, tx);807    const result = getGenericResult(events);808809    expect(result.success).to.be.true;810  });811}812813export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {814815  await usingApi(async (api) => {816817    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);818    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;819    const result = getGenericResult(events);820821    expect(result.success).to.be.false;822  });823}824825export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {826  await usingApi(async (api) => {827    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);828    const events = await submitTransactionAsync(sender, tx);829    const result = getGenericResult(events);830831    expect(result.success).to.be.true;832  });833}834835export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {836  await usingApi(async (api) => {837    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);838    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;839    const result = getGenericResult(events);840841    expect(result.success).to.be.false;842  });843}844845export async function getNextSponsored(846  api: ApiPromise,847  collectionId: number,848  account: string | CrossAccountId,849  tokenId: number,850): Promise<number> {851  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));852}853854export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {855  await usingApi(async (api) => {856    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);857    const events = await submitTransactionAsync(sender, tx);858    const result = getGenericResult(events);859860    expect(result.success).to.be.true;861  });862}863864export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {865  let allowlisted = false;866  await usingApi(async (api) => {867    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;868  });869  return allowlisted;870}871872export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {873  await usingApi(async (api) => {874    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());875    const events = await submitTransactionAsync(sender, tx);876    const result = getGenericResult(events);877878    expect(result.success).to.be.true;879  });880}881882export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {883  await usingApi(async (api) => {884    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());885    const events = await submitTransactionAsync(sender, tx);886    const result = getGenericResult(events);887888    expect(result.success).to.be.true;889  });890}891892export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {893  await usingApi(async (api) => {894    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());895    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;896    const result = getGenericResult(events);897898    expect(result.success).to.be.false;899  });900}901902export interface CreateFungibleData {903  readonly Value: bigint;904}905906export interface CreateReFungibleData { }907export interface CreateNftData { }908909export type CreateItemData = {910  NFT: CreateNftData;911} | {912  Fungible: CreateFungibleData;913} | {914  ReFungible: CreateReFungibleData;915};916917export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {918  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);919  const events = await submitTransactionAsync(sender, tx);920  return getGenericResult(events).success;921}922923export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {924  await usingApi(async (api) => {925    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);926    // if burning token by admin - use adminButnItemExpectSuccess927    expect(balanceBefore >= BigInt(value)).to.be.true;928929    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;930931    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);932    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);933  });934}935936export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {937  await usingApi(async (api) => {938    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);939940    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;941    const result = getCreateCollectionResult(events);942    // tslint:disable-next-line:no-unused-expression943    expect(result.success).to.be.false;944  });945}946947export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {948  await usingApi(async (api) => {949    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);950    const events = await submitTransactionAsync(sender, tx);951    return getGenericResult(events).success;952  });953}954955export async function956approve(957  api: ApiPromise,958  collectionId: number,959  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,960) {961  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);962  const events = await submitTransactionAsync(owner, approveUniqueTx);963  return getGenericResult(events).success;964}965966export async function967approveExpectSuccess(968  collectionId: number,969  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,970) {971  await usingApi(async (api: ApiPromise) => {972    const result = await approve(api, collectionId, tokenId, owner, approved, amount);973    expect(result).to.be.true;974975    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));976  });977}978979export async function adminApproveFromExpectSuccess(980  collectionId: number,981  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,982) {983  await usingApi(async (api: ApiPromise) => {984    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);985    const events = await submitTransactionAsync(admin, approveUniqueTx);986    const result = getGenericResult(events);987    expect(result.success).to.be.true;988989    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));990  });991}992993export async function994transferFrom(995  api: ApiPromise,996  collectionId: number,997  tokenId: number,998  accountApproved: IKeyringPair,999  accountFrom: IKeyringPair | CrossAccountId,1000  accountTo: IKeyringPair | CrossAccountId,1001  value: number | bigint,1002) {1003  const from = normalizeAccountId(accountFrom);1004  const to = normalizeAccountId(accountTo);1005  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1006  const events = await submitTransactionAsync(accountApproved, transferFromTx);1007  return getGenericResult(events).success;1008}10091010export async function1011transferFromExpectSuccess(1012  collectionId: number,1013  tokenId: number,1014  accountApproved: IKeyringPair,1015  accountFrom: IKeyringPair | CrossAccountId,1016  accountTo: IKeyringPair | CrossAccountId,1017  value: number | bigint = 1,1018  type = 'NFT',1019) {1020  await usingApi(async (api: ApiPromise) => {1021    const from = normalizeAccountId(accountFrom);1022    const to = normalizeAccountId(accountTo);1023    let balanceBefore = 0n;1024    if (type === 'Fungible' || type === 'ReFungible') {1025      balanceBefore = await getBalance(api, collectionId, to, tokenId);1026    }1027    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1028    if (type === 'NFT') {1029      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1030    }1031    if (type === 'Fungible') {1032      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1033      if (JSON.stringify(to) !== JSON.stringify(from)) {1034        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1035      } else {1036        expect(balanceAfter).to.be.equal(balanceBefore);1037      }1038    }1039    if (type === 'ReFungible') {1040      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1041    }1042  });1043}10441045export async function1046transferFromExpectFail(1047  collectionId: number,1048  tokenId: number,1049  accountApproved: IKeyringPair,1050  accountFrom: IKeyringPair,1051  accountTo: IKeyringPair,1052  value: number | bigint = 1,1053) {1054  await usingApi(async (api: ApiPromise) => {1055    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1056    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1057    const result = getCreateCollectionResult(events);1058    // tslint:disable-next-line:no-unused-expression1059    expect(result.success).to.be.false;1060  });1061}10621063/* eslint no-async-promise-executor: "off" */1064export async function getBlockNumber(api: ApiPromise): Promise<number> {1065  return new Promise<number>(async (resolve) => {1066    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1067      unsubscribe();1068      resolve(head.number.toNumber());1069    });1070  });1071}10721073export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1074  await usingApi(async (api) => {1075    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1076    const events = await submitTransactionAsync(sender, changeAdminTx);1077    const result = getCreateCollectionResult(events);1078    expect(result.success).to.be.true;1079  });1080}10811082export async function adminApproveFromExpectFail(1083  collectionId: number,1084  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1085) {1086  await usingApi(async (api: ApiPromise) => {1087    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1088    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1089    const result = getGenericResult(events);1090    expect(result.success).to.be.false;1091  });1092}10931094export async function1095getFreeBalance(account: IKeyringPair): Promise<bigint> {1096  let balance = 0n;1097  await usingApi(async (api) => {1098    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1099  });11001101  return balance;1102}11031104export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1105  const tx = api.tx.balances.transfer(target, amount);1106  const events = await submitTransactionAsync(source, tx);1107  const result = getGenericResult(events);1108  expect(result.success).to.be.true;1109}11101111export async function1112scheduleExpectSuccess(1113  operationTx: any,1114  sender: IKeyringPair,1115  blockSchedule: number,1116  scheduledId: string,1117  period = 1,1118  repetitions = 1,1119) {1120  await usingApi(async (api: ApiPromise) => {1121    const blockNumber: number | undefined = await getBlockNumber(api);1122    const expectedBlockNumber = blockNumber + blockSchedule;11231124    expect(blockNumber).to.be.greaterThan(0);1125    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1126      scheduledId,1127      expectedBlockNumber, 1128      repetitions > 1 ? [period, repetitions] : null, 1129      0, 1130      {Value: operationTx as any},1131    );11321133    const events = await submitTransactionAsync(sender, scheduleTx);1134    expect(getGenericResult(events).success).to.be.true;1135  });1136}11371138export async function1139scheduleExpectFailure(1140  operationTx: any,1141  sender: IKeyringPair,1142  blockSchedule: number,1143  scheduledId: string,1144  period = 1,1145  repetitions = 1,1146) {1147  await usingApi(async (api: ApiPromise) => {1148    const blockNumber: number | undefined = await getBlockNumber(api);1149    const expectedBlockNumber = blockNumber + blockSchedule;11501151    expect(blockNumber).to.be.greaterThan(0);1152    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1153      scheduledId,1154      expectedBlockNumber, 1155      repetitions <= 1 ? null : [period, repetitions], 1156      0, 1157      {Value: operationTx as any},1158    );11591160    //const events = 1161    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1162    //expect(getGenericResult(events).success).to.be.false;1163  });1164}11651166export async function1167scheduleTransferAndWaitExpectSuccess(1168  collectionId: number,1169  tokenId: number,1170  sender: IKeyringPair,1171  recipient: IKeyringPair,1172  value: number | bigint = 1,1173  blockSchedule: number,1174  scheduledId: string,1175) {1176  await usingApi(async (api: ApiPromise) => {1177    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11781179    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11801181    // sleep for n + 1 blocks1182    await waitNewBlocks(blockSchedule + 1);11831184    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11851186    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1187    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1188  });1189}11901191export async function1192scheduleTransferExpectSuccess(1193  collectionId: number,1194  tokenId: number,1195  sender: IKeyringPair,1196  recipient: IKeyringPair,1197  value: number | bigint = 1,1198  blockSchedule: number,1199  scheduledId: string,1200) {1201  await usingApi(async (api: ApiPromise) => {1202    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12031204    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12051206    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1207  });1208}12091210export async function1211scheduleTransferFundsPeriodicExpectSuccess(1212  amount: bigint,1213  sender: IKeyringPair,1214  recipient: IKeyringPair,1215  blockSchedule: number,1216  scheduledId: string,1217  period: number,1218  repetitions: number,1219) {1220  await usingApi(async (api: ApiPromise) => {1221    const transferTx = api.tx.balances.transfer(recipient.address, amount);12221223    const balanceBefore = await getFreeBalance(recipient);1224    1225    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12261227    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1228  });1229}12301231export async function1232transfer(1233  api: ApiPromise,1234  collectionId: number,1235  tokenId: number,1236  sender: IKeyringPair,1237  recipient: IKeyringPair | CrossAccountId,1238  value: number | bigint,1239) : Promise<boolean> {1240  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1241  const events = await executeTransaction(api, sender, transferTx);1242  return getGenericResult(events).success;1243}12441245export async function1246transferExpectSuccess(1247  collectionId: number,1248  tokenId: number,1249  sender: IKeyringPair,1250  recipient: IKeyringPair | CrossAccountId,1251  value: number | bigint = 1,1252  type = 'NFT',1253) {1254  await usingApi(async (api: ApiPromise) => {1255    const from = normalizeAccountId(sender);1256    const to = normalizeAccountId(recipient);12571258    let balanceBefore = 0n;1259    if (type === 'Fungible' || type === 'ReFungible') {1260      balanceBefore = await getBalance(api, collectionId, to, tokenId);1261    }12621263    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1264    const events = await executeTransaction(api, sender, transferTx);1265    const result = getTransferResult(api, events);12661267    expect(result.collectionId).to.be.equal(collectionId);1268    expect(result.itemId).to.be.equal(tokenId);1269    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1270    expect(result.recipient).to.be.deep.equal(to);1271    expect(result.value).to.be.equal(BigInt(value));12721273    if (type === 'NFT') {1274      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1275    }1276    if (type === 'Fungible' || type === 'ReFungible') {1277      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1278      if (JSON.stringify(to) !== JSON.stringify(from)) {1279        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1280      } else {1281        expect(balanceAfter).to.be.equal(balanceBefore);1282      }1283    }1284  });1285}12861287export async function1288transferExpectFailure(1289  collectionId: number,1290  tokenId: number,1291  sender: IKeyringPair,1292  recipient: IKeyringPair | CrossAccountId,1293  value: number | bigint = 1,1294) {1295  await usingApi(async (api: ApiPromise) => {1296    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1297    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1298    const result = getGenericResult(events);1299    // if (events && Array.isArray(events)) {1300    //   const result = getCreateCollectionResult(events);1301    // tslint:disable-next-line:no-unused-expression1302    expect(result.success).to.be.false;1303    //}1304  });1305}13061307export async function1308approveExpectFail(1309  collectionId: number,1310  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1311) {1312  await usingApi(async (api: ApiPromise) => {1313    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1314    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1315    const result = getCreateCollectionResult(events);1316    // tslint:disable-next-line:no-unused-expression1317    expect(result.success).to.be.false;1318  });1319}13201321export async function getBalance(1322  api: ApiPromise,1323  collectionId: number,1324  owner: string | CrossAccountId | IKeyringPair,1325  token: number,1326): Promise<bigint> {1327  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1328}1329export async function getTokenOwner(1330  api: ApiPromise,1331  collectionId: number,1332  token: number,1333): Promise<CrossAccountId> {1334  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1335  if (owner == null) throw new Error('owner == null');1336  return normalizeAccountId(owner);1337}1338export async function getTopmostTokenOwner(1339  api: ApiPromise,1340  collectionId: number,1341  token: number,1342): Promise<CrossAccountId> {1343  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1344  if (owner == null) throw new Error('owner == null');1345  return normalizeAccountId(owner);1346}1347export async function getTokenChildren(1348  api: ApiPromise,1349  collectionId: number,1350  tokenId: number,1351): Promise<UpDataStructsTokenChild[]> {1352  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1353}1354export async function isTokenExists(1355  api: ApiPromise,1356  collectionId: number,1357  token: number,1358): Promise<boolean> {1359  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1360}1361export async function getLastTokenId(1362  api: ApiPromise,1363  collectionId: number,1364): Promise<number> {1365  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1366}1367export async function getAdminList(1368  api: ApiPromise,1369  collectionId: number,1370): Promise<string[]> {1371  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1372}1373export async function getTokenProperties(1374  api: ApiPromise,1375  collectionId: number,1376  tokenId: number,1377  propertyKeys: string[],1378): Promise<UpDataStructsProperty[]> {1379  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1380}13811382export async function createFungibleItemExpectSuccess(1383  sender: IKeyringPair,1384  collectionId: number,1385  data: CreateFungibleData,1386  owner: CrossAccountId | string = sender.address,1387) {1388  return await usingApi(async (api) => {1389    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13901391    const events = await submitTransactionAsync(sender, tx);1392    const result = getCreateItemResult(events);13931394    expect(result.success).to.be.true;1395    return result.itemId;1396  });1397}13981399export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1400  await usingApi(async (api) => {1401    const to = normalizeAccountId(owner);1402    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14031404    const events = await submitTransactionAsync(sender, tx);1405    expect(getGenericResult(events).success).to.be.true;1406  });1407}14081409export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1410  await usingApi(async (api) => {1411    const to = normalizeAccountId(owner);1412    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14131414    const events = await submitTransactionAsync(sender, tx);1415    const result = getCreateItemsResult(events);14161417    for (const res of result) {1418      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1419    }1420  });1421}14221423export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1424  await usingApi(async (api) => {1425    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14261427    const events = await submitTransactionAsync(sender, tx);1428    const result = getCreateItemsResult(events);14291430    for (const res of result) {1431      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1432    }1433  });1434}14351436export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1437  let newItemId = 0;1438  await usingApi(async (api) => {1439    const to = normalizeAccountId(owner);1440    const itemCountBefore = await getLastTokenId(api, collectionId);1441    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14421443    let tx;1444    if (createMode === 'Fungible') {1445      const createData = {fungible: {value: 10}};1446      tx = api.tx.unique.createItem(collectionId, to, createData as any);1447    } else if (createMode === 'ReFungible') {1448      const createData = {refungible: {pieces: 100}};1449      tx = api.tx.unique.createItem(collectionId, to, createData as any);1450    } else {1451      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1452      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1453    }14541455    const events = await submitTransactionAsync(sender, tx);1456    const result = getCreateItemResult(events);14571458    const itemCountAfter = await getLastTokenId(api, collectionId);1459    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14601461    if (createMode === 'NFT') {1462      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1463    }14641465    // What to expect1466    // tslint:disable-next-line:no-unused-expression1467    expect(result.success).to.be.true;1468    if (createMode === 'Fungible') {1469      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1470    } else {1471      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1472    }1473    expect(collectionId).to.be.equal(result.collectionId);1474    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1475    expect(to).to.be.deep.equal(result.recipient);1476    newItemId = result.itemId;1477  });1478  return newItemId;1479}14801481export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1482  await usingApi(async (api) => {14831484    let tx;1485    if (createMode === 'NFT') {1486      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1487      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1488    } else {1489      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1490    }149114921493    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1494    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1495    const result = getCreateItemResult(events);14961497    expect(result.success).to.be.false;1498  });1499}15001501export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1502  let newItemId = 0;1503  await usingApi(async (api) => {1504    const to = normalizeAccountId(owner);1505    const itemCountBefore = await getLastTokenId(api, collectionId);1506    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15071508    let tx;1509    if (createMode === 'Fungible') {1510      const createData = {fungible: {value: 10}};1511      tx = api.tx.unique.createItem(collectionId, to, createData as any);1512    } else if (createMode === 'ReFungible') {1513      const createData = {refungible: {pieces: 100}};1514      tx = api.tx.unique.createItem(collectionId, to, createData as any);1515    } else {1516      const createData = {nft: {}};1517      tx = api.tx.unique.createItem(collectionId, to, createData as any);1518    }15191520    const events = await executeTransaction(api, sender, tx);1521    const result = getCreateItemResult(events);15221523    const itemCountAfter = await getLastTokenId(api, collectionId);1524    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15251526    // What to expect1527    // tslint:disable-next-line:no-unused-expression1528    expect(result.success).to.be.true;1529    if (createMode === 'Fungible') {1530      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1531    } else {1532      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1533    }1534    expect(collectionId).to.be.equal(result.collectionId);1535    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1536    expect(to).to.be.deep.equal(result.recipient);1537    newItemId = result.itemId;1538  });1539  return newItemId;1540}15411542export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1543  const createData = {refungible: {pieces: amount}};1544  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15451546  const events = await submitTransactionAsync(sender, tx);1547  return  getCreateItemResult(events);1548}15491550export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1551  await usingApi(async (api) => {1552    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15531554    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1555    const result = getCreateItemResult(events);15561557    expect(result.success).to.be.false;1558  });1559}15601561export async function setPublicAccessModeExpectSuccess(1562  sender: IKeyringPair, collectionId: number,1563  accessMode: 'Normal' | 'AllowList',1564) {1565  await usingApi(async (api) => {15661567    // Run the transaction1568    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1569    const events = await submitTransactionAsync(sender, tx);1570    const result = getGenericResult(events);15711572    // Get the collection1573    const collection = await queryCollectionExpectSuccess(api, collectionId);15741575    // What to expect1576    // tslint:disable-next-line:no-unused-expression1577    expect(result.success).to.be.true;1578    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1579  });1580}15811582export async function setPublicAccessModeExpectFail(1583  sender: IKeyringPair, collectionId: number,1584  accessMode: 'Normal' | 'AllowList',1585) {1586  await usingApi(async (api) => {15871588    // Run the transaction1589    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1590    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1591    const result = getGenericResult(events);15921593    // What to expect1594    // tslint:disable-next-line:no-unused-expression1595    expect(result.success).to.be.false;1596  });1597}15981599export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1600  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1601}16021603export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1604  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1605}16061607export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1608  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1609}16101611export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1612  await usingApi(async (api) => {16131614    // Run the transaction1615    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1616    const events = await submitTransactionAsync(sender, tx);1617    const result = getGenericResult(events);1618    expect(result.success).to.be.true;16191620    // Get the collection1621    const collection = await queryCollectionExpectSuccess(api, collectionId);16221623    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1624  });1625}16261627export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1628  await setMintPermissionExpectSuccess(sender, collectionId, true);1629}16301631export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1632  await usingApi(async (api) => {1633    // Run the transaction1634    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1635    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1636    const result = getCreateCollectionResult(events);1637    // tslint:disable-next-line:no-unused-expression1638    expect(result.success).to.be.false;1639  });1640}16411642export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1643  await usingApi(async (api) => {1644    // Run the transaction1645    const tx = api.tx.unique.setChainLimits(limits);1646    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1647    const result = getCreateCollectionResult(events);1648    // tslint:disable-next-line:no-unused-expression1649    expect(result.success).to.be.false;1650  });1651}16521653export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1654  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1655}16561657export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1658  await usingApi(async (api) => {1659    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16601661    // Run the transaction1662    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1663    const events = await submitTransactionAsync(sender, tx);1664    const result = getGenericResult(events);1665    expect(result.success).to.be.true;16661667    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1668  });1669}16701671export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1672  await usingApi(async (api) => {16731674    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16751676    // Run the transaction1677    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1678    const events = await submitTransactionAsync(sender, tx);1679    const result = getGenericResult(events);1680    expect(result.success).to.be.true;16811682    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1683  });1684}16851686export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1687  await usingApi(async (api) => {16881689    // Run the transaction1690    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1691    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1692    const result = getGenericResult(events);16931694    // What to expect1695    // tslint:disable-next-line:no-unused-expression1696    expect(result.success).to.be.false;1697  });1698}16991700export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1701  await usingApi(async (api) => {1702    // Run the transaction1703    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1704    const events = await submitTransactionAsync(sender, tx);1705    const result = getGenericResult(events);17061707    // What to expect1708    // tslint:disable-next-line:no-unused-expression1709    expect(result.success).to.be.true;1710  });1711}17121713export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1714  await usingApi(async (api) => {1715    // Run the transaction1716    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1717    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1718    const result = getGenericResult(events);17191720    // What to expect1721    // tslint:disable-next-line:no-unused-expression1722    expect(result.success).to.be.false;1723  });1724}17251726export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1727  : Promise<UpDataStructsRpcCollection | null> => {1728  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1729};17301731export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1732  // set global object - collectionsCount1733  return (await api.rpc.unique.collectionStats()).created.toNumber();1734};17351736export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1737  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1738}17391740export async function waitNewBlocks(blocksCount = 1): Promise<void> {1741  await usingApi(async (api) => {1742    const promise = new Promise<void>(async (resolve) => {1743      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1744        if (blocksCount > 0) {1745          blocksCount--;1746        } else {1747          unsubscribe();1748          resolve();1749        }1750      });1751    });1752    return promise;1753  });1754}17551756export async function repartitionRFT(1757  api: ApiPromise,1758  collectionId: number,1759  sender: IKeyringPair,1760  tokenId: number,1761  amount: bigint,1762): Promise<boolean> {1763  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1764  const events = await submitTransactionAsync(sender, tx);1765  const result = getGenericResult(events);17661767  return result.success;1768}17691770export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1771  let i: any = it;1772  if (opts.only) i = i.only;1773  else if (opts.skip) i = i.skip;1774  i(name, async () => {1775    await usingApi(async (api, privateKeyWrapper) => {1776      await cb({api, privateKeyWrapper});1777    });1778  });1779}17801781itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1782itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});
after · tests/src/util/helpers.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 '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';31import {Context} from 'mocha';3233chai.use(chaiAsPromised);34const expect = chai.expect;3536export type CrossAccountId = {37  Substrate: string,38} | {39  Ethereum: string,40};414243export enum Pallets {44  Inflation = 'inflation',45  RmrkCore = 'rmrkcore',46  RmrkEquip = 'rmrkequip',47  ReFungible = 'refungible',48  Fungible = 'fungible',49  NFT = 'nonfungible',50  Scheduler = 'scheduler',51  AppPromotion = 'apppromotion',52}5354export async function isUnique(): Promise<boolean> {55  return usingApi(async api => {56    const chain = await api.rpc.system.chain();5758    return chain.eq('UNIQUE');59  });60}6162export async function isQuartz(): Promise<boolean> {63  return usingApi(async api => {64    const chain = await api.rpc.system.chain();65    66    return chain.eq('QUARTZ');67  });68}6970let modulesNames: any;71export function getModuleNames(api: ApiPromise): string[] {72  if (typeof modulesNames === 'undefined') 73    modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());74  return modulesNames;75}7677export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {78  return await usingApi(async api => {79    const pallets = getModuleNames(api);8081    return requiredPallets.filter(p => !pallets.includes(p));82  });83}8485export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {86  return (await missingRequiredPallets(requiredPallets)).length == 0;87}8889export async function requirePallets(mocha: Context, requiredPallets: string[]) {90  const missingPallets = await missingRequiredPallets(requiredPallets);9192  if (missingPallets.length > 0) {93    const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;94    const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;95    const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9697    console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);9899    mocha.skip();100  }101}102103export function bigIntToSub(api: ApiPromise, number: bigint) {104  return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();105}106107export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {108  if (typeof input === 'string') {109    if (input.length >= 47) {110      return {Substrate: input};111    } else if (input.length === 42 && input.startsWith('0x')) {112      return {Ethereum: input.toLowerCase()};113    } else if (input.length === 40 && !input.startsWith('0x')) {114      return {Ethereum: '0x' + input.toLowerCase()};115    } else {116      throw new Error(`Unknown address format: "${input}"`);117    }118  }119  if ('address' in input) {120    return {Substrate: input.address};121  }122  if ('Ethereum' in input) {123    return {124      Ethereum: input.Ethereum.toLowerCase(),125    };126  } else if ('ethereum' in input) {127    return {128      Ethereum: (input as any).ethereum.toLowerCase(),129    };130  } else if ('Substrate' in input) {131    return input;132  } else if ('substrate' in input) {133    return {134      Substrate: (input as any).substrate,135    };136  }137138  // AccountId139  return {Substrate: input.toString()};140}141export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {142  input = normalizeAccountId(input);143  if ('Substrate' in input) {144    return input.Substrate;145  } else {146    return evmToAddress(input.Ethereum);147  }148}149150export const U128_MAX = (1n << 128n) - 1n;151152const MICROUNIQUE = 1_000_000_000_000n;153const MILLIUNIQUE = 1_000n * MICROUNIQUE;154const CENTIUNIQUE = 10n * MILLIUNIQUE;155export const UNIQUE = 100n * CENTIUNIQUE;156157interface GenericResult<T> {158  success: boolean;159  data: T | null;160}161162interface CreateCollectionResult {163  success: boolean;164  collectionId: number;165}166167interface CreateItemResult {168  success: boolean;169  collectionId: number;170  itemId: number;171  recipient?: CrossAccountId;172  amount?: number;173}174175interface DestroyItemResult {176  success: boolean;177  collectionId: number;178  itemId: number;179  owner: CrossAccountId;180  amount: number;181}182183interface TransferResult {184  collectionId: number;185  itemId: number;186  sender?: CrossAccountId;187  recipient?: CrossAccountId;188  value: bigint;189}190191interface IReFungibleOwner {192  fraction: BN;193  owner: number[];194}195196interface IGetMessage {197  checkMsgUnqMethod: string;198  checkMsgTrsMethod: string;199  checkMsgSysMethod: string;200}201202export interface IFungibleTokenDataType {203  value: number;204}205206export interface IChainLimits {207  collectionNumbersLimit: number;208  accountTokenOwnershipLimit: number;209  collectionsAdminsLimit: number;210  customDataLimit: number;211  nftSponsorTransferTimeout: number;212  fungibleSponsorTransferTimeout: number;213  refungibleSponsorTransferTimeout: number;214  //offchainSchemaLimit: number;215  //constOnChainSchemaLimit: number;216}217218export interface IReFungibleTokenDataType {219  owner: IReFungibleOwner[];220}221222export function uniqueEventMessage(events: EventRecord[]): IGetMessage {223  let checkMsgUnqMethod = '';224  let checkMsgTrsMethod = '';225  let checkMsgSysMethod = '';226  events.forEach(({event: {method, section}}) => {227    if (section === 'common') {228      checkMsgUnqMethod = method;229    } else if (section === 'treasury') {230      checkMsgTrsMethod = method;231    } else if (section === 'system') {232      checkMsgSysMethod = method;233    } else { return null; }234  });235  const result: IGetMessage = {236    checkMsgUnqMethod,237    checkMsgTrsMethod,238    checkMsgSysMethod,239  };240  return result;241}242243export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {244  const event = events.find(r => check(r.event));245  if (!event) return;246  return event.event as T;247}248249export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;250export function getGenericResult<T>(251  events: EventRecord[],252  expectSection: string,253  expectMethod: string,254  extractAction: (data: GenericEventData) => T255): GenericResult<T>;256257export function getGenericResult<T>(258  events: EventRecord[],259  expectSection?: string,260  expectMethod?: string,261  extractAction?: (data: GenericEventData) => T,262): GenericResult<T> {263  let success = false;264  let successData = null;265266  events.forEach(({event: {data, method, section}}) => {267    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);268    if (method === 'ExtrinsicSuccess') {269      success = true;270    } else if ((expectSection == section) && (expectMethod == method)) {271      successData = extractAction!(data as any);272    }273  });274275  const result: GenericResult<T> = {276    success,277    data: successData,278  };279  return result;280}281282export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {283  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));284  const result: CreateCollectionResult = {285    success: genericResult.success,286    collectionId: genericResult.data ?? 0,287  };288  return result;289}290291export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {292  const results: CreateItemResult[] = [];293  294  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {295    const collectionId = parseInt(data[0].toString(), 10);296    const itemId = parseInt(data[1].toString(), 10);297    const recipient = normalizeAccountId(data[2].toJSON() as any);298    const amount = parseInt(data[3].toString(), 10);299300    const itemRes: CreateItemResult = {301      success: true,302      collectionId,303      itemId,304      recipient,305      amount,306    };307308    results.push(itemRes);309    return results;310  });311312  if (!genericResult.success) return [];313  return results;314}315316export function getCreateItemResult(events: EventRecord[]): CreateItemResult {317  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));318  319  if (genericResult.data == null) 320    return {321      success: genericResult.success,322      collectionId: 0,323      itemId: 0,324      amount: 0,325    };326  else 327    return {328      success: genericResult.success,329      collectionId: genericResult.data[0] as number,330      itemId: genericResult.data[1] as number,331      recipient: normalizeAccountId(genericResult.data![2] as any),332      amount: genericResult.data[3] as number,333    };334}335336export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {337  const results: DestroyItemResult[] = [];338  339  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {340    const collectionId = parseInt(data[0].toString(), 10);341    const itemId = parseInt(data[1].toString(), 10);342    const owner = normalizeAccountId(data[2].toJSON() as any);343    const amount = parseInt(data[3].toString(), 10);344345    const itemRes: DestroyItemResult = {346      success: true,347      collectionId,348      itemId,349      owner,350      amount,351    };352353    results.push(itemRes);354    return results;355  });356357  if (!genericResult.success) return [];358  return results;359}360361export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {362  for (const {event} of events) {363    if (api.events.common.Transfer.is(event)) {364      const [collection, token, sender, recipient, value] = event.data;365      return {366        collectionId: collection.toNumber(),367        itemId: token.toNumber(),368        sender: normalizeAccountId(sender.toJSON() as any),369        recipient: normalizeAccountId(recipient.toJSON() as any),370        value: value.toBigInt(),371      };372    }373  }374  throw new Error('no transfer event');375}376377interface Nft {378  type: 'NFT';379}380381interface Fungible {382  type: 'Fungible';383  decimalPoints: number;384}385386interface ReFungible {387  type: 'ReFungible';388}389390export type CollectionMode = Nft | Fungible | ReFungible;391392export type Property = {393  key: any,394  value: any,395};396397type Permission = {398  mutable: boolean;399  collectionAdmin: boolean;400  tokenOwner: boolean;401}402403type PropertyPermission = {404  key: any;405  permission: Permission;406}407408export type CreateCollectionParams = {409  mode: CollectionMode,410  name: string,411  description: string,412  tokenPrefix: string,413  properties?: Array<Property>,414  propPerm?: Array<PropertyPermission>415};416417const defaultCreateCollectionParams: CreateCollectionParams = {418  description: 'description',419  mode: {type: 'NFT'},420  name: 'name',421  tokenPrefix: 'prefix',422};423424export async function425createCollection(426  api: ApiPromise,427  sender: IKeyringPair,428  params: Partial<CreateCollectionParams> = {},429): Promise<CreateCollectionResult> {430  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};431432  let modeprm = {};433  if (mode.type === 'NFT') {434    modeprm = {nft: null};435  } else if (mode.type === 'Fungible') {436    modeprm = {fungible: mode.decimalPoints};437  } else if (mode.type === 'ReFungible') {438    modeprm = {refungible: null};439  }440441  const tx = api.tx.unique.createCollectionEx({442    name: strToUTF16(name),443    description: strToUTF16(description),444    tokenPrefix: strToUTF16(tokenPrefix),445    mode: modeprm as any,446  });447  const events = await executeTransaction(api, sender, tx);448  return getCreateCollectionResult(events);449}450451export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {452  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};453454  let collectionId = 0;455  await usingApi(async (api, privateKeyWrapper) => {456    // Get number of collections before the transaction457    const collectionCountBefore = await getCreatedCollectionCount(api);458459    // Run the CreateCollection transaction460    const alicePrivateKey = privateKeyWrapper('//Alice');461462    const result = await createCollection(api, alicePrivateKey, params);463464    // Get number of collections after the transaction465    const collectionCountAfter = await getCreatedCollectionCount(api);466467    // Get the collection468    const collection = await queryCollectionExpectSuccess(api, result.collectionId);469470    // What to expect471    // tslint:disable-next-line:no-unused-expression472    expect(result.success).to.be.true;473    expect(result.collectionId).to.be.equal(collectionCountAfter);474    // tslint:disable-next-line:no-unused-expression475    expect(collection).to.be.not.null;476    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');477    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));478    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);479    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);480    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);481482    collectionId = result.collectionId;483  });484485  return collectionId;486}487488export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {489  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};490491  let collectionId = 0;492  await usingApi(async (api, privateKeyWrapper) => {493    // Get number of collections before the transaction494    const collectionCountBefore = await getCreatedCollectionCount(api);495496    // Run the CreateCollection transaction497    const alicePrivateKey = privateKeyWrapper('//Alice');498499    let modeprm = {};500    if (mode.type === 'NFT') {501      modeprm = {nft: null};502    } else if (mode.type === 'Fungible') {503      modeprm = {fungible: mode.decimalPoints};504    } else if (mode.type === 'ReFungible') {505      modeprm = {refungible: null};506    }507508    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});509    const events = await submitTransactionAsync(alicePrivateKey, tx);510    const result = getCreateCollectionResult(events);511512    // Get number of collections after the transaction513    const collectionCountAfter = await getCreatedCollectionCount(api);514515    // Get the collection516    const collection = await queryCollectionExpectSuccess(api, result.collectionId);517518    // What to expect519    // tslint:disable-next-line:no-unused-expression520    expect(result.success).to.be.true;521    expect(result.collectionId).to.be.equal(collectionCountAfter);522    // tslint:disable-next-line:no-unused-expression523    expect(collection).to.be.not.null;524    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');525    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));526    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);527    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);528    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);529530531    collectionId = result.collectionId;532  });533534  return collectionId;535}536537export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {538  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};539540  await usingApi(async (api, privateKeyWrapper) => {541    // Get number of collections before the transaction542    const collectionCountBefore = await getCreatedCollectionCount(api);543544    // Run the CreateCollection transaction545    const alicePrivateKey = privateKeyWrapper('//Alice');546547    let modeprm = {};548    if (mode.type === 'NFT') {549      modeprm = {nft: null};550    } else if (mode.type === 'Fungible') {551      modeprm = {fungible: mode.decimalPoints};552    } else if (mode.type === 'ReFungible') {553      modeprm = {refungible: null};554    }555556    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});557    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;558559560    // Get number of collections after the transaction561    const collectionCountAfter = await getCreatedCollectionCount(api);562563    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');564  });565}566567export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {568  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};569570  let modeprm = {};571  if (mode.type === 'NFT') {572    modeprm = {nft: null};573  } else if (mode.type === 'Fungible') {574    modeprm = {fungible: mode.decimalPoints};575  } else if (mode.type === 'ReFungible') {576    modeprm = {refungible: null};577  }578579  await usingApi(async (api, privateKeyWrapper) => {580    // Get number of collections before the transaction581    const collectionCountBefore = await getCreatedCollectionCount(api);582583    // Run the CreateCollection transaction584    const alicePrivateKey = privateKeyWrapper('//Alice');585    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});586    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;587588    // Get number of collections after the transaction589    const collectionCountAfter = await getCreatedCollectionCount(api);590591    // What to expect592    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');593  });594}595596export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {597  let bal = 0n;598  let unused;599  do {600    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;601    unused = privateKeyWrapper(`//${randomSeed}`);602    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();603  } while (bal !== 0n);604  return unused;605}606607export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {608  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();609}610611export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {612  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));613}614615export async function findNotExistingCollection(api: ApiPromise): Promise<number> {616  const totalNumber = await getCreatedCollectionCount(api);617  const newCollection: number = totalNumber + 1;618  return newCollection;619}620621function getDestroyResult(events: EventRecord[]): boolean {622  let success = false;623  events.forEach(({event: {method}}) => {624    if (method == 'ExtrinsicSuccess') {625      success = true;626    }627  });628  return success;629}630631export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {632  await usingApi(async (api, privateKeyWrapper) => {633    // Run the DestroyCollection transaction634    const alicePrivateKey = privateKeyWrapper(senderSeed);635    const tx = api.tx.unique.destroyCollection(collectionId);636    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;637  });638}639640export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {641  await usingApi(async (api, privateKeyWrapper) => {642    // Run the DestroyCollection transaction643    const alicePrivateKey = privateKeyWrapper(senderSeed);644    const tx = api.tx.unique.destroyCollection(collectionId);645    const events = await submitTransactionAsync(alicePrivateKey, tx);646    const result = getDestroyResult(events);647    expect(result).to.be.true;648649    // What to expect650    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;651  });652}653654export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {655  await usingApi(async (api) => {656    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);657    const events = await submitTransactionAsync(sender, tx);658    const result = getGenericResult(events);659660    expect(result.success).to.be.true;661  });662}663664export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {665  await usingApi(async(api) => {666    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);667    const events = await submitTransactionAsync(sender, tx);668    const result = getGenericResult(events);669670    expect(result.success).to.be.true;671  });672};673674export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {675  await usingApi(async (api) => {676    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);677    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;678    const result = getGenericResult(events);679680    expect(result.success).to.be.false;681  });682}683684export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {685  await usingApi(async (api, privateKeyWrapper) => {686687    // Run the transaction688    const senderPrivateKey = privateKeyWrapper(sender);689    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);690    const events = await submitTransactionAsync(senderPrivateKey, tx);691    const result = getGenericResult(events);692693    // Get the collection694    const collection = await queryCollectionExpectSuccess(api, collectionId);695696    // What to expect697    expect(result.success).to.be.true;698    expect(collection.sponsorship.toJSON()).to.deep.equal({699      unconfirmed: sponsor,700    });701  });702}703704export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {705  await usingApi(async (api, privateKeyWrapper) => {706707    // Run the transaction708    const alicePrivateKey = privateKeyWrapper(sender);709    const tx = api.tx.unique.removeCollectionSponsor(collectionId);710    const events = await submitTransactionAsync(alicePrivateKey, tx);711    const result = getGenericResult(events);712713    // Get the collection714    const collection = await queryCollectionExpectSuccess(api, collectionId);715716    // What to expect717    expect(result.success).to.be.true;718    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});719  });720}721722export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {723  await usingApi(async (api, privateKeyWrapper) => {724725    // Run the transaction726    const alicePrivateKey = privateKeyWrapper(senderSeed);727    const tx = api.tx.unique.removeCollectionSponsor(collectionId);728    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;729  });730}731732export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {733  await usingApi(async (api, privateKeyWrapper) => {734735    // Run the transaction736    const alicePrivateKey = privateKeyWrapper(senderSeed);737    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);738    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;739  });740}741742export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {743  await usingApi(async (api, privateKeyWrapper) => {744745    // Run the transaction746    const sender = privateKeyWrapper(senderSeed);747    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);748  });749}750751export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {752  await usingApi(async (api, privateKeyWrapper) => {753754    // Run the transaction755    const tx = api.tx.unique.confirmSponsorship(collectionId);756    const events = await submitTransactionAsync(sender, tx);757    const result = getGenericResult(events);758759    // Get the collection760    const collection = await queryCollectionExpectSuccess(api, collectionId);761762    // What to expect763    expect(result.success).to.be.true;764    expect(collection.sponsorship.toJSON()).to.be.deep.equal({765      confirmed: sender.address,766    });767  });768}769770771export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {772  await usingApi(async (api, privateKeyWrapper) => {773774    // Run the transaction775    const sender = privateKeyWrapper(senderSeed);776    const tx = api.tx.unique.confirmSponsorship(collectionId);777    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;778  });779}780781export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {782  await usingApi(async (api) => {783    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);784    const events = await submitTransactionAsync(sender, tx);785    const result = getGenericResult(events);786787    expect(result.success).to.be.true;788  });789}790791export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {792  await usingApi(async (api) => {793    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);794    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;795    const result = getGenericResult(events);796797    expect(result.success).to.be.false;798  });799}800801export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {802803  await usingApi(async (api) => {804805    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);806    const events = await submitTransactionAsync(sender, tx);807    const result = getGenericResult(events);808809    expect(result.success).to.be.true;810  });811}812813export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {814815  await usingApi(async (api) => {816817    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);818    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;819    const result = getGenericResult(events);820821    expect(result.success).to.be.false;822  });823}824825export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {826  await usingApi(async (api) => {827    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);828    const events = await submitTransactionAsync(sender, tx);829    const result = getGenericResult(events);830831    expect(result.success).to.be.true;832  });833}834835export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {836  await usingApi(async (api) => {837    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);838    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;839    const result = getGenericResult(events);840841    expect(result.success).to.be.false;842  });843}844845export async function getNextSponsored(846  api: ApiPromise,847  collectionId: number,848  account: string | CrossAccountId,849  tokenId: number,850): Promise<number> {851  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));852}853854export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {855  await usingApi(async (api) => {856    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);857    const events = await submitTransactionAsync(sender, tx);858    const result = getGenericResult(events);859860    expect(result.success).to.be.true;861  });862}863864export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {865  let allowlisted = false;866  await usingApi(async (api) => {867    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;868  });869  return allowlisted;870}871872export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {873  await usingApi(async (api) => {874    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());875    const events = await submitTransactionAsync(sender, tx);876    const result = getGenericResult(events);877878    expect(result.success).to.be.true;879  });880}881882export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {883  await usingApi(async (api) => {884    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());885    const events = await submitTransactionAsync(sender, tx);886    const result = getGenericResult(events);887888    expect(result.success).to.be.true;889  });890}891892export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {893  await usingApi(async (api) => {894    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());895    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;896    const result = getGenericResult(events);897898    expect(result.success).to.be.false;899  });900}901902export interface CreateFungibleData {903  readonly Value: bigint;904}905906export interface CreateReFungibleData { }907export interface CreateNftData { }908909export type CreateItemData = {910  NFT: CreateNftData;911} | {912  Fungible: CreateFungibleData;913} | {914  ReFungible: CreateReFungibleData;915};916917export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {918  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);919  const events = await submitTransactionAsync(sender, tx);920  return getGenericResult(events).success;921}922923export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {924  await usingApi(async (api) => {925    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);926    // if burning token by admin - use adminButnItemExpectSuccess927    expect(balanceBefore >= BigInt(value)).to.be.true;928929    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;930931    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);932    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);933  });934}935936export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {937  await usingApi(async (api) => {938    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);939940    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;941    const result = getCreateCollectionResult(events);942    // tslint:disable-next-line:no-unused-expression943    expect(result.success).to.be.false;944  });945}946947export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {948  await usingApi(async (api) => {949    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);950    const events = await submitTransactionAsync(sender, tx);951    return getGenericResult(events).success;952  });953}954955export async function956approve(957  api: ApiPromise,958  collectionId: number,959  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,960) {961  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);962  const events = await submitTransactionAsync(owner, approveUniqueTx);963  return getGenericResult(events).success;964}965966export async function967approveExpectSuccess(968  collectionId: number,969  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,970) {971  await usingApi(async (api: ApiPromise) => {972    const result = await approve(api, collectionId, tokenId, owner, approved, amount);973    expect(result).to.be.true;974975    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));976  });977}978979export async function adminApproveFromExpectSuccess(980  collectionId: number,981  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,982) {983  await usingApi(async (api: ApiPromise) => {984    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);985    const events = await submitTransactionAsync(admin, approveUniqueTx);986    const result = getGenericResult(events);987    expect(result.success).to.be.true;988989    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));990  });991}992993export async function994transferFrom(995  api: ApiPromise,996  collectionId: number,997  tokenId: number,998  accountApproved: IKeyringPair,999  accountFrom: IKeyringPair | CrossAccountId,1000  accountTo: IKeyringPair | CrossAccountId,1001  value: number | bigint,1002) {1003  const from = normalizeAccountId(accountFrom);1004  const to = normalizeAccountId(accountTo);1005  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1006  const events = await submitTransactionAsync(accountApproved, transferFromTx);1007  return getGenericResult(events).success;1008}10091010export async function1011transferFromExpectSuccess(1012  collectionId: number,1013  tokenId: number,1014  accountApproved: IKeyringPair,1015  accountFrom: IKeyringPair | CrossAccountId,1016  accountTo: IKeyringPair | CrossAccountId,1017  value: number | bigint = 1,1018  type = 'NFT',1019) {1020  await usingApi(async (api: ApiPromise) => {1021    const from = normalizeAccountId(accountFrom);1022    const to = normalizeAccountId(accountTo);1023    let balanceBefore = 0n;1024    if (type === 'Fungible' || type === 'ReFungible') {1025      balanceBefore = await getBalance(api, collectionId, to, tokenId);1026    }1027    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1028    if (type === 'NFT') {1029      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1030    }1031    if (type === 'Fungible') {1032      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1033      if (JSON.stringify(to) !== JSON.stringify(from)) {1034        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1035      } else {1036        expect(balanceAfter).to.be.equal(balanceBefore);1037      }1038    }1039    if (type === 'ReFungible') {1040      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1041    }1042  });1043}10441045export async function1046transferFromExpectFail(1047  collectionId: number,1048  tokenId: number,1049  accountApproved: IKeyringPair,1050  accountFrom: IKeyringPair,1051  accountTo: IKeyringPair,1052  value: number | bigint = 1,1053) {1054  await usingApi(async (api: ApiPromise) => {1055    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1056    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1057    const result = getCreateCollectionResult(events);1058    // tslint:disable-next-line:no-unused-expression1059    expect(result.success).to.be.false;1060  });1061}10621063/* eslint no-async-promise-executor: "off" */1064export async function getBlockNumber(api: ApiPromise): Promise<number> {1065  return new Promise<number>(async (resolve) => {1066    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1067      unsubscribe();1068      resolve(head.number.toNumber());1069    });1070  });1071}10721073export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1074  await usingApi(async (api) => {1075    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1076    const events = await submitTransactionAsync(sender, changeAdminTx);1077    const result = getCreateCollectionResult(events);1078    expect(result.success).to.be.true;1079  });1080}10811082export async function adminApproveFromExpectFail(1083  collectionId: number,1084  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1085) {1086  await usingApi(async (api: ApiPromise) => {1087    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1088    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1089    const result = getGenericResult(events);1090    expect(result.success).to.be.false;1091  });1092}10931094export async function1095getFreeBalance(account: IKeyringPair): Promise<bigint> {1096  let balance = 0n;1097  await usingApi(async (api) => {1098    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1099  });11001101  return balance;1102}11031104export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1105  const tx = api.tx.balances.transfer(target, amount);1106  const events = await submitTransactionAsync(source, tx);1107  const result = getGenericResult(events);1108  expect(result.success).to.be.true;1109}11101111export async function1112scheduleExpectSuccess(1113  operationTx: any,1114  sender: IKeyringPair,1115  blockSchedule: number,1116  scheduledId: string,1117  period = 1,1118  repetitions = 1,1119) {1120  await usingApi(async (api: ApiPromise) => {1121    const blockNumber: number | undefined = await getBlockNumber(api);1122    const expectedBlockNumber = blockNumber + blockSchedule;11231124    expect(blockNumber).to.be.greaterThan(0);1125    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1126      scheduledId,1127      expectedBlockNumber, 1128      repetitions > 1 ? [period, repetitions] : null, 1129      0, 1130      {Value: operationTx as any},1131    );11321133    const events = await submitTransactionAsync(sender, scheduleTx);1134    expect(getGenericResult(events).success).to.be.true;1135  });1136}11371138export async function1139scheduleExpectFailure(1140  operationTx: any,1141  sender: IKeyringPair,1142  blockSchedule: number,1143  scheduledId: string,1144  period = 1,1145  repetitions = 1,1146) {1147  await usingApi(async (api: ApiPromise) => {1148    const blockNumber: number | undefined = await getBlockNumber(api);1149    const expectedBlockNumber = blockNumber + blockSchedule;11501151    expect(blockNumber).to.be.greaterThan(0);1152    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1153      scheduledId,1154      expectedBlockNumber, 1155      repetitions <= 1 ? null : [period, repetitions], 1156      0, 1157      {Value: operationTx as any},1158    );11591160    //const events = 1161    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1162    //expect(getGenericResult(events).success).to.be.false;1163  });1164}11651166export async function1167scheduleTransferAndWaitExpectSuccess(1168  collectionId: number,1169  tokenId: number,1170  sender: IKeyringPair,1171  recipient: IKeyringPair,1172  value: number | bigint = 1,1173  blockSchedule: number,1174  scheduledId: string,1175) {1176  await usingApi(async (api: ApiPromise) => {1177    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11781179    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11801181    // sleep for n + 1 blocks1182    await waitNewBlocks(blockSchedule + 1);11831184    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11851186    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1187    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1188  });1189}11901191export async function1192scheduleTransferExpectSuccess(1193  collectionId: number,1194  tokenId: number,1195  sender: IKeyringPair,1196  recipient: IKeyringPair,1197  value: number | bigint = 1,1198  blockSchedule: number,1199  scheduledId: string,1200) {1201  await usingApi(async (api: ApiPromise) => {1202    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12031204    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12051206    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1207  });1208}12091210export async function1211scheduleTransferFundsPeriodicExpectSuccess(1212  amount: bigint,1213  sender: IKeyringPair,1214  recipient: IKeyringPair,1215  blockSchedule: number,1216  scheduledId: string,1217  period: number,1218  repetitions: number,1219) {1220  await usingApi(async (api: ApiPromise) => {1221    const transferTx = api.tx.balances.transfer(recipient.address, amount);12221223    const balanceBefore = await getFreeBalance(recipient);1224    1225    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12261227    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1228  });1229}12301231export async function1232transfer(1233  api: ApiPromise,1234  collectionId: number,1235  tokenId: number,1236  sender: IKeyringPair,1237  recipient: IKeyringPair | CrossAccountId,1238  value: number | bigint,1239) : Promise<boolean> {1240  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1241  const events = await executeTransaction(api, sender, transferTx);1242  return getGenericResult(events).success;1243}12441245export async function1246transferExpectSuccess(1247  collectionId: number,1248  tokenId: number,1249  sender: IKeyringPair,1250  recipient: IKeyringPair | CrossAccountId,1251  value: number | bigint = 1,1252  type = 'NFT',1253) {1254  await usingApi(async (api: ApiPromise) => {1255    const from = normalizeAccountId(sender);1256    const to = normalizeAccountId(recipient);12571258    let balanceBefore = 0n;1259    if (type === 'Fungible' || type === 'ReFungible') {1260      balanceBefore = await getBalance(api, collectionId, to, tokenId);1261    }12621263    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1264    const events = await executeTransaction(api, sender, transferTx);1265    const result = getTransferResult(api, events);12661267    expect(result.collectionId).to.be.equal(collectionId);1268    expect(result.itemId).to.be.equal(tokenId);1269    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1270    expect(result.recipient).to.be.deep.equal(to);1271    expect(result.value).to.be.equal(BigInt(value));12721273    if (type === 'NFT') {1274      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1275    }1276    if (type === 'Fungible' || type === 'ReFungible') {1277      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1278      if (JSON.stringify(to) !== JSON.stringify(from)) {1279        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1280      } else {1281        expect(balanceAfter).to.be.equal(balanceBefore);1282      }1283    }1284  });1285}12861287export async function1288transferExpectFailure(1289  collectionId: number,1290  tokenId: number,1291  sender: IKeyringPair,1292  recipient: IKeyringPair | CrossAccountId,1293  value: number | bigint = 1,1294) {1295  await usingApi(async (api: ApiPromise) => {1296    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1297    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1298    const result = getGenericResult(events);1299    // if (events && Array.isArray(events)) {1300    //   const result = getCreateCollectionResult(events);1301    // tslint:disable-next-line:no-unused-expression1302    expect(result.success).to.be.false;1303    //}1304  });1305}13061307export async function1308approveExpectFail(1309  collectionId: number,1310  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1311) {1312  await usingApi(async (api: ApiPromise) => {1313    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1314    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1315    const result = getCreateCollectionResult(events);1316    // tslint:disable-next-line:no-unused-expression1317    expect(result.success).to.be.false;1318  });1319}13201321export async function getBalance(1322  api: ApiPromise,1323  collectionId: number,1324  owner: string | CrossAccountId | IKeyringPair,1325  token: number,1326): Promise<bigint> {1327  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1328}1329export async function getTokenOwner(1330  api: ApiPromise,1331  collectionId: number,1332  token: number,1333): Promise<CrossAccountId> {1334  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1335  if (owner == null) throw new Error('owner == null');1336  return normalizeAccountId(owner);1337}1338export async function getTopmostTokenOwner(1339  api: ApiPromise,1340  collectionId: number,1341  token: number,1342): Promise<CrossAccountId> {1343  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1344  if (owner == null) throw new Error('owner == null');1345  return normalizeAccountId(owner);1346}1347export async function getTokenChildren(1348  api: ApiPromise,1349  collectionId: number,1350  tokenId: number,1351): Promise<UpDataStructsTokenChild[]> {1352  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1353}1354export async function isTokenExists(1355  api: ApiPromise,1356  collectionId: number,1357  token: number,1358): Promise<boolean> {1359  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1360}1361export async function getLastTokenId(1362  api: ApiPromise,1363  collectionId: number,1364): Promise<number> {1365  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1366}1367export async function getAdminList(1368  api: ApiPromise,1369  collectionId: number,1370): Promise<string[]> {1371  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1372}1373export async function getTokenProperties(1374  api: ApiPromise,1375  collectionId: number,1376  tokenId: number,1377  propertyKeys: string[],1378): Promise<UpDataStructsProperty[]> {1379  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1380}13811382export async function createFungibleItemExpectSuccess(1383  sender: IKeyringPair,1384  collectionId: number,1385  data: CreateFungibleData,1386  owner: CrossAccountId | string = sender.address,1387) {1388  return await usingApi(async (api) => {1389    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13901391    const events = await submitTransactionAsync(sender, tx);1392    const result = getCreateItemResult(events);13931394    expect(result.success).to.be.true;1395    return result.itemId;1396  });1397}13981399export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1400  await usingApi(async (api) => {1401    const to = normalizeAccountId(owner);1402    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14031404    const events = await submitTransactionAsync(sender, tx);1405    expect(getGenericResult(events).success).to.be.true;1406  });1407}14081409export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1410  await usingApi(async (api) => {1411    const to = normalizeAccountId(owner);1412    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14131414    const events = await submitTransactionAsync(sender, tx);1415    const result = getCreateItemsResult(events);14161417    for (const res of result) {1418      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1419    }1420  });1421}14221423export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1424  await usingApi(async (api) => {1425    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14261427    const events = await submitTransactionAsync(sender, tx);1428    const result = getCreateItemsResult(events);14291430    for (const res of result) {1431      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1432    }1433  });1434}14351436export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1437  let newItemId = 0;1438  await usingApi(async (api) => {1439    const to = normalizeAccountId(owner);1440    const itemCountBefore = await getLastTokenId(api, collectionId);1441    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14421443    let tx;1444    if (createMode === 'Fungible') {1445      const createData = {fungible: {value: 10}};1446      tx = api.tx.unique.createItem(collectionId, to, createData as any);1447    } else if (createMode === 'ReFungible') {1448      const createData = {refungible: {pieces: 100}};1449      tx = api.tx.unique.createItem(collectionId, to, createData as any);1450    } else {1451      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1452      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1453    }14541455    const events = await submitTransactionAsync(sender, tx);1456    const result = getCreateItemResult(events);14571458    const itemCountAfter = await getLastTokenId(api, collectionId);1459    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14601461    if (createMode === 'NFT') {1462      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1463    }14641465    // What to expect1466    // tslint:disable-next-line:no-unused-expression1467    expect(result.success).to.be.true;1468    if (createMode === 'Fungible') {1469      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1470    } else {1471      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1472    }1473    expect(collectionId).to.be.equal(result.collectionId);1474    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1475    expect(to).to.be.deep.equal(result.recipient);1476    newItemId = result.itemId;1477  });1478  return newItemId;1479}14801481export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1482  await usingApi(async (api) => {14831484    let tx;1485    if (createMode === 'NFT') {1486      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1487      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1488    } else {1489      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1490    }149114921493    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1494    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1495    const result = getCreateItemResult(events);14961497    expect(result.success).to.be.false;1498  });1499}15001501export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1502  let newItemId = 0;1503  await usingApi(async (api) => {1504    const to = normalizeAccountId(owner);1505    const itemCountBefore = await getLastTokenId(api, collectionId);1506    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15071508    let tx;1509    if (createMode === 'Fungible') {1510      const createData = {fungible: {value: 10}};1511      tx = api.tx.unique.createItem(collectionId, to, createData as any);1512    } else if (createMode === 'ReFungible') {1513      const createData = {refungible: {pieces: 100}};1514      tx = api.tx.unique.createItem(collectionId, to, createData as any);1515    } else {1516      const createData = {nft: {}};1517      tx = api.tx.unique.createItem(collectionId, to, createData as any);1518    }15191520    const events = await executeTransaction(api, sender, tx);1521    const result = getCreateItemResult(events);15221523    const itemCountAfter = await getLastTokenId(api, collectionId);1524    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15251526    // What to expect1527    // tslint:disable-next-line:no-unused-expression1528    expect(result.success).to.be.true;1529    if (createMode === 'Fungible') {1530      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1531    } else {1532      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1533    }1534    expect(collectionId).to.be.equal(result.collectionId);1535    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1536    expect(to).to.be.deep.equal(result.recipient);1537    newItemId = result.itemId;1538  });1539  return newItemId;1540}15411542export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1543  const createData = {refungible: {pieces: amount}};1544  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15451546  const events = await submitTransactionAsync(sender, tx);1547  return  getCreateItemResult(events);1548}15491550export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1551  await usingApi(async (api) => {1552    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15531554    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1555    const result = getCreateItemResult(events);15561557    expect(result.success).to.be.false;1558  });1559}15601561export async function setPublicAccessModeExpectSuccess(1562  sender: IKeyringPair, collectionId: number,1563  accessMode: 'Normal' | 'AllowList',1564) {1565  await usingApi(async (api) => {15661567    // Run the transaction1568    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1569    const events = await submitTransactionAsync(sender, tx);1570    const result = getGenericResult(events);15711572    // Get the collection1573    const collection = await queryCollectionExpectSuccess(api, collectionId);15741575    // What to expect1576    // tslint:disable-next-line:no-unused-expression1577    expect(result.success).to.be.true;1578    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1579  });1580}15811582export async function setPublicAccessModeExpectFail(1583  sender: IKeyringPair, collectionId: number,1584  accessMode: 'Normal' | 'AllowList',1585) {1586  await usingApi(async (api) => {15871588    // Run the transaction1589    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1590    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1591    const result = getGenericResult(events);15921593    // What to expect1594    // tslint:disable-next-line:no-unused-expression1595    expect(result.success).to.be.false;1596  });1597}15981599export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1600  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1601}16021603export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1604  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1605}16061607export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1608  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1609}16101611export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1612  await usingApi(async (api) => {16131614    // Run the transaction1615    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1616    const events = await submitTransactionAsync(sender, tx);1617    const result = getGenericResult(events);1618    expect(result.success).to.be.true;16191620    // Get the collection1621    const collection = await queryCollectionExpectSuccess(api, collectionId);16221623    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1624  });1625}16261627export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1628  await setMintPermissionExpectSuccess(sender, collectionId, true);1629}16301631export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1632  await usingApi(async (api) => {1633    // Run the transaction1634    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1635    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1636    const result = getCreateCollectionResult(events);1637    // tslint:disable-next-line:no-unused-expression1638    expect(result.success).to.be.false;1639  });1640}16411642export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1643  await usingApi(async (api) => {1644    // Run the transaction1645    const tx = api.tx.unique.setChainLimits(limits);1646    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1647    const result = getCreateCollectionResult(events);1648    // tslint:disable-next-line:no-unused-expression1649    expect(result.success).to.be.false;1650  });1651}16521653export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1654  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1655}16561657export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1658  await usingApi(async (api) => {1659    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16601661    // Run the transaction1662    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1663    const events = await submitTransactionAsync(sender, tx);1664    const result = getGenericResult(events);1665    expect(result.success).to.be.true;16661667    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1668  });1669}16701671export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1672  await usingApi(async (api) => {16731674    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16751676    // Run the transaction1677    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1678    const events = await submitTransactionAsync(sender, tx);1679    const result = getGenericResult(events);1680    expect(result.success).to.be.true;16811682    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1683  });1684}16851686export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1687  await usingApi(async (api) => {16881689    // Run the transaction1690    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1691    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1692    const result = getGenericResult(events);16931694    // What to expect1695    // tslint:disable-next-line:no-unused-expression1696    expect(result.success).to.be.false;1697  });1698}16991700export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1701  await usingApi(async (api) => {1702    // Run the transaction1703    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1704    const events = await submitTransactionAsync(sender, tx);1705    const result = getGenericResult(events);17061707    // What to expect1708    // tslint:disable-next-line:no-unused-expression1709    expect(result.success).to.be.true;1710  });1711}17121713export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1714  await usingApi(async (api) => {1715    // Run the transaction1716    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1717    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1718    const result = getGenericResult(events);17191720    // What to expect1721    // tslint:disable-next-line:no-unused-expression1722    expect(result.success).to.be.false;1723  });1724}17251726export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1727  : Promise<UpDataStructsRpcCollection | null> => {1728  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1729};17301731export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1732  // set global object - collectionsCount1733  return (await api.rpc.unique.collectionStats()).created.toNumber();1734};17351736export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1737  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1738}17391740export async function waitNewBlocks(blocksCount = 1): Promise<void> {1741  await usingApi(async (api) => {1742    const promise = new Promise<void>(async (resolve) => {1743      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1744        if (blocksCount > 0) {1745          blocksCount--;1746        } else {1747          unsubscribe();1748          resolve();1749        }1750      });1751    });1752    return promise;1753  });1754}17551756export async function repartitionRFT(1757  api: ApiPromise,1758  collectionId: number,1759  sender: IKeyringPair,1760  tokenId: number,1761  amount: bigint,1762): Promise<boolean> {1763  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1764  const events = await submitTransactionAsync(sender, tx);1765  const result = getGenericResult(events);17661767  return result.success;1768}17691770export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1771  let i: any = it;1772  if (opts.only) i = i.only;1773  else if (opts.skip) i = i.skip;1774  i(name, async () => {1775    await usingApi(async (api, privateKeyWrapper) => {1776      await cb({api, privateKeyWrapper});1777    });1778  });1779}17801781itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1782itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -2008,7 +2008,7 @@
     if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;
     const stakeResult = await this.helper.executeExtrinsic(
       signer,
-      'api.tx.promotion.stake', [amountToStake],
+      'api.tx.appPromotion.stake', [amountToStake],
       true, `stake failed for ${label}`,
     );
     // TODO extract info from stakeResult
@@ -2026,7 +2026,7 @@
     if(typeof label === 'undefined') label = `${signer.address}`;
     const unstakeResult = await this.helper.executeExtrinsic(
       signer,
-      'api.tx.promotion.unstake', [],
+      'api.tx.appPromotion.unstake', [],
       true, `unstake failed for ${label}`,
     );
     // TODO extract info from unstakeResult