import { createWalletClient, http, publicActions } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { mainnet } from "viem/chains";
const API = "https://app.ravn.exchange/api/v1";
const wallet = createWalletClient({
account: privateKeyToAccount(process.env.PRIVATE_KEY),
chain: mainnet,
transport: http(),
}).extend(publicActions);
async function ravn(path, body) {
const res = await fetch(API + path, {
method: "POST",
headers: {
"content-type": "application/json",
...(process.env.RAVN_API_KEY && { "x-api-key": process.env.RAVN_API_KEY }),
},
body: JSON.stringify(body),
});
const { data, error } = await res.json();
if (error) throw new Error(`${error.code}: ${error.message}`);
return data;
}
// Send one transaction and wait until it's mined. Throws unless it succeeded.
async function send({ to, data, value, gasLimit }) {
const hash = await wallet.sendTransaction({
to: to.toLowerCase(),
data,
value: BigInt(value ?? "0"),
gas: gasLimit ? BigInt(gasLimit) : undefined,
});
const receipt = await wallet.waitForTransactionReceipt({ hash });
if (receipt.status !== "success" || receipt.transactionHash !== hash) throw new Error(`${hash} failed`);
return hash;
}
const quote = await ravn("/quote", {
inputChainId: 1,
outputChainId: -2,
inputToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
outputToken: "So11111111111111111111111111111111111111112",
inputAmount: "1000000000000000000",
userAddress: wallet.account.address,
destinationAddress: process.env.SOL_DESTINATION,
});
const exec = await ravn("/execute", { quoteToken: quote.quoteToken });
let ref, txHash;
if (exec.sandbox) {
ref = "sandbox"; // a test execution: never send it. /status answers at once.
} else if (exec.executionType === "SIGNATURE") {
// Gasless, but the allowance must still be mined first, or the order never fills.
if (exec.approval?.reset) await send(exec.approval.reset);
if (exec.approval) await send(exec.approval);
const signature = await wallet.signTypedData(exec.typedData);
const approvalSignature = exec.approvalData && (await wallet.signTypedData(exec.approvalData));
({ statusRef: ref } = await ravn("/submit-signature", { quoteToken: exec.quoteToken, signature, approvalSignature }));
} else {
// TRANSACTION or DEPOSIT: send each call once the one before it has succeeded.
if (!exec.calls) throw new Error("No calls: see Execution types for this chain");
const feeCall = exec.fee ? exec.calls.at(-1) : undefined; // your fee is always last
let swapHash;
for (const call of exec.calls) if (call !== feeCall) swapHash = await send(call);
ref = exec.statusRef ?? swapHash;
txHash = swapHash;
if (feeCall) {
// The swap is out: a failed fee must not stop the tracking below.
txHash = (await send(feeCall).catch((e) => console.log(`fee not sent: ${e.message}`))) ?? swapHash;
}
}
// Poll until final, for up to an hour. Keep going through "expired" (a refund is on its way)
// and "not_found" (not seen yet), and retry a failed call (a 429, a network blip).
const FINAL = ["success", "refunded", "failed", "unknown"];
let status;
for (let i = 0; i < 360 && !FINAL.includes(status); i++) {
if (i) await new Promise((r) => setTimeout(r, 10_000));
try {
({ status } = await ravn("/status", { quoteToken: exec.quoteToken, ref, txHash }));
console.log(status);
} catch (e) {
if (/^(INVALID_REQUEST|QUOTE_INVALID|UNAUTHORIZED)/.test(e.message)) throw e; // a retry won't fix it
console.log(`status call failed, retrying: ${e.message}`);
}
}
if (!FINAL.includes(status)) console.log("Not final yet: keep polling later with", { quoteToken: exec.quoteToken, ref, txHash });