git.delta.rocks / unique-network / refs/commits / 7586abb798e7

difftreelog

Use itEth

Max Andreev2022-09-15parent: #0c093d5.patch.diff
in: master

2 files changed

modifiedtests/src/app-promotion.test.tsdiffbeforeafterboth
--- a/tests/src/app-promotion.test.ts
+++ b/tests/src/app-promotion.test.ts
@@ -27,8 +27,9 @@
 
 import {encodeAddress} from '@polkadot/util-crypto';
 import {stringToU8a} from '@polkadot/util';
-import {SponsoringMode, contractHelpers, createEthAccountWithBalance, deployFlipper, itWeb3, transferBalanceToEth} from './eth/util/helpers';
+import {SponsoringMode} from './eth/util/helpers';
 import {DevUniqueHelper} from './util/playgrounds/unique.dev';
+import {itEth} from './eth/util/playgrounds';
 chai.use(chaiAsPromised);
 const expect = chai.expect;
 
@@ -38,7 +39,7 @@
 const palletAddress = calculatePalleteAddress('appstake');
 let accounts: IKeyringPair[] = [];
 const LOCKING_PERIOD = 20n; // 20 blocks of relay
-const UNLOCKING_PERIOD = 10n; // 20 blocks of parachain
+const UNLOCKING_PERIOD = 10n; // 10 blocks of parachain
 const rewardAvailableInBlock = (stakedInBlock: bigint) => (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);
 
 const beforeEach = async (context: Mocha.Context) => {
@@ -64,13 +65,13 @@
     const totalStakedBefore = await helper.staking.getTotalStaked();
 
     // Minimum stake amount is 100:
-    await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.eventually.rejected;
+    await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;
     await helper.staking.stake(staker, 100n * nominal);
 
     // Staker balance is: miscFrozen: 100, feeFrozen: 100, reserved: 0n...
     // ...so he can not transfer 900
     expect (await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});
-    await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejected;
+    await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');
     
     expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);
     expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
@@ -95,7 +96,7 @@
     expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);
     expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);
 
-    await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejected;
+    await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');
 
     // After unstake can stake again
     await helper.staking.unstake(staker);
@@ -107,11 +108,11 @@
     const staker = accounts.pop()!;
 
     // Can't stake full balance because Alice needs to pay some fee
-    await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.eventually.rejected;
+    await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected;
     await helper.staking.stake(staker, 500n * nominal);
 
     // Can't stake 500 tkn because Alice has Less than 500 transferable;
-    await expect(helper.staking.stake(staker, 500n * nominal)).to.be.eventually.rejected; 
+    await expect(helper.staking.stake(staker, 500n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions'); 
     expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);
   });
   
@@ -119,7 +120,7 @@
     const crowd = [accounts.pop()!, accounts.pop()!, accounts.pop()!, accounts.pop()!];
       
     const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));
-    await expect(Promise.all(crowdStartsToStake)).to.be.eventually.fulfilled;
+    await expect(Promise.all(crowdStartsToStake)).to.be.fulfilled;
 
     const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));
     expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);
@@ -140,7 +141,7 @@
     // Right after unstake balance is reserved
     // Staker can not transfer 
     expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 900n * nominal, miscFrozen: 0n, feeFrozen: 0n});
-    await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejected;
+    await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.InsufficientBalance');
     expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(900n * nominal);
     expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
     expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);
@@ -246,11 +247,11 @@
   itSub('can be set by sudo only', 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.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;
+    await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.rejected;
+    await expect(helper.signTransaction(nonAdmin, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.rejected;
 
     // Alice can
-    await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.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.fulfilled;
   });
   
   itSub('can be any valid CrossAccountId', async ({helper}) => {
@@ -259,23 +260,23 @@
     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.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;
+    await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.fulfilled;
+    await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.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.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;
+    await expect(helper.signTransaction(account, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
   });
 
   itSub('can be reassigned', async ({helper}) => {
     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.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(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(oldAdmin))))).to.be.fulfilled;
+    await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(newAdmin))))).to.be.fulfilled;
+    await expect(helper.signTransaction(oldAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
       
-    await expect(helper.signTransaction(newAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.fulfilled;
+    await expect(helper.signTransaction(newAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
   });
 });
 
@@ -309,7 +310,7 @@
 
     const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
       
-    await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;
+    await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
     expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');
   });
 
