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

difftreelog

refactor move token address mapping to trait

Yaroslav Bolyukin2022-04-07parent: #3ae92b8.patch.diff
in: master

6 files changed

modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -19,18 +19,12 @@
 
 // 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 1
 // TODO: Unhardcode prefix
-const ETH_ACCOUNT_PREFIX: [u8; 16] = [
+const ETH_COLLECTION_PREFIX: [u8; 16] = [
 	0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,
 ];
 
-// 0xf8238ccfff8ed887463fd5e00000000100000002  - collection 1, token 2
-// TODO: Unhardcode prefix
-const ETH_ACCOUNT_TOKEN_PREFIX: [u8; 12] = [
-	0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,
-];
-
 pub fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {
-	if eth[0..16] != ETH_ACCOUNT_PREFIX {
+	if eth[0..16] != ETH_COLLECTION_PREFIX {
 		return None;
 	}
 	let mut id_bytes = [0; 4];
@@ -39,28 +33,7 @@
 }
 pub fn collection_id_to_address(id: CollectionId) -> H160 {
 	let mut out = [0; 20];
-	out[0..16].copy_from_slice(&ETH_ACCOUNT_PREFIX);
+	out[0..16].copy_from_slice(&ETH_COLLECTION_PREFIX);
 	out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));
-	H160(out)
-}
-
-pub fn map_eth_to_token_id(eth: &H160) -> Option<(CollectionId, TokenId)> {
-	if eth[0..12] != ETH_ACCOUNT_TOKEN_PREFIX {
-		return None;
-	}
-	let mut id_bytes = [0; 4];
-	let mut token_id_bytes = [0; 4];
-	id_bytes.copy_from_slice(&eth[12..16]);
-	token_id_bytes.copy_from_slice(&eth[16..20]);
-	Some((
-		CollectionId(u32::from_be_bytes(id_bytes)),
-		TokenId(u32::from_be_bytes(token_id_bytes)),
-	))
-}
-pub fn collection_token_id_to_address(id: CollectionId, token: TokenId) -> H160 {
-	let mut out = [0; 20];
-	out[0..12].copy_from_slice(&ETH_ACCOUNT_TOKEN_PREFIX);
-	out[12..16].copy_from_slice(&u32::to_be_bytes(id.0));
-	out[16..20].copy_from_slice(&u32::to_be_bytes(token.0));
 	H160(out)
 }
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -165,8 +165,10 @@
 	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};
 	use pallet_evm::account;
 	use dispatch::CollectionDispatch;
+	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};
+	use frame_system::pallet_prelude::*;
 	use frame_support::traits::Currency;
-	use up_data_structs::TokenId;
+	use up_data_structs::{TokenId, mapping::TokenAddressMapping};
 	use scale_info::TypeInfo;
 	use up_evm_mapping::CrossAccountId;
 
@@ -185,6 +187,9 @@
 		type CollectionDispatch: CollectionDispatch<Self>;
 
 		type TreasuryAccountId: Get<Self::AccountId>;
+
+		type EvmTokenAddressMapping: TokenAddressMapping<H160>;
+		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;
 	}
 
 	#[pallet::pallet]
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -20,34 +20,23 @@
 	convert::{TryFrom, TryInto},
 	fmt,
 };
-use frame_support::storage::bounded_btree_map::BoundedBTreeMap;
-use sp_std::collections::btree_map::BTreeMap;
+use frame_support::{
+	storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},
+	traits::ConstU16,
+};
+use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet};
 
 #[cfg(feature = "serde")]
-pub use serde::{Serialize, Deserialize};
+use serde::{Serialize, Deserialize};
 
 use sp_core::U256;
 use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};
 use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};
-pub use frame_support::{
-	BoundedVec, construct_runtime, decl_event, decl_module, decl_storage, decl_error,
-	dispatch::DispatchResult,
-	ensure, fail, parameter_types,
-	traits::{
-		Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,
-		Randomness, IsSubType, WithdrawReasons,
-	},
-	weights::{
-		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
-		DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,
-		WeightToFeePolynomial, DispatchClass,
-	},
-	StorageValue, transactional,
-	pallet_prelude::ConstU32,
-};
+use frame_support::{BoundedVec, traits::ConstU32};
 use derivative::Derivative;
 use scale_info::TypeInfo;
 
+pub mod mapping;
 mod migration;
 
 pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;
