12345678import {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';222324import 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';3031class EthGroupBase {32 helper: EthUniqueHelper;3334 constructor(helper: EthUniqueHelper) {35 this.helper = helper;36 }37}383940class ContractGroup extends EthGroupBase {41 async findImports(imports?: ContractImports[]){42 if(!imports) return function(path: string) {43 return {error: `File not found: ${path}`};44 };45 46 const knownImports = {} as any;47 for(const imp of imports) {48 knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();49 }50 51 return function(path: string) {52 if(knownImports.hasOwnPropertyDescriptor(path)) return {contents: knownImports[path]};53 return {error: `File not found: ${path}`};54 };55 }5657 async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {58 const out = JSON.parse(solc.compile(JSON.stringify({59 language: 'Solidity',60 sources: {61 [`${name}.sol`]: {62 content: src,63 },64 },65 settings: {66 outputSelection: {67 '*': {68 '*': ['*'],69 },70 },71 },72 }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];73 74 return {75 abi: out.abi,76 object: '0x' + out.evm.bytecode.object,77 };78 }7980 async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {81 const compiledContract = await this.compile(name, src, imports);82 return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);83 }8485 async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {86 const web3 = this.helper.getWeb3();87 const contract = new web3.eth.Contract(abi, undefined, {88 data: object,89 from: signer,90 gas: this.helper.eth.DEFAULT_GAS,91 });92 return await contract.deploy({data: object}).send({from: signer});93 }9495}96 97class NativeContractGroup extends EthGroupBase {9899 contractHelpers(caller: string): Contract {100 const web3 = this.helper.getWeb3();101 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});102 }103104 collectionHelpers(caller: string) {105 const web3 = this.helper.getWeb3();106 return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});107 }108109 collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {110 const abi = {111 'nft': nonFungibleAbi,112 'rft': refungibleAbi,113 'ft': fungibleAbi,114 }[mode];115 const web3 = this.helper.getWeb3();116 return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});117 }118119 collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {120 return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller);121 }122123 rftToken(address: string, caller?: string): Contract {124 const web3 = this.helper.getWeb3();125 return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});126 }127128 rftTokenById(collectionId: number, tokenId: number, caller?: string): Contract {129 return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);130 }131}132133 134class EthGroup extends EthGroupBase {135 DEFAULT_GAS = 2_500_000;136137 createAccount() {138 const web3 = this.helper.getWeb3();139 const account = web3.eth.accounts.create();140 web3.eth.accounts.wallet.add(account.privateKey);141 return account.address;142 }143144 async createAccountWithBalance(donor: IKeyringPair, amount=1000n) {145 const account = this.createAccount();146 await this.transferBalanceFromSubstrate(donor, account, amount);147 148 return account;149 }150151 async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {152 return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));153 }154155 async callEVM(signer: IKeyringPair, contractAddress: string, abi: any, value: string, gasLimit?: number) {156 if(!gasLimit) gasLimit = this.DEFAULT_GAS;157 const web3 = this.helper.getWeb3();158 const gasPrice = await web3.eth.getGasPrice();159 160 await this.helper.executeExtrinsic(161 signer,162 'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],163 true,164 );165 }166167 async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {168 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);169 170 const result = await collectionHelper.methods.createNonfungibleCollection(name, description, tokenPrefix).send();171172 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);173 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);174175 return {collectionId, collectionAddress};176 }177178 async createRefungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {179 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);180 181 const result = await collectionHelper.methods.createRFTCollection(name, description, tokenPrefix).send();182183 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);184 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);185186 return {collectionId, collectionAddress};187 }188189 async deployCollectorContract(signer: string): Promise<Contract> {190 return await this.helper.ethContract.deployByCode(signer, 'Collector', `191 // SPDX-License-Identifier: UNLICENSED192 pragma solidity ^0.8.6;193194 contract Collector {195 uint256 collected;196 fallback() external payable {197 giveMoney();198 }199 function giveMoney() public payable {200 collected += msg.value;201 }202 function getCollected() public view returns (uint256) {203 return collected;204 }205 function getUnaccounted() public view returns (uint256) {206 return address(this).balance - collected;207 }208209 function withdraw(address payable target) public {210 target.transfer(collected);211 collected = 0;212 }213 }214 `);215 }216217 async deployFlipper(signer: string): Promise<Contract> {218 return await this.helper.ethContract.deployByCode(signer, 'Flipper', `219 // SPDX-License-Identifier: UNLICENSED220 pragma solidity ^0.8.6;221222 contract Flipper {223 bool value = false;224 function flip() public {225 value = !value;226 }227 function getValue() public view returns (bool) {228 return value;229 }230 }231 `);232 }233234 async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {235 const before = await this.helper.balance.getEthereum(user);236 await call();237 238 await this.helper.wait.newBlocks(1);239 const after = await this.helper.balance.getEthereum(user);240241 return before - after;242 }243} 244 245class EthAddressGroup extends EthGroupBase {246 extractCollectionId(address: string): number {247 if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');248 return parseInt(address.substr(address.length - 8), 16);249 }250251 fromCollectionId(collectionId: number): string {252 if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');253 return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);254 }255256 extractTokenId(address: string): {collectionId: number, tokenId: number} {257 if (!address.startsWith('0x'))258 throw 'address not starts with "0x"';259 if (address.length > 42)260 throw 'address length is more than 20 bytes';261 return {262 collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),263 tokenId: Number('0x' + address.substring(address.length - 8)),264 };265 }266267 fromTokenId(collectionId: number, tokenId: number): string {268 return this.helper.util.getTokenAddress({collectionId, tokenId});269 }270271 normalizeAddress(address: string): string {272 return '0x' + address.substring(address.length - 40);273 }274} 275 276277export class EthUniqueHelper extends DevUniqueHelper {278 web3: Web3 | null = null;279 web3Provider: WebsocketProvider | null = null;280281 eth: EthGroup;282 ethAddress: EthAddressGroup;283 ethNativeContract: NativeContractGroup;284 ethContract: ContractGroup;285286 constructor(logger: { log: (msg: any, level: any) => void, level: any }) {287 super(logger);288 this.eth = new EthGroup(this);289 this.ethAddress = new EthAddressGroup(this);290 this.ethNativeContract = new NativeContractGroup(this);291 this.ethContract = new ContractGroup(this);292 }293294 getWeb3(): Web3 {295 if(this.web3 === null) throw Error('Web3 not connected');296 return this.web3;297 }298299 async connectWeb3(wsEndpoint: string) {300 if(this.web3 !== null) return;301 this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);302 this.web3 = new Web3(this.web3Provider);303 }304305 async disconnectWeb3() {306 if(this.web3 === null) return;307 this.web3Provider?.connection.close();308 this.web3 = null;309 }310}311