Cancel and refunds
When an order refunds
Section titled “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.fillBybefore 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.
A deposit that arrives too late is handled apart from settlement: see 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
Section titled “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
Section titled “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:
Cancel Khalani order ord_3f9a1c2b7d4e5f60718293a4b5c6d7e8Chain: eip155:42161Refund to: 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4refundTo 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.
// EVM, with viemconst signature = await walletClient.signMessage({ account: refundTo, message });A non-EVM source uses its chain’s own scheme, listed in 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
Section titled “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.
POST /v3/orders/{id}/actionsX-API-Key: <your key>Content-Type: application/json
{ "kind": "cancel", "signature": "0x…" }// 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<Order>(`/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<Hex> { 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<Order> { return call<Order>(`/orders/${orderId}/actions`, apiKey, { kind: "cancel", signature });}
async function call<T>(path: string, apiKey: string, body?: unknown): Promise<T> { 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 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
Section titled “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).