git.delta.rocks / unique-network / refs/commits / dae8a5f4351f

difftreelog

Merge pull request #629 from UniqueNetwork/feature/eth-tests-playgrnds

ut-akuznetsov2022-10-05parents: #ab38216 #5721d4c.patch.diff
in: master
Feature/eth tests playgrnds

7 files changed

modifiedtests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -1,33 +1,45 @@
-import {addToAllowListExpectSuccess, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, getDetailedCollectionInfo, setCollectionSponsorExpectSuccess, UNIQUE} from '../util/helpers';
-import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents, createEthAccountWithBalance, evmCollectionHelpers, getCollectionAddressFromResult, evmCollection, ethBalanceViaSub} from './util/helpers';
-import nonFungibleAbi from './nonFungibleAbi.json';
-import {expect} from 'chai';
-import {evmToAddress} from '@polkadot/util-crypto';
+import {IKeyringPair} from '@polkadot/types/types';
+import {usingPlaygrounds} from './../util/playgrounds/index';
+import {itEth, expect} from '../eth/util/playgrounds';
 
 describe('evm collection sponsoring', () => {
-  itWeb3('sponsors mint transactions', async ({web3, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+  let nominal: bigint;
+
+  before(async () => {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      donor = privateKey('//Alice');
+      nominal = helper.balance.getOneTokenNominal();
+    });
+  });
+
+  beforeEach(async () => {
+    await usingPlaygrounds(async (helper) => {
+      [alice] = await helper.arrange.createAccounts([1000n], donor);
+    });
+  });
 
-    const collection = await createCollectionExpectSuccess();
-    await setCollectionSponsorExpectSuccess(collection, alice.address);
-    await confirmSponsorshipExpectSuccess(collection);
+  itEth('sponsors mint transactions', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'spnr', permissions: {mintMode: true}});
+    await collection.setSponsor(alice, alice.address);
+    await collection.confirmSponsorship(alice);
 
-    const minter = createEthAccount(web3);
-    expect(await web3.eth.getBalance(minter)).to.equal('0');
+    const minter = helper.eth.createAccount();
+    expect(await helper.balance.getEthereum(minter)).to.equal(0n);
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collection), {from: minter, ...GAS_ARGS});
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', minter);
 
-    await enablePublicMintingExpectSuccess(alice, collection);
-    await addToAllowListExpectSuccess(alice, collection, {Ethereum: minter});
+    await collection.addToAllowList(alice, {Ethereum: minter});
 
     const nextTokenId = await contract.methods.nextTokenId().call();
     expect(nextTokenId).to.equal('1');
     const result = await contract.methods.mint(minter, nextTokenId).send();
-    const events = normalizeEvents(result.events);
+    const events = helper.eth.normalizeEvents(result.events);
     expect(events).to.be.deep.equal([
       {
-        address,
+        address: collectionAddress,
         event: 'Transfer',
         args: {
           from: '0x0000000000000000000000000000000000000000',
@@ -59,13 +71,14 @@
   //   expect(bigIntToSub(api, BigInt(sponsorTuple[1]))).to.be.eq(sponsor.address);
   // });
 
-  itWeb3('Remove sponsor', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionHelpers = evmCollectionHelpers(web3, owner);
-    let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * UNIQUE)});
-    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
-    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+  itEth('Remove sponsor', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
+
+    let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
+    const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+    const sponsor = await helper.eth.createAccountWithBalance(donor);
+    const collectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner);
 
     expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
     result = await collectionEvm.methods.setCollectionSponsor(sponsor).send({from: owner});
@@ -80,30 +93,31 @@
     expect(sponsorTuple.field_0).to.be.eq('0x0000000000000000000000000000000000000000');
   });
 
-  itWeb3('Sponsoring collection from evm address via access list', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionHelpers = evmCollectionHelpers(web3, owner);
-    let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * UNIQUE)});
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+  itEth('Sponsoring collection from evm address via access list', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
+
+    let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
+    const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+    const collectionId = helper.ethAddress.extractCollectionId(collectionIdAddress);
+    const collection = helper.nft.getCollectionObject(collectionId);
+    const sponsor = await helper.eth.createAccountWithBalance(donor);
+    const collectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner);
+
     result = await collectionEvm.methods.setCollectionSponsor(sponsor).send({from: owner});
-    let collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
-    const ss58Format = (api.registry.getChainProperties())!.toJSON().ss58Format;
-    expect(collectionSub.sponsorship.isUnconfirmed).to.be.true;
-    expect(collectionSub.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor, Number(ss58Format)));
+    let collectionData = (await collection.getData())!;
+    expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
     await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
 
     await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
-    collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
-    expect(collectionSub.sponsorship.isConfirmed).to.be.true;
-    expect(collectionSub.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor, Number(ss58Format)));
+    collectionData = (await collection.getData())!;
+    expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
 
-    const user = createEthAccount(web3);
+    const user = helper.eth.createAccount();
     const nextTokenId = await collectionEvm.methods.nextTokenId().call();
     expect(nextTokenId).to.be.equal('1');
 
-    const oldPermissions = (await getDetailedCollectionInfo(api, collectionId))!.permissions.toHuman();
+    const oldPermissions = (await collection.getData())!.raw.permissions; // (await getDetailedCollectionInfo(api, collectionId))!.permissions.toHuman();
     expect(oldPermissions.mintMode).to.be.false;
     expect(oldPermissions.access).to.be.equal('Normal');
 
@@ -111,12 +125,12 @@
     await collectionEvm.methods.addToCollectionAllowList(user).send({from: owner});
     await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
 
-    const newPermissions = (await getDetailedCollectionInfo(api, collectionId))!.permissions.toHuman();
+    const newPermissions = (await collection.getData())!.raw.permissions; // (await getDetailedCollectionInfo(api, collectionId))!.permissions.toHuman();
     expect(newPermissions.mintMode).to.be.true;
     expect(newPermissions.access).to.be.equal('AllowList');
 
-    const ownerBalanceBefore = await ethBalanceViaSub(api, owner);
-    const sponsorBalanceBefore = await ethBalanceViaSub(api, sponsor);
+    const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+    const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
 
     {
       const nextTokenId = await collectionEvm.methods.nextTokenId().call();
@@ -126,7 +140,7 @@
         nextTokenId,
         'Test URI',
       ).send({from: user});
-      const events = normalizeEvents(result.events);
+      const events = helper.eth.normalizeEvents(result.events);
 
       expect(events).to.be.deep.equal([
         {
@@ -140,8 +154,8 @@
         },
       ]);
 
-      const ownerBalanceAfter = await ethBalanceViaSub(api, owner);
-      const sponsorBalanceAfter = await ethBalanceViaSub(api, sponsor);
+      const ownerBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(owner));
+      const sponsorBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(sponsor));
 
       expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
       expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);
@@ -205,33 +219,34 @@
   //   }
   // });
 
-  itWeb3('Check that transaction via EVM spend money from sponsor address', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionHelpers = evmCollectionHelpers(web3, owner);
-    let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * UNIQUE)});
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+  itEth('Check that transaction via EVM spend money from sponsor address', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
+
+    let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
+    const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+    const collectionId = helper.ethAddress.extractCollectionId(collectionIdAddress);
+    const collection = helper.nft.getCollectionObject(collectionId);
+    const sponsor = await helper.eth.createAccountWithBalance(donor);
+    const collectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner);
+
     result = await collectionEvm.methods.setCollectionSponsor(sponsor).send();
-    let collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
-    const ss58Format = (api.registry.getChainProperties())!.toJSON().ss58Format;
-    expect(collectionSub.sponsorship.isUnconfirmed).to.be.true;
-    expect(collectionSub.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor, Number(ss58Format)));
+    let collectionData = (await collection.getData())!;
+    expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
     await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
-    const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
+
+    const sponsorCollection = helper.ethNativeContract.collection(collectionIdAddress, 'nft', sponsor);
     await sponsorCollection.methods.confirmCollectionSponsorship().send();
-    collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
-    expect(collectionSub.sponsorship.isConfirmed).to.be.true;
-    expect(collectionSub.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor, Number(ss58Format)));
+    collectionData = (await collection.getData())!;
+    expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
 
-    const user = createEthAccount(web3);
+    const user = helper.eth.createAccount();
     await collectionEvm.methods.addCollectionAdmin(user).send();
     
