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, TEthCrossAccount, NormalizedEvent, EthProperty} 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';30import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';31import {TCollectionMode} from '../../../util/playgrounds/types';3233class EthGroupBase {34 helper: EthUniqueHelper;3536 constructor(helper: EthUniqueHelper) {37 this.helper = helper;38 }39}404142class ContractGroup extends EthGroupBase {43 async findImports(imports?: ContractImports[]){44 if(!imports) return function(path: string) {45 return {error: `File not found: ${path}`};46 };4748 const knownImports = {} as {[key: string]: string};49 for(const imp of imports) {50 knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();51 }5253 return function(path: string) {54 if(path in knownImports) return {contents: knownImports[path]};55 return {error: `File not found: ${path}`};56 };57 }5859 async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {60 const out = JSON.parse(solc.compile(JSON.stringify({61 language: 'Solidity',62 sources: {63 [`${name}.sol`]: {64 content: src,65 },66 },67 settings: {68 outputSelection: {69 '*': {70 '*': ['*'],71 },72 },73 },74 }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];7576 return {77 abi: out.abi,78 object: '0x' + out.evm.bytecode.object,79 };80 }8182 async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {83 const compiledContract = await this.compile(name, src, imports);84 return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);85 }8687 async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {88 const web3 = this.helper.getWeb3();89 const contract = new web3.eth.Contract(abi, undefined, {90 data: object,91 from: signer,92 gas: this.helper.eth.DEFAULT_GAS,93 });94 return await contract.deploy({data: object}).send({from: signer});95 }9697}9899class NativeContractGroup extends EthGroupBase {100101 contractHelpers(caller: string): Contract {102 const web3 = this.helper.getWeb3();103 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});104 }105106 collectionHelpers(caller: string) {107 const web3 = this.helper.getWeb3();108 return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});109 }110111 collection(address: string, mode: TCollectionMode, caller?: string): Contract {112 const abi = {113 'nft': nonFungibleAbi,114 'rft': refungibleAbi,115 'ft': fungibleAbi,116 }[mode];117 const web3 = this.helper.getWeb3();118 return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});119 }120121 collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {122 return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller);123 }124125 rftToken(address: string, caller?: string): Contract {126 const web3 = this.helper.getWeb3();127 return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});128 }129130 rftTokenById(collectionId: number, tokenId: number, caller?: string): Contract {131 return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);132 }133}134135136class EthGroup extends EthGroupBase {137 DEFAULT_GAS = 2_500_000;138139 createAccount() {140 const web3 = this.helper.getWeb3();141 const account = web3.eth.accounts.create();142 web3.eth.accounts.wallet.add(account.privateKey);143 return account.address;144 }145146 async createAccountWithBalance(donor: IKeyringPair, amount=100n) {147 const account = this.createAccount();148 await this.transferBalanceFromSubstrate(donor, account, amount);149150 return account;151 }152153 async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=100n, inTokens=true) {154 return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));155 }156157 async getCollectionCreationFee(signer: string) {158 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);159 return await collectionHelper.methods.collectionCreationFee().call();160 }161162 async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {163 if(!gasLimit) gasLimit = this.DEFAULT_GAS;164 const web3 = this.helper.getWeb3();165 const gasPrice = await web3.eth.getGasPrice();166 167 await this.helper.executeExtrinsic(168 signer,169 'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],170 true,171 );172 }173174 async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {175 return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);176 }177178 async createCollecion(functionName: string, signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {179 const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();180 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);181182 const result = await collectionHelper.methods[functionName](name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});183184 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);185 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);186 const events = this.helper.eth.normalizeEvents(result.events);187188 return {collectionId, collectionAddress, events};189 }190191 createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {192 return this.createCollecion('createNFTCollection', signer, name, description, tokenPrefix);193 }194195 async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {196 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);197198 const {collectionId, collectionAddress, events} = await this.createCollecion('createNFTCollection', signer, name, description, tokenPrefix);199200 await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();201202 return {collectionId, collectionAddress, events};203 }204205 createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[]}> {206 return this.createCollecion('createRFTCollection', signer, name, description, tokenPrefix);207 }208209 async createFungibleCollection(signer: string, name: string, decimals: number, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[]}> {210 const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();211 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);212213 const result = await collectionHelper.methods.createFTCollection(name, decimals, description, tokenPrefix).send({value: Number(collectionCreationPrice)});214 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);215 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);216217 const events = this.helper.eth.normalizeEvents(result.events);218219 return {collectionId, collectionAddress, events};220 }221222 async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {223 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);224225 const {collectionId, collectionAddress, events} = await this.createCollecion('createRFTCollection', signer, name, description, tokenPrefix);226227 await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();228229 return {collectionId, collectionAddress, events};230 }231232 async deployCollectorContract(signer: string): Promise<Contract> {233 return await this.helper.ethContract.deployByCode(signer, 'Collector', `234 // SPDX-License-Identifier: UNLICENSED235 pragma solidity ^0.8.6;236237 contract Collector {238 uint256 collected;239 fallback() external payable {240 giveMoney();241 }242 function giveMoney() public payable {243 collected += msg.value;244 }245 function getCollected() public view returns (uint256) {246 return collected;247 }248 function getUnaccounted() public view returns (uint256) {249 return address(this).balance - collected;250 }251252 function withdraw(address payable target) public {253 target.transfer(collected);254 collected = 0;255 }256 }257 `);258 }259260 async deployFlipper(signer: string): Promise<Contract> {261 return await this.helper.ethContract.deployByCode(signer, 'Flipper', `262 // SPDX-License-Identifier: UNLICENSED263 pragma solidity ^0.8.6;264265 contract Flipper {266 bool value = false;267 function flip() public {268 value = !value;269 }270 function getValue() public view returns (bool) {271 return value;272 }273 }274 `);275 }276277 async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {278 const before = await this.helper.balance.getEthereum(user);279 await call();280 281 await this.helper.wait.newBlocks(1);282 const after = await this.helper.balance.getEthereum(user);283284 return before - after;285 }286287 normalizeEvents(events: any): NormalizedEvent[] {288 const output = [];289 for (const key of Object.keys(events)) {290 if (key.match(/^[0-9]+$/)) {291 output.push(events[key]);292 } else if (Array.isArray(events[key])) {293 output.push(...events[key]);294 } else {295 output.push(events[key]);296 }297 }298 output.sort((a, b) => a.logIndex - b.logIndex);299 return output.map(({address, event, returnValues}) => {300 const args: { [key: string]: string } = {};301 for (const key of Object.keys(returnValues)) {302 if (!key.match(/^[0-9]+$/)) {303 args[key] = returnValues[key];304 }305 }306 return {307 address,308 event,309 args,310 };311 });312 }313314 async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {315 const wrappedCode = async () => {316 await code();317 318 await this.helper.wait.newBlocks(1);319 };320 return await this.helper.arrange.calculcateFee(address, wrappedCode);321 }322}323324class EthAddressGroup extends EthGroupBase {325 extractCollectionId(address: string): number {326 if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');327 return parseInt(address.substr(address.length - 8), 16);328 }329330 fromCollectionId(collectionId: number): string {331 if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');332 return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);333 }334335 extractTokenId(address: string): {collectionId: number, tokenId: number} {336 if (!address.startsWith('0x'))337 throw 'address not starts with "0x"';338 if (address.length > 42)339 throw 'address length is more than 20 bytes';340 return {341 collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),342 tokenId: Number('0x' + address.substring(address.length - 8)),343 };344 }345346 fromTokenId(collectionId: number, tokenId: number): string {347 return this.helper.util.getTokenAddress({collectionId, tokenId});348 }349350 normalizeAddress(address: string): string {351 return '0x' + address.substring(address.length - 40);352 }353}354export class EthPropertyGroup extends EthGroupBase {355 property(key: string, value: string): EthProperty {356 return [357 key,358 '0x'+Buffer.from(value).toString('hex'),359 ];360 }361}362export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;363364export class EthCrossAccountGroup extends EthGroupBase {365 fromAddress(address: TEthereumAccount): TEthCrossAccount {366 return {367 0: address,368 1: '0',369 field_0: address,370 field_1: '0',371 };372 }373374 fromKeyringPair(keyring: IKeyringPair): TEthCrossAccount {375 return {376 0: '0x0000000000000000000000000000000000000000',377 1: keyring.addressRaw,378 field_0: '0x0000000000000000000000000000000000000000',379 field_1: keyring.addressRaw,380 };381 }382}383384export class EthUniqueHelper extends DevUniqueHelper {385 web3: Web3 | null = null;386 web3Provider: WebsocketProvider | null = null;387388 eth: EthGroup;389 ethAddress: EthAddressGroup;390 ethNativeContract: NativeContractGroup;391 ethContract: ContractGroup;392 ethCrossAccount: EthCrossAccountGroup;393 ethProperty: EthPropertyGroup;394395 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {396 options.helperBase = options.helperBase ?? EthUniqueHelper;397398 super(logger, options);399 this.eth = new EthGroup(this);400 this.ethAddress = new EthAddressGroup(this);401 this.ethCrossAccount = new EthCrossAccountGroup(this);402 this.ethNativeContract = new NativeContractGroup(this);403 this.ethContract = new ContractGroup(this);404 this.ethProperty = new EthPropertyGroup(this);405 }406407 getWeb3(): Web3 {408 if(this.web3 === null) throw Error('Web3 not connected');409 return this.web3;410 }411412 connectWeb3(wsEndpoint: string) {413 if(this.web3 !== null) return;414 this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);415 this.web3 = new Web3(this.web3Provider);416 }417418 async disconnect() {419 if(this.web3 === null) return;420 this.web3Provider?.connection.close();421422 await super.disconnect();423 }424425 clearApi() {426 super.clearApi();427 this.web3 = null;428 }429430 clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {431 const newHelper = super.clone(helperCls, options) as EthUniqueHelper;432 newHelper.web3 = this.web3;433 newHelper.web3Provider = this.web3Provider;434435 return newHelper;436 }437}