import { decode } from 'bech32-buffer'; import Big from 'big.js'; import Web3 from 'web3'; import { BSC_TO_BBC_GAS_LIMIT } from '../../constants'; import { ITxData, ITxReceipt } from '../../types'; import { formatAmount } from '../../utils'; import { tokenHubAbi, tokenHubContractAddress } from '../abis/tokenHub'; import { buildApprovalTx } from '../approval'; import { getBscFee } from '../fee/getBscFee'; import { IFeeResponse } from './types'; export const getBscToBbcFee = async ( txData: ITxData, { approvalTx, replayFee, skipApproval, }: { skipApproval?: boolean; approvalTx?: ITxReceipt; replayFee?: string; } = {}, ): Promise => { const { network, asset } = txData; const web3 = new Web3(new Web3.providers.HttpProvider(network.url)); const tokenHubContract = new web3.eth.Contract(tokenHubAbi, tokenHubContractAddress); const decodeTo = `0x${Buffer.from(decode(txData.to).data).toString('hex')}`; const amountWei = formatAmount(txData.value, asset?.decimals); // TODO: draft code, Should be optimized const relayFeeWei = replayFee || (await tokenHubContract.methods.getMiniRelayFee().call()); const _approvalTx = approvalTx || (!skipApproval && (await buildApprovalTx(txData))) || undefined; const expireTime = (() => { const d = new Date(Date.now()); d.setMinutes(d.getMinutes() + 60); return d.getTime(); })(); const toTokenHubAmountWei = new Big(amountWei).gt(relayFeeWei) ? new Big(amountWei).minus(relayFeeWei).toFixed() : amountWei; const data = tokenHubContract.methods .transferOut( asset?.contractAddress, decodeTo, web3.utils.toHex(toTokenHubAmountWei), expireTime, ) .encodeABI(); const value = web3.utils.fromWei( new Big(relayFeeWei) .add(asset?.networkSymbol.toUpperCase() === 'BNB' ? toTokenHubAmountWei : 0) .toFixed(), ); const bscFee = await getBscFee({ ...txData, data, to: tokenHubContractAddress, value, gas: { gasLimit: txData.gas?.gasLimit || (_approvalTx ? BSC_TO_BBC_GAS_LIMIT.toFixed() : undefined), }, }); const fee = new Big(bscFee.fee) .add(_approvalTx?.fee ?? 0) .add(web3.utils.fromWei(relayFeeWei)) .toFixed(); return { fee, gasLimit: bscFee.gasLimit, gasPrice: bscFee.gasPrice, baseFee: new Big(fee).minus(bscFee.fee).toFixed(), } as IFeeResponse; };