addedprimitives/data-structs/src/mapping.rsdiffbeforeafterboth
--- /dev/null
+++ b/primitives/data-structs/src/mapping.rs
@@ -0,0 +1,63 @@
+use core::marker::PhantomData;
+
+use sp_core::H160;
+
+use crate::{CollectionId, TokenId};
+use up_evm_mapping::CrossAccountId;
+
+pub trait TokenAddressMapping<Address> {
+	fn token_to_address(collection: CollectionId, token: TokenId) -> Address;
+	fn address_to_token(address: &Address) -> Option<(CollectionId, TokenId)>;
+	fn is_token_address(address: &Address) -> bool;
+}
+
+pub struct EvmTokenAddressMapping;
+
+/// 0xf8238ccfff8ed887463fd5e00000000100000002  - collection 1, token 2
+const ETH_COLLECTION_TOKEN_PREFIX: [u8; 12] = [
+	0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,
+];
+
+impl TokenAddressMapping<H160> for EvmTokenAddressMapping {
+	fn token_to_address(collection: CollectionId, token: TokenId) -> H160 {
+		let mut out = [0; 20];
+		out[0..12].copy_from_slice(&ETH_COLLECTION_TOKEN_PREFIX);
+		out[12..16].copy_from_slice(&u32::to_be_bytes(collection.0));
+		out[16..20].copy_from_slice(&u32::to_be_bytes(token.0));
+		H160(out)
+	}
+
+	fn address_to_token(eth: &H160) -> Option<(CollectionId, TokenId)> {
+		if eth[0..12] != ETH_COLLECTION_TOKEN_PREFIX {
+			return None;
+		}
+		let mut id_bytes = [0; 4];
+		let mut token_id_bytes = [0; 4];
+		id_bytes.copy_from_slice(&eth[12..16]);
+		token_id_bytes.copy_from_slice(&eth[16..20]);
+		Some((
+			CollectionId(u32::from_be_bytes(id_bytes)),
+			TokenId(u32::from_be_bytes(token_id_bytes)),
+		))
+	}
+
+	fn is_token_address(address: &H160) -> bool {
+		address[0..12] == ETH_COLLECTION_TOKEN_PREFIX
+	}
+}
+
+pub struct CrossTokenAddressMapping<A>(PhantomData<A>);
+
+impl<A, C: CrossAccountId<A>> TokenAddressMapping<C> for CrossTokenAddressMapping<A> {
+	fn token_to_address(collection: CollectionId, token: TokenId) -> C {
+		C::from_eth(EvmTokenAddressMapping::token_to_address(collection, token))
+	}
+
+	fn address_to_token(address: &C) -> Option<(CollectionId, TokenId)> {
+		EvmTokenAddressMapping::address_to_token(address.as_eth())
+	}
+
+	fn is_token_address(address: &C) -> bool {
+		EvmTokenAddressMapping::is_token_address(address.as_eth())
+	}
+}
modifiedruntime/opal/src/lib.rsdiffbeforeafterboth
--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -66,6 +66,7 @@
 		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,
 	},
 };
