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

difftreelog

test call fees

Yaroslav Bolyukin2021-08-18parent: #0999c79.patch.diff
in: master

6 files changed

addedtests/src/eth/base.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/base.test.ts
@@ -0,0 +1,22 @@
+
+import { createEthAccount, createEthAccountWithBalance, deployFlipper, ethBalanceViaSub, GAS_ARGS, itWeb3, recordEthFee } from './util/helpers';
+import { expect } from 'chai';
+import { UNIQUE } from '../util/helpers';
+
+describe('Contract calls', () => {
+  itWeb3('Call of simple contract fee is less than 0.2 UNQ', async ({ web3, api }) => {
+    const deployer = await createEthAccountWithBalance(api, web3);
+    const flipper = await deployFlipper(web3 as any, deployer);
+
+    const cost = await recordEthFee(api, deployer, () => flipper.methods.flip());
+    expect(cost < BigInt(0.2 * Number(UNIQUE))).to.be.true;
+  });
+
+  itWeb3('Balance transfer fee is less than 0.2 UNQ', async ({ web3, api }) => {
+    const userA = await createEthAccountWithBalance(api, web3);
+    const userB = createEthAccount(web3);
+
+    const cost = await recordEthFee(api, userA, () => web3.eth.sendTransaction({ from: userA, to: userB, value: '1000000', ...GAS_ARGS }));
+    expect(cost - await ethBalanceViaSub(api, userB) < BigInt(0.2 * Number(UNIQUE))).to.be.true;
+  });
+});
\ No newline at end of file
modifiedtests/src/eth/fungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/fungible.test.ts
+++ b/tests/src/eth/fungible.test.ts
@@ -4,8 +4,8 @@
 //
 
 import privateKey from '../substrate/privateKey';
-import { approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess } from '../util/helpers';
-import { collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents, recordEvents, subToEth, transferBalanceToEth } from './util/helpers';
+import { approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess, UNIQUE } from '../util/helpers';
+import { collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, transferBalanceToEth } from './util/helpers';
 import fungibleAbi from './fungibleAbi.json';
 import { expect } from 'chai';
 
@@ -192,6 +192,64 @@
   });
 });
 
