# API keys Source: https://docs.oneswap.cc/guides/api-keys Create, rotate, and revoke the SDK keys that authenticate your requests. Every swap request is authenticated with an **integrator API key**. You create and manage keys from your OneSwap account (self-serve), then pass the key to the SDK. | Network | Create keys at | | ------- | ---------------------------------------------- | | Mainnet | [swap.oneswap.cc](https://swap.oneswap.cc) | | Devnet | [devnet.oneswap.cc](https://devnet.oneswap.cc) | ## Key format A key looks like `sk_live_` followed by **48 hex characters**: ``` sk_live_0a1b2c3d…4e5f6071 # sk_live_ + 48 hex chars (shown once, at creation) ``` The plaintext key is shown **once**, at creation. OneSwap stores only a hash of it, so it cannot be shown again. If you lose a key, mint a new one and revoke the old. ## How the SDK uses the key Pass the key when you construct the client. The SDK sends it on every request as the HTTP header `x-sdk-key`: ```typescript theme={null} import { OneSwap } from '@oneswap/sdk' const oneswap = new OneSwap({ apiKey: 'sk_live_...' }) ``` ## Creating a key Sign in to your OneSwap account — [swap.oneswap.cc](https://swap.oneswap.cc) for mainnet, [devnet.oneswap.cc](https://devnet.oneswap.cc) for devnet — and open the **SDK keys** section. Create a key with an optional label (e.g. "production backend"). The response shows the plaintext `sk_live_...` value **once** — copy it into your server's secret store immediately. ## Listing keys The same account page lists your keys — label, active state, rate limit, and creation date. The secret is never shown again; only metadata is listed. ## Rotating a key There is no in-place rotation. To rotate: 1. Create a new key from your account. 2. Deploy it to your servers. 3. Revoke the old key once nothing uses it. ## Revoking a key Revoke (delete) a key from the same account page. This is how you rotate out a leaked or retired key — revocation is immediate. ## Rate limits Each key has a base per-minute rate limit (`ratePerMin`), and operations are tiered relative to it: | Operation | Limit | | --------------------------------------------- | ----------------------------------------------------- | | `swaps.createSwap` | The tightest tier — **1×** the key's per-minute limit | | `swaps.getSwap` / `swaps.waitForSwap` polling | **4×** the create rate | | `quotes.get`, `pools.*`, `tokens.list` | Generous read ceilings, shared with anonymous traffic | On top of the base limit, OneSwap can configure **per-operation limits for your key** (different ceilings for creating swaps, quoting, reading tickers, and so on). If your integration needs more headroom on a specific operation — say, high-frequency quoting — ask for a per-operation raise rather than a blanket one. Exceeding a limit returns HTTP `429` (`RateLimitError`). Back off and retry — see [Error handling](/guides/error-handling). ## Security best practices Treat your `sk_live_` key like a password. Anyone with it can create swaps under your integrator account. * **Server-side only.** Keep the key on your backend. Never ship it to a browser, mobile app, or any end-user surface. * **Never expose it to end-users.** Your users interact with a deposit party — they never need, and must never see, your key. * **Store it in a secret manager**, not in source control or client bundles. * **Use separate keys** per environment or service so you can revoke one without disrupting the others. * **Revoke immediately** if a key is exposed, then create a replacement. # Error handling Source: https://docs.oneswap.cc/guides/error-handling Typed SDK errors, terminal statuses, and how to handle both safely. Failures come in two shapes: 1. **Thrown errors** — the SDK throws a typed error (every class extends `OneSwapError`). These happen at call time (`swaps.createSwap`, `quotes.get`, …) — for example a pair with no pool, an already-open swap, an invalid key, or a rate limit. 2. **Terminal statuses** — the swap is created successfully but ends in a non-success terminal state (`refunded`, `expired`, `failed`). You read these off the swap's `status`, not from a thrown error. Because swaps are **atomic DvP**, a swap that does not complete has its input **refunded** — funds are never stranded by a partial swap. ## Typed errors Every error extends `OneSwapError`, which carries an optional `status` (HTTP status code) and `data` (the parsed response body). Catch by class with `instanceof`: ```typescript theme={null} import { OneSwap, OpenSwapExistsError, NoDirectPoolError, RateLimitError, AuthError, } from '@oneswap/sdk' try { const swap = await oneswap.swaps.createSwap({ userRef: 'user-1042', inSymbol: 'CBTC', amountIn: 0.01, outSymbol: 'HTEST', }) } catch (err) { if (err instanceof OpenSwapExistsError) { // this user already has an open swap — resume it instead } else if (err instanceof RateLimitError) { // back off and retry } else { throw err } } ``` | Class | HTTP | When | What to do | | ------------------------------- | ----- | --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | `OpenSwapExistsError` | `409` | `createSwap` for a `userRef` that already has an open (non-terminal) swap | Call `getOpenSwap(userRef)`, then `cancel` it if no deposit arrived, or resume it if one did | | `ConflictError` | `409` | `cancel` on a swap that already holds funds | Don't retry the cancel — `waitForSwap` on it instead | | `NoDirectPoolError` | — | `quotes.get` for a pair no pool trades directly (`createSwap` errors similarly with `no pool for IN/OUT`) | Route through an intermediate asset (usually CC) as two separate swaps | | `AmbiguousPoolPairError` | — | `quotes.get` for a pair that several pools trade; carries `candidates` | Retry with `poolId` set to one of the candidates | | `ValidationError` | `400` | Bad arguments (missing symbols, non-positive amount, mismatched `poolId`) | Fix the request | | `AuthError` | `401` | The API key is missing, malformed, or revoked | Check the key and mint a new one if needed | | `NotFoundError` | `404` | Unknown swap id or pool id | Check the id | | `RateLimitError` | `429` | Too many requests for the key's per-minute tier | Back off and retry (see below) | | `ServerError` | `5xx` | The API failed to process the request | Retry with backoff; contact OneSwap if persistent | | `NetworkError` / `TimeoutError` | — | The request never completed (connection failure / local timeout) | Retry; the operation may or may not have happened — reads are safe to repeat | ## Terminal statuses A created swap always reaches one of these terminal statuses. Read `status` (and `amountOut` / `senderParty` / `error`) off the swap: | Status | Meaning | What to do | | ----------- | -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | `returned` | **Success** — `amountOut` of `outSymbol` was returned to `senderParty` | Record the payout | | `refunded` | Deposit amount was outside the **1%** tolerance, or output was below `minOut` — the input was returned to the sender | Tell the user; they can try again with the exact amount or a lower `minOut` | | `expired` | No deposit arrived before `deadline` (60 minutes) — nothing happened | Create a fresh swap if the user still wants to trade | | `cancelled` | Closed via `cancel()` before any deposit arrived — nothing happened | Create a fresh swap if the user still wants to trade | | `failed` | An unexpected error (rare); `error` is set | Inspect `error`; the input is refunded by the atomic guarantee | ## The "already has an open swap" case Only one open swap per `userRef` is allowed. When you hit this, don't create a duplicate — ask for the open swap and act on it. You don't need to have stored the id: `getOpenSwap` finds it for you. ```typescript theme={null} import { OpenSwapExistsError } from '@oneswap/sdk' async function createOrResume(args) { try { return await oneswap.swaps.createSwap(args) } catch (err) { if (!(err instanceof OpenSwapExistsError)) throw err const open = await oneswap.swaps.getOpenSwap(args.userRef) if (!open) return oneswap.swaps.createSwap(args) // it finished in the meantime // No deposit yet? Release it and start the swap the user actually asked for. if (open.status === 'awaiting_deposit') { await oneswap.swaps.cancel(open.id) return oneswap.swaps.createSwap(args) } // A deposit is in flight — that swap must run to completion. Resume it. return open } } ``` `cancel` only closes a swap still in `awaiting_deposit`. Once a deposit has arrived the swap holds the user's funds and must run to completion — cancelling then throws `ConflictError` (409). Never treat that 409 as a reason to retry `createSwap`; wait on the existing swap with `waitForSwap` instead. Store `swap.id` against your `userRef` at creation so you can always find the open swap again. ## The "no direct pool" case Every swap settles against one pool, and there is no multi-hop routing. `quotes.get` throws `NoDirectPoolError` when no pool trades the pair — the error tells you both symbols so you can route through an intermediate asset yourself: ```typescript theme={null} import { NoDirectPoolError } from '@oneswap/sdk' try { await oneswap.quotes.get({ from: 'HANDL', to: 'EDELx', amount: 100 }) } catch (err) { if (err instanceof NoDirectPoolError) { // No HANDL/EDELx pool. Two swaps instead: HANDL→CC, then CC→EDELx — // two settlements, two network fees, and the price can move between legs. } } ``` ## Rate limits Requests beyond a key's per-minute tier throw `RateLimitError` (`429`). Create is the tightest tier; polling and reads are looser. Back off and retry: ```typescript theme={null} import { RateLimitError } from '@oneswap/sdk' async function pollWithBackoff(id: string) { let delay = 3000 for (;;) { try { return await oneswap.swaps.getSwap(id) } catch (err) { if (err instanceof RateLimitError) { await new Promise((r) => setTimeout(r, delay)) delay = Math.min(delay * 2, 30000) continue } throw err } } } ``` Prefer `waitForSwap` (or a fixed poll interval) over tight polling loops so you stay under the limit. ## A robust create-and-wait pattern ```typescript theme={null} async function runSwap() { let swap try { swap = await oneswap.swaps.createSwap({ userRef: 'user-1042', inSymbol: 'CBTC', amountIn: 0.01, outSymbol: 'HTEST', }) } catch (err) { // Bad pair, already-open swap, auth, or rate limit — no swap was created. console.error('Could not create swap:', (err as Error).message) return } // Show the user where to deposit. console.log(`Send ${swap.amountIn} ${swap.inSymbol} to ${swap.depositParty} before ${swap.deadline}`) const done = await oneswap.swaps.waitForSwap(swap.id) switch (done.status) { case 'returned': console.log(`Returned ${done.amountOut} ${done.outSymbol} to ${done.senderParty}`) break case 'refunded': console.log('Refunded — amount outside tolerance or below minOut. Input returned to sender.') break case 'expired': console.log('No deposit arrived before the deadline. Nothing happened.') break case 'failed': console.log('Unexpected failure:', done.error, '— input is refunded by the atomic guarantee.') break } } ``` If `waitForSwap` times out while a swap is still non-terminal, the swap may still settle. Resume with `getSwap(id)` rather than treating it as failed. # Swaps Source: https://docs.oneswap.cc/guides/swaps The full swap lifecycle: deposit parties, tolerances, return-to-sender, and reconciliation. Swaps let you offer token exchange to end-users who can only make a **plain fund transfer** — their wallet cannot sign a Canton DvP transaction. You create a swap, hand the user a Canton party to fund, and OneSwap does the rest custodially and atomically, returning the output token to the party that funded the swap. ## Lifecycle Call `swaps.createSwap` with your stable `userRef`, the input token and amount, and the output token. OneSwap resolves the `{ inSymbol, outSymbol }` pair to a visible pool and returns a [`Swap`](/reference/types#swap) in status `awaiting_deposit` with a per-user `depositParty` and a `deadline`. ```typescript theme={null} const swap = await oneswap.swaps.createSwap({ userRef: 'user-1042', inSymbol: 'CBTC', amountIn: 0.01, outSymbol: 'HTEST', }) ``` Tell your end-user to send **`amountIn` of `inSymbol`** to `swap.depositParty` before `swap.deadline`. This is a normal token transfer — the user's wallet never signs a swap. Once the deposit lands on-ledger, the swap moves to `deposit_detected`, then `swapping` while the atomic swap executes. On success the swap reaches `returned`: `amountOut` of `outSymbol` is sent back to `senderParty` — the exact party that funded the deposit. ## Status reference Terminal statuses are `returned`, `refunded`, `expired`, `failed`, and `cancelled`. | Status | Meaning | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------- | | `awaiting_deposit` | Created; waiting for the end-user's deposit to `depositParty`. | | `deposit_detected` | The deposit has been seen on-ledger. | | `swapping` | The atomic swap is in progress. | | `recovering` | A step failed while holding the deposit; it is being retried and the funds returned to the sender. Not terminal — keep polling. | | `needs_review` | Automatic recovery was exhausted. The funds are safe and a human is resolving it. Not terminal. | | `returned` | **Success.** `amountOut` of `outSymbol` was sent back to `senderParty`. | | `refunded` | The deposit was returned to the sender (deposit amount outside tolerance, or output below `minOut`). | | `expired` | No deposit arrived before `deadline`; nothing happened. | | `failed` | An unexpected error (rare); `error` is set. | | `cancelled` | Closed via `swaps.cancel()` before any deposit arrived; nothing happened. | ## Deposit-amount tolerance The deposit must be within **1%** of `amountIn`. If the amount that arrives is outside that band, the swap is **refunded** — OneSwap never guesses intent from a wrong amount. Show your users the exact `amountIn` and `inSymbol` and make it easy to send precisely that. ## Deposit deadline Every swap has a **60-minute** deposit window from creation, exposed as `deadline` (an ISO timestamp). If no deposit arrives before then, the swap becomes `expired` and nothing happens — the user was never charged. Surface the countdown to your user and create a fresh swap if they miss the window. ## Slippage and minimum output By default OneSwap applies **2% (200 bps)** slippage tolerance. You can override it per swap: * `slippageBps` — set a different tolerance in basis points (e.g. `100` for 1%). * `minOut` — set a hard floor on the output amount. If the swap would return less than `minOut` of `outSymbol`, it is **refunded** instead. ```typescript theme={null} const swap = await oneswap.swaps.createSwap({ userRef: 'user-1042', inSymbol: 'CBTC', amountIn: 0.01, outSymbol: 'HTEST', poolId: 'rt-...', // pass the pool id returned by your quote minOut: 0.95, // refund rather than return less than this slippageBps: 100, // 1% tolerance instead of the 2% default }) ``` Use [`quotes.get`](/reference/sdk-methods) to price the swap first. Quotes made with your SDK key already include the input-token network fee (`feeModel: 'deposit'`), so their `amountOut` matches settlement — use it directly as the basis for `minOut`, minus your slippage margin. ## Return-to-sender semantics The output is always paid back to the party that **funded** the deposit, reported as `senderParty` on the returned swap. You do not supply a destination address — there isn't one to get wrong. This is what makes these swaps safe for fund-transfer-only wallets: the user gets their output at the same party they sent from. ## One open swap per user At most **one open (non-terminal) swap per `userRef`** may exist at a time. If you call `createSwap` for a `userRef` that already has an open swap, the call throws `OpenSwapExistsError`: > this user already has an open swap; finish or let it expire first You do not have to wait out the deadline. [`swaps.getOpenSwap(userRef)`](/reference/sdk-methods#swaps-getopenswap) returns that open swap — use it to recover the id when you no longer have it (after a restart, or when the `createSwap` response was lost) — and [`swaps.cancel(id)`](/reference/sdk-methods#swaps-cancel) closes it if no deposit has arrived yet: ```typescript theme={null} import { OpenSwapExistsError } from '@oneswap/sdk' try { swap = await oneswap.swaps.createSwap({ userRef, inSymbol: 'CC', amountIn: 100, outSymbol: 'CBTC' }) } catch (err) { if (!(err instanceof OpenSwapExistsError)) throw err const open = await oneswap.swaps.getOpenSwap(userRef) if (open?.status === 'awaiting_deposit') { await oneswap.swaps.cancel(open.id) // nothing deposited — release it and retry } else if (open) { await oneswap.swaps.waitForSwap(open.id) // funds are in flight — let it finish } } ``` Once a deposit has arrived the swap holds funds and must run to completion — `cancel` throws `ConflictError` (409) in that case, so wait it out instead. See [Error handling](/guides/error-handling) for how to detect and recover from this. ## One pool per swap Every swap settles against exactly **one pool**. The `{ inSymbol, outSymbol }` pair must have a live pool that trades it directly; if it doesn't, `createSwap` errors (and `quotes.get` throws `NoDirectPoolError`). There is no multi-hop routing — to move between two tokens with no shared pool, run two swaps through an intermediate asset (usually CC), each with its own settlement and fees. SDK 1.3.0 and later accept `poolId` in `createSwap`. Pass the `poolId` returned by `quotes.get` to guarantee that settlement uses the pool you quoted. ## Network fee comes from the input A per-swap network fee is taken **from the input token** to cover the on-chain settlement cost. It is priced **live for every swap** — the measured cost of settling the swap on Canton (the swap's traffic size × the network's current price per MB, plus a small buffer), converted into the input token — so it tracks the real cost rather than a fixed amount (typically around **\$1.5–2** at recent network prices, and it moves with the network). Your end-user's wallet needs no CC or gas of any kind — they only ever send the input token. Account for this when you quote amounts to your users: the output reflects the input minus this network fee and the pool's 0.30% swap fee. ## Atomic settlement Swaps are atomic DvP. The swap either **completes and returns the output token**, or the **input is refunded** — funds are never stranded by a partial swap. That means every swap you create ends in a clean terminal state you can act on. ## Reconciling on your side Use your own `userRef` as the reconciliation key: * Store the returned `swap.id` (an `esc_...` id) against your `userRef` when you create a swap. * One open swap per `userRef` means there is never ambiguity about which swap a user's deposit belongs to. * On terminal status, record the outcome: `returned` (with `amountOut`), `refunded`, `expired`, `cancelled`, or `failed` (with `error`). ## Polling for status Poll `getSwap` on your own cadence: ```typescript theme={null} const swap = await oneswap.swaps.createSwap({ userRef: 'user-1042', inSymbol: 'CBTC', amountIn: 0.01, outSymbol: 'HTEST', }) const terminal = new Set(['returned', 'refunded', 'expired', 'failed', 'cancelled']) let current = await oneswap.swaps.getSwap(swap.id) while (!terminal.has(current.status)) { await new Promise((r) => setTimeout(r, 3000)) current = await oneswap.swaps.getSwap(swap.id) } console.log('Final status:', current.status) ``` ## Awaiting completion `waitForSwap` wraps the polling loop for you and resolves on the first terminal status (or on timeout): ```typescript theme={null} const done = await oneswap.swaps.waitForSwap(swap.id, { pollMs: 3000, // poll interval (default 3000) timeoutMs: 900000, // give up after 15 min (default 900000) }) switch (done.status) { case 'returned': console.log(`Returned ${done.amountOut} ${done.outSymbol} to ${done.senderParty}`) break case 'refunded': console.log('Refunded — amount out of tolerance, or below minOut') break case 'expired': console.log('No deposit arrived before the deadline') break case 'cancelled': console.log('Cancelled before any deposit arrived') break case 'failed': console.log('Unexpected failure:', done.error) break } ``` Swaps are live on OneSwap **devnet** and **mainnet** — see [API keys](/guides/api-keys) for getting your `sk_live_...` credential. # Trader SDK Source: https://docs.oneswap.cc/guides/trader-sdk Quote and trade a OneSwap wallet with an administrator-issued Trader SDK key. The Trader SDK lets an approved OneSwap account trade its own wallet from a server-side application. It is separate from the integrator SDK: a trader key is bound to one existing wallet and cannot onboard users or withdraw funds. ## Install ```bash theme={null} npm install @oneswap/trader-sdk ``` ## Get a trader key A OneSwap administrator enables Trader SDK access and issues a key for the approved account and wallet. A trader cannot enable access, create a key, change its wallet binding, or enable three-token fees through the SDK. Contact OneSwap when you need a new or replacement key. The key, account, bound wallet, and requested pool must all remain approved. OneSwap can revoke access immediately. A trader key can execute trades with real wallet funds. Keep it in a server-side secret manager. Never embed it in a website, browser extension, mobile app, repository, log, or analytics event. Ask OneSwap to revoke and replace an exposed key. ## Create the client ```ts theme={null} import { TraderSDK } from '@oneswap/trader-sdk' const trader = new TraderSDK({ apiKey: process.env.ONESWAP_TRADER_KEY!, environment: 'mainnet', }) ``` The wallet is resolved from the administrator-issued key, so SDK methods do not accept a `walletId`. Self-custody wallets also require an active OneSwap user mandate; the trader key never contains or replaces the self-custody key. ## Discover pools, tokens, and balances ```ts theme={null} const pools = await trader.pools() const tokens = await trader.tokens() const balances = await trader.balances() const pool = pools.find((candidate) => candidate.id === 'rt-...') if (!pool) throw new Error('Pool is unavailable to this trader') ``` A pool has an ordered pair of assets. `xToY: true` spends `assetX` and receives `assetY`; `false` reverses the direction. ## Quote and swap Quote immediately before a swap and use the quote to set the output floor: ```ts theme={null} const quote = await trader.quote({ poolId: pool.id, amountIn: 100, xToY: true, feeMode: 'prepaid', }) if (!quote.sufficientFunds) throw new Error('Insufficient spendable balance') const result = await trader.swap({ poolId: pool.id, amountIn: 100, xToY: true, minAmountOut: quote.amountOut * 0.99, feeMode: quote.feeMode, idempotencyKey: 'order-1042', }) ``` Use a unique `idempotencyKey` for each intended swap. Reuse it only when retrying that exact swap, so a timeout or process restart cannot execute the order twice. ## Three-token network fees When a OneSwap administrator has enabled the trader and configured a distinct fee instrument for a synchronous atomic pool, select it explicitly on both calls: ```ts theme={null} const tokenFeeQuote = await trader.quote({ poolId: pool.id, amountIn: 100, xToY: true, feeMode: 'token', }) if (tokenFeeQuote.sufficientFunds) { await trader.swap({ poolId: pool.id, amountIn: 100, xToY: true, minAmountOut: tokenFeeQuote.amountOut * 0.99, feeMode: 'token', idempotencyKey: 'order-1043', }) } ``` For Trader SDK quotes, `tokenFee.amount` is derived from the live Canton traffic cost, including the extra fee-token allocation. OneSwap subtracts measured reward recovery, applies the best applicable global, pool, account, or wallet network-fee promotion, and then converts CC → USDCx → the configured fee token at live prices. The quote reports the final amount and authoritative fee-token balance checks. A trader with a 100% promotion receives `amount: 0` and `promotionalWaiver: true`; settlement omits the fee allocation. A trader without that promotion pays the converted amount shown in the final quote. When charged, the swap input, output, and fee-token allocation settle atomically. Use the same pool, direction, amount, and `feeMode` for the quote and swap. Do not reuse a prepaid quote for a token-fee swap or switch fee modes after calculating `minAmountOut`. ## History and asynchronous intents ```ts theme={null} const history = await trader.history({ limit: 50 }) if (result.status === 'reserved' && result.intentId) { const status = await trader.intent(result.intentId) console.log(status.status) } ``` Synchronous pools return their settlement result directly. For an asynchronous pool, poll the returned intent until it reaches a terminal state. Three-token settlement is available only on synchronous atomic pools. ## Disable access Contact OneSwap to revoke a key, disable Trader SDK access, or change three-token eligibility. Revoked access is rejected on subsequent SDK calls. # Introduction Source: https://docs.oneswap.cc/introduction Embed token swaps, quotes, and live market data into your app with the OneSwap SDK. # OneSwap SDK OneSwap is an atomic delivery-versus-payment (DvP) DEX on the **Canton Network**. The SDK lets you embed token swaps, quoting, and live market data into your own app for your end-users. ```typescript theme={null} import { OneSwap } from '@oneswap/sdk' const oneswap = new OneSwap({ apiKey: 'sk_live_...' }) // Quote it first: how much HTEST for 0.01 CBTC? const quote = await oneswap.quotes.get({ from: 'CBTC', to: 'HTEST', amount: 0.01 }) console.log(`~${quote.amountOut} HTEST (price impact ${quote.priceImpactPct}%)`) // 1. Create a swap for your end-user const swap = await oneswap.swaps.createSwap({ userRef: 'user-1042', inSymbol: 'CBTC', amountIn: 0.01, outSymbol: 'HTEST', }) // 2. Tell the user to send `amountIn` of `inSymbol` to this Canton party console.log(swap.depositParty) // 3. Wait for OneSwap to detect the deposit, swap, and return the output const done = await oneswap.swaps.waitForSwap(swap.id) if (done.status === 'returned') { console.log(`Returned ${done.amountOut} ${done.outSymbol} to ${done.senderParty}`) } ``` ## How swaps work Swaps are built for integrators whose end-users' wallets **can only make a plain fund transfer** — they cannot sign a Canton DvP transaction themselves. Instead of asking the user to co-sign anything, you hand them a Canton party id to send funds to. OneSwap detects the deposit, performs the swap custodially and atomically, and returns the output token **to the party that funded the swap** (return-to-sender). 1. Your backend calls `swaps.createSwap` and gets back a per-user `depositParty` (a Canton party id) and a `deadline`. 2. You tell your end-user to send `amountIn` of `inSymbol` to `depositParty`. 3. OneSwap detects the deposit, performs the atomic swap, and returns the output token to the **depositing** party. 4. You poll `swaps.getSwap` (or await `swaps.waitForSwap`) until the swap reaches a terminal status. Because the swap is atomic DvP, it either completes and returns the output token or the input is refunded — funds are never left stranded by a partial swap. ## Market data and quotes Alongside swap execution, the SDK reads the DEX itself: * **`quotes.get({ from, to, amount })`** — a full quote for a pair: expected output, price impact, and the fee breakdown. The SDK resolves which pool trades the pair and the direction for you. * **`pools.list()` / `pools.get(id)`** — every visible pool with live reserves and fee configuration, or one pool with its settled-swap history. * **`pools.getTicker(id)`** — live USD price, 24h change, and 24h volume for a pool. * **`tokens.list()`** — the tokens OneSwap can settle. Every swap settles against exactly one pool. When no pool trades a pair directly, `quotes.get` throws `NoDirectPoolError` — there is no multi-hop routing, so route through an intermediate asset (usually CC) as two separate swaps. ## Who it's for * Apps and wallets whose users can transfer tokens but cannot sign a Canton DvP transaction. * Integrators who want a swap embedded in their product without building settlement logic. * Any backend that can call an HTTP API and hold a stable id for each of its users. **Availability.** Swaps are live on OneSwap **devnet** and **mainnet**. All you need is an SDK API key (`sk_live_...`) from your OneSwap account — [swap.oneswap.cc](https://swap.oneswap.cc) (mainnet) or [devnet.oneswap.cc](https://devnet.oneswap.cc) (devnet); see [API keys](/guides/api-keys). Market data and quotes are read-only and available on both networks. ## What you get * **Swaps** — create a swap, hand the user a deposit party, poll to completion. * **Return-to-sender** — output is always paid back to the party that funded the swap. * **Atomic DvP** — the swap completes and returns output, or the input is refunded. * **No gas for your users** — the per-swap network fee is taken from the input token, so the end-user's wallet needs no CC. * **Quotes and market data** — price a swap before creating it, and read pools, tickers, and tokens. Install, mint a key, and run your first swap The full lifecycle, tolerances, and reconciliation Every method and parameter Trade a wallet programmatically with optional three-token fees Every TypeScript shape the SDK returns # Quickstart Source: https://docs.oneswap.cc/quickstart Quote and run your first swap in under 5 minutes. This walks you through one complete swap: quote it, create it, hand your user a deposit party, and wait for the output to be returned to them. ```bash theme={null} npm install @oneswap/sdk ``` Create an SDK key from your OneSwap account (self-serve) — [swap.oneswap.cc](https://swap.oneswap.cc) for mainnet, [devnet.oneswap.cc](https://devnet.oneswap.cc) for devnet. The key looks like `sk_live_` followed by 48 hex characters and is shown **once** at creation — store it somewhere safe. See [API keys](/guides/api-keys) for the full flow. Keep the key on your **server only**. It is your integrator credential; never ship it to a browser or to an end-user. ```typescript theme={null} import { OneSwap } from '@oneswap/sdk' const oneswap = new OneSwap({ apiKey: 'sk_live_...' }) ``` The client sends your key on every request as the `x-sdk-key` header. It talks to **mainnet** by default; pass `environment: 'devnet'` to use the devnet backend — the SDK resolves the URL itself, so you never set one: ```typescript theme={null} const oneswap = new OneSwap({ apiKey: 'sk_live_...', environment: 'devnet', // 'mainnet' (default) | 'devnet' }) ``` Before creating anything, ask what the swap would return. The SDK finds the pool that trades the pair and derives the direction for you: ```typescript theme={null} const quote = await oneswap.quotes.get({ from: 'CBTC', // token the user pays with to: 'HTEST', // token the user receives amount: 0.01, // amount of `from` to swap }) console.log(quote.amountOut) // expected output, before it moves console.log(quote.priceImpactPct) // price impact of this trade size console.log(quote.poolId) // the pool the pair resolved to ``` If no pool trades the pair directly, this throws `NoDirectPoolError` — route through an intermediate asset (usually CC) as two separate swaps. ```typescript theme={null} const swap = await oneswap.swaps.createSwap({ userRef: 'user-1042', // your stable id for this end-user inSymbol: 'CBTC', // token the user deposits amountIn: 0.01, // amount of inSymbol to swap outSymbol: 'HTEST', // token to return to the user poolId: quote.poolId, // settle against the pool that produced the quote }) console.log(swap.id) // 'esc_...' console.log(swap.status) // 'awaiting_deposit' console.log(swap.depositParty) // the Canton party the user must fund console.log(swap.deadline) // ISO timestamp — deposit before this ``` Only one open swap is allowed per `userRef` at a time. Tell your end-user to send **`amountIn` of `inSymbol`** (here, `0.01 CBTC`) to `swap.depositParty` before `swap.deadline` (60 minutes from creation). The deposit must land within **1%** of `amountIn`, or it is refunded. OneSwap never guesses intent from a wrong amount. ```typescript theme={null} const done = await oneswap.swaps.waitForSwap(swap.id) if (done.status === 'returned') { // Success — output was paid back to the party that funded the swap console.log(`Returned ${done.amountOut} ${done.outSymbol} to ${done.senderParty}`) } else { // refunded | expired | failed console.log(`Swap ended as ${done.status}`, done.error) } ``` `waitForSwap` resolves once the swap reaches a terminal status (`returned`, `refunded`, `expired`, or `failed`), or when its local timeout is hit. ## Complete example ```typescript theme={null} import { OneSwap } from '@oneswap/sdk' const oneswap = new OneSwap({ apiKey: 'sk_live_...' }) async function swapForUser() { // 1. Quote it first const quote = await oneswap.quotes.get({ from: 'CBTC', to: 'HTEST', amount: 0.01 }) console.log(`Expecting ~${quote.amountOut} HTEST (impact ${quote.priceImpactPct}%)`) // 2. Create the swap const swap = await oneswap.swaps.createSwap({ userRef: 'user-1042', inSymbol: 'CBTC', amountIn: 0.01, outSymbol: 'HTEST', poolId: quote.poolId, }) // 3. Show your end-user where to send the deposit console.log(`Send ${swap.amountIn} ${swap.inSymbol} to ${swap.depositParty}`) console.log(`Deposit before ${swap.deadline}`) // 4. Wait for OneSwap to detect, swap, and return the output const done = await oneswap.swaps.waitForSwap(swap.id) if (done.status === 'returned') { console.log(`Done — returned ${done.amountOut} ${done.outSymbol} to ${done.senderParty}`) } else { console.log(`Swap ended as ${done.status}`, done.error) } } swapForUser() ``` ## Reading the market The same client reads pools, tickers, and tokens — useful for building your own token pickers and price displays: ```typescript theme={null} const tokens = await oneswap.tokens.list() // what can be swapped const pools = await oneswap.pools.list() // every visible pool, with live reserves // Live market data for the pool your quote resolved to const ticker = await oneswap.pools.getTicker(quote.poolId) console.log(`${ticker.pair}: $${ticker.price.usd} (${ticker.priceChange24h.pct ?? '—'}% 24h)`) console.log(`24h volume: $${ticker.volume24h.usd} across ${ticker.volume24h.swaps} swaps`) ``` `priceChange24h` fields are `null` while the price history is warming up (the first 24h after a pool starts being tracked). ## What's next Lifecycle, tolerances, min-out, and reconciliation Create, rotate, and revoke keys safely Typed errors, refunds, expiries, and robust polling The full client surface # SDK methods Source: https://docs.oneswap.cc/reference/sdk-methods The full OneSwap client surface: swaps, quotes, pools, and tokens. The client exposes four namespaces: `swaps` (execution), `quotes`, `pools`, and `tokens` (market data). ## Constructor ```typescript theme={null} import { OneSwap } from '@oneswap/sdk' const oneswap = new OneSwap({ apiKey: 'sk_live_...' }) ``` Your integrator API key (`sk_live_` followed by 48 hex chars). Sent on every request as the `x-sdk-key` header. Keep it server-side only. Which OneSwap backend to use. The SDK resolves the URL itself — you never pass a raw URL. Per-request timeout in milliseconds. ```typescript theme={null} // Point at devnet for integration testing const oneswap = new OneSwap({ apiKey: 'sk_live_...', environment: 'devnet', }) ``` ## `swaps.createSwap` Create a swap. Returns a [`Swap`](/reference/types#swap) in status `awaiting_deposit`, carrying the `depositParty` your end-user must fund and the `deadline` they must beat. SDK 1.3.0 added the optional `poolId` argument. ```typescript theme={null} oneswap.swaps.createSwap(args: { userRef: string inSymbol: string amountIn: number outSymbol: string poolId?: string minOut?: number slippageBps?: number }): Promise ``` Your stable id for the end-user. Only one open swap per `userRef` at a time. The token the user deposits, e.g. `'CBTC'`. Decimal amount of `inSymbol` to swap. The deposit must arrive within **1%** of this amount. The token to return to the user, e.g. `'HTEST'`. Pin the swap to a specific visible or API-key-authorized pool. The pool must trade exactly `inSymbol`/`outSymbol`. Pass the `poolId` returned by `quotes.get` to settle against the pool you quoted. Optional hard floor on the output amount. If the swap would return less than this, it is refunded. Optional slippage tolerance in basis points. Defaults to `200` (2%). ```typescript theme={null} const swap = await oneswap.swaps.createSwap({ userRef: 'user-1042', inSymbol: 'CBTC', amountIn: 0.01, outSymbol: 'HTEST', poolId: 'rt-...', minOut: 0.95, slippageBps: 100, }) console.log(swap.id) // 'esc_...' console.log(swap.status) // 'awaiting_deposit' console.log(swap.depositParty) // the party the user must fund console.log(swap.deadline) // ISO timestamp ``` Throws if `{ inSymbol, outSymbol }` has no pool available to the API key (`no pool for IN/OUT`), if the specified `poolId` is unavailable or trades a different pair, or `OpenSwapExistsError` if the `userRef` already has an open swap. See [Error handling](/guides/error-handling). `oneswap.escrow` — the 1.0.0 name for this namespace — still works as a deprecated alias of the same instance. ## `swaps.getSwap` Fetch the current state of a swap by id. Only returns swaps owned by your integrator. ```typescript theme={null} oneswap.swaps.getSwap(id: string): Promise ``` The swap id returned by `createSwap` (`esc_...`). ```typescript theme={null} const swap = await oneswap.swaps.getSwap('esc_...') console.log(swap.status) ``` ## `swaps.waitForSwap` Poll a swap until it reaches a terminal status (`returned`, `refunded`, `expired`, `failed`, or `cancelled`), or until the local timeout. Resolves with the final [`Swap`](/reference/types#swap). ```typescript theme={null} oneswap.swaps.waitForSwap(id: string, opts?: { pollMs?: number timeoutMs?: number }): Promise ``` The swap id to wait on. Poll interval in milliseconds. Give up after this many milliseconds (default 15 minutes). On timeout the swap may still be settling — resume with `getSwap(id)`. ```typescript theme={null} const done = await oneswap.swaps.waitForSwap('esc_...', { pollMs: 3000, timeoutMs: 900000, }) if (done.status === 'returned') { console.log(`Returned ${done.amountOut} ${done.outSymbol} to ${done.senderParty}`) } ``` ## `swaps.getOpenSwap` Added in SDK 1.2.0. Fetch the user's open (non-terminal) swap, or `null` if they have none. A `userRef` may hold only one open swap at a time — `createSwap` throws [`OpenSwapExistsError`](/guides/error-handling) while one is live. Use this to recover the swap id when you no longer have it: after a process restart, or when the `createSwap` response was lost in flight. ```typescript theme={null} oneswap.swaps.getOpenSwap(userRef: string): Promise ``` Your stable identifier for the end user, the same value passed to `createSwap`. ```typescript theme={null} const open = await oneswap.swaps.getOpenSwap('user-123') if (open) { console.log(`${open.id} is ${open.status}`) } ``` ## `swaps.cancel` Added in SDK 1.2.0. Cancel a swap that has not yet received a deposit, freeing the user to start another immediately instead of waiting out the one-hour deposit deadline. Resolves with the closed [`Swap`](/reference/types#swap) (`status: 'cancelled'`). Only a swap still in `awaiting_deposit` can be cancelled. Once a deposit has arrived the swap holds funds and must run to completion — cancelling then throws `ConflictError` (409), and you should `waitForSwap` instead. Calling this on an already-finished swap returns it unchanged, so it is safe to retry. ```typescript theme={null} oneswap.swaps.cancel(id: string): Promise ``` The swap id to cancel (`esc_...`). Together with `getOpenSwap`, this is how you recover from a blocked user: ```typescript theme={null} import { OpenSwapExistsError } from '@oneswap/sdk' try { swap = await oneswap.swaps.createSwap({ userRef: 'user-123', inSymbol: 'CC', amountIn: 100, outSymbol: 'CBTC', }) } catch (err) { if (!(err instanceof OpenSwapExistsError)) throw err const open = await oneswap.swaps.getOpenSwap('user-123') if (open?.status === 'awaiting_deposit') { await oneswap.swaps.cancel(open.id) // nothing was deposited — release and retry } else if (open) { await oneswap.swaps.waitForSwap(open.id) // funds are in flight — let it finish } } ``` ## `quotes.get` Quote a swap of `amount` `from`-tokens into `to`-tokens. The SDK resolves the pool that trades the pair (or takes `poolId` verbatim), derives the direction, and returns a [`QuoteResult`](/reference/types#quoteresult) — the quote plus the resolved `poolId` and `xToY`. ```typescript theme={null} oneswap.quotes.get(args: { from: string to: string amount: number poolId?: string walletId?: string }): Promise ``` Symbol of the token you pay with, e.g. `'CC'`. Symbol of the token you receive, e.g. `'CBTC'`. Amount of `from` to swap. Must be positive. Pin a specific pool instead of resolving one from the symbol pair. The pool must still trade exactly `from`/`to`. A custodial wallet id you own — the quote then reports `walletBalanceIn` and `sufficientBalance` for that wallet. Requires an authenticated session context, so most SDK callers omit it. ```typescript theme={null} const quote = await oneswap.quotes.get({ from: 'CC', to: 'CBTC', amount: 100 }) console.log(quote.amountOut) // expected output in CBTC console.log(quote.priceImpactPct) // price impact of this trade size console.log(quote.effFeeBps) // effective pool fee after any discount console.log(quote.networkFeeIn) // network fee carved from the input console.log(quote.poolId) // the pool the pair resolved to console.log(quote.xToY) // direction within that pool ``` Throws [`NoDirectPoolError`](/guides/error-handling#the-no-direct-pool-case) when no pool trades the pair (there is no multi-hop routing) and `AmbiguousPoolPairError` (with `candidates`) when several do — retry with `poolId`. The pool list backing symbol resolution is cached for 30 seconds per client instance. **Quotes made with your SDK key are settlement-accurate.** Because the SDK sends your `x-sdk-key` on every request, the backend prices your quotes with the same fee model `swaps.createSwap` settles with: the live per-swap network fee is carved from the input (`networkFeeIn` > 0, `effInput` = `amount` − `networkFeeIn`), so `amountOut` matches what the swap actually returns (modulo price movement between quote and settlement). The response reports this as `feeModel: 'deposit'`. Since the fee is roughly flat in USD per swap, it dominates very small amounts — check `networkFeeIn` against `amount` before quoting tiny swaps to users, and base `minOut` on this quote's `amountOut`. ## `pools.list` All pools available to the caller, with live reserves and fee configuration. ```typescript theme={null} oneswap.pools.list(): Promise ``` ```typescript theme={null} const pools = await oneswap.pools.list() for (const p of pools) { console.log(`${p.id}: ${p.assetX.symbol}/${p.assetY.symbol}`, p.reserveX, p.reserveY) } ``` ## `pools.get` One pool plus its full settled-swap history. ```typescript theme={null} oneswap.pools.get(poolId: string): Promise // { pool, swaps } ``` The pool id (`rt-...`), from `pools.list()` or a quote's `poolId`. ```typescript theme={null} const { pool, swaps } = await oneswap.pools.get('rt-...') console.log(pool.feeBps, swaps.length) ``` ## `pools.getTicker` Live market data for a pool: USD price derived from the pool's own reserve ratio, 24h change, and 24h volume. Returns a [`PoolTicker`](/reference/types#poolticker). Cached up to 30s server-side. ```typescript theme={null} oneswap.pools.getTicker(poolId: string): Promise ``` The pool id (`rt-...`). ```typescript theme={null} const ticker = await oneswap.pools.getTicker('rt-...') console.log(ticker.pair) // 'CC/CBTC' console.log(ticker.base) // the asset being priced, e.g. 'CBTC' console.log(ticker.price.usd) // e.g. '61462.225' console.log(ticker.priceChange24h.pct) // e.g. '1.8342' — or null during warm-up console.log(ticker.volume24h.usd) // 24h volume in USD console.log(ticker.volume24h.swaps) // number of swaps in the window ``` `priceChange24h` fields are `null` until the pool's price history is at least 24h old, and `price.usd` is `null` for pools that cannot be USD-priced (e.g. unseeded pools). ## `tokens.list` The tokens OneSwap can settle — display symbol plus the on-ledger instrument identity. ```typescript theme={null} oneswap.tokens.list(): Promise ``` ```typescript theme={null} const tokens = await oneswap.tokens.list() console.log(tokens.map((t) => t.symbol)) // ['CC', 'CBTC', ...] ``` # Types Source: https://docs.oneswap.cc/reference/types TypeScript shapes used by the OneSwap SDK. ## Client options Options passed to the `OneSwap` constructor. ```typescript theme={null} interface OneSwapConfig { apiKey: string // 'sk_live_...' — sent as the x-sdk-key header environment?: 'mainnet' | 'devnet' // default 'mainnet'; the SDK resolves the URL itself timeout?: number // per-request timeout in ms (default 30000) } ``` ## `CreateSwapArgs` The argument to `oneswap.swaps.createSwap`. ```typescript theme={null} interface CreateSwapArgs { userRef: string // your stable id for the end-user (one open swap per userRef at a time) inSymbol: string // token the user deposits, e.g. 'CBTC' amountIn: number // decimal amount of inSymbol to swap outSymbol: string // token to return to the user, e.g. 'HTEST' poolId?: string // pin the pool returned by a quote (SDK 1.3.0+) minOut?: number // optional hard floor on output; below it the swap is refunded slippageBps?: number // optional; default 200 (2%) } ``` When you quote first, pass the quote's `poolId` to `createSwap` so both operations use the same pool. ## `WaitForSwapOptions` The optional second argument to `oneswap.swaps.waitForSwap`. ```typescript theme={null} interface WaitForSwapOptions { pollMs?: number // default 3000 timeoutMs?: number // default 900000 (15 min) } ``` ## `SwapStatus` The lifecycle status of a swap. Terminal statuses are `returned`, `refunded`, `expired`, `failed`, and `cancelled`. ```typescript theme={null} type SwapStatus = | 'awaiting_deposit' | 'deposit_detected' | 'swapping' | 'recovering' | 'needs_review' | 'returned' | 'refunded' | 'expired' | 'failed' | 'cancelled' ``` SDK 1.2.0 added `cancelled`, and added `recovering` and `needs_review` to the union — those two were always reachable, but were missing from the published type. Both are **non-terminal**: the funds are in motion and `waitForSwap` keeps polling. If you `switch` exhaustively over `SwapStatus`, you may need new cases. ## `Swap` Returned by `createSwap`, `getSwap`, and `waitForSwap`. ```typescript theme={null} interface Swap { id: string // 'esc_...' status: SwapStatus poolId: string inSymbol: string outSymbol: string amountIn: number minOut: number | null depositParty: string // the Canton party id the end-user must fund deadline: string // ISO timestamp; deposit must arrive before this amountOut?: number | null // set once returned senderParty?: string | null // the party that funded (output is returned here) error?: string | null } ``` | Field | Notes | | -------------- | ------------------------------------------------------------------------------------------- | | `id` | Swap id, `esc_...`. Store it against your `userRef`. | | `status` | See [`SwapStatus`](#swapstatus) and the [status reference](/guides/swaps#status-reference). | | `poolId` | The pool the `{ inSymbol, outSymbol }` pair resolved to. | | `amountIn` | The amount the user must deposit — within **1%** tolerance. | | `minOut` | The hard output floor, or `null` if none was set. | | `depositParty` | The Canton party id the end-user sends `amountIn` of `inSymbol` to. | | `deadline` | ISO timestamp, 60 minutes from creation. Deposit before this or the swap expires. | | `amountOut` | The returned amount of `outSymbol`; set once `status` is `returned`. | | `senderParty` | The party that funded the deposit; the output is returned here. | | `error` | Set when `status` is `failed`. | ## `GetQuoteArgs` The argument to `oneswap.quotes.get`. ```typescript theme={null} interface GetQuoteArgs { from: string // symbol of the token you pay with, e.g. 'CC' to: string // symbol of the token you receive, e.g. 'CBTC' amount: number // amount of `from` to swap (positive) poolId?: string // pin a pool instead of resolving from symbols walletId?: string // custodial wallet id — adds walletBalanceIn/sufficientBalance } ``` ## `Quote` A swap quote. Amounts are numbers denominated in the input/output token. ```typescript theme={null} interface Quote { amountOut: number // expected output in the `to` token priceImpactPct: number // price impact of this trade size, in percent networkFeeIn: number // per-swap network fee carved from the input. Priced with the // settlement fee model when quoting with your SDK key // (feeModel 'deposit'); 0 under the 'prepaid' model swapFeeBps: number // the pool's configured fee, in basis points effFeeBps: number // effective fee after any discount discountBps: number // discount applied to the platform slice, in bps newReserveX: number // pool reserve X after this swap newReserveY: number // pool reserve Y after this swap effInput: number // input actually swapped (amount − networkFeeIn) inputCredit: number // input credited to the pool reserve (effInput − platformFee) platformFee: number // platform slice of the pool fee, in the input token lpFee: number // LP slice of the pool fee, in the input token inSym: string // symbol of the input token lpShare: number // LP share of the pool fee (fraction) platformShare: number // platform share of the pool fee (fraction) effectiveFeeRate: number // effFeeBps as a fraction chargedPlatformRate: number // platform rate actually charged, as a fraction walletBalanceIn?: number // only when walletId was passed: spendable input balance sufficientBalance?: boolean // only when walletId was passed: balance covers `amount` feeModel?: 'deposit' | 'prepaid' // how the network fee was priced: 'deposit' (carved from // the input — the model your SDK-keyed quotes use, matching // settlement) or 'prepaid' (fee charged outside the input) } ``` ## `QuoteResult` What `quotes.get` returns: the [`Quote`](#quote) plus the resolution the SDK did for you. ```typescript theme={null} interface QuoteResult extends Quote { poolId: string // the pool the pair resolved to xToY: boolean // direction within that pool (true = paying with assetX) } ``` ## `Token` One entry from `tokens.list()`. ```typescript theme={null} interface Token { symbol: string // display symbol, e.g. 'CC' admin: string // on-ledger instrument admin party id: string // on-ledger instrument id, e.g. 'Amulet' registryUrl?: string // registrar base URL, when the token needs a dedicated one } ``` ## `Pool` One entry from `pools.list()` (and the `pool` field of [`PoolDetail`](#pooldetail)). ```typescript theme={null} interface PoolAsset { symbol: string admin: string id: string } interface Pool { id: string // 'rt-...' name: string | null assetX: PoolAsset assetY: PoolAsset reserveX: number // live reserve of assetX reserveY: number // live reserve of assetY feeBps: number // total swap fee in basis points totalLpTokens: number visible?: boolean swapsEnabled?: boolean // false = liquidity-only mode (quotes/swaps rejected) asyncSettlement?: boolean lpFeeShare?: number | null platformFeeShare?: number | null createdAt?: string primary?: boolean // pools.list() only: the operator-designated default pool swaps?: number // pools.list() only: settled-swap count } ``` ## `PoolDetail` What `pools.get(id)` returns. ```typescript theme={null} interface PoolDetail { pool: Pool swaps: PoolSwap[] // full settled-swap history, oldest first } // A settled swap as recorded by the backend. Wire shape is the raw ledger row: // snake_case keys, numeric columns serialized as strings. interface PoolSwap { id: string pool_id: string at: string // ISO timestamp update_id: string | null trader: string x_to_y: boolean amount_in: string amount_out: string network_fee_in: string swap_fee: string new_reserve_x: string new_reserve_y: string } ``` ## `PoolTicker` What `pools.getTicker(id)` returns. Formatted figures are strings; `null` means "not derivable right now". ```typescript theme={null} interface PoolTicker { poolId: string pair: string // e.g. 'CC/CBTC' — assetX/assetY as configured on the pool base: string | null // the asset being priced (e.g. 'CBTC'); null when un-priceable pricedVia: string // how the USD value was derived (e.g. 'CC/USDCx') price: { usd: string | null } priceChange24h: { pct: string | null // percent change vs ~24h ago; null during warm-up from: string | null // USD price ~24h ago to: string | null // USD price now } volume24h: { usd: string | null // 24h volume at current USD prices swaps: number // number of swaps in the window } asOf: string // ISO timestamp the ticker was computed } ``` `priceChange24h` fields are `null` until the pool's hourly price history is at least 24h old (warm-up), and `price.usd` is `null` when the pool cannot be USD-priced (e.g. unseeded). ## `PoolPairCandidate` Carried by `AmbiguousPoolPairError.candidates` when several pools trade a requested pair. ```typescript theme={null} interface PoolPairCandidate { poolId: string name: string | null assetX: string // symbol assetY: string // symbol } ```