import { executeAndTrack, ExecuteAndTrackError } from "@ravnexchange/sdk";
function SwapButton({ params }: { params: GetQuoteParams }) {
const { quote, isExpired, refetch } = useRavnQuote(client, params);
const [track, setTrack] = useState<{ quoteToken: string; ref: string; txHash?: string } | null>(null);
const { status } = useRavnStatus(client, track);
const handleSwap = async () => {
// Sends the approval, the swap or deposit, and your fee, in order. The hook does the polling.
// `handlers`: your wallet functions, or the SDK's wallet add-ons (/sdks/core#wallet-add-ons).
try {
const result = await executeAndTrack(client, { quoteToken: quote!.quoteToken }, handlers, {
sendDeposit: true,
pollUntilTerminal: false,
});
if (result.depositNotSent) return; // a deposit it couldn't send: show the address instead
setTrack({ quoteToken: result.quoteToken, ref: result.statusRef!, txHash: result.statusTxHash });
} catch (e) {
const sent = e instanceof ExecuteAndTrackError ? e.partial : undefined;
// No swap hash: it never went out (its approval failed, say). The error stands: get a fresh quote.
if (!(sent?.txHash || sent?.signature || sent?.signedTransaction || sent?.sentUnclear)) throw e;
// Signed or sent, but no ref yet: RAVN, the venue or the wallet may hold it, so don't send a new one.
if (!sent.statusRef) throw e;
// Failed after the swap went out: keep tracking it with what was sent.
setTrack({ quoteToken: sent.quoteToken!, ref: sent.statusRef, txHash: sent.statusTxHash });
}
};
if (isExpired) return <button onClick={refetch}>Refresh quote</button>;
return <button onClick={handleSwap}>{status ? status.status : "Swap"}</button>;
}