# MCP server Source: https://docs.ravn.exchange/ai-agents/mcp-server Connect Claude, Cursor or any MCP client to RAVN. Free, no key. **Endpoint:** `https://app.ravn.exchange/api/mcp` (Streamable HTTP). No key needed; pass yours as the optional `apiKey` argument on any tool for a higher rate limit and your fee. > [card] [Add to Claude.ai](https://claude.ai/customize/connectors?modal=add-custom-connector\&connectorName=RAVN\&connectorUrl=https%3A%2F%2Fapp.ravn.exchange%2Fapi%2Fmcp) > > One click: opens Claude's connector dialog, pre-filled. > [card] [Add to Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=RAVN\&config=eyJ1cmwiOiJodHRwczovL2FwcC5yYXZuLmV4Y2hhbmdlL2FwaS9tY3AifQ%3D%3D) > > One click, on a machine with Cursor installed. ```json Claude Desktop / Claude Code / Cursor theme={null} { "mcpServers": { "ravn": { "url": "https://app.ravn.exchange/api/mcp" } } } ``` ```toml Codex CLI (~/.codex/config.toml) theme={null} [mcp_servers.ravn] url = "https://app.ravn.exchange/api/mcp" auth = "none" ``` A plain `GET` answers `405`: that's expected, MCP speaks `POST`. RAVN is also listed on [MCP.so](https://mcp.so/servers/ravn), [Glama](https://glama.ai/mcp/connectors/exchange.ravn/ravn) and [Smithery](https://smithery.ai/servers/team-dgp6/ravn). ## The loop Ask your client something like *"Swap 0.01 ETH on Ethereum to USDC on Base for 0x1234…5678."* It runs: 1. `ravn_quote` → a priced route and a `quoteToken`. 2. `ravn_execute` → a `TRANSACTION`, `SIGNATURE` or `DEPOSIT`, plus a new `quoteToken`. 3. Your wallet acts on it ([who signs?](/ai-agents/overview#who-signs)): * `TRANSACTION`: send it, and any `fee` as [Collecting your fee](/collecting-your-fee) says. * `SIGNATURE`: sign `typedData`, then `ravn_submit_signature` → a `statusRef`. * `DEPOSIT`: send the input to the address. From Bitcoin, `ravn_btc_prepare_send` builds it. 4. `ravn_status` with step 2's `quoteToken` and the `statusRef` (or the transaction hash), until `success`, `refunded` or `failed`. ## Tools The arguments match the REST endpoints. Every tool also takes an optional `apiKey`. | Tool | Same as | | - | - | | `ravn_quote` | [`POST /quote`](/api-reference/quote). `confidential` here races NEAR Intents only | | `ravn_execute` | [`POST /execute`](/api-reference/execute). Hinkal quotes aren't supported | | `ravn_submit_signature` | [`POST /submit-signature`](/api-reference/submit-signature) | | `ravn_status` | [`POST /status`](/api-reference/status) | | `ravn_tokens`, `ravn_tokens_resolve` | [`GET /tokens`](/api-reference/tokens-list), [`GET /tokens/resolve`](/api-reference/tokens) | | `ravn_chains`, `ravn_btc_coverage`, `ravn_health` | [`GET /chains`](/api-reference/chains), [`/tokens/btc-coverage`](/api-reference/btc-coverage), [`/health`](/api-reference/health) | ### `ravn_btc_prepare_send` Turns a Bitcoin `DEPOSIT` into an unsigned PSBT (`psbtBase64`) for your wallet to sign and broadcast. UTXOs and fee rates come from mempool.space. RAVN never sees a private key. | Argument | Required | | | - | - | - | | `fromAddress` | yes | The sending address, native SegWit (`bc1q…`) or Taproot (`bc1p…`) | | `toAddress` | yes | `deposit.address` | | `amountSats` | yes | `deposit.amount` | | `feeAddress`, `feeAmountSats` | when the execution has a `fee` | `fee.address` and `fee.amount`. Leave them out and your fee is never paid | | `feeRateSatsPerVb` | no | Default: mempool.space's estimate | | `network` | no | `mainnet` (default) or `testnet` | # AI agents Source: https://docs.ravn.exchange/ai-agents/overview Three ways for an agent to swap through RAVN: a free MCP server, pay-per-call x402, or the REST API. All three run the same quote, execute and status flow, with the same prices as RAVN's own app. | | Signup | Cost | Best for | | - | - | - | - | | [MCP server](/ai-agents/mcp-server) | None | Free | Claude, Cursor and any MCP client: add one URL | | [x402](/ai-agents/x402-payments) | None | \$0.001 per quote, \$0.01 per execute, in USDC | Agents that pay per call instead of holding a key | | [REST API](/api-reference/overview) | None, or a [free key](/tools/get-api-key) | Free | Your own HTTP client | Your fee applies on any of them when you send your API key. ## Who signs? RAVN never signs for you. `execute` returns a transaction, typed data or a deposit address, and your agent's wallet acts on it. Decide once how that wallet works: * **A key in the agent's environment**, signing with a library like `viem`. Simplest. * **A human approves** each transaction in their own wallet before it's sent. * **A custody service or enclave** (Turnkey, Privy, a CDP wallet) signs on the agent's request, so the key never enters the agent. For a Bitcoin deposit, the MCP tool [`ravn_btc_prepare_send`](/ai-agents/mcp-server#ravn_btc_prepare_send) builds the transaction to sign, so the agent needs no Bitcoin code of its own. # x402 payments Source: https://docs.ravn.exchange/ai-agents/x402-payments Pay per call in USDC instead of holding an API key. RAVN's quote and execute are also sold per call over [x402](https://www.x402.org): no key, no signup, nothing to leak. Agents can find RAVN through Coinbase's x402 Bazaar and [x402scan](https://x402scan.com). If you don't need that, the [MCP server](/ai-agents/mcp-server) and REST API are free. | Endpoint | Price | Same as | | - | - | - | | `POST https://app.ravn.exchange/api/v1/x402/quote` | \$0.001 | [`POST /quote`](/api-reference/quote) | | `POST https://app.ravn.exchange/api/v1/x402/execute` | \$0.01 | [`POST /execute`](/api-reference/execute) | Paid in USDC on Base or Solana. Bodies, responses and errors match the free endpoints, and a `quoteToken` works on either. Status, submit and every other call stay free: use the normal endpoints. * You pay only for a success. An error (any 4xx or 5xx, such as `NO_LIQUIDITY` or `QUOTE_EXPIRED`) costs nothing. * Each IP has 30 slots, held by its failed calls (for about a minute) and its calls still running. With none free, its calls get `429 RATE_LIMITED`: retry after `details.retryAfterSec`, and fix any request that keeps failing. * A payment buys one call. Sending it again gets `400`: let your client sign a new one. * The price pays for the call, not the swap. Send your `x-api-key` too and the quote carries your fee; without one it's 0. * `/x402/quote` ignores `broadcastViaRavn` (a free `/quote` made with it still executes on `/x402/execute`), and refuses `call` (`400 INVALID_REQUEST`): quote calls on the free `/quote` with a key. Hinkal and Fynd aren't offered: execute them on the free endpoints. * `sandbox: true` works, but the call is still charged. ## How it works 1. Call the endpoint. RAVN answers `402` with the payment terms in the `payment-required` header (base64; the body is an empty `{}`). 2. Your x402 client signs a USDC payment and retries with it attached. 3. RAVN runs the call, settles the payment only if it succeeded, and returns the normal response. x402 client libraries do steps 2 and 3 for you: ```javascript theme={null} import { wrapFetchWithPayment, x402Client } from "@x402/fetch"; import { ExactEvmScheme, toClientEvmSigner } from "@x402/evm"; const core = new x402Client(); core.register("eip155:*", new ExactEvmScheme(toClientEvmSigner(yourEvmWalletClient))); const x402Fetch = wrapFetchWithPayment(fetch, core); const res = await x402Fetch("https://app.ravn.exchange/api/v1/x402/quote", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ inputChainId: 1, outputChainId: -2, inputToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", outputToken: "So11111111111111111111111111111111111111112", inputAmount: "1000000000000000000", userAddress: "0xYourAddress", destinationAddress: "YourSolanaAddress", }), }); const { data } = await res.json(); // includes quoteToken ``` Pay from Solana with `@x402/svm` instead. If x402 is switched off, both endpoints answer `503 NOT_CONFIGURED`: use the free ones. # GET /tokens/btc-coverage Source: https://docs.ravn.exchange/api-reference/btc-coverage How many Bitcoin venues list each RAVN token on a chain. When native BTC is the **source**, this counts how many BTC venues list each of RAVN's tokens on a chain. Use it to rank your token list, not to hide tokens: a quote is the only check, and tokens off RAVN's list can route from BTC too. **chainId** `integer` *required* The destination chain. ```bash theme={null} curl -s "https://app.ravn.exchange/api/v1/tokens/btc-coverage?chainId=8453" ``` ## Response **coverage** `object` Token address → number of BTC venues that list it (1 to 3). EVM addresses are lowercase; Solana mints keep their case. **filtered** `boolean` `false` means coverage couldn't be checked right now and `coverage` is empty. Show your full list rather than nothing. **chainId** `integer` The chain asked for. ```json theme={null} { "data": { "chainId": 8453, "filtered": true, "coverage": { "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee": 2, "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913": 2 } } } ``` ```ts theme={null} const key = chainId === -2 ? token.address : token.address.toLowerCase(); const venues = coverage[key] ?? 0; // 0: not on RAVN's list, quote it to check ``` Rank your list by count: a token more venues list is more likely to keep routing through one venue's outage. # GET /chains Source: https://docs.ravn.exchange/api-reference/chains Every supported chain. Static: cache it. Use it to fill a chain picker. ```bash theme={null} curl -s https://app.ravn.exchange/api/v1/chains ``` ## Response An array of `{ chainId, name, shortName, nativeCurrency: { name, symbol, decimals }, explorerUrl, logoUrl? }`. ```json theme={null} { "data": [ { "chainId": 1, "name": "Ethereum", "shortName": "ETH", "nativeCurrency": { "name": "Ether", "symbol": "ETH", "decimals": 18 }, "explorerUrl": "https://etherscan.io" }, { "chainId": -1, "name": "Bitcoin", "shortName": "BTC", "nativeCurrency": { "name": "Bitcoin", "symbol": "BTC", "decimals": 8 }, "explorerUrl": "https://mempool.space" } ] } ``` Tempo's native currency (`USD`) is a unit of account, not a swappable token. Arc's native coin is the same balance as its USDC token: see [Supported chains](/supported#chains). # POST /execute Source: https://docs.ravn.exchange/api-reference/execute https://app.ravn.exchange/openapi.json POST /api/v1/execute Turn a quote into what the wallet signs or sends. Takes a `quoteToken` from [`/quote`](/api-reference/quote) and returns one execution, tagged by `executionType`. What to do with each type: [Execution types](/execution-types). ## Request **quoteToken** `string` *required* From `/quote`, or from one of its `alternatives`. **destinationAddress** `string` A recipient given late. Only a few venues accept one here; the rest refuse an address that differs from the quote's (`400 INVALID_REQUEST`). Set it on the quote instead. **refundAddress** `string` A refund address given late. Same rule as `destinationAddress`. **authorization** `string` Only when answering a Hinkal [`AUTHORIZE` step](/private-swaps#authorize-steps), with `signature`. **signature** `string` The paying wallet's signature over that step's `sign`. **Idempotency-Key** `string` Any unique value per swap attempt, such as a UUID. A retry with the same key within 24 hours returns the first answer instead of building again, so a timeout never opens a second deposit address. Use a new key for each `AUTHORIZE` answer. ```bash theme={null} curl -s -X POST https://app.ravn.exchange/api/v1/execute \ -H 'content-type: application/json' \ -H 'Idempotency-Key: 0b6f1f8e-1c1a-4d2b-9a57-3f1d8e1c2a90' \ -d '{ "quoteToken": "" }' ``` ## Response **executionType** `string` `TRANSACTION`, `SIGNATURE` or `DEPOSIT` (`AUTHORIZE` for an opted-in [Hinkal](/private-swaps#hinkal) swap). See [Execution types](/execution-types). **quoteToken** `string` Use this one, not the quote's, for every later call. **swapId** `string` This swap's id in RAVN's ledger. [Webhooks](/webhooks) name it. **statusRef** `string` What to poll `/status` with, when present. **approval** `object` An ERC-20 approval to send and mine first, when needed. May carry `reset`. See [Approvals](/execution-types#approvals). **transaction** `object` `TRANSACTION` only. EVM: `to`, `data`, `value`, `chainId`, and `gasLimit` to send it with. Solana: `serialized`, base64. **calls** `object[]` EVM, when RAVN could build it (almost always). Every transaction to send, in order: approvals, the swap or deposit, then your fee. **batch** `boolean` `true` when `calls` may go in one atomic wallet batch. **submit** `object` Where to post what you signed: `/submit-signature` on a `SIGNATURE`, `/submit-transaction` on a `TRANSACTION` you [must not broadcast](/api-reference/submit-transaction). **typedData** `object` `SIGNATURE` only. The order to sign. `approvalData`, when present, is a second one. **deposit** `object` `DEPOSIT` only. Send `amount` of the input token to `address`. Ready-made: `psbt` (Bitcoin), `transaction` (Solana, with your fee). `expiresAt`, when set, is the deadline: send right away and never after it. **fee** `object` Your fee, when this route collects it beside the swap: `amount`, `address`, `chainId`, and on EVM a `transaction`. See [Collecting your fee](/collecting-your-fee). **sandbox** `boolean` `true` on a [sandbox](/sandbox-mode) quote. Never send it. ```json theme={null} { "data": { "executionType": "DEPOSIT", "quoteToken": "rq_…", "swapId": "p_…", "deposit": { "address": "0x…", "amount": "1000000000000000000", "chainId": 1 }, "calls": [{ "to": "0x…", "data": "0x", "value": "1000000000000000000", "chainId": 1 }], "batch": false, "statusRef": "…" } } ``` ## Errors | Code | Fix | | - | - | | `410 QUOTE_EXPIRED` | The quote is too old, or re-priced below its minimum. Quote again | | `400 QUOTE_NOT_EXECUTABLE` | A preview. Quote again with the addresses in `details.missing` | | `400 QUOTE_INVALID` | The token is malformed or altered. Quote again | | `400 INVALID_REQUEST` | A late address this venue won't take, or a bad field | | `502 BUILD_FAILED` | The venue couldn't build the swap right now. Quote again | | `503 UNAVAILABLE` / `VENUE_RATE_LIMITED` | Retry the same call, with the same `Idempotency-Key`, after `details.retryAfterSec` | # GET /health Source: https://docs.ravn.exchange/api-reference/health Which venues are live right now. Always answers `200`: read `status`, not the HTTP code. Public, no key. ```bash theme={null} curl -s https://app.ravn.exchange/api/v1/health ``` ## Response **status** `string` `ok` or `degraded`. **venues** `array` `{ id, name, logoUrl?, healthy }` for each venue that can win a quote right now. `id` is what `excludeVenues` and `onlyVenues` take. ```json theme={null} { "data": { "status": "ok", "venues": [ { "id": "chainflip", "name": "Chainflip", "logoUrl": "https://coin-images.coingecko.com/coins/images/25576/small/kdt_AgmT_400x400.png", "healthy": true }, { "id": "relay", "name": "Relay", "logoUrl": "https://relay.link/apple-touch-icon.png", "healthy": true } ] } } ``` This list, not the tables in these docs, is the source of truth for which venues are live. # POST & PATCH /v1/keys Source: https://docs.ravn.exchange/api-reference/keys Create a key, then set your fee, payout addresses, webhook and allowed sites. Which key goes where: [Public and secret keys](/authentication#public-and-secret-keys). ## Create a key: POST /v1/keys The [signup form](/tools/get-api-key) calls this for you. No key needed; 5 signups a minute per IP. **email** `string` *required* Where your key and partnership follow-ups go. **projectName** `string` *required* **website** `string` *required* A valid URL. **telegram** `string` *required* **twitter** `string` *required* **feeBps** `integer` Your fee, 0 to 100 bps. Default 0. Optional: `discord`, `blurb`, `category`, `chains`, `apisPlanned`. ```bash theme={null} curl -s -X POST https://app.ravn.exchange/api/v1/keys \ -H 'content-type: application/json' -d '{ "email": "you@project.xyz", "projectName": "Your Project", "website": "https://project.xyz", "telegram": "@yourproject", "twitter": "@yourproject" }' ``` ```json theme={null} { "data": { "apiKey": "rvn_live_…", "secretKey": "rvn_sk_…", "partnerId": "…", "feeBps": 0 } } ``` `apiKey` is your public key. `secretKey` is shown only in this response: store it on your server. ## Update a key: PATCH /v1/keys Send your **secret key** as `x-api-key`. Include at least one field. **feeBps** `integer` 0 to 100 bps. See [Pricing](/pricing). **payoutAddresses** `object` Any of `evm`, `solana`, `thorchain` (`thor1…`), `bitcoin`. A new or changed address takes effect 24 hours later. See [Getting paid](/pricing#getting-paid). **webhookUrl** `string` An `https://` URL. See [Webhooks](/webhooks). **allowedOrigins** `string[]` Up to 20 sites (`https://app.example.com`) your public key works from in a browser, replacing the current list. `[]` allows any, except in the [widget](/sdks/widget), which needs your site listed. ```bash theme={null} curl -s -X PATCH https://app.ravn.exchange/api/v1/keys \ -H 'x-api-key: rvn_sk_your_secret_key' \ -H 'content-type: application/json' -d '{ "feeBps": 25, "payoutAddresses": { "evm": "0xYourPayoutAddress" }, "webhookUrl": "https://your-service.example/ravn-webhook" }' ``` ```json theme={null} { "data": { "feeBps": 25, "payoutAddresses": { "evm": "0xYourPayoutAddress" }, "webhookUrl": "https://your-service.example/ravn-webhook", "webhookSecret": "a1b2c3…" } } ``` `webhookSecret` comes back whenever you set `webhookUrl`. Enterprise keys: `feeBps`, `webhookUrl` and `allowedOrigins` answer `404 NOT_FOUND` (RAVN sets your fee), so an enterprise key doesn't work in the widget yet. `payoutAddresses` works. ## Rotate your secret key `POST /v1/keys/secret`, no body, with your current secret key as `x-api-key`. The old secret stops working within a minute. A key from before secret keys existed claims its first secret the same way, before 1 December 2026. Lost your secret key? Contact RAVN. ```bash theme={null} curl -s -X POST https://app.ravn.exchange/api/v1/keys/secret \ -H 'x-api-key: rvn_sk_your_current_secret_key' ``` ```json theme={null} { "data": { "secretKey": "rvn_sk_…" } } ``` ## Errors | Code | When | | - | - | | `400 INVALID_REQUEST` | No field, or a bad value: `feeBps` out of range, a malformed address, a non-`https` webhook | | `401 UNAUTHORIZED` | No key, or a secret key that was already rotated | | `403 FORBIDDEN` | A public key, or not your current secret key | | `404 NOT_FOUND` | A self-serve-only field on an enterprise key | # OpenAPI spec Source: https://docs.ravn.exchange/api-reference/openapi The machine-readable spec, for Postman, Insomnia or an agent's tool loader. The OpenAPI 3.1 document for every endpoint, including the x402 ones: ``` https://app.ravn.exchange/openapi.json ``` Import it by URL in Postman or Insomnia, or hand it to any agent framework that loads tools from OpenAPI. # Overview Source: https://docs.ravn.exchange/api-reference/overview Base URL, conventions and every endpoint. ``` https://app.ravn.exchange/api/v1 ``` * **Requests and responses** are JSON. Keys are optional: see [Authentication](/authentication). * **Amounts** are strings in the token's smallest unit (wei, lamports, satoshis). * **Native coin** is `0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE`. Native SOL is the mint `So11111111111111111111111111111111111111112`. * **Every response** has the same envelope, an `x-request-id` header to quote to support, and the API's [version](/changelog#versions) in `ravn-version` and `meta.version`: ```json Success theme={null} { "data": { }, "meta": { "requestId": "…", "version": "2026-11-09" } } ``` ```json Failure theme={null} { "error": { "code": "NO_LIQUIDITY", "message": "…", "details": { } }, "meta": { "requestId": "…", "version": "2026-11-09" } } ``` The full spec is at [`/openapi.json`](/api-reference/openapi), ready for Postman or an agent's tool loader. ## Endpoints | Endpoint | What it does | | - | - | | [`POST /quote`](/api-reference/quote) | Best route for a swap, plus a `quoteToken` | | [`POST /execute`](/api-reference/execute) | What the wallet signs or sends | | [`POST /submit-signature`](/api-reference/submit-signature) | Place a signed gasless order | | [`POST /submit-transaction`](/api-reference/submit-transaction) | Send a signed Solana transaction through RAVN | | [`POST /status`](/api-reference/status) | Track a swap until it's final | | [`POST /recover`](/api-reference/recover) | Recover a failed Hinkal swap | | [`POST` & `PATCH /keys`](/api-reference/keys) | Create a key; set your fee, payouts, webhook | | [`GET /chains`](/api-reference/chains) | Supported chains | | [`GET /tokens`](/api-reference/tokens-list) | RAVN's token list for a chain | | [`GET /tokens/resolve`](/api-reference/tokens) | Any token's metadata by address | | [`GET /tokens/btc-coverage`](/api-reference/btc-coverage) | How many BTC venues list each token | | [`GET /health`](/api-reference/health) | Which venues are live | ## Chain IDs | Chain | ID | Chain | ID | | - | - | - | - | | **Bitcoin** | **-1** | **Solana** | **-2** | | Ethereum | 1 | Base | 8453 | | Optimism | 10 | Arbitrum | 42161 | | BNB Chain | 56 | Linea | 59144 | | Unichain | 130 | Avalanche | 43114 | | Polygon | 137 | Robinhood Chain | 4663 | | zkSync Era | 324 | Monad | 143 | | World Chain | 480 | HyperEVM | 999 | | Tempo | 4217 | Arc | 5042 | | Elysium | 99901 | | | [`GET /chains`](/api-reference/chains) returns the same list. # POST /quote Source: https://docs.ravn.exchange/api-reference/quote https://app.ravn.exchange/openapi.json POST /api/v1/quote Get the best-priced route for a swap. Races every venue that can serve the pair and returns the best route, plus a `quoteToken` for [`/execute`](/api-reference/execute). ## Request **inputChainId** `integer` *required* Source chain ID. See [chain IDs](/api-reference/overview#chain-ids). **outputChainId** `integer` *required* Destination chain ID. **inputToken** `string` *required* Token address or Solana mint. Native coin: `0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE`. **outputToken** `string` *required* Token address or Solana mint. Native coin: as above. **inputAmount** `string` *required* In the input token's smallest unit. With `call.exactAmount`, the most your user sends. **userAddress** `string` *required* The wallet that pays. **destinationAddress** `string` Where the output goes. Set it here: without it some routes return only a preview (`executable: false`), and most won't accept a different one at `/execute`. **refundAddress** `string` Where the input goes back if the swap fails. Defaults to `userAddress`. Needed when selling BTC from a `userAddress` that isn't a Bitcoin address. **slippageBps** `integer` 1 to 5000. Omit for Auto: 50 bps, or the venue's own setting on some routes (shown in `slippage.bps`). Setting it leaves out venues with no minimum output unless `allowNoMinimum` is set. **allowNoMinimum** `boolean` Let venues with no minimum output (Rift) race even though you set `slippageBps`. Default `false`. **rankingMode** `string` `best_output` (default) or `fastest`, the quickest route within your slippage. **excludeVenues** `string[]` Venue IDs to leave out, including from RAVN's multi-step routes. IDs are on [Supported chains & venues](/supported#venues). **onlyVenues** `string[]` Race only these venue IDs. A multi-step route races only when every venue in it is listed. **confidential** `boolean` A [private swap](/private-swaps): only private venues race. **authorizeSteps** `boolean` Your flow can answer Hinkal's [`AUTHORIZE` steps](/private-swaps#authorize-steps). Without it, Hinkal doesn't race. **clientTimezone** `string` Your user's IANA timezone, e.g. `Europe/Berlin`. Sent only to Houdini Swap. Default `UTC`. **broadcastViaRavn** `boolean` You can post signed Solana transactions back to RAVN. Adds more Solana routes: see [Bitcoin and Solana](/bitcoin-and-solana#broadcastviaravn). **call** `object` End the swap with a call into your registered contract, such as a vault deposit for your user, instead of paying an address. See [Call a contract after the swap](#call-a-contract-after-the-swap). **timeoutMs** `integer` How long the race waits for venues, in ms. Default `6000`, from 1,000 to 15,000. **stream** `boolean` Stream prices while the race runs. See [Streamed response](#streamed-response). **sandbox** `boolean` Test the flow without moving funds. See [Sandbox mode](/sandbox-mode). ```bash theme={null} curl -s -X POST https://app.ravn.exchange/api/v1/quote \ -H 'content-type: application/json' -d '{ "inputChainId": 1, "outputChainId": -2, "inputToken": "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", "outputToken": "So11111111111111111111111111111111111111112", "inputAmount": "1000000000000000000", "userAddress": "0x1111111111111111111111111111111111111111", "destinationAddress": "YourSo1anaWa11etAddressGoesHere311111111111" }' ``` ## Response **quoteToken** `string` Pass it to `/execute` as is. Never parse it. **venue** `object` The winning venue's `id`, `name` and `logoUrl` (its logo, absent when RAVN has none). RAVN's own multi-step routes are named `RAVN` and list their venues in `hops`. **routeType** `string` For example `CROSS_ECOSYSTEM` or `EVM_CROSS_CHAIN`. **input** `object` The input `token` and `amount`. **output** `object` The output `token` and quoted `amount`. **expectedOutputAmount** `string` What RAVN expects the route to deliver. The same as `output.amount` unless the route has no minimum output. Rank on this if you sort routes yourself. **fee** `object` Your integrator fee: `bps`, `amount`, `token`, `supported`. See [Pricing](/pricing#the-fee-on-each-quote). **executable** `boolean` `false` means a preview only. `/execute` refuses it with `QUOTE_NOT_EXECUTABLE`, naming the missing address in `details.missing`: quote again with it. **slippage** `object` `bps`, `isFirm`, `guaranteedMin`, `noMinimum`, `expectedShortfallBps`, or `null`. When `noMinimum` is `true` there is no guaranteed minimum: the user can get more or less than quoted. Tell them before they send. **gas** `object` Native gas the user needs: `native`, `nativeSymbol`, `usd`, `estimated`. `null` on gasless routes. **inputUsd** `string` USD value of the input. `null` when it can't be priced. **outputUsd** `string` USD value of the output. Compare with `inputUsd` to warn about a large loss. **estimatedTimeSeconds** `number` Expected time to settle. Can be fractional. **estimatedTimeIsGuess** `boolean` `true` when the venue gave no timing, so the estimate is generic. **expiresAt** `integer` Epoch ms. Execute before it. Up to 10 minutes later, `/execute` prices the route again and builds it only if it still meets the minimum this quote showed, else `410 QUOTE_EXPIRED`. **hops** `array` On RAVN's multi-step routes, the venues it runs through, in order, each shaped like `venue`. The user signs only the first. **alternatives** `array` Every other usable route, best first. Each has its own `quoteToken` (execute it to take that route), `inputAmount`, `expectedOutputAmount`, `fee`, `slippage` and `expiresAt`. With `call.exactAmount`, compare them on `inputAmount`. Skip any with `pickable: false`. ```json theme={null} { "data": { "quoteToken": "rq_…", "venue": { "id": "chainflip", "name": "Chainflip", "logoUrl": "https://coin-images.coingecko.com/coins/images/25576/small/kdt_AgmT_400x400.png" }, "routeType": "CROSS_ECOSYSTEM", "input": { "token": { "symbol": "ETH", "decimals": 18 }, "amount": "1000000000000000000" }, "output": { "token": { "symbol": "SOL", "decimals": 9 }, "amount": "18985000000" }, "expectedOutputAmount": "18985000000", "fee": { "bps": 0, "amount": "0", "token": { "symbol": "SOL" }, "supported": true }, "executable": true, "slippage": { "bps": 50, "isFirm": false, "guaranteedMin": "18890075000", "noMinimum": false, "expectedShortfallBps": 0 }, "inputUsd": "3412.20", "outputUsd": "3405.81", "estimatedTimeSeconds": 162.4, "expiresAt": 1750000000000, "alternatives": [ { "venue": { "id": "relay", "name": "Relay", "logoUrl": "https://relay.link/apple-touch-icon.png" }, "quoteToken": "rq_…", "pickable": true, "outputAmount": "18930000000", "expectedOutputAmount": "18930000000", "expiresAt": 1749999990000 } ] } } ``` The response is abbreviated: tokens carry full metadata, and alternatives carry every field above. Returns `404 NO_LIQUIDITY` when no venue can serve the pair or amount. See [Errors](/errors). ## Streamed response With `"stream": true` the answer is newline-delimited JSON (`application/x-ndjson`), one event per line. The first prices usually arrive within a second. ```json theme={null} {"type":"venues","venueIds":["chainflip","relay","near_intents"]} {"type":"settled","venueId":"relay","quotes":[{"venue":{"id":"relay","name":"Relay","logoUrl":"https://relay.link/apple-touch-icon.png"},"outputAmount":"18930000000",…}]} {"type":"done","status":200,"data":{ …the same body as above… },"meta":{ … }} ``` * `venues`: the venues racing. * `settled`: one venue answered. Show its prices, but don't execute them (they have no `quoteToken`). `quotes` is empty when it had nothing usable. * `preview`: an early price from RAVN's own multi-step route, before its `settled`. Show it like `settled`; that route's next `preview` or its `settled` replaces it. * `done`: the final answer, always the last line. Execute only this one. A failed race carries `status` (such as `404`) and `error` here, because the HTTP status was already `200`. A request refused before the race starts gets a normal JSON error. A stream that ends without `done` failed: request it again. ## Call a contract after the swap Set `call` and the output goes into your contract instead of to an address: a vault, perps or privacy-pool deposit for your user, from any supported chain, Bitcoin included, in one step. 1. Ask RAVN to register your contract and its function on your key, for each chain. Any other call gets `400 INVALID_REQUEST`. 2. Set `outputToken` to the ERC-20 your contract takes, and `destinationAddress` to your user's EVM address. 3. Fill in `call`: * `target`: your contract on the output chain. * `data`: the calldata, selector included. * `amountAt`: the byte offset in `data`, selector included, where RAVN writes the amount as a uint256: `4` for `deposit(uint256 assets, address receiver)`. Leave it out only when `data` already holds `exactAmount`. * `exactAmount`: put exactly this much of `outputToken` into the call, in its smallest unit. Your user then sends only what that takes (`input.amount`). Without it, the call gets `output.amount`, what the swap of `inputAmount` guarantees. * `leftoverTo`: where anything the call doesn't spend goes. Defaults to `destinationAddress`. > [!WARNING] > > The venue's contract makes the call, not your user's wallet. `data` must name your user as the > owner of what the call creates (`receiver`, `onBehalfOf`): anything credited to the caller can be > taken. ```json theme={null} { "inputChainId": 42161, "outputChainId": 8453, "inputToken": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", "outputToken": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "inputAmount": "10000000", "userAddress": "0x1111111111111111111111111111111111111111", "destinationAddress": "0x1111111111111111111111111111111111111111", "call": { "target": "0x2222222222222222222222222222222222222222", "data": "0x6e553f6500000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111", "amountAt": 4 } } ``` This deposits 10 USDC from Arbitrum into a vault on Base for `0x1111…1111`. `output.amount` is what the call receives. RAVN runs the call against the chain before quoting. A call that fails that run comes back as `404 NO_LIQUIDITY`: check `data`, that your contract credits your user and, with `exactAmount`, that `inputAmount` covers it. If the call fails when the swap lands, your user gets the input back on the source chain, or the output token at `destinationAddress`. An expired call quote isn't priced again at `/execute`: quote again. Your fee on top (0 to 1%, 60% of it yours) works as on any swap. **From Bitcoin**, the call lands on Ethereum, Base, Arbitrum, Optimism, Polygon, Avalanche or Monad; into Avalanche or Monad, set `exactAmount`. Your user sends `deposit.amount` in one plain transfer: your fee is taken inside the route in `outputToken`, so there's no `fee` output to add. With `exactAmount`, `deposit.amount` carries a margin so the price can move while the BTC confirms. For a vault, ask RAVN to register your contract for a leftover: all of it is then swapped, the call gets exactly `exactAmount`, and the rest goes to `leftoverTo` in `outputToken` in the same transaction. The margin is about 3% at the default `slippageBps`, so set `inputAmount` to cover it; above a `slippageBps` of 3% the leftover isn't offered. Otherwise, as for a privacy pool, nothing is paid beside the deposit: what the swap didn't use goes back to their [Bitcoin refund address](/bitcoin-and-solana) minus a refund fee (currently about 1,900 sats), so a smaller surplus isn't returned. A call that fails when the swap lands pays out on the output chain, in USDC or `outputToken`, at `destinationAddress`, not in BTC. # POST /recover Source: https://docs.ravn.exchange/api-reference/recover https://app.ravn.exchange/openapi.json POST /api/v1/recover Get back the funds a failed Hinkal swap left at Hinkal. A [Hinkal](/private-swaps#hinkal) swap whose payout fails isn't refunded on its own. This endpoint sends the funds back to the wallet that paid, and only there. Use it when `/status` reports `failed` with `venueStatus` ending `(needs recovery)`, or when the deposit confirmed but `/status` still says `pending` 25 minutes after the order. It works for 7 days after the order. > [!WARNING] > > **A recovery is public.** It's an ordinary on-chain payment back to the paying wallet, which can > link that wallet to the one it was paying. Tell your user before they sign. On JavaScript or TypeScript, [`recoverStuckFunds`](/sdks/core#recoverstuckfunds) runs the whole flow and checks each step. In Python, use [`recover_stuck_funds`](/sdks/python#recover_stuck_funds). ## The flow **1. Ask with the statusRef** `{ statusRef }` answers `sign` step 1: a `personal_sign` that opens a read-only session. Check it as on [`/execute`](/private-swaps#authorize-steps): the same three lines, never the extra "can also be used to submit transactions" line. **2. Prove the wallet paid** Send `{ statusRef, authorization, signature }` signed by the paying wallet. It answers `sign` step 2 (a recovery to sign) or `nothing`. **3. Sign the recovery** Check the typed data: domain `{ name: "Hinkal Enclave", chainId }` on the swap's source chain, `primaryType` `RecoverStuckBridgeBalance` or `WithdrawStuckUtxos`, `message.chainId` equal to the domain's, one `tokenAddress`, and `recipient` the paying wallet. Send `{ statusRef, authorization, signature }` again. It answers `done` with what was recovered. **4. Look again** A swap can leave more than one token. Send `{ statusRef, authorization }` with the `authorization` from `done` and no signature, until the answer is `nothing`. Each `authorization` is single-use and lasts 10 minutes. ## Request **statusRef** `string` *required* The `statusRef` of the Hinkal swap's `TRANSACTION`. **authorization** `string` From the previous answer. **signature** `string` The paying wallet's signature over the previous answer's `sign`. Leave it out after `done`. ```bash theme={null} curl -s -X POST https://app.ravn.exchange/api/v1/recover \ -H 'content-type: application/json' \ -d '{ "statusRef": "" }' ``` ## Response ```json sign theme={null} { "data": { "status": "sign", "authorization": "hk_…", "step": 1, "expiresAt": "2026-10-22T12:09:00.000Z", "sign": { "method": "personal_sign", "message": "Authorize Hinkal session\nSession ID: …\nPublic Key: …" } } } ``` ```json done theme={null} { "data": { "status": "done", "authorization": "hk_…", "recovered": [{ "chainId": 8453, "tokenAddress": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "amount": "49650000" }] } } ``` ```json nothing theme={null} { "data": { "status": "nothing" } } ``` `recovered` amounts are before Hinkal's recovery fee, so the wallet receives slightly less. `nothing` means nothing is stuck right now. A failed bridge shows up about 3 minutes after the payout fails, so try again a few minutes later if you called too soon. ## Errors | Code | Fix | | - | - | | `400 INVALID_REQUEST` | Not a Hinkal order id, a signature from the wrong wallet ("sign with the wallet that paid"), or an expired or used `authorization`: start again from step 1 | | `429 RATE_LIMITED` | 30 calls an hour per IP, or 300 per key. Wait the minutes the message gives | | `502 BUILD_FAILED` / `500 INTERNAL` | Hinkal can't be reached right now. Try again shortly | # POST /status Source: https://docs.ravn.exchange/api-reference/status https://app.ravn.exchange/openapi.json POST /api/v1/status Track a swap until it's final. Poll every swap until it's final. Besides your UI, it's how RAVN confirms the swap, and only confirmed swaps earn your fee. `GET` with query parameters also works, but `POST` is safer: a `quoteToken` can be too long for a URL. ## Request **quoteToken** `string` *required* The one `/execute` returned, not the one from `/quote`. **ref** `string` *required* The `statusRef` from `/execute` (or from `/submit-signature` on a `SIGNATURE`). On a `TRANSACTION` without one, the swap's transaction hash. **txHash** `string` EVM only: the hash of the last transaction you sent from `calls`, which proves your fee. Send it on every poll. See [Collecting your fee](/collecting-your-fee). ```bash theme={null} curl -s -X POST https://app.ravn.exchange/api/v1/status \ -H 'content-type: application/json' \ -d '{ "quoteToken": "", "ref": "" }' ``` ## Response **status** `string` One of the values below. **venue** `string` The venue handling the swap. **venueStatus** `string` The venue's own raw status, for debugging. **deliveredAmount** `string` Once final, what was delivered, when the venue reports it. **txHash** `string` Once final, the transaction that paid the user, when the venue names one. **tracking** `string` `"unavailable"` when `status` is `unknown`. | `status` | Meaning | What to do | | - | - | - | | `pending` | Waiting for the deposit, or not seen yet | Keep polling | | `processing` | Funds received, being filled | Keep polling | | `success` | Delivered | Stop | | `refunded` | Returned to the sender | Stop | | `failed` | Failed | Stop | | `expired` | The deadline passed. A refund is usually on its way | Keep polling, less often: it usually turns `refunded`, within hours (up to about a week on Eco Routes). An order that was never funded stays `expired` | | `not_found` | The venue hasn't seen it yet | Keep polling. If it stays, check `quoteToken` and `ref` | | `unknown` | This swap can't be tracked | Stop: polling won't change it | Poll every 5 to 10 seconds, or 10 to 15 for a Bitcoin deposit. A failed call (a `429`, a network blip) changes nothing: retry it. The swap is credited to the key that made the quote, even when later calls don't send that key. ```json theme={null} { "data": { "status": "success", "venue": "chainflip", "deliveredAmount": "18921340000", "txHash": "5x…" } } ``` # POST /submit-signature Source: https://docs.ravn.exchange/api-reference/submit-signature https://app.ravn.exchange/openapi.json POST /api/v1/submit-signature Place a signed gasless order. For a `SIGNATURE` execution: sign its `typedData`, then post the signature here. RAVN places the order with the venue. ## Request **quoteToken** `string` *required* The one `/execute` returned. **signature** `string` *required* The signature over `typedData`, hex. **approvalSignature** `string` The signature over `approvalData`, when the execution had one. ```bash theme={null} curl -s -X POST https://app.ravn.exchange/api/v1/submit-signature \ -H 'content-type: application/json' \ -d '{ "quoteToken": "", "signature": "0x…" }' ``` ## Response **statusRef** `string` Poll [`/status`](/api-reference/status) with it. **venue** `string` The venue that took the order. ```json theme={null} { "data": { "statusRef": "0x…orderUid", "venue": "cow" } } ``` ## Errors | Code | Fix | | - | - | | `422 ORDER_REJECTED` | The venue refused the order (`message` says why). If it's a duplicate, an earlier submit went through: don't sign again | | `502 BUILD_FAILED` | The venue errored, and the order may still have been placed. Check `/status` before signing a new one | | `503 VENUE_RATE_LIMITED` | Retry after `details.retryAfterSec` | # POST /submit-transaction Source: https://docs.ravn.exchange/api-reference/submit-transaction https://app.ravn.exchange/openapi.json POST /api/v1/submit-transaction Send a signed Solana transaction through RAVN. Only for a `TRANSACTION` that carries `submit`, which appears only on quotes sent with [`broadcastViaRavn: true`](/bitcoin-and-solana#broadcastviaravn). > [!WARNING] > > **Never broadcast a transaction that came with `submit`.** Sign `transaction.serialized` without > sending it, and post it here. RAVN checks it, then sends it (or hands it to Jupiter to land). > Broadcast yourself, it can fail to land, or the funds can end up stuck at the venue. * A Layerswap memo payment: the wallet must already hold the amount and SOL for fees. Post it within about a minute, before its blockhash expires. * A Jupiter order: post it within seconds (market makers hold a price about 20 seconds), and let the call run up to 2 minutes while it lands. ## Request **quoteToken** `string` *required* The one `/execute` returned with this transaction. **signedTransaction** `string` *required* `transaction.serialized`, signed by the user's wallet, base64. Sign it as returned: any change is refused. ```bash theme={null} curl -s -X POST https://app.ravn.exchange/api/v1/submit-transaction \ -H 'content-type: application/json' \ -d '{ "quoteToken": "", "signedTransaction": "" }' ``` ## Response **txHash** `string` The landed transaction's signature. Poll `/status` with the execution's `statusRef`, or with this `txHash` when there was none. ```json theme={null} { "data": { "txHash": "5igSig…" } } ``` Posting the same `signedTransaction` again is always safe: it lands once, and a retry returns the same `txHash`. ## Errors | Code | Fix | | - | - | | `400 INVALID_REQUEST` | Nothing was sent. The transaction isn't signed, was changed, or a smart-contract wallet rewrote it (sign with a standard wallet). Or `quoteToken` isn't the one from this `/execute` answer | | `422 ORDER_REJECTED` | Nothing was sent (expired blockhash, too little SOL, or Jupiter refused). Call `/execute` again, or quote again if past `expiresAt` | | `502 BUILD_FAILED` | It may already have been sent. Retry with the **same** `signedTransaction` until you get `200` or `422`. Don't sign a new one before then | # GET /tokens/resolve Source: https://docs.ravn.exchange/api-reference/tokens Look up any token by address. Reads a token's symbol, name and decimals on-chain, for "paste any address" flows. **chainId** `integer` *required* The token's chain. **address** `string` *required* The token address or Solana mint. ```bash theme={null} curl -s "https://app.ravn.exchange/api/v1/tokens/resolve?chainId=1&address=0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" ``` ## Response ```json theme={null} { "data": { "token": { "symbol": "USDC", "name": "USD Coin", "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "decimals": 6, "chainId": 1, "isNative": false } } } ``` Returns `400 UNSUPPORTED_TOKEN` when the address isn't a token on that chain. # GET /tokens Source: https://docs.ravn.exchange/api-reference/tokens-list RAVN's token list for a chain. Fill a token picker without keeping your own list. A token being listed doesn't guarantee a route: a quote is the only check. Unlisted tokens still swap by address (see [`/tokens/resolve`](/api-reference/tokens)). **chainId** `integer` *required* The chain to list. ```bash theme={null} curl -s "https://app.ravn.exchange/api/v1/tokens?chainId=1" ``` ## Response An array of `{ symbol, name, address, decimals, chainId, isNative, logoUrl? }`. ```json theme={null} { "data": [ { "symbol": "ETH", "name": "Ether", "address": "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", "decimals": 18, "chainId": 1, "isNative": true }, { "symbol": "USDC", "name": "USD Coin", "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "decimals": 6, "chainId": 1, "isNative": false } ] } ``` An unsupported `chainId` returns `400 INVALID_REQUEST`. # Authentication Source: https://docs.ravn.exchange/authentication API keys and rate limits. Every endpoint works with no key, so you can call it right now. A free key raises your rate limit and lets you charge your own fee. [Get one in 30 seconds](/tools/get-api-key). Send it as a header: ``` x-api-key: rvn_live_your_key ``` | Tier | Rate limit | `/status` polls | How to get it | | - | - | - | - | | No key | 30 requests/min per IP | 120/min | Nothing to do | | Self-serve key | 120 requests/min | 480/min | [Get an API key](/tools/get-api-key) | | Enterprise key | Custom | 4× your limit | [Contact RAVN](https://x.com/ravnexchange) | `/status` polls have their own budget, so tracking swaps never eats into quotes and executes. ## Public and secret keys Each self-serve key comes as a pair, shown once at signup. | | Public key `rvn_live_…` | Secret key `rvn_sk_…` | | - | - | - | | Quote, execute, submit, status, tokens, chains | Yes | Yes | | Change fee, payout addresses, webhook, allowed origins | No | Yes | | Rotate the secret key | No | Yes | | Where it belongs | Anywhere, browsers included | Your server only | Both count against the same rate limit and earn the same fee. RAVN stores only a hash of the secret key, so it can't show it again. Leaked it? Rotate it with [`POST /v1/keys/secret`](/api-reference/keys#rotate-your-secret-key): the old one stops working within a minute. **Lock your public key to your sites.** Set `allowedOrigins` with [`PATCH /v1/keys`](/api-reference/keys). Browser requests from any other site are refused. Requests without an `Origin` header (your servers) always work. > [!NOTE] > > **Key from before secret keys existed?** It keeps full rights until **1 December 2026**. Claim its > secret now with `POST /v1/keys/secret`, from your server, sending the current key: from then on the > current key is your public key. Claim it first if the key is in browser code, since only one claim > is allowed. If the claim is refused, contact RAVN. ## Browsers and headers CORS is enabled on every endpoint, so browser apps can call the API directly. Every response carries `x-request-id`: quote it when you contact support. Rate-limited endpoints also send: | Header | Meaning | | - | - | | `X-RateLimit-Limit` | Requests allowed per minute on this budget | | `X-RateLimit-Remaining` | Requests left in the current window | | `X-RateLimit-Reset` | When the window resets, in epoch seconds | | `Retry-After` | On a `429`: seconds to wait | ## Errors | Code | When | | - | - | | `401 UNAUTHORIZED` | The key doesn't exist | | `403 FORBIDDEN` | A public key where the secret key is needed, or a site outside `allowedOrigins` | | `429 RATE_LIMITED` | Over your limit. Wait `details.retryAfterSec` | | `503 UNAVAILABLE` | RAVN can't check keys for a moment. Your key is fine: retry after `details.retryAfterSec` | # Bitcoin and Solana Source: https://docs.ravn.exchange/bitcoin-and-solana What's different when a swap starts or ends on native Bitcoin or Solana. Bitcoin is chain `-1` and Solana is chain `-2`. The quote, execute and status calls are the same as on any chain. This page covers what your wallet code does differently. ## Bitcoin **Buying BTC.** Set `destinationAddress` to the user's Bitcoin address. The execution is whatever the source chain needs, usually a `TRANSACTION` or a `DEPOSIT`. **Selling BTC** always returns a `DEPOSIT`: the user sends BTC to `deposit.address`. * Set `userAddress` to the Bitcoin address the BTC is sent from. If it isn't a Bitcoin address, also set `refundAddress` to one. Set both on the quote: some venues won't take them later. * From a native SegWit (`bc1q…`) `userAddress`, the answer includes `deposit.psbt`: the deposit, your fee as a second output and change back to the sender, built from their confirmed coins. Sign and broadcast it as is. * Without `deposit.psbt` (another address type, too little balance), pay exactly `deposit.amount` to `deposit.address`. When the execution has a `fee`, add a second output of `fee.amount` sats to `fee.address` in the **same** transaction. One deposit per transaction. * Or show the address and a QR code and let the user send from any wallet. A Bitcoin deposit usually takes 30 minutes or more to settle. Poll `/status` every 10 to 15 seconds. Quote a token to check that it routes from native BTC. [`/tokens/btc-coverage`](/api-reference/btc-coverage) ranks RAVN's tokens by how many BTC venues list them. ## Solana Native SOL is the mint `So11111111111111111111111111111111111111112`. **A `TRANSACTION`** carries `transaction.serialized`, a base64 versioned transaction. Sign it and send it with `confirmed` commitment: it's built on a confirmed blockhash, so a `finalized` preflight reports `BlockhashNotFound` for its first \~13 seconds. Any fee is already inside it. Send it from the user's own wallet: a smart account (Squads-style) that runs it inside its own program pays the fee where RAVN can't see it. **A `DEPOSIT`** is a transfer of `deposit.amount` to `deposit.address`. When it carries your fee, `deposit.transaction` is the deposit and the fee as one unsigned transaction: sign and send it within a minute, before its blockhash expires. Missed the minute? Call `/execute` again with a new `Idempotency-Key` (the same key returns the same expired transaction) and send only to the **new** deposit. Building it yourself? Put the fee in the **same** transaction: a System transfer for SOL, or `createAssociatedTokenAccountIdempotent` then `transferChecked` (under the mint's own token program, such as Token-2022) for a token. One deposit per transaction. `/status` takes `txHash` only for EVM transactions. Don't send a Solana signature there. ### `broadcastViaRavn` Set `broadcastViaRavn: true` on the quote if your app can post a signed Solana transaction back to RAVN instead of broadcasting it. It adds routes that often price better: * Layerswap memo payments: a Solana wallet's USDC into native BTC, or USDG into Robinhood Chain stocks, with no account rent. Often the best price under about \$200. * Jupiter orders a market maker or gas sponsor also signs. Long-tail tokens can price 7 to 33 bp better, and a wallet short of SOL can still swap. This doesn't apply when RAVN adds your fee to the order: fees under 50 bps, and some pairs above. Then the market maker or gas sponsor can't sign it. A `TRANSACTION` that then carries `submit` must **not** be broadcast. Sign it and post it to [`/submit-transaction`](/api-reference/submit-transaction), within seconds for a Jupiter order. One without `submit` you broadcast as usual. # Changelog Source: https://docs.ravn.exchange/changelog Every change to the API, newest first, and the rules for changing it. Every change to the API's shape since 2 October 2026 is listed here, newest first. Subscribe with the RSS button above. SDK releases are in the [SDK changelog](https://github.com/ravndex/ravn-sdk/blob/main/CHANGELOG.md). ## Versions The API lives at `/api/v1`. Its version is the date of the latest entry below, for example `2026-11-11`. Every response sends it in the `ravn-version` header and `meta.version`, and the [OpenAPI spec](/api-reference/openapi) carries it as `info.version`. ## What can change in v1 Within `/v1` the API only grows. Expect: * New endpoints, new optional request fields and new response fields. Ignore fields you don't know. * New error codes. Show the `message` of a `code` you don't know. * New `status` values. Treat one you don't know like `expired` (see [`/status`](/api-reference/status)). * New chains, venues and tokens, listed on [Supported chains & venues](/supported). Within `/v1` we don't remove or rename a field or endpoint, change a field's type or meaning, make a request field required, or send an `executionType` you haven't opted into (`AUTHORIZE` needs `authorizeSteps`). Every change to the API's shape is checked against these rules before it ships. ## Deprecations When something has to go, we: 1. Post it here at least 90 days before it stops working, with that date. 2. Mark it `deprecated` in the OpenAPI spec and the SDK, so your editor strikes it through. 3. Send the `Deprecation` and `Sunset` headers on every call that uses it. A security fix can move faster. One did: keys issued before public and secret keys existed (21 October 2026\) keep full rights only until 1 December 2026, announced on 21 October (see that entry). ## /v2 A `/v2` comes only for a change that can't be made by adding. `/v1` keeps working for at least 12 months after `/v2` ships. ## Changes **2026-11-11** * With [`call.exactAmount`](/api-reference/quote#call-a-contract-after-the-swap), your user sends only what the amount takes: `inputAmount` is the most, and `input.amount` what they send. This corrects `call` the day after it shipped, before any integrator could use it. * Alternatives and streamed prices carry `inputAmount`. * [`call`](/api-reference/quote#call-a-contract-after-the-swap) works from Bitcoin, with your fee taken inside the route. * [`/x402/quote`](/ai-agents/x402-payments) answers `400 INVALID_REQUEST` to `call`, which it never carried. **2026-11-10** * [`/quote`](/api-reference/quote#call-a-contract-after-the-swap) takes `call`: the swap ends with a call into your registered contract, such as a vault deposit for your user. **2026-11-09** * `ravn-version` and `meta.version` name the API's version: the date of its latest change. They said `2024-01` before. * The OpenAPI spec describes the streamed prices of [`/quote`](/api-reference/quote#streamed-response) (`PriceDTO`) and the answer of [`/recover`](/api-reference/recover) (`RecoverDTO`). * A streamed [`/quote`](/api-reference/quote#streamed-response) sends `preview` lines: an early price from RAVN's own multi-step route, before its `settled`. **2026-10-30** * A pair RAVN doesn't swap answers `400 INVALID_REQUEST` with the reason, not `500 INTERNAL`. **2026-10-28** * `/v1` accepts the `x-ravn-sdk` header from browsers: the SDK names its version in it. **2026-10-25** * `venue.logoUrl`: each venue's logo, on quotes, alternatives, streamed prices, `hops` and [`/health`](/api-reference/health). **2026-10-23** * `transaction.gasLimit`, and `gasLimit` on the swap's entry in `calls`: send the EVM transaction with it. See [`/execute`](/api-reference/execute). **2026-10-22** * Hinkal [private swaps](/private-swaps): `authorizeSteps` on `/quote`, `AUTHORIZE` steps at `/execute`, and [`POST /recover`](/api-reference/recover) for a failed one. **2026-10-21** * [Public and secret keys](/authentication#public-and-secret-keys): `POST /keys/secret`, and `403 FORBIDDEN` for a public key where the secret key is needed. A key from before keeps full rights until 1 December 2026. * `expectedOutputAmount` on the quote and each alternative, `slippage.expectedShortfallBps`, and `pickable` on alternatives. * `approval.spender` names the contract the approval's calldata approves. **2026-10-20** * `"stream": true` on [`/quote`](/api-reference/quote#streamed-response): each venue's price as it lands. * `quoteToken` is usually a short id. * `/execute` prices a quote again up to 10 minutes past `expiresAt`, and answers `410 QUOTE_EXPIRED` when it no longer meets the minimum shown. **2026-10-19** * `excludeVenues` and `onlyVenues` cover every step of a multi-step route. **2026-10-18** * Executions come ready to sign: `calls` and `batch` on EVM, `deposit.psbt` for Bitcoin, and `deposit.transaction` for a Solana deposit that carries your fee. **2026-10-17** * `swapId` on every execution, the `Idempotency-Key` header on `/execute`, and [webhooks](/webhooks) for every final swap. * `timeoutMs` on `/quote`: how long the race waits for venues. * `approval` comes only when the wallet needs a new allowance, and carries `reset` when the token needs its allowance set to 0 first. * `sandbox: true` on the execution of a [sandbox](/sandbox-mode) quote. * [Rate-limit headers](/authentication#browsers-and-headers) and `503 UNAVAILABLE`. **2026-10-16** * `onlyVenues` on `/quote`: race only the venues you list. **2026-10-14** * `fee` on an execution: your fee, when the route collects it beside the swap or the deposit. See [Collecting your fee](/collecting-your-fee). * A missing address at `/execute` answers `400 INVALID_REQUEST` naming the field, not `502 BUILD_FAILED`. **2026-10-13** * `broadcastViaRavn` on `/quote` and [`POST /submit-transaction`](/api-reference/submit-transaction): more Solana routes, sent through RAVN. * `allowNoMinimum` on `/quote`: let routes with no minimum race beside your `slippageBps`. * A `refundAddress` given at `/execute` answers `400 INVALID_REQUEST` where the venue would drop it. **2026-10-12** * Every alternative carries its own `expiresAt`, and `expiresAt` is always a real time. * `txHash` on [`/status`](/api-reference/status): the transaction that proves your fee. * `/submit-signature` answers a venue's refusal with `422 ORDER_REJECTED` and its rate limit with `503 VENUE_RATE_LIMITED`, not `500`. **2026-10-11** * `/execute` answers `502 BUILD_FAILED` when the venue can't build the swap, and `503 VENUE_RATE_LIMITED` when it is rate-limiting RAVN, not `500`. **2026-10-02** * `slippage.noMinimum`: the route holds no guaranteed minimum. Alternatives carry `slippage` too. # Collecting your fee Source: https://docs.ravn.exchange/collecting-your-fee Two things your code does so every swap with your fee pays you. You set a fee on your key once, on top of every swap, and keep 60% of it ([Pricing](/pricing)). It applies to every call that sends that key as `x-api-key`. A swap then pays you only when RAVN can prove it, and that takes two things from your code: 1. **Pay the `fee` an execution asks for**, when it has one. 2. **Poll `/status` until the swap is final**, reporting the fee's transaction. Skip either and the swap still fills for your user, but nothing is owed to you on it. > [!TIP] > > On JavaScript or TypeScript, [`executeAndTrack`](/sdks/core#executeandtrack) does both. The > [Quickstart](/quickstart) script does both too. ## 1. Pay `fee` when the execution has one Most routes take your fee inside the swap, so there's nothing extra to pay. A few can't, and then `/execute` adds a `fee` object. The ready-made payload already includes it: | The swap starts on | Send | `fee` | | - | - | - | | An EVM chain | `calls`, in order. Your fee is the last call | its own transaction, sent after the swap succeeds | | Bitcoin | `deposit.psbt` | an extra output of the deposit transaction | | Solana, a deposit | `deposit.transaction` | inside the deposit transaction | | Solana, a transaction | `transaction.serialized`, as returned | already inside it | Rules that keep the fee provable: * Send the fee exactly as given, and only after the swap or deposit transaction has succeeded. Sending `calls` in order does that. A fee paid on a swap that reverts, or that the venue later refunds, stays with RAVN. * In a wallet batch (`batch: true`), put one fee-bearing swap per batch. * A native-coin fee (ETH, say) must be a plain transaction of its own unless `batch` is `true`. A contract wallet that can't send a plain transaction (a Safe, an ERC-4337 account) can't pay it. * Building a Bitcoin or Solana deposit yourself? The fee must go in the **same** transaction as the deposit, or RAVN can't find it. A Bitcoin fee under 546 sats isn't charged. ## 2. Report the swap to `/status` until it's final Poll [`/status`](/api-reference/status) with: * `quoteToken`: the one `/execute` returned. * `ref`: the `statusRef` (from `/execute`, or `/submit-signature` for `SIGNATURE`), else the swap's transaction hash. * `txHash`: on an EVM chain, the hash of the **last** transaction you sent from `calls`. That's the one carrying your fee (or the whole batch). Never a batch id or an ERC-4337 `userOpHash`. Not needed on Bitcoin or Solana: RAVN finds the fee inside the deposit. Send `txHash` on every poll. Stop at `success`, `refunded` or `failed`. Keep polling through `expired` (a refund is on its way) and `not_found` (the venue hasn't seen it yet). > [!NOTE] > > RAVN stops waiting for a fee a day after `/execute`: a fee reported later earns nothing. A > delivered swap can read `processing` for up to 15 minutes while RAVN confirms the fee transaction, > so keep polling. [Webhooks](/webhooks) tell you a swap is final but don't replace these polls. # Errors Source: https://docs.ravn.exchange/errors Every error code, what it means and how to fix it. Failures return `{ error: { code, message, details? }, meta }`. Branch on `code`: `message` can change. Log `meta.requestId` (also the `x-request-id` header) and quote it to support. | Code | HTTP | Meaning | Fix | | - | - | - | - | | `INVALID_REQUEST` | 400 | A field failed validation, or RAVN doesn't swap this pair (for example BTC to BTC) | Read `details.fieldErrors` and fix the named fields, or change the pair | | `UNSUPPORTED_TOKEN` | 400 | The token isn't valid on that chain | Check the address and chain ID | | `QUOTE_INVALID` | 400 | The `quoteToken` is malformed or altered | Pass it exactly as received, or quote again | | `QUOTE_NOT_EXECUTABLE` | 400 | The quote was a preview (`executable: false`) | Quote again with the addresses in `details.missing` | | `UNAUTHORIZED` | 401 | The `x-api-key` doesn't exist | Fix the key, or send none | | `FORBIDDEN` | 403 | A public key where the secret key is needed, or a site outside `allowedOrigins` | Use the [secret key](/authentication#public-and-secret-keys) from your server, or add the site | | `NO_LIQUIDITY` | 404 | No venue can serve this pair or amount | See below | | `NOT_FOUND` | 404 | No such resource for this caller | Check the path, and that the field applies to your key type | | `QUOTE_EXPIRED` | 410 | The quote is too old, or re-priced below its minimum | Quote again | | `ORDER_REJECTED` | 422 | The venue or Solana refused a submitted order or transaction | Read `message`. A duplicate-order refusal means an earlier submit went through: don't sign again. Otherwise execute or quote again | | `RATE_LIMITED` | 429 | Over your rate limit | Wait `details.retryAfterSec`. A [key](/tools/get-api-key) raises the limit | | `INTERNAL` | 500 | An unexpected or venue-side error | Retry. If it persists, contact support with the `requestId` | | `BUILD_FAILED` | 502 | The venue couldn't build or take the swap right now | On `/execute`: quote again. On a submit: [check before signing again](#submits) | | `VENUE_RATE_LIMITED` | 503 | The venue is rate-limiting RAVN | Retry the same call after `details.retryAfterSec` | | `UNAVAILABLE` | 503 | RAVN can't check keys or look up the quote for a moment | Retry the same call after `details.retryAfterSec` | | `NOT_CONFIGURED` | 503 | The endpoint isn't enabled yet (for example x402) | Use the free endpoints | ## NO\_LIQUIDITY `details` says why: ```json theme={null} { "error": { "code": "NO_LIQUIDITY", "message": "No liquidity available for this pair/amount", "details": { "routeType": "EVM_CROSS_CHAIN", "eligibleVenues": ["across", "relay", "mayan"], "excludedVenues": [] } } } ``` * `eligibleVenues` empty: no venue serves this chain pair. Check [Supported chains & venues](/supported). * `excludedVenues` lists what your `excludeVenues` or `onlyVenues` left out. If it covers the eligible venues, you excluded the route yourself. * Otherwise the venues had nothing at this amount. Try a different amount, or check [`/health`](/api-reference/health). ## Submits After a `BUILD_FAILED` from a submit, the order or transaction may already be live: * `/submit-signature`: check `/status` before signing a new order. * `/submit-transaction`: retry with the **same** `signedTransaction` until you get `200` or `ORDER_REJECTED`. Never sign a new one before that. # Execution types Source: https://docs.ravn.exchange/execution-types What /execute returns, and what to do with each answer. `/execute` answers with one `executionType`. Your code branches on that one field. | `executionType` | The user | Then poll `/status` with `ref` = | | - | - | - | | `TRANSACTION` | Signs and sends a transaction | `statusRef` if present, else the swap's transaction hash | | `SIGNATURE` | Signs typed data (no gas). You post it to `/submit-signature` | the `statusRef` `/submit-signature` returns | | `DEPOSIT` | Sends the input token to an address | `statusRef` | Every answer carries a `quoteToken`. Use **that** one, not the one from `/quote`, for `/submit-signature`, `/submit-transaction` and `/status`. > [!TIP] > > On JavaScript or TypeScript, [`executeAndTrack`](/sdks/core#executeandtrack) handles all of this > for you, on every chain. ## TRANSACTION ```json theme={null} { "executionType": "TRANSACTION", "quoteToken": "…", "approval": { "to": "0x…", "data": "0x095ea7b3…", "value": "0", "chainId": 8453, "spender": "0x…", "amount": "25000000" }, "transaction": { "to": "0x…", "data": "0x…", "value": "0", "chainId": 8453, "gasLimit": "310000" }, "calls": [ { "to": "0x…", "data": "0x095ea7b3…", "value": "0", "chainId": 8453 }, { "to": "0x…", "data": "0x…", "value": "0", "chainId": 8453, "gasLimit": "310000" } ], "batch": true } ``` **On an EVM chain**, send `calls` in order, each once the one before it has succeeded, and stop if one reverts. (In the rare case `calls` is missing, send the same fields in that order yourself.) `calls` is everything to send, already in order: `approval.reset`, `approval`, the swap (`transaction`), then your fee (`fee.transaction`) when one applies. * Send the swap with `transaction.gasLimit` as its gas limit when it's set (viem: `gas: BigInt(gasLimit)`). * When `batch` is `true`, you may send all of `calls` in one atomic wallet batch (EIP-5792 `wallet_sendCalls`) instead. Simulate the batch first and fall back to one by one if it fails. **On Solana** (`chainId: -2`), `transaction.serialized` is a base64 versioned transaction. Sign it and send it from the user's own wallet, with `confirmed` commitment. Any fee is already inside it. **With `submit`.** Only on quotes sent with `broadcastViaRavn: true`. Don't broadcast it: sign `transaction.serialized` and post it to [`/submit-transaction`](/api-reference/submit-transaction). ## SIGNATURE ```json theme={null} { "executionType": "SIGNATURE", "quoteToken": "…", "approval": { "to": "0x…", "data": "0x095ea7b3…", "value": "0", "chainId": 1, "spender": "0x…", "amount": "25000000" }, "typedData": { }, "approvalData": { }, "submit": { "url": "/api/v1/submit-signature" } } ``` 1. Send `approval` (and `approval.reset` first, when present) and wait for it to be mined. Gasless orders still pull the tokens through an allowance: without it the order is accepted and then silently never fills. 2. Sign `typedData`. When `approvalData` is present, sign it too. 3. Post both signatures to [`/submit-signature`](/api-reference/submit-signature). It returns the `statusRef` to poll with. ## DEPOSIT ```json theme={null} { "executionType": "DEPOSIT", "quoteToken": "…", "deposit": { "address": "…", "amount": "1000000000000000000", "chainId": 1, "expiresAt": "2026-10-02T12:15:00.000Z" }, "statusRef": "…" } ``` Send exactly `deposit.amount` of the quote's **input** token to `deposit.address`. Ready-made versions come with the answer: | Paying from | Send | | - | - | | An EVM chain | `calls`: the transfer, then your fee when one applies | | Bitcoin (a `bc1q…` sender) | `deposit.psbt`: sign and broadcast it as is. It pays the deposit, your fee and the change | | Solana, with your fee | `deposit.transaction`: the deposit and the fee in one transaction. Sign and send it within a minute | No approval is needed. When `deposit.expiresAt` is set, send the deposit right away and never after that time: some routes need it to have **arrived** by then. Send a native-coin deposit from a regular wallet, not from a smart contract: some venues don't credit coin a contract moves. You can also show the address and a QR code and let the user send it from any wallet. That's how native Bitcoin is usually paid. ## Approvals `approval` is a ready-to-send ERC-20 `approve(spender, amount)`, sent to the token contract. * Wait for it to be **mined** before the swap. Otherwise the swap reverts and the user pays gas for nothing. * RAVN leaves it out when the user's allowance already covers the swap. When RAVN couldn't read the allowance it's included anyway; skip it if your own read shows enough. * That read sees only mined transactions. Run one swap per token and spender at a time: a second swap started while the first is pending can come back without the `approval` it needs. * `approval.reset` appears for tokens like Ethereum USDT that can't change one non-zero allowance to another. Send it first. * The spender is `approval.spender`. Don't assume it's `transaction.to`. * `unlimitedRecommended: true` means the venue would rather you approve once for a large amount. `data` still approves the exact amount; raising it is your call. ## AUTHORIZE steps (Hinkal) A fourth type, only for [Hinkal](/private-swaps#hinkal) private swaps you opt into with `authorizeSteps: true`. The paying wallet signs twice before the `TRANSACTION` comes. See [Private swaps](/private-swaps#authorize-steps). # FAQ Source: https://docs.ravn.exchange/faq Common questions and quick fixes. > [accordion] Is RAVN custodial? Does it use bridges? > > No custody: the user signs or sends directly to the venue. RAVN runs no bridge of its own, and > the user always receives the real token, never a wrapped copy (unless they asked for one, like > WBTC). NEAR Intents holds the deposit as a matching token on NEAR for the minutes its swap takes; > leave it out with `excludeVenues: ["near_intents"]` if you'd rather. > [accordion] Do I need an API key? > > No. Every call works without one, at 30 requests a minute per IP. A [free > key](/tools/get-api-key) raises that to 120 and lets you charge your own fee. > [accordion] How do fees work? > > You put your own fee on top of every swap, up to 1%. RAVN shares it with you: you keep 60%, RAVN > 40% (a few venues take their own cut first). RAVN adds no fee of its own. See > [Pricing](/pricing) and [Collecting your fee](/collecting-your-fee). > [accordion] Can users swap without gas? > > Yes, on gasless routes (`SIGNATURE`): the user signs a message and a solver pays the gas. A token > approval may still be needed once. > [accordion] Why is my quote executable: false? > > It was priced without an address the venue needs. Quote again with `destinationAddress` (and > `refundAddress` when selling BTC from a non-Bitcoin `userAddress`). `/execute` names the missing > one in `details.missing`. > [accordion] Why did /execute return QUOTE\_EXPIRED? > > The quote passed `expiresAt` and, priced again, no longer met its minimum. Quote again. Execute > soon after quoting, and send an `Idempotency-Key` so a retry doesn't build twice. > [accordion] A delivered swap still says processing > > When your fee was paid beside the swap, RAVN confirms that transaction first, for up to 15 > minutes after `/execute`. Keep polling with `txHash`. > [accordion] /status keeps saying not\_found > > Normal for the first minutes: the venue hasn't seen the swap yet. If it stays, check you're > polling with the `quoteToken` from `/execute` and the right `ref`. > [accordion] Selling a wallet's whole native balance fails > > The swap needs gas on top of what it sends. When the execution has `transaction.gasLimit`, > leave `gasLimit` × the max fee per gas unspent (plus the L1 fee on OP-stack chains). > [accordion] How do I get help? > > Every response has a `requestId` (also the `x-request-id` header). Send it with your question > via [ravn.exchange](https://ravn.exchange) or [@ravnexchange](https://x.com/ravnexchange), and we > can trace the exact request. # RAVN Integrator API Source: https://docs.ravn.exchange/introduction One API to swap any asset across EVM chains, Solana and native Bitcoin. RAVN races market makers, intent networks and cross-chain solvers on every quote and returns the best route in one format. Your users swap across EVM chains, Solana and **native Bitcoin**, and always receive the real token, never a wrapped copy. > [card] [Quickstart](/quickstart) > > Swap ETH to SOL end to end in a few minutes. > [card] [Widget](/sdks/widget) > > A drop-in swap UI that uses your page's wallet. > [card] [SDKs](/sdks/overview) > > TypeScript, React and Python clients. > [card] [AI agents](/ai-agents/overview) > > A free MCP server, or pay per call with x402. ## How it works ```mermaid theme={null} flowchart LR Q["POST /quote"] --> R{{"Every eligible venue\nraces in parallel"}} R --> E["POST /execute\nwhat the wallet signs or sends"] E --> S["The user signs or sends\ndirectly to the venue"] S --> T["POST /status\nuntil it's final"] ``` 1. **Quote.** One request races every venue that can serve the pair and returns the best route, plus an opaque `quoteToken`. 2. **Execute.** RAVN returns exactly what to do, as one of three `executionType`s: sign and send a `TRANSACTION`, sign a gasless `SIGNATURE`, or send a `DEPOSIT` to an address. 3. **Track.** Poll `/status` until the swap is final. RAVN never holds funds: the user signs or sends directly to the venue. RAVN runs no bridge of its own. On NEAR Intents routes, the deposit is held as a matching token on NEAR for the minutes the swap takes. Every quote names its venue. ## Pricing Put your own fee on top of every swap, up to 1%. RAVN shares it with you: **you keep 60%, RAVN 40%** (a few venues take their own cut first). RAVN adds no fee of its own. See [Pricing](/pricing). ## Base URL ``` https://app.ravn.exchange/api/v1 ``` No key is needed to start. [Get a free key](/tools/get-api-key) for a higher rate limit and your own fee. Conventions and every endpoint: [API reference](/api-reference/overview). # Pricing Source: https://docs.ravn.exchange/pricing Put your own fee on top of every swap. RAVN shares it with you, 60/40. **Put your own fee on top of every swap**, from 0 to 1%. It sits on top of the best price RAVN finds, and every quote already shows your user's output after it. RAVN adds no fee of its own. **RAVN shares that fee with you: you keep 60%, RAVN keeps 40%.** RAVN's share comes out of your fee, never on top of it, so it costs your users nothing extra. A few venues take their own cut first ([below](#revenue-share)). Payouts are moving to USDC ([Getting paid](#getting-paid)). > [!NOTE] > > **Example.** You set 50 bps. On a \$10,000 swap your user pays a \$50 fee. You receive \$30 and RAVN > \$20. With no key, or a key with no fee set, swaps carry no fee of yours. Gas and a venue's own costs are part of the quoted price, not RAVN fees. (In RAVN's own app, public swaps are free and private swaps carry RAVN's 0.1% fee, except from Bitcoin.) ## Set your fee Any self-serve key can set its fee, from 0 to 100 bps (1%), with your secret key: ```bash theme={null} curl -s -X PATCH https://app.ravn.exchange/api/v1/keys \ -H 'x-api-key: rvn_sk_your_secret_key' \ -H 'content-type: application/json' \ -d '{ "feeBps": 20 }' ``` It applies to every call that sends your key, over REST, the [widget](/sdks/widget), the [MCP server](/ai-agents/mcp-server) or [x402](/ai-agents/x402-payments). Enterprise fees are set by RAVN as part of your agreement. To make sure each swap pays it, see [Collecting your fee](/collecting-your-fee). ## Revenue share On almost every venue the split is 60% to you, 40% to RAVN. A few venues take their own cut of the fee first, and the rest is split in the same proportion: | Venue | You | RAVN | The venue | | - | - | - | - | | Every other venue | 60% | 40% | none | | NEAR Intents (public swaps) | 30% | 20% | 50% | | Jupiter, fees of 50 bps and up that Jupiter collects | 48% | 32% | 20% | | OKX DEX | 48% | 32% | 20% | | Fynd | 48% | 32% | 20% | | CoW Protocol | 45% | 30% | 25% | A few routes can't carry a fee at all: Eco Routes from Solana or Bitcoin, and Layerswap and Houdini Swap from Bitcoin. Their quotes show `fee.supported: false`. In the widget, swaps from Bitcoin carry no fee either. > [!NOTE] > > **NEAR Intents** takes its own fee: 20 bps, or 1 bp when both tokens are stablecoins or the same > asset. A NEAR quote's `fee` shows the total, so it never reads `bps: 0`. > > * No fee of yours: users pay NEAR's 20 bps. > * Public swaps with your fee: NEAR takes half of it, but at least 20 bps. From 40 bps (2 bps on > those pairs) users pay exactly your fee. Below that they pay half your fee plus 20 bps: a 5 bps fee > comes to 23. > * Private swaps: users pay your fee plus NEAR's 20 bps. ## The fee on each quote Every quote, and each of its `alternatives`, carries: ```json theme={null} "fee": { "bps": 20, "amount": "1000000", "token": { }, "supported": true } ``` * `bps`: the fee applied to this quote. `0` when your key has none or the route can't carry it. * `amount`: the fee in `token`'s smallest unit. The quoted output is already net of it. * `token`: the token the fee is taken in. Usually the output token, but some routes take it in the input token or in USDC on the destination chain, so read it from each quote. * `supported`: `false` when this route can't carry a fee. Read these from each quote rather than assuming they match your key's `feeBps`. ## Getting paid Register a payout address per ecosystem with [`PATCH /v1/keys`](/api-reference/keys): `payoutAddresses.evm`, `.solana`, `.thorchain` and `.bitcoin`. Without one, that ecosystem's balance accrues until you add it. * A new or changed payout address takes effect **24 hours** after you set it. Until then payouts go to the previous address. This keeps a leaked key from redirecting your payouts. * Only swaps that reached `settled` count, which is why you [poll every swap](/collecting-your-fee) to a final status. Sandbox swaps never count. * **Payouts are moving to USDC.** Most of your share will be paid in USDC instead of the token each fee was collected in. There is no payout on 1 November 2026, and the date of the first USDC payout is still to come. Until then your share keeps accruing. A few venues pay RAVN their own way, and these stay as they are. Your share follows once RAVN has received it: | Venue | You're paid in | Minimum | | - | - | - | | THORChain | RUNE | \$2 | | Bebop | ETH on Ethereum, after Bebop's monthly invoice | \$5 | | CoW Protocol | The chain's native coin, after CoW's weekly payment | \$5 | | NEAR Intents (public swaps) | USDC on Base, as NEAR's fee pool pays out | \$5 | | Fees in BTC, paid beside a Bitcoin deposit or out of a swap's BTC output | BTC, to `payoutAddresses.bitcoin` | 546 sats | > [!WARNING] > > **Chainflip pays you on-chain, to your first EVM payout address.** Once your key has a fee and an > EVM payout address, RAVN registers you as a Chainflip affiliate. Your share is withdrawn in USDC to > the EVM payout address in effect at your first fee-bearing Chainflip swap, and Chainflip never lets > it change. Set the right EVM payout address before routing Chainflip swaps. ## Fee by access path | Access | Swap fee | Cost of the call | | - | - | - | | No key | 0 bps | Free, rate-limited | | Self-serve key | Yours, 0 to 100 bps | Free | | Enterprise key | Agreed with RAVN | Free or agreed | | [MCP server](/ai-agents/mcp-server) | Your key's, when you pass one | Free | | [x402](/ai-agents/x402-payments) | Your key's, when you also send `x-api-key`; else 0 | \$0.001 per quote, \$0.01 per execute, in USDC | Need custom terms or rate limits? DM [@ravnexchange](https://x.com/ravnexchange) or reach out via [ravn.exchange](https://ravn.exchange). # Private swaps Source: https://docs.ravn.exchange/private-swaps Swaps whose deposit and payout aren't directly linked on-chain. Set `confidential: true` on [`/quote`](/api-reference/quote). The race narrows to venues with a private settlement path, and the best output wins. If none can quote, you get `404 NO_LIQUIDITY`, never a public fill. | Venue | Cost vs a public swap | Speed | Notes | | - | - | - | - | | NEAR Intents (Confidential Intents) | About 0.3 bps more EVM to EVM, 5 to 8 bps when Bitcoin or Solana is a leg | Like a public swap | The cheapest. Any to any | | Houdini Swap | About 3% below spot | Minutes to an hour | Settles through two partner exchanges, which hold the funds meanwhile. About \$25 minimum | | Hinkal | About 0.3 to 0.45% less than NEAR | Seconds after the deposit, plus the bridge | Opt-in, EVM chains only. [See below](#hinkal) | Each hides the direct link between deposit and payout; how strongly depends on the venue. Your integrator fee applies, [paid beside the swap](/collecting-your-fee). Read `estimatedTimeSeconds` before executing. ## Compliance * **Houdini Swap** receives your request's IP and user agent, plus `clientTimezone` (your user's IANA timezone, default `UTC`). Its terms bar US persons and sanctioned jurisdictions. * **Hinkal**'s terms bar Cuba, Iran, North Korea, Syria, and Crimea, Sevastopol, Donetsk and Luhansk. RAVN leaves a venue out when your request comes from a barred country. You are responsible for your end users' eligibility: pass `excludeVenues: ["houdini"]` or `["hinkal"]` where you can't meet it. ## Hinkal Your user pays into Hinkal's shared pool, and Hinkal pays the recipient from a fresh wallet through LI.FI, so the payout can arrive in another token or on another chain. LI.FI's 0.25% and Hinkal's 0.10% plus a small flat fee come out of the quoted output. The deposit itself is heavy (450k to 670k gas), paid by the user's wallet and shown in the quote's `gas`. **Limits** * Races only when the quote has `authorizeSteps: true` (or `onlyVenues` naming `hinkal`), so a flow that can't collect the signatures below never gets a Hinkal quote. * From Ethereum, Base, Arbitrum, Polygon, BNB Chain or Robinhood Chain. Pays out on any of those, plus Solana, Arc, Tempo, Avalanche, Monad and HyperEVM. * Any token Hinkal's pool takes, except stETH and PAXG. Up to \$10,000 a swap. * Needs `destinationAddress` on the quote, or the quote is only a preview. Takes no `refundAddress` other than `userAddress`. * Up to 12 swaps an hour per IP, or 120 per API key. Past that, `/execute` answers `502 BUILD_FAILED`. Send your key. * Not available through the [MCP server](/ai-agents/mcp-server) or [x402](/ai-agents/x402-payments). **Privacy is thinner than NEAR's.** Hinkal has few users, and the payout follows the deposit by seconds for about the same amount, so timing can still link the two wallets. Hinkal screens depositors, and a flagged depositor's funds can only go back, publicly, to the wallet that paid. RAVN keeps the order encrypted for 7 days to track and recover it. Tell your users it hides the direct link, never that it's untraceable. ### AUTHORIZE steps Before Hinkal's swap is built, the paying wallet (`userAddress`) signs twice. `/execute` asks for each signature with an `AUTHORIZE` answer: ```json theme={null} { "executionType": "AUTHORIZE", "quoteToken": "…", "authorization": "hk_…", "sign": { "method": "personal_sign", "message": "Authorize Hinkal session\nSession ID: …\nPublic Key: …" }, "expiresAt": "2026-10-22T12:09:00.000Z", "step": 1, "steps": 2 } ``` Have the wallet sign `sign`, then call `/execute` again with the same `quoteToken`, this `authorization` and the `signature`, before `expiresAt`, with a **new** `Idempotency-Key`. Repeat until a `TRANSACTION` comes back. Signing moves no funds. Check each step before your user signs: 1. **`personal_sign`**: opens a read-only session. The message must be exactly the three lines above. Refuse one that adds `This signature can also be used to submit transactions.`: that mode's key could move the wallet's funds. 2. **`eth_signTypedData_v4`**: Hinkal's `PrivateSendBridge` order, signed on the input chain. Its domain is only `{ name: "Hinkal Enclave", chainId }`, it's for the input token (the zero address for the chain's coin) and at most the input amount, and `recipients` holds exactly one entry: your `destinationAddress`. 3. **The `TRANSACTION`**: the approval on a token sell, then `prooflessDeposit` on `0x7cb60446d7635C68EDf1c568cac74A1f98c1Cfa4` (the same address on every chain), your fee when one applies, and a `statusRef`. Send its `calls` one by one. > [!WARNING] > > **Send the deposit within 10 minutes of receiving the second `AUTHORIZE`.** Hinkal prices its route > then, and a later deposit is likely to fail at the bridge. The `TRANSACTION` carries no deadline, so > note the time yourself. Have the wallet sign step 2 within about 6 minutes: with under 4 of them > left, the order is refused (`400 INVALID_REQUEST`) and you start again from `/execute`. On JavaScript or TypeScript, [`executeAndTrack`](/sdks/core#executeandtrack) checks and signs both steps, then sends the deposit. In Python, [`check_authorize`](/sdks/python#execute) checks each step. A [sandbox](/sandbox-mode) quote skips the steps. ### When a Hinkal swap fails A failed payout is **not refunded on its own**. `/status` reports `failed` (never `refunded`), with `venueStatus` ending `(needs recovery)`, and the funds wait at Hinkal on the source chain. The paying wallet gets them back with [`POST /recover`](/api-reference/recover), within 7 days. After 7 days RAVN no longer holds the swap and its status reads `unknown`. # Quickstart Source: https://docs.ravn.exchange/quickstart Swap 1 ETH on Ethereum for SOL on Solana, end to end. Every swap is three steps: **quote** it, **execute** it to get what the wallet signs, then **track** it until it's final. No API key is needed to try it. [Get a free key](/tools/get-api-key) when you want a higher rate limit or your own fee. ## 1. Get a quote ```bash theme={null} curl -s -X POST https://app.ravn.exchange/api/v1/quote \ -H 'content-type: application/json' -d '{ "inputChainId": 1, "outputChainId": -2, "inputToken": "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", "outputToken": "So11111111111111111111111111111111111111112", "inputAmount": "1000000000000000000", "userAddress": "0x1111111111111111111111111111111111111111", "destinationAddress": "YourSo1anaWa11etAddressGoesHere311111111111" }' ``` You get the best route across every venue, the expected output and a `quoteToken`. The addresses above are placeholders: nobody holds their keys, so never send funds to them. ## 2. Execute and track Pass the `quoteToken` to `/execute`. It returns exactly what the wallet must sign or send, tagged by `executionType`. Then poll `/status` until the swap is final. Both scripts below swap from an EVM wallet. Save one as `quickstart.mjs`, run `npm install viem` (plus `@ravnexchange/sdk` for the first), then `PRIVATE_KEY=0x… SOL_DESTINATION= node quickstart.mjs`. > [tab] TypeScript SDK (recommended) > > `executeAndTrack` handles every execution type, approvals, your fee and status polling. > > ```js theme={null} > import { RavnClient, executeAndTrack } from "@ravnexchange/sdk"; > import { createWalletClient, http, publicActions } from "viem"; > import { privateKeyToAccount } from "viem/accounts"; > import { mainnet } from "viem/chains"; > > const wallet = createWalletClient({ > account: privateKeyToAccount(process.env.PRIVATE_KEY), > chain: mainnet, > transport: http(), > }).extend(publicActions); > const client = new RavnClient({ apiKey: process.env.RAVN_API_KEY }); // the key is optional > > const quote = await client.getQuote({ > inputChainId: 1, > outputChainId: -2, > inputToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", > outputToken: "So11111111111111111111111111111111111111112", > inputAmount: "1000000000000000000", > userAddress: wallet.account.address, > destinationAddress: process.env.SOL_DESTINATION, > }); > > const result = await executeAndTrack( > client, > { quoteToken: quote.quoteToken }, > { > sendTransaction: ({ to, data, value, gasLimit }) => > wallet.sendTransaction({ > to: to.toLowerCase(), > data, > value: BigInt(value ?? "0"), > gas: gasLimit ? BigInt(gasLimit) : undefined, > }), > waitForReceipt: (hash) => wallet.waitForTransactionReceipt({ hash }), > signTypedData: (typedData) => wallet.signTypedData(typedData), > }, > { sendDeposit: true } > ); > > console.log(result.finalStatus?.status); // "success" > ``` > [tab] HTTP (any language) > > The same flow on the raw API. On an EVM chain, `/execute` lists every transaction to send, in > order, as `calls`: the approval when one is needed, the swap or deposit, then your fee when > one applies. Report the fee's transaction to `/status` as `txHash`: that's how your fee is > proven. > > ```js theme={null} > import { createWalletClient, http, publicActions } from "viem"; > import { privateKeyToAccount } from "viem/accounts"; > import { mainnet } from "viem/chains"; > > const API = "https://app.ravn.exchange/api/v1"; > const wallet = createWalletClient({ > account: privateKeyToAccount(process.env.PRIVATE_KEY), > chain: mainnet, > transport: http(), > }).extend(publicActions); > > async function ravn(path, body) { > const res = await fetch(API + path, { > method: "POST", > headers: { > "content-type": "application/json", > ...(process.env.RAVN_API_KEY && { "x-api-key": process.env.RAVN_API_KEY }), > }, > body: JSON.stringify(body), > }); > const { data, error } = await res.json(); > if (error) throw new Error(`${error.code}: ${error.message}`); > return data; > } > > // Send one transaction and wait until it's mined. Throws unless it succeeded. > async function send({ to, data, value, gasLimit }) { > const hash = await wallet.sendTransaction({ > to: to.toLowerCase(), > data, > value: BigInt(value ?? "0"), > gas: gasLimit ? BigInt(gasLimit) : undefined, > }); > const receipt = await wallet.waitForTransactionReceipt({ hash }); > if (receipt.status !== "success" || receipt.transactionHash !== hash) throw new Error(`${hash} failed`); > return hash; > } > > const quote = await ravn("/quote", { > inputChainId: 1, > outputChainId: -2, > inputToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", > outputToken: "So11111111111111111111111111111111111111112", > inputAmount: "1000000000000000000", > userAddress: wallet.account.address, > destinationAddress: process.env.SOL_DESTINATION, > }); > const exec = await ravn("/execute", { quoteToken: quote.quoteToken }); > > let ref, txHash; > if (exec.sandbox) { > ref = "sandbox"; // a test execution: never send it. /status answers at once. > } else if (exec.executionType === "SIGNATURE") { > // Gasless, but the allowance must still be mined first, or the order never fills. > if (exec.approval?.reset) await send(exec.approval.reset); > if (exec.approval) await send(exec.approval); > const signature = await wallet.signTypedData(exec.typedData); > const approvalSignature = exec.approvalData && (await wallet.signTypedData(exec.approvalData)); > ({ statusRef: ref } = await ravn("/submit-signature", { quoteToken: exec.quoteToken, signature, approvalSignature })); > } else { > // TRANSACTION or DEPOSIT: send each call once the one before it has succeeded. > if (!exec.calls) throw new Error("No calls: see Execution types for this chain"); > const feeCall = exec.fee ? exec.calls.at(-1) : undefined; // your fee is always last > let swapHash; > for (const call of exec.calls) if (call !== feeCall) swapHash = await send(call); > ref = exec.statusRef ?? swapHash; > txHash = swapHash; > if (feeCall) { > // The swap is out: a failed fee must not stop the tracking below. > txHash = (await send(feeCall).catch((e) => console.log(`fee not sent: ${e.message}`))) ?? swapHash; > } > } > > // Poll until final, for up to an hour. Keep going through "expired" (a refund is on its way) > // and "not_found" (not seen yet), and retry a failed call (a 429, a network blip). > const FINAL = ["success", "refunded", "failed", "unknown"]; > let status; > for (let i = 0; i < 360 && !FINAL.includes(status); i++) { > if (i) await new Promise((r) => setTimeout(r, 10_000)); > try { > ({ status } = await ravn("/status", { quoteToken: exec.quoteToken, ref, txHash })); > console.log(status); > } catch (e) { > if (/^(INVALID_REQUEST|QUOTE_INVALID|UNAUTHORIZED)/.test(e.message)) throw e; // a retry won't fix it > console.log(`status call failed, retrying: ${e.message}`); > } > } > if (!FINAL.includes(status)) console.log("Not final yet: keep polling later with", { quoteToken: exec.quoteToken, ref, txHash }); > ``` > > This script covers EVM wallets. For Solana and Bitcoin, see > [Execution types](/execution-types). > [!TIP] > > Add `sandbox: true` to the quote to run the whole flow without moving funds: both scripts then sign > and send nothing. See [Sandbox mode](/sandbox-mode). > [!WARNING] > > Poll every swap until it's final. It's how RAVN confirms the swap, and only confirmed swaps earn > your fee. Always use the `quoteToken` that `/execute` returned for the calls after it. ## Next > [card] [Earn on every swap](/pricing) > > Put your fee on top of every swap. You keep 60% of it. > [card] [Execution types](/execution-types) > > What to do with each answer, on every chain. > [card] [API reference](/api-reference/overview) > > Every endpoint and field. > [card] [Widget](/sdks/widget) > > A ready-made swap UI instead. # Sandbox mode Source: https://docs.ravn.exchange/sandbox-mode Run the whole quote, execute and status flow without moving funds. Add `sandbox: true` to [`/quote`](/api-reference/quote) (or `/x402/quote`). The price is still live and real. The flag rides inside the `quoteToken`, so every later call sees it with nothing else to pass. Sandbox swaps are never metered or paid. | Call | In sandbox | | - | - | | `/execute` | Opens nothing at any venue. Every answer carries `"sandbox": true` | | `/submit-signature` | Doesn't forward the signature. Returns a stand-in `statusRef` | | `/submit-transaction` | Runs its checks, sends nothing. Returns a stand-in `txHash` | | `/status` | Answers `success` at once, with the quoted output as `deliveredAmount`. Any `ref` works | **What `/execute` returns.** Venues that would open something to build the swap (an order, a deposit address, a channel) return a stand-in `DEPOSIT` instead: send to it and the funds go to your user's own wallet (`refundAddress`, else `userAddress`). These are NEAR Intents, Rift, Garden, Layerswap, Houdini Swap, Hinkal, Chainflip, RAVN's two-hop routes and THORChain from Bitcoin. To test `TRANSACTION` handling, quote another venue, for example with `onlyVenues`. > [!WARNING] > > Every other venue returns its **real** transaction or typed data, built live, and Relay from Bitcoin > returns the real deposit address it opened when it quoted. Sent or signed to the venue, it swaps for > real. Check `"sandbox": true` and never send it. The SDK's `executeAndTrack` > sends nothing on a sandbox execution. On x402, the USDC charge for the call still applies in sandbox mode. # @ravnexchange/sdk Source: https://docs.ravn.exchange/sdks/core The TypeScript client. Typed calls, plus one function that runs a whole swap. ```bash theme={null} npm install @ravnexchange/sdk ``` ```ts theme={null} import { RavnClient } from "@ravnexchange/sdk"; const client = new RavnClient({ apiKey: "rvn_live_…" }); // optional: omit for the anonymous tier ``` **apiKey** `string` Your public key. Never put the secret key in browser code. **guard** `object | false` Tunes [the check before the wallet](#the-check-before-the-wallet): `{ solanaRpcUrl }` to simulate Solana transactions on your RPC, `{ allowContracts: { [chainId]: ["0x…"] } }` to accept a venue's new contract early. `false` turns it off. **baseUrl** `string` Default `https://app.ravn.exchange/api/v1`. **fetch** `function` Your own `fetch` (React Native, tests). These docs cover the latest version. What changed between versions is in the [changelog](https://github.com/ravndex/ravn-sdk/blob/main/CHANGELOG.md). ## executeAndTrack Runs a whole swap from a `quoteToken`: execute, approvals, the swap, your fee, then status polling to a final state. It works for every execution type and chain, given your own wallet functions. ```ts theme={null} import { executeAndTrack } from "@ravnexchange/sdk"; const quote = await client.getQuote({ /* … */ }); const result = await executeAndTrack( client, { quoteToken: quote.quoteToken }, { sendTransaction: ({ to, data, value, gasLimit }) => wallet.sendTransaction({ to: to!.toLowerCase() as `0x${string}`, // lowercase passes viem's checksum check data: data as `0x${string}`, value: BigInt(value ?? "0"), gas: gasLimit ? BigInt(gasLimit) : undefined, }), waitForReceipt: (hash) => wallet.waitForTransactionReceipt({ hash: hash as `0x${string}` }), signTypedData: (typedData) => wallet.signTypedData(typedData as any), }, { sendDeposit: true, onProgress: ({ partial }) => db.saveSwap(partial), // every hash, the moment it exists } ); result.finalStatus?.status; // "success", "refunded", "failed" or "unknown" ``` **Handlers.** Give it only what your app can do: | Handler | Needed for | | - | - | | `sendTransaction(tx)` | Every EVM transaction. Return the hash. Send `tx.gasLimit` as the gas limit when set | | `waitForReceipt(hash)` | Every EVM transaction. Return the receipt itself: RAVN's fee is sent only after a successful swap receipt | | `signTypedData(typedData)` | `SIGNATURE` executions, and Hinkal's order step | | `sendCalls(txs)` | Optional. Sends calls in one EIP-5792 batch when `batch` allows. Return each call's on-chain transaction hash | | `signSolanaTransaction(serialized)` | Solana transactions that carry `submit` (`broadcastViaRavn` quotes). Sign, don't send | | `sendBitcoinPsbt(psbt)` | Bitcoin deposits, with `sendDeposit`. Sign, finalize, broadcast, return the txid | | `sendSolanaTransaction(serialized)` | Solana deposits, with `sendDeposit`. Sign, send, return the signature | | `signMessage(message)`, `switchChain(chainId)` | Hinkal's [`AUTHORIZE` steps](/private-swaps#authorize-steps) | | `hasAllowance(approval)` | Optional. Your own allowance read, to skip an approval you don't need | Every handler that sends should reject only when nothing was sent. **Options** | Option | Default | | | - | - | - | | `sendDeposit` | `false` | Also send `DEPOSIT`s and their fee, from the ready-made payload. Without it you send deposits yourself (`result.feePayment` says what to pay beside one) | | `onProgress` | | Called with every hash as it exists, and on every poll. Persist `partial` to resume after a crash | | `pollUntilTerminal` | `true` | `false` returns once everything is sent; then poll `getStatus` yourself | | `pollIntervalMs` | `4000` | Use 10,000 to 15,000 for Bitcoin deposits | | `maxWaitMs` | none | Stop polling after this long. Set it on a backend | | `signal` | | An `AbortSignal` to stop | **Result**: `execution`, `quoteToken` (the one `/execute` returned), `txHash`, `statusRef`, `statusTxHash`, `approvalTxHash`, `feeTxHash`, `feeError` (why your fee wasn't sent or proven, if it wasn't), `finalStatus`, and with `sendDeposit` on, `depositNotSent` (why a deposit wasn't sent: send it yourself). > [!WARNING] > > With `sendDeposit` on, send a deposit yourself **only when `depositNotSent` is set**, or your user > pays twice. On a [sandbox](/sandbox-mode) execution nothing is sent. **Errors and resuming.** Before anything is sent, it rejects with the underlying error. After that, it rejects only with an `ExecuteAndTrackError` (`code`: `FAILED`, `ABORTED` or `TIMEOUT`) whose `partial` holds every hash so far. Keep polling with `getStatus(partial.quoteToken, partial.statusRef, partial.statusTxHash)`. ## Methods Each wraps one endpoint with the same fields as the [API reference](/api-reference/overview) and throws `RavnApiError` on failure. | Method | Endpoint | | - | - | | `getQuote(params)` | [`POST /quote`](/api-reference/quote) | | `getQuoteStream(params, { onEvent })` | `POST /quote` with `stream: true`. `onEvent` gets each venue's prices; it resolves to the same quote as `getQuote` | | `execute({ quoteToken, idempotencyKey? }, { intent? })` | [`POST /execute`](/api-reference/execute). Checked before it returns (see below) | | `submitSignature({ quoteToken, signature, approvalSignature? })` | [`POST /submit-signature`](/api-reference/submit-signature) | | `submitTransaction({ quoteToken, signedTransaction })` | [`POST /submit-transaction`](/api-reference/submit-transaction) | | `getStatus(quoteToken, ref, txHash?, { signal? })` | [`POST /status`](/api-reference/status). Doesn't retry: retry `RATE_LIMITED`, `5xx` and `NETWORK_ERROR` yourself | | `getTokens(chainId)`, `getChains()` | [`GET /tokens`](/api-reference/tokens-list), [`GET /chains`](/api-reference/chains) | | `recover(params, { userAddress })` | One step of [`POST /recover`](/api-reference/recover), checked | ### depositFeePayment `depositFeePayment(execution)` says what fee to pay beside a `DEPOSIT` you send yourself: `kind` `transaction` (EVM: send it once the deposit confirms), `bitcoin_output` or `solana_transfer` (add it to the deposit's own transaction). `undefined` when there's none. ### recoverStuckFunds Gets a failed [Hinkal](/private-swaps#hinkal) swap's funds back to the paying wallet, checking every step before it's signed: ```ts theme={null} import { recoverStuckFunds } from "@ravnexchange/sdk"; const { recovered } = await recoverStuckFunds( client, { statusRef, userAddress }, // userAddress: the paying wallet, from your own wallet connection { signMessage: (message) => wallet.signMessage({ message }), signTypedData: (typedData) => wallet.signTypedData(typedData), switchChain: (chainId) => wallet.switchChain({ id: chainId }), // optional } ); ``` ## The check before the wallet `execute` (and so `executeAndTrack`) checks every execution against what your user asked to swap before you can hand it to a wallet. It throws `UnsafeExecutionError` unless: * EVM transactions and approvals go only to contracts RAVN's venues use, and touch only the input token, up to the input amount; * no more native coin is sent than the input amount, and none on a token sell; * RAVN's fee goes only to RAVN and is at most 1%; * signatures are of kinds RAVN's venues use, for the input token, up to the amount; * a Bitcoin PSBT pays only the deposit, RAVN's fee and change back to the sender; * a Solana transaction calls only programs RAVN's venues use and moves at most the input amount. With `guard: { solanaRpcUrl }` it's also simulated on your RPC (Agave 2.3 or later), and every transfer out of the user's accounts must stay within the swap. It knows what was asked from your own `getQuote`. For a `quoteToken` quoted elsewhere (say, on your server), pass it: `execute({ quoteToken }, { intent: { inputChainId, inputToken, inputAmount, userAddress } })`. Quote with token addresses, not symbols. What it can't see: whether a venue pays out fairly once funds are in its contract, and allowances the user already gave those contracts. Without a Solana RPC, rely on the wallet's own simulation. An `UnsafeExecutionError` means nothing was sent: get a fresh quote, and tell RAVN if it persists. ## Errors ```ts theme={null} import { RavnApiError } from "@ravnexchange/sdk"; try { await client.execute({ quoteToken }); } catch (err) { if (err instanceof RavnApiError) console.log(err.code, err.status, err.retryAfterSec, err.details); } ``` `code` is the [API error code](/errors), or `NETWORK_ERROR` when no response came back. # SDKs & widget Source: https://docs.ravn.exchange/sdks/overview A typed client, React hooks, a Python client, or a drop-in widget. All of them sit on the same [API](/api-reference/overview): same fields, same prices, same fees. | Package | For | Install | | - | - | - | | [`@ravnexchange/sdk`](/sdks/core) | Any JS/TS app or backend. `executeAndTrack` runs a whole swap | `npm install @ravnexchange/sdk` | | [`@ravnexchange/react`](/sdks/react) | Your own swap UI in React | `npm install @ravnexchange/react @ravnexchange/sdk` | | [`ravnexchange`](/sdks/python) | Python backends | `pip install ravnexchange` | | [Widget](/sdks/widget) | A ready-made swap UI in an iframe, using your page's wallet | `npm install @ravnexchange/widget-connector` | None of them hold keys or connect wallets: you pass in your own signer. # ravnexchange (Python) Source: https://docs.ravn.exchange/sdks/python A typed Python client for the API. No dependencies. ```bash theme={null} pip install ravnexchange ``` ```python theme={null} from ravnexchange import RavnClient, RavnApiError client = RavnClient(api_key="rvn_live_…") # optional: omit for the anonymous tier try: quote = client.get_quote({ "inputChainId": 1, "outputChainId": -2, "inputToken": "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", "outputToken": "So11111111111111111111111111111111111111112", "inputAmount": "1000000000000000000", "userAddress": "0x1111111111111111111111111111111111111111", "destinationAddress": "YourSo1anaWa11etAddressGoesHere311111111111", }) execution = client.execute({"quoteToken": quote["quoteToken"]}) # Branch on execution["executionType"]: see Execution types. except RavnApiError as e: print(e.code, e.details, str(e)) ``` Methods are snake\_case, but request fields keep the API's camelCase keys. Each method returns the response's `data` and raises `RavnApiError` (`code`, `details`, `meta`; the message is `str(e)`) on failure. The client signs nothing: handle each execution as in [Execution types](/execution-types). | Method | Endpoint | | - | - | | `get_quote(params)` | [`POST /quote`](/api-reference/quote) | | `execute(params)` | [`POST /execute`](/api-reference/execute) | | `submit_signature(params)` | [`POST /submit-signature`](/api-reference/submit-signature) | | `submit_transaction(params)` | [`POST /submit-transaction`](/api-reference/submit-transaction) | | `get_status(quote_token, ref, tx_hash=None)` | [`POST /status`](/api-reference/status) | | `get_tokens(chain_id)`, `get_chains()` | [`GET /tokens`](/api-reference/tokens-list), [`GET /chains`](/api-reference/chains) | | `recover(params, user_address)` | One step of [`POST /recover`](/api-reference/recover), checked | ## execute For a [Hinkal](/private-swaps#hinkal) quote sent with `authorizeSteps: True`, `execute` first answers `AUTHORIZE` twice. Check each step with `check_authorize`, sign it with the paying wallet, and call `execute` again until the `TRANSACTION` comes back. Check that with `check_hinkal_deposit` before sending anything. ```python theme={null} import time from eth_account import Account from eth_account.messages import encode_defunct from ravnexchange import check_authorize, check_hinkal_deposit account = Account.from_key(private_key) # the paying wallet: the quote's userAddress while execution["executionType"] == "AUTHORIZE": check_authorize(execution, params) # params: what you passed to get_quote sign = execution["sign"] if sign["method"] == "personal_sign": signature = account.sign_message(encode_defunct(text=sign["message"])).signature else: order_received = time.time() # send the deposit within 10 minutes of this signature = account.sign_typed_data(full_message=sign["typedData"]).signature execution = client.execute({ "quoteToken": quote["quoteToken"], "authorization": execution["authorization"], "signature": signature, }) check_hinkal_deposit(execution, params) ``` Both raise `UnsafeExecutionError` when a step isn't what your user asked for. This client checks Hinkal's answers only, not other venues'. ## recover\_stuck\_funds Gets a failed Hinkal swap's funds back to the paying wallet, checking every step: ```python theme={null} from ravnexchange import recover_stuck_funds recovered = recover_stuck_funds( client, status_ref=execution["statusRef"], user_address=account.address, # the paying wallet, from your own wallet sign_message=lambda message: account.sign_message(encode_defunct(text=message)).signature, sign_typed_data=lambda typed: account.sign_typed_data(full_message=typed).signature, ) ``` Building an AI agent? The [MCP server](/ai-agents/mcp-server) covers the same calls with no code. # @ravnexchange/react Source: https://docs.ravn.exchange/sdks/react React hooks for quotes, executes and status, on top of the SDK. Three hooks that manage the state around quote, execute and status. They never sign or send: bring your own wallet. React 18 or later. ```bash theme={null} npm install @ravnexchange/react @ravnexchange/sdk ``` ```ts theme={null} import { RavnClient } from "@ravnexchange/sdk"; import { useRavnQuote, useRavnExecute, useRavnStatus } from "@ravnexchange/react"; const client = new RavnClient(); // create once, pass to every hook ``` ## useRavnQuote ```ts theme={null} const { quote, isLoading, error, isExpired, refetch } = useRavnQuote(client, params); ``` Fetches whenever `params` changes (compared by value). Pass `null` to skip. `isExpired` turns true when the quote's `expiresAt` passes. It doesn't refetch on its own: stop the user from signing and call `refetch()`. ## useRavnExecute ```ts theme={null} const { execute, data, isLoading, error } = useRavnExecute(client); const execution = await execute({ quoteToken: quote.quoteToken }); ``` State around `client.execute()`, for when you send each execution yourself, exactly as [Execution types](/execution-types) says: send `calls` in order (approvals included), or on a `SIGNATURE` mine the approval before signing, and report your fee's hash as `txHash` on `/status`. Simpler: let the core SDK's [`executeAndTrack`](/sdks/core#executeandtrack) send it, as below. ## useRavnStatus ```ts theme={null} const { status, isLoading, error } = useRavnStatus(client, { quoteToken, ref, txHash }, 4_000); ``` Polls until `success`, `refunded`, `failed` or `unknown`, through `expired` and `not_found`. Pass `null` until you have a `ref`. Use 10,000 to 15,000 ms for a Bitcoin deposit. Stops on errors that can't succeed on retry (`UNAUTHORIZED`, `INVALID_REQUEST`, `QUOTE_INVALID`, `NOT_FOUND`). ## Together ```tsx theme={null} import { executeAndTrack, ExecuteAndTrackError } from "@ravnexchange/sdk"; function SwapButton({ params }: { params: GetQuoteParams }) { const { quote, isExpired, refetch } = useRavnQuote(client, params); const [track, setTrack] = useState<{ quoteToken: string; ref: string; txHash?: string } | null>(null); const { status } = useRavnStatus(client, track); const handleSwap = async () => { // Sends the approval, the swap or deposit, and your fee, in order. The hook does the polling. // `handlers`: your wallet functions, as on the executeAndTrack page. try { const result = await executeAndTrack(client, { quoteToken: quote!.quoteToken }, handlers, { sendDeposit: true, pollUntilTerminal: false, }); if (result.depositNotSent) return; // a deposit it couldn't send: show the address instead setTrack({ quoteToken: result.quoteToken, ref: result.statusRef!, txHash: result.statusTxHash }); } catch (e) { // Failed after the swap went out: keep tracking it with what was sent. const sent = e instanceof ExecuteAndTrackError ? e.partial : undefined; if (!sent?.statusRef) throw e; setTrack({ quoteToken: sent.quoteToken!, ref: sent.statusRef, txHash: sent.statusTxHash }); } }; if (isExpired) return ; return ; } ``` # Embedding the widget Source: https://docs.ravn.exchange/sdks/widget A drop-in swap UI in an iframe, using the wallet your page already has connected. The widget is a hosted swap UI. It never asks the user to connect a second wallet: `@ravnexchange/widget-connector` lets it use the wallet already connected on your page. To earn from it, set your fee and your site on your key, then give the widget your public key: you put your own fee on top, and RAVN shares it with you 60/40 ([Pricing](/pricing)). **1. Embed the iframe** Set `?origin=` to your page's exact origin. ```html theme={null} ``` Keep `allow-same-origin`: without it the widget can't talk to your page. It needs no `allow-popups` or `allow-top-navigation`. `v1` stays stable; a breaking change ships as `v2`. **2. Wrap your wallet** ```bash theme={null} npm install @ravnexchange/widget-connector ``` ```ts theme={null} import type { RavnWallet, RavnSolanaWallet } from "@ravnexchange/widget-connector"; const evmWallet: RavnWallet = { address: account.address ?? null, chainId: account.chainId ?? null, sendTransaction: (req) => wagmiSendTransaction(req), signTypedData: (req) => wagmiSignTypedData(req.typedData), signMessage: (req) => wagmiSignMessage(req.message), switchChain: (req) => wagmiSwitchChain(req.chainId).then(() => ({ ok: true })), }; const solanaWallet: RavnSolanaWallet = { address: solanaAccount?.address ?? null, signTransaction: (req) => adapter.signTransaction(req.transaction), }; ``` > [!WARNING] > > These call your wallet, which shows the user what they're signing. Never wire them to a signer > with no confirmation step. **3. Connect the bridge** ```ts theme={null} import { createRavnWidgetBridge } from "@ravnexchange/widget-connector"; const bridge = createRavnWidgetBridge({ iframe: iframeRef.current, widgetOrigin: "https://app.ravn.exchange", getWallet: () => (isEvmConnected ? evmWallet : null), getSolanaWallet: () => (isSolanaConnected ? solanaWallet : null), config: { primaryColor: "#7C3AED" }, // optional: see Theming }); bridge.updateWallet(isEvmConnected ? { address, chainId } : null); // on every EVM wallet change bridge.updateSolanaWallet(isSolanaConnected ? { address: solanaAddress } : null); // on every Solana change bridge.destroy(); // on unmount ``` **4. Earn your fee** Run this once from your server, with your secret key ([get a key](/tools/get-api-key) if you don't have one). It sets your fee, where RAVN pays your share, and the sites your key works on: ```bash theme={null} curl -s -X PATCH https://app.ravn.exchange/api/v1/keys \ -H 'x-api-key: rvn_sk_your_secret_key' \ -H 'content-type: application/json' -d '{ "feeBps": 25, "payoutAddresses": { "evm": "0xYourPayoutAddress", "solana": "YourSo1anaWa11etAddressGoesHere311111111111" }, "allowedOrigins": ["https://your-site.example"] }' ``` List the origin you set in `?origin=`, plus every other site that uses the key in a browser. Your fee and site list take effect within a minute. Then add `apiKey: "rvn_live_your_key"` to the bridge's `config`. On a page the key doesn't list, the widget stops quoting and says why. The widget collects your fee and reports each swap itself, and widget swaps reach your [webhook](/webhooks) too. Details: [Set your fee](/pricing#set-your-fee) and [Getting paid](/pricing#getting-paid). Pass your public key (`rvn_live_…`), never your secret key. A secret key stops the widget: [rotate it](/api-reference/keys#rotate-your-secret-key). A key from before secret keys existed works once you [claim its secret key](/authentication#public-and-secret-keys). Native BTC deposits need nothing from you: the widget shows the deposit address, a QR code and live status itself. If the bridge never answers, the widget shows "Couldn't reach the host page": check that `?origin=` is your page's exact origin and that you created the bridge. For tighter framing, set your page's CSP `frame-src` to `https://app.ravn.exchange`. To match your brand, see [Theming](/sdks/widget-theming). ## Reference **iframe** `HTMLIFrameElement` *required* The embedded iframe. **widgetOrigin** `string` *required* `https://app.ravn.exchange`. Never `*`. **getWallet** `() =\> RavnWallet | null` *required* Your EVM wallet, or `null` when none is connected. **getSolanaWallet** `() =\> RavnSolanaWallet | null` Your Solana wallet, or `null`. `signTransaction` gets an unsigned base64 versioned transaction and returns it signed. **config** `object` Your public key as `apiKey`, so widget swaps carry your fee, plus the widget's [theme](/sdks/widget-theming). A wallet request while no wallet is connected fails in the widget with `WALLET_NOT_CONNECTED` or `SOLANA_WALLET_NOT_CONNECTED`. # Theming the widget Source: https://docs.ravn.exchange/sdks/widget-theming Match the widget's colors, corners and font to your product. Pass a theme as `config` to [`createRavnWidgetBridge`](/sdks/widget). Set only the fields you want; the rest keep their defaults. ```ts theme={null} const bridge = createRavnWidgetBridge({ iframe: iframeRef.current, widgetOrigin: "https://app.ravn.exchange", getWallet: () => evmWallet, config: { primaryColor: "#7C3AED", secondaryColor: "#A78BFA", borderRadius: 16, fontFamily: "Georgia, serif", }, }); ``` > [card] [Playground](https://app.ravn.exchange/widget/playground) > > Tune every field on the real widget, then copy the `config`. | Field | Sets | | - | - | | `primaryColor` | Buttons and highlights. The button label color adjusts for contrast | | `secondaryColor` | Tab underline and glows | | `background` | Behind the card | | `cardBackground` | The card. Inputs inside it are shaded darker automatically | | `textPrimary`, `textSecondary` | Text | | `success`, `error` | Confirmations and errors | | `borderRadius` | Corner radius in px, for the card and every control. `0` is sharp | | `fontFamily` | Any CSS `font-family`. Load the font on your page yourself | Colors take any CSS color. A value that isn't one is ignored. There's no light/dark switch: the widget is designed for a dark canvas. # Security Source: https://docs.ravn.exchange/security Non-custodial, tamper-evident quotes, and a check before the wallet. **RAVN never holds funds.** It finds the route and builds what to sign. The user signs or sends directly to the venue, and each venue checks the order it settles. A transaction posted to [`/submit-transaction`](/api-reference/submit-transaction) is signed by the user and sent by RAVN as signed. **Quotes can't be altered.** The `quoteToken` is signed. Changing the amount, fee or route invalidates it (`QUOTE_INVALID`), and `/execute` checks its expiry before building. **The SDK checks every execution before the wallet sees it.** `@ravnexchange/sdk` holds what `/execute` returns to what your user asked: only the contracts RAVN's venues use, only the input token, at most the input amount, RAVN's fee at most 1% and only to RAVN. It ships through npm, apart from RAVN's servers, so on EVM chains and Bitcoin even a compromised RAVN couldn't empty a wallet through your integration: the most at stake is the swap amount. On Solana, give it your RPC and it simulates each transaction too. RAVN's server runs the same check on every answer. See [the check before the wallet](/sdks/core#the-check-before-the-wallet). **Gasless where it counts.** On RFQ and gasless venues the user signs a message and a solver pays the gas, so they need only the token they're selling. [`GET /health`](/api-reference/health) reports each venue's live status. # Supported chains & venues Source: https://docs.ravn.exchange/supported Every chain RAVN swaps across, and the venues it routes through. ## Chains | Chain | ID | Chain | ID | | - | - | - | - | | **Bitcoin** (native BTC) | `-1` | **Solana** (SOL and SPL) | `-2` | | Ethereum | `1` | Base | `8453` | | Optimism | `10` | Arbitrum | `42161` | | BNB Chain | `56` | Linea | `59144` | | Unichain | `130` | Avalanche | `43114` | | Polygon | `137` | Robinhood Chain | `4663` | | zkSync Era | `324` | Monad | `143` | | World Chain | `480` | HyperEVM | `999` | | Tempo | `4217` | Arc | `5042` | | Elysium | `99901` | | | [`GET /chains`](/api-reference/chains) and [`GET /tokens`](/api-reference/tokens-list) return the same data, live. * **Tempo**'s native `USD` is a unit of account, not a token: only its ERC-20s swap (USDC.e, pathUSD, USDT0, PRIME). * **Arc** (Circle's chain) pays gas in USDC, and its native coin is the same balance as the USDC token at `0x3600000000000000000000000000000000000000`. Quote USDC by that address, not the native sentinel. Leave about 0.04 USDC for gas: selling the whole balance reverts. ## Venues Each quote races only the venues that can serve that route. The `id` is what quotes, `/health`, `excludeVenues` and `onlyVenues` use. [`/health`](/api-reference/health) is the live list. | Venue | `id` | Execution | Serves | | - | - | - | - | | 0x Gasless | `0x_gasless` | `SIGNATURE` | EVM same-chain, token sells | | 0x Swap | `0x_swap` | `TRANSACTION` | EVM same-chain | | 0x Solana | `0x_solana` | `TRANSACTION` | Solana same-chain | | Bebop | `bebop` | `SIGNATURE` or `TRANSACTION` | EVM same-chain, token sells | | CoW Protocol | `cow` | `SIGNATURE` | EVM same-chain, token sells | | FlowRouter | `flowrouter` | `TRANSACTION` | Robinhood Chain same-chain | | Fly Trade | `flytrade` | `TRANSACTION` | EVM same-chain | | Fynd | `fynd` | `TRANSACTION` | EVM same-chain | | Jupiter | `jupiter` | `TRANSACTION` | Solana same-chain | | KyberSwap | `kyberswap` | `TRANSACTION` | EVM same-chain | | Nordstern | `nordstern` | `TRANSACTION` | EVM same-chain | | OKX DEX | `okx` | `TRANSACTION` | EVM and Solana same-chain | | Across | `across` | `TRANSACTION` | Cross-chain, EVM and Solana | | Chainflip | `chainflip` | `DEPOSIT` | Native BTC, ETH, SOL and major stablecoins, any direction | | Eco Routes | `eco` | `TRANSACTION` | Cross-chain stablecoins, including USDC on Arc | | Layerswap | `layerswap` | `DEPOSIT` or `TRANSACTION` | EVM into native BTC and Robinhood Chain stocks; EVM to EVM or Solana; BTC into WBTC | | Mayan | `mayan` | `TRANSACTION` | Same-chain, cross-chain, EVM and Solana | | NEAR Intents | `near_intents` | `DEPOSIT` | Any to any, including native BTC | | Relay | `relay` | `TRANSACTION`, `SIGNATURE` or `DEPOSIT` | Same and cross-chain, EVM and Solana, native BTC either way | | Rift | `rift` | `DEPOSIT` | Same and cross-chain on Ethereum, Arbitrum, Base, Polygon and Robinhood Chain, native BTC either way. No minimum output | | THORChain | `thorchain` | `TRANSACTION` | EVM into native BTC | | Houdini Swap | `houdini` | `DEPOSIT` | [Private swaps](/private-swaps) only | | Hinkal | `hinkal` | `AUTHORIZE`, then `TRANSACTION` | [Private swaps](/private-swaps) only, opt-in | RAVN's own multi-step routes appear as `venue.name` `RAVN` (`venue.id` `compose`, or `relay` for Relay with a swap on arrival), with their venues in `hops`. `excludeVenues` removes a venue from these routes too; `onlyVenues` races one only when every venue in it is listed. Some venues route through others of their own choosing (Layerswap, Relay, Rift, Across, Mayan), which neither list reaches. **Send a Fynd swap as RAVN returns it.** Fynd's license requires every swap it routes to settle through its router, unchanged: don't change the transaction's target or calldata, or take the route elsewhere. **Rift has no minimum output.** It sets its rate when the deposit lands, so the user can receive more or less than quoted. Its quotes carry `slippage.noMinimum: true`: tell the user before they send. RAVN ranks it on `expectedOutputAmount`, which already takes off its expected shortfall. Rift races when `slippageBps` is left on Auto, or with `allowNoMinimum: true`. **Selling BTC** works through Chainflip, Relay, NEAR Intents and Rift (and Layerswap, into WBTC). THORChain only buys BTC for now. # Get an API key Source: https://docs.ravn.exchange/tools/get-api-key Free and instant. No review. Fill in the form and your keys appear at once. You get a **public key** for your app and a **secret key** for your server ([which goes where](/authentication#public-and-secret-keys)). Your rate limit goes from 30 to 120 requests a minute. Next, [put your fee on top of every swap](/pricing#set-your-fee) with the secret key, up to 1%. You keep 60% of it and RAVN 40%. Need custom limits or terms? Reach out on [X](https://x.com/ravnexchange). # Use cases Source: https://docs.ravn.exchange/use-cases What teams build on RAVN. > [card] [Wallets](/sdks/widget) > > In-app swaps across EVM, Solana and native BTC, gasless on RFQ routes. The widget is a drop-in > UI. > [card] Treasury tools > > Rebalance across chains (ETH to BTC, stablecoins across chains) in one call, non-custodially. > [card] DeFi dashboards > > Let users act on a position without leaving the dashboard. > [card] [Bots and agents](/ai-agents/overview) > > One quote, execute and status loop for every chain, with firm RFQ prices. > [card] [Bitcoin apps](/bitcoin-and-solana) > > Swap in and out of real BTC, never cbBTC or another wrapped copy. > [card] Payments > > Settle any asset into the exact token and chain a payment needs. > [card] [Vaults and pools](/api-reference/quote#call-a-contract-after-the-swap) > > Deposit any asset from any chain, Bitcoin included, into your vault, perps or privacy pool in one step. # Webhooks Source: https://docs.ravn.exchange/webhooks Get notified when a swap made with your key is final. RAVN posts to your URL when a swap made with your key settles, is refunded or fails. A webhook tells you a swap is final. It doesn't report the swap to RAVN, so [keep polling `/status`](/collecting-your-fee) too. ## Register a URL Set an `https://` URL with your secret key: ```bash theme={null} curl -s -X PATCH https://app.ravn.exchange/api/v1/keys \ -H 'x-api-key: rvn_sk_your_secret_key' \ -H 'content-type: application/json' \ -d '{ "webhookUrl": "https://your-service.example/ravn-webhook" }' ``` ```json theme={null} { "data": { "webhookUrl": "https://your-service.example/ravn-webhook", "webhookSecret": "a1b2c3…" } } ``` `webhookSecret` signs every delivery. It stays the same when you change the URL, and every registration returns it. Enterprise keys don't support webhooks yet. ## The payload ```json theme={null} { "event": "swap.settled", "swapId": "…", "requestId": "…", "partnerId": "…", "venue": "mayan", "deliveredOut": "18921340", "slippageBps": 10, "ts": 1750000000000 } ``` * `event`: `swap.settled`, `swap.refunded` or `swap.failed`. Each swap gets one. * `swapId`: the `swapId` `/execute` returned. `requestId` is the same value. * `deliveredOut` and `slippageBps` can be `null` when the venue doesn't report them. * `ts`: delivery time, epoch milliseconds. ## Delivery * Any `2xx` within 5 seconds counts as delivered. Otherwise it's retried 5, 20, 45, 80 minutes later and so on, for a day, then dropped. * It can arrive twice. Deduplicate on `swapId` and `event`. * Webhooks come from a job that runs about every 5 minutes, so they lag `/status` by up to that. A swap whose fee RAVN is still confirming can take up to a day. ## Verify the signature Each request carries `x-ravn-signature: sha256=`, an HMAC-SHA256 of the raw body with your `webhookSecret`. Check it against the raw bytes, before parsing. ```js Node theme={null} import { createHmac, timingSafeEqual } from "node:crypto"; function isValidSignature(rawBody, signatureHeader, secret) { const expected = "sha256=" + createHmac("sha256", secret).update(rawBody).digest("hex"); const a = Buffer.from(expected); const b = Buffer.from(signatureHeader ?? ""); return a.length === b.length && timingSafeEqual(a, b); } ``` ```python Python theme={null} import hashlib import hmac def is_valid_signature(raw_body: bytes, signature_header: str, secret: str) -> bool: expected = "sha256=" + hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, signature_header or "") ```