From 52d7b024ebb048b1995b5098a3743ffb979a73df Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Thu, 8 Feb 2024 14:24:44 +0100 Subject: [PATCH] fix: add gas estimation for staking --- src/features/swap/hooks/useStaking.ts | 39 ++++++++++++++++++--------- 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/src/features/swap/hooks/useStaking.ts b/src/features/swap/hooks/useStaking.ts index 124398cc..e8f592d7 100644 --- a/src/features/swap/hooks/useStaking.ts +++ b/src/features/swap/hooks/useStaking.ts @@ -8,7 +8,7 @@ import logger from 'src/services/logger'; import { Mode } from 'src/types'; import { transactionEvent } from 'src/utils/ga'; import { Celo, CeloUSD, StCelo, Token } from 'src/utils/tokens'; -import { useContractWrite, usePublicClient } from 'wagmi'; +import { Address, useContractWrite, usePublicClient } from 'wagmi'; import { showErrorToast, showHashToast, showStakingToast } from '../utils/toast'; export function useStaking() { @@ -28,6 +28,19 @@ export function useStaking() { const client = usePublicClient(); + const _estimateGas = useCallback( + (address: Address, value: bigint) => { + return publicClient.estimateContractGas({ + abi: managerContract.abi, + address: managerContract.address!, + account: address!, + functionName: 'deposit', + value, + }); + }, + [publicClient, managerContract] + ); + const stake = useCallback( async (callbacks?: TxCallbacks) => { if (!address || !celoAmount || celoAmount.isEqualTo(0) || !stCeloBalance || !loadBalances) { @@ -41,7 +54,9 @@ export function useStaking() { value: celoAmount.displayAsBase(), }); try { - const stakeHash = await _stake({ value: celoAmount?.toBigInt() }); + const value = celoAmount?.toBigInt(); + const gas = await _estimateGas(address!, value); + const stakeHash = await _stake({ value, gas }); console.info('stakeHash', stakeHash); transactionEvent({ action: Mode.stake, @@ -95,19 +110,19 @@ export function useStaking() { return null; } - const gasFee = new Token( - await publicClient.estimateContractGas({ - abi: managerContract.abi, - address: managerContract.address!, - account: address!, - functionName: 'deposit', - value: celoAmount.toBigInt(), - }) - ); + const gasFee = new Token(await _estimateGas(address!, celoAmount.toBigInt())); const gasFeeInCelo = new Celo(gasFee.multipliedBy(suggestedGasPrice)); const gasFeeInUSD = new CeloUSD(gasFeeInCelo.multipliedBy(celoToUSDRate)); return gasFeeInUSD; - }, [celoAmount, celoBalance, managerContract, publicClient, suggestedGasPrice, celoToUSDRate]); + }, [ + celoAmount, + celoBalance, + address, + managerContract.address, + _estimateGas, + suggestedGasPrice, + celoToUSDRate, + ]); const receivedStCelo = useMemo( () => (celoAmount ? new StCelo(celoAmount.multipliedBy(stakingRate).dp(0)) : null),