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

difftreelog

test ethContract group for eth-playgrounds

Andrey2022-09-04parent: #a68b33e.patch.diff
in: master

5 files changed

modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -30,6 +30,7 @@
     "testEth": "mocha --timeout 9999999 -r ts-node/register './**/eth/**/*.test.ts'",
     "testEthMarketplace": "mocha --timeout 9999999 -r ts-node/register './**/eth/marketplace/**/*.test.ts'",
     "testEthNesting": "mocha --timeout 9999999 -r ts-node/register './**/eth/nesting/**/*.test.ts'",
+    "testEthPayable": "mocha --timeout 9999999 -r ts-node/register './**/eth/payable.test.ts'",
     "load": "mocha --timeout 9999999 -r ts-node/register './**/*.load.ts'",
     "loadTransfer": "ts-node src/transfer.nload.ts",
     "testCollision": "mocha --timeout 9999999 -r ts-node/register ./src/collision-tests/*.test.ts",
modifiedtests/src/eth/payable.test.tsdiffbeforeafterboth
before · tests/src/eth/payable.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 {expect} from 'chai';18import {submitTransactionAsync} from '../substrate/substrate-api';19import {createEthAccountWithBalance, deployCollector, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from './util/helpers';20import {evmToAddress} from '@polkadot/util-crypto';21import {getGenericResult, UNIQUE} from '../util/helpers';22import {getBalanceSingle, transferBalanceExpectSuccess} from '../substrate/get-balance';2324describe('EVM payable contracts', () => {25  itWeb3('Evm contract can receive wei from eth account', async ({api, web3, privateKeyWrapper}) => {26    const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);27    const contract = await deployCollector(web3, deployer);2829    await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: '10000', ...GAS_ARGS});3031    expect(await contract.methods.getCollected().call()).to.be.equal('10000');32  });3334  itWeb3('Evm contract can receive wei from substrate account', async ({api, web3, privateKeyWrapper}) => {35    const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);36    const contract = await deployCollector(web3, deployer);37    const alice = privateKeyWrapper('//Alice');3839    // Transaction fee/value will be payed from subToEth(sender) evm balance,40    // which is backed by evmToAddress(subToEth(sender)) substrate balance41    await transferBalanceToEth(api, alice, subToEth(alice.address));4243    {44      const tx = api.tx.evm.call(45        subToEth(alice.address),46        contract.options.address,47        contract.methods.giveMoney().encodeABI(),48        '10000',49        GAS_ARGS.gas,50        await web3.eth.getGasPrice(),51        null,52        null,53        [],54      );55      const events = await submitTransactionAsync(alice, tx);56      const result = getGenericResult(events);57      expect(result.success).to.be.true;58    }5960    expect(await contract.methods.getCollected().call()).to.be.equal('10000');61  });6263  // We can't handle sending balance to backing storage of evm balance, because evmToAddress operation is irreversible64  itWeb3('Wei sent directly to backing storage of evm contract balance is unaccounted', async({api, web3, privateKeyWrapper}) => {65    const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);66    const contract = await deployCollector(web3, deployer);67    const alice = privateKeyWrapper('//Alice');6869    await transferBalanceExpectSuccess(api, alice, evmToAddress(contract.options.address), '10000');7071    expect(await contract.methods.getUnaccounted().call()).to.be.equal('10000');72  });7374  itWeb3('Balance can be retrieved from evm contract', async({api, web3, privateKeyWrapper}) => {75    const FEE_BALANCE = 1000n * UNIQUE;76    const CONTRACT_BALANCE = 1n * UNIQUE;7778    const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);79    const contract = await deployCollector(web3, deployer);80    const alice = privateKeyWrapper('//Alice');8182    await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: CONTRACT_BALANCE.toString(), ...GAS_ARGS});8384    const receiver = privateKeyWrapper(`//Receiver${Date.now()}`);8586    // First receive balance on eth balance of bob87    {88      const ethReceiver = subToEth(receiver.address);89      expect(await web3.eth.getBalance(ethReceiver)).to.be.equal('0');90      await contract.methods.withdraw(ethReceiver).send({from: deployer});91      expect(await web3.eth.getBalance(ethReceiver)).to.be.equal(CONTRACT_BALANCE.toString());92    }9394    // Some balance is required to pay fee for evm.withdraw call95    await transferBalanceExpectSuccess(api, alice, receiver.address, FEE_BALANCE.toString());9697    // Withdraw balance from eth to substrate98    {99      const initialReceiverBalance = await getBalanceSingle(api, receiver.address);100      const tx = api.tx.evm.withdraw(101        subToEth(receiver.address),102        CONTRACT_BALANCE.toString(),103      );104      const events = await submitTransactionAsync(receiver, tx);105      const result = getGenericResult(events);106      expect(result.success).to.be.true;107      const finalReceiverBalance = await getBalanceSingle(api, receiver.address);108109      expect(finalReceiverBalance > initialReceiverBalance).to.be.true;110    }111  });112});
after · tests/src/eth/payable.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';1819import {itEth, expect, usingEthPlaygrounds} from './util/playgrounds';2021describe('EVM payable contracts', () => {22  let donor: IKeyringPair;2324  before(async function() {25    await usingEthPlaygrounds(async (helper, privateKey) => {26      donor = privateKey('//Alice');27    });28  });2930  itEth('Evm contract can receive wei from eth account', async ({helper}) => {31    const deployer = await helper.eth.createAccountWithBalance(donor);32    const contract = await helper.eth.deployCollectorContract(deployer);3334    const web3 = helper.getWeb3();3536    await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: '10000', gas: helper.eth.DEFAULT_GAS});3738    expect(await contract.methods.getCollected().call()).to.be.equal('10000');39  });4041  itEth('Evm contract can receive wei from substrate account', async ({helper}) => {42    const deployer = await helper.eth.createAccountWithBalance(donor);43    const contract = await helper.eth.deployCollectorContract(deployer);44    const [alice] = await helper.arrange.createAccounts([10n], donor);4546    const weiCount = '10000';4748    // Transaction fee/value will be payed from subToEth(sender) evm balance,49    // which is backed by evmToAddress(subToEth(sender)) substrate balance50    await helper.eth.transferBalanceFromSubstrate(alice, helper.address.substrateToEth(alice.address), 5n);515253    await helper.eth.callEVM(alice, contract.options.address, contract.methods.giveMoney().encodeABI(), weiCount);5455    expect(await contract.methods.getCollected().call()).to.be.equal(weiCount);56  });5758  // We can't handle sending balance to backing storage of evm balance, because evmToAddress operation is irreversible59  itEth('Wei sent directly to backing storage of evm contract balance is unaccounted', async({helper}) => {60    const deployer = await helper.eth.createAccountWithBalance(donor);61    const contract = await helper.eth.deployCollectorContract(deployer);62    const [alice] = await helper.arrange.createAccounts([10n], donor);6364    const weiCount = 10_000n;6566    await helper.eth.transferBalanceFromSubstrate(alice, contract.options.address, weiCount, false);6768    expect(await contract.methods.getUnaccounted().call()).to.be.equal(weiCount.toString());69  });7071  itEth('Balance can be retrieved from evm contract', async({helper, privateKey}) => {72    const FEE_BALANCE = 10n * helper.balance.getOneTokenNominal();73    const CONTRACT_BALANCE = 1n * helper.balance.getOneTokenNominal();7475    const deployer = await helper.eth.createAccountWithBalance(donor);76    const contract = await helper.eth.deployCollectorContract(deployer);77    const [alice] = await helper.arrange.createAccounts([20n], donor);7879    const web3 = helper.getWeb3();8081    await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: CONTRACT_BALANCE.toString(), gas: helper.eth.DEFAULT_GAS});8283    const receiver = privateKey(`//Receiver${Date.now()}`);8485    // First receive balance on eth balance of bob86    {87      const ethReceiver = helper.address.substrateToEth(receiver.address);88      expect(await web3.eth.getBalance(ethReceiver)).to.be.equal('0');89      await contract.methods.withdraw(ethReceiver).send({from: deployer});90      expect(await web3.eth.getBalance(ethReceiver)).to.be.equal(CONTRACT_BALANCE.toString());91    }9293    // Some balance is required to pay fee for evm.withdraw call94    await helper.balance.transferToSubstrate(alice, receiver.address, FEE_BALANCE);95    // await transferBalanceExpectSuccess(api, alice, receiver.address, FEE_BALANCE.toString());9697    // Withdraw balance from eth to substrate98    {99      const initialReceiverBalance = await helper.balance.getSubstrate(receiver.address);100      await helper.executeExtrinsic(receiver, 'api.tx.evm.withdraw', [helper.address.substrateToEth(receiver.address), CONTRACT_BALANCE.toString()], true);101      const finalReceiverBalance = await helper.balance.getSubstrate(receiver.address);102103      expect(finalReceiverBalance > initialReceiverBalance).to.be.true;104    }105  });106});
addedtests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -0,0 +1,9 @@
+export interface ContractImports {
+  solPath: string;
+  fsPath: string;
+}
+
+export interface CompiledContract {
+  abi: any;
+  object: string;
+}
\ No newline at end of file
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
@@ -3,15 +3,21 @@
 
 /* eslint-disable function-call-argument-newline */
 
+import {readFile} from 'fs/promises';
+
 import Web3 from 'web3';
 import {WebsocketProvider} from 'web3-core';
 import {Contract} from 'web3-eth-contract';
 
+import * as solc from 'solc';
+
 import {evmToAddress} from '@polkadot/util-crypto';
 import {IKeyringPair} from '@polkadot/types/types';
 
 import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';
 
+import {ContractImports, CompiledContract} from './types';
+
 // Native contracts ABI
 import collectionHelpersAbi from '../../collectionHelpersAbi.json';
 import fungibleAbi from '../../fungibleAbi.json';
@@ -27,19 +33,75 @@
     this.helper = helper;
   }
 }