@@ -318,19 +319,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.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.eventually.fulfilled;
+    await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.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.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.eventually.fulfilled;
+    await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.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.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.eventually.fulfilled;
+    await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;
     expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
   });
 
@@ -339,7 +340,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.appPromotion.sponsorCollection(collectionId))).to.be.eventually.fulfilled;
+    await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;
       
     // Collection limits still can be changed by the owner
     expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;
@@ -355,7 +356,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.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.eventually.fulfilled;
+    await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;
     expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);
   });
   
@@ -363,12 +364,12 @@
     const collectionOwner = accounts.pop()!;
       
     // collection has never existed
-    await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(999999999))).to.be.eventually.rejected;
+    await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(999999999))).to.be.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.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;
+    await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
   });
 });
 
@@ -381,9 +382,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.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.fulfilled;
+    await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
       
-    await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;
+    await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
     expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
   });
 
@@ -409,7 +410,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.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;
+    await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
       
     expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});
   });
@@ -419,8 +420,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.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;
-    await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(999999999))).to.be.eventually.rejected;
+    await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
+    await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(999999999))).to.be.rejected;
   });
 });
 
@@ -429,122 +430,119 @@
     await beforeEach(this);
   });
 
-  itWeb3('should set palletes address as a sponsor', async ({api, web3, privateKeyWrapper}) => {
-    await usingPlaygrounds(async (helper) => {
-      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
-      const flipper = await deployFlipper(web3, contractOwner);
-      const contractMethods = contractHelpers(web3, contractOwner);
+  itEth('should set palletes address as a sponsor', async ({helper}) => {
+    const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+    const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
+    const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
 
-      await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(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);  
-      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
-        confirmed: {
-          substrate: palletAddress,
-        },
-      });
+    await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);
+    
+    expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;  
+    expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);  
+    expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+      confirmed: {
+        substrate: palletAddress,
+      },
     });
   });
 
-  itWeb3('should overwrite sponsoring mode and existed sponsor', async ({api, web3, privateKeyWrapper}) => {
-    await usingPlaygrounds(async (helper) => {
-      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
-      const flipper = await deployFlipper(web3, contractOwner);
-      const contractMethods = contractHelpers(web3, contractOwner);
+  itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {
+    const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+    const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
+    const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
 
-      await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
+    await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;
 
-      // Contract is self sponsored
-      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.be.deep.equal({
-        confirmed: {
-          ethereum: flipper.options.address.toLowerCase(),
-        },
-      });
+    // Contract is self sponsored
+    expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.be.deep.equal({
+      confirmed: {
+        ethereum: flipper.options.address.toLowerCase(),
+      },
+    });
 
-      // set promotion sponsoring
-      await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));
+    // set promotion sponsoring
+    await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);
 
-      // new sponsor is pallet 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);  
-      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
-        confirmed: {
-          substrate: palletAddress,
-        },
-      });
+    // new sponsor is pallet address
+    expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;  
+    expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);  
+    expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+      confirmed: {
+        substrate: palletAddress,
+      },
     });
   });
 
-  itWeb3('can be overwritten by contract owner', async ({api, web3, privateKeyWrapper}) => {
-    await usingPlaygrounds(async (helper) => {      
-      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
-      const flipper = await deployFlipper(web3, contractOwner);
-      const contractMethods = contractHelpers(web3, contractOwner);
+  itEth('can be overwritten by contract owner', async ({helper}) => {
+    const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+    const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
+    const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
 
-      // contract sponsored by pallet
-      await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));
+    // contract sponsored by pallet
+    await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);
 
-      // owner sets self sponsoring
-      await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
+    // owner sets self sponsoring
+    await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
 
-      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);  
-      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
-        confirmed: {
-          ethereum: flipper.options.address.toLowerCase(),
-        },
-      });
+    expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;  
+    expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);  
+    expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+      confirmed: {
+        ethereum: flipper.options.address.toLowerCase(),
+      },
     });
   });
 