-    const ownerBalanceBefore = await ethBalanceViaSub(api, owner);
-    const sponsorBalanceBefore = await ethBalanceViaSub(api, sponsor);
-    
-  
-    const userCollectionEvm = evmCollection(web3, user, collectionIdAddress);
+    const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+    const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+
+    const userCollectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', user);
     const nextTokenId = await userCollectionEvm.methods.nextTokenId().call();
     expect(nextTokenId).to.be.equal('1');
     result = await userCollectionEvm.methods.mintWithTokenURI(
@@ -240,8 +255,8 @@
       'Test URI',
     ).send();
 
-    const events = normalizeEvents(result.events);
-    const address = collectionIdToAddress(collectionId);
+    const events = helper.eth.normalizeEvents(result.events);
+    const address = helper.ethAddress.fromCollectionId(collectionId);
 
     expect(events).to.be.deep.equal([
       {
@@ -256,9 +271,9 @@
     ]);
     expect(await userCollectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
   
-    const ownerBalanceAfter = await ethBalanceViaSub(api, owner);
+    const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
     expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);
-    const sponsorBalanceAfter = await ethBalanceViaSub(api, sponsor);
+    const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
     expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
   });
 });
modifiedtests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth
before · tests/src/eth/contractSponsoring.test.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 * as solc from 'solc';18import {expect} from 'chai';19import {expectSubstrateEventsAtBlock} from '../util/helpers';20import Web3 from 'web3';2122import {23  contractHelpers,24  createEthAccountWithBalance,25  transferBalanceToEth,26  deployFlipper,27  itWeb3,28  SponsoringMode,29  createEthAccount,30  ethBalanceViaSub,31  normalizeEvents,32  CompiledContract,33  GAS_ARGS,34  subToEth,35} from './util/helpers';36import {submitTransactionAsync} from '../substrate/substrate-api';3738describe('Sponsoring EVM contracts', () => {39  itWeb3('Self sponsored can be set by the address that deployed the contract', async ({api, web3, privateKeyWrapper}) => {40    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);41    const flipper = await deployFlipper(web3, owner);42    const helpers = contractHelpers(web3, owner);43    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;44    await expect(helpers.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;45    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.true;46  });4748  itWeb3('Set self sponsored events', async ({api, web3, privateKeyWrapper}) => {49    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);50    const flipper = await deployFlipper(web3, owner);51    const helpers = contractHelpers(web3, owner);52    53    const result = await helpers.methods.selfSponsoredEnable(flipper.options.address).send();54    // console.log(result);55    const ethEvents = normalizeEvents(result.events);56    expect(ethEvents).to.be.deep.equal([57      {58        address: flipper.options.address,59        event: 'ContractSponsorSet',60        args: {61          contractAddress: flipper.options.address,62          sponsor: flipper.options.address,63        },64      },65      {66        address: flipper.options.address,67        event: 'ContractSponsorshipConfirmed',68        args: {69          contractAddress: flipper.options.address,70          sponsor: flipper.options.address,71        },72      },73    ]);7475    await expectSubstrateEventsAtBlock(76      api, 77      result.blockNumber,78      'evmContractHelpers',79      ['ContractSponsorSet','ContractSponsorshipConfirmed'],80    );81  });8283  itWeb3('Self sponsored can not be set by the address that did not deployed the contract', async ({api, web3, privateKeyWrapper}) => {84    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);85    const notOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);86    const flipper = await deployFlipper(web3, owner);87    const helpers = contractHelpers(web3, owner);88    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;89    await expect(helpers.methods.selfSponsoredEnable(flipper.options.address).call({from: notOwner})).to.be.rejectedWith('NoPermission');90    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;91  });9293  itWeb3('Sponsoring can be set by the address that has deployed the contract', async ({api, web3, privateKeyWrapper}) => {94    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);95    const flipper = await deployFlipper(web3, owner);96    const helpers = contractHelpers(web3, owner);97    expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;98    await expect(helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner})).to.be.not.rejected;99    expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;100  });101102  itWeb3('Sponsoring cannot be set by the address that did not deployed the contract', async ({api, web3, privateKeyWrapper}) => {103    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);104    const notOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);105    const flipper = await deployFlipper(web3, owner);106    const helpers = contractHelpers(web3, owner);107    expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;108    await expect(helpers.methods.setSponsoringMode(notOwner, SponsoringMode.Allowlisted).call({from: notOwner})).to.be.rejectedWith('NoPermission');109    expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;110  });111  112  itWeb3('Sponsor can be set by the address that deployed the contract', async ({api, web3, privateKeyWrapper}) => {113    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);114    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);115    const flipper = await deployFlipper(web3, owner);116    const helpers = contractHelpers(web3, owner);117    expect(await helpers.methods.hasPendingSponsor(flipper.options.address).call()).to.be.false;118    await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).send()).to.be.not.rejected;119    expect(await helpers.methods.hasPendingSponsor(flipper.options.address).call()).to.be.true;120  });121  122  itWeb3('Set sponsor event', async ({api, web3, privateKeyWrapper}) => {123    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);124    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);125    const flipper = await deployFlipper(web3, owner);126    const helpers = contractHelpers(web3, owner);127    128    const result = await helpers.methods.setSponsor(flipper.options.address, sponsor).send();129    const events = normalizeEvents(result.events);130    expect(events).to.be.deep.equal([131      {132        address: flipper.options.address,133        event: 'ContractSponsorSet',134        args: {135          contractAddress: flipper.options.address,136          sponsor: sponsor,137        },138      },139    ]);140141    await expectSubstrateEventsAtBlock(142      api, 143      result.blockNumber,144      'evmContractHelpers',145      ['ContractSponsorSet'],146    );147  });148  149  itWeb3('Sponsor can not be set by the address that did not deployed the contract', async ({api, web3, privateKeyWrapper}) => {150    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);151    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);152    const notOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);153    const flipper = await deployFlipper(web3, owner);154    const helpers = contractHelpers(web3, owner);155    expect(await helpers.methods.hasPendingSponsor(flipper.options.address).call()).to.be.false;156    await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).call({from: notOwner})).to.be.rejectedWith('NoPermission');157    expect(await helpers.methods.hasPendingSponsor(flipper.options.address).call()).to.be.false;158  });159160  itWeb3('Sponsorship can be confirmed by the address that pending as sponsor', async ({api, web3, privateKeyWrapper}) => {161    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);162    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);163    const flipper = await deployFlipper(web3, owner);164    const helpers = contractHelpers(web3, owner);165    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;166    await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).send()).to.be.not.rejected;167    await expect(helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor})).to.be.not.rejected;168    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.true;169  });170171  itWeb3('Confirm sponsorship event', async ({api, web3, privateKeyWrapper}) => {172    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);173    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);174    const flipper = await deployFlipper(web3, owner);175    const helpers = contractHelpers(web3, owner);176    await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).send()).to.be.not.rejected;177    const result = await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});178    const events = normalizeEvents(result.events);179    expect(events).to.be.deep.equal([180      {181        address: flipper.options.address,182        event: 'ContractSponsorshipConfirmed',183        args: {184          contractAddress: flipper.options.address,185          sponsor: sponsor,186        },187      },188    ]);189190    await expectSubstrateEventsAtBlock(191      api, 192      result.blockNumber,193      'evmContractHelpers',194      ['ContractSponsorshipConfirmed'],195    );196  });197198  itWeb3('Sponsorship can not be confirmed by the address that not pending as sponsor', async ({api, web3, privateKeyWrapper}) => {199    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);200    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);201    const notSponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);202    const flipper = await deployFlipper(web3, owner);203    const helpers = contractHelpers(web3, owner);204    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;205    await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).send()).to.be.not.rejected;206    await expect(helpers.methods.confirmSponsorship(flipper.options.address).call({from: notSponsor})).to.be.rejectedWith('NoPermission');207    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;208  });209210  itWeb3('Sponsorship can not be confirmed by the address that not set as sponsor', async ({api, web3, privateKeyWrapper}) => {211    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);212    const notSponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);213    const flipper = await deployFlipper(web3, owner);214    const helpers = contractHelpers(web3, owner);215    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;216    await expect(helpers.methods.confirmSponsorship(flipper.options.address).call({from: notSponsor})).to.be.rejectedWith('NoPendingSponsor');217    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;218  });219220  itWeb3('Get self sponsored sponsor', async ({api, web3, privateKeyWrapper}) => {221    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);222    const flipper = await deployFlipper(web3, owner);223    const helpers = contractHelpers(web3, owner);224    await helpers.methods.selfSponsoredEnable(flipper.options.address).send();225    226    const result = await helpers.methods.sponsor(flipper.options.address).call();227228    expect(result[0]).to.be.eq(flipper.options.address);229    expect(result[1]).to.be.eq('0');230  });231232  itWeb3('Get confirmed sponsor', async ({api, web3, privateKeyWrapper}) => {233    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);234    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);235    const flipper = await deployFlipper(web3, owner);236    const helpers = contractHelpers(web3, owner);237    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();238    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});239    240    const result = await helpers.methods.sponsor(flipper.options.address).call();241242    expect(result[0]).to.be.eq(sponsor);243    expect(result[1]).to.be.eq('0');244  });245246  itWeb3('Sponsor can be removed by the address that deployed the contract', async ({api, web3, privateKeyWrapper}) => {247    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);248    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);249    const flipper = await deployFlipper(web3, owner);250    const helpers = contractHelpers(web3, owner);251252    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;253    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();254    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});255    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.true;256    257    await helpers.methods.removeSponsor(flipper.options.address).send();258    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;259  });260261  itWeb3('Remove sponsor event', async ({api, web3, privateKeyWrapper}) => {262    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);263    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);264    const flipper = await deployFlipper(web3, owner);265    const helpers = contractHelpers(web3, owner);266267    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();268    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});269    270    const result = await helpers.methods.removeSponsor(flipper.options.address).send();271    const events = normalizeEvents(result.events);272    expect(events).to.be.deep.equal([273      {274        address: flipper.options.address,275        event: 'ContractSponsorRemoved',276        args: {277          contractAddress: flipper.options.address,278        },279      },280    ]);281282    await expectSubstrateEventsAtBlock(283      api, 284      result.blockNumber,285      'evmContractHelpers',286      ['ContractSponsorRemoved'],287    );288  });289290  itWeb3('Sponsor can not be removed by the address that did not deployed the contract', async ({api, web3, privateKeyWrapper}) => {291    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);292    const notOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);293    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);294    const flipper = await deployFlipper(web3, owner);295    const helpers = contractHelpers(web3, owner);296297    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;298    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();299    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});300    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.true;301    302    await expect(helpers.methods.removeSponsor(flipper.options.address).call({from: notOwner})).to.be.rejectedWith('NoPermission');303    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.true;304  });305306  itWeb3('In generous mode, non-allowlisted user transaction will be sponsored', async ({api, web3, privateKeyWrapper}) => {307    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);308    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);309    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);310311    const flipper = await deployFlipper(web3, owner);312313    const helpers = contractHelpers(web3, owner);314315    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();316    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});317318    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: owner});319    await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});320321    const sponsorBalanceBefore = await ethBalanceViaSub(api, sponsor);322    const callerBalanceBefore = await ethBalanceViaSub(api, caller);323324    await flipper.methods.flip().send({from: caller});325    expect(await flipper.methods.getValue().call()).to.be.true;326327    // Balance should be taken from sponsor instead of caller328    const sponsorBalanceAfter = await ethBalanceViaSub(api, sponsor);329    const callerBalanceAfter = await ethBalanceViaSub(api, caller);330    expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;331    expect(callerBalanceAfter).to.be.eq(callerBalanceBefore);332  });333334  itWeb3('In generous mode, non-allowlisted user transaction will be self sponsored', async ({api, web3, privateKeyWrapper}) => {335    const alice = privateKeyWrapper('//Alice');336337    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);338    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);339340    const flipper = await deployFlipper(web3, owner);341342    const helpers = contractHelpers(web3, owner);343344    await helpers.methods.selfSponsoredEnable(flipper.options.address).send();345346    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: owner});347    await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});348349    await transferBalanceToEth(api, alice, flipper.options.address);350351    const contractBalanceBefore = await ethBalanceViaSub(api, flipper.options.address);352    const callerBalanceBefore = await ethBalanceViaSub(api, caller);353354    await flipper.methods.flip().send({from: caller});355    expect(await flipper.methods.getValue().call()).to.be.true;356357    // Balance should be taken from sponsor instead of caller358    const contractBalanceAfter = await ethBalanceViaSub(api, flipper.options.address);359    const callerBalanceAfter = await ethBalanceViaSub(api, caller);360    expect(contractBalanceAfter < contractBalanceBefore).to.be.true;361    expect(callerBalanceAfter).to.be.eq(callerBalanceBefore);362  });363364  itWeb3('Sponsoring is set, an address that has no UNQ can send a transaction and it works. Sponsor balance should decrease (allowlisted)', async ({api, web3, privateKeyWrapper}) => {365    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);366    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);367    const caller = createEthAccount(web3);368369    const flipper = await deployFlipper(web3, owner);370371    const helpers = contractHelpers(web3, owner);372    await helpers.methods.toggleAllowlist(flipper.options.address, true).send({from: owner});373    await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({from: owner});374375    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner});376    await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});377378    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();379    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});380381    const sponsorBalanceBefore = await ethBalanceViaSub(api, sponsor);382    expect(sponsorBalanceBefore).to.be.not.equal('0');383384    await flipper.methods.flip().send({from: caller});385    expect(await flipper.methods.getValue().call()).to.be.true;386387    // Balance should be taken from flipper instead of caller388    const sponsorBalanceAfter = await ethBalanceViaSub(api, sponsor);389    expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;390  });391392  itWeb3('Sponsoring is set, an address that has no UNQ can send a transaction and it works. Sponsor balance should not decrease (non-allowlisted)', async ({api, web3, privateKeyWrapper}) => {393    const alice = privateKeyWrapper('//Alice');394395    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);396    const caller = createEthAccount(web3);397398    const flipper = await deployFlipper(web3, owner);399400    const helpers = contractHelpers(web3, owner);401402    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner});403    await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});404405    await transferBalanceToEth(api, alice, flipper.options.address);406407    const originalFlipperBalance = await web3.eth.getBalance(flipper.options.address);408    expect(originalFlipperBalance).to.be.not.equal('0');409410    await expect(flipper.methods.flip().send({from: caller})).to.be.rejectedWith(/InvalidTransaction::Payment/);411    expect(await flipper.methods.getValue().call()).to.be.false;412413    // Balance should be taken from flipper instead of caller414    const balanceAfter = await web3.eth.getBalance(flipper.options.address);415    expect(+balanceAfter).to.be.equals(+originalFlipperBalance);416  });417418  itWeb3('Sponsoring is set, an address that has UNQ can send a transaction and it works. User balance should not change', async ({api, web3, privateKeyWrapper}) => {419    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);420    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);421    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);422423    const flipper = await deployFlipper(web3, owner);424425    const helpers = contractHelpers(web3, owner);426    await helpers.methods.toggleAllowlist(flipper.options.address, true).send({from: owner});427    await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({from: owner});428429    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner});430    await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});431432    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();433    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});434435    const sponsorBalanceBefore = await ethBalanceViaSub(api, sponsor);436    const callerBalanceBefore = await ethBalanceViaSub(api, caller);437438    await flipper.methods.flip().send({from: caller});439    expect(await flipper.methods.getValue().call()).to.be.true;440441    const sponsorBalanceAfter = await ethBalanceViaSub(api, sponsor);442    const callerBalanceAfter = await ethBalanceViaSub(api, caller);443    expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;444    expect(callerBalanceAfter).to.be.equals(callerBalanceBefore);445  });446447  itWeb3('Sponsoring is limited, with setContractRateLimit. The limitation is working if transactions are sent more often, the sender pays the commission.', async ({api, web3, privateKeyWrapper}) => {448    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);449    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);450    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);451    const originalCallerBalance = await web3.eth.getBalance(caller);452453    const flipper = await deployFlipper(web3, owner);454455    const helpers = contractHelpers(web3, owner);456    await helpers.methods.toggleAllowlist(flipper.options.address, true).send({from: owner});457    await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({from: owner});458459    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner});460    await helpers.methods.setSponsoringRateLimit(flipper.options.address, 10).send({from: owner});461462    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();463    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});464465    const originalFlipperBalance = await web3.eth.getBalance(sponsor);466    expect(originalFlipperBalance).to.be.not.equal('0');467468    await flipper.methods.flip().send({from: caller});469    expect(await flipper.methods.getValue().call()).to.be.true;470    expect(await web3.eth.getBalance(caller)).to.be.equals(originalCallerBalance);471472    const newFlipperBalance = await web3.eth.getBalance(sponsor);473    expect(newFlipperBalance).to.be.not.equals(originalFlipperBalance);474475    await flipper.methods.flip().send({from: caller});476    expect(await web3.eth.getBalance(sponsor)).to.be.equal(newFlipperBalance);477    expect(await web3.eth.getBalance(caller)).to.be.not.equals(originalCallerBalance);478  });479480  // TODO: Find a way to calculate default rate limit481  itWeb3('Default rate limit equals 7200', async ({api, web3, privateKeyWrapper}) => {482    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);483    const flipper = await deployFlipper(web3, owner);484    const helpers = contractHelpers(web3, owner);485    expect(await helpers.methods.sponsoringRateLimit(flipper.options.address).call()).to.be.equals('7200');486  });487});488489describe('Sponsoring Fee Limit', () => {490491  let testContract: CompiledContract;492  493  function compileTestContract() {494    if (!testContract) {495      const input = {496        language: 'Solidity',497        sources: {498          ['TestContract.sol']: {499            content:500            `501            // SPDX-License-Identifier: MIT502            pragma solidity ^0.8.0;503            504            contract TestContract {505              event Result(bool);506507              function test(uint32 cycles) public {508                uint256 counter = 0;509                while(true) {510                  counter ++;511                  if (counter > cycles){512                    break;513                  }514                }515                emit Result(true);516              }517            }518            `,519          },520        },521        settings: {522          outputSelection: {523            '*': {524              '*': ['*'],525            },526          },527        },528      };529      const json = JSON.parse(solc.compile(JSON.stringify(input)));530      const out = json.contracts['TestContract.sol']['TestContract'];531  532      testContract = {533        abi: out.abi,534        object: '0x' + out.evm.bytecode.object,535      };536    }537    return testContract;538  }539  540  async function deployTestContract(web3: Web3, owner: string) {541    const compiled = compileTestContract();542    const testContract = new web3.eth.Contract(compiled.abi, undefined, {543      data: compiled.object,544      from: owner,545      ...GAS_ARGS,546    });547    return await testContract.deploy({data: compiled.object}).send({from: owner});548  }549550  itWeb3('Default fee limit', async ({api, web3, privateKeyWrapper}) => {551    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);552    const flipper = await deployFlipper(web3, owner);553    const helpers = contractHelpers(web3, owner);554    expect(await helpers.methods.sponsoringFeeLimit(flipper.options.address).call()).to.be.equals('115792089237316195423570985008687907853269984665640564039457584007913129639935');555  });556557  itWeb3('Set fee limit', async ({api, web3, privateKeyWrapper}) => {558    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);559    const flipper = await deployFlipper(web3, owner);560    const helpers = contractHelpers(web3, owner);561    await helpers.methods.setSponsoringFeeLimit(flipper.options.address, 100).send();562    expect(await helpers.methods.sponsoringFeeLimit(flipper.options.address).call()).to.be.equals('100');563  });564565  itWeb3('Negative test - set fee limit by non-owner', async ({api, web3, privateKeyWrapper}) => {566    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);567    const stranger = await createEthAccountWithBalance(api, web3, privateKeyWrapper);568    const flipper = await deployFlipper(web3, owner);569    const helpers = contractHelpers(web3, owner);570    await expect(helpers.methods.setSponsoringFeeLimit(flipper.options.address, 100).send({from: stranger})).to.be.rejected;571  });572573  itWeb3('Negative test - check that eth transactions exceeding fee limit are not executed', async ({api, web3, privateKeyWrapper}) => {574    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);575    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);576    const user = await createEthAccountWithBalance(api, web3, privateKeyWrapper);577578    const testContract = await deployTestContract(web3, owner);579    const helpers = contractHelpers(web3, owner);580    581    await helpers.methods.setSponsoringMode(testContract.options.address, SponsoringMode.Generous).send({from: owner});582    await helpers.methods.setSponsoringRateLimit(testContract.options.address, 0).send({from: owner});583    584    await helpers.methods.setSponsor(testContract.options.address, sponsor).send();585    await helpers.methods.confirmSponsorship(testContract.options.address).send({from: sponsor});586587    const gasPrice = BigInt(await web3.eth.getGasPrice());588589    await helpers.methods.setSponsoringFeeLimit(testContract.options.address, 2_000_000n * gasPrice).send();590591    const originalUserBalance = await web3.eth.getBalance(user);592    await testContract.methods.test(100).send({from: user, gas: 2_000_000});593    expect(await web3.eth.getBalance(user)).to.be.equal(originalUserBalance);594595    await testContract.methods.test(100).send({from: user, gas: 2_100_000});596    expect(await web3.eth.getBalance(user)).to.not.be.equal(originalUserBalance);597  });598599  itWeb3('Negative test - check that evm.call transactions exceeding fee limit are not executed', async ({api, web3, privateKeyWrapper}) => {600    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);601    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);602603    const testContract = await deployTestContract(web3, owner);604    const helpers = contractHelpers(web3, owner);605    606    await helpers.methods.setSponsoringMode(testContract.options.address, SponsoringMode.Generous).send({from: owner});607    await helpers.methods.setSponsoringRateLimit(testContract.options.address, 0).send({from: owner});608    609    await helpers.methods.setSponsor(testContract.options.address, sponsor).send();610    await helpers.methods.confirmSponsorship(testContract.options.address).send({from: sponsor});611612    const gasPrice = BigInt(await web3.eth.getGasPrice());613614    await helpers.methods.setSponsoringFeeLimit(testContract.options.address, 2_000_000n * gasPrice).send();615616    const alice = privateKeyWrapper('//Alice');617    const originalAliceBalance = (await api.query.system.account(alice.address)).data.free.toBigInt();618    619    await submitTransactionAsync(620      alice,621      api.tx.evm.call(622        subToEth(alice.address),623        testContract.options.address,624        testContract.methods.test(100).encodeABI(),625        Uint8Array.from([]),626        2_000_000n,627        gasPrice,628        null,629        null,630        [],631      ),632    );633    expect((await api.query.system.account(alice.address)).data.free.toBigInt()).to.be.equal(originalAliceBalance);634    635    await submitTransactionAsync(636      alice,637      api.tx.evm.call(638        subToEth(alice.address),639        testContract.options.address,640        testContract.methods.test(100).encodeABI(),641        Uint8Array.from([]),642        2_100_000n,643        gasPrice,644        null,645        null,646        [],647      ),648    );649    expect((await api.query.system.account(alice.address)).data.free.toBigInt()).to.not.be.equal(originalAliceBalance);650  });651});
after · tests/src/eth/contractSponsoring.test.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {IKeyringPair} from '@polkadot/types/types';18import * as solc from 'solc';19import {EthUniqueHelper} from './util/playgrounds/unique.dev';20import {itEth, expect, SponsoringMode, usingEthPlaygrounds} from '../eth/util/playgrounds';21import {usingPlaygrounds} from '../util/playgrounds';22import {CompiledContract} from './util/playgrounds/types';2324describe('Sponsoring EVM contracts', () => {25  let donor: IKeyringPair;2627  before(async () => {28    await usingPlaygrounds(async (_helper, privateKey) => {29      donor = privateKey('//Alice');30    });31  });3233  itEth('Self sponsored can be set by the address that deployed the contract', async ({helper, privateKey}) => {34    const owner = await helper.eth.createAccountWithBalance(donor);35    const flipper = await helper.eth.deployFlipper(owner);36    const helpers = helper.ethNativeContract.contractHelpers(owner);3738    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;39    await expect(helpers.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;40    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.true;41  });4243  itEth('Set self sponsored events', async ({helper}) => {44    const owner = await helper.eth.createAccountWithBalance(donor);45    const flipper = await helper.eth.deployFlipper(owner);46    const helpers = helper.ethNativeContract.contractHelpers(owner);47    48    const result = await helpers.methods.selfSponsoredEnable(flipper.options.address).send();49    const ethEvents = helper.eth.helper.eth.normalizeEvents(result.events);50    expect(ethEvents).to.be.deep.equal([51      {52        address: flipper.options.address,53        event: 'ContractSponsorSet',54        args: {55          contractAddress: flipper.options.address,56          sponsor: flipper.options.address,57        },58      },59      {60        address: flipper.options.address,61        event: 'ContractSponsorshipConfirmed',62        args: {63          contractAddress: flipper.options.address,64          sponsor: flipper.options.address,65        },66      },67    ]);68  });6970  itEth('Self sponsored can not be set by the address that did not deployed the contract', async ({helper}) => {71    const owner = await helper.eth.createAccountWithBalance(donor);72    const notOwner = await helper.eth.createAccountWithBalance(donor);73    const helpers = helper.ethNativeContract.contractHelpers(owner);74    const flipper = await helper.eth.deployFlipper(owner);7576    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;77    await expect(helpers.methods.selfSponsoredEnable(flipper.options.address).call({from: notOwner})).to.be.rejectedWith('NoPermission');78    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;79  });8081  itEth('Sponsoring can be set by the address that has deployed the contract', async ({helper}) => {82    const owner = await helper.eth.createAccountWithBalance(donor);83    const helpers = helper.ethNativeContract.contractHelpers(owner);84    const flipper = await helper.eth.deployFlipper(owner);8586    expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;87    await expect(helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner})).to.be.not.rejected;88    expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;89  });9091  itEth('Sponsoring cannot be set by the address that did not deployed the contract', async ({helper}) => {92    const owner = await helper.eth.createAccountWithBalance(donor);93    const notOwner = await helper.eth.createAccountWithBalance(donor);94    const helpers = helper.ethNativeContract.contractHelpers(owner);95    const flipper = await helper.eth.deployFlipper(owner);9697    expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;98    await expect(helpers.methods.setSponsoringMode(notOwner, SponsoringMode.Allowlisted).call({from: notOwner})).to.be.rejectedWith('NoPermission');99    expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;100  });101  102  itEth('Sponsor can be set by the address that deployed the contract', async ({helper}) => {103    const owner = await helper.eth.createAccountWithBalance(donor);104    const sponsor = await helper.eth.createAccountWithBalance(donor);105    const helpers = helper.ethNativeContract.contractHelpers(owner);106    const flipper = await helper.eth.deployFlipper(owner);107108    expect(await helpers.methods.hasPendingSponsor(flipper.options.address).call()).to.be.false;109    await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).send()).to.be.not.rejected;110    expect(await helpers.methods.hasPendingSponsor(flipper.options.address).call()).to.be.true;111  });112  113  itEth('Set sponsor event', async ({helper}) => {114    const owner = await helper.eth.createAccountWithBalance(donor);115    const sponsor = await helper.eth.createAccountWithBalance(donor);116    const helpers = helper.ethNativeContract.contractHelpers(owner);117    const flipper = await helper.eth.deployFlipper(owner);118    119    const result = await helpers.methods.setSponsor(flipper.options.address, sponsor).send();120    const events = helper.eth.normalizeEvents(result.events);121    expect(events).to.be.deep.equal([122      {123        address: flipper.options.address,124        event: 'ContractSponsorSet',125        args: {126          contractAddress: flipper.options.address,127          sponsor: sponsor,128        },129      },130    ]);131  });132  133  itEth('Sponsor can not be set by the address that did not deployed the contract', async ({helper}) => {134    const owner = await helper.eth.createAccountWithBalance(donor);135    const sponsor = await helper.eth.createAccountWithBalance(donor);136    const notOwner = await helper.eth.createAccountWithBalance(donor);137    const helpers = helper.ethNativeContract.contractHelpers(owner);138    const flipper = await helper.eth.deployFlipper(owner);139140    expect(await helpers.methods.hasPendingSponsor(flipper.options.address).call()).to.be.false;141    await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).call({from: notOwner})).to.be.rejectedWith('NoPermission');142    expect(await helpers.methods.hasPendingSponsor(flipper.options.address).call()).to.be.false;143  });144145  itEth('Sponsorship can be confirmed by the address that pending as sponsor', async ({helper}) => {146    const owner = await helper.eth.createAccountWithBalance(donor);147    const sponsor = await helper.eth.createAccountWithBalance(donor);148    const helpers = helper.ethNativeContract.contractHelpers(owner);149    const flipper = await helper.eth.deployFlipper(owner);150151    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;152    await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).send()).to.be.not.rejected;153    await expect(helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor})).to.be.not.rejected;154    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.true;155  });156157  itEth('Confirm sponsorship event', async ({helper}) => {158    const owner = await helper.eth.createAccountWithBalance(donor);159    const sponsor = await helper.eth.createAccountWithBalance(donor);160    const helpers = helper.ethNativeContract.contractHelpers(owner);161    const flipper = await helper.eth.deployFlipper(owner);162163    await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).send()).to.be.not.rejected;164    const result = await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});165    const events = helper.eth.normalizeEvents(result.events);166    expect(events).to.be.deep.equal([167      {168        address: flipper.options.address,169        event: 'ContractSponsorshipConfirmed',170        args: {171          contractAddress: flipper.options.address,172          sponsor: sponsor,173        },174      },175    ]);176  });177178  itEth('Sponsorship can not be confirmed by the address that not pending as sponsor', async ({helper}) => {179    const owner = await helper.eth.createAccountWithBalance(donor);180    const sponsor = await helper.eth.createAccountWithBalance(donor);181    const notSponsor = await helper.eth.createAccountWithBalance(donor);182    const helpers = helper.ethNativeContract.contractHelpers(owner);183    const flipper = await helper.eth.deployFlipper(owner);184185    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;186    await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).send()).to.be.not.rejected;187    await expect(helpers.methods.confirmSponsorship(flipper.options.address).call({from: notSponsor})).to.be.rejectedWith('NoPermission');188    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;189  });190191  itEth('Sponsorship can not be confirmed by the address that not set as sponsor', async ({helper}) => {192    const owner = await helper.eth.createAccountWithBalance(donor);193    const notSponsor = await helper.eth.createAccountWithBalance(donor);194    const helpers = helper.ethNativeContract.contractHelpers(owner);195    const flipper = await helper.eth.deployFlipper(owner);196197    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;198    await expect(helpers.methods.confirmSponsorship(flipper.options.address).call({from: notSponsor})).to.be.rejectedWith('NoPendingSponsor');199    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;200  });201202  itEth('Get self sponsored sponsor', async ({helper}) => {203    const owner = await helper.eth.createAccountWithBalance(donor);204    const helpers = helper.ethNativeContract.contractHelpers(owner);205    const flipper = await helper.eth.deployFlipper(owner);206207    await helpers.methods.selfSponsoredEnable(flipper.options.address).send();208    209    const result = await helpers.methods.sponsor(flipper.options.address).call();210211    expect(result[0]).to.be.eq(flipper.options.address);212    expect(result[1]).to.be.eq('0');213  });214215  itEth('Get confirmed sponsor', async ({helper}) => {216    const owner = await helper.eth.createAccountWithBalance(donor);217    const sponsor = await helper.eth.createAccountWithBalance(donor);218    const helpers = helper.ethNativeContract.contractHelpers(owner);219    const flipper = await helper.eth.deployFlipper(owner);220221    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();222    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});223    224    const result = await helpers.methods.sponsor(flipper.options.address).call();225226    expect(result[0]).to.be.eq(sponsor);227    expect(result[1]).to.be.eq('0');228  });229230  itEth('Sponsor can be removed by the address that deployed the contract', async ({helper}) => {231    const owner = await helper.eth.createAccountWithBalance(donor);232    const sponsor = await helper.eth.createAccountWithBalance(donor);233    const helpers = helper.ethNativeContract.contractHelpers(owner);234    const flipper = await helper.eth.deployFlipper(owner);235236    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;237    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();238    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});239    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.true;240    241    await helpers.methods.removeSponsor(flipper.options.address).send();242    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;243  });244245  itEth('Remove sponsor event', async ({helper}) => {246    const owner = await helper.eth.createAccountWithBalance(donor);247    const sponsor = await helper.eth.createAccountWithBalance(donor);248    const helpers = helper.ethNativeContract.contractHelpers(owner);249    const flipper = await helper.eth.deployFlipper(owner);250251    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();252    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});253    254    const result = await helpers.methods.removeSponsor(flipper.options.address).send();255    const events = helper.eth.normalizeEvents(result.events);256    expect(events).to.be.deep.equal([257      {258        address: flipper.options.address,259        event: 'ContractSponsorRemoved',260        args: {261          contractAddress: flipper.options.address,262        },263      },264    ]);265  });266267  itEth('Sponsor can not be removed by the address that did not deployed the contract', async ({helper}) => {268    const owner = await helper.eth.createAccountWithBalance(donor);269    const notOwner = await helper.eth.createAccountWithBalance(donor);270    const sponsor = await helper.eth.createAccountWithBalance(donor);271    const helpers = helper.ethNativeContract.contractHelpers(owner);272    const flipper = await helper.eth.deployFlipper(owner);273274    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;275    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();276    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});277    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.true;278    279    await expect(helpers.methods.removeSponsor(flipper.options.address).call({from: notOwner})).to.be.rejectedWith('NoPermission');280    expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.true;281  });282283  itEth('In generous mode, non-allowlisted user transaction will be sponsored', async ({helper}) => {284    const owner = await helper.eth.createAccountWithBalance(donor);285    const sponsor = await helper.eth.createAccountWithBalance(donor);286    const caller = await helper.eth.createAccountWithBalance(donor);287    const helpers = helper.ethNativeContract.contractHelpers(owner);288    const flipper = await helper.eth.deployFlipper(owner);289290    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();291    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});292293    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: owner});294    await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});295296    const sponsorBalanceBefore = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(sponsor));297    const callerBalanceBefore = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(caller));298299    await flipper.methods.flip().send({from: caller});300    expect(await flipper.methods.getValue().call()).to.be.true;301302    // Balance should be taken from sponsor instead of caller303    const sponsorBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(sponsor));304    const callerBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(caller));305    expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;306    expect(callerBalanceAfter).to.be.eq(callerBalanceBefore);307  });308309  itEth('In generous mode, non-allowlisted user transaction will be self sponsored', async ({helper}) => {310    const owner = await helper.eth.createAccountWithBalance(donor);311    const caller = await helper.eth.createAccountWithBalance(donor);312    const helpers = helper.ethNativeContract.contractHelpers(owner);313    const flipper = await helper.eth.deployFlipper(owner);314315    await helpers.methods.selfSponsoredEnable(flipper.options.address).send();316317    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: owner});318    await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});319320    await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address);321322    const contractBalanceBefore = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(flipper.options.address));323    const callerBalanceBefore = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(caller));324325    await flipper.methods.flip().send({from: caller});326    expect(await flipper.methods.getValue().call()).to.be.true;327328    // Balance should be taken from sponsor instead of caller329    const contractBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(flipper.options.address));330    const callerBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(caller));331    expect(contractBalanceAfter < contractBalanceBefore).to.be.true;332    expect(callerBalanceAfter).to.be.eq(callerBalanceBefore);333  });334335  itEth('Sponsoring is set, an address that has no UNQ can send a transaction and it works. Sponsor balance should decrease (allowlisted)', async ({helper}) => {336    const owner = await helper.eth.createAccountWithBalance(donor);337    const sponsor = await helper.eth.createAccountWithBalance(donor);338    const caller = helper.eth.createAccount();339    const helpers = helper.ethNativeContract.contractHelpers(owner);340    const flipper = await helper.eth.deployFlipper(owner);341342    await helpers.methods.toggleAllowlist(flipper.options.address, true).send({from: owner});343    await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({from: owner});344345    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner});346    await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});347348    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();349    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});350351    const sponsorBalanceBefore = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(sponsor));352    expect(sponsorBalanceBefore).to.be.not.equal('0');353354    await flipper.methods.flip().send({from: caller});355    expect(await flipper.methods.getValue().call()).to.be.true;356357    // Balance should be taken from flipper instead of caller358    const sponsorBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(sponsor));359    expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;360  });361362  itEth('Sponsoring is set, an address that has no UNQ can send a transaction and it works. Sponsor balance should not decrease (non-allowlisted)', async ({helper}) => {363    const owner = await helper.eth.createAccountWithBalance(donor);364    const caller = await helper.eth.createAccount();365    const helpers = helper.ethNativeContract.contractHelpers(owner);366    const flipper = await helper.eth.deployFlipper(owner);367368    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner});369    await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});370371    await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address);372373    const originalFlipperBalance = await helper.balance.getEthereum(flipper.options.address);374    expect(originalFlipperBalance).to.be.not.equal('0');375376    await expect(flipper.methods.flip().send({from: caller})).to.be.rejectedWith(/InvalidTransaction::Payment/);377    expect(await flipper.methods.getValue().call()).to.be.false;378379    // Balance should be taken from flipper instead of caller380    // FIXME the comment is wrong! What check should be here?381    const balanceAfter = await helper.balance.getEthereum(flipper.options.address);382    expect(balanceAfter).to.be.equals(originalFlipperBalance);383  });384385  itEth('Sponsoring is set, an address that has UNQ can send a transaction and it works. User balance should not change', async ({helper}) => {386    const owner = await helper.eth.createAccountWithBalance(donor);387    const sponsor = await helper.eth.createAccountWithBalance(donor);388    const caller = await helper.eth.createAccountWithBalance(donor);389    const helpers = helper.ethNativeContract.contractHelpers(owner);390    const flipper = await helper.eth.deployFlipper(owner);391392    await helpers.methods.toggleAllowlist(flipper.options.address, true).send({from: owner});393    await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({from: owner});394395    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner});396    await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});397398    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();399    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});400401    const sponsorBalanceBefore = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(sponsor));402    const callerBalanceBefore = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(caller));403404    await flipper.methods.flip().send({from: caller});405    expect(await flipper.methods.getValue().call()).to.be.true;406407    const sponsorBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(sponsor));408    const callerBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(caller));409    expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;410    expect(callerBalanceAfter).to.be.equals(callerBalanceBefore);411  });412413  itEth('Sponsoring is limited, with setContractRateLimit. The limitation is working if transactions are sent more often, the sender pays the commission.', async ({helper}) => {414    const owner = await helper.eth.createAccountWithBalance(donor);415    const sponsor = await helper.eth.createAccountWithBalance(donor);416    const caller = await helper.eth.createAccountWithBalance(donor);417    const helpers = helper.ethNativeContract.contractHelpers(owner);418    const flipper = await helper.eth.deployFlipper(owner);419    420    const originalCallerBalance = await helper.balance.getEthereum(caller);421    await helpers.methods.toggleAllowlist(flipper.options.address, true).send({from: owner});422    await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({from: owner});423424    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner});425    await helpers.methods.setSponsoringRateLimit(flipper.options.address, 10).send({from: owner});426427    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();428    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});429430    const originalFlipperBalance = await helper.balance.getEthereum(sponsor);431    expect(originalFlipperBalance).to.be.not.equal('0');432433    await flipper.methods.flip().send({from: caller});434    expect(await flipper.methods.getValue().call()).to.be.true;435    expect(await helper.balance.getEthereum(caller)).to.be.equals(originalCallerBalance);436437    const newFlipperBalance = await helper.balance.getEthereum(sponsor);438    expect(newFlipperBalance).to.be.not.equals(originalFlipperBalance);439440    await flipper.methods.flip().send({from: caller});441    expect(await helper.balance.getEthereum(sponsor)).to.be.equal(newFlipperBalance);442    expect(await helper.balance.getEthereum(caller)).to.be.not.equals(originalCallerBalance);443  });444445  // TODO: Find a way to calculate default rate limit446  itEth('Default rate limit equals 7200', async ({helper}) => {447    const owner = await helper.eth.createAccountWithBalance(donor);448    const helpers = helper.ethNativeContract.contractHelpers(owner);449    const flipper = await helper.eth.deployFlipper(owner);450451    expect(await helpers.methods.sponsoringRateLimit(flipper.options.address).call()).to.be.equals('7200');452  });453});454455describe('Sponsoring Fee Limit', () => {456  let donor: IKeyringPair;457  let alice: IKeyringPair;458  let DEFAULT_GAS: number;459460  function compileTestContract() {461    if (!testContract) {462      const input = {463        language: 'Solidity',464        sources: {465          ['TestContract.sol']: {466            content:467            `468            // SPDX-License-Identifier: MIT469            pragma solidity ^0.8.0;470            471            contract TestContract {472              event Result(bool);473474              function test(uint32 cycles) public {475                uint256 counter = 0;476                while(true) {477                  counter ++;478                  if (counter > cycles){479                    break;480                  }481                }482                emit Result(true);483              }484            }485            `,486          },487        },488        settings: {489          outputSelection: {490            '*': {491              '*': ['*'],492            },493          },494        },495      };496      const json = JSON.parse(solc.compile(JSON.stringify(input)));497      const out = json.contracts['TestContract.sol']['TestContract'];498  499      testContract = {500        abi: out.abi,501        object: '0x' + out.evm.bytecode.object,502      };503    }504    return testContract;505  }506  507  async function deployTestContract(helper: EthUniqueHelper, owner: string) {508    const web3 = helper.getWeb3();509    const compiled = compileTestContract();510    const testContract = new web3.eth.Contract(compiled.abi, undefined, {511      data: compiled.object,512      from: owner,513      gas: DEFAULT_GAS,514    });515    return await testContract.deploy({data: compiled.object}).send({from: owner});516  }517518  before(async () => {519    await usingEthPlaygrounds(async (helper, privateKey) => {520      donor = privateKey('//Alice');521      DEFAULT_GAS = helper.eth.DEFAULT_GAS;522    });523  });524525  beforeEach(async () => {526    await usingPlaygrounds(async (helper) => {527      [alice] = await helper.arrange.createAccounts([1000n], donor);528    });529  });530531  let testContract: CompiledContract;532  533534535  itEth('Default fee limit', async ({helper}) => {536    const owner = await helper.eth.createAccountWithBalance(donor);537    const helpers = helper.ethNativeContract.contractHelpers(owner);538    const flipper = await helper.eth.deployFlipper(owner);539540    expect(await helpers.methods.sponsoringFeeLimit(flipper.options.address).call()).to.be.equals('115792089237316195423570985008687907853269984665640564039457584007913129639935');541  });542543  itEth('Set fee limit', async ({helper}) => {544    const owner = await helper.eth.createAccountWithBalance(donor);545    const helpers = helper.ethNativeContract.contractHelpers(owner);546    const flipper = await helper.eth.deployFlipper(owner);547548    await helpers.methods.setSponsoringFeeLimit(flipper.options.address, 100).send();549    expect(await helpers.methods.sponsoringFeeLimit(flipper.options.address).call()).to.be.equals('100');550  });551552  itEth('Negative test - set fee limit by non-owner', async ({helper}) => {553    const owner = await helper.eth.createAccountWithBalance(donor);554    const stranger = await helper.eth.createAccountWithBalance(donor);555    const helpers = helper.ethNativeContract.contractHelpers(owner);556    const flipper = await helper.eth.deployFlipper(owner);557558    await expect(helpers.methods.setSponsoringFeeLimit(flipper.options.address, 100).send({from: stranger})).to.be.rejected;559  });560561  itEth('Negative test - check that eth transactions exceeding fee limit are not executed', async ({helper}) => {562    const owner = await helper.eth.createAccountWithBalance(donor);563    const sponsor = await helper.eth.createAccountWithBalance(donor);564    const user = await helper.eth.createAccountWithBalance(donor);565    const helpers = helper.ethNativeContract.contractHelpers(owner);566567    const testContract = await deployTestContract(helper, owner);568    569    await helpers.methods.setSponsoringMode(testContract.options.address, SponsoringMode.Generous).send({from: owner});570    await helpers.methods.setSponsoringRateLimit(testContract.options.address, 0).send({from: owner});571    572    await helpers.methods.setSponsor(testContract.options.address, sponsor).send();573    await helpers.methods.confirmSponsorship(testContract.options.address).send({from: sponsor});574575    const gasPrice = BigInt(await helper.getWeb3().eth.getGasPrice());576577    await helpers.methods.setSponsoringFeeLimit(testContract.options.address, 2_000_000n * gasPrice).send();578579    const originalUserBalance = await helper.balance.getEthereum(user);580    await testContract.methods.test(100).send({from: user, gas: 2_000_000});581    expect(await helper.balance.getEthereum(user)).to.be.equal(originalUserBalance);582583    await testContract.methods.test(100).send({from: user, gas: 2_100_000});584    expect(await helper.balance.getEthereum(user)).to.not.be.equal(originalUserBalance);585  });586587  itEth('Negative test - check that evm.call transactions exceeding fee limit are not executed', async ({helper, privateKey}) => {588    const owner = await helper.eth.createAccountWithBalance(donor);589    const sponsor = await helper.eth.createAccountWithBalance(donor);590    const helpers = helper.ethNativeContract.contractHelpers(owner);591592    const testContract = await deployTestContract(helper, owner);593    594    await helpers.methods.setSponsoringMode(testContract.options.address, SponsoringMode.Generous).send({from: owner});595    await helpers.methods.setSponsoringRateLimit(testContract.options.address, 0).send({from: owner});596    597    await helpers.methods.setSponsor(testContract.options.address, sponsor).send();598    await helpers.methods.confirmSponsorship(testContract.options.address).send({from: sponsor});599600    const gasPrice = BigInt(await helper.getWeb3().eth.getGasPrice());601602    await helpers.methods.setSponsoringFeeLimit(testContract.options.address, 2_000_000n * gasPrice).send();603604    const originalAliceBalance = await helper.balance.getSubstrate(alice.address);605606    await helper.eth.sendEVM(607      alice,608      testContract.options.address,609      testContract.methods.test(100).encodeABI(),610      '0',611      2_000_000,612    );613    // expect((await api.query.system.account(alice.address)).data.free.toBigInt()).to.be.equal(originalAliceBalance);614    expect(await helper.balance.getSubstrate(alice.address)).to.be.equal(originalAliceBalance);615    616    await helper.eth.sendEVM(617      alice,618      testContract.options.address,619      testContract.methods.test(100).encodeABI(),620      '0',621      2_100_000,622    );623    expect(await helper.balance.getSubstrate(alice.address)).to.not.be.equal(originalAliceBalance);624  });625});
modifiedtests/src/eth/scheduling.test.tsdiffbeforeafterboth
--- a/tests/src/eth/scheduling.test.ts
+++ b/tests/src/eth/scheduling.test.ts
@@ -18,7 +18,8 @@
 import {createEthAccountWithBalance, deployFlipper, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from './util/helpers';
 import {scheduleExpectSuccess, waitNewBlocks, requirePallets, Pallets} from '../util/helpers';
 
-describe('Scheduing EVM smart contracts', () => {
+// TODO mrshiposha update this test in #581
+describe.skip('Scheduing EVM smart contracts', () => {
   before(async function() {
     await requirePallets(this, [Pallets.Scheduler]);
   });
modifiedtests/src/eth/sponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/sponsoring.test.ts
+++ b/tests/src/eth/sponsoring.test.ts
@@ -14,20 +14,31 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-import {expect} from 'chai';
-import {contractHelpers, createEthAccount, createEthAccountWithBalance, deployCollector, deployFlipper, itWeb3, SponsoringMode} from './util/helpers';
+import {IKeyringPair} from '@polkadot/types/types';
+import {itEth, expect, SponsoringMode} from '../eth/util/playgrounds';
+import {usingPlaygrounds} from './../util/playgrounds/index';
 
 describe('EVM sponsoring', () => {
-  itWeb3('Fee is deducted from contract if sponsoring is enabled', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const caller = createEthAccount(web3);
-    const originalCallerBalance = await web3.eth.getBalance(caller);
-    expect(originalCallerBalance).to.be.equal('0');
+  let donor: IKeyringPair;
 
-    const flipper = await deployFlipper(web3, owner);
+  before(async () => {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      donor = privateKey('//Alice');
+    });
+  });
+
+  itEth('Fee is deducted from contract if sponsoring is enabled', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const sponsor = await helper.eth.createAccountWithBalance(donor);
+    const caller = helper.eth.createAccount();
+    const originalCallerBalance = await helper.balance.getEthereum(caller);
+
+    expect(originalCallerBalance).to.be.equal(0n);
+
+    const flipper = await helper.eth.deployFlipper(owner);
+
+    const helpers = helper.ethNativeContract.contractHelpers(owner);
 
-    const helpers = contractHelpers(web3, owner);
     await helpers.methods.toggleAllowlist(flipper.options.address, true).send({from: owner});
     await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({from: owner});
     
@@ -39,27 +50,29 @@
     await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});
     expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;
 
-    const originalSponsorBalance = await web3.eth.getBalance(sponsor);
-    expect(originalSponsorBalance).to.be.not.equal('0');
+    const originalSponsorBalance = await helper.balance.getEthereum(sponsor);
+    expect(originalSponsorBalance).to.be.not.equal(0n);
 
     await flipper.methods.flip().send({from: caller});
     expect(await flipper.methods.getValue().call()).to.be.true;
 
     // Balance should be taken from flipper instead of caller
-    expect(await web3.eth.getBalance(caller)).to.be.equals(originalCallerBalance);
-    expect(await web3.eth.getBalance(sponsor)).to.be.not.equals(originalSponsorBalance);
+    expect(await helper.balance.getEthereum(caller)).to.be.equal(originalCallerBalance);
+    expect(await helper.balance.getEthereum(sponsor)).to.be.not.equal(originalSponsorBalance);
   });
 
-  itWeb3('...but this doesn\'t applies to payable value', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const originalCallerBalance = await web3.eth.getBalance(caller);
-    expect(originalCallerBalance).to.be.not.equal('0');
+  itEth('...but this doesn\'t applies to payable value', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const sponsor = await helper.eth.createAccountWithBalance(donor);
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const originalCallerBalance = await helper.balance.getEthereum(caller);
+
+    expect(originalCallerBalance).to.be.not.equal(0n);
+
+    const collector = await helper.eth.deployCollectorContract(owner);
 
-    const collector = await deployCollector(web3, owner);
+    const helpers = helper.ethNativeContract.contractHelpers(owner);
 
-    const helpers = contractHelpers(web3, owner);
     await helpers.methods.toggleAllowlist(collector.options.address, true).send({from: owner});
     await helpers.methods.toggleAllowed(collector.options.address, caller, true).send({from: owner});
 
@@ -71,14 +84,14 @@
     await helpers.methods.setSponsor(collector.options.address, sponsor).send({from: owner});
     await helpers.methods.confirmSponsorship(collector.options.address).send({from: sponsor});
 
-    const originalSponsorBalance = await web3.eth.getBalance(sponsor);
-    expect(originalSponsorBalance).to.be.not.equal('0');
+    const originalSponsorBalance = await helper.balance.getEthereum(sponsor);
+    expect(originalSponsorBalance).to.be.not.equal(0n);
 
     await collector.methods.giveMoney().send({from: caller, value: '10000'});
 
     // Balance will be taken from both caller (value) and from collector (fee)
-    expect(await web3.eth.getBalance(caller)).to.be.equals((BigInt(originalCallerBalance) - 10000n).toString());
-    expect(await web3.eth.getBalance(sponsor)).to.be.not.equals(originalSponsorBalance);
+    expect(await helper.balance.getEthereum(caller)).to.be.equals((originalCallerBalance - 10000n));
+    expect(await helper.balance.getEthereum(sponsor)).to.be.not.equals(originalSponsorBalance);
     expect(await collector.methods.getCollected().call()).to.be.equal('10000');
   });
 });
modifiedtests/src/eth/tokenProperties.test.tsdiffbeforeafterboth
--- a/tests/src/eth/tokenProperties.test.ts
+++ b/tests/src/eth/tokenProperties.test.ts
@@ -1,94 +1,119 @@
-import {addCollectionAdminExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess} from '../util/helpers';
-import {cartesian, collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3} from './util/helpers';
-import nonFungibleAbi from './nonFungibleAbi.json';
-import {expect} from 'chai';
-import {executeTransaction} from '../substrate/substrate-api';
+import {IKeyringPair} from '@polkadot/types/types';
+import {usingPlaygrounds} from './../util/playgrounds/index';
+import {itEth, expect} from '../eth/util/playgrounds';
 
 describe('EVM token properties', () => {
-  itWeb3('Can be reconfigured', async({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+
+  before(async () => {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([1000n], donor);
+    });
+  });
+
+  itEth('Can be reconfigured', async({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+
     for(const [mutable,collectionAdmin, tokenOwner] of cartesian([], [false, true], [false, true], [false, true])) {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await addCollectionAdminExpectSuccess(alice, collection, {Ethereum: caller});
-      
-      const address = collectionIdToAddress(collection);
-      const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
-  
+      const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'ethp'});
+      await collection.addAdmin(alice, {Ethereum: caller});
+
+      const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+      const contract = helper.ethNativeContract.collection(address, 'nft', caller);
+
       await contract.methods.setTokenPropertyPermission('testKey', mutable, collectionAdmin, tokenOwner).send({from: caller});
   
-      const state = (await api.query.common.collectionPropertyPermissions(collection)).toJSON();
-      expect(state).to.be.deep.equal({
-        [web3.utils.toHex('testKey')]: {mutable, collectionAdmin, tokenOwner},
-      });
+      const state = await collection.getPropertyPermissions();
+      expect(state).to.be.deep.equal([{
+        key: 'testKey',
+        permission: {mutable, collectionAdmin, tokenOwner},
+      }]);
     }
   });
-  itWeb3('Can be set', async({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-    const token = await createItemExpectSuccess(alice, collection, 'NFT');
 
-    await executeTransaction(api, alice, api.tx.unique.setTokenPropertyPermissions(collection, [{
-      key: 'testKey',
-      permission: {
-        collectionAdmin: true,
-      },
-    }]));
+  itEth('Can be set', async({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.nft.mintCollection(alice, {
+      tokenPrefix: 'ethp',
+      tokenPropertyPermissions: [{
+        key: 'testKey',
+        permission: {
+          collectionAdmin: true,
+        },
+      }],
+    });
+    const token = await collection.mintToken(alice);
 
-    await addCollectionAdminExpectSuccess(alice, collection, {Ethereum: caller});
+    await collection.addAdmin(alice, {Ethereum: caller});
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'nft', caller);
 
-    await contract.methods.setProperty(token, 'testKey', Buffer.from('testValue')).send({from: caller});
+    await contract.methods.setProperty(token.tokenId, 'testKey', Buffer.from('testValue')).send({from: caller});
 
-    const [{value}] = (await api.rpc.unique.tokenProperties(collection, token, ['testKey'])).toHuman()! as any;
+    const [{value}] = await token.getProperties(['testKey']);
     expect(value).to.equal('testValue');
   });
-  itWeb3('Can be deleted', async({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-    const token = await createItemExpectSuccess(alice, collection, 'NFT');
 
-    await executeTransaction(api, alice, api.tx.unique.setTokenPropertyPermissions(collection, [{
-      key: 'testKey',
-      permission: {
-        mutable: true,
-        collectionAdmin: true,
-      },
-    }]));
-    await executeTransaction(api, alice, api.tx.unique.setTokenProperties(collection, token, [{key: 'testKey', value: 'testValue'}]));
+  itEth('Can be deleted', async({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.nft.mintCollection(alice, {
+      tokenPrefix: 'ethp',
+      tokenPropertyPermissions: [{
+        key: 'testKey',
+        permission: {
+          mutable: true,
+          collectionAdmin: true,
+        },
+      }],
+    });
+
+    await collection.addAdmin(alice, {Ethereum: caller});
 
-    await addCollectionAdminExpectSuccess(alice, collection, {Ethereum: caller});
+    const token = await collection.mintToken(alice);
+    await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}]);
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'nft', caller);
 
-    await contract.methods.deleteProperty(token, 'testKey').send({from: caller});
+    await contract.methods.deleteProperty(token.tokenId, 'testKey').send({from: caller});
 
-    const result = (await api.rpc.unique.tokenProperties(collection, token, ['testKey'])).toJSON()! as any;
+    const result = await token.getProperties(['testKey']);
     expect(result.length).to.equal(0);
   });
-  itWeb3('Can be read', async({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
-    const caller = createEthAccount(web3);
-    const collection = await createCollectionExpectSuccess({mode: {type:'NFT'}});
-    const token = await createItemExpectSuccess(alice, collection, 'NFT');
 
-    await executeTransaction(api, alice, api.tx.unique.setTokenPropertyPermissions(collection, [{
-      key: 'testKey',
-      permission: {
-        collectionAdmin: true,
-      },
-    }]));
-    await executeTransaction(api, alice, api.tx.unique.setTokenProperties(collection, token, [{key: 'testKey', value: 'testValue'}]));
+  itEth('Can be read', async({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.nft.mintCollection(alice, {
+      tokenPrefix: 'ethp',
+      tokenPropertyPermissions: [{
+        key: 'testKey',
+        permission: {
+          collectionAdmin: true,
+        },
+      }],
+    });
+    const token = await collection.mintToken(alice);
+    await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}]);
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'nft', caller);
 
-    const value = await contract.methods.property(token, 'testKey').call();
-    expect(value).to.equal(web3.utils.toHex('testValue'));
+    const value = await contract.methods.property(token.tokenId, 'testKey').call();
+    expect(value).to.equal(helper.getWeb3().utils.toHex('testValue'));
   });
 });
+
+
+type ElementOf<A> = A extends readonly (infer T)[] ? T : never;
+function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {
+  if(args.length === 0) {
+    yield internalRest as any;
+    return;
+  }
+  for(const value of args[0]) {
+    yield* cartesian([...internalRest, value], ...args.slice(1)) as any;
+  }
+}
\ No newline at end of file
modifiedtests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -6,4 +6,10 @@
 export interface CompiledContract {
   abi: any;
   object: string;
-}
\ No newline at end of file
+}
+
+export type NormalizedEvent = {
+  address: string,
+  event: string,
+  args: { [key: string]: string }
+};
modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -18,7 +18,7 @@
 
 import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';
 
-import {ContractImports, CompiledContract} from './types';
+import {ContractImports, CompiledContract, NormalizedEvent} from './types';
 
 // Native contracts ABI
 import collectionHelpersAbi from '../../collectionHelpersAbi.json';
@@ -252,6 +252,33 @@
 
     return before - after;
   }
+
+  normalizeEvents(events: any): NormalizedEvent[] {
+    const output = [];
+    for (const key of Object.keys(events)) {
+      if (key.match(/^[0-9]+$/)) {
+        output.push(events[key]);
+      } else if (Array.isArray(events[key])) {
+        output.push(...events[key]);
+      } else {
+        output.push(events[key]);
+      }
+    }
+    output.sort((a, b) => a.logIndex - b.logIndex);
+    return output.map(({address, event, returnValues}) => {
+      const args: { [key: string]: string } = {};
+      for (const key of Object.keys(returnValues)) {
+        if (!key.match(/^[0-9]+$/)) {
+          args[key] = returnValues[key];
+        }
+      }
+      return {
+        address,
+        event,
+        args,
+      };
+    });
+  }
 }  
 
 class EthAddressGroup extends EthGroupBase {