+
+
+class ContractGroup extends EthGroupBase {
+  async findImports(imports?: ContractImports[]){
+    if(!imports) return function(path: string) {
+      return {error: 'File not found'};
+    };
+  
+    const knownImports = {} as any;
+    for(let imp of imports) {
+      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();
+    }
+  
+    return function(path: string) {
+      if(knownImports.hasOwnProperty(path)) return {contents: knownImports[path]};
+      return {error: 'File not found'};
+    }
+  }
+
+  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {
+    const out = JSON.parse(solc.compile(JSON.stringify({
+      language: 'Solidity',
+      sources: {
+        [`${name}.sol`]: {
+          content: src,
+        },
+      },
+      settings: {
+        outputSelection: {
+          '*': {
+            '*': ['*'],
+          },
+        },
+      },
+    }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];
   
+    return {
+      abi: out.abi,
+      object: '0x' + out.evm.bytecode.object,
+    };
+  }
+
+  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {
+    const compiledContract = await this.compile(name, src, imports);
+    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);
+  }
+
+  async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {
+    const web3 = this.helper.getWeb3();
+    const contract = new web3.eth.Contract(abi, undefined, {
+      data: object,
+      from: signer,
+      gas: this.helper.eth.DEFAULT_GAS
+    });
+    return await contract.deploy({data: object}).send({from: signer});
+  }
+
+}
   
 class NativeContractGroup extends EthGroupBase {
-  DEFAULT_GAS = 2_500_000;
 
   contractHelpers(caller: string): Contract {
     const web3 = this.helper.getWeb3();
-    return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.DEFAULT_GAS});
+    return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});
   }
 
   collectionHelpers(caller: string) {
     const web3 = this.helper.getWeb3();
-    return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.DEFAULT_GAS});
+    return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});
   }
 
   collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {
@@ -49,12 +111,12 @@
       'ft': fungibleAbi
     }[mode];
     const web3 = this.helper.getWeb3();
