# Quickstart (v2)

> Quote, build, deposit and track one real order, end to end, in one TypeScript file.

> API v2 is deprecated. It stays supported, but new integrations should use the [Khalani API](/) (v3). See [Migrate to v3](/v2/migrate/).

This page takes one order from quote to delivery: 10 USDC on Arbitrum to USDC on Base.

:::caution[This uses real funds]
The full run calls the production API, and its deposit moves real tokens. Use small amounts while you integrate.
:::

## How it fits together

An integration has four steps. Your backend makes the API calls with your key, and the user's wallet sends the deposit.

| Step | What happens |
|---|---|
| 1.&nbsp;Quote | `GET /v2/quote` prices the trade and returns the build request. |
| 2.&nbsp;Build | `POST /v2/build` creates the order and returns the transactions to send. |
| 3.&nbsp;Deposit | The wallet sends `approveTxs`, then `depositTx`, on the source chain. |
| 4.&nbsp;Track | `GET /v2/orders/{orderId}` reports progress until `delivered` or `delivery_failed`. |

## Try a quote

A quote creates nothing and moves no funds. Set `KHALANI_API_KEY` to your key (see [API access](/v2/api-access/)) and run:

```bash
curl -sS "https://api.hyperstream.dev/v2/quote?fromChainId=42161&from=0xaf88d065e77c8cC2239327C5EDb3A432268e5831&toChainId=8453&to=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913&srcAmount=10000000" \
  -H "X-API-Key: $KHALANI_API_KEY"
```

`spend` is what the user sends and `receive.minAmount` is the least they get. `build` is the next request, already filled in.

## 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 and fees 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:

```bash
npm init -y
npm pkg set type=module
npm install viem@2.57.7
KHALANI_API_KEY=... DEPOSITOR_PRIVATE_KEY=0x... node quickstart.ts
```

Each 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`.

```ts title="quickstart.ts"
// Node.js 24 (24.22.1 or newer): KHALANI_API_KEY=... DEPOSITOR_PRIVATE_KEY=0x... node quickstart.ts
import { createPublicClient, createWalletClient, formatUnits, type Hex, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { arbitrum } from "viem/chains";

const API = "https://api.hyperstream.dev";
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("DEPOSITOR_PRIVATE_KEY") as Hex);
const transport = http(process.env["ARBITRUM_RPC_URL"]);
const wallet = createWalletClient({ account, chain: arbitrum, transport });
const chain = createPublicClient({ chain: arbitrum, transport });

type Token = { amount: string; symbol: string; decimals: number };
type Quote = { spend: Token; receive: Token & { minAmount: string }; build: Record<string, unknown> };
type Tx = { to: Hex; data: Hex; value: string };
type Built = { orderId: Hex; approveTxs?: Tx[]; depositTx: Tx & { gasLimit: Hex } };

// 1. Quote (your backend): price 10 USDC on Arbitrum to USDC on Base.
const params = new URLSearchParams({
	fromChainId: "42161",
	from: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", // USDC on Arbitrum
	toChainId: "8453",
	to: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC on Base
	srcAmount: "10000000", // amounts are base units: 10 USDC at 6 decimals
});
const quote = await api<Quote>(`/v2/quote?${params}`);
const { spend, receive } = quote;
console.log(`You send ${show(spend.amount, spend)} and receive at least ${show(receive.minAmount, receive)}`);

// 2. Build (your backend): the quote's build object, unchanged, plus the depositor.
const built = await api<Built>("/v2/build", {
	method: "POST",
	body: JSON.stringify({ ...quote.build, depositor: account.address }),
});
console.log(`Order ${built.orderId}`); // Save it: you track the order with it.

// 3. Deposit (the user's wallet): each approval in order, then the deposit, once.
for (const tx of built.approveTxs ?? []) await send(tx);
await send(built.depositTx, BigInt(built.depositTx.gasLimit));

// 4. Track (your backend): poll until delivery succeeds or fails.
let state = "";
while (state !== "delivered" && state !== "delivery_failed") {
	await new Promise((resolve) => setTimeout(resolve, 10_000));
	const order = await api<{ state: string }>(`/v2/orders/${built.orderId}`);
	state = order.state;
	console.log(state);
}

async function send(tx: Tx, gas?: bigint): Promise<void> {
	const hash = await wallet.sendTransaction({ to: tx.to, data: tx.data, value: BigInt(tx.value), gas });
	const receipt = await chain.waitForTransactionReceipt({ hash });
	if (receipt.status !== "success") throw new Error(`Transaction reverted: ${hash}`);
	console.log(`Confirmed ${hash}`);
}

async function api<T>(path: string, init: RequestInit = {}): Promise<T> {
	const res = await fetch(`${API}${path}`, {
		...init,
		headers: { "Content-Type": "application/json", "X-API-Key": API_KEY },
	});
	if (!res.ok) throw new Error(`${res.status} ${path}: ${await res.text()}`);
	return (await res.json()) as T;
}

function show(amount: string, token: Token): string {
	return `${formatUnits(BigInt(amount), token.decimals)} ${token.symbol}`;
}

function env(name: string): string {
	const value = process.env[name];
	if (!value) throw new Error(`Set ${name}`);
	return value;
}
```

## What happens at each step

1. **Quote.** The API asks solvers for a price. If they can't fill the amount, the error suggests one they can.
2. **Build.** Send the quote's `build` object back unchanged, plus the depositor's address. Its `terms` field is Khalani's signature on the quoted price, so a changed or expired quote is rejected. The response has the `orderId` and the transactions for the user's wallet. Deposit right away: the order's deadline starts at the build.
3. **Deposit.** The user's wallet approves the USDC, then sends the deposit. Shortly after it confirms, the order goes live and solvers can fill it.
4. **Track.** Solvers fill the order, and the user receives USDC on Base. Anything left unfilled is refunded on Arbitrum. `delivered` means the funds arrived. For `delivery_failed`, contact Khalani with the `orderId`.

To check an order later, set `ORDER_ID` to the printed `orderId` and run this. It needs no key:

```bash
curl -sS "https://api.hyperstream.dev/v2/orders/$ORDER_ID"
```

## Next

- [Build and deposit](/v2/guides/build-and-deposit/): wallet rules, recipients, and non-EVM sources.
- [Track orders](/v2/guides/track-orders/): read what was paid out and refunded.
- [Order lifecycle](/v2/guides/order-lifecycle/): every state an order passes through.
- [Errors and retries](/v2/guides/errors/): what to retry and what to fix.
