-
- Sending two transactions: Approve and Swap
+
+ {needsApproval
+ ? 'Sending two transactions: Approve and Swap'
+ : 'Sending swap transaction'}
+
+
+ {`Sign with ${connector?.name || 'wallet'} to proceed`}
-
{`Sign with ${
- connector?.name || 'wallet'
- } to proceed`}
>
)
diff --git a/src/features/swap/useAllowance.tsx b/src/features/swap/useAllowance.tsx
new file mode 100644
index 0000000..467bab6
--- /dev/null
+++ b/src/features/swap/useAllowance.tsx
@@ -0,0 +1,43 @@
+import { useQuery } from '@tanstack/react-query'
+import { Contract } from 'ethers'
+import { ERC20_ABI } from 'src/config/consts'
+import { BrokerAddresses } from 'src/config/exchanges'
+import { TokenId, getTokenAddress } from 'src/config/tokens'
+import { getProvider } from 'src/features/providers'
+import { logger } from 'src/utils/logger'
+
+async function fetchAllowance(
+ tokenAddr: string,
+ accountAddress: string,
+ chainId: number
+): Promise
{
+ logger.info(`Fetching allowance for token ${tokenAddr} on chain ${chainId}`)
+ const provider = getProvider(chainId)
+ const contract = new Contract(tokenAddr, ERC20_ABI, provider)
+ const brokerAddress = BrokerAddresses[chainId as keyof typeof BrokerAddresses]
+
+ const allowance = await contract.allowance(accountAddress, brokerAddress)
+ logger.info(`Allowance: ${allowance.toString()}`)
+ return allowance.toString()
+}
+
+export function useAllowance(chainId: number, tokenId: TokenId, accountAddress?: string) {
+ const { data: allowance, isLoading } = useQuery(
+ ['tokenAllowance', chainId, tokenId, accountAddress],
+ async () => {
+ if (!accountAddress) return '0'
+ const tokenAddr = getTokenAddress(tokenId, chainId)
+ return fetchAllowance(tokenAddr, accountAddress, chainId)
+ },
+ {
+ retry: false,
+ enabled: Boolean(accountAddress && chainId && tokenId),
+ staleTime: 5000, // Consider allowance stale after 5 seconds
+ }
+ )
+
+ return {
+ allowance: allowance || '0',
+ isLoading,
+ }
+}
diff --git a/src/features/swap/useSwapTransaction.ts b/src/features/swap/useSwapTransaction.ts
index 6680883..3532161 100644
--- a/src/features/swap/useSwapTransaction.ts
+++ b/src/features/swap/useSwapTransaction.ts
@@ -36,8 +36,10 @@ export function useSwapTransaction(
!isApproveConfirmed ||
new BigNumber(amountInWei).lte(0) ||
new BigNumber(thresholdAmountInWei).lte(0)
- )
+ ) {
+ logger.debug('Skipping swap transaction')
return null
+ }
const sdk = await getMentoSdk(chainId)
const fromTokenAddr = getTokenAddress(fromToken, chainId)
const toTokenAddr = getTokenAddress(toToken, chainId)