+describe('Fungible: Fees', () => {
+  itWeb3('approve() call fee is less than 0.2UNQ', async ({ web3, api }) => {
+    const collection = await createCollectionExpectSuccess({
+      mode: { type: 'Fungible', decimalPoints: 0 },
+    });
+    const alice = privateKey('//Alice');
+
+    const owner = await createEthAccountWithBalance(api, web3);
+    const spender = createEthAccount(web3);
+
+    await createFungibleItemExpectSuccess(alice, collection, { Value: 200n }, { ethereum: owner });
+
+    const address = collectionIdToAddress(collection);
+    const contract = new web3.eth.Contract(fungibleAbi as any, address, { from: owner, ...GAS_ARGS });
+
+    const cost = await recordEthFee(api, owner, () => contract.methods.approve(spender, 100).send({ from: owner }));
+    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+  });
+
+  itWeb3('transferFrom() call fee is less than 0.2UNQ', async ({ web3, api }) => {
+    const collection = await createCollectionExpectSuccess({
+      mode: {type: 'Fungible', decimalPoints: 0},
+    });
+    const alice = privateKey('//Alice');
+  
+    const owner = await createEthAccountWithBalance(api, web3);
+    const spender = await createEthAccountWithBalance(api, web3);
+
+    await createFungibleItemExpectSuccess(alice, collection, { Value: 200n }, { ethereum: owner });
+
+    const address = collectionIdToAddress(collection);
+    const contract = new web3.eth.Contract(fungibleAbi as any, address, { from: owner, ...GAS_ARGS });
+
+    await contract.methods.approve(spender, 100).send({ from: owner });
+
+    const cost = await recordEthFee(api, spender, () => contract.methods.transferFrom(owner, spender, 100).send({ from: spender }));
+    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+  });
+
+  itWeb3('transfer() call fee is less than 0.2UNQ', async ({ web3, api }) => {
+    const collection = await createCollectionExpectSuccess({
+      mode: { type: 'Fungible', decimalPoints: 0 },
+    });
+    const alice = privateKey('//Alice');
+
+    const owner = await createEthAccountWithBalance(api, web3);
+    const receiver = createEthAccount(web3);
+
+    await createFungibleItemExpectSuccess(alice, collection, { Value: 200n }, { ethereum: owner });
+
+    const address = collectionIdToAddress(collection);
+    const contract = new web3.eth.Contract(fungibleAbi as any, address, { from: owner, ...GAS_ARGS });
+
+    const cost = await recordEthFee(api, owner, () => contract.methods.transfer(receiver, 100).send({ from: owner }));
+    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+  });
+});
+
 describe('Fungible: Substrate calls', () => {
   itWeb3('Events emitted for approve()', async ({ web3 }) => {
     const collection = await createCollectionExpectSuccess({
modifiedtests/src/eth/helpersSmoke.test.tsdiffbeforeafterboth
--- a/tests/src/eth/helpersSmoke.test.ts
+++ b/tests/src/eth/helpersSmoke.test.ts
@@ -1,26 +1,24 @@
 import { expect } from 'chai';
 import waitNewBlocks from '../substrate/wait-new-blocks';
-import { createEthAccountWithBalance, deployFlipper, itWeb3, usingWeb3Http, contractHelpers } from './util/helpers';
+import { createEthAccountWithBalance, deployFlipper, itWeb3, contractHelpers } from './util/helpers';
 
-itWeb3('Contract owner is recorded', async ({ api, web3 }) => {
-  await usingWeb3Http(async web3Http => {
-    const owner = await createEthAccountWithBalance(api, web3Http);
+describe('Helpers sanity check', () => {
+  itWeb3('Contract owner is recorded', async ({ api, web3 }) => {
+    const owner = await createEthAccountWithBalance(api, web3);
 
-    const flipper = await deployFlipper(web3Http, owner);
+    const flipper = await deployFlipper(web3, owner);
     await waitNewBlocks(api, 1);
 
     expect(await contractHelpers(web3, owner).methods.contractOwner(flipper.options.address).call()).to.be.equal(owner);
   });
-});
 
-itWeb3('Flipper is working', async({api}) => {
-  await usingWeb3Http(async web3Http => {
-    const owner = await createEthAccountWithBalance(api, web3Http);
-    const flipper = await deployFlipper(web3Http, owner);
+  itWeb3('Flipper is working', async ({ api, web3 }) => {
+    const owner = await createEthAccountWithBalance(api, web3);
+    const flipper = await deployFlipper(web3, owner);
     await waitNewBlocks(api, 1);
 
     expect(await flipper.methods.getValue().call()).to.be.false;
-    await flipper.methods.flip().send({from: owner});
+    await flipper.methods.flip().send({ from: owner });
     await waitNewBlocks(api, 1);
     expect(await flipper.methods.getValue().call()).to.be.true;
   });
modifiedtests/src/eth/nonFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -4,8 +4,8 @@
 //
 
 import privateKey from '../substrate/privateKey';
-import { approveExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess } from '../util/helpers';
-import { collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents, recordEvents, subToEth, transferBalanceToEth } from './util/helpers';
+import { approveExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess, UNIQUE } from '../util/helpers';
+import { collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, transferBalanceToEth } from './util/helpers';
 import nonFungibleAbi from './nonFungibleAbi.json';
 import { expect } from 'chai';
 import waitNewBlocks from '../substrate/wait-new-blocks';
@@ -192,6 +192,64 @@
   });
 });
 
+describe('NFT: Fees', () => {
+  itWeb3('approve() call fee is less than 0.2UNQ', async ({ web3, api }) => {
+    const collection = await createCollectionExpectSuccess({
+      mode: { type: 'NFT' },
+    });
+    const alice = privateKey('//Alice');
+
+    const owner = await createEthAccountWithBalance(api, web3);
+    const spender = createEthAccount(web3);
+
+    const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', { ethereum: owner });
+
+    const address = collectionIdToAddress(collection);
+    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, { from: owner, ...GAS_ARGS });
+
+    const cost = await recordEthFee(api, owner, () => contract.methods.approve(spender, tokenId).send({ from: owner }));
+    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+  });
+
+  itWeb3('transferFrom() call fee is less than 0.2UNQ', async ({ web3, api }) => {
+    const collection = await createCollectionExpectSuccess({
+      mode: { type: 'NFT' },
+    });
+    const alice = privateKey('//Alice');
+  
+    const owner = await createEthAccountWithBalance(api, web3);
+    const spender = await createEthAccountWithBalance(api, web3);
+
+    const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', { ethereum: owner });
+
+    const address = collectionIdToAddress(collection);
+    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, { from: owner, ...GAS_ARGS });
+
+    await contract.methods.approve(spender, tokenId).send({ from: owner });
+
+    const cost = await recordEthFee(api, spender, () => contract.methods.transferFrom(owner, spender, tokenId).send({ from: spender }));
+    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+  });
+
+  itWeb3('transfer() call fee is less than 0.2UNQ', async ({ web3, api }) => {
+    const collection = await createCollectionExpectSuccess({
+      mode: { type: 'NFT' },
+    });
+    const alice = privateKey('//Alice');
+
+    const owner = await createEthAccountWithBalance(api, web3);
+    const receiver = createEthAccount(web3);
+
+    const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', { ethereum: owner });
+
+    const address = collectionIdToAddress(collection);
+    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, { from: owner, ...GAS_ARGS });
+
+    const cost = await recordEthFee(api, owner, () => contract.methods.transfer(receiver, tokenId).send({ from: owner }));
+    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+  });
+});
+
 describe('NFT: Substrate calls', () => {
   itWeb3('Events emitted for approve()', async ({ web3 }) => {
     const collection = await createCollectionExpectSuccess({
modifiedtests/src/eth/util/helpers.tsdiffbeforeafterboth
before · tests/src/eth/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56// eslint-disable-next-line @typescript-eslint/triple-slash-reference7/// <reference path="helpers.d.ts" />89import { ApiPromise } from '@polkadot/api';10import { addressToEvm, evmToAddress } from '@polkadot/util-crypto';11import Web3 from 'web3';12import usingApi, { submitTransactionAsync } from '../../substrate/substrate-api';13import { IKeyringPair } from '@polkadot/types/types';14import { expect } from 'chai';15import { getGenericResult } from '../../util/helpers';16import * as solc from 'solc';17import config from '../../config';18import privateKey from '../../substrate/privateKey';19import contractHelpersAbi from './contractHelpersAbi.json';2021export const GAS_ARGS = { gas: 0x1000000, gasPrice: '0x01' };2223let web3Connected = false;24export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {25  if (web3Connected) throw new Error('do not nest usingWeb3 calls');26  web3Connected = true;2728  const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);29  const web3 = new Web3(provider);3031  try {32    return await cb(web3);33  } finally {34    // provider.disconnect(3000, 'normal disconnect');35    provider.connection.close();36    web3Connected = false;37  }38}3940type Web3HttpMarker = {web3Http: true};4142export async function usingWeb3Http<T>(cb: (web3: Web3 & Web3HttpMarker) => Promise<T> | T): Promise<T> {43  const provider = new Web3.providers.HttpProvider(config.frontierUrl);44  const web3: Web3 & Web3HttpMarker = new Web3(provider) as any;45  web3.web3Http = true;4647  return await cb(web3);48}4950export function collectionIdToAddress(address: number): string {51  if (address >= 0xffffffff || address < 0) throw new Error('id overflow');52  const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,53    address >> 24,54    (address >> 16) & 0xff,55    (address >> 8) & 0xff,56    address & 0xff,57  ]);58  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));59}6061export function createEthAccount(web3: Web3) {62  const account = web3.eth.accounts.create();63  web3.eth.accounts.wallet.add(account.privateKey);64  return account.address;65}6667export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {68  const alice = privateKey('//Alice');69  const account = createEthAccount(web3);70  await transferBalanceToEth(api, alice, account);7172  return account;73}7475export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 999999999999999) {76  const tx = api.tx.balances.transfer(evmToAddress(target), amount);77  const events = await submitTransactionAsync(source, tx);78  const result = getGenericResult(events);79  expect(result.success).to.be.true;80}8182export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {83  let i: any = it;84  if (opts.only) i = i.only;85  else if (opts.skip) i = i.skip;86  i(name, async () => {87    await usingApi(async api => {88      await usingWeb3(async web3 => {89        await cb({ api, web3 });90      });91    });92  });93}94itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { only: true });95itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { skip: true });9697export async function generateSubstrateEthPair(web3: Web3) {98  const account = web3.eth.accounts.create();99  evmToAddress(account.address);100}101102type NormalizedEvent = {103    address: string,104    event: string,105    args: { [key: string]: string }106};107108export function normalizeEvents(events: any): NormalizedEvent[] {109  const output = [];110  for (const key of Object.keys(events)) {111    if (key.match(/^[0-9]+$/)) {112      output.push(events[key]);113    } else if (Array.isArray(events[key])) {114      output.push(...events[key]);115    } else {116      output.push(events[key]);117    }118  }119  output.sort((a, b) => a.logIndex - b.logIndex);120  return output.map(({ address, event, returnValues }) => {121    const args: { [key: string]: string } = {};122    for (const key of Object.keys(returnValues)) {123      if (!key.match(/^[0-9]+$/)) {124        args[key] = returnValues[key];125      }126    }127    return {128      address,129      event,130      args,131    };132  });133}134135export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {136  const out: any = [];137  contract.events.allEvents((_: any, event: any) => {138    out.push(event);139  });140  await action();141  return normalizeEvents(out);142}143144export function subToEth(eth: string): string {145  const bytes = addressToEvm(eth);146  const string = '0x' + Buffer.from(bytes).toString('hex');147  return Web3.utils.toChecksumAddress(string);148}149150export function compileContract(name: string, src: string) {151  const out = JSON.parse(solc.compile(JSON.stringify({152    language: 'Solidity',153    sources: {154      [`${name}.sol`]: {155        content: `156          // SPDX-License-Identifier: UNLICENSED157          pragma solidity ^0.8.6;158159          ${src}160        `,161      },162    },163    settings: {164      outputSelection: {165        '*': {166          '*': ['*'],167        },168      },169    },170  }))).contracts[`${name}.sol`][name];171172  return {173    abi: out.abi,174    object: '0x' + out.evm.bytecode.object,175  };176}177178export async function deployFlipper(web3: Web3 & Web3HttpMarker, deployer: string) {179  const compiled = compileContract('Flipper', `180    contract Flipper {181      bool value = false;182      function flip() public {183        value = !value;184      }185      function getValue() public view returns (bool) {186        return value;187      }188    }189  `);190  const Flipper = new web3.eth.Contract(compiled.abi, undefined, {191    data: compiled.object,192    from: deployer,193    ...GAS_ARGS,194  });195  const flipper = await Flipper.deploy({ data: compiled.object }).send({from: deployer});196197  return flipper;198}199200export async function deployCollector(web3: Web3 & Web3HttpMarker, deployer: string) {201  const compiled = compileContract('Collector', `202    contract Collector {203      uint256 collected;204      function giveMoney() public payable {205        collected += msg.value;206      }207      function getCollected() public view returns (uint256) {208        return collected;209      }210    }211  `);212  const Collector = new web3.eth.Contract(compiled.abi, undefined, {213    data: compiled.object,214    from: deployer,215    ...GAS_ARGS,216  });217  const collector = await Collector.deploy({ data: compiled.object }).send({ from: deployer });218219  return collector;220}221222export function contractHelpers(web3: Web3, caller: string) {223  return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});224}
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -53,6 +53,11 @@
 
 export const U128_MAX = (1n << 128n) - 1n;
 
+const MICROUNIQUE = 1_000_000_000n;
+const MILLIUNIQUE = 1_000n * MICROUNIQUE;
+const CENTIUNIQUE = 10n * MILLIUNIQUE;
+export const UNIQUE = 100n * CENTIUNIQUE;
+
 type GenericResult = {
   success: boolean,
 };