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

difftreelog

tests(dev-mode): all fixed up

Fahrrader2022-04-06parent: #219f5f0.patch.diff
in: master

4 files changed

modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -212,6 +212,16 @@
 				vec![
 					get_account_id_from_seed::<sr25519::Public>("Alice"),
 					get_account_id_from_seed::<sr25519::Public>("Bob"),
+					get_account_id_from_seed::<sr25519::Public>("Charlie"),
+					get_account_id_from_seed::<sr25519::Public>("Dave"),
+					get_account_id_from_seed::<sr25519::Public>("Eve"),
+					get_account_id_from_seed::<sr25519::Public>("Ferdie"),
+					get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
+					get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
+					get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),
+					get_account_id_from_seed::<sr25519::Public>("Dave//stash"),
+					get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
+					get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
 				],
 				1000
 			)
modifiedtests/src/eth/base.test.tsdiffbeforeafterboth
--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -34,7 +34,8 @@
     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;
+    const balanceB = await ethBalanceViaSub(api, userB);
+    expect(cost - balanceB < BigInt(0.2 * Number(UNIQUE))).to.be.true;
   });
 
   itWeb3('NFT transfer is close to 0.15 UNQ', async ({web3, api}) => {
modifiedtests/src/eth/util/helpers.tsdiffbeforeafterboth
before · tests/src/eth/util/helpers.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// eslint-disable-next-line @typescript-eslint/triple-slash-reference18/// <reference path="helpers.d.ts" />1920import {ApiPromise} from '@polkadot/api';21import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';22import Web3 from 'web3';23import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';24import {IKeyringPair} from '@polkadot/types/types';25import {expect} from 'chai';26import {getGenericResult, UNIQUE} from '../../util/helpers';27import * as solc from 'solc';28import config from '../../config';29import privateKey from '../../substrate/privateKey';30import contractHelpersAbi from './contractHelpersAbi.json';31import getBalance from '../../substrate/get-balance';3233export const GAS_ARGS = {gas: 2500000};3435export enum SponsoringMode {36  Disabled = 0,37  Allowlisted = 1,38  Generous = 2,39}4041let web3Connected = false;42export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {43  if (web3Connected) throw new Error('do not nest usingWeb3 calls');44  web3Connected = true;4546  const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);47  const web3 = new Web3(provider);4849  try {50    return await cb(web3);51  } finally {52    // provider.disconnect(3000, 'normal disconnect');53    provider.connection.close();54    web3Connected = false;55  }56}5758export function collectionIdToAddress(address: number): string {59  if (address >= 0xffffffff || address < 0) throw new Error('id overflow');60  const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,61    address >> 24,62    (address >> 16) & 0xff,63    (address >> 8) & 0xff,64    address & 0xff,65  ]);66  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));67}6869export function createEthAccount(web3: Web3) {70  const account = web3.eth.accounts.create();71  web3.eth.accounts.wallet.add(account.privateKey);72  return account.address;73}7475export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {76  const alice = privateKey('//Alice');77  const account = createEthAccount(web3);78  await transferBalanceToEth(api, alice, account);7980  return account;81}8283export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {84  const tx = api.tx.balances.transfer(evmToAddress(target), amount);85  const events = await submitTransactionAsync(source, tx);86  const result = getGenericResult(events);87  expect(result.success).to.be.true;88}8990export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {91  let i: any = it;92  if (opts.only) i = i.only;93  else if (opts.skip) i = i.skip;94  i(name, async () => {95    await usingApi(async api => {96      await usingWeb3(async web3 => {97        await cb({api, web3});98      });99    });100  });101}102itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});103itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});104105export async function generateSubstrateEthPair(web3: Web3) {106  const account = web3.eth.accounts.create();107  evmToAddress(account.address);108}109110type NormalizedEvent = {111    address: string,112    event: string,113    args: { [key: string]: string }114};115116export function normalizeEvents(events: any): NormalizedEvent[] {117  const output = [];118  for (const key of Object.keys(events)) {119    if (key.match(/^[0-9]+$/)) {120      output.push(events[key]);121    } else if (Array.isArray(events[key])) {122      output.push(...events[key]);123    } else {124      output.push(events[key]);125    }126  }127  output.sort((a, b) => a.logIndex - b.logIndex);128  return output.map(({address, event, returnValues}) => {129    const args: { [key: string]: string } = {};130    for (const key of Object.keys(returnValues)) {131      if (!key.match(/^[0-9]+$/)) {132        args[key] = returnValues[key];133      }134    }135    return {136      address,137      event,138      args,139    };140  });141}142143export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {144  const out: any = [];145  contract.events.allEvents((_: any, event: any) => {146    out.push(event);147  });148  await action();149  return normalizeEvents(out);150}151152export function subToEthLowercase(eth: string): string {153  const bytes = addressToEvm(eth);154  return '0x' + Buffer.from(bytes).toString('hex');155}156157export function subToEth(eth: string): string {158  return Web3.utils.toChecksumAddress(subToEthLowercase(eth));159}160161export function compileContract(name: string, src: string) {162  const out = JSON.parse(solc.compile(JSON.stringify({163    language: 'Solidity',164    sources: {165      [`${name}.sol`]: {166        content: `167          // SPDX-License-Identifier: UNLICENSED168          pragma solidity ^0.8.6;169170          ${src}171        `,172      },173    },174    settings: {175      outputSelection: {176        '*': {177          '*': ['*'],178        },179      },180    },181  }))).contracts[`${name}.sol`][name];182183  return {184    abi: out.abi,185    object: '0x' + out.evm.bytecode.object,186  };187}188189export async function deployFlipper(web3: Web3, deployer: string) {190  const compiled = compileContract('Flipper', `191    contract Flipper {192      bool value = false;193      function flip() public {194        value = !value;195      }196      function getValue() public view returns (bool) {197        return value;198      }199    }200  `);201  const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {202    data: compiled.object,203    from: deployer,204    ...GAS_ARGS,205  });206  const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});207208  return flipper;209}210211export async function deployCollector(web3: Web3, deployer: string) {212  const compiled = compileContract('Collector', `213    contract Collector {214      uint256 collected;215      fallback() external payable {216        giveMoney();217      }218      function giveMoney() public payable {219        collected += msg.value;220      }221      function getCollected() public view returns (uint256) {222        return collected;223      }224      function getUnaccounted() public view returns (uint256) {225        return address(this).balance - collected;226      }227228      function withdraw(address payable target) public {229        target.transfer(collected);230        collected = 0;231      }232    }233  `);234  const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {235    data: compiled.object,236    from: deployer,237    ...GAS_ARGS,238  });239  const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});240241  return collector;242}243244export function contractHelpers(web3: Web3, caller: string) {245  return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});246}247248/**249 * Execute ethereum method call using substrate account250 * @param to target contract251 * @param mkTx - closure, receiving `contract.methods`, and returning method call,252 * to be used as following (assuming `to` = erc20 contract):253 * `m => m.transfer(to, amount)`254 *255 * # Example256 * ```ts257 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));258 * ```259 */260export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {261  const tx = api.tx.evm.call(262    subToEth(from.address),263    to.options.address,264    mkTx(to.methods).encodeABI(),265    value,266    GAS_ARGS.gas,267    await web3.eth.getGasPrice(),268    null,269    null,270    [],271  );272  const events = await submitTransactionAsync(from, tx);273  expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;274}275276export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {277  return (await getBalance(api, [evmToAddress(address)]))[0];278}279280/**281 * Measure how much gas given closure consumes282 *283 * @param user which user balance will be checked284 */285export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {286  const before = await ethBalanceViaSub(api, user);287288  await call();289290  const after = await ethBalanceViaSub(api, user);291292  // Can't use .to.be.less, because chai doesn't supports bigint293  expect(after < before).to.be.true;294295  return before - after;296}
after · tests/src/eth/util/helpers.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// eslint-disable-next-line @typescript-eslint/triple-slash-reference18/// <reference path="helpers.d.ts" />1920import {ApiPromise} from '@polkadot/api';21import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';22import Web3 from 'web3';23import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';24import {IKeyringPair} from '@polkadot/types/types';25import {expect} from 'chai';26import {getGenericResult, UNIQUE} from '../../util/helpers';27import * as solc from 'solc';28import config from '../../config';29import privateKey from '../../substrate/privateKey';30import contractHelpersAbi from './contractHelpersAbi.json';31import getBalance from '../../substrate/get-balance';32import waitNewBlocks from '../../substrate/wait-new-blocks';3334export const GAS_ARGS = {gas: 2500000};3536export enum SponsoringMode {37  Disabled = 0,38  Allowlisted = 1,39  Generous = 2,40}4142let web3Connected = false;43export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {44  if (web3Connected) throw new Error('do not nest usingWeb3 calls');45  web3Connected = true;4647  const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);48  const web3 = new Web3(provider);4950  try {51    return await cb(web3);52  } finally {53    // provider.disconnect(3000, 'normal disconnect');54    provider.connection.close();55    web3Connected = false;56  }57}5859export function collectionIdToAddress(address: number): string {60  if (address >= 0xffffffff || address < 0) throw new Error('id overflow');61  const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,62    address >> 24,63    (address >> 16) & 0xff,64    (address >> 8) & 0xff,65    address & 0xff,66  ]);67  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));68}6970export function createEthAccount(web3: Web3) {71  const account = web3.eth.accounts.create();72  web3.eth.accounts.wallet.add(account.privateKey);73  return account.address;74}7576export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {77  const alice = privateKey('//Alice');78  const account = createEthAccount(web3);79  await transferBalanceToEth(api, alice, account);8081  return account;82}8384export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {85  const tx = api.tx.balances.transfer(evmToAddress(target), amount);86  const events = await submitTransactionAsync(source, tx);87  const result = getGenericResult(events);88  expect(result.success).to.be.true;89}9091export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {92  let i: any = it;93  if (opts.only) i = i.only;94  else if (opts.skip) i = i.skip;95  i(name, async () => {96    await usingApi(async api => {97      await usingWeb3(async web3 => {98        await cb({api, web3});99      });100    });101  });102}103itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});104itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});105106export async function generateSubstrateEthPair(web3: Web3) {107  const account = web3.eth.accounts.create();108  evmToAddress(account.address);109}110111type NormalizedEvent = {112    address: string,113    event: string,114    args: { [key: string]: string }115};116117export function normalizeEvents(events: any): NormalizedEvent[] {118  const output = [];119  for (const key of Object.keys(events)) {120    if (key.match(/^[0-9]+$/)) {121      output.push(events[key]);122    } else if (Array.isArray(events[key])) {123      output.push(...events[key]);124    } else {125      output.push(events[key]);126    }127  }128  output.sort((a, b) => a.logIndex - b.logIndex);129  return output.map(({address, event, returnValues}) => {130    const args: { [key: string]: string } = {};131    for (const key of Object.keys(returnValues)) {132      if (!key.match(/^[0-9]+$/)) {133        args[key] = returnValues[key];134      }135    }136    return {137      address,138      event,139      args,140    };141  });142}143144export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {145  const out: any = [];146  contract.events.allEvents((_: any, event: any) => {147    out.push(event);148  });149  await action();150  return normalizeEvents(out);151}152153export function subToEthLowercase(eth: string): string {154  const bytes = addressToEvm(eth);155  return '0x' + Buffer.from(bytes).toString('hex');156}157158export function subToEth(eth: string): string {159  return Web3.utils.toChecksumAddress(subToEthLowercase(eth));160}161162export function compileContract(name: string, src: string) {163  const out = JSON.parse(solc.compile(JSON.stringify({164    language: 'Solidity',165    sources: {166      [`${name}.sol`]: {167        content: `168          // SPDX-License-Identifier: UNLICENSED169          pragma solidity ^0.8.6;170171          ${src}172        `,173      },174    },175    settings: {176      outputSelection: {177        '*': {178          '*': ['*'],179        },180      },181    },182  }))).contracts[`${name}.sol`][name];183184  return {185    abi: out.abi,186    object: '0x' + out.evm.bytecode.object,187  };188}189190export async function deployFlipper(web3: Web3, deployer: string) {191  const compiled = compileContract('Flipper', `192    contract Flipper {193      bool value = false;194      function flip() public {195        value = !value;196      }197      function getValue() public view returns (bool) {198        return value;199      }200    }201  `);202  const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {203    data: compiled.object,204    from: deployer,205    ...GAS_ARGS,206  });207  const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});208209  return flipper;210}211212export async function deployCollector(web3: Web3, deployer: string) {213  const compiled = compileContract('Collector', `214    contract Collector {215      uint256 collected;216      fallback() external payable {217        giveMoney();218      }219      function giveMoney() public payable {220        collected += msg.value;221      }222      function getCollected() public view returns (uint256) {223        return collected;224      }225      function getUnaccounted() public view returns (uint256) {226        return address(this).balance - collected;227      }228229      function withdraw(address payable target) public {230        target.transfer(collected);231        collected = 0;232      }233    }234  `);235  const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {236    data: compiled.object,237    from: deployer,238    ...GAS_ARGS,239  });240  const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});241242  return collector;243}244245export function contractHelpers(web3: Web3, caller: string) {246  return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});247}248249/**250 * Execute ethereum method call using substrate account251 * @param to target contract252 * @param mkTx - closure, receiving `contract.methods`, and returning method call,253 * to be used as following (assuming `to` = erc20 contract):254 * `m => m.transfer(to, amount)`255 *256 * # Example257 * ```ts258 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));259 * ```260 */261export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {262  const tx = api.tx.evm.call(263    subToEth(from.address),264    to.options.address,265    mkTx(to.methods).encodeABI(),266    value,267    GAS_ARGS.gas,268    await web3.eth.getGasPrice(),269    null,270    null,271    [],272  );273  const events = await submitTransactionAsync(from, tx);274  expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;275}276277export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {278  return (await getBalance(api, [evmToAddress(address)]))[0];279}280281/**282 * Measure how much gas given closure consumes283 *284 * @param user which user balance will be checked285 */286export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {287  const before = await ethBalanceViaSub(api, user);288289  await call();290291  // In dev mode, the transaction might not finish processing in time292  await waitNewBlocks(api, 1);293  const after = await ethBalanceViaSub(api, user);294295  // Can't use .to.be.less, because chai doesn't supports bigint296  expect(after < before).to.be.true;297298  return before - after;299}
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -344,15 +344,12 @@
     // Run the CreateCollection transaction
     const alicePrivateKey = privateKey('//Alice');
     const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});
-    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
-    const result = getCreateCollectionResult(events);
+    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
 
     // Get number of collections after the transaction
     const collectionCountAfter = await getCreatedCollectionCount(api);
 
     // What to expect
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.false;
     expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');
   });
 }