git.delta.rocks / unique-network / refs/commits / 3ce311c312ce

difftreelog

source

tests/src/eth/util/playgrounds/unique.dev.ts9.6 KiBsourcehistory
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 * as solc from 'solc';1516import {evmToAddress} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';1819import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';2021import {ContractImports, CompiledContract} from './types';2223// Native contracts ABI24import collectionHelpersAbi from '../../collectionHelpersAbi.json';25import fungibleAbi from '../../fungibleAbi.json';26import nonFungibleAbi from '../../nonFungibleAbi.json';27import refungibleAbi from '../../reFungibleAbi.json';28import refungibleTokenAbi from '../../reFungibleTokenAbi.json';29import contractHelpersAbi from './../contractHelpersAbi.json';30import {TEthereumAccount} from '../../../util/playgrounds/types';3132class EthGroupBase {33  helper: EthUniqueHelper;3435  constructor(helper: EthUniqueHelper) {36    this.helper = helper;37  }38}394041class ContractGroup extends EthGroupBase {42  async findImports(imports?: ContractImports[]){43    if(!imports) return function(path: string) {44      return {error: `File not found: ${path}`};45    };46  47    const knownImports = {} as {[key: string]: string};48    for(const imp of imports) {49      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();50    }51  52    return function(path: string) {53      if(path in knownImports) return {contents: knownImports[path]};54      return {error: `File not found: ${path}`};55    };56  }5758  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {59    const out = JSON.parse(solc.compile(JSON.stringify({60      language: 'Solidity',61      sources: {62        [`${name}.sol`]: {63          content: src,64        },65      },66      settings: {67        outputSelection: {68          '*': {69            '*': ['*'],70          },71        },72      },73    }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];74  75    return {76      abi: out.abi,77      object: '0x' + out.evm.bytecode.object,78    };79  }8081  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {82    const compiledContract = await this.compile(name, src, imports);83    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);84  }8586  async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {87    const web3 = this.helper.getWeb3();88    const contract = new web3.eth.Contract(abi, undefined, {89      data: object,90      from: signer,91      gas: this.helper.eth.DEFAULT_GAS,92    });93    return await contract.deploy({data: object}).send({from: signer});94  }9596}97  98class NativeContractGroup extends EthGroupBase {99100  contractHelpers(caller: string): Contract {101    const web3 = this.helper.getWeb3();102    return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});103  }104105  collectionHelpers(caller: string) {106    const web3 = this.helper.getWeb3();107    return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});108  }109110  collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {111    const abi = {112      'nft': nonFungibleAbi,113      'rft': refungibleAbi,114      'ft': fungibleAbi,115    }[mode];116    const web3 = this.helper.getWeb3();117    return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});118  }119120  rftTokenByAddress(address: string, caller?: string): Contract {121    const web3 = this.helper.getWeb3();122    return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});123  }124125  rftToken(collectionId: number, tokenId: number, caller?: string): Contract {126    return this.rftTokenByAddress(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);127  }128}129130  131class EthGroup extends EthGroupBase {132  DEFAULT_GAS = 2_500_000;133134  createAccount() {135    const web3 = this.helper.getWeb3();136    const account = web3.eth.accounts.create();137    web3.eth.accounts.wallet.add(account.privateKey);138    return account.address;139  }140141  async createAccountWithBalance(donor: IKeyringPair, amount=1000n) {142    const account = this.createAccount();143    await this.transferBalanceFromSubstrate(donor, account, amount);144  145    return account;146  }147148  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {149    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));150  }151152  async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {153    if(!gasLimit) gasLimit = this.DEFAULT_GAS;154    const web3 = this.helper.getWeb3();155    const gasPrice = await web3.eth.getGasPrice();156    // TODO: check execution status157    await this.helper.executeExtrinsic(158      signer,159      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],160      true,161    );162  }163  164  async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {165    return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);166  }167168  async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {169    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);170        171    const result = await collectionHelper.methods.createNonfungibleCollection(name, description, tokenPrefix).send();172173    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);174    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);175176    return {collectionId, collectionAddress};177  }178179  async deployCollectorContract(signer: string): Promise<Contract> {180    return await this.helper.ethContract.deployByCode(signer, 'Collector', `181    // SPDX-License-Identifier: UNLICENSED182    pragma solidity ^0.8.6;183184    contract Collector {185      uint256 collected;186      fallback() external payable {187        giveMoney();188      }189      function giveMoney() public payable {190        collected += msg.value;191      }192      function getCollected() public view returns (uint256) {193        return collected;194      }195      function getUnaccounted() public view returns (uint256) {196        return address(this).balance - collected;197      }198199      function withdraw(address payable target) public {200        target.transfer(collected);201        collected = 0;202      }203    }204  `);205  }206207  async deployFlipper(signer: string): Promise<Contract> {208    return await this.helper.ethContract.deployByCode(signer, 'Flipper', `209    // SPDX-License-Identifier: UNLICENSED210    pragma solidity ^0.8.6;211212    contract Flipper {213      bool value = false;214      function flip() public {215        value = !value;216      }217      function getValue() public view returns (bool) {218        return value;219      }220    }221  `);222  }223}  224  225class EthAddressGroup extends EthGroupBase {226  extractCollectionId(address: string): number {227    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');228    return parseInt(address.substr(address.length - 8), 16);229  }230231  fromCollectionId(collectionId: number): string {232    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');233    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);234  }235236  extractTokenId(address: string): {collectionId: number, tokenId: number} {237    if (!address.startsWith('0x'))238      throw 'address not starts with "0x"';239    if (address.length > 42)240      throw 'address length is more than 20 bytes';241    return {242      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),243      tokenId: Number('0x' + address.substring(address.length - 8)),244    };245  }246247  fromTokenId(collectionId: number, tokenId: number): string  {248    return this.helper.util.getTokenAddress({collectionId, tokenId});249  }250251  normalizeAddress(address: string): string {252    return '0x' + address.substring(address.length - 40);253  }254}  255 256257export class EthUniqueHelper extends DevUniqueHelper {258  web3: Web3 | null = null;259  web3Provider: WebsocketProvider | null = null;260261  eth: EthGroup;262  ethAddress: EthAddressGroup;263  ethNativeContract: NativeContractGroup;264  ethContract: ContractGroup;265266  constructor(logger: { log: (msg: any, level: any) => void, level: any }) {267    super(logger);268    this.eth = new EthGroup(this);269    this.ethAddress = new EthAddressGroup(this);270    this.ethNativeContract = new NativeContractGroup(this);271    this.ethContract = new ContractGroup(this);272  }273274  getWeb3(): Web3 {275    if(this.web3 === null) throw Error('Web3 not connected');276    return this.web3;277  }278279  async connectWeb3(wsEndpoint: string) {280    if(this.web3 !== null) return;281    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);282    this.web3 = new Web3(this.web3Provider);283  }284285  async disconnectWeb3() {286    if(this.web3 === null) return;287    this.web3Provider?.connection.close();288    this.web3 = null;289  }290}291