Khalani API: get started, guides and concepts for integrating the v3 API. Start here
# API access
> Get an API key, keep it on your backend, and know what it can and cannot do.
Khalani issues API keys during onboarding. There is no self-serve sign-up. Your account comes with:
* **Your commercial terms**: your commission in basis points and the wallet it is paid to.
* **Your order deadlines**: how long the user has to fund each order (`fundBy`), and solvers to fill it (`fillBy`). Ask Khalani to change them.
`GET /v3/catalog` returns your commission and Khalani’s fee in basis points. Every quote gives your order deadlines as `terms.fundWithinSeconds` and `terms.fillWithinSeconds`.
## Send the key from your backend
Send the key in the `X-API-Key` header, on every request:
```bash
curl -sS https://api.hyperstream.dev/v3/catalog -H "X-API-Key: $KHALANI_API_KEY"
```
Every v3 route needs the key, order reads included. Call the API from your backend only. Anyone who has your key can use it, so keep it out of browser code, app bundles and logs.
## What a key can do
One key is your whole integration. It can quote, create orders under your name, read and list every order you created along with its accounts, and relay cancels.
It can’t move funds. A deposit is a transaction or transfer the user sends from their own wallet, and a cancel needs the signature of the order’s `refundTo` account.
## Authentication errors
| Answer | Meaning |
| --------------------- | -------------------------------------------------------------------------------------------- |
| `401 UNAUTHENTICATED` | The `X-API-Key` header is missing. |
| `403 FORBIDDEN` | The key is unknown or inactive, or your account isn’t set up to trade. `message` says which. |
A `403` is always about your account. Its `recovery` is `contact_support`, and retrying won’t fix it. Contact Khalani through your onboarding channel with the `requestId`.
## Check that you are ready
`GET /v3/catalog` is the readiness check for your key. It keeps working during maintenance, subject to its [per-IP rate limit](/guides/rate-limits/). A `200` means your key works and your account is enabled; a `403` names the problem. Retry a `429` after `retryAfterSeconds`.
# Quickstart
> Quote, create, fund and track one real order, end to end, in one TypeScript file.
This page takes one order from quote to delivery: 10 USDC on Arbitrum to USDC on Base.
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 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
A quote creates nothing and moves no funds. Set `KHALANI_API_KEY` to your key (see [API access](/api-access/)) and run:
```bash
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
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:
```bash
npm init -y
npm pkg set type=module
npm install viem@2.57.7
KHALANI_API_KEY=... PAYER_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`. It pays out to the same address on Base.
quickstart.ts
```ts
// Node.js 24 (24.22.1 or newer): KHALANI_API_KEY=... PAYER_PRIVATE_KEY=0x... node quickstart.ts
import { 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("/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 id
const 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(`/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 {
await confirm(await wallet.writeContract({ address: token, abi: erc20Abi, functionName: "approve", args: [spender, value] }));
}
async function confirm(hash: Hex): Promise {
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(path: string, body?: unknown, attempt = 1): Promise {
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(path, body, attempt + 1);
}
throw new Error(`${res.status} ${path}: ${error?.code} (${error?.recovery}) ${error?.message} [${error?.requestId}]`);
}
function sleep(seconds: number): Promise {
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
1. **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.
2. **Create.** The option goes back unchanged, with the accounts: the payer, who sends the deposit, and the recipient on Base. `refundTo` defaults to the payer. The answer is the order and its funding steps. Fund it right away, because it must be funded before `terms.fundBy`.
3. **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.
4. **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.pollAfterSeconds` turns null, and prints the two legs.
To check an order later, set `ORDER_ID` to the printed id and run:
```bash
curl -sS "https://api.hyperstream.dev/v3/orders/$ORDER_ID" -H "X-API-Key: $KHALANI_API_KEY"
```
## Next
* [Create orders](/guides/create-orders/): the accounts to bind and how to retry creation safely.
* [Fund orders](/guides/fund-orders/): allowance rules, and transfers on non-EVM chains.
* [Track orders](/guides/track-orders/): what to show the user, and syncing many orders.
* [Errors and retries](/guides/errors/): acting on each error’s `recovery`.
* [Build with a coding agent](/agents/): point your agent at these docs.
# Build with a coding agent
> Point a coding agent at the raw docs and the OpenAPI spec, give it the rules, and test what it builds without moving funds.
These docs are written so that a coding agent, such as Claude Code, Codex or Cursor, can build an integration from them alone. What it needs is all plain text:
| File | What it holds |
| ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| [`/llms.txt`](/llms.txt) | The rules an integration must follow, and a link to every page’s Markdown copy. Start here. |
| [`/_llms-txt/khalani-api.txt`](/_llms-txt/khalani-api.txt) | Every get-started, guide and concept page for the API, in one file. |
| [`/openapi/v3.json`](/openapi/v3.json) | The OpenAPI 3.1 contract: every route, field, status and example. |
| `/.md` | Any page as Markdown: add `.md` to its path, such as [`/guides/fund-orders.md`](/guides/fund-orders.md). |
## Have it read the files raw
Tell your agent to download these files, for example with `curl`, rather than through a web-browsing or fetch tool. Many such tools summarize a page before the agent sees it, and a summary drops exact values from tables and code: an error code, a field name, an amount in base units. An agent working from a summary writes plausible code against an API that doesn’t exist.
## A prompt to start from
Paste this into your agent, and add your own stack and where the code goes:
```text
Build a backend integration with the Khalani API v3 (https://api.hyperstream.dev/v3).
Read these with curl, raw, before writing code. Don't use a summarizing fetch tool:
- https://docs.khalani.network/llms.txt (the integration rules: follow every one)
- https://docs.khalani.network/_llms-txt/khalani-api.txt (the guides)
- https://docs.khalani.network/openapi/v3.json (the contract; generate types from it)
Build: fetch the catalog, quote a trade, create an order from an option the
user's wallet can fund, return the funding steps to the frontend, poll the
order until summary.pollAfterSeconds is null, and relay a cancel signed by
refundTo. Read the API key from the KHALANI_API_KEY environment variable;
it must never reach the browser.
Handle every error by its `recovery` field, not its `code`. Treat open lists
as open. Send API-Revision: 0 on every request. Write tests that mock the
API and the wallet; never send a real deposit from a test.
```
## Generate types
Generate TypeScript types from the contract, so the compiler checks field names:
```bash
npx openapi-typescript@7.13.0 https://docs.khalani.network/openapi/v3.json -o khalani-v3.d.ts
```
Each named schema, such as `Order`, `QuoteResponse` and `ApiError`, becomes `components["schemas"]["Order"]`. Open lists come through as their known values or any string, so a value added later still type-checks.
## Test without moving funds
Most of an integration can be exercised for free:
* `GET /v3/catalog` and `POST /v3/quote` create nothing.
* `POST /v3/orders` creates an order, but nothing moves until the user funds it. An order you never fund expires at no cost. It does count against your [rate limits](/guides/rate-limits/).
* Errors are easy to provoke: a 1-unit quote returns `422 AMOUNT_TOO_SMALL`, and a second `POST /v3/orders` with the same option and other accounts returns `409 QUOTE_USED`.
Run one real order with a small amount, as the [quickstart](/quickstart/) does, before you go live. There is no test environment: every call reaches production.
## Review what it wrote
Check these by hand. They are where generated integrations go wrong:
* The API key is read on the backend only, and never logged.
* Asset ids come from the catalog, and amounts are base-unit strings converted with each asset’s `decimals`, never floats.
* The option `id` is sent to `POST /v3/orders` unchanged.
* An option whose `requires` holds a value the code doesn’t know is skipped.
* On an EVM source, the deposit is sent from the `payer`, after the [allowance check](/guides/fund-orders/#check-the-allowance-first), with the step’s `value` and `gasLimit`.
* On a non-EVM source, exactly the transfer step’s `amount` goes to its `to` address as given, once.
* Polling follows `summary.pollAfterSeconds` and stops when it is null. It doesn’t stop at `delivering`.
* Errors are handled by `recovery`. A request that failed with `retry` is resent unchanged.
* Response parsing ignores unknown fields.
# Cancel and refunds
> When orders refund, how a user cancels early, and how refundTo signs the cancel.
## When an order refunds
Settlement pays the filled part to `recipient` on the destination chain and refunds the rest of the deposit, less the flat fee, to `refundTo` on the source chain. A refund happens when:
* the order reaches `terms.fillBy` before it fills in full, or
* the user cancels it early while it trades.
In the first case the order settles on its own, and you don’t need to do anything. For a published order, the flat fee, `terms.flatFee`, is kept even if it never fills. On a partly filled order, the percentage fees apply to the filled part only. See [Fees and commission](/guides/fees/).
A deposit that arrives too late is handled apart from settlement: see [the two deadlines](/guides/order-lifecycle/#the-two-deadlines). If the order never published, Khalani returns the full deposit without charging the flat fee. Once recorded, the order shows the refund in `summary.refund` and moves to `delivering` and then `done`, or straight to `done` if delivery is already confirmed.
## Cancel early
An order can be cancelled while it is `trading`, including after a partial fill. The filled part is paid out and the rest refunded to `refundTo`, less `terms.flatFee`. The quote’s `actions.cancel` tells you in advance whether its order can be. When it can’t, show the user before they pay.
On the order, `actions.cancel.available` says whether a cancel is possible now. When it isn’t, `reason.code` says why:
| `reason.code` | Meaning |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `NOT_LIVE` | The order hasn’t published yet. Wait for `trading`. |
| `EARLY_CANCEL_DISABLED` | One of the assets doesn’t allow early cancel. Khalani decides this per asset. The order settles when it fills or reaches `fillBy`. |
| `CANCEL_PENDING` | A cancel is on its way. |
| `TRADING_ENDED` | Trading is over. |
The reason codes are an open list.
## Sign the cancel
When a cancel is possible, `actions.cancel.proof.message` is the text to sign, and `actions.cancel.signer` the account that signs it: `refundTo`. On the order, `signer` is an account, `{ chain, address }`. On a quote option it is the name of the role, `"refundTo"`, since no account is bound yet. The message is the same on every read:
```text
Cancel Khalani order ord_3f9a1c2b7d4e5f60718293a4b5c6d7e8
Chain: eip155:42161
Refund to: 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4
```
`refundTo` signs it with its wallet’s sign-message call, which shows the user the text. `proof.format` names the signing scheme, which depends on the source chain.
On an EVM source the format is `eip191_cancel_proof`: sign with `personal_sign` and send the 65-byte signature as 0x hex. A contract wallet’s EIP-1271 signature can be any length, even `0x` from a Safe that approved the message on chain.
```ts
// EVM, with viem
const signature = await walletClient.signMessage({ account: refundTo, message });
```
A non-EVM source uses its chain’s own scheme, listed in [Notes for specific chains](/guides/supported-assets/#notes-for-specific-chains). The format is an open list: a new chain can add one, and you can’t offer a cancel in a format you don’t know.
The message has no nonce or expiry. Sign it only when the user asks to cancel.
## Send the cancel
The signature comes from the user’s wallet, and your key relays it. A cancel has two halves: your frontend asks the wallet to sign, and your backend sends the signature.
```http
POST /v3/orders/{id}/actions
X-API-Key:
Content-Type: application/json
{ "kind": "cancel", "signature": "0x…" }
```
cancel.ts
```ts
// Cancel an order in two halves: refundTo's wallet signs in your frontend, and your backend relays the
// signature with its API key. The API key never reaches the browser.
import type { Address, Hex, WalletClient } from "viem";
const API = "https://api.hyperstream.dev/v3";
type CancelAction = {
available: boolean;
reason: { code: string; message: string } | null;
signer: { chain: string; address: string };
proof: { format: string; message: string } | null;
};
type Order = { id: string; status: string; actions: { cancel: CancelAction } };
// Backend: read the order and pass the frontend what to sign. The message is the same on every read.
export async function cancelRequest(orderId: string, apiKey: string): Promise<{ message: string; signer: Address }> {
const order = await call(`/orders/${orderId}`, apiKey);
const { available, reason, signer, proof } = order.actions.cancel;
if (!available || !proof) throw new Error(`Can't cancel now: ${reason?.code}`);
// This snippet signs on EVM. A non-EVM source uses its chain's format: see Notes for specific chains.
if (proof.format !== "eip191_cancel_proof") throw new Error(`Unsupported cancel format ${proof.format}`);
return { message: proof.message, signer: signer.address as Address };
}
// Frontend: refundTo signs the message with personal_sign, which shows the user the text.
export async function signCancel(wallet: WalletClient, request: { message: string; signer: Address }): Promise {
return wallet.signMessage({ account: request.signer, message: request.message });
}
// Backend: relay the signature. A 200 or a 202 is the order, with the cancel in `invocations`. Keep
// tracking it until it is over. Sending the same signature again is safe: it never cancels twice.
export async function relayCancel(orderId: string, signature: Hex, apiKey: string): Promise {
return call(`/orders/${orderId}/actions`, apiKey, { kind: "cancel", signature });
}
async function call(path: string, apiKey: string, body?: unknown): Promise {
const res = await fetch(`${API}${path}`, {
method: body === undefined ? "GET" : "POST",
headers: { "Content-Type": "application/json", "X-API-Key": apiKey, "API-Revision": "0" },
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
// Every error is an ApiError: its `recovery` says what to do next, a code you don't know included.
if (!res.ok) {
const error = (await res.json()) as { code: string; message: string; recovery: string };
throw new Error(`${res.status} ${error.code} (${error.recovery}): ${error.message}`);
}
return (await res.json()) as T;
}
```
| The order | Answer |
| -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| Trading, with no cancel yet | The cancel is relayed and recorded in `invocations`. `202` while the order still trades, or `200` if trading already ended. |
| Trading, with no cancel yet, and a signature that isn’t `refundTo`’s over this message | `400 INVALID_SIGNATURE`. |
| A cancel recorded already | `200`, with nothing relayed or checked again, however the order went since. |
| Stopped short of a full fill, with no cancel recorded | `409 ACTION_UNAVAILABLE`, `details.reason` `TRADING_ENDED`. |
| Filled in full, with no cancel recorded | `409 ACTION_UNAVAILABLE`, `details.reason` `ORDER_OVERTAKEN`. |
| Not published yet, or early cancel disabled | `409 ACTION_UNAVAILABLE`, with the reason in `details.reason`. |
| A dependency is briefly unavailable | `503 UPSTREAM_UNAVAILABLE`: the cancel may have gone through. |
| An unexpected server error | `500 INTERNAL`. Contact Khalani with the `requestId`. |
Treat `200` and `202` alike. Either is the order, with the cancel recorded in `invocations` as `pending`, then `accepted` once the order stops short of a full fill, or `rejected` with `ORDER_OVERTAKEN` if a full fill got there first. A cancel that races a fill is safe, because whichever lands first settles the order. Then the order settles as usual, so [keep tracking it](/guides/track-orders/) until `summary.pollAfterSeconds` is null.
**After a `503` or a lost answer, send the same signature again.** It never cancels twice. A `409 ACTION_UNAVAILABLE` with `details.reason` `TRADING_ENDED` then means the order stopped without a recorded cancel. Read it to see how it ended.
## Who can’t cancel
A cancel needs `refundTo`’s signature: from the key its address belongs to, or, for an EVM contract wallet, one its EIP-1271 `isValidSignature` accepts. These accounts can’t cancel, and their orders refund at `fillBy` if unfilled:
* an exchange deposit address, or any account whose user has no signing wallet,
* an EVM contract that doesn’t sign through EIP-1271,
* a non-EVM account whose address no longer signs with its own key, such as one whose signing permissions moved to other keys.
The API can’t tell them apart from an account that can sign, so `actions.cancel.available` can still be true for them. Bind a `refundTo` the user signs with (see [Create orders](/guides/create-orders/#choose-the-accounts)).
# Conventions
> Base URL, ids, amounts, nulls, open and closed lists, revisions and retries, shared by every endpoint.
## Base URL and requests
Every endpoint is under `https://api.hyperstream.dev/v3/`. These docs write paths as `/v3/…`. The [OpenAPI spec](/openapi/v3.json) lists its server as `https://api.hyperstream.dev`, with `/v3` in each path.
* Send your API key in the `X-API-Key` header on every request, from your backend. See [API access](/api-access/).
* Bodies are JSON. Send `Content-Type: application/json` on `POST` requests.
* **Requests are strict.** A body field or query parameter the route doesn’t take is a `400 VALIDATION_FAILED` that names it in `field`. So a misspelled role is rejected too.
* Every response carries an `x-request-id` header. Every error body repeats it as `requestId`. Log it, and quote it when you contact Khalani.
## Chains and assets
Chains and assets are named by [CAIP](https://chainagnostic.org/) ids, the same on every chain family:
| What | Format | Examples |
| ----------- | -------------------------------------------------- | ---------------------------------------------------------------------------------- |
| Chain | [CAIP-2](https://chainagnostic.org/CAIPs/caip-2) | `eip155:42161` (Arbitrum), `eip155:8453` (Base) |
| Asset | [CAIP-19](https://chainagnostic.org/CAIPs/caip-19) | `eip155:42161/erc20:0xaf88d065e77c8cC2239327C5EDb3A432268e5831` (USDC on Arbitrum) |
| Native coin | CAIP-19 `slip44` | `eip155:42161/slip44:60` (ETH on Arbitrum) |
Non-EVM chains use their own CAIP-2 namespaces, and new ones appear as chains are added. Treat ids as opaque strings.
* **Take asset ids from `GET /v3/catalog`.** Don’t build them yourself. The API matches the id it lists.
* To call an EVM token contract, read it from the id: the address after `erc20:`. A `slip44` id has no contract.
* The catalog lists a chain’s native coin where it trades. A relay fee names its chain’s native coin by its `slip44` id.
## Accounts
An `Account` is `{ chain, address }`:
```json
{ "chain": "eip155:42161", "address": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4" }
```
Give each address in the chain’s usual format. On EVM the API takes lowercase or checksummed hex and returns it checksummed. On other chains it returns the chain’s canonical form, so compare addresses as the API returns them.
The list filter `GET /v3/orders?account=…` takes a [CAIP-10](https://chainagnostic.org/CAIPs/caip-10) account id instead, the chain and address joined by `:`: `eip155:42161:0x5B38Da6a701c568545dCfcB03FcB875f56beddC4`.
## Amounts
An `AssetAmount` is an amount with its asset:
```json
{
"asset": { "id": "eip155:42161/erc20:0xaf88d065e77c8cC2239327C5EDb3A432268e5831", "chain": "eip155:42161", "symbol": "USDC", "decimals": 6 },
"amount": "100000000"
}
```
* `amount` is a decimal string of integer base units. With 6 decimals, `"100000000"` is 100 USDC.
* A request takes the base-unit string alone, next to the asset id: `{ "asset": "", "amount": "100000000" }`.
* Decimals differ between chains, even for the same token. Read `decimals` from the asset, never assume it.
* Rates, such as `terms.minRate`, are decimal strings in whole tokens: destination tokens per source token sent, fees included.
## Times and transactions
* Times are RFC 3339 strings in UTC, such as `2026-11-09T20:48:20Z`.
* A transaction is a `TransactionRef`, `{ chain, hash }`.
## Nulls and unknown fields
* Response fields are present unless marked optional. `null` means unknown, not yet, or not applicable.
* New fields can appear in any response. Ignore fields you don’t know, or a strict response parser breaks on the next release.
## Closed and open lists
Each enumerated field is either closed or open, and the OpenAPI spec says which.
**Closed lists** hold every value they will ever have: order `status` and `outcome`, step `id`, `type` and `status`, receipt observation, obligation `kind` and `status`, cancel request status, requirement `blocks`, and an error’s `recovery`. Branch on these freely. A value the spec marks reserved isn’t sent yet.
**Open lists** can gain values: error and problem codes, notice codes, change kinds, action kinds, formats, capabilities, roles, role constraints, actors and a leg’s `withoutTx`. Show an unknown value as is. Four unknowns change what you may do:
| Unknown value | What it means |
| ------------------------------------------ | -------------------------- |
| A capability in an option’s `requires` | You can’t use that option. |
| A `constraint` on one of an option’s roles | You can’t use that option. |
| A step’s `instruction.format` | You can’t run that step. |
| The cancel `format` | You can’t cancel early. |
## Repeating a request
Every request is safe to send again, because a repeat never acts twice:
* A quote option makes one order. Sending the same `POST /v3/orders` again returns that order.
* An order has one cancel signature. Sending the same cancel again changes nothing.
So a retry is always safe. Retry after a lost answer or a timeout, and after an error whose `recovery` is `retry`. After any other error, change something first, as its `recovery` says. See [Errors and retries](/guides/errors/).
## Revisions
Revisions let you take breaking changes on your own schedule. A change that could break an integration, such as a renamed field or a new required parameter, ships as a new revision of `/v3`. Your integration keeps the behaviour it was built against until you update your code and send the new revision.
**Send the `API-Revision` header on every request, set to the revision you built and tested against.** That is `0` for an integration built from these docs. Without the header, a request gets the revision that was current when your integration was set up. Sending it makes the pin explicit in your code.
Additive changes reach every revision, because they don’t break an integration that follows these docs: a new response field, a new value in an open list, a new chain or token in the catalog. An unknown revision is a `400 VALIDATION_FAILED` naming `API-Revision`. The `curl` examples in these docs leave the header out for brevity.
# Create orders
> Turn a quote option into an order, bind the right accounts, and retry creation safely.
`POST /v3/orders` turns one quote option into an order bound to the user’s accounts. The answer is the order, with the steps that fund it. Nothing happens on-chain until the user runs those steps.
## The request
```bash
curl -sS https://api.hyperstream.dev/v3/orders \
-H "X-API-Key: $KHALANI_API_KEY" -H "Content-Type: application/json" \
-d '{
"option": "opt_…",
"accounts": {
"payer": { "chain": "eip155:42161", "address": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4" },
"recipient": { "chain": "eip155:8453", "address": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4" }
}
}'
```
* `option` is an option’s `id` from `POST /v3/quote`, unchanged, sent before the quote’s `expiresAt`.
* `accounts` binds an account to each role the option lists in `roles`. Each account is `{ chain, address }`, on the chain the role names.
* Leave out a role you leave to its default, or send it as `null`. Do the same for a role the option doesn’t list. A `payer` on a non-EVM source is a `400 ACCOUNT_INVALID`.
The answer is `201` with the order. Every later call uses its `id` (`ord_…`), so store it before you hand anything to the wallet.
## Choose the accounts
| Role | Who it is | Rules |
| ----------- | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `payer` | Sends the deposit, on an EVM source. | Required on an EVM source, absent on a non-EVM source. The deposit must come from this account: a deposit from any other account can’t fund the order, and has to be recovered through Khalani. |
| `recipient` | Receives the payout, on the destination chain. | Required. |
| `refundTo` | Receives any refund, on the source chain, and signs cancels. | Defaults to `payer` on an EVM source. Required on a non-EVM source. |
Bind accounts the user controls:
* **When early cancellation is available, `refundTo` must be able to sign messages**: an account one key controls, or on EVM a contract wallet that signs through EIP-1271, such as a Safe. Never an exchange deposit address, a token contract, or any other contract that can’t sign. The refund would land there, and no one could cancel the order. The API can’t tell these apart from a wallet, so it accepts them.
* **Take addresses from the user’s connected wallet.** The addresses in these docs are placeholders or token contracts.
* **The recipient and `refundTo` must be able to receive.** The API checks this when it can, and answers `422 ACCOUNT_NOT_READY` or `422 ACCOUNT_NOT_ACTIVATED`. On EVM, a native coin is paid as a plain transfer, so a contract with no payable `receive` or `fallback` function can’t receive one. Some non-EVM chains have their own rules: see [Notes for specific chains](/guides/supported-assets/#notes-for-specific-chains).
* **A smart-contract wallet doesn’t have the same address on every chain.** Send `recipient` and `refundTo` explicitly, as accounts it controls on those chains.
## Retry creation safely
Sending the same request again never creates a second order, so retry it after a lost answer, a timeout, or an error whose `recovery` is `retry`:
* If creation finished, you get the order back with `200`, even after the quote expired.
* If the first request is still running and the funding window is open, you get `409 IDEMPOTENCY_IN_PROGRESS`. Send it again after `retryAfterSeconds`.
* If the first request reserved the option, a retry can finish creation with `201` while the original funding window is open.
* If the option is still available and the quote is valid, the retry can create the order as usual.
A repeat is the same request when it names the same option and the same accounts. Address formatting doesn’t matter, and neither does sending `refundTo` as its default or leaving it out.
The same option with other accounts is a `409 QUOTE_USED`, whether its creation finished or not. Request a new quote. To find an order the first request made, list with `GET /v3/orders?account=`.
## Errors
| Answer | Meaning | What to do |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `400 VALIDATION_FAILED` | The body doesn’t match the schema, such as a missing `recipient`. `field` names it. | Fix the request. |
| `400 ROLE_MISSING` | `payer` is missing on an EVM source, or `refundTo` on a non-EVM source. `field` names it. | Add the account. |
| `400 ACCOUNT_INVALID` | An account is on the wrong chain, its address isn’t valid there or is the zero address, or it names a role the option doesn’t have. `field` names it. | Fix the account. |
| `400 OPTION_INVALID` | The option wasn’t issued to your key, or was changed. | Request a new quote. |
| `400 UNSUPPORTED_PAIR` | The pair stopped trading since the quote. | Refresh the catalog and quote again. |
| `409 QUOTE_USED` | The option is reserved for other accounts. | Request a new quote. |
| `409 REQUOTE_REQUIRED` | Your fees or the order’s deadlines changed since the quote. | Request a new quote. |
| `409 IDEMPOTENCY_IN_PROGRESS` | The same request is still running. | Send it again after `retryAfterSeconds`. |
| `422 AMOUNT_TOO_SMALL` | With the fees now, the deposit would publish or pay nothing. Its `recovery` is `requote`. | Request a new quote, which gives the size range. |
| `410 QUOTE_EXPIRED` | The quote or the order’s funding window expired before creation finished. | Request a new quote. |
| `422 ACCOUNT_NOT_ACTIVATED` | The recipient or `refundTo` must be activated on its chain before it can be paid. | Activate it as the chain requires, then retry. See [Notes for specific chains](/guides/supported-assets/#notes-for-specific-chains). |
| `422 ACCOUNT_NOT_READY` | The recipient or `refundTo` can’t take the payment, such as an EVM contract that rejects a native coin. | Make the account ready as the chain requires, or use another account. |
| `503 UPSTREAM_UNAVAILABLE` | A dependency can’t be reached now. | Send the same request again after `retryAfterSeconds` or a backoff. |
| `503 MAINTENANCE` | Order creation is paused. | Retry after `retryAfterSeconds`. |
Every error says what to do in `recovery`, including codes not listed here. See [Errors and retries](/guides/errors/).
## Next
The order is `awaiting_funding`. [Fund it](/guides/fund-orders/) before `terms.fundBy`.
# Errors and retries
> The one error shape, how to act on its recovery, and every error code by status.
## The error shape
Every error, from every route, is an `ApiError`:
```json
{
"code": "QUOTE_USED",
"message": "This quote is reserved for other accounts; request a new quote",
"details": null,
"field": "option",
"recovery": "requote",
"retryAfterSeconds": null,
"requestId": "6f1d2c3b-4a5e-4f60-8718-293a4b5c6d7e"
}
```
| Field | Meaning |
| ------------------- | --------------------------------------------------------------------------------------- |
| `code` | What went wrong. An open list: new codes can appear. |
| `message` | For your logs. Don’t parse it: the wording can change. |
| `details` | Structured detail for some codes, otherwise null. |
| `field` | The request field at fault, such as `send.amount` or `accounts.payer`, or null. |
| `recovery` | What to do next. A closed list. |
| `retryAfterSeconds` | When to retry, on a `retry` error that knows. Otherwise null. |
| `requestId` | The request’s id, also in the `x-request-id` header. Quote it when you contact Khalani. |
## Act on `recovery`
Branch on `recovery`, not on `code`. It says what to do next for every error, a code you don’t know included:
| `recovery` | Do this |
| ----------------- | ------------------------------------------------------------------------------------------------ |
| `fix_request` | Change the request, as `field` and `details` say. Sending it unchanged fails again. |
| `requote` | Request a new quote, and create the order from it. |
| `retry` | Send the same request again, after `retryAfterSeconds` when it is set, or with a capped backoff. |
| `read_order` | Read the order to see where it stands. |
| `restart_sync` | Sync again with no cursor. |
| `contact_support` | Contact Khalani with the `requestId`. |
```ts
switch (error.recovery) {
case "retry": return retryAfter(error.retryAfterSeconds ?? backoff());
case "requote": return startOver();
case "read_order": return refreshOrder();
case "restart_sync": return syncFromScratch();
case "fix_request": // a bug in your integration, or bad user input in `field`
case "contact_support": return fail(error);
}
```
Every request is safe to repeat. See [Repeating a request](/guides/conventions/#repeating-a-request).
## `details`
`details` is null except on these codes:
| Code | `details` |
| --------------------------------------------- | ------------------------------------------------------------------------------------ |
| `VALIDATION_FAILED` from the request’s schema | `issues`: each bad field, with its `message`. |
| `AMOUNT_TOO_SMALL`, `AMOUNT_TOO_LARGE` | `minAmount` and `maxAmount`: the range that would quote, as `AssetAmount`s, or null. |
| `ACTION_UNAVAILABLE` | `reason`: why the action can’t run, such as `TRADING_ENDED`. |
Don’t depend on `details` for `VALIDATION_FAILED`: some validation errors name only `field`, and malformed JSON names neither.
## Codes by status
| HTTP | Codes |
| ---- | -------------------------------------------------------------------------------------------------------------------------------------- |
| 400 | `VALIDATION_FAILED`, `UNSUPPORTED_ASSET`, `UNSUPPORTED_PAIR`, `ACCOUNT_INVALID`, `ROLE_MISSING`, `OPTION_INVALID`, `INVALID_SIGNATURE` |
| 401 | `UNAUTHENTICATED`: no `X-API-Key` |
| 403 | `FORBIDDEN`: the key is unknown or inactive, or your terms can’t be used |
| 404 | `NOT_FOUND`: no such order of yours, or no such route |
| 409 | `QUOTE_USED`, `REQUOTE_REQUIRED`, `IDEMPOTENCY_IN_PROGRESS`, `ACTION_UNAVAILABLE` |
| 410 | `QUOTE_EXPIRED`, `CURSOR_EXPIRED` |
| 422 | `AMOUNT_TOO_SMALL`, `AMOUNT_TOO_LARGE`, `ACCOUNT_NOT_ACTIVATED`, `ACCOUNT_NOT_READY` |
| 429 | `RATE_LIMITED`: over a [rate limit](/guides/rate-limits/). Retry after `retryAfterSeconds`. |
| 500 | `INTERNAL`: sending the request again won’t fix it. Contact Khalani with the `requestId`. |
| 503 | `MAINTENANCE`, `UPSTREAM_UNAVAILABLE`, `PRICE_UNAVAILABLE`, `NO_CAPACITY`: retry after `retryAfterSeconds`, or with a backoff. |
## Every code
| Code | `recovery` | Meaning |
| -------------------------------------- | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `VALIDATION_FAILED` | `fix_request` | The request doesn’t match the schema, takes a field the route doesn’t, or names an unknown `API-Revision`. |
| `UNSUPPORTED_ASSET` | `fix_request` | The catalog doesn’t list the asset. Refresh it. |
| `UNSUPPORTED_PAIR` | `fix_request`, or `requote` at order creation | The two assets can’t trade, such as the same asset on both sides, or the pair stopped trading. |
| `ACCOUNT_INVALID` | `fix_request` | An account is on the wrong chain or isn’t a valid address there. |
| `ROLE_MISSING` | `fix_request` | A role the order needs has no account. |
| `OPTION_INVALID` | `requote` | The option wasn’t issued to your key, or was changed. |
| `INVALID_SIGNATURE` | `fix_request` | The cancel signature isn’t `refundTo`’s over the cancel message. |
| `UNAUTHENTICATED` | `fix_request` | No `X-API-Key` header. |
| `FORBIDDEN` | `contact_support` | The key is unknown or inactive, or your terms can’t be used. |
| `NOT_FOUND` | `fix_request` | No such order of yours, or no such route. |
| `QUOTE_USED` | `requote` | The option is reserved for other accounts. |
| `REQUOTE_REQUIRED` | `requote` | Your fees or the order’s deadlines changed since the quote. |
| `IDEMPOTENCY_IN_PROGRESS` | `retry` | The same request is still running. |
| `ACTION_UNAVAILABLE` | `read_order` | The action can’t run on the order now. `details.reason` says why. |
| `QUOTE_EXPIRED` | `requote` | The quote or the order’s funding window expired before creation finished. |
| `CURSOR_EXPIRED` | `restart_sync` | The sync cursor can’t be used any more. |
| `AMOUNT_TOO_SMALL`, `AMOUNT_TOO_LARGE` | `fix_request`, or `requote` at order creation | The size is out of range. `details` has the range. |
| `ACCOUNT_NOT_ACTIVATED` | `fix_request` | The account must be activated on its chain before it can be paid. |
| `ACCOUNT_NOT_READY` | `fix_request` | The account can’t take the payment, such as an EVM contract that rejects a native coin. |
| `RATE_LIMITED` | `retry` | Over a rate limit. |
| `INTERNAL` | `contact_support` | A server error. |
| `PRICE_UNAVAILABLE` | `retry` | Pricing failed for now. |
| `NO_CAPACITY` | `retry` | Nothing is fillable in this direction now. |
| `UPSTREAM_UNAVAILABLE` | `retry` | A chain or a dependent service can’t be reached now. |
| `MAINTENANCE` | `retry` | Quoting and order creation are paused. |
An error can name a `recovery` other than its code’s usual one. Follow the error’s.
## Getting help
Contact Khalani through your onboarding channel with the `requestId`, the order `id` if there is one, and the time of the call.
# Fees and commission
> The flat fee, Khalani's fee, your commission and the relay fee, and where each shows in the catalog, quotes and orders.
Fees come off the deposit before the order is published. Solvers then price what remains, so their rate contains none of these fees. What the quote shows already has every fee taken off: `display.receive` and `display.receiveMin` are what the user gets, and `terms.minRate` is `receiveMin` per token of the whole deposit.
## The parts
**A flat fee per order.** The source asset’s `depositFee` plus the destination asset’s `withdrawFee`, from `GET /v3/catalog`. Each is in its own asset’s base units, so the quote converts the withdraw fee into the source asset at a live price, and shows the total as `display.flatFee`. Once the order publishes, the flat fee is kept in full at any fill level, even when the order never fills. If the deposit couldn’t publish, its recovery refunds the full deposit without a flat fee.
**Khalani’s fee and your commission**, `operatorFeeBps` and `commissionBps` in `GET /v3/catalog`. Each is basis points of the deposit less the flat fee, on the part that fills. Your commission is paid to your commission wallet on the hub when the order settles.
**The relay fee**, on an EVM source only. The deposit transaction pays it in the chain’s gas token, on top of `send`, as the deposit step’s `value`. `display.relayFee` estimates it in the quote.
**Source-chain gas** for the approval and deposit transactions, paid by the user’s wallet as usual.
```text
flat fee = depositFee(source) + withdrawFee(destination, converted to source units)
published = (send − flat fee) × (1 − (operatorFeeBps + commissionBps) / 10 000)
receive = published × solvers' rate, rounded down
protocolFee = flat fee + Khalani's fee (your commission is not in it)
```
## Where fees appear
| Field | Where | What it holds |
| --------------------------------------------- | ------- | ------------------------------------------------------------------------------ |
| `assets[].depositFee`, `assets[].withdrawFee` | Catalog | Each asset’s flat fee as a source and as a destination, in its own base units. |
| `operatorFeeBps`, `commissionBps` | Catalog | Khalani’s fee and your commission, in basis points. |
| `display.flatFee` | Quote | The order’s flat fee, in the source asset, rounded up. |
| `display.protocolFee` | Quote | The flat fee plus Khalani’s fee, rounded up. Not your commission. |
| `display.relayFee` | Quote | The relay fee estimate, in the gas token. Null on a non-EVM source. |
| `terms.flatFee` | Order | The quote’s `display.flatFee`. |
| `charges.protocolFee` | Order | The protocol fee taken at settlement, rounded up. |
| `fills[].send` | Order | What each fill used of the deposit, its share of the percentage fees included. |
No endpoint returns the commission earned on a single order. It reaches your commission wallet as its own transfer on the hub, and you withdraw it on your own schedule.
Only Khalani can change your percentages and commission wallet, on your request. No API call can. After a change, an option quoted before it answers `409 REQUOTE_REQUIRED` at order creation: quote again.
# Fund orders
> Run an order's funding steps from the user's wallet before fundBy, as EVM contract calls or, on a non-EVM chain, one transfer.
An order is funded by its `steps`. `summary.actionNeeded` says what to ask of the user now:
```json
"actionNeeded": {
"kind": "send_transaction",
"executor": { "chain": "eip155:42161", "address": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4" },
"steps": ["approve", "deposit"]
}
```
* `kind` is `send_transaction`, where the `executor` sends EVM contract calls, or `send_transfer`, where anyone sends one token transfer.
* `steps` lists the ids of the steps to run, in order. A step’s `id` says what it does: `approve_reset`, `approve`, `deposit` or `transfer`.
* `actionNeeded` is null once the deposit shows or the order publishes, and once funding closes at `fundBy`.
**The deposit must be exactly the quoted amount, `terms.send`, sent before `terms.fundBy`.** Each step’s `instruction` says how. Don’t guess at a step whose `instruction.format` you don’t know. It can’t be run.
The source chain decides how the order is funded:
* On an EVM source, the `payer` sends contract calls: any approvals, then the deposit.
* On a non-EVM source, anyone sends one token transfer to a deposit address. Non-EVM chains accept nothing else.
## EVM source: send the contract calls
On an EVM source the steps are `transaction` steps for the payer to send, one after another and in this order:
1. `approve_reset`, when a leftover allowance must be cleared first,
2. `approve`, when the allowance is short,
3. `deposit`.
Each step’s `instruction` (format `evm_call`) holds the transaction in `payload`:
```json
{
"id": "deposit",
"type": "transaction",
"status": "pending",
"chain": "eip155:42161",
"actor": "payer",
"executor": { "chain": "eip155:42161", "address": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4" },
"instruction": {
"format": "evm_call",
"payload": {
"chainId": 42161,
"from": "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4",
"to": "0x1111111111111111111111111111111111111111",
"data": "0xf3125a1f…",
"value": "100000000000000",
"gasLimit": "250000"
},
"approval": null,
"allowance": {
"spender": "0x1111111111111111111111111111111111111111",
"amount": { "asset": { "id": "eip155:42161/erc20:0xaf88d065e77c8cC2239327C5EDb3A432268e5831", "chain": "eip155:42161", "symbol": "USDC", "decimals": 6 }, "amount": "100000000" }
}
}
}
```
The rules for the wallet:
* **Send each transaction from `payload.from`, the payer, on `payload.chainId`.** A deposit from any other account can’t fund the order: to get it back, contact Khalani with the transaction hash. Check the wallet’s connected account before you send.
* **Send `value` and `gasLimit` as given.** Both are decimal strings: `value` in wei, `gasLimit` in gas units. The deposit’s `value` is the relay fee when the order was created, plus the amount for a native coin. If the fee rises before the deposit lands, the deposit reverts, and you need a new quote and a new order.
* **Wait for each transaction to succeed before you send the next.** A receipt alone doesn’t rule out a revert, so check its status.
* **Send the deposit once.** A second deposit can’t fund anything, and getting it back means contacting Khalani with its transaction hash. For a native coin, no allowance stops a second one from landing.
An approval step’s `instruction.approval` names the `spender` and the `amount` it approves. The deposit’s `instruction.allowance` names the allowance it needs. A native coin needs no approvals: its deposit is the only step, and its `instruction.allowance` is null, so skip the check below.
### Check the allowance first
The approval steps reflect the payer’s allowance when the order was created. Another order on the same token can change it since. So before the approvals, and again if the deposit reverts, read the payer’s allowance of the token in `allowance.amount.asset` for `allowance.spender`, and go by it:
| Allowance now | Send |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| At least `allowance.amount.amount` | Only the deposit. |
| 0 | `approve(spender, allowance.amount.amount)`, then the deposit. |
| Anything between | `approve(spender, 0)`, then `approve(spender, allowance.amount.amount)`, then the deposit. Some tokens, such as USDT on Ethereum, revert an approval from one nonzero allowance to another. |
The `approve_reset` and `approve` steps are those approvals as the allowance stood at creation. Send them as given when the allowance hasn’t changed since. When it has, send your own `approve` calls on the token in `allowance.amount.asset`, and let the wallet estimate their gas. The [quickstart](/quickstart/) does this with viem, sending only its own approvals.
With an EIP-1193 wallet, forward the payload’s fields, converting the decimal strings to hex:
```ts
const { from, to, data, value, gasLimit } = step.instruction.payload;
await provider.request({
method: "eth_sendTransaction",
params: [{ from, to, data, value: `0x${BigInt(value).toString(16)}`, gas: `0x${BigInt(gasLimit).toString(16)}` }],
});
```
## Non-EVM source: send the transfer
On a non-EVM source there is one `transfer` step, and anyone may send it, including an exchange withdrawal that can follow every instruction returned. Its `instruction` (format `transfer`) names the deposit address and the amount:
```json
{
"format": "transfer",
"to": { "chain": "", "address": "" },
"amount": { "asset": { "id": "", "chain": "", "symbol": "USDT", "decimals": 6 }, "amount": "100000000" }
}
```
* **Send exactly `amount` of the asset to `to`, as given. Include `memo` unchanged when the instruction supplies one; otherwise use no memo.** A transfer of any other amount can’t fund the order, and Khalani returns it to the sender.
* **Send it once.** To get a second transfer back, contact Khalani with its transaction hash.
* **Check the option’s `requires` first.** Some chains ask more of the paying wallet. See [Notes for specific chains](/guides/supported-assets/#notes-for-specific-chains).
* A transfer that can’t fund the order closes the step and adds the `NOT_PUBLISHED` notice to `summary.notices`. Don’t send another. Khalani returns it.
## How the steps progress
| Step `status` | Meaning |
| ------------- | ----------------------------------------------------------------------------------------------------------------- |
| `pending` | Not seen yet. Run it if `summary.actionNeeded` lists it. |
| `completed` | The deposit showed, or the order published. |
| `closed` | Funding closed at `fundBy`, or a transfer couldn’t fund the order (`NOT_PUBLISHED`). Stop asking the user to pay. |
The steps stay `pending` until the order shows the deposit or publishes. Then every step completes together. This can take a few minutes after the transaction confirms, depending on the source chain.
**The API doesn’t see your transactions before that.** A step can still be listed after its transaction succeeds. Watch the transactions yourself, and send a step again only if its transaction failed.
## Deadlines
Send the deposit before `terms.fundBy`. At `fundBy`, funding closes on an order whose deposit hasn’t shown. Its steps show `closed` and `actionNeeded` turns null. A deposit sent in time can still show after that, and counts. Don’t let the user pay after `fundBy`: see [Order lifecycle](/guides/order-lifecycle/#the-two-deadlines) for what happens to a late deposit.
## Next
[Track the order](/guides/track-orders/) until `summary.pollAfterSeconds` is null.
# Order lifecycle
> The steps of an integration, an order's statuses and outcome, and its two deadlines.
## The steps
| Step | Call | Who |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |
| 1. Catalog | `GET /v3/catalog` lists the chains and assets you can trade, with their fees. | Your backend |
| 2. Quote | `POST /v3/quote` prices a trade and returns its options. | Your backend |
| 3. Create | `POST /v3/orders` turns one option into an order, with the steps that fund it. | Your backend |
| 4. Fund | The steps in `summary.actionNeeded`: EVM transactions from the payer, or one transfer from anyone. | The user’s wallet |
| 5. Track | `GET /v3/orders/{id}` until `summary.pollAfterSeconds` is null, or sync every order with `GET /v3/orders?sort=updatedAt`. | Your backend |
| 6. Cancel (optional) | `POST /v3/orders/{id}/actions` with a signed cancel, while the order trades. | The user signs; your backend relays |
```
sequenceDiagram
participant B as Your backend
participant A as Khalani API
participant W as User's wallet
B->>A: POST /v3/quote
A-->>B: options
B->>A: POST /v3/orders (option, accounts)
A-->>B: order, with its funding steps
B->>W: the steps in summary.actionNeeded
W->>W: approve and deposit (EVM), or transfer
loop every summary.pollAfterSeconds
B->>A: GET /v3/orders/{id}
A-->>B: status, outcome, summary
end
```
## Status
`status` is a closed list. Orders can skip statuses. An `expired` order can later become `delivering` or `done` when its deposit is refunded.
| `status` | Meaning |
| ------------------ | --------------------------------------------------------------------------------------------------------- |
| `awaiting_funding` | Created. Waiting for the deposit. |
| `confirming` | Khalani has seen the deposit, and the order is about to go live. |
| `trading` | Published: solvers can fill it, and it can be cancelled early. |
| `settling` | Trading ended: it filled, was cancelled, or reached `fillBy`. The payout and refund are being worked out. |
| `delivering` | Settled. The payout and the refund are on their way. |
| `done` | Delivered. Nothing is left to happen. |
| `expired` | It didn’t publish by `fillBy`. Trading is over; a deposit refund can still follow. |
To know whether the user has been paid, read `summary`, as [Track orders](/guides/track-orders/) explains.
## Outcome
`outcome` says how trading ended. It is null until `settling`.
| `outcome` | Meaning | What the user gets |
| --------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `full` | Filled in full. | The payout. |
| `partial` | Cancelled, or reached `fillBy`, after at least one fill. | A payout for the filled part, and a refund of the rest less the flat fee. |
| `none` | Cancelled, or reached `fillBy`, with no fill. | A refund of the deposit less the flat fee if it published, or the full deposit if it couldn’t publish. |
## The two deadlines
Every order has two deadlines, set by your account. The quote gives them as durations, `terms.fundWithinSeconds` and `terms.fillWithinSeconds`, and the order as times counted from its creation, `terms.fundBy` and `terms.fillBy`. Ask Khalani to change them.
**`fundBy` is when to stop asking the user to pay.** Show it on your payment screen. Once it passes without a deposit:
* every step shows `closed`,
* `summary.actionNeeded` turns null, and
* the history records a `funding_closed` change.
Hide the payment action then. If the user still wants to trade, quote again and create a new order. A deposit sent before `fundBy` that shows up a little later still counts.
**`fillBy` caps how long the user waits.** Solvers can fill the order until then. At `fillBy`, an order that hasn’t filled in full settles on its own: the user gets the filled part, and the rest of the deposit back, less the flat fee. You don’t need to do anything. So tell the user they will have their tokens, or their refund, by `fillBy` at the latest.
`fundBy` comes well before `fillBy`, so a deposit sent in time can still trade. A deposit that arrives after `fillBy` can’t fund the order: the order ends `expired`, shows the `NOT_PUBLISHED` notice, and the user waits longer to get the deposit back. Once Khalani records its full refund, the notice goes and the order moves to `delivering` and then `done`, or straight to `done` if delivery is already confirmed.
## Settlement
An order settles once, when the first of these happens:
* it fills in full,
* it reaches `fillBy`, or
* a cancel is accepted.
Settlement pays the filled part to `recipient` on the destination chain, at no less than `terms.minRate`. It refunds the unfilled part of the deposit, less the flat fee, to `refundTo` on the source chain. An order can fill in parts, from more than one fill.
## When to stop
Once `summary.pollAfterSeconds` is null, stop routine polling of that order: it is `done` or `expired`. Keep syncing with `sort=updatedAt` for later deposit and refund updates to expired orders. An order nobody funds ends `expired` shortly after `fillBy`. If a deposit for it arrives later, the order stays `expired`, gains the `NOT_PUBLISHED` notice, and sync lists it again. Sync lists it again when Khalani returns that deposit, as the order moves to `delivering` and then `done`, or straight to `done` if delivery is already confirmed. See [Track orders](/guides/track-orders/).
# Quotes and pricing
> Price a trade, pick an option, read what it commits to and what to show the user, and handle size limits.
`POST /v3/quote` prices one trade without creating anything. Use it for your confirmation screen: “you send X, you receive Y”. It is a required step, because only a quote option can create an order.
## Request a quote
```bash
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" }
}'
```
* `send.amount` is what the user sends, fees included, in base units. Quotes are exact-input: the API prices this amount.
* `receive.asset` is what the user gets. You don’t send a receive amount. The quote tells you what the user gets.
* Take both asset ids from `GET /v3/catalog`. Any listed asset trades against any other, on the same chain or across chains.
* Khalani sets the slippage. You don’t send one.
## The answer
The answer holds `expiresAt` and a list of `options`, each priced at current market rates. A quote doesn’t hold a price or reserve liquidity, so quote again when the user returns to a stale screen, and expect two quotes seconds apart to differ.
Quoting 10 USDC from Arbitrum to USDC on Base returns one option like this one. The amounts are illustrative, and the long `id` is shortened:
```json
{
"expiresAt": "2026-11-10T02:50:21Z",
"options": [
{
"id": "opt_eyJ2IjoxLCJz…",
"requires": ["format:evm_call"],
"roles": [
{"role": "payer", "chain": "eip155:42161", "required": true, "defaultFrom": null, "constraint": "sender_bound"},
{"role": "recipient", "chain": "eip155:8453", "required": true, "defaultFrom": null, "constraint": null},
{"role": "refundTo", "chain": "eip155:42161", "required": false, "defaultFrom": "payer", "constraint": null}
],
"terms": {
"send": {"asset": {"id": "eip155:42161/erc20:0xaf88d065e77c8cC2239327C5EDb3A432268e5831", "chain": "eip155:42161", "symbol": "USDC", "decimals": 6}, "amount": "10000000"},
"receiveAsset": {"id": "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "chain": "eip155:8453", "symbol": "USDC", "decimals": 6},
"minRate": "0.9966671",
"slippageBps": 3,
"fundWithinSeconds": 2400,
"fillWithinSeconds": 3600
},
"display": {
"send": {"asset": {"id": "eip155:42161/erc20:0xaf88d065e77c8cC2239327C5EDb3A432268e5831", "chain": "eip155:42161", "symbol": "USDC", "decimals": 6}, "amount": "10000000"},
"receive": {"asset": {"id": "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "chain": "eip155:8453", "symbol": "USDC", "decimals": 6}, "amount": "9969662"},
"receiveMin": {"asset": {"id": "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "chain": "eip155:8453", "symbol": "USDC", "decimals": 6}, "amount": "9966671"},
"protocolFee": {"asset": {"id": "eip155:42161/erc20:0xaf88d065e77c8cC2239327C5EDb3A432268e5831", "chain": "eip155:42161", "symbol": "USDC", "decimals": 6}, "amount": "0"},
"flatFee": {"asset": {"id": "eip155:42161/erc20:0xaf88d065e77c8cC2239327C5EDb3A432268e5831", "chain": "eip155:42161", "symbol": "USDC", "decimals": 6}, "amount": "0"},
"relayFee": {"asset": {"id": "eip155:42161/slip44:60", "chain": "eip155:42161", "symbol": "ETH", "decimals": 18}, "amount": "0"}
},
"actions": {
"cancel": {
"available": true,
"reason": null,
"signer": "refundTo",
"format": "eip191_cancel_proof"
}
}
}
]
}
```
The [reference](/api/operations/quote/) has the full shape. Each part of an option follows.
### `id`
Pass it to `POST /v3/orders` unchanged, before `expiresAt`. An option makes one order. Its format can change, so don’t parse it.
Read `expiresAt` on every quote. The lifetime varies by pair, and is shorter on pairs whose price moves faster.
### `requires`
What you need to be able to do to fund the order. It is an open list: **skip an option that requires something you don’t know or can’t do.**
| Value | Meaning |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `format:evm_call` | Send contract calls from the payer’s wallet. Every EVM source. |
| `format:transfer` | Send a plain token transfer, from any wallet. Every non-EVM source. |
| `solana:associated_token_account` | Derive the returned wallet owner’s ATA for the asset’s mint under the standard SPL Token program, create it idempotently if absent (sender pays rent), and send one exact payment. No memo, split payment or top-up. See [Solana funding](/guides/supported-assets/#solana). |
For example, Solana USDT uses `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB` (six decimals). Its transfer goes to the owner’s ATA for that mint; check the catalog for availability.
A non-EVM chain can add a capability of its own. [Notes for specific chains](/guides/supported-assets/#notes-for-specific-chains) lists them.
### `roles`
The accounts the order needs. You bind them when you create the order. Each role has its `chain`, whether it is `required`, the role it defaults to (`defaultFrom`), and a `constraint`. `sender_bound` means the deposit must come from this account. An unknown `constraint` means you can’t use the option.
| Source | `payer` | `recipient` | `refundTo` |
| ------- | --------------------------------------------------------------- | ----------------------------------- | --------------------------------------------- |
| EVM | Required. Sends the deposit, which must come from this account. | Required, on the destination chain. | Optional, defaults to `payer`. Signs cancels. |
| Non-EVM | None: anyone may send the transfer. | Required, on the destination chain. | Required. Signs cancels. |
Roles are an open list, so bind the roles each option lists. The table shows the usual ones.
### `terms`
What the order commits to:
* `minRate`: the least a full fill pays per token of `send`, the whole deposit with fees still in it, in destination tokens. It equals `display.receiveMin` divided by `display.send`. Don’t take fees off `send` before you apply it.
* `slippageBps`: the slippage Khalani applied to reach `minRate`.
* `fundWithinSeconds` and `fillWithinSeconds`: the seconds from creation to the order’s two deadlines, `fundBy` and `fillBy`. See [Order lifecycle](/guides/order-lifecycle/#the-two-deadlines).
### `display`
What to show the user:
| Field | Show it as |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `send` | What the user pays, fees included. |
| `receive` | What the user gets at the current price. Show this one. |
| `receiveMin` | The least a full fill pays. It holds as long as your fees aren’t changed before the order publishes. |
| `protocolFee` | The flat fee plus Khalani’s fee, rounded up. Your commission isn’t in it. |
| `flatFee` | The part kept whatever fills, rounded up. An order that doesn’t fill refunds `send` less `flatFee`. Show the user that refund before they pay. |
| `relayFee` | On an EVM source, an estimate of what the deposit pays on top of `send`, in the chain’s gas token. Null on non-EVM sources. |
Source-chain gas is also on top of `send`. See [Fees and commission](/guides/fees/).
### `actions.cancel`
Whether the order can be cancelled early once it trades, the role that signs the cancel (`signer`), and the signature `format` it will need. Early cancel is off unless both assets allow it. An unknown `format` means you can’t cancel early. Tell the user before they pay when they can’t. See [Cancel and refunds](/guides/cancel-and-refunds/).
## What a quote guarantees
**A `200` means the size is fillable right now.** The API refuses to price a size it couldn’t fill.
**A full fill pays at least `receiveMin`.** The order publishes at `terms.minRate`, and the hub enforces that rate on every fill.
**The rate is guaranteed, the total is not.** An order can fill in part. If an order for 1,000 fills 600 and is cancelled, the user receives the 600’s worth at no less than `minRate`, and the rest of the deposit back less the flat fee. When a shortfall is unacceptable, such as paying an invoice of a fixed amount, read the payout once the order settles and top up.
## Size limits
| Answer | Meaning | What to do |
| ---------------------- | --------------------------------------------------------------------------------------------------- | ----------------------------- |
| `422 AMOUNT_TOO_SMALL` | Below what would fill. `details.minAmount` and `details.maxAmount` give the range that would quote. | Quote again within the range. |
| `422 AMOUNT_TOO_LARGE` | Above what would fill. Same `details`. | Quote again within the range. |
`details.minAmount` and `details.maxAmount` are `AssetAmount` objects in the source asset, or null. Send their `amount` back as `send.amount`.
At or below the flat fee, `details.minAmount` only clears the fee and `details.maxAmount` is null. Quote again at `minAmount` to learn the full range. The range can move between calls, so a quote at its edge can still fail. If it does, follow the new figures.
For example, quoting 0.001 USDC from Arbitrum to USDT on Ethereum can return:
```json
{
"code": "AMOUNT_TOO_SMALL",
"message": "Deposit is at or below the flat fee, so nothing would be published",
"details": {
"minAmount": { "asset": { "id": "eip155:42161/erc20:0xaf88d065e77c8cC2239327C5EDb3A432268e5831", "chain": "eip155:42161", "symbol": "USDC", "decimals": 6 }, "amount": "99893" },
"maxAmount": null
},
"field": "send.amount",
"recovery": "fix_request",
"retryAfterSeconds": null,
"requestId": "5e43f255-5a23-4c66-a864-2ecb8735142a"
}
```
The catalog doesn’t list a minimum, because it depends on solvers’ current costs. Only a quote tells you.
## Other refusals
| Answer | What to do |
| ----------------------------------------------- | ---------------------------------------------------------------------------------- |
| `400 UNSUPPORTED_ASSET`, `400 UNSUPPORTED_PAIR` | The asset or pair doesn’t trade. Refresh the catalog. |
| `400 VALIDATION_FAILED` | Fix the field named in `field`. |
| `503 PRICE_UNAVAILABLE` | Pricing failed for now. Retry after `retryAfterSeconds`, or with a backoff. |
| `503 NO_CAPACITY` | Nothing is fillable in this direction now. Retry later, without changing the size. |
| `503 MAINTENANCE` | Quoting and order creation are paused. Retry after `retryAfterSeconds`. |
Every error carries a `recovery` that tells you what to do, whatever the code. See [Errors and retries](/guides/errors/).
# Rate limits and reliability
> Rate limits, maintenance windows, what an outage can and cannot affect, and how to get help.
## Rate limits
Requests per minute:
| Routes | Per IP | Per integrator |
| ----------------------------------------------------------------------------------- | ------ | -------------- |
| `GET /v3/catalog` | 600 | |
| `POST /v3/quote` | 600 | 120 |
| `POST /v3/orders` | 300 | 60 |
| `GET /v3/orders`, `GET /v3/orders/{id}` and `GET /v3/orders/{id}/changes`, together | 600 | |
| `POST /v3/orders/{id}/actions` | 600 | |
Over a limit, a route answers `429 RATE_LIMITED` with `retryAfterSeconds`. Wait that long before you retry.
* The per-IP limit is checked before your key, so other traffic from a shared egress IP can use up your allowance.
* IPv6 clients are counted per /64 network, not per address, so every host in a /64 shares one per-IP allowance.
* Requests from a Cloudflare Worker in another zone are counted per calling zone (the `CF-Worker` header), not by the IP that all such Workers share.
* Limits are counted per edge location and are approximate.
Reading each open order every `summary.pollAfterSeconds` reaches the 600-a-minute read limit at about 100 to 150 orders in progress, since it is every 10 to 30 seconds per order. Past a few dozen, [sync](/guides/track-orders/#list-and-sync) with `GET /v3/orders?sort=updatedAt` instead. One call returns up to 50 changed orders.
## Maintenance
When maintenance pauses Khalani API order admission, `POST /v3/quote` and `POST /v3/orders` answer `503 MAINTENANCE` with `retryAfterSeconds` and the `Retry-After` header:
```json
{ "code": "MAINTENANCE", "message": "Order creation is paused for maintenance", "details": null, "field": null,
"recovery": "retry", "retryAfterSeconds": 300, "requestId": "…" }
```
The two routes pause together, so a quote never offers an order that creation would refuse. The catalog, order reads, sync and cancels keep working, and orders already created keep settling. `GET /v3/catalog` works during maintenance, so use it as your [readiness check](/api-access/#check-that-you-are-ready).
## What an outage can affect
An API outage delays quotes, order creation, order reads and settlement. It can’t change an order’s terms, because the rate, the accounts and the deadlines are signed when the order is created, and the contracts enforce them when it publishes and settles. A filled unit always settles at no less than `terms.minRate`.
If the API is unavailable when an order reaches `fillBy`, settlement runs once service resumes. Meanwhile the funds stay in the hub contract under the order’s signed terms. If an order hasn’t settled after service is back, contact Khalani with its `id`.
## Getting help
Contact Khalani through your onboarding channel. Include the order `id` if there is one, the `requestId` of the failing response, and the time of the call. Contact Khalani in particular when:
* an error’s `recovery` is `contact_support`,
* an order shows a notice in `summary.notices` for longer than you’d expect, or
* an order stays `confirming` for more than a few minutes.
# Supported chains and tokens
> Read the live catalog of chains and tokens, and how EVM and non-EVM chains differ for an integration.
`GET /v3/catalog` is the list of chains and tokens you can trade. Khalani adds chains and tokens continuously, both EVM and non-EVM, so read the list from the catalog. Any listed asset trades against any other, across chains or on the same chain. Pairs aren’t listed separately.
```bash
curl -sS https://api.hyperstream.dev/v3/catalog -H "X-API-Key: $KHALANI_API_KEY" | jq '.assets[] | {id, symbol, decimals}'
```
The answer holds `chains` (each a CAIP-2 `id` and a `name`), `assets`, and your `operatorFeeBps` and `commissionBps`. Each asset is `{ id, chain, symbol, decimals, depositFee, withdrawFee }`. [Fees and commission](/guides/fees/) explains the two fees.
## Reading the catalog
* **Take asset ids from the catalog.** Fetch it at startup and refresh it every few minutes. An asset can be added or removed at any time, and a quote with an id the catalog stopped listing answers `400 UNSUPPORTED_ASSET` or `400 UNSUPPORTED_PAIR`.
* **Expect new chains.** A chain you haven’t seen before can appear in the catalog. Offer its assets only once your integration can fund and receive on that chain. An option whose `requires` you don’t know tells you that you can’t (see [Quotes and pricing](/guides/quotes/#requires)).
* **Decimals differ by chain**, even for the same token. Read `decimals` from the asset.
* The catalog is the same for every integrator, except your own `operatorFeeBps` and `commissionBps`.
* The minimum trade size isn’t in the catalog, because it depends on solvers’ current costs. A quote below it answers `422 AMOUNT_TOO_SMALL` with the range that works.
## EVM and non-EVM chains
The API works the same way on every chain: the same quote, order and tracking calls. What differs is how the user funds an order on the source chain:
| | EVM source | Non-EVM source |
| ----------------- | ---------------------------------------------------------------- | ---------------------------------------------------------- |
| Funding | Contract calls the payer sends: any approvals, then the deposit. | One token transfer, from any wallet, to a deposit address. |
| Option `requires` | `format:evm_call` | `format:transfer`, plus any capability the chain needs. |
| `payer` | Required: the deposit must come from it. | None. |
| `refundTo` | Optional, defaults to `payer`. | Required. |
| Relay fee | Paid in the deposit’s `value`. | None. |
Non-EVM chains accept transfers only. See [Fund orders](/guides/fund-orders/#non-evm-source-send-the-transfer).
On the destination side, the recipient receives the token on any chain. Some chains limit which accounts can receive, as the notes below say.
## Notes for specific chains
Most integrations need none of these. Read the section for a chain only when you offer it.
### 0G USDC.e
Use chain `eip155:16661` and asset `eip155:16661/erc20:0x1f3AA82227281cA364bFb3d253B0f1af1Da6473E`, with 6 decimals, when the catalog lists it. USDC.e is USDC bridged through Chainlink CCIP and backed by USDC locked on Ethereum. It is not Circle-issued USDC on 0G.
Delivery into 0G typically takes about 20 minutes and needs at least 30 minutes left before the order’s deadline. Fund the order promptly so a solver has time to deliver. Any unfilled remainder expires at `fillBy` and is returned through [normal settlement](/guides/order-lifecycle/). Orders out of 0G are fast.
These illustrative `POST /v3/quote` requests trade in each direction. Take asset ids from the live catalog, and use an amount within the quote’s supported range. A small amount can answer `422 AMOUNT_TOO_SMALL`.
Base USDC to 0G USDC.e:
```json
{
"send": {
"asset": "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"amount": "5000000"
},
"receive": {
"asset": "eip155:16661/erc20:0x1f3AA82227281cA364bFb3d253B0f1af1Da6473E"
}
}
```
0G USDC.e to Base USDC:
```json
{
"send": {
"asset": "eip155:16661/erc20:0x1f3AA82227281cA364bFb3d253B0f1af1Da6473E",
"amount": "5000000"
},
"receive": {
"asset": "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
}
}
```
### TRON
* Give addresses as Base58 (`T…`) or hex (`41…`). The API returns Base58.
* A recipient or `refundTo` must be activated: it has received TRX or a token before. Otherwise order creation answers `422 ACCOUNT_NOT_ACTIVATED`.
* Cancels use the format `tip191_cancel_proof`: sign with TronWeb’s `signMessageV2` and send the 65-byte signature as 0x hex.
```ts
const signature = await tronWeb.trx.signMessageV2(message);
```
### Stellar
* Give accounts as `G…` or muxed `M…` addresses. A muxed address and its `G…` account are different accounts.
* A recipient or `refundTo` must be able to take the asset: funded, with an authorized trustline that has room for the amount, and with no required memo. Otherwise order creation answers `422 ACCOUNT_NOT_READY`.
* The deposit address is a muxed `M…` address, and options carry `stellar:muxed_destination` in `requires`. Pay it exactly as given, with no memo: a payment to its `G…` account isn’t credited. Offer the option only if the paying wallet can pay a muxed address.
* Stellar assets have 7 decimals, so the same token can have different decimals here than on EVM.
* Cancels use the format `sep53_cancel_proof`: sign with a [SEP-53](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0053.md) call, such as Freighter’s `signMessage`, and send the 64-byte signature as base64 or 0x hex.
```ts
// @stellar/freighter-api v4 or later, which returns base64
const { signedMessage: signature } = await signMessage(message, { address: refundTo });
```
### Solana
* Use the mainnet chain id `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp` and USDC asset id `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`. USDT uses `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB`. Both have six decimals; use the catalog to check availability. Preserve the case of mints, wallet addresses and transaction signatures. Native SOL cannot fund these orders.
* Give `recipient` and `refundTo` as canonical base58 wallet-owner addresses, never token accounts. Order creation checks the wallet and its associated token account (ATA) for the asset’s mint; an invalid or frozen account is refused, and a failed account check can be retried.
* For a Solana source, supply a Solana `refundTo` and the destination’s `recipient`. Omit `payer`: anyone can fund the order. A Solana destination needs a Solana `recipient`; use the source’s usual payer and refund roles.
* A Solana source requires `format:transfer` and `solana:associated_token_account`. The step’s `to.address` is a one-time wallet owner. Derive the owner’s ATA for the asset’s mint under the standard SPL Token program and create it idempotently if absent. The sender pays SOL transaction fees and ATA rent. Send exactly the returned amount to the ATA, with no memo, split payment or top-up. Sending tokens to the owner as if it were a token account does not fund the order.
* Use `terms.fundBy` and `terms.fillBy` as returned. A Solana source reserves additional time to detect the deposit before trading, so its `fillBy` is later than an EVM order’s with the same `fundBy`.
* Send one payment by `fundBy`. The step can remain pending for up to a minute while Khalani observes it: do not pay again. Wrong amounts and extra payments can quarantine funds for manual recovery. A payment can finalize too late even when sent before the deadline; follow the order’s notices. Recovery has the same limits as other non-EVM sources and is separate from the trade’s payout or refund.
* An order with Solana on either side cannot be cancelled early. Wait for settlement or expiry. Solana transaction references contain native base58 signatures, never hashes of those signatures.
These quote examples use one USDC (one million base units). USDT works the same way with its own mint: replace the Solana asset id with the USDT id above. Use the returned option id unchanged in `POST /v3/orders`. Read live ids and decimals from the catalog.
```json
{
"send": {"asset": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "amount": "1000000"},
"receive": {"asset": "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"}
}
```
For EVM to Solana, reverse the assets; the EVM payer sends the returned calls in order.
```json
{
"send": {"asset": "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "amount": "1000000"},
"receive": {"asset": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}
}
```
### Zcash
* Take the ZEC asset id from the catalog. ZEC amounts use eight decimals. A ZEC order exchanges native ZEC with USDC.
* For a ZEC source, omit `payer` and supply a Zcash `refundTo`. The recipient is on the destination chain. The Zcash refund address must be mainnet transparent. Addresses are validated for their network, encoding and checksum.
* A transparent deposit sends the exact amount in one output to the returned address, with no memo or OP_RETURN.
* Use `terms.fundBy` and `terms.fillBy` as returned. A ZEC source reserves additional time for confirmations before trading; do not derive deadlines from another chain’s orders. Do not split, top up or reuse a deposit instruction.
* A ZEC destination must be mainnet transparent. Unified and Sapling addresses are rejected for both payouts and refunds. An order with ZEC on either side cannot be cancelled early. Track its payout and refund until completed; a settlement transaction alone does not prove delivery.
# Track orders
> Poll an order, show the user what was paid and refunded, keep every order in sync, and read an order's history.
## Read one order
`GET /v3/orders/{id}` takes the order’s `ord_` id and needs your key. Track orders from your backend.
```bash
curl -sS "https://api.hyperstream.dev/v3/orders/$ORDER_ID" -H "X-API-Key: $KHALANI_API_KEY"
```
**Poll it after `summary.pollAfterSeconds`, until that is null.** Null means routine polling can stop because the order is `done` or `expired`. Keep syncing with `sort=updatedAt` to receive later deposit and refund updates for expired orders. There are no webhooks. With more than a few dozen open orders, [sync](#list-and-sync).
Every change to an order raises its `version`. Reads can arrive out of order, for example a sync page and a read by id. Keep the one with the higher `version`. Two reads with the same `version` show the same order.
## What to show the user
Read `status`, `outcome` and `summary`. The [lifecycle](/guides/order-lifecycle/) lists every status and outcome.
**Before settlement**, show what the order commits to:
* `terms.receive`: the amount the quote showed.
* `terms.receiveMin`: the least a full fill pays.
* `terms.flatFee`: the quote’s `display.flatFee`. A published order that doesn’t fill, cancelled or not, refunds `send` less it. Recovery of a deposit that never published refunds the full deposit.
**After settlement**, show the two legs, `summary.payout` and `summary.refund`:
```json
"payout": { "amount": { "asset": { "id": "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "chain": "eip155:8453", "symbol": "USDC", "decimals": 6 }, "amount": "99620254" },
"status": "completed", "tx": { "chain": "eip155:8453", "hash": "0x…" }, "withoutTx": null }
```
| Field | Meaning |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `amount` | What this leg pays. Null until the order settles, and briefly after. |
| `status` | `pending` until it settles, `in_flight` on its way, `completed` once it lands. |
| `tx` | The delivery transaction, once seen. |
| `withoutTx` | Why a `completed` leg has no `tx`, else null. An [open list](/guides/conventions/#closed-and-open-lists): `sub_unit_amount` or `tx_unknown`. |
Both legs are always present. A leg with nothing to deliver completes with amount 0, so **show a leg once its `amount` is above zero**: a full fill has a payout, an order with no fill a refund, and a partial fill both.
A leg is complete once its `status` is `completed`, even while the order still shows `delivering`. A completed leg can have `tx: null` and empty obligation `evidence`; its `withoutTx` says why:
* `sub_unit_amount`: the amount was smaller than the smallest unit on the chain the leg pays out on, so nothing was transferred. For example, a partial fill can leave a ZEC refund below one zatoshi. Its refund leg completes with amount `"0"`, `tx: null` and `withoutTx: "sub_unit_amount"`.
* `tx_unknown`: the leg was delivered, but its transaction is unknown, and may never become available.
### Notices
`summary.notices` lists what Khalani is handling, each a `code` with `params`. The user has nothing to do. Tell them what is delayed.
| `code` | Meaning |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `NOT_PUBLISHED` | A deposit arrived that couldn’t fund the order, such as one that arrived too late. Khalani returns it to the sender. For an order that never published, the notice goes once the refund is recorded in `summary.refund`. If another deposit published the order, the notice remains for the separate stranded deposit. |
| `SETTLEMENT_STUCK` | Settlement is delayed. Khalani keeps retrying it. |
| `DELIVERY_STUCK` | A payout or refund is delayed. Khalani is recovering it. |
Notice codes are an open list. Show an unknown one as is.
## The order record
The rest of the order is the record behind `summary`:
| Field | What it holds |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `accounts` | The `payer`, `recipient` and `refundTo` the order was created with. |
| `steps` | The funding steps. See [Fund orders](/guides/fund-orders/). |
| `liveAt` | When the order went live for solvers. |
| `receipts` | The deposit’s transaction, once seen. |
| `fills` | Each fill, with `send`, what it used of the deposit (its share of the percentage fees included), and `receive`, what it pays. The fills’ `receive` add up to the payout. For a published order, their `send`, `terms.flatFee` and the refund add up to `terms.send`, give or take a base unit of rounding. |
| `obligations` | The `payout` to `recipient` and the `refund` to `refundTo`: the legs `summary` shows, with each delivery’s transaction, and when it was seen, in `evidence`. |
| `requirements` | What holds the order up, and who acts. Those Khalani acts on are also in `summary.notices`. |
| `invocations` | The cancel request, if any. See [Cancel and refunds](/guides/cancel-and-refunds/). |
| `actions.cancel` | Whether a cancel is possible now, and what to sign. |
| `charges.protocolFee` | The protocol fee taken at settlement, rounded up like `terms.flatFee`. |
## List and sync
`GET /v3/orders` returns your orders in pages of up to 50, limited to your key.
| Query | Meaning |
| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status` | Repeat it for several. Not with `sort=updatedAt`. |
| `account` | A [CAIP-10](https://chainagnostic.org/CAIPs/caip-10) id, such as `eip155:42161:0x5B38Da6a701c568545dCfcB03FcB875f56beddC4`. Matches the payer, the recipient or `refundTo`. |
| `sendAsset`, `receiveAsset` | An asset id. |
| `sort` | `createdAt` (the default) or `updatedAt`. |
| `cursor` | The `cursor` from the previous page. Leave it out on the first page. |
Keep the sort and filters unchanged while paging. A cursor in the wrong format, `cursor=null` included, is a `400 VALIDATION_FAILED`.
**`sort=createdAt`** lists newest first. `cursor` is null after the last page. Stop only then: a page before it can come back empty when it skipped orders v3 doesn’t show.
**`sort=updatedAt` syncs.** Each page holds the orders that changed after the cursor you send, each once and in its current state, oldest change first. Keep the last cursor you got, and ask again every 10 to 30 seconds:
* A page that comes back **empty with the cursor you sent** means you are caught up. Keep the cursor and ask again later.
* A page that comes back **empty with a new cursor** skipped changes that aren’t listed. Ask again now, with the new cursor.
* `410 CURSOR_EXPIRED` means the API can no longer use your cursor. Sync again with no cursor, which returns every order in its current state, and continue from the cursor it gives. A cursor doesn’t expire with time.
```bash
curl -sS "https://api.hyperstream.dev/v3/orders?sort=updatedAt&cursor=$CURSOR" -H "X-API-Key: $KHALANI_API_KEY"
```
Past a few dozen open orders, sync instead of reading each one: see [Rate limits](/guides/rate-limits/).
## Change history
A recovered order can move straight from `expired` to `done` if its refund is already delivered. Its history then records `delivered` with the refund record, without an intermediate `settled` change. An in-flight refund records `settled`, then `delivered` when delivery completes. A refund already known to have failed records `delivery_stuck` directly; show its `DELIVERY_STUCK` notice.
`GET /v3/orders/{id}/changes` lists the changes to one of your orders, oldest first. It records what happened to the order, while the order itself shows its current state. Each change has the order’s `version` after it, its time, a `kind`, and `records`, the ids of the steps and records it set.
| `kind` | When |
| -------------------------------------- | -------------------------------------------------- |
| `created` | The order was created. |
| `deposit_seen` | The deposit showed. |
| `funding_closed` | `fundBy` passed with no deposit. |
| `expired` | The order didn’t publish by `fillBy`. |
| `not_published` | A deposit arrived that couldn’t publish the order. |
| `published` | The order went live. |
| `cancel_requested` | A cancel was accepted for relay. |
| `filled` | A fill landed. |
| `trading_ended` | Trading stopped. |
| `settlement_stuck` | Settlement is delayed. |
| `settled` | The order settled. |
| `payout_delivered`, `refund_delivered` | One leg landed before the other. |
| `delivery_stuck` | A payout or refund is delayed. |
| `delivered` | Every leg landed. |
| `updated` | Anything else, before `settled`. |
Change kinds are an open list, and changes can arrive in a different order from the one above. Versions in the history can skip numbers: not every change to the order is listed.
# Collaborative solving
> How one order is filled from many sources of liquidity, settled together or in parts, without ever going below its rate.
Collaborative solving means one order can be filled from many sources of liquidity at once, so no single counterparty has to supply all of it. Solvers compose a fill from whatever they can reach: inventory, other venues and other orders in the book. The hub settles the result atomically.
Three mechanisms make it work.
## 1. Solutions are graphs
A solver submits a **solution**, a graph that says where each input intent’s escrow goes and which output satisfies each intent. The hub checks the graph before applying it:
* every input intent is open and within its deadline,
* escrow is conserved: for every input, what is spent plus what remains equals what was escrowed,
* every intent receives at least its rate, on whatever fraction is filled.
If any check fails, the whole solution reverts. Settlement is every leg or none, so a solver can combine many legs without the risk of executing half of them.
## 2. Orders can fill each other
The simplest graph has two orders that want each other’s tokens: one gives USDT for USDC, the other gives USDC for USDT. Each order’s escrow pays the other’s output, and no solver inventory is needed. A cycle of three or more orders can settle the same way.
When the legs don’t balance, the solver adds a **just-in-time intent** of its own to cover the difference, published and consumed in the same transaction. A solver’s standing liquidity is just another node in the graph.
## 3. Orders fill in parts
An order can be filled by several solutions. A solver that fills part of it leaves a child intent with the same rate and deadline for the next fill, from the same solver or another one. See [Intents and orders](/concepts/intents-and-orders/#partial-fills-form-a-chain).
```
flowchart LR
O["Order: 10,000 USDC on Arbitrum for USDT on Ethereum, at rate r"]
O -- "fill 6,000 at r or better" --> F1["Solution 1 solver inventory, just-in-time"]
O -- "remainder 4,000" --> C["child intent same rate r, same deadline"]
C -- "fill 4,000 at r or better" --> F2["Solution 2 sourced on another venue"]
F1 --> S["Settlement 10,000 filled at r or better, paid out once"]
F2 --> S
```
## What it means for your users
No single solver needs inventory for the whole order, so more orders fill completely: each part can come from wherever liquidity is available at that moment. However the order is split, no filled unit settles below the order’s rate. On an order with slippage, parts filled at different times can pay different prices between that rate and the quote. The user receives one payout, and one refund for anything unfilled, however many fills it took.
## Which mechanism fills an order
Solvers choose how to fill each order from the liquidity available at the time, so the mix of mechanisms varies from order to order. Your integration doesn’t depend on it: the guarantees above hold however an order is filled.
# Glossary
> The terms these docs use, in one place.
**Account.** An address on one chain, `{ chain, address }`. An order binds one to each of its roles: `payer`, `recipient` and `refundTo`.
**Attestation (quote terms).** Khalani’s signature over a quote option, carried inside its `id`. It pins `POST /v3/orders` to the quoted numbers until the quote’s `expiresAt`.
**CAIP ids.** Chain-neutral identifiers: CAIP-2 for a chain (`eip155:42161`), CAIP-19 for an asset, CAIP-10 for an account. See [Conventions](/guides/conventions/#chains-and-assets).
**Child intent.** The remainder of a partly filled intent, re-published with the parent’s exact terms and a smaller amount. See [Intents and orders](/concepts/intents-and-orders/#partial-fills-form-a-chain).
**Collaborative solving.** Filling one order from several sources of liquidity, settled atomically or across partial fills. See [Collaborative solving](/concepts/collaborative-solving/).
**Commission.** Your fee, in basis points, paid to your commission wallet on the hub when an order settles.
**Deadlines.** An order has two, counted from its creation: `fundBy`, to send the deposit by, and `fillBy`, after which it takes no more fills. Both come from your account’s order deadlines.
**Deposit contract.** The contract on a spoke that holds deposited tokens and releases payouts and refunds. Non-EVM chains have none: deposits go to a per-order deposit address, handled by an operated bridge service.
**Funding steps.** What the user’s wallet runs to fund an order, listed in its `steps`: approvals and a deposit on EVM, or one transfer on a non-EVM chain.
**Flat fee.** A fixed fee per order: the source asset’s `depositFee` plus the destination asset’s `withdrawFee`. It is kept in full, even on an order that never fills.
**Hub.** The chain that keeps Khalani’s books. Orders are published, filled and settled there.
**Integrator.** You: the party that holds an API key and creates orders for its users.
**Intent.** A declaration of an acceptable outcome, authorized by its owner, with its source value escrowed. An order becomes one intent on the hub. See [Intents and orders](/concepts/intents-and-orders/).
**Just-in-time intent.** An intent a solver publishes and consumes in the same transaction, to supply the part of a fill that other legs don’t cover.
**mToken.** The hub’s one-to-one ledger entry for one token on one spoke, minted on deposit and burned on withdrawal.
**Netting.** Filling orders against each other, so each order’s escrow pays another’s output.
**Option.** One way to make a quoted trade, from `POST /v3/quote`: what it requires of the user’s wallet, the accounts it needs, and its terms. Its `id` creates one order.
**Order.** What `POST /v3/orders` creates: an order record, its signed terms, the steps that fund it, and the intent it becomes on the hub once funded.
**Payer.** The account that sends an EVM order’s deposit. The deposit must come from it. An order from a non-EVM chain has none: anyone may send its transfer.
**Partial fill.** A fill of part of an order, at no less than the order’s rate. The rest stays open as a child intent.
**Rate.** The least an order receives per unit of source. On the hub it applies to the amount left after fees, and every fill must meet it. The order shows it over the whole deposit, fees included, as `terms.minRate`.
**Recipient.** The account that receives an order’s payout, on the destination chain.
**Recovery.** The field on every API error that says what to do next: fix the request, request a new quote, retry, read the order, restart a sync, or contact Khalani. See [Errors and retries](/guides/errors/).
**Refund account (`refundTo`).** The account that receives an order’s refund, on the source chain, and signs its cancel.
**Relayer.** The operated service that carries deposits from spokes to the hub, and withdrawals from the hub to spokes. The hub trusts what authorized relayers deliver.
**Root intent.** The first intent of an order, published when its deposit arrives.
**Settlement.** The one hub transaction that closes an order: it pays the filled part what its fills delivered, at least the order’s rate and at most its quote, refunds the unfilled share of the deposit after the flat fee, and takes the fees.
**Slippage.** How far under its quote an order may fill, in basis points (`slippageBps`). The order’s rate is the quote less the slippage.
**Solution.** What a solver submits through intent sequencing: a graph of which escrow pays which output. The hub validates it and applies it atomically, every leg or none.
**Solver.** An independent agent, authorized to submit solutions, that fills intents and is paid its spread. See [Solvers and solver markets](/concepts/solvers-and-solver-markets/).
**Solver market.** The network of solvers competing to fill orders, seen from the side of the party publishing them. From a solver’s side, the same book is an intent market.
**Spoke.** A chain your users hold tokens on. Its custody holds deposits and releases payouts: a deposit contract on EVM spokes, an operated bridge service on non-EVM ones.
# How Khalani works
> Hub and spokes, mTokens, and what happens to the user's funds from deposit to payout.
Khalani separates accounting and matching from custody and delivery.
* The **hub** is one chain that keeps the books. Orders are published, matched and settled there.
* **Spokes** are the chains your users hold tokens on: Ethereum, Arbitrum, Base and the others. On EVM spokes a deposit contract holds the real tokens and pays them out. On non-EVM spokes, deposits go to a per-order deposit address, and an operated bridge service credits them and executes payouts. Spokes run no matching logic.
## mTokens: the hub’s ledger
When a user deposits a token on a spoke, the token stays in that spoke’s custody, and the hub mints an **mToken**: a one-to-one ledger entry for that token on that spoke. USDC on Arbitrum and USDC on Base are different mTokens.
Everything after the deposit (publishing the order, filling it, settling it) happens in mTokens on the hub. When value leaves, the hub burns the mTokens first and the destination spoke releases the real tokens. Minting on each credited deposit and burning on each withdrawal keeps every mToken backed by the token held in its spoke’s custody.
```text
user wallet ──deposit──► spoke deposit contract ══ relayed ══► hub: mint mToken
▲ │
└──── release ◄═══ relayed ═════ burn mToken
```
## A transfer is a trade
Moving value from chain A to chain B takes three steps, and the middle one is an ordinary trade on the hub:
1. **Deposit on A.** The hub mints mToken-A.
2. **Trade on the hub.** An order exchanges mToken-A for mToken-B, filled by solvers.
3. **Withdraw on B.** The hub burns mToken-B and B’s custody releases the real token.
A cross-chain swap changes only the pair in the middle, and a same-chain conversion puts both ends on one spoke. Because every case is a trade in one book, the same liquidity serves all of them.
## The journey of one order
```
sequenceDiagram
participant W as User's wallet
participant A as Spoke A (source)
participant H as Hub
participant S as Solvers
participant B as Spoke B (destination)
W->>A: deposit (the order's funding steps)
A->>H: deposit relayed: mint mToken-A
H->>H: order published as an intent
S->>H: fill: mToken-A for mToken-B, at the order's rate or better
H->>H: settlement: payout, refund, fees
H->>B: withdrawal relayed: burn mToken-B
B->>W: payout released to the recipient
```
1. **Create.** The API signs the order’s terms: the pair, the amount, the rate, the slippage, the flat fee, the accounts and the deadline.
2. **Deposit.** The user’s wallet sends the deposit to the source spoke’s deposit contract, or on a non-EVM chain transfers it to the order’s deposit address.
3. **Relay and publish.** The deposit is relayed to the hub, which mints mTokens and publishes the order as an [intent](/concepts/intents-and-orders/) with those terms.
4. **Fill.** [Solvers](/concepts/solvers-and-solver-markets/) fill the intent, whole or in parts, each part at the order’s rate or better.
5. **Settle.** When the order fills completely, reaches its deadline, or is cancelled, one hub transaction pays the filled part, refunds the unfilled share, and takes the fees.
6. **Pay out.** The hub burns the mTokens and the destination spoke releases the payout to the recipient. Any refund is released on the source spoke the same way.
## Who does what
| Party | Does | Cannot |
| ---------------------- | --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| **Your backend** | Quotes, creates orders, relays cancels | Move user funds: deposits and cancels need the user’s signature |
| **The user’s wallet** | Sends the deposit, and signs any cancel | Change the terms of a created order |
| **Solvers** | Fill orders, competing to do so | Fill below an order’s rate: every fill is re-validated on the hub |
| **Khalani’s services** | Quote, sign order terms, track orders, sequence fills and settlement, relay messages between chains | Change an order’s rate or accounts after it is created |
# Intents and orders
> What an intent is, how an API order becomes one, and how partial fills form a chain.
## What an intent is
An intent is a declaration of an acceptable outcome, authorized by its owner: what must be true when it settles, not the steps to get there.
> “Get me from New York to Paris tomorrow, in under eight hours, for under $800.” The traveller fixes price, timing and destination. The travel agent chooses the airlines and the connections.
On Khalani an intent escrows its source value up front and states the outcome it accepts. The hub releases the escrow only for a fill that meets that outcome. A fill that doesn’t meet it cannot execute, so the user never carries that risk.
An intent has two sides:
* **Give:** the escrowed source, an amount of one mToken.
* **Get:** the outcome it accepts. For an API order that is a **rate**: the least amount of the destination mToken per unit of source, on any fraction of the source that fills.
## How an order becomes an intent
An order created with `POST /v3/orders` becomes one intent on the hub, the **root intent**, when its deposit arrives:
* **Give:** the deposit, in source mTokens, less the fees withheld at publish.
* **Get:** the destination mToken at no less than the order’s rate, the quote less any slippage, fillable in any fraction.
* **Valid until:** the order’s deadline.
The order’s terms (pair, amount, rate, slippage, flat fee, accounts, deadline) were signed when the order was created and must match the deposit the user sent. No API call or transaction can change them after the deposit. `fills` in the order lists each fill by the intent it solved.
The intent’s rate applies to the deposit less the fees withheld at publish. The order’s `terms.minRate` states the same guarantee over the whole deposit, fees included, which is what the user sees.
## Partial fills form a chain
A rate-based intent can fill in pieces. When a solver fills part of it, the hub splits the intent in the same transaction: the filled slice’s output is credited to the order on the hub, the parent closes, and the remainder becomes a **child intent**. Nothing is paid out to the user until the order settles.
The child is not a new order. The hub requires it to carry the parent’s exact terms (same author, rate and deadline), so only the amount shrinks. A sequence of partial fills therefore forms a chain in which every link holds the rate of the original order:
```
flowchart LR
root["root intent 1,000"] -- "remainder 400" --> c1["child 1 400"]
c1 -- "remainder 150" --> c2["child 2 150"]
c2 --> tip["tip open, filled, expired or cancelled"]
root -. "filled 600" .-> p1["credited at the rate or better"]
c1 -. "filled 250" .-> p2["credited at the rate or better"]
```
The API reports the whole chain as one order. Its `fills` list each link’s fill as it is observed.
## How an intent ends
The last child in the chain is its **tip**. It either fills completely, reaches the deadline, or is cancelled, and one settlement transaction then closes the order:
* the filled part, priced between the order’s rate and its quote, is paid to `recipient` on the destination chain,
* the unfilled share of the deposit, after the flat fee, is refunded to `refundTo` on the source chain,
* the fees are taken: the flat fee in full, the percentage fees on the filled part only.
Each order settles once. Cancels and fills are applied in sequence, so a cancel that races a fill settles what was filled and refunds the rest.
# Solvers and solver markets
> Who fills orders, how they compete, and what they can and cannot do with your users' funds.
## What a solver is
A solver is an independent agent that turns an intent’s “what” into a “how”:
1. It watches the hub for open intents.
2. It works out how to satisfy them: from its own inventory, by sourcing the token on other venues, or by matching intents against each other.
3. It submits that plan, a **solution**, to the hub through intent sequencing.
4. It is paid only if the hub validates the solution and settles it.
A solver earns its spread: the difference between the rate an order accepts and what it costs the solver to deliver. When you quote, solvers are pricing your order. The rate in the quote is the one they are prepared to fill at.
## What a solver cannot do
The hub re-validates every solution before applying it. A solver therefore cannot:
* fill below an intent’s rate, on any fraction of it,
* send the output anywhere but the order’s recipients,
* take escrowed funds it is not owed.
A solver that misprices, goes offline, or misbehaves can only leave an order unfilled, and an unfilled order is refunded at its deadline. So it is safe to let many independent solvers fill orders.
## Solver markets
From your side, you publish orders into a **solver market**: a network of independent agents competing to fill them. A solver sees the same book as an **intent market**, a live stream of orders, each priced by the rate it accepts.
Orders and solvers meet in one shared book on the hub, every order is settled by the same contracts, and any authorized solver can fill any open order whose terms it can meet.
### Why one shared book
mTokens are per token per chain, but they all clear in one book. A solver’s inventory therefore serves every pair at once:
* the same token across chains (USDC on Ethereum to USDC on Base),
* different tokens on one chain (USDT to USDC on Arbitrum),
* different tokens across chains (USDT on Ethereum to USDC on Polygon).
Liquidity is shared across pairs and chains, so a new pair can use all existing liquidity the day it is listed. For your users, that means more solvers able to fill each order, which keeps quotes competitive and fills reliable.
## Where to go next
* [Collaborative solving](/concepts/collaborative-solving/): how several sources of liquidity fill one order.