Quickstart
This page takes one order from quote to delivery: 10 USDC on Arbitrum to USDC on Base.
How it fits together
Section titled “How it fits together”An integration has four steps. Your backend makes the API calls with your key, and the user’s wallet funds the order.
| Step | What happens |
|---|---|
| 1. Quote | POST /v3/quote prices the trade and returns options. |
| 2. Create | POST /v3/orders turns an option into an order, with the steps that fund it. |
| 3. Fund | The wallet approves the token if needed, then sends the deposit, on the source chain. |
| 4. Track | GET /v3/orders/{id} reports progress until summary.pollAfterSeconds is null. |
Try a quote
Section titled “Try a quote”A quote creates nothing and moves no funds. Set KHALANI_API_KEY to your key (see API access) and run:
curl -sS https://api.hyperstream.dev/v3/quote \ -H "X-API-Key: $KHALANI_API_KEY" -H "Content-Type: application/json" \ -d '{"send":{"asset":"eip155:42161/erc20:0xaf88d065e77c8cC2239327C5EDb3A432268e5831","amount":"10000000"},"receive":{"asset":"eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"}}'Each option’s display.receive is what the user gets at the current price and display.receiveMin the least a full fill pays. Its id is what you create the order from.
Run a full order
Section titled “Run a full order”You need:
- Your API key.
- Node.js 24 (24.22.1 or newer), which runs this TypeScript file directly.
- A wallet with 10 USDC and a little ETH for gas on Arbitrum. The script signs with that wallet’s private key. In your product, the user’s own wallet signs the same transactions.
Save the code below as quickstart.ts in a new directory, then run:
npm init -ynpm pkg set type=modulenpm install viem@2.57.7KHALANI_API_KEY=... PAYER_PRIVATE_KEY=0x... node quickstart.tsEach run creates a new order and moves real funds. Keep the private key out of source control. The script uses Arbitrum’s public RPC unless you set ARBITRUM_RPC_URL. It pays out to the same address on Base.
// Node.js 24 (24.22.1 or newer): KHALANI_API_KEY=... PAYER_PRIVATE_KEY=0x... node quickstart.tsimport { type Address, createPublicClient, createWalletClient, erc20Abi, formatUnits, type Hex, http } from "viem";import { privateKeyToAccount } from "viem/accounts";import { arbitrum } from "viem/chains";
const API = "https://api.hyperstream.dev/v3";const API_KEY = env("KHALANI_API_KEY");// In your product, the user's own wallet signs. Here a private key stands in for it.const account = privateKeyToAccount(env("PAYER_PRIVATE_KEY") as Hex);const transport = http(process.env["ARBITRUM_RPC_URL"]);const wallet = createWalletClient({ account, chain: arbitrum, transport });const arbitrumClient = createPublicClient({ chain: arbitrum, transport });
// Asset ids come from GET /v3/catalog.const USDC_ARBITRUM = "eip155:42161/erc20:0xaf88d065e77c8cC2239327C5EDb3A432268e5831";const USDC_BASE = "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
type Amount = { asset: { id: string; symbol: string; decimals: number }; amount: string };type Option = { id: string; requires: string[]; display: { receive: Amount; receiveMin: Amount; flatFee: Amount } };type Payload = { from: Address; to: Address; data: Hex; value: string; gasLimit: string };type Instruction = { format: string; payload?: Payload; allowance?: { spender: Address; amount: Amount } | null };type Leg = { amount: Amount | null; status: string };type ApiError = { code: string; message: string; recovery: string; retryAfterSeconds: number | null; requestId: string };type Order = { id: string; status: string; outcome: string | null; steps: { id: string; instruction: Instruction }[]; summary: { pollAfterSeconds: number | null; payout: Leg; refund: Leg };};
// 1. Quote (your backend): price 10 USDC on Arbitrum to USDC on Base. Amounts are base units.const quote = await api<{ options: Option[] }>("/quote", { send: { asset: USDC_ARBITRUM, amount: "10000000" }, receive: { asset: USDC_BASE },});// Use an option whose requirements you meet. This script can send EVM transactions, nothing else.const option = quote.options.find((o) => o.requires.every((r) => r === "format:evm_call"));if (!option) throw new Error("No option this script can fund");const { receive, receiveMin, flatFee } = option.display;console.log(`You receive about ${show(receive)}, at least ${show(receiveMin)}. Unfilled, you get back 10 USDC less ${show(flatFee)}.`);
// 2. Create the order (your backend): the option, unchanged, and the accounts. Save order.id.let order = await api<Order>("/orders", { option: option.id, accounts: { payer: { chain: "eip155:42161", address: account.address }, recipient: { chain: "eip155:8453", address: account.address }, },});console.log(`Order ${order.id}`);
// 3. Fund (the user's wallet): approve as the allowance requires now, then deposit, once.const deposit = order.steps.find((step) => step.id === "deposit")?.instruction;if (deposit?.format !== "evm_call" || !deposit.payload || !deposit.allowance) throw new Error("No EVM deposit step");if (deposit.payload.from.toLowerCase() !== account.address.toLowerCase()) throw new Error("Send the deposit from the payer");const { spender, amount } = deposit.allowance;const token = amount.asset.id.split(":").at(-1) as Address; // the erc20 contract in the asset idconst needed = BigInt(amount.amount);const allowance = await arbitrumClient.readContract({ address: token, abi: erc20Abi, functionName: "allowance", args: [account.address, spender],});if (allowance < needed) { // Some tokens refuse to change one nonzero allowance to another, so clear it first. if (allowance > 0n) await approve(token, spender, 0n); await approve(token, spender, needed);}const { to, data, value, gasLimit } = deposit.payload;await confirm(await wallet.sendTransaction({ to, data, value: BigInt(value), gas: BigInt(gasLimit) }));
// 4. Track (your backend): read the order again after pollAfterSeconds, until it is null.while (order.summary.pollAfterSeconds !== null) { await sleep(order.summary.pollAfterSeconds); order = await api<Order>(`/orders/${order.id}`); console.log(order.status);}const { payout, refund } = order.summary;console.log(`Outcome ${order.outcome}: payout ${leg(payout)}, refund ${leg(refund)}`);
async function approve(token: Address, spender: Address, value: bigint): Promise<void> { await confirm(await wallet.writeContract({ address: token, abi: erc20Abi, functionName: "approve", args: [spender, value] }));}
async function confirm(hash: Hex): Promise<void> { const receipt = await arbitrumClient.waitForTransactionReceipt({ hash }); if (receipt.status !== "success") throw new Error(`Transaction reverted: ${hash}`); console.log(`Confirmed ${hash}`);}
// Every request is safe to send again, so this retries the errors whose `recovery` says to, a few// times. Any other error stops the script: in your product, act on its `recovery`.async function api<T>(path: string, body?: unknown, attempt = 1): Promise<T> { const res = await fetch(`${API}${path}`, { method: body === undefined ? "GET" : "POST", headers: { "Content-Type": "application/json", "X-API-Key": API_KEY, "API-Revision": "0" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }); if (res.ok) return (await res.json()) as T; const error = (await res.json().catch(() => null)) as ApiError | null; if (error?.recovery === "retry" && attempt < 3) { await sleep(error.retryAfterSeconds ?? 2 ** attempt); return api<T>(path, body, attempt + 1); } throw new Error(`${res.status} ${path}: ${error?.code} (${error?.recovery}) ${error?.message} [${error?.requestId}]`);}
function sleep(seconds: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, seconds * 1000));}
function show({ asset, amount }: Amount): string { return `${formatUnits(BigInt(amount), asset.decimals)} ${asset.symbol}`;}
function leg({ amount, status }: Leg): string { return amount ? `${show(amount)} (${status})` : status;}
function env(name: string): string { const value = process.env[name]; if (!value) throw new Error(`Set ${name}`); return value;}What happens at each step
Section titled “What happens at each step”- Quote. The API asks solvers for a price and returns options. The script takes the one it can fund, which needs EVM transactions (
format:evm_call). If the size is out of range, the error gives the range that works. - Create. The option goes back unchanged, with the accounts: the payer, who sends the deposit, and the recipient on Base.
refundTodefaults to the payer. The answer is the order and its funding steps. Fund it right away, because it must be funded beforeterms.fundBy. - Fund. The script reads the current USDC allowance and approves only what is missing, then sends the deposit step’s transaction from the payer. Shortly after it confirms, the order goes live and solvers can fill it.
- Track. Solvers fill the order, and the user receives USDC on Base. Anything left unfilled at the deadline is refunded on Arbitrum, less the flat fee. The script stops when
summary.pollAfterSecondsturns null, and prints the two legs.
To check an order later, set ORDER_ID to the printed id and run:
curl -sS "https://api.hyperstream.dev/v3/orders/$ORDER_ID" -H "X-API-Key: $KHALANI_API_KEY"- Create orders: the accounts to bind and how to retry creation safely.
- Fund orders: allowance rules, and transfers on non-EVM chains.
- Track orders: what to show the user, and syncing many orders.
- Errors and retries: acting on each error’s
recovery. - Build with a coding agent: point your agent at these docs.