import type { SwapResponse , TradeComputed } from '../../types' ; import { useAsync } from 'react-use' ; import type { AsyncState } from 'react-use/lib/useAsyncFn' ; import { TradeStrategy } from '../../types' ; import { EthereumTokenType , useAccount , useTraderConstants } from '@masknet/web3-shared-evm' ; import { TargetChainIdContext } from '../useTargetChainIdContext' ; import { useExchangeProxyContract } from '../../contracts/balancer/useExchangeProxyContract' ; import type { ExchangeProxy } from '@masknet/web3-contracts/types/ExchangeProxy' ; import { useTradeAmount } from './useTradeAmount' ; import { SLIPPAGE_DEFAULT } from '../../constants' ; export function useTradeGasLimit ( trade ) { const account = useAccount ( ) ; const { targetChainId } = TargetChainIdContext . useContainer ( ) ; const exchangeProxyContract = useExchangeProxyContract ( targetChainId ) ; const { BALANCER_ETH_ADDRESS } = useTraderConstants ( targetChainId ) ; const tradeAmount = useTradeAmount ( trade , SLIPPAGE_DEFAULT ) ; return useAsync ( async ( ) => { if ( ! trade || ! trade . inputToken || ! trade . outputToken || ! exchangeProxyContract || ! BALANCER_ETH_ADDRESS ) return 0 ; const { swaps : [ swaps ] , } = trade . trade_ as SwapResponse ; const swap_ = swaps . map ( ( x ) => x . map ( ( y ) => [ y . pool , y . tokenIn , y . tokenOut , y . swapAmount , y . limitReturnAmount , y . maxPrice , ] as [ string , string , string , string , string , string ] ) ) ; const inputTokenAddress = trade . inputToken . type === EthereumTokenType . Native ? BALANCER_ETH_ADDRESS : trade . inputToken . address ; const outputTokenAddress = trade . outputToken . type === EthereumTokenType . Native ? BALANCER_ETH_ADDRESS : trade . outputToken . address ; let transactionValue = '0' ; if ( trade . strategy === TradeStrategy . ExactIn && trade . inputToken . type === EthereumTokenType . Native ) transactionValue = trade . inputAmount . toFixed ( ) ; else if ( trade . strategy === TradeStrategy . ExactOut && trade . outputToken . type === EthereumTokenType . Native ) transactionValue = trade . outputAmount . toFixed ( ) ; const tx = trade . strategy === TradeStrategy . ExactIn ? exchangeProxyContract . methods . multihopBatchSwapExactIn ( swap_ , inputTokenAddress , outputTokenAddress , trade . inputAmount . toFixed ( ) , tradeAmount . toFixed ( ) ) : exchangeProxyContract . methods . multihopBatchSwapExactOut ( swap_ , inputTokenAddress , outputTokenAddress , tradeAmount . toFixed ( ) ) ; return tx . estimateGas ( { from : account , value : transactionValue , } ) ; } , [ trade , exchangeProxyContract , BALANCER_ETH_ADDRESS , tradeAmount , account ] ) ; }