|
| 1 | +import { SwapQuote } from '@0xsequence/api' |
| 2 | +import { sendTransactions } from '@0xsequence/connect' |
| 3 | +import { compareAddress, useToast } from '@0xsequence/design-system' |
| 4 | +import { useAPIClient, useIndexerClient } from '@0xsequence/hooks' |
| 5 | +import { ReactNode, useEffect, useState } from 'react' |
| 6 | +import { Hex, zeroAddress } from 'viem' |
| 7 | +import { useAccount, useChainId, usePublicClient, useWalletClient } from 'wagmi' |
| 8 | + |
| 9 | +import { SwapContextProvider } from '../../../contexts/Swap' |
| 10 | +import { useNavigation } from '../../../hooks/useNavigation' |
| 11 | +import { TokenBalanceWithPrice } from '../../../utils' |
| 12 | + |
| 13 | +export const SwapProvider = ({ children }: { children: ReactNode }) => { |
| 14 | + const toast = useToast() |
| 15 | + const { address: userAddress, connector } = useAccount() |
| 16 | + const { setNavigation } = useNavigation() |
| 17 | + const apiClient = useAPIClient() |
| 18 | + const connectedChainId = useChainId() |
| 19 | + |
| 20 | + const [fromCoin, _setFromCoin] = useState<TokenBalanceWithPrice>() |
| 21 | + const [fromAmount, setFromAmount] = useState<number>(0) |
| 22 | + const [toCoin, _setToCoin] = useState<TokenBalanceWithPrice>() |
| 23 | + const [toAmount, setToAmount] = useState<number>(0) |
| 24 | + const [recentInput, setRecentInput] = useState<'from' | 'to'>('from') |
| 25 | + const [setNonRecentAmount, _setNonRecentAmount] = useState<() => void>(() => 0) |
| 26 | + |
| 27 | + const [isSwapReady, setIsSwapReady] = useState(false) |
| 28 | + const [swapQuoteData, setSwapQuoteData] = useState<SwapQuote>() |
| 29 | + const [isSwapQuotePending, setIsSwapQuotePending] = useState(false) |
| 30 | + const [hasInsufficientFunds, setHasInsufficientFunds] = useState(false) |
| 31 | + const [isErrorSwapQuote, setIsErrorSwapQuote] = useState(false) |
| 32 | + |
| 33 | + const [isTxnPending, setIsTxnPending] = useState(false) |
| 34 | + const [isErrorTxn, setIsErrorTxn] = useState(false) |
| 35 | + |
| 36 | + const publicClient = usePublicClient({ chainId: connectedChainId }) |
| 37 | + const { data: walletClient } = useWalletClient({ chainId: connectedChainId }) |
| 38 | + const indexerClient = useIndexerClient(connectedChainId) |
| 39 | + |
| 40 | + useEffect(() => { |
| 41 | + setFromCoin(undefined) |
| 42 | + setFromAmount(0) |
| 43 | + setToCoin(undefined) |
| 44 | + setToAmount(0) |
| 45 | + setRecentInput('from') |
| 46 | + setIsSwapReady(false) |
| 47 | + setSwapQuoteData(undefined) |
| 48 | + setIsSwapQuotePending(false) |
| 49 | + setIsErrorSwapQuote(false) |
| 50 | + setIsTxnPending(false) |
| 51 | + setIsErrorTxn(false) |
| 52 | + }, [userAddress, connectedChainId]) |
| 53 | + |
| 54 | + useEffect(() => { |
| 55 | + if (recentInput === 'from') { |
| 56 | + _setNonRecentAmount(() => setFromAmount) |
| 57 | + } else { |
| 58 | + _setNonRecentAmount(() => setToAmount) |
| 59 | + } |
| 60 | + }, [recentInput]) |
| 61 | + |
| 62 | + useEffect(() => { |
| 63 | + setIsSwapReady(false) |
| 64 | + setSwapQuoteData(undefined) |
| 65 | + setIsErrorSwapQuote(false) |
| 66 | + }, [fromCoin, toCoin, fromAmount, toAmount]) |
| 67 | + |
| 68 | + useEffect(() => { |
| 69 | + const fetchSwapQuote = async () => { |
| 70 | + if (!fromCoin || !toCoin || (fromAmount === 0 && toAmount === 0)) { |
| 71 | + return |
| 72 | + } |
| 73 | + |
| 74 | + setIsSwapQuotePending(true) |
| 75 | + setIsErrorSwapQuote(false) |
| 76 | + |
| 77 | + let swapQuote |
| 78 | + try { |
| 79 | + // swapQuote = await apiClient.getSwapQuoteV2({ |
| 80 | + // userAddress: String(userAddress), |
| 81 | + // buyCurrencyAddress: toCoin.contractAddress, |
| 82 | + // sellCurrencyAddress: fromCoin.contractAddress, |
| 83 | + // tokenAmount: String(recentInput === 'to' ? toAmount : fromAmount), |
| 84 | + // isBuyAmount: recentInput === 'to', |
| 85 | + // chainId: connectedChainId, |
| 86 | + // includeApprove: true |
| 87 | + // }) |
| 88 | + |
| 89 | + swapQuote = await apiClient.getSwapQuoteV2({ |
| 90 | + userAddress: String(userAddress), |
| 91 | + buyCurrencyAddress: toCoin.contractAddress, |
| 92 | + sellCurrencyAddress: fromCoin.contractAddress, |
| 93 | + buyAmount: String(toAmount), |
| 94 | + chainId: connectedChainId, |
| 95 | + includeApprove: true |
| 96 | + }) |
| 97 | + |
| 98 | + const transactionValue = swapQuote?.swapQuote?.transactionValue || '0' |
| 99 | + |
| 100 | + // TODO: change this to "amount" from return |
| 101 | + |
| 102 | + if (recentInput === 'from') { |
| 103 | + setToAmount(Number(transactionValue)) |
| 104 | + } else { |
| 105 | + setFromAmount(Number(transactionValue)) |
| 106 | + } |
| 107 | + |
| 108 | + setSwapQuoteData(swapQuote?.swapQuote) |
| 109 | + setIsSwapReady(true) |
| 110 | + } catch (error) { |
| 111 | + const hasInsufficientFunds = (error as any).code === -4 |
| 112 | + setHasInsufficientFunds(hasInsufficientFunds) |
| 113 | + setIsErrorSwapQuote(true) |
| 114 | + } |
| 115 | + setIsSwapQuotePending(false) |
| 116 | + } |
| 117 | + |
| 118 | + fetchSwapQuote() |
| 119 | + }, [fromCoin, toCoin, fromAmount, toAmount]) |
| 120 | + |
| 121 | + const setFromCoin = (coin: TokenBalanceWithPrice | undefined) => { |
| 122 | + if (coin?.chainId === toCoin?.chainId && coin?.contractAddress === toCoin?.contractAddress) { |
| 123 | + switchCoinOrder() |
| 124 | + } else { |
| 125 | + _setFromCoin(coin) |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + const setToCoin = (coin: TokenBalanceWithPrice | undefined) => { |
| 130 | + if (coin?.chainId === fromCoin?.chainId && coin?.contractAddress === fromCoin?.contractAddress) { |
| 131 | + switchCoinOrder() |
| 132 | + } else { |
| 133 | + _setToCoin(coin) |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + const switchCoinOrder = () => { |
| 138 | + const tempFrom = fromCoin |
| 139 | + const tempTo = toCoin |
| 140 | + const tempFromAmount = fromAmount |
| 141 | + const tempToAmount = toAmount |
| 142 | + _setFromCoin(tempTo) |
| 143 | + _setToCoin(tempFrom) |
| 144 | + setFromAmount(tempToAmount) |
| 145 | + setToAmount(tempFromAmount) |
| 146 | + } |
| 147 | + |
| 148 | + const onSubmitSwap = async () => { |
| 149 | + if (isErrorSwapQuote || !userAddress || !publicClient || !walletClient || !connector) { |
| 150 | + console.error('Please ensure validation before submitting') |
| 151 | + return |
| 152 | + } |
| 153 | + |
| 154 | + setIsErrorTxn(false) |
| 155 | + setIsTxnPending(true) |
| 156 | + |
| 157 | + try { |
| 158 | + const isSwapNativeToken = compareAddress(zeroAddress, swapQuoteData?.currencyAddress || '') |
| 159 | + |
| 160 | + const getSwapTransactions = () => { |
| 161 | + if (!swapQuoteData) { |
| 162 | + return [] |
| 163 | + } |
| 164 | + |
| 165 | + const swapTransactions = [ |
| 166 | + // Swap quote optional approve step |
| 167 | + ...(swapQuoteData?.approveData && !isSwapNativeToken |
| 168 | + ? [ |
| 169 | + { |
| 170 | + to: swapQuoteData?.currencyAddress as Hex, |
| 171 | + data: swapQuoteData?.approveData as Hex, |
| 172 | + chain: connectedChainId |
| 173 | + } |
| 174 | + ] |
| 175 | + : []), |
| 176 | + // Swap quote tx |
| 177 | + { |
| 178 | + to: swapQuoteData?.to as Hex, |
| 179 | + data: swapQuoteData?.transactionData as Hex, |
| 180 | + chain: connectedChainId, |
| 181 | + ...(isSwapNativeToken |
| 182 | + ? { |
| 183 | + value: BigInt(swapQuoteData?.transactionValue || '0') |
| 184 | + } |
| 185 | + : {}) |
| 186 | + } |
| 187 | + ] |
| 188 | + return swapTransactions |
| 189 | + } |
| 190 | + |
| 191 | + const walletClientChainId = await walletClient.getChainId() |
| 192 | + if (walletClientChainId !== connectedChainId) { |
| 193 | + await walletClient.switchChain({ id: connectedChainId }) |
| 194 | + } |
| 195 | + |
| 196 | + await sendTransactions({ |
| 197 | + connector, |
| 198 | + walletClient, |
| 199 | + publicClient, |
| 200 | + chainId: connectedChainId, |
| 201 | + indexerClient, |
| 202 | + senderAddress: userAddress, |
| 203 | + transactions: [...getSwapTransactions()] |
| 204 | + }) |
| 205 | + |
| 206 | + toast({ |
| 207 | + title: 'Transaction sent', |
| 208 | + description: `Successfully swapped ${fromAmount} ${fromCoin?.contractInfo?.name} for ${toAmount} ${toCoin?.contractInfo?.name}`, |
| 209 | + variant: 'success' |
| 210 | + }) |
| 211 | + |
| 212 | + setNavigation({ |
| 213 | + location: 'home' |
| 214 | + }) |
| 215 | + } catch (error) { |
| 216 | + console.error('Failed to send transactions', error) |
| 217 | + setIsSwapReady(false) |
| 218 | + setIsTxnPending(false) |
| 219 | + setIsErrorTxn(true) |
| 220 | + } |
| 221 | + } |
| 222 | + |
| 223 | + return ( |
| 224 | + <SwapContextProvider |
| 225 | + value={{ |
| 226 | + fromCoin, |
| 227 | + fromAmount, |
| 228 | + toCoin, |
| 229 | + toAmount, |
| 230 | + recentInput, |
| 231 | + isSwapReady, |
| 232 | + isSwapQuotePending, |
| 233 | + hasInsufficientFunds, |
| 234 | + isErrorSwapQuote, |
| 235 | + isTxnPending, |
| 236 | + isErrorTxn, |
| 237 | + setFromCoin, |
| 238 | + setFromAmount, |
| 239 | + setToCoin, |
| 240 | + setToAmount, |
| 241 | + setRecentInput, |
| 242 | + setNonRecentAmount, |
| 243 | + switchCoinOrder, |
| 244 | + onSubmitSwap |
| 245 | + }} |
| 246 | + > |
| 247 | + {children} |
| 248 | + </SwapContextProvider> |
| 249 | + ) |
| 250 | +} |
0 commit comments