import { TypedTransaction } from '@ethereumjs/tx'; import { decode } from 'bech32-buffer'; import Web3 from 'web3'; import Big from 'big.js'; import { ISign, ITxData, ITxReceipt } from '../types'; import { formatAmount } from '../utils'; import { tokenHubAbi, tokenHubContractAddress } from './abis/tokenHub'; import { buildApprovalTx } from './approval'; import { prepareForBscOrEth } from './prepareForBscOrEth'; import { getBscToBbcFee } from './fee/getBscToBbcFee'; export const prepareForBscToBbc = async (txData: ITxData): Promise => { const { network, asset } = txData; const web3 = new Web3(new Web3.providers.HttpProvider(network.url)); const decodeTo = `0x${Buffer.from(decode(txData.to).data).toString('hex')}`; const tokenHubContract = new web3.eth.Contract(tokenHubAbi, tokenHubContractAddress); const relayFeeWei = await tokenHubContract.methods.getMiniRelayFee().call(); const approvalTx = await buildApprovalTx(txData); const amountWei = formatAmount(txData.value, asset?.decimals); const expireTime = (() => { const d = new Date(Date.now()); d.setMinutes(d.getMinutes() + 60); return d.getTime(); })(); const value = web3.utils.fromWei( new Big(relayFeeWei) .add(asset?.networkSymbol.toUpperCase() === 'BNB' ? amountWei : 0) .toFixed(), ); const { gasLimit, gasPrice, fee } = await getBscToBbcFee(txData, { skipApproval: true, approvalTx, replayFee: relayFeeWei, }); const nonce = approvalTx ? (approvalTx?.tx as TypedTransaction).nonce.toNumber() + 1 : 0; const transferOutTx = await prepareForBscOrEth({ ...txData, nonce, data: tokenHubContract.methods .transferOut(asset?.contractAddress, decodeTo, web3.utils.toHex(amountWei), expireTime) .encodeABI(), to: tokenHubContractAddress, value, gas: { gasPrice, gasLimit, }, }); return { fee, approvalTx: approvalTx?.tx, tx: transferOutTx.tx, sign: (privateKey: string) => { return { signedTx: transferOutTx.sign(privateKey).signedTx, signedApprovalTx: approvalTx?.sign(privateKey).signedTx, }; }, send: async (tx: ISign) => { if (tx.signedApprovalTx) { await web3.eth.sendSignedTransaction(tx.signedApprovalTx); } return web3.eth.sendSignedTransaction(tx.signedTx); }, }; };