Skip to content

Commit

Permalink
fix: add gas estimation for staking
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolasbrugneaux committed Feb 8, 2024
1 parent 6bbac7f commit 52d7b02
Showing 1 changed file with 27 additions and 12 deletions.
39 changes: 27 additions & 12 deletions src/features/swap/hooks/useStaking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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) {
Expand All @@ -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,
Expand Down Expand Up @@ -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),
Expand Down

0 comments on commit 52d7b02

Please sign in to comment.