-  itWeb3('can not be set by non admin', async ({api, web3, privateKeyWrapper}) => {
-    await usingPlaygrounds(async (helper) => {      
-      const nonAdmin = accounts.pop()!;
-      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
-      const flipper = await deployFlipper(web3, contractOwner);
-      const contractMethods = contractHelpers(web3, contractOwner);
+  itEth('can not be set by non admin', async ({helper}) => {
+    const nonAdmin = accounts.pop()!;
+    const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+    const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
+    const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
 
-      await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
+    await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;
 
-      // nonAdmin calls sponsorContract
-      await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address))).to.be.rejected;
+    // nonAdmin calls sponsorContract
+    await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');
 
-      // contract still self-sponsored 
-      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
-        confirmed: {
-          ethereum: flipper.options.address.toLowerCase(),
-        },
-      });
+    // contract still self-sponsored 
+    expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+      confirmed: {
+        ethereum: flipper.options.address.toLowerCase(),
+      },
     });
+  });
 
-    itWeb3('should be rejected for non-contract address', async ({api, web3, privateKeyWrapper}) => {
-      await usingPlaygrounds(async (helper) => {
+  itEth('should actually sponsor transactions', async ({helper}) => {
+    // Contract caller
+    const caller = await helper.eth.createAccountWithBalance(alice, 1000n);
+    const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);
+        
+    // Deploy flipper
+    const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+    const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
+    const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+    
+    // Owner sets to sponsor every tx
+    await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});
+    await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});
+    await helper.eth.transferBalanceFromSubstrate(alice, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);
 
-      });
-    });
-  });
+    // Set promotion to the Flipper
+    await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorContract(flipper.options.address));
 
-  itWeb3('should actually sponsor transactions', async ({api, web3, privateKeyWrapper}) => {
-    await usingPlaygrounds(async (helper) => {      
-      const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
-      const flipper = await deployFlipper(web3, contractOwner);
-      const contractHelper = contractHelpers(web3, contractOwner);
-      await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});
-      await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});
-      await transferBalanceToEth(api, alice, flipper.options.address, 1000n);
+    // Caller calls Flipper
+    await flipper.methods.flip().send({from: caller});
+    expect(await flipper.methods.getValue().call()).to.be.true;
 
-      await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));
-      await flipper.methods.flip().send({from: caller});
-      expect(await flipper.methods.getValue().call()).to.be.true;
+    // The contracts and caller balances have not changed
+    const callerBalance = await helper.balance.getEthereum(caller);
+    const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);
+    expect(callerBalance).to.be.equal(1000n * nominal);
+    expect(1000n * nominal === contractBalanceAfter).to.be.true;
 
-      const callerBalance = await helper.balance.getEthereum(caller);
-      const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);
-
-      expect(callerBalance).to.be.equal(1000n * nominal);
-      expect(1000n * nominal > contractBalanceAfter).to.be.true;
-    });
+    // The pallet balance has decreased
+    const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);
+    expect(palletBalanceAfter < palletBalanceBefore).to.be.true;
   });
 });
 
@@ -553,56 +551,53 @@
     await beforeEach(this);
   });
 
-  itWeb3('should remove pallet address from contract sponsors', async ({api, web3, privateKeyWrapper}) => {
-    await usingPlaygrounds(async (helper) => {      
-      const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
-      const flipper = await deployFlipper(web3, contractOwner);
-      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.appPromotion.sponsorContract(flipper.options.address));
-      await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringContract(flipper.options.address));
+  itEth('should remove pallet address from contract sponsors', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(alice, 1000n);
+    const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+    const flipper = await helper.eth.deployFlipper(contractOwner);
+    await helper.eth.transferBalanceFromSubstrate(alice, flipper.options.address);
+    const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
 
-      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);  
-      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
-        disabled: null,
-      });
+    await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});
+    await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);
+    await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);
 
