|
| 1 | +"use client"; |
| 2 | +import { useQuery } from "@tanstack/react-query"; |
| 3 | +import * as Buy from "../../../bridge/Buy.js"; |
| 4 | +import * as Transfer from "../../../bridge/Transfer.js"; |
| 5 | +import type { Token } from "../../../bridge/types/Token.js"; |
| 6 | +import type { ThirdwebClient } from "../../../client/client.js"; |
| 7 | +import { checksumAddress } from "../../../utils/address.js"; |
| 8 | + |
| 9 | +interface UseBridgeQuoteParams { |
| 10 | + originToken: Token; |
| 11 | + destinationToken: Token; |
| 12 | + destinationAmount: bigint; |
| 13 | + client: ThirdwebClient; |
| 14 | + enabled?: boolean; |
| 15 | + feePayer?: "sender" | "receiver"; |
| 16 | +} |
| 17 | + |
| 18 | +export function useBridgeQuote({ |
| 19 | + originToken, |
| 20 | + destinationToken, |
| 21 | + destinationAmount, |
| 22 | + feePayer, |
| 23 | + client, |
| 24 | + enabled = true, |
| 25 | +}: UseBridgeQuoteParams) { |
| 26 | + return useQuery({ |
| 27 | + enabled: |
| 28 | + enabled && !!originToken && !!destinationToken && !!destinationAmount, |
| 29 | + queryFn: async () => { |
| 30 | + // if ssame token and chain, use transfer |
| 31 | + if ( |
| 32 | + checksumAddress(originToken.address) === |
| 33 | + checksumAddress(destinationToken.address) && |
| 34 | + originToken.chainId === destinationToken.chainId |
| 35 | + ) { |
| 36 | + const transfer = await Transfer.prepare({ |
| 37 | + amount: destinationAmount, |
| 38 | + chainId: originToken.chainId, |
| 39 | + client, |
| 40 | + feePayer, |
| 41 | + receiver: destinationToken.address, |
| 42 | + sender: originToken.address, |
| 43 | + tokenAddress: originToken.address, |
| 44 | + }); |
| 45 | + return transfer; |
| 46 | + } |
| 47 | + const quote = await Buy.quote({ |
| 48 | + amount: destinationAmount, |
| 49 | + client, |
| 50 | + destinationChainId: destinationToken.chainId, |
| 51 | + destinationTokenAddress: destinationToken.address, |
| 52 | + originChainId: originToken.chainId, |
| 53 | + originTokenAddress: originToken.address, |
| 54 | + }); |
| 55 | + |
| 56 | + return quote; |
| 57 | + }, |
| 58 | + queryKey: [ |
| 59 | + "bridge-quote", |
| 60 | + originToken.chainId, |
| 61 | + originToken.address, |
| 62 | + destinationToken.chainId, |
| 63 | + destinationToken.address, |
| 64 | + destinationAmount.toString(), |
| 65 | + feePayer, |
| 66 | + ], |
| 67 | + refetchInterval: 60000, // 30 seconds |
| 68 | + retry: 3, // 1 minute |
| 69 | + staleTime: 30000, |
| 70 | + }); |
| 71 | +} |
0 commit comments