-    return new web3.eth.Contract(abi as any, address, {gas: this.DEFAULT_GAS, ...(caller ? {from: caller} : {})});
+    return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});
   }
 
   rftTokenByAddress(address: string, caller?: string): Contract {
     const web3 = this.helper.getWeb3();
-    return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.DEFAULT_GAS, ...(caller ? {from: caller} : {})});
+    return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});
   }
 
   rftToken(collectionId: number, tokenId: number, caller?: string): Contract {
@@ -64,6 +126,8 @@
 
   
 class EthGroup extends EthGroupBase {
+  DEFAULT_GAS = 2_500_000;
+
   createAccount() {
     const web3 = this.helper.getWeb3();
     const account = web3.eth.accounts.create();
@@ -78,8 +142,20 @@
     return account;
   }
 
-  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n) {
-    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * this.helper.balance.getOneTokenNominal());
+  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {
+    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));
+  }
+
+  async callEVM(signer: IKeyringPair, contractAddress: string, abi: any, value: string, gasLimit?: number) {
+    if(!gasLimit) gasLimit = this.DEFAULT_GAS;
+    const web3 = this.helper.getWeb3();
+    const gasPrice = await web3.eth.getGasPrice();
+    // TODO: check execution status
+    await this.helper.executeExtrinsic(
+      signer,
+      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],
+      true, `Unable to perform evm.call`
+    );
   }
 
   async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
@@ -92,6 +168,34 @@
 
     return {collectionId, collectionAddress};
   }
+
+  async deployCollectorContract(signer: string): Promise<Contract> {
+    return await this.helper.ethContract.deployByCode(signer, 'Collector', `
+    // SPDX-License-Identifier: UNLICENSED
+    pragma solidity ^0.8.6;
+
+    contract Collector {
+      uint256 collected;
+      fallback() external payable {
+        giveMoney();
+      }
+      function giveMoney() public payable {
+        collected += msg.value;
+      }
+      function getCollected() public view returns (uint256) {
+        return collected;
+      }
+      function getUnaccounted() public view returns (uint256) {
+        return address(this).balance - collected;
+      }
+
+      function withdraw(address payable target) public {
+        target.transfer(collected);
+        collected = 0;
+      }
+    }
+  `);
+  }
 }
   
   
@@ -134,12 +238,14 @@
   eth: EthGroup;
   ethAddress: EthAddressGroup;
   ethNativeContract: NativeContractGroup;
+  ethContract: ContractGroup;
 
   constructor(logger: { log: (msg: any, level: any) => void, level: any }) {
     super(logger);
     this.eth = new EthGroup(this);
     this.ethAddress = new EthAddressGroup(this);
     this.ethNativeContract = new NativeContractGroup(this);
+    this.ethContract = new ContractGroup(this);
   }
 
   getWeb3(): Web3 {
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -388,6 +388,7 @@
       type: this.chainLogType.EXTRINSIC,
       status: result.status,
       call: extrinsic,
+      signer: this.getSignerAddress(sender),
       params,
     } as IUniqueHelperLog;