import { Connection, VersionedTransaction } from "@solana/web3.js";
const ROUTE = "https://partners.route.fun/solana";
// Backend: a partner key stays on the server. (On the public tier, drop the header.)
export async function buildSwap(input: string, output: string, amount: bigint, user: string) {
const q = new URLSearchParams({ in: input, out: output, amount: amount.toString(), recipient: user, slippageBps: "50" });
const res = await fetch(`${ROUTE}/quote?${q}`, { headers: { authorization: `Bearer ${process.env.ROUTE_API_KEY}` } });
const body = await res.json();
if (!res.ok) throw new Error(body.error ?? `Route returned ${res.status}`);
return body; // tx, amount_out, amount_out_after_fee, min_out, fee_bps, expiry_slot
}
// Client: the wallet signs and sends.
export async function sendSwap(build: { tx: string }, wallet: { signTransaction(t: VersionedTransaction): Promise<VersionedTransaction> }, connection: Connection) {
const signed = await wallet.signTransaction(VersionedTransaction.deserialize(Buffer.from(build.tx, "base64")));
const sig = await connection.sendRawTransaction(signed.serialize(), { maxRetries: 3 });
await connection.confirmTransaction(sig, "confirmed");
return sig;
}