+use up_data_structs::mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping};
 use up_data_structs::{CollectionId, TokenId, CollectionStats, Collection};
 // use pallet_contracts::weights::WeightInfo;
 // #[cfg(any(feature = "std", test))]
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';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}244245/** 246 * pallet evm_contract_helpers247 * @param web3 248 * @param caller - eth address249 * @returns 250 */251export function contractHelpers(web3: Web3, caller: string) {252  return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});253}254255/**256 * Execute ethereum method call using substrate account257 * @param to target contract258 * @param mkTx - closure, receiving `contract.methods`, and returning method call,259 * to be used as following (assuming `to` = erc20 contract):260 * `m => m.transfer(to, amount)`261 *262 * # Example263 * ```ts264 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));265 * ```266 */267export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {268  const tx = api.tx.evm.call(269    subToEth(from.address),270    to.options.address,271    mkTx(to.methods).encodeABI(),272    value,273    GAS_ARGS.gas,274    await web3.eth.getGasPrice(),275    null,276    null,277    [],278  );279  const events = await submitTransactionAsync(from, tx);280  expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;281}282283export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {284  return (await getBalance(api, [evmToAddress(address)]))[0];285}286287/**288 * Measure how much gas given closure consumes289 *290 * @param user which user balance will be checked291 */292export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {293  const before = await ethBalanceViaSub(api, user);294295  await call();296297  // In dev mode, the transaction might not finish processing in time298  await waitNewBlocks(api, 1);299  const after = await ethBalanceViaSub(api, user);300301  // Can't use .to.be.less, because chai doesn't supports bigint302  expect(after < before).to.be.true;303304  return before - after;305}
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}5859function encodeIntBE(v: number): number[] {60  if (v >= 0xffffffff || v < 0) throw new Error('id overflow');61  return [62    v >> 24,63    (v >> 16) & 0xff,64    (v >> 8) & 0xff,65    v & 0xff,66  ];67}6869export function collectionIdToAddress(collection: number): string {70  const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,71    ...encodeIntBE(collection),72  ]);73  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));74}7576export function tokenIdToAddress(collection: number, token: number): string {77  const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,78    ...encodeIntBE(collection),79    ...encodeIntBE(token),80  ]);81  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));82}8384export function createEthAccount(web3: Web3) {85  const account = web3.eth.accounts.create();86  web3.eth.accounts.wallet.add(account.privateKey);87  return account.address;88}8990export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {91  const alice = privateKey('//Alice');92  const account = createEthAccount(web3);93  await transferBalanceToEth(api, alice, account);9495  return account;96}9798export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {99  const tx = api.tx.balances.transfer(evmToAddress(target), amount);100  const events = await submitTransactionAsync(source, tx);101  const result = getGenericResult(events);102  expect(result.success).to.be.true;103}104105export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {106  let i: any = it;107  if (opts.only) i = i.only;108  else if (opts.skip) i = i.skip;109  i(name, async () => {110    await usingApi(async api => {111      await usingWeb3(async web3 => {112        await cb({api, web3});113      });114    });115  });116}117itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});118itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});119120export async function generateSubstrateEthPair(web3: Web3) {121  const account = web3.eth.accounts.create();122  evmToAddress(account.address);123}124125type NormalizedEvent = {126    address: string,127    event: string,128    args: { [key: string]: string }129};130131export function normalizeEvents(events: any): NormalizedEvent[] {132  const output = [];133  for (const key of Object.keys(events)) {134    if (key.match(/^[0-9]+$/)) {135      output.push(events[key]);136    } else if (Array.isArray(events[key])) {137      output.push(...events[key]);138    } else {139      output.push(events[key]);140    }141  }142  output.sort((a, b) => a.logIndex - b.logIndex);143  return output.map(({address, event, returnValues}) => {144    const args: { [key: string]: string } = {};145    for (const key of Object.keys(returnValues)) {146      if (!key.match(/^[0-9]+$/)) {147        args[key] = returnValues[key];148      }149    }150    return {151      address,152      event,153      args,154    };155  });156}157158export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {159  const out: any = [];160  contract.events.allEvents((_: any, event: any) => {161    out.push(event);162  });163  await action();164  return normalizeEvents(out);165}166167export function subToEthLowercase(eth: string): string {168  const bytes = addressToEvm(eth);169  return '0x' + Buffer.from(bytes).toString('hex');170}171172export function subToEth(eth: string): string {173  return Web3.utils.toChecksumAddress(subToEthLowercase(eth));174}175176export function compileContract(name: string, src: string) {177  const out = JSON.parse(solc.compile(JSON.stringify({178    language: 'Solidity',179    sources: {180      [`${name}.sol`]: {181        content: `182          // SPDX-License-Identifier: UNLICENSED183          pragma solidity ^0.8.6;184185          ${src}186        `,187      },188    },189    settings: {190      outputSelection: {191        '*': {192          '*': ['*'],193        },194      },195    },196  }))).contracts[`${name}.sol`][name];197198  return {199    abi: out.abi,200    object: '0x' + out.evm.bytecode.object,201  };202}203204export async function deployFlipper(web3: Web3, deployer: string) {205  const compiled = compileContract('Flipper', `206    contract Flipper {207      bool value = false;208      function flip() public {209        value = !value;210      }211      function getValue() public view returns (bool) {212        return value;213      }214    }215  `);216  const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {217    data: compiled.object,218    from: deployer,219    ...GAS_ARGS,220  });221  const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});222223  return flipper;224}225226export async function deployCollector(web3: Web3, deployer: string) {227  const compiled = compileContract('Collector', `228    contract Collector {229      uint256 collected;230      fallback() external payable {231        giveMoney();232      }233      function giveMoney() public payable {234        collected += msg.value;235      }236      function getCollected() public view returns (uint256) {237        return collected;238      }239      function getUnaccounted() public view returns (uint256) {240        return address(this).balance - collected;241      }242243      function withdraw(address payable target) public {244        target.transfer(collected);245        collected = 0;246      }247    }248  `);249  const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {250    data: compiled.object,251    from: deployer,252    ...GAS_ARGS,253  });254  const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});255256  return collector;257}258259/** 260 * pallet evm_contract_helpers261 * @param web3 262 * @param caller - eth address263 * @returns 264 */265export function contractHelpers(web3: Web3, caller: string) {266  return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});267}268269/**270 * Execute ethereum method call using substrate account271 * @param to target contract272 * @param mkTx - closure, receiving `contract.methods`, and returning method call,273 * to be used as following (assuming `to` = erc20 contract):274 * `m => m.transfer(to, amount)`275 *276 * # Example277 * ```ts278 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));279 * ```280 */281export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {282  const tx = api.tx.evm.call(283    subToEth(from.address),284    to.options.address,285    mkTx(to.methods).encodeABI(),286    value,287    GAS_ARGS.gas,288    await web3.eth.getGasPrice(),289    null,290    null,291    [],292  );293  const events = await submitTransactionAsync(from, tx);294  expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;295}296297export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {298  return (await getBalance(api, [evmToAddress(address)]))[0];299}300301/**302 * Measure how much gas given closure consumes303 *304 * @param user which user balance will be checked305 */306export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {307  const before = await ethBalanceViaSub(api, user);308309  await call();310311  // In dev mode, the transaction might not finish processing in time312  await waitNewBlocks(api, 1);313  const after = await ethBalanceViaSub(api, user);314315  // Can't use .to.be.less, because chai doesn't supports bigint316  expect(after < before).to.be.true;317318  return before - after;319}