git.delta.rocks / unique-network / refs/commits / 82643c5daa1a

difftreelog

feat add tests

Trubnikov Sergey2023-04-25parent: #f0ad1b0.patch.diff
in: master

12 files changed

modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -267,7 +267,7 @@
 pub fn development_config() -> DefaultChainSpec {
 	let mut properties = Map::new();
 	properties.insert("tokenSymbol".into(), default_runtime::TOKEN_SYMBOL.into());
-	properties.insert("tokenDecimals".into(), 18.into());
+	properties.insert("tokenDecimals".into(), default_runtime::DECIMALS.into());
 	properties.insert(
 		"ss58Format".into(),
 		default_runtime::SS58Prefix::get().into(),
@@ -341,7 +341,7 @@
 pub fn local_testnet_config() -> DefaultChainSpec {
 	let mut properties = Map::new();
 	properties.insert("tokenSymbol".into(), default_runtime::TOKEN_SYMBOL.into());
-	properties.insert("tokenDecimals".into(), 18.into());
+	properties.insert("tokenDecimals".into(), default_runtime::DECIMALS.into());
 	properties.insert(
 		"ss58Format".into(),
 		default_runtime::SS58Prefix::get().into(),
modifiedpallets/balances-adapter/src/erc.rsdiffbeforeafterboth
--- a/pallets/balances-adapter/src/erc.rs
+++ b/pallets/balances-adapter/src/erc.rs
@@ -38,14 +38,14 @@
 
 #[solidity_interface(name = ERC20, events(ERC20Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x942e8b22)]
 impl<T: Config> NativeFungibleHandle<T> {
-	fn allowance(&self, owner: Address, spender: Address) -> Result<U256> {
+	fn allowance(&self, _owner: Address, _spender: Address) -> Result<U256> {
 		Ok(U256::zero())
 	}
 
 	// #[weight(<SelfWeightOf<T>>::approve())]
-	fn approve(&mut self, caller: Caller, spender: Address, amount: U256) -> Result<bool> {
+	fn approve(&mut self, _caller: Caller, _spender: Address, _amount: U256) -> Result<bool> {
 		// self.consume_store_reads(1)?;
-		Err("Approve not supported now".into())
+		Err("Approve not supported".into())
 	}
 
 	fn balance_of(&self, owner: Address) -> Result<U256> {
@@ -106,7 +106,7 @@
 		let to = T::CrossAccountId::from_eth(to);
 		let amount = amount.try_into().map_err(|_| "amount overflow")?;
 
-		if from != to {
+		if from != caller {
 			return Err("no permission".into());
 		}
 		// let budget = self
@@ -171,7 +171,7 @@
 		let to = to.into_sub_cross_account::<T>()?;
 		let amount = amount.try_into().map_err(|_| "amount overflow")?;
 
-		if from != to {
+		if from != caller {
 			return Err("no permission".into());
 		}
 
modifiedpallets/common/src/dispatch.rsdiffbeforeafterboth
--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -83,7 +83,7 @@
 	///
 	/// * `sender` - The owner of the collection.
 	/// * `handle` - Collection handle.
-	fn destroy(sender: T::CrossAccountId, handle: CollectionHandle<T>) -> DispatchResult;
+	fn destroy(sender: T::CrossAccountId, collection_id: CollectionId) -> DispatchResult;
 
 	/// Get a specialized collection from the handle.
 	///
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -1296,10 +1296,7 @@
 			sender: T::CrossAccountId,
 			collection_id: CollectionId,
 		) -> DispatchResult {
-			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			collection.check_is_internal()?;
-
-			T::CollectionDispatch::destroy(sender, collection)?;
+			T::CollectionDispatch::destroy(sender, collection_id)?;
 
 			// TODO: basket cleanup should be moved elsewhere
 			// Maybe runtime dispatch.rs should perform it?
modifiedruntime/common/config/pallets/mod.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -24,7 +24,8 @@
 		weights::CommonWeights,
 		RelayChainBlockNumberProvider,
 	},
-	Runtime, RuntimeEvent, RuntimeCall, RuntimeOrigin, RUNTIME_NAME, TOKEN_SYMBOL, Balances,
+	Runtime, RuntimeEvent, RuntimeCall, RuntimeOrigin, RUNTIME_NAME, TOKEN_SYMBOL, DECIMALS,
+	Balances,
 };
 use frame_support::traits::{ConstU32, ConstU64, Currency};
 use up_common::{
@@ -53,7 +54,7 @@
 
 parameter_types! {
 	pub const CollectionCreationPrice: Balance = 2 * UNIQUE;
-	pub const Decimals: u8 = 32;
+	pub const Decimals: u8 = DECIMALS;
 	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account_truncating();
 	pub Name: String = RUNTIME_NAME.to_string();
 	pub Symbol: String = TOKEN_SYMBOL.to_string();
modifiedruntime/common/dispatch.rsdiffbeforeafterboth
--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -99,7 +99,10 @@
 		Ok(id)
 	}
 
-	fn destroy(sender: T::CrossAccountId, collection: CollectionHandle<T>) -> DispatchResult {
+	fn destroy(sender: T::CrossAccountId, collection_id: CollectionId) -> DispatchResult {
+		let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+		collection.check_is_internal()?;
+
 		match collection.mode {
 			CollectionMode::ReFungible => {
 				PalletRefungible::destroy_collection(RefungibleHandle::cast(collection), &sender)?
modifiedruntime/opal/src/lib.rsdiffbeforeafterboth
--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -45,6 +45,7 @@
 
 pub const RUNTIME_NAME: &str = "opal";
 pub const TOKEN_SYMBOL: &str = "OPL";
+pub const DECIMALS: u8 = 18;
 
 /// This runtime version.
 pub const VERSION: RuntimeVersion = RuntimeVersion {
modifiedruntime/quartz/src/lib.rsdiffbeforeafterboth
--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -48,6 +48,7 @@
 #[cfg(not(feature = "become-sapphire"))]
 pub const RUNTIME_NAME: &str = "quartz";
 pub const TOKEN_SYMBOL: &str = "QTZ";
+pub const DECIMALS: u8 = 18;
 
 /// This runtime version.
 pub const VERSION: RuntimeVersion = RuntimeVersion {
modifiedruntime/unique/src/lib.rsdiffbeforeafterboth
--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -45,6 +45,7 @@
 
 pub const RUNTIME_NAME: &str = "unique";
 pub const TOKEN_SYMBOL: &str = "UNQ";
+pub const DECIMALS: u8 = 18;
 
 /// This runtime version.
 pub const VERSION: RuntimeVersion = RuntimeVersion {
modifiedtests/src/eth/nativeFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nativeFungible.test.ts
+++ b/tests/src/eth/nativeFungible.test.ts
@@ -15,29 +15,157 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import {IKeyringPair} from '@polkadot/types/types';
-import {itEth, usingEthPlaygrounds} from './util';
+import {expect, itEth, usingEthPlaygrounds} from './util';
 
-describe('NativeFungible: Plain calls', () => {
+describe('NativeFungible: ERC20 calls', () => {
   let donor: IKeyringPair;
-  let alice: IKeyringPair;
-  let owner: IKeyringPair;
 
   before(async function() {
     await usingEthPlaygrounds(async (helper, privateKey) => {
       donor = await privateKey({url: import.meta.url});
-      [alice, owner] = await helper.arrange.createAccounts([30n, 20n], donor);
+      // [alice] = await helper.arrange.createAccounts([30n], donor);
     });
   });
 
-  itEth.skip('Can perform approve()', async ({helper}) => {
+  itEth('approve()', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const spender = helper.eth.createAccount();
-    const collection = await helper.ft.mintCollection(alice);
-    await collection.mint(alice, 200n, {Ethereum: owner});
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    await expect(contract.methods.approve(spender, 100).call({from: owner})).to.be.rejectedWith('Approve not supported');
+  });
+
+  itEth('balanceOf()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor, 123n);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const balance = await contract.methods.balanceOf(owner).call({from: owner});
+    expect(balance).to.be.eq('123000000000000000000');
+  });
+
+  itEth('decimals()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const decimals = await contract.methods.decimals().call({from: owner});
+    expect(decimals).to.be.eq('18');
+  });
+
+  itEth('name()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const name = await contract.methods.name().call({from: owner});
+    expect(name).to.be.eq('opal');
+  });
+
+  itEth('symbol()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const name = await contract.methods.symbol().call({from: owner});
+    expect(name).to.be.eq('OPL');
+  });
+
+  itEth('totalSupply()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const totalSupplyEth = BigInt(await contract.methods.totalSupply().call({from: owner}));
+    const totalSupplySub = await helper.balance.getTotalIssuance();
+    expect(totalSupplyEth).to.be.eq(totalSupplySub);
+  });
+
+  itEth('transfer()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const balanceOwnerBefore = await helper.balance.getEthereum(owner);
+    const balanceReceiverBefore = await helper.balance.getEthereum(receiver);
+
+    await contract.methods.transfer(receiver, 50).send({from: owner});
+
+    const balanceOwnerAfter = await helper.balance.getEthereum(owner);
+    const balanceReceiverAfter = await helper.balance.getEthereum(receiver);
+
+    expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
+    expect(balanceReceiverBefore === balanceReceiverAfter - 50n).to.be.true;
+  });
 
+  itEth('transferFrom()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = await helper.eth.createAccountWithBalance(donor);
     const collectionAddress = helper.ethAddress.fromCollectionId(0);
     const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
 
-    await contract.methods.approve(spender, 100).send({from: owner});
+    const balanceOwnerBefore = await helper.balance.getEthereum(owner);
+    const balanceReceiverBefore = await helper.balance.getEthereum(receiver);
+
+    await contract.methods.transferFrom(owner, receiver, 50).send({from: owner});
+
+    const balanceOwnerAfter = await helper.balance.getEthereum(owner);
+    const balanceReceiverAfter = await helper.balance.getEthereum(receiver);
+
+    expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
+    expect(balanceReceiverBefore === balanceReceiverAfter - 50n).to.be.true;
+
+    await expect(contract.methods.transferFrom(receiver, receiver, 50).call({from: owner})).to.be.rejectedWith('no permission');
+  });
+});
+
+describe('NativeFungible: ERC20UniqueExtensions calls', () => {
+  let donor: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = await privateKey({url: import.meta.url});
+      // [alice] = await helper.arrange.createAccounts([30n], donor);
+    });
+  });
+
+  itEth('transferCross()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = await helper.ethCrossAccount.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const balanceOwnerBefore = await helper.balance.getEthereum(owner);
+    const balanceReceiverBefore = await helper.balance.getEthereum(receiver.eth);
+
+    await contract.methods.transferCross(receiver, 50).send({from: owner});
+
+    const balanceOwnerAfter = await helper.balance.getEthereum(owner);
+    const balanceReceiverAfter = await helper.balance.getEthereum(receiver.eth);
+
+    expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
+    expect(balanceReceiverBefore === balanceReceiverAfter - 50n).to.be.true;
+  });
+
+  itEth('transferFromCross()', async ({helper}) => {
+    const owner = await helper.ethCrossAccount.createAccountWithBalance(donor);
+    const receiver = await helper.ethCrossAccount.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner.eth);
+
+    const balanceOwnerBefore = await helper.balance.getEthereum(owner.eth);
+    const balanceReceiverBefore = await helper.balance.getEthereum(receiver.eth);
+
+    await contract.methods.transferFromCross(owner, receiver, 50).send({from: owner.eth});
+
+    const balanceOwnerAfter = await helper.balance.getEthereum(owner.eth);
+    const balanceReceiverAfter = await helper.balance.getEthereum(receiver.eth);
+
+    expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
+    expect(balanceReceiverBefore === balanceReceiverAfter - 50n).to.be.true;
+
+    await expect(contract.methods.transferFromCross(receiver, receiver, 50).call({from: owner.eth})).to.be.rejectedWith('no permission');
   });
 });
\ No newline at end of file
modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
before · tests/src/eth/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable function-call-argument-newline */5// eslint-disable-next-line @typescript-eslint/triple-slash-reference6/// <reference path="unique.dev.d.ts" />78import {readFile} from 'fs/promises';910import Web3 from 'web3';11import {WebsocketProvider} from 'web3-core';12import {Contract} from 'web3-eth-contract';1314import solc from 'solc';1516import {evmToAddress} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';1819import {ArrangeGroup, DevUniqueHelper} from '../../../util/playgrounds/unique.dev';2021import {ContractImports, CompiledContract, CrossAddress, NormalizedEvent, EthProperty} from './types';2223// Native contracts ABI24import collectionHelpersAbi from '../../abi/collectionHelpers.json' assert {type: 'json'};25import nativeFungibleAbi from '../../abi/nativeFungible.json' assert {type: 'json'};26import fungibleAbi from '../../abi/fungible.json' assert {type: 'json'};27import fungibleDeprecatedAbi from '../../abi/fungibleDeprecated.json' assert {type: 'json'};28import nonFungibleAbi from '../../abi/nonFungible.json' assert {type: 'json'};29import nonFungibleDeprecatedAbi from '../../abi/nonFungibleDeprecated.json' assert {type: 'json'};30import refungibleAbi from '../../abi/reFungible.json' assert {type: 'json'};31import refungibleDeprecatedAbi from '../../abi/reFungibleDeprecated.json' assert {type: 'json'};32import refungibleTokenAbi from '../../abi/reFungibleToken.json' assert {type: 'json'};33import refungibleTokenDeprecatedAbi from '../../abi/reFungibleTokenDeprecated.json' assert {type: 'json'};34import contractHelpersAbi from '../../abi/contractHelpers.json' assert {type: 'json'};35import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';36import {TCollectionMode} from '../../../util/playgrounds/types';3738class EthGroupBase {39  helper: EthUniqueHelper;40  gasPrice?: string;4142  constructor(helper: EthUniqueHelper) {43    this.helper = helper;44  }45  async getGasPrice() {46    if (this.gasPrice)47      return this.gasPrice;48    this.gasPrice = await this.helper.getWeb3().eth.getGasPrice();49    return this.gasPrice;50  }51}525354class ContractGroup extends EthGroupBase {55  async findImports(imports?: ContractImports[]) {56    if (!imports) return function(path: string) {57      return {error: `File not found: ${path}`};58    };5960    const knownImports = {} as { [key: string]: string };61    for (const imp of imports) {62      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();63    }6465    return function(path: string) {66      if (path in knownImports) return {contents: knownImports[path]};67      return {error: `File not found: ${path}`};68    };69  }7071  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {72    const compiled = JSON.parse(solc.compile(JSON.stringify({73      language: 'Solidity',74      sources: {75        [`${name}.sol`]: {76          content: src,77        },78      },79      settings: {80        outputSelection: {81          '*': {82            '*': ['*'],83          },84        },85      },86    }), {import: await this.findImports(imports)}));8788    const hasErrors = compiled['errors']89      && compiled['errors'].length > 090      && compiled.errors.some(function(err: any) {91        return err.severity == 'error';92      });9394    if (hasErrors) {95      throw compiled.errors;96    }97    const out = compiled.contracts[`${name}.sol`][name];9899    return {100      abi: out.abi,101      object: '0x' + out.evm.bytecode.object,102    };103  }104105  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[], gas?: number): Promise<Contract> {106    const compiledContract = await this.compile(name, src, imports);107    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object, gas);108  }109110  async deployByAbi(signer: string, abi: any, object: string, gas?: number): Promise<Contract> {111    const web3 = this.helper.getWeb3();112    const contract = new web3.eth.Contract(abi, undefined, {113      data: object,114      from: signer,115      gas: gas ?? this.helper.eth.DEFAULT_GAS,116      gasPrice: await this.getGasPrice(),117    });118    return await contract.deploy({data: object}).send({from: signer});119  }120121}122123class NativeContractGroup extends EthGroupBase {124125  async contractHelpers(caller: string): Promise<Contract> {126    const web3 = this.helper.getWeb3();127    return new web3.eth.Contract(contractHelpersAbi as any, this.helper.getApi().consts.evmContractHelpers.contractAddress.toString(), {128      from: caller,129      gas: this.helper.eth.DEFAULT_GAS,130      gasPrice: await this.getGasPrice(),131    });132  }133134  async collectionHelpers(caller: string) {135    const web3 = this.helper.getWeb3();136    return new web3.eth.Contract(collectionHelpersAbi as any, this.helper.getApi().consts.common.contractAddress.toString(), {137      from: caller,138      gas: this.helper.eth.DEFAULT_GAS,139      gasPrice: await this.getGasPrice(),140    });141  }142143  async collection(address: string, mode: TCollectionMode, caller?: string, mergeDeprecated = false) {144    let abi;145    if (address === '0x17C4e6453cC49aaAAEaCA894E6d9683e00000000' && mode === 'ft') {146      abi = nativeFungibleAbi;147    } else {148      abi ={149        'nft': nonFungibleAbi,150        'rft': refungibleAbi,151        'ft': fungibleAbi,152      }[mode];153    }154    if (mergeDeprecated) {155      const deprecated = {156        'nft': nonFungibleDeprecatedAbi,157        'rft': refungibleDeprecatedAbi,158        'ft': fungibleDeprecatedAbi,159      }[mode];160      abi = [...abi, ...deprecated];161    }162    const web3 = this.helper.getWeb3();163    return new web3.eth.Contract(abi as any, address, {164      gas: this.helper.eth.DEFAULT_GAS,165      gasPrice: await this.getGasPrice(),166      ...(caller ? {from: caller} : {}),167    });168  }169170  collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string, mergeDeprecated = false) {171    return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller, mergeDeprecated);172  }173174  async rftToken(address: string, caller?: string, mergeDeprecated = false) {175    const web3 = this.helper.getWeb3();176    const abi = mergeDeprecated ? [...refungibleTokenAbi, ...refungibleTokenDeprecatedAbi] : refungibleTokenAbi;177    return new web3.eth.Contract(abi as any, address, {178      gas: this.helper.eth.DEFAULT_GAS,179      gasPrice: await this.getGasPrice(),180      ...(caller ? {from: caller} : {}),181    });182  }183184  rftTokenById(collectionId: number, tokenId: number, caller?: string, mergeDeprecated = false) {185    return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller, mergeDeprecated);186  }187}188189190class EthGroup extends EthGroupBase {191  DEFAULT_GAS = 2_500_000;192193  createAccount() {194    const web3 = this.helper.getWeb3();195    const account = web3.eth.accounts.create();196    web3.eth.accounts.wallet.add(account.privateKey);197    return account.address;198  }199200  async createAccountWithBalance(donor: IKeyringPair, amount = 600n) {201    const account = this.createAccount();202    await this.transferBalanceFromSubstrate(donor, account, amount);203204    return account;205  }206207  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount = 100n, inTokens = true) {208    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));209  }210211  async getCollectionCreationFee(signer: string) {212    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);213    return await collectionHelper.methods.collectionCreationFee().call();214  }215216  async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {217    if (!gasLimit) gasLimit = this.DEFAULT_GAS;218    const web3 = this.helper.getWeb3();219    const gasPrice = await web3.eth.getGasPrice();220    // TODO: check execution status221    await this.helper.executeExtrinsic(222      signer,223      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],224      true,225    );226  }227228  async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {229    return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);230  }231232  createCollectionMethodName(mode: TCollectionMode) {233    switch (mode) {234      case 'ft':235        return 'createFTCollection';236      case 'nft':237        return 'createNFTCollection';238      case 'rft':239        return 'createRFTCollection';240    }241  }242243  async createCollection(mode: TCollectionMode, signer: string, name: string, description: string, tokenPrefix: string, decimals = 18, mergeDeprecated = false): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[], collection: Contract }> {244    const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();245    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);246    const functionName: string = this.createCollectionMethodName(mode);247248    const functionParams = mode === 'ft' ? [name, decimals, description, tokenPrefix] : [name, description, tokenPrefix];249    const result = await collectionHelper.methods[functionName](...functionParams).send({value: Number(collectionCreationPrice)});250251    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);252    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);253    const events = this.helper.eth.normalizeEvents(result.events);254    const collection = await this.helper.ethNativeContract.collectionById(collectionId, mode, signer, mergeDeprecated);255256    return {collectionId, collectionAddress, events, collection};257  }258259  createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {260    return this.createCollection('nft', signer, name, description, tokenPrefix);261  }262263  async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {264    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);265266    const {collectionId, collectionAddress, events} = await this.createCollection('nft', signer, name, description, tokenPrefix);267268    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();269270    return {collectionId, collectionAddress, events};271  }272273  createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {274    return this.createCollection('rft', signer, name, description, tokenPrefix);275  }276277  createFungibleCollection(signer: string, name: string, decimals: number, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {278    return this.createCollection('ft', signer, name, description, tokenPrefix, decimals);279  }280281  async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {282    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);283284    const {collectionId, collectionAddress, events} = await this.createCollection('rft', signer, name, description, tokenPrefix);285286    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();287288    return {collectionId, collectionAddress, events};289  }290291  async deployCollectorContract(signer: string): Promise<Contract> {292    return await this.helper.ethContract.deployByCode(signer, 'Collector', `293    // SPDX-License-Identifier: UNLICENSED294    pragma solidity ^0.8.6;295296    contract Collector {297      uint256 collected;298      fallback() external payable {299        giveMoney();300      }301      function giveMoney() public payable {302        collected += msg.value;303      }304      function getCollected() public view returns (uint256) {305        return collected;306      }307      function getUnaccounted() public view returns (uint256) {308        return address(this).balance - collected;309      }310311      function withdraw(address payable target) public {312        target.transfer(collected);313        collected = 0;314      }315    }316  `);317  }318319  async deployFlipper(signer: string): Promise<Contract> {320    return await this.helper.ethContract.deployByCode(signer, 'Flipper', `321    // SPDX-License-Identifier: UNLICENSED322    pragma solidity ^0.8.6;323324    contract Flipper {325      bool value = false;326      function flip() public {327        value = !value;328      }329      function getValue() public view returns (bool) {330        return value;331      }332    }333  `);334  }335336  async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {337    const before = await this.helper.balance.getEthereum(user);338    await call();339    // In dev mode, the transaction might not finish processing in time340    await this.helper.wait.newBlocks(1);341    const after = await this.helper.balance.getEthereum(user);342343    return before - after;344  }345346  normalizeEvents(events: any): NormalizedEvent[] {347    const output = [];348    for (const key of Object.keys(events)) {349      if (key.match(/^[0-9]+$/)) {350        output.push(events[key]);351      } else if (Array.isArray(events[key])) {352        output.push(...events[key]);353      } else {354        output.push(events[key]);355      }356    }357    output.sort((a, b) => a.logIndex - b.logIndex);358    return output.map(({address, event, returnValues}) => {359      const args: { [key: string]: string } = {};360      for (const key of Object.keys(returnValues)) {361        if (!key.match(/^[0-9]+$/)) {362          args[key] = returnValues[key];363        }364      }365      return {366        address,367        event,368        args,369      };370    });371  }372373  async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {374    const wrappedCode = async () => {375      await code();376      // In dev mode, the transaction might not finish processing in time377      await this.helper.wait.newBlocks(1);378    };379    return await this.helper.arrange.calculcateFee(address, wrappedCode);380  }381}382383class EthAddressGroup extends EthGroupBase {384  extractCollectionId(address: string): number {385    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');386    return parseInt(address.substr(address.length - 8), 16);387  }388389  fromCollectionId(collectionId: number): string {390    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');391    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);392  }393394  extractTokenId(address: string): { collectionId: number, tokenId: number } {395    if (!address.startsWith('0x'))396      throw 'address not starts with "0x"';397    if (address.length > 42)398      throw 'address length is more than 20 bytes';399    return {400      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),401      tokenId: Number('0x' + address.substring(address.length - 8)),402    };403  }404405  fromTokenId(collectionId: number, tokenId: number): string {406    return this.helper.util.getTokenAddress({collectionId, tokenId});407  }408409  normalizeAddress(address: string): string {410    return '0x' + address.substring(address.length - 40);411  }412}413export class EthPropertyGroup extends EthGroupBase {414  property(key: string, value: string): EthProperty {415    return [416      key,417      '0x' + Buffer.from(value).toString('hex'),418    ];419  }420}421export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;422423export class EthCrossAccountGroup extends EthGroupBase {424  createAccount(): CrossAddress {425    return this.fromAddress(this.helper.eth.createAccount());426  }427428  async createAccountWithBalance(donor: IKeyringPair, amount = 100n) {429    return this.fromAddress(await this.helper.eth.createAccountWithBalance(donor, amount));430  }431432  fromAddress(address: TEthereumAccount): CrossAddress {433    return {434      eth: address,435      sub: '0',436    };437  }438439  fromKeyringPair(keyring: IKeyringPair): CrossAddress {440    return {441      eth: '0x0000000000000000000000000000000000000000',442      sub: keyring.addressRaw,443    };444  }445}446447export class FeeGas {448  fee: number | bigint = 0n;449450  gas: number | bigint = 0n;451452  public static async build(helper: EthUniqueHelper, fee: bigint): Promise<FeeGas> {453    const instance = new FeeGas();454    instance.fee = instance.convertToTokens(fee);455    instance.gas = await instance.convertToGas(fee, helper);456    return instance;457  }458459  private async convertToGas(fee: bigint, helper: EthUniqueHelper): Promise<bigint> {460    const gasPrice = BigInt(await helper.getWeb3().eth.getGasPrice());461    return fee / gasPrice;462  }463464  private convertToTokens(value: bigint, nominal = 1_000_000_000_000_000_000n): number {465    return Number((value * 1000n) / nominal) / 1000;466  }467}468469class EthArrangeGroup extends ArrangeGroup {470  helper: EthUniqueHelper;471472  constructor(helper: EthUniqueHelper) {473    super(helper);474    this.helper = helper;475  }476477  async calculcateFeeGas(payer: ICrossAccountId, promise: () => Promise<any>): Promise<FeeGas> {478    const fee = await this.calculcateFee(payer, promise);479    return await FeeGas.build(this.helper, fee);480  }481}482export class EthUniqueHelper extends DevUniqueHelper {483  web3: Web3 | null = null;484  web3Provider: WebsocketProvider | null = null;485486  eth: EthGroup;487  ethAddress: EthAddressGroup;488  ethCrossAccount: EthCrossAccountGroup;489  ethNativeContract: NativeContractGroup;490  ethContract: ContractGroup;491  ethProperty: EthPropertyGroup;492  arrange: EthArrangeGroup;493  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: { [key: string]: any } = {}) {494    options.helperBase = options.helperBase ?? EthUniqueHelper;495496    super(logger, options);497    this.eth = new EthGroup(this);498    this.ethAddress = new EthAddressGroup(this);499    this.ethCrossAccount = new EthCrossAccountGroup(this);500    this.ethNativeContract = new NativeContractGroup(this);501    this.ethContract = new ContractGroup(this);502    this.ethProperty = new EthPropertyGroup(this);503    this.arrange = new EthArrangeGroup(this);504    super.arrange = this.arrange;505  }506507  getWeb3(): Web3 {508    if (this.web3 === null) throw Error('Web3 not connected');509    return this.web3;510  }511512  connectWeb3(wsEndpoint: string) {513    if (this.web3 !== null) return;514    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);515    this.web3 = new Web3(this.web3Provider);516  }517518  async disconnect() {519    if (this.web3 === null) return;520    this.web3Provider?.connection.close();521522    await super.disconnect();523  }524525  clearApi() {526    super.clearApi();527    this.web3 = null;528  }529530  clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {531    const newHelper = super.clone(helperCls, options) as EthUniqueHelper;532    newHelper.web3 = this.web3;533    newHelper.web3Provider = this.web3Provider;534535    return newHelper;536  }537}
after · tests/src/eth/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable function-call-argument-newline */5// eslint-disable-next-line @typescript-eslint/triple-slash-reference6/// <reference path="unique.dev.d.ts" />78import {readFile} from 'fs/promises';910import Web3 from 'web3';11import {WebsocketProvider} from 'web3-core';12import {Contract} from 'web3-eth-contract';1314import solc from 'solc';1516import {evmToAddress} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';1819import {ArrangeGroup, DevUniqueHelper} from '../../../util/playgrounds/unique.dev';2021import {ContractImports, CompiledContract, CrossAddress, NormalizedEvent, EthProperty} from './types';2223// Native contracts ABI24import collectionHelpersAbi from '../../abi/collectionHelpers.json' assert {type: 'json'};25import nativeFungibleAbi from '../../abi/nativeFungible.json' assert {type: 'json'};26import fungibleAbi from '../../abi/fungible.json' assert {type: 'json'};27import fungibleDeprecatedAbi from '../../abi/fungibleDeprecated.json' assert {type: 'json'};28import nonFungibleAbi from '../../abi/nonFungible.json' assert {type: 'json'};29import nonFungibleDeprecatedAbi from '../../abi/nonFungibleDeprecated.json' assert {type: 'json'};30import refungibleAbi from '../../abi/reFungible.json' assert {type: 'json'};31import refungibleDeprecatedAbi from '../../abi/reFungibleDeprecated.json' assert {type: 'json'};32import refungibleTokenAbi from '../../abi/reFungibleToken.json' assert {type: 'json'};33import refungibleTokenDeprecatedAbi from '../../abi/reFungibleTokenDeprecated.json' assert {type: 'json'};34import contractHelpersAbi from '../../abi/contractHelpers.json' assert {type: 'json'};35import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';36import {TCollectionMode} from '../../../util/playgrounds/types';3738class EthGroupBase {39  helper: EthUniqueHelper;40  gasPrice?: string;4142  constructor(helper: EthUniqueHelper) {43    this.helper = helper;44  }45  async getGasPrice() {46    if (this.gasPrice)47      return this.gasPrice;48    this.gasPrice = await this.helper.getWeb3().eth.getGasPrice();49    return this.gasPrice;50  }51}525354class ContractGroup extends EthGroupBase {55  async findImports(imports?: ContractImports[]) {56    if (!imports) return function(path: string) {57      return {error: `File not found: ${path}`};58    };5960    const knownImports = {} as { [key: string]: string };61    for (const imp of imports) {62      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();63    }6465    return function(path: string) {66      if (path in knownImports) return {contents: knownImports[path]};67      return {error: `File not found: ${path}`};68    };69  }7071  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {72    const compiled = JSON.parse(solc.compile(JSON.stringify({73      language: 'Solidity',74      sources: {75        [`${name}.sol`]: {76          content: src,77        },78      },79      settings: {80        outputSelection: {81          '*': {82            '*': ['*'],83          },84        },85      },86    }), {import: await this.findImports(imports)}));8788    const hasErrors = compiled['errors']89      && compiled['errors'].length > 090      && compiled.errors.some(function(err: any) {91        return err.severity == 'error';92      });9394    if (hasErrors) {95      throw compiled.errors;96    }97    const out = compiled.contracts[`${name}.sol`][name];9899    return {100      abi: out.abi,101      object: '0x' + out.evm.bytecode.object,102    };103  }104105  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[], gas?: number): Promise<Contract> {106    const compiledContract = await this.compile(name, src, imports);107    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object, gas);108  }109110  async deployByAbi(signer: string, abi: any, object: string, gas?: number): Promise<Contract> {111    const web3 = this.helper.getWeb3();112    const contract = new web3.eth.Contract(abi, undefined, {113      data: object,114      from: signer,115      gas: gas ?? this.helper.eth.DEFAULT_GAS,116      gasPrice: await this.getGasPrice(),117    });118    return await contract.deploy({data: object}).send({from: signer});119  }120121}122123class NativeContractGroup extends EthGroupBase {124125  async contractHelpers(caller: string): Promise<Contract> {126    const web3 = this.helper.getWeb3();127    return new web3.eth.Contract(contractHelpersAbi as any, this.helper.getApi().consts.evmContractHelpers.contractAddress.toString(), {128      from: caller,129      gas: this.helper.eth.DEFAULT_GAS,130      gasPrice: await this.getGasPrice(),131    });132  }133134  async collectionHelpers(caller: string) {135    const web3 = this.helper.getWeb3();136    return new web3.eth.Contract(collectionHelpersAbi as any, this.helper.getApi().consts.common.contractAddress.toString(), {137      from: caller,138      gas: this.helper.eth.DEFAULT_GAS,139      gasPrice: await this.getGasPrice(),140    });141  }142143  async collection(address: string, mode: TCollectionMode, caller?: string, mergeDeprecated = false) {144    let abi;145    if (address === '0x17C4e6453cC49aaAAEaCA894E6d9683e00000000') {146      abi = nativeFungibleAbi;147    } else {148      abi ={149        'nft': nonFungibleAbi,150        'rft': refungibleAbi,151        'ft': fungibleAbi,152      }[mode];153    }154    if (mergeDeprecated) {155      const deprecated = {156        'nft': nonFungibleDeprecatedAbi,157        'rft': refungibleDeprecatedAbi,158        'ft': fungibleDeprecatedAbi,159      }[mode];160      abi = [...abi, ...deprecated];161    }162    const web3 = this.helper.getWeb3();163    return new web3.eth.Contract(abi as any, address, {164      gas: this.helper.eth.DEFAULT_GAS,165      gasPrice: await this.getGasPrice(),166      ...(caller ? {from: caller} : {}),167    });168  }169170  collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string, mergeDeprecated = false) {171    return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller, mergeDeprecated);172  }173174  async rftToken(address: string, caller?: string, mergeDeprecated = false) {175    const web3 = this.helper.getWeb3();176    const abi = mergeDeprecated ? [...refungibleTokenAbi, ...refungibleTokenDeprecatedAbi] : refungibleTokenAbi;177    return new web3.eth.Contract(abi as any, address, {178      gas: this.helper.eth.DEFAULT_GAS,179      gasPrice: await this.getGasPrice(),180      ...(caller ? {from: caller} : {}),181    });182  }183184  rftTokenById(collectionId: number, tokenId: number, caller?: string, mergeDeprecated = false) {185    return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller, mergeDeprecated);186  }187}188189190class EthGroup extends EthGroupBase {191  DEFAULT_GAS = 2_500_000;192193  createAccount() {194    const web3 = this.helper.getWeb3();195    const account = web3.eth.accounts.create();196    web3.eth.accounts.wallet.add(account.privateKey);197    return account.address;198  }199200  async createAccountWithBalance(donor: IKeyringPair, amount = 600n) {201    const account = this.createAccount();202    await this.transferBalanceFromSubstrate(donor, account, amount);203204    return account;205  }206207  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount = 100n, inTokens = true) {208    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));209  }210211  async getCollectionCreationFee(signer: string) {212    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);213    return await collectionHelper.methods.collectionCreationFee().call();214  }215216  async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {217    if (!gasLimit) gasLimit = this.DEFAULT_GAS;218    const web3 = this.helper.getWeb3();219    const gasPrice = await web3.eth.getGasPrice();220    // TODO: check execution status221    await this.helper.executeExtrinsic(222      signer,223      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],224      true,225    );226  }227228  async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {229    return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);230  }231232  createCollectionMethodName(mode: TCollectionMode) {233    switch (mode) {234      case 'ft':235        return 'createFTCollection';236      case 'nft':237        return 'createNFTCollection';238      case 'rft':239        return 'createRFTCollection';240    }241  }242243  async createCollection(mode: TCollectionMode, signer: string, name: string, description: string, tokenPrefix: string, decimals = 18, mergeDeprecated = false): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[], collection: Contract }> {244    const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();245    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);246    const functionName: string = this.createCollectionMethodName(mode);247248    const functionParams = mode === 'ft' ? [name, decimals, description, tokenPrefix] : [name, description, tokenPrefix];249    const result = await collectionHelper.methods[functionName](...functionParams).send({value: Number(collectionCreationPrice)});250251    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);252    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);253    const events = this.helper.eth.normalizeEvents(result.events);254    const collection = await this.helper.ethNativeContract.collectionById(collectionId, mode, signer, mergeDeprecated);255256    return {collectionId, collectionAddress, events, collection};257  }258259  createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {260    return this.createCollection('nft', signer, name, description, tokenPrefix);261  }262263  async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {264    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);265266    const {collectionId, collectionAddress, events} = await this.createCollection('nft', signer, name, description, tokenPrefix);267268    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();269270    return {collectionId, collectionAddress, events};271  }272273  createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {274    return this.createCollection('rft', signer, name, description, tokenPrefix);275  }276277  createFungibleCollection(signer: string, name: string, decimals: number, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {278    return this.createCollection('ft', signer, name, description, tokenPrefix, decimals);279  }280281  async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {282    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);283284    const {collectionId, collectionAddress, events} = await this.createCollection('rft', signer, name, description, tokenPrefix);285286    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();287288    return {collectionId, collectionAddress, events};289  }290291  async deployCollectorContract(signer: string): Promise<Contract> {292    return await this.helper.ethContract.deployByCode(signer, 'Collector', `293    // SPDX-License-Identifier: UNLICENSED294    pragma solidity ^0.8.6;295296    contract Collector {297      uint256 collected;298      fallback() external payable {299        giveMoney();300      }301      function giveMoney() public payable {302        collected += msg.value;303      }304      function getCollected() public view returns (uint256) {305        return collected;306      }307      function getUnaccounted() public view returns (uint256) {308        return address(this).balance - collected;309      }310311      function withdraw(address payable target) public {312        target.transfer(collected);313        collected = 0;314      }315    }316  `);317  }318319  async deployFlipper(signer: string): Promise<Contract> {320    return await this.helper.ethContract.deployByCode(signer, 'Flipper', `321    // SPDX-License-Identifier: UNLICENSED322    pragma solidity ^0.8.6;323324    contract Flipper {325      bool value = false;326      function flip() public {327        value = !value;328      }329      function getValue() public view returns (bool) {330        return value;331      }332    }333  `);334  }335336  async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {337    const before = await this.helper.balance.getEthereum(user);338    await call();339    // In dev mode, the transaction might not finish processing in time340    await this.helper.wait.newBlocks(1);341    const after = await this.helper.balance.getEthereum(user);342343    return before - after;344  }345346  normalizeEvents(events: any): NormalizedEvent[] {347    const output = [];348    for (const key of Object.keys(events)) {349      if (key.match(/^[0-9]+$/)) {350        output.push(events[key]);351      } else if (Array.isArray(events[key])) {352        output.push(...events[key]);353      } else {354        output.push(events[key]);355      }356    }357    output.sort((a, b) => a.logIndex - b.logIndex);358    return output.map(({address, event, returnValues}) => {359      const args: { [key: string]: string } = {};360      for (const key of Object.keys(returnValues)) {361        if (!key.match(/^[0-9]+$/)) {362          args[key] = returnValues[key];363        }364      }365      return {366        address,367        event,368        args,369      };370    });371  }372373  async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {374    const wrappedCode = async () => {375      await code();376      // In dev mode, the transaction might not finish processing in time377      await this.helper.wait.newBlocks(1);378    };379    return await this.helper.arrange.calculcateFee(address, wrappedCode);380  }381}382383class EthAddressGroup extends EthGroupBase {384  extractCollectionId(address: string): number {385    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');386    return parseInt(address.substr(address.length - 8), 16);387  }388389  fromCollectionId(collectionId: number): string {390    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');391    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);392  }393394  extractTokenId(address: string): { collectionId: number, tokenId: number } {395    if (!address.startsWith('0x'))396      throw 'address not starts with "0x"';397    if (address.length > 42)398      throw 'address length is more than 20 bytes';399    return {400      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),401      tokenId: Number('0x' + address.substring(address.length - 8)),402    };403  }404405  fromTokenId(collectionId: number, tokenId: number): string {406    return this.helper.util.getTokenAddress({collectionId, tokenId});407  }408409  normalizeAddress(address: string): string {410    return '0x' + address.substring(address.length - 40);411  }412}413export class EthPropertyGroup extends EthGroupBase {414  property(key: string, value: string): EthProperty {415    return [416      key,417      '0x' + Buffer.from(value).toString('hex'),418    ];419  }420}421export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;422423export class EthCrossAccountGroup extends EthGroupBase {424  createAccount(): CrossAddress {425    return this.fromAddress(this.helper.eth.createAccount());426  }427428  async createAccountWithBalance(donor: IKeyringPair, amount = 100n) {429    return this.fromAddress(await this.helper.eth.createAccountWithBalance(donor, amount));430  }431432  fromAddress(address: TEthereumAccount): CrossAddress {433    return {434      eth: address,435      sub: '0',436    };437  }438439  fromKeyringPair(keyring: IKeyringPair): CrossAddress {440    return {441      eth: '0x0000000000000000000000000000000000000000',442      sub: keyring.addressRaw,443    };444  }445}446447export class FeeGas {448  fee: number | bigint = 0n;449450  gas: number | bigint = 0n;451452  public static async build(helper: EthUniqueHelper, fee: bigint): Promise<FeeGas> {453    const instance = new FeeGas();454    instance.fee = instance.convertToTokens(fee);455    instance.gas = await instance.convertToGas(fee, helper);456    return instance;457  }458459  private async convertToGas(fee: bigint, helper: EthUniqueHelper): Promise<bigint> {460    const gasPrice = BigInt(await helper.getWeb3().eth.getGasPrice());461    return fee / gasPrice;462  }463464  private convertToTokens(value: bigint, nominal = 1_000_000_000_000_000_000n): number {465    return Number((value * 1000n) / nominal) / 1000;466  }467}468469class EthArrangeGroup extends ArrangeGroup {470  helper: EthUniqueHelper;471472  constructor(helper: EthUniqueHelper) {473    super(helper);474    this.helper = helper;475  }476477  async calculcateFeeGas(payer: ICrossAccountId, promise: () => Promise<any>): Promise<FeeGas> {478    const fee = await this.calculcateFee(payer, promise);479    return await FeeGas.build(this.helper, fee);480  }481}482export class EthUniqueHelper extends DevUniqueHelper {483  web3: Web3 | null = null;484  web3Provider: WebsocketProvider | null = null;485486  eth: EthGroup;487  ethAddress: EthAddressGroup;488  ethCrossAccount: EthCrossAccountGroup;489  ethNativeContract: NativeContractGroup;490  ethContract: ContractGroup;491  ethProperty: EthPropertyGroup;492  arrange: EthArrangeGroup;493  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: { [key: string]: any } = {}) {494    options.helperBase = options.helperBase ?? EthUniqueHelper;495496    super(logger, options);497    this.eth = new EthGroup(this);498    this.ethAddress = new EthAddressGroup(this);499    this.ethCrossAccount = new EthCrossAccountGroup(this);500    this.ethNativeContract = new NativeContractGroup(this);501    this.ethContract = new ContractGroup(this);502    this.ethProperty = new EthPropertyGroup(this);503    this.arrange = new EthArrangeGroup(this);504    super.arrange = this.arrange;505  }506507  getWeb3(): Web3 {508    if (this.web3 === null) throw Error('Web3 not connected');509    return this.web3;510  }511512  connectWeb3(wsEndpoint: string) {513    if (this.web3 !== null) return;514    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);515    this.web3 = new Web3(this.web3Provider);516  }517518  async disconnect() {519    if (this.web3 === null) return;520    this.web3Provider?.connection.close();521522    await super.disconnect();523  }524525  clearApi() {526    super.clearApi();527    this.web3 = null;528  }529530  clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {531    const newHelper = super.clone(helperCls, options) as EthUniqueHelper;532    newHelper.web3 = this.web3;533    newHelper.web3Provider = this.web3Provider;534535    return newHelper;536  }537}
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -2400,7 +2400,16 @@
     return {free: accountInfo.free.toBigInt(), frozen: accountInfo.frozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};
   }
 
-  async getLocked(address: TSubstrateAccount): Promise<[{ id: string, amount: bigint, reason: string }]> {
+  /**
+   * Get total issuance
+   * @returns
+   */
+  async getTotalIssuance(): Promise<bigint> {
+    const total = (await this.helper.callRpc('api.query.balances.totalIssuance', []));
+    return total.toBigInt();
+  }
+
+  async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {
     const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();
     return locks.map((lock: any) => { return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons}; });
   }
@@ -2488,6 +2497,14 @@
   }
 
   /**
+   * Get total issuance
+   * @returns
+   */
+  getTotalIssuance(): Promise<bigint> {
+    return this.subBalanceGroup.getTotalIssuance();
+  }
+
+  /**
    * Get locked balances
    * @param address substrate address
    * @returns locked balances with reason via api.query.balances.locks