Skip to content

Commit

Permalink
fix: don't apply auto refuel when swapping to native tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
chybisov committed Mar 16, 2023
1 parent 8dd8086 commit fe85b38
Showing 1 changed file with 35 additions and 29 deletions.
64 changes: 35 additions & 29 deletions packages/widget/src/hooks/useGasRefuel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,61 +9,67 @@ import { useTokenBalance } from './useTokenBalance';
export const useGasRefuel = () => {
const { getChainById } = useChains();

const [fromChain, fromToken, toChain, toAddress] = useWatch({
name: [
SwapFormKey.FromChain,
SwapFormKey.FromToken,
SwapFormKey.ToChain,
SwapFormKey.ToAddress,
],
});
const [fromChainId, fromTokenAddress, toChainId, toTokenAddress, toAddress] =
useWatch({
name: [
SwapFormKey.FromChain,
SwapFormKey.FromToken,
SwapFormKey.ToChain,
SwapFormKey.ToToken,
SwapFormKey.ToAddress,
],
});

const currentChain = getChainById(toChain);
const toChain = getChainById(toChainId);

const { token: nativeToken } = useTokenBalance(
toChain && currentChain?.nativeToken,
toChainId && toChain?.nativeToken,
toAddress,
);

const { data: gasRecommendation, isLoading } = useGasRecommendation(
toChain,
fromChain,
fromToken,
toChainId,
fromChainId,
fromTokenAddress,
);

const enabled = useMemo(() => {
if (
// We don't allow same chain refuel.
// If a user runs out of gas, he can't send a source chain transaction.
fromChain !== toChain &&
gasRecommendation?.available &&
gasRecommendation.recommended &&
nativeToken
fromChainId === toChainId ||
// We don't want to apply auto refuel when swapping to native tokens
toChain?.nativeToken.address === toTokenAddress ||
!gasRecommendation?.available ||
!gasRecommendation.recommended ||
!nativeToken
) {
const tokenBalance = Big(nativeToken.amount ?? 0);
return false;
}
const tokenBalance = Big(nativeToken.amount ?? 0);

// check if the user balance < 50% of the recommended amount
const recommendedAmount = Big(gasRecommendation.recommended.amount)
.div(10 ** gasRecommendation.recommended.token.decimals)
.div(2);
// check if the user balance < 50% of the recommended amount
const recommendedAmount = Big(gasRecommendation.recommended.amount)
.div(10 ** gasRecommendation.recommended.token.decimals)
.div(2);

const insufficientGas = tokenBalance.lt(recommendedAmount);
return insufficientGas;
}
return false;
const insufficientGas = tokenBalance.lt(recommendedAmount);
return insufficientGas;
}, [
fromChain,
fromChainId,
gasRecommendation?.available,
gasRecommendation?.recommended,
nativeToken,
toChain,
toChain?.nativeToken.address,
toChainId,
toTokenAddress,
]);

return {
enabled: enabled,
availble: gasRecommendation?.available,
isLoading: isLoading,
chain: currentChain,
chain: toChain,
gasRecommendation,
};
};

0 comments on commit fe85b38

Please sign in to comment.