-      await flipper.methods.flip().send({from: caller});
-      expect(await flipper.methods.getValue().call()).to.be.true;
+    expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;  
+    expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);  
+    expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+      disabled: null,
+    });
 
-      const callerBalance = await helper.balance.getEthereum(caller);
-      const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);
+    await flipper.methods.flip().send({from: caller});
+    expect(await flipper.methods.getValue().call()).to.be.true;
 
-      // caller payed for call
-      expect(1000n * nominal > callerBalance).to.be.true;
-      expect(contractBalanceAfter).to.be.equal(1000n * nominal);
-    });
+    const callerBalance = await helper.balance.getEthereum(caller);
+    const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);
+
+    // caller payed for call
+    expect(1000n * nominal > callerBalance).to.be.true;
+    expect(contractBalanceAfter).to.be.equal(1000n * nominal);
   });
 
-  itWeb3('can not be called by non-admin', async ({api, web3, privateKeyWrapper}) => {
-    await usingPlaygrounds(async (helper) => {      
-      const nonAdmin = accounts.pop()!;
-      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
-      const flipper = await deployFlipper(web3, contractOwner);
+  itEth('can not be called by non-admin', async ({helper}) => {
+    const nonAdmin = accounts.pop()!;
+    const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+    const flipper = await helper.eth.deployFlipper(contractOwner);
 
-      await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));
-      await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringContract(flipper.options.address))).to.be.rejected;
-    });
+    await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);
+    const stopSponsoringResult = await helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]);
+    expect(stopSponsoringResult.status).to.equal('Fail');
+    expect(stopSponsoringResult.moduleError).to.equal('appPromotion.NoPermission');
   });
 
-  itWeb3('should not affect a contract which is not sponsored by pallete', async ({api, web3, privateKeyWrapper}) => {
-    await usingPlaygrounds(async (helper) => {      
-      const nonAdmin = accounts.pop()!;
-      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
-      const flipper = await deployFlipper(web3, contractOwner);
-      const contractHelper = contractHelpers(web3, contractOwner);
-      await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
+  itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {
+    const nonAdmin = accounts.pop()!;
+    const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+    const flipper = await helper.eth.deployFlipper(contractOwner);
+    const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+    await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;
 
-      await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringContract(flipper.options.address))).to.be.rejected;
-    });
+    await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');
   });
 });
 
modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
before · tests/src/eth/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable function-call-argument-newline */5// eslint-disable-next-line @typescript-eslint/triple-slash-reference6/// <reference path="unique.dev.d.ts" />78import {readFile} from 'fs/promises';910import Web3 from 'web3';11import {WebsocketProvider} from 'web3-core';12import {Contract} from 'web3-eth-contract';1314import * as solc from 'solc';1516import {evmToAddress} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';1819import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';2021import {ContractImports, CompiledContract} from './types';2223// Native contracts ABI24import collectionHelpersAbi from '../../collectionHelpersAbi.json';25import fungibleAbi from '../../fungibleAbi.json';26import nonFungibleAbi from '../../nonFungibleAbi.json';27import refungibleAbi from '../../reFungibleAbi.json';28import refungibleTokenAbi from '../../reFungibleTokenAbi.json';29import contractHelpersAbi from './../contractHelpersAbi.json';3031class EthGroupBase {32  helper: EthUniqueHelper;3334  constructor(helper: EthUniqueHelper) {35    this.helper = helper;36  }37}383940class ContractGroup extends EthGroupBase {41  async findImports(imports?: ContractImports[]){42    if(!imports) return function(path: string) {43      return {error: `File not found: ${path}`};44    };45  46    const knownImports = {} as any;47    for(const imp of imports) {48      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();49    }50  51    return function(path: string) {52      if(knownImports.hasOwnPropertyDescriptor(path)) return {contents: knownImports[path]};53      return {error: `File not found: ${path}`};54    };55  }5657  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {58    const out = JSON.parse(solc.compile(JSON.stringify({59      language: 'Solidity',60      sources: {61        [`${name}.sol`]: {62          content: src,63        },64      },65      settings: {66        outputSelection: {67          '*': {68            '*': ['*'],69          },70        },71      },72    }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];73  74    return {75      abi: out.abi,76      object: '0x' + out.evm.bytecode.object,77    };78  }7980  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {81    const compiledContract = await this.compile(name, src, imports);82    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);83  }8485  async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {86    const web3 = this.helper.getWeb3();87    const contract = new web3.eth.Contract(abi, undefined, {88      data: object,89      from: signer,90      gas: this.helper.eth.DEFAULT_GAS,91    });92    return await contract.deploy({data: object}).send({from: signer});93  }9495}96  97class NativeContractGroup extends EthGroupBase {9899  contractHelpers(caller: string): Contract {100    const web3 = this.helper.getWeb3();101    return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});102  }103104  collectionHelpers(caller: string) {105    const web3 = this.helper.getWeb3();106    return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});107  }108109  collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {110    const abi = {111      'nft': nonFungibleAbi,112      'rft': refungibleAbi,113      'ft': fungibleAbi,114    }[mode];115    const web3 = this.helper.getWeb3();116    return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});117  }118119  rftTokenByAddress(address: string, caller?: string): Contract {120    const web3 = this.helper.getWeb3();121    return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});122  }123124  rftToken(collectionId: number, tokenId: number, caller?: string): Contract {125    return this.rftTokenByAddress(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);126  }127}128129  130class EthGroup extends EthGroupBase {131  DEFAULT_GAS = 2_500_000;132133  createAccount() {134    const web3 = this.helper.getWeb3();135    const account = web3.eth.accounts.create();136    web3.eth.accounts.wallet.add(account.privateKey);137    return account.address;138  }139140  async createAccountWithBalance(donor: IKeyringPair, amount=1000n) {141    const account = this.createAccount();142    await this.transferBalanceFromSubstrate(donor, account, amount);143  144    return account;145  }146147  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {148    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));149  }150151  async callEVM(signer: IKeyringPair, contractAddress: string, abi: any, value: string, gasLimit?: number) {152    if(!gasLimit) gasLimit = this.DEFAULT_GAS;153    const web3 = this.helper.getWeb3();154    const gasPrice = await web3.eth.getGasPrice();155    // TODO: check execution status156    await this.helper.executeExtrinsic(157      signer,158      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],159      true,160    );161  }162163  async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {164    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);165        166    const result = await collectionHelper.methods.createNonfungibleCollection(name, description, tokenPrefix).send();167168    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);169    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);170171    return {collectionId, collectionAddress};172  }173174  async deployCollectorContract(signer: string): Promise<Contract> {175    return await this.helper.ethContract.deployByCode(signer, 'Collector', `176    // SPDX-License-Identifier: UNLICENSED177    pragma solidity ^0.8.6;178179    contract Collector {180      uint256 collected;181      fallback() external payable {182        giveMoney();183      }184      function giveMoney() public payable {185        collected += msg.value;186      }187      function getCollected() public view returns (uint256) {188        return collected;189      }190      function getUnaccounted() public view returns (uint256) {191        return address(this).balance - collected;192      }193194      function withdraw(address payable target) public {195        target.transfer(collected);196        collected = 0;197      }198    }199  `);200  }201}202  203  204class EthAddressGroup extends EthGroupBase {205  extractCollectionId(address: string): number {206    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');207    return parseInt(address.substr(address.length - 8), 16);208  }209210  fromCollectionId(collectionId: number): string {211    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');212    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);213  }214215  extractTokenId(address: string): {collectionId: number, tokenId: number} {216    if (!address.startsWith('0x'))217      throw 'address not starts with "0x"';218    if (address.length > 42)219      throw 'address length is more than 20 bytes';220    return {221      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),222      tokenId: Number('0x' + address.substring(address.length - 8)),223    };224  }225226  fromTokenId(collectionId: number, tokenId: number): string  {227    return this.helper.util.getNestingTokenAddress(collectionId, tokenId);228  }229230  normalizeAddress(address: string): string {231    return '0x' + address.substring(address.length - 40);232  }233}  234 235236export class EthUniqueHelper extends DevUniqueHelper {237  web3: Web3 | null = null;238  web3Provider: WebsocketProvider | null = null;239240  eth: EthGroup;241  ethAddress: EthAddressGroup;242  ethNativeContract: NativeContractGroup;243  ethContract: ContractGroup;244245  constructor(logger: { log: (msg: any, level: any) => void, level: any }) {246    super(logger);247    this.eth = new EthGroup(this);248    this.ethAddress = new EthAddressGroup(this);249    this.ethNativeContract = new NativeContractGroup(this);250    this.ethContract = new ContractGroup(this);251  }252253  getWeb3(): Web3 {254    if(this.web3 === null) throw Error('Web3 not connected');255    return this.web3;256  }257258  async connectWeb3(wsEndpoint: string) {259    if(this.web3 !== null) return;260    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);261    this.web3 = new Web3(this.web3Provider);262  }263264  async disconnectWeb3() {265    if(this.web3 === null) return;266    this.web3Provider?.connection.close();267    this.web3 = null;268  }269}270  
after · tests/src/eth/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable function-call-argument-newline */5// eslint-disable-next-line @typescript-eslint/triple-slash-reference6/// <reference path="unique.dev.d.ts" />78import {readFile} from 'fs/promises';910import Web3 from 'web3';11import {WebsocketProvider} from 'web3-core';12import {Contract} from 'web3-eth-contract';1314import * as solc from 'solc';1516import {evmToAddress} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';1819import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';2021import {ContractImports, CompiledContract} from './types';2223// Native contracts ABI24import collectionHelpersAbi from '../../collectionHelpersAbi.json';25import fungibleAbi from '../../fungibleAbi.json';26import nonFungibleAbi from '../../nonFungibleAbi.json';27import refungibleAbi from '../../reFungibleAbi.json';28import refungibleTokenAbi from '../../reFungibleTokenAbi.json';29import contractHelpersAbi from './../contractHelpersAbi.json';3031class EthGroupBase {32  helper: EthUniqueHelper;3334  constructor(helper: EthUniqueHelper) {35    this.helper = helper;36  }37}383940class ContractGroup extends EthGroupBase {41  async findImports(imports?: ContractImports[]){42    if(!imports) return function(path: string) {43      return {error: `File not found: ${path}`};44    };45  46    const knownImports = {} as any;47    for(const imp of imports) {48      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();49    }50  51    return function(path: string) {52      if(knownImports.hasOwnPropertyDescriptor(path)) return {contents: knownImports[path]};53      return {error: `File not found: ${path}`};54    };55  }5657  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {58    const out = JSON.parse(solc.compile(JSON.stringify({59      language: 'Solidity',60      sources: {61        [`${name}.sol`]: {62          content: src,63        },64      },65      settings: {66        outputSelection: {67          '*': {68            '*': ['*'],69          },70        },71      },72    }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];73  74    return {75      abi: out.abi,76      object: '0x' + out.evm.bytecode.object,77    };78  }7980  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {81    const compiledContract = await this.compile(name, src, imports);82    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);83  }8485  async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {86    const web3 = this.helper.getWeb3();87    const contract = new web3.eth.Contract(abi, undefined, {88      data: object,89      from: signer,90      gas: this.helper.eth.DEFAULT_GAS,91    });92    return await contract.deploy({data: object}).send({from: signer});93  }9495}96  97class NativeContractGroup extends EthGroupBase {9899  contractHelpers(caller: string): Contract {100    const web3 = this.helper.getWeb3();101    return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});102  }103104  collectionHelpers(caller: string) {105    const web3 = this.helper.getWeb3();106    return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});107  }108109  collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {110    const abi = {111      'nft': nonFungibleAbi,112      'rft': refungibleAbi,113      'ft': fungibleAbi,114    }[mode];115    const web3 = this.helper.getWeb3();116    return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});117  }118119  rftTokenByAddress(address: string, caller?: string): Contract {120    const web3 = this.helper.getWeb3();121    return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});122  }123124  rftToken(collectionId: number, tokenId: number, caller?: string): Contract {125    return this.rftTokenByAddress(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);126  }127}128129  130class EthGroup extends EthGroupBase {131  DEFAULT_GAS = 2_500_000;132133  createAccount() {134    const web3 = this.helper.getWeb3();135    const account = web3.eth.accounts.create();136    web3.eth.accounts.wallet.add(account.privateKey);137    return account.address;138  }139140  async createAccountWithBalance(donor: IKeyringPair, amount=1000n) {141    const account = this.createAccount();142    await this.transferBalanceFromSubstrate(donor, account, amount);143  144    return account;145  }146147  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {148    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));149  }150151  async callEVM(signer: IKeyringPair, contractAddress: string, abi: any, value: string, gasLimit?: number) {152    if(!gasLimit) gasLimit = this.DEFAULT_GAS;153    const web3 = this.helper.getWeb3();154    const gasPrice = await web3.eth.getGasPrice();155    // TODO: check execution status156    await this.helper.executeExtrinsic(157      signer,158      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],159      true,160    );161  }162163  async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {164    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);165        166    const result = await collectionHelper.methods.createNonfungibleCollection(name, description, tokenPrefix).send();167168    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);169    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);170171    return {collectionId, collectionAddress};172  }173174  async deployCollectorContract(signer: string): Promise<Contract> {175    return await this.helper.ethContract.deployByCode(signer, 'Collector', `176    // SPDX-License-Identifier: UNLICENSED177    pragma solidity ^0.8.6;178179    contract Collector {180      uint256 collected;181      fallback() external payable {182        giveMoney();183      }184      function giveMoney() public payable {185        collected += msg.value;186      }187      function getCollected() public view returns (uint256) {188        return collected;189      }190      function getUnaccounted() public view returns (uint256) {191        return address(this).balance - collected;192      }193194      function withdraw(address payable target) public {195        target.transfer(collected);196        collected = 0;197      }198    }199  `);200  }201202  async deployFlipper(signer: string): Promise<Contract> {203    return await this.helper.ethContract.deployByCode(signer, 'Flipper', `204    contract Flipper {205      bool value = false;206      function flip() public {207        value = !value;208      }209      function getValue() public view returns (bool) {210        return value;211      }212    }213  `);214  }215}  216  217class EthAddressGroup extends EthGroupBase {218  extractCollectionId(address: string): number {219    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');220    return parseInt(address.substr(address.length - 8), 16);221  }222223  fromCollectionId(collectionId: number): string {224    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');225    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);226  }227228  extractTokenId(address: string): {collectionId: number, tokenId: number} {229    if (!address.startsWith('0x'))230      throw 'address not starts with "0x"';231    if (address.length > 42)232      throw 'address length is more than 20 bytes';233    return {234      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),235      tokenId: Number('0x' + address.substring(address.length - 8)),236    };237  }238239  fromTokenId(collectionId: number, tokenId: number): string  {240    return this.helper.util.getNestingTokenAddress(collectionId, tokenId);241  }242243  normalizeAddress(address: string): string {244    return '0x' + address.substring(address.length - 40);245  }246}  247 248249export class EthUniqueHelper extends DevUniqueHelper {250  web3: Web3 | null = null;251  web3Provider: WebsocketProvider | null = null;252253  eth: EthGroup;254  ethAddress: EthAddressGroup;255  ethNativeContract: NativeContractGroup;256  ethContract: ContractGroup;257258  constructor(logger: { log: (msg: any, level: any) => void, level: any }) {259    super(logger);260    this.eth = new EthGroup(this);261    this.ethAddress = new EthAddressGroup(this);262    this.ethNativeContract = new NativeContractGroup(this);263    this.ethContract = new ContractGroup(this);264  }265266  getWeb3(): Web3 {267    if(this.web3 === null) throw Error('Web3 not connected');268    return this.web3;269  }270271  async connectWeb3(wsEndpoint: string) {272    if(this.web3 !== null) return;273    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);274    this.web3 = new Web3(this.web3Provider);275  }276277  async disconnectWeb3() {278    if(this.web3 === null) return;279    this.web3Provider?.connection.close();280    this.web3 = null;281  }282}283