import Web3 from 'web3'; import { TransactionFactory } from '@ethereumjs/tx'; import Common, { Hardfork } from '@ethereumjs/common'; import ert20TokenAbi from 'human-standard-token-abi'; import { ISign, ITxData, ITxReceipt } from '../types'; import { formatAmount, checkNativeToken } from '../utils'; import { isEthNetwork } from '../utils/address'; import { getBscFee } from './fee/getBscFee'; const _prepareToSendTx = async (txData: ITxData): Promise => { const { network, from, asset } = txData; const web3 = new Web3(new Web3.providers.HttpProvider(network.url)); const value = formatAmount(txData.value, asset?.decimals); const isNativeToken = checkNativeToken({ networkSymbol: asset?.networkSymbol, network, }); const txParam: any = { from, to: txData.to, value: web3.utils.toHex(value), data: txData.data, }; // Transfer to non-nativeToken coins if (!isNativeToken && !txData.data) { if (!asset?.contractAddress) throw new Error(`Asset "${asset?.networkSymbol} does not have a contract address"`); const contract = new web3.eth.Contract(ert20TokenAbi, asset?.contractAddress); const data = contract.methods.transfer(txData.to, txParam.value).encodeABI(); txParam.data = web3.utils.toHex(data); txParam.to = asset?.contractAddress; txParam.value = web3.utils.toHex(0); } // GasLimit const { gasLimit, gasPrice, fee } = await getBscFee(txData); txParam.gasLimit = web3.utils.toHex(gasLimit); txParam.nonce = txData.nonce || (await web3.eth.getTransactionCount(from, 'pending')); const common = Common.custom( { chainId: Number(network.chainId), url: network.url, }, { hardfork: network.hardfork || Hardfork.Chainstart, }, ); // EIP-1559 tx if (Number(txData.type) === 2 || (txData.gas?.maxFeePerGas && txData.gas?.maxPriorityFeePerGas)) { txParam.type = web3.utils.toHex('2'); txParam.chainId = web3.utils.toHex(network.chainId); txParam.maxFeePerGas = web3.utils.toHex(txData.gas?.maxFeePerGas as string); txParam.maxPriorityFeePerGas = web3.utils.toHex(txData.gas?.maxPriorityFeePerGas as string); common.setHardfork(Hardfork.London); } else { txParam.gasPrice = web3.utils.toHex(gasPrice as string); } if (__DEV__) { console.debug('txParam: ', txParam); } const tx = TransactionFactory.fromTxData(txParam, { common }); return { tx, fee, sign: (privateKey: string) => { const _privateKey = Buffer.from(privateKey, 'hex'); const signedTx = tx.sign(_privateKey); const serializedTx = signedTx.serialize(); return { signedTx: `0x${serializedTx.toString('hex')}`, }; }, send: (tx: ISign) => web3.eth.sendSignedTransaction(tx.signedTx), }; }; export const prepareForBscOrEth = (txData: ITxData): Promise => { let network = txData.network; if (isEthNetwork(network)) { network = { ...network, hardfork: network.hardfork || 'homestead', }; } return _prepareToSendTx({ ...txData, network }); };