# Balances and Open Orders Source: https://docs.kuru.io/accounts/balances-and-reservations Understand which funds are available, reserved, or committed to liquidity. Depositing assets increases your available trading balance. Placing an order or providing passive liquidity commits some of that balance until the action is completed or unwound. | Balance category | What it means | Available to withdraw? | | - | - | - | | Available | Funds that are not committed to orders or liquidity | Subject to withdrawal capacity and checks | | Reserved for orders | Funds backing the unfilled portion of open orders | After the reservation is released | | Passive liquidity | Inventory committed to a liquidity position | After removing it from the position | ## What an order reserves A sell order reserves the asset being sold. A buy order reserves the payment asset and the maker-fee allowance needed if it fills. The reservation prevents the same funds from backing multiple orders. It does not mean the trade has already happened. ## A partial-fill example Suppose you deposit 1,000 USDC and place a resting order to buy 0.2 WETH at 2,500 USDC. For this example, assume no fees. | Step | Available USDC | Reserved USDC | WETH received | | - | -: | -: | -: | | Deposit | 1,000 | 0 | 0 | | Place the order | 500 | 500 | 0 | | 0.1 WETH fills | 500 | 250 | 0.1 | | Cancel the remainder | 750 | 0 | 0.1 | With fees, the reservation and final balance also reflect the applicable charge. See [Fees](/matching-engine/fees). ## Passive liquidity is separate Providing passive liquidity moves assets out of available balance into a position. That inventory is not an open-order reservation. It can change composition as traders buy and sell against the position. A balance display that adds only available and reserved funds does not include passive-position inventory. Index [passive-band events](/matching-engine/passive-liquidity) separately when reconciling market-wide liquidity. For integration details, use [Accounts and Funding](/sdk/accounts) and the [balance API](/api/data-source/reference/user-balances). # Deposits and Withdrawals Source: https://docs.kuru.io/accounts/deposits-and-withdrawals Move assets between your wallet and your trading balance. Your wallet balance and your Kuru trading balance are separate. Deposit assets before using them to trade; withdraw available assets when you want to move them back to a wallet. ## Deposit into your main account For an ERC-20 token, approve Kuru's custody contract to transfer the amount, then submit the deposit. Native MON deposits send MON with the deposit transaction instead of using an approval. Deposits always credit the main account. You can fund another owner's main account, but doing so does not give you permission to trade or withdraw their funds. To fund a subaccount, deposit into the main account and then make an internal transfer. Wait for a successful transaction and confirm the credited balance before trading. Token support and valid price data are required for deposits as well as withdrawals. ## Release funds before withdrawing Only available funds can be withdrawn. Cancel the unfilled portion of an order to release its reservation. Transfer any subaccount proceeds back to the main account. A partial fill cannot be undone by canceling the remainder. You keep the asset bought or the proceeds received from the executed portion. ## Choose the receiving wallet Withdraw from the main account and specify a recipient wallet. This sends assets out of Kuru; it does not credit another Kuru trading account, even if the recipient also uses Kuru. The owner or a signer with withdrawal authority can submit this action. Trading permission alone does not allow it. ## Withdrawal availability Kuru also checks a shared withdrawal allowance and valid token prices. An available account balance alone does not guarantee that a withdrawal will succeed. The full requested amount is paid or the transaction reverts. There is no pending withdrawal queue or partial payout. On current mainnet, capacity comes from a shared \$200,000 bucket that refills continuously over about 24 hours, plus deposit credit that expires after 24 hours. Read [Withdrawal Availability](/accounts/withdrawal-availability) for how capacity works, a numbers example, and what to check if a withdrawal fails. Developers can use [Accounts and Funding](/sdk/accounts) for the exact calls. # One Click Trading Source: https://docs.kuru.io/accounts/one-click-trading Trade with a passkey wallet without approving every order in your main wallet. One Click Trading lets you place and cancel orders without signing a wallet transaction in your main wallet each time. It uses a passkey wallet powered by [Mera](https://www.category.xyz/blogs/mera-crypto-onboarding-with-only-a-passkey-on-any-network), developed by Category Labs. ## How it works When you enable One Click Trading: 1. **Create a passkey wallet.** Kuru creates a Mera wallet secured by your device's passkey. You can use Face ID, Touch ID, or your device PIN to unlock it, depending on your device. 2. **Authorize trading.** Your main wallet grants the passkey wallet trading permission for seven days. 3. **Set up trading access.** Kuru configures a trading API key for the passkey wallet, which acts as an authorized signer for your account. 4. **Trade with one click.** Place and cancel orders without manually approving each transaction in your main wallet. ## Permissions and security * **Trading only:** The passkey wallet can trade on your behalf, but cannot withdraw funds. * **Seven-day authorization:** The trading permission expires after seven days. Renew it to keep using One Click Trading. * **Main-wallet control:** Your main wallet retains ownership of the account and can revoke the passkey wallet's trading permission. Trading permission can still change the value and composition of your holdings. For the full permission scope and revocation behavior, see [Trading Permissions](/accounts/signers-and-permissions). # Accounts Source: https://docs.kuru.io/accounts/overview How your wallet, trading balance, and orders fit together. A Kuru account keeps track of your trading balances, open orders, and liquidity positions. Your wallet controls the account and authorizes actions such as depositing, trading, and withdrawing. ## Wallet balance and trading balance Assets in your wallet are separate from assets deposited into Kuru. Depositing moves assets into the exchange's smart contracts and credits your trading account. Withdrawing moves available assets out of the exchange. Your account balance can be used across markets that accept the same asset. You do not need a separate deposit for every order book. ## Available and committed funds Some of your balance may be committed to open orders or passive liquidity. Only available funds can be used for a new action or withdrawn. For example, a buy order reserves the asset you are spending. Canceling its unfilled remainder releases that reservation. See [Balances and Open Orders](/accounts/balances-and-reservations). ## Separating strategies [Subaccounts](/accounts/subaccounts) let you maintain separate balances and orders under one owner. This can help you keep the funds used by one strategy separate from another. ## Letting a bot trade You can give another wallet permission to act for your account. This is useful for a trading bot or an application that signs trading actions on your behalf. Permissions determine what that wallet can do. Read [Trading Permissions](/accounts/signers-and-permissions) before granting access. To begin funding an account, see [Deposits and Withdrawals](/accounts/deposits-and-withdrawals). # Trading Permissions Source: https://docs.kuru.io/accounts/signers-and-permissions Give a bot access and understand the scope of that access. You can authorize another wallet to act for your Kuru account. This is useful for a trading bot or an application that signs actions on your behalf, without sharing your owner key. ## Access covers the whole account family Permissions apply to your main account and every current or future subaccount. You cannot give a signer access to just one subaccount in this account model. | Permission | What it allows | | - | - | | Trading | Place, replace and cancel orders; swap; manage passive liquidity; create subaccounts; configure permitted trading hooks | | Internal transfers | Move available funds between accounts owned by the same root | | Withdrawals | Withdraw from the main account to a chosen recipient, and transfer funds within the family | | Administration | Manage signers and exercise all of the permissions above | Trading access can change the value and composition of your holdings. It is not a spending limit or a restriction to particular markets. Use separate owners when strategies require separate permission boundaries. ## Expiry and revocation Access may expire at a chosen time or remain active until revoked. Permissions are checked when an action executes, not only when it is signed. Revoking a signer removes its access across the family. It does not cancel resting orders or remove passive liquidity. Decide separately whether to close those positions. Granting or revoking a signer also invalidates older signed trading instructions that use the previous authorization state. Other bots using the same owner may need to refresh their instructions. Creating a subaccount does not cause this invalidation. ## Rotating a key Stop new instructions from the old signer, reconcile outstanding transactions, and revoke its permissions. Grant the replacement the permissions it needs, confirm the authorization, and resume using fresh instructions. Logging out of Relay or letting its login token expire does not revoke onchain permissions. Developers should follow [Signer Lifecycle and Nonces](/sdk/signer-lifecycle). # Subaccounts Source: https://docs.kuru.io/accounts/subaccounts Keep separate trading balances under one owner. Subaccounts separate the funds, orders, and liquidity positions used by different strategies. You might keep a market-making balance separate from funds used for discretionary trading. ## Separate balances, shared control An order uses the balance of the account it belongs to. It cannot automatically draw on funds in another subaccount or in the main account. All subaccounts share the same owner and trading permissions. Giving a bot trading access lets it trade across the entire account family, including subaccounts created later. A subaccount separates balances; it does not restrict a bot to one strategy. ## Funding a subaccount Deposit into your main account first, then transfer available funds into the subaccount. To withdraw subaccount funds to a wallet, transfer them back to the main account first. Internal transfers move available balances. They do not move orders or liquidity positions. Release committed funds before transferring them. ## Creating subaccounts The owner, an administrator, or an authorized trading signer can create a subaccount. There is no new wallet to fund or private key to manage. Names such as “Market making” are labels supplied by your application. Developers can follow [Creating Subaccounts](/sdk/subaccounts) for account IDs, creation calls, and balance transfers. # Withdrawal Availability Source: https://docs.kuru.io/accounts/withdrawal-availability What withdrawal capacity is, how it refills, and why a withdrawal can fail even when you have funds. Every withdrawal needs two things: 1. **Available balance** in your main account for the token you are withdrawing. 2. **Withdrawal capacity**: enough room in Kuru's shared withdrawal budget to cover the withdrawal's USD value. Having funds in your account does not guarantee that a withdrawal will succeed. Capacity must also be available when the transaction executes. ## What withdrawal capacity is Withdrawal capacity is a protocol-wide limit, measured in USD, on how much value can leave Kuru over time. It is **shared across all accounts and all supported tokens**. It is not a personal or per-token limit, so withdrawals by other users draw from the same capacity as yours. Each withdrawal is valued in USD at the token's current price and uses that amount of capacity. There is **no withdrawal queue**. A withdrawal is either paid in full immediately or the whole transaction reverts. ## Where capacity comes from Capacity has two sources. ### The withdrawal bucket The main source is a single global bucket: | Setting | Current mainnet value | | - | - | | Bucket size | \$200,000 | | Refill rate | About \$8,333 per hour (about \$2.31 per second) | | Time to refill from empty | About 24 hours | The bucket refills **continuously**. It does not reset all at once at a fixed time each day. For example, if withdrawals reduce it to \$50,000, it holds about \$58,333 an hour later. It never holds more than \$200,000, so leaving it full does not build up extra capacity. ### Deposit credit Each deposit also adds one-time credit equal to the deposit's USD value. Deposit credit expires **24 hours** after the deposit, even if it is never used. Deposits do not refill the bucket. Withdrawals use the oldest unexpired deposit credit first, then draw from the bucket. At any moment, available capacity is: **unexpired deposit credit + current bucket level** Trades, fees, and transfers between subaccounts do not add capacity. > [!NOTE] > > These are the current mainnet settings, and governance can change them. Testnet uses different values. Read `capacityUsd18` and `ratePerSecondUsd18` on the [WithdrawalLimiter](/contracts/withdrawal-limiter) for the live configuration. ## A numbers example Assume USDC is worth exactly \$1, the bucket starts full, there is no deposit credit, and no one else deposits or withdraws. Values show the state after each event. | Time | Event | Deposit credit | Bucket | Total capacity | Result | | - | - | -: | -: | -: | - | | 00:00 | Alice withdraws 150,000 USDC | \$0 | \$50,000 | \$50,000 | Paid in full from the bucket. | | 00:00 | Bob tries to withdraw 80,000 USDC | \$0 | \$50,000 | \$50,000 | The whole transaction reverts. **Nothing is queued** or partially paid. | | 03:00 | Three hours pass | \$0 | \$75,000 | \$75,000 | The bucket refills by \$25,000. | | 03:00 | Carol deposits 10,000 USDC | \$10,000 | \$75,000 | \$85,000 | Carol's credit expires at 03:00 the next day if unused. | | 03:00 | Bob tries again with 80,000 USDC | \$0 | \$5,000 | \$5,000 | Paid in full: \$10,000 from Carol's credit, then \$70,000 from the bucket. | From \$5,000, the bucket is full again about 23.4 hours later. In practice, USD values come from live token prices, and capacity can change between a preview and the transaction. ## If a withdrawal cannot complete The transaction reverts without paying any part of the amount. Check that the funds are available in the main account, the caller has withdrawal permission, the recipient is valid, prices are current, and withdrawals are enabled. If capacity is the problem: * **Wait.** The bucket refills by about \$8,333 per hour. * **Withdraw less.** Choose an amount that fits within current capacity. * **Split large withdrawals.** A withdrawal worth more than \$200,000 can succeed only if unexpired deposit credit covers the difference. Otherwise, split it into smaller withdrawals over time. Other users draw from the same capacity, so it may be used up before your transaction executes. A preview is an estimate at the moment it is read. It does not reserve capacity or guarantee that the withdrawal will succeed. ## What a withdrawal screen should show * The account's **available token balance**. * The **current shared withdrawal capacity** in USD, and an estimated maximum withdrawal in the selected token. * A short explanation that capacity is shared, refills at about \$8,333 per hour up to \$200,000, and that deposit credit expires after 24 hours. * If the amount exceeds capacity, a warning that the whole transaction will fail rather than wait in a queue. Optionally, an estimate of when enough capacity should be available, noting that other withdrawals can use it first. Refresh the estimate immediately before submission, and do not present it as a reservation. ## Approved payouts A withdrawal can also be paid as an approved payout, which does not use shared withdrawal capacity. It requires Kuru's signature. Once Kuru signs, you can withdraw after a **6-hour timelock**. Approved payouts still check funds, pricing, freezes, and protocol pause. They are not a queue or an automatic fallback when capacity runs out. Applications implementing this route should read the [withdrawal reference](/contracts/withdrawal-limiter). # Following Account Activity Source: https://docs.kuru.io/api/account-activity Connect a wallet identity to balances, orders, and executions. Use account data to reconcile what actually happened after a transaction. A Relay broadcast response does not establish that an order is resting or that balances have changed. ## Resolve the account For direct chain reads, resolve the owner with `rootAccountIdOf` and select the target root or child ID. Children have no address. The hosted [Resolve user address](/api/data-source/reference/resolve-user) endpoint provides the address-to-user lookup. An unregistered address returns `userId: null` under that documented schema. Use the account being traded, not automatically the secondary signer or sponsor address. A signer can act for a different funded account. ## Initial state and subscriptions Load [finalized balances](/api/data-source/reference/user-balances) and [open orders](/api/data-source/reference/user-orders). Each response has its own cursor. When both its epoch and sequence are present, install that snapshot and subscribe to the corresponding finalized user stream after that cut. Do not reuse a cursor from a different dataset without the API's documented guarantee. For user orders and balances, subscribing without `seq` can establish a fresh authoritative snapshot. ## Apply updates Replace local state on a full snapshot. Apply deltas in order after validating their predecessor. For orders, distinguish creation, partial or complete execution, cancellation, and RAB reduction. Match the order ID before mutating a reused slot. A submitted order may be skipped, immediately filled, or left resting. Use transaction outcomes together with [user orders](/api/exchange/websocket-reference/user-orders) and [user trades](/api/exchange/websocket-reference/user-trades), rather than requiring every successful action to appear in open orders. ## History and completeness The [order-event endpoint](/api/data-source/reference/order-events) is completion-oriented history; it excludes partial fills. Use user trades for execution history. REST snapshots are bounded. If `truncated` is true, do not present the response as the complete account state or use it alone to authorize a cancel-all workflow. User WebSocket streams provide full snapshots according to their reference semantics. Balances contain available and active-order-reserved funds. Passive positions are accounted for separately. See [Balances and Open Orders](/accounts/balances-and-reservations). # Data Source REST API Source: https://docs.kuru.io/api/data-source Finalized catalogs, trading history, account fee tiers, and account value and PnL snapshots. The REST method playground defaults to mainnet and offers testnet in its server dropdown: ```text theme={null} Mainnet (default): https://api.mainnet.kuru.io Testnet: https://api.testnet.kuru.io ``` It exposes finalized exchange data under `/api/v1`. Catalog resources use a `feedEpoch: null` envelope because they are not WebSocket replay cuts. Market and user datasets return the committed `feedEpoch` and the corresponding `marketSeq` or `globalUserSeq` when a replay cursor is available. > [card] [Markets](/api/data-source/reference/markets) > > Browse spot markets and trailing 24-hour summaries. > [card] [Market details](/api/data-source/reference/market) > > Read one market's tokens and trading configuration. > [card] [Market trades](/api/data-source/reference/market-trades) > > Read finalized fills and obtain the market WebSocket join cursor. > [card] [Tokens](/api/data-source/reference/tokens) > > Browse supported token metadata. > [card] [Token details](/api/data-source/reference/token) > > Read one supported token. > [card] [Candles](/api/data-source/reference/candles) > > Query historical OHLCV candles. > [card] [Resolve user](/api/data-source/reference/resolve-user) > > Resolve a wallet address to its Kuru user ID. > [card] [User open orders](/api/data-source/reference/user-orders) > > Read a finalized open-order snapshot and its user cursor. > [card] [User balances](/api/data-source/reference/user-balances) > > Read all finalized balances or select one token. > [card] [User trades](/api/data-source/reference/user-trades) > > Read finalized maker and taker trades with fees and PnL. > [card] [Order events](/api/data-source/reference/order-events) > > Read finalized order creation, cancellation, and RAB reduction history. > [card] [User fee tier](/api/data-source/reference/user-fee-tier) > > Read the root account's assigned maker and taker fee rates. > [card] [Account value and PnL snapshots](/api/data-source/reference/account-value-snapshots) > > Read hourly USDC account value and cumulative PnL history. Fee tiers and account-value snapshots return `feedEpoch` as a decimal string (or `null` before initialization), without a replay sequence. An epoch of `"0"` is valid for a fresh feed. These endpoints are not WebSocket replay bootstraps. ## REST to WebSocket handoff For market trades, pair `feedEpoch` with `marketSeq` and subscribe to the matching finalized market stream. For user orders, balances, or trades, pair `feedEpoch` with `globalUserSeq` and subscribe to the matching finalized user stream. Install the REST data first, then request replay from that exact cursor. Both cursor fields may be `null` before the current feed epoch has materialized that scope. In that case the response remains valid finalized data, but it is not a WebSocket replay bootstrap. ## Response envelopes Catalog collections return: ```json theme={null} {"feedEpoch":null,"data":[],"pagination":{"nextCursor":null}} ``` Catalog resources and candles return: ```json theme={null} {"feedEpoch":null,"data":{}} ``` Errors include a request ID for support and tracing: ```json theme={null} { "feedEpoch": null, "error": {"code": "BadRequest", "message": "invalid request"}, "requestId": "01J..." } ``` # Get account value and PnL snapshots Source: https://docs.kuru.io/api/data-source/reference/account-value-snapshots api/data-source/openapi.yaml GET /api/v1/users/{userId}/account-value-snapshots Read hourly history and latest indexed account value and PnL in USDC. Returns stored hourly snapshots and a live indexed point for the specified account, without combining its subaccounts. Account value and PnL share this endpoint; there is no separate PnL snapshot endpoint. No request body is accepted. **userId** `string` *required* Unsigned 64-bit Kuru account ID as a decimal string. **timeframe** `string` (default: 7d) One of `1d`, `7d`, or `30d`. History starts one timeframe before the current UTC hour (exclusive). A live point extends the response through the latest indexed balance/trade source time or last stored hourly boundary, whichever is later (inclusive). This does not prove ingestion is caught up to the chain. All monetary values are exact decimal strings in **USDC × 10¹⁸**: `"1000000000000000000"` represents 1 USDC. PnL can be negative. Timestamps are Unix **seconds**, not milliseconds. **feedEpoch** `string | null` *required* Materialization feed epoch, or `null` before initialization. `"0"` is valid. This is not a snapshot timestamp or a WebSocket replay sequence. **data.totalAccountValueX18** `string | null` *required* Latest indexed account value, including free and reserved token balances, valued at latest indexed prices. Does not include passive LP positions. **data.performance** `array` *required* Tuples `[accountValueX18, pnlX18, timestamp]`, oldest first. At most 24, 168, or 720 hourly points plus one live point. The final point need not be hour-aligned; duplicate timestamps are not returned. **data.relativePnlX18** `string | null` *required* Latest cumulative total PnL minus start-hour cumulative total PnL. An amount, not a percentage. Null when a required boundary value is unavailable. **data.relativeVolumeX18** `string | null` *required* The user's maker/taker trade notional over the selected window, converted to USDC at each trade's historical quote-token price. Excludes transfers. ### Performance tuple | Position | Field | Type | Meaning | | - | - | - | - | | 0 | `accountValueX18` | string or null | Total token-balance value in USDC at the tuple timestamp. | | 1 | `pnlX18` | string or null | Cumulative realized plus unrealized PnL across markets, not just that hour's PnL. | | 2 | `timestamp` | integer | Unix seconds. The live point uses indexed source time or the last stored hourly boundary, whichever is later—not request time. | Historical hours are stored snapshots; missing hours are not fabricated. Unknown valuations or unavailable snapshot values are `null`, not zero. A nonzero holding without a supported valuation market makes the account total unknown. For a configured valuation market with no trade yet, the valuation uses zero. The single live point reads current free and reserved balances directly from `user_token_balances` and current inventory, cost basis and realized PnL from `user_market_positions`, valued using latest indexed trade prices. It does not reconstruct live state from append-only events or hourly snapshots. History, current state, prices and feed epoch are read in one consistent database snapshot. With no snapshots but indexed account state, the live point is still returned. Accounts without history or state return `performance: []` and null account/PnL summaries. Volume includes trades through the indexed source cutoff and is `"0"` when none exist. Historical values are never repriced using current prices. Illustrative response: ```json 200 theme={null} { "feedEpoch": "0", "data": { "totalAccountValueX18": "2500000000000000000000", "performance": [ ["2500000000000000000000", "-5000000000000000000", 1791763200] ], "relativePnlX18": "-5000000000000000000", "relativeVolumeX18": "100000000000000000000" } } ``` Unknown users return HTTP 200 with empty history, not 404. Invalid IDs, unsupported timeframes, and unknown query parameters return 400. Unsupported methods, including POST, return 405. # Get candles Source: https://docs.kuru.io/api/data-source/reference/candles api/data-source/openapi.yaml GET /api/v1/markets/{marketAddress}/candles Query finalized OHLCV candles for one market. **marketAddress** `string` *required* Lowercase 20-byte market contract address. **interval** `string` *required* One of `1s`, `1m`, `5m`, `1h`, `6h`, or `1d`. Each interval maps directly to a materialized continuous aggregate. **from** `integer` *required* Inclusive lower bound on the candle's start timestamp, in Unix seconds. **to** `integer` Inclusive upper bound on the candle's start timestamp, in Unix seconds. When omitted, the upper bound is the current time. **countback** `integer` (default: 5000) Return up to the latest N candles within the requested range. Accepts `1` to `5000`. Results are returned oldest-first. The query does not search before `from` to satisfy the count, so fewer than N candles may be returned. **limit** `integer` Backward-compatible alias for `countback`, with the same range and behavior. Providing both `limit` and `countback` returns `400 Bad Request`. When neither `countback` nor `limit` is supplied, the latest 5000 candles at most within the requested range are returned, ordered oldest-first. Responses never exceed 5000 candles. Empty, zero, negative, non-integer, or greater-than-5000 count values are rejected. `from` must be less than or equal to an explicit `to`. For example, if a range contains ten one-minute candles from `10:00` through `10:09`, `countback=3` returns `10:07`, `10:08`, and `10:09`. Omitting both count parameters returns all ten candles. Range bounds apply to bucket start times: for hourly candles, a `from` at `10:15` excludes the `10:00` candle, while a `to` at `11:00` includes the `11:00` candle. The response is columnar. Values at the same array index belong to one candle: `t` is Unix time in seconds, `o/h/l/c` are price integer strings in market pp, and `v` remains x18 quote volume. Missing intervals carry forward the preceding aggregate close: open, high, low and close all equal that price, and volume is zero. The preceding price may be before `from`; returned timestamps never are. If no earlier price is known, leading empty buckets are omitted. A market with no candles returns empty arrays. Synthetic candles count toward `countback` and `limit`; future buckets are never generated, even if `to` is in the future. Boundaries are UTC-aligned. Actual candles retain their original OHLCV. This is query-time filling and does not change the continuous aggregates or repair missed refreshes. `feedEpoch` and `marketSeq` report the materialization epoch and the market's sequence progress, read alongside the candles and cached with the response. Either may be `null` when the corresponding progress is unavailable. Candle aggregates can lag this progress while refreshing; these fields do not guarantee that all trades through `marketSeq` are included in the candle arrays. Historical range filters do not change this progress metadata. ```json 200 theme={null} { "feedEpoch": 283, "marketSeq": "5798", "data": { "t": [ 1788274800, 1788339600, 1788350400 ], "o": [ "255179", "244994", "237485" ], "h": [ "257507", "257282", "247071" ], "l": [ "242806", "242282", "237485" ], "c": [ "252201", "252272", "247071" ], "v": [ "1330230000000000000000", "1252520000000000000000", "38550000000000000000" ] } } ``` # Get market details Source: https://docs.kuru.io/api/data-source/reference/market api/data-source/openapi.yaml GET /api/v1/markets/{marketAddress} Read one market's token pair, precision settings, and summary. > [!NOTE] > > The response below is a WETHUSDC mainnet snapshot observed on 17 October 2026. Market statistics and configuration can change; query the selected server for current state. **marketAddress** `string` *required* Lowercase 20-byte market contract address. **feedEpoch** `null` *required* Market metadata is not an Exchange Gateway replay cut. **data** `object` *required* The requested market and its current trailing statistics. **marketAddress** `string` *required* Lowercase 20-byte market contract address. **symbol** `string` *required* Display symbol for the market pair. **baseToken** `object` *required* Base-token metadata. **tokenAddress** `string` *required* **name** `string` *required* **symbol** `string` *required* **decimals** `integer` *required* **logoUrl** `string | null` *required* **description** `string | null` *required* **websiteUrl** `string | null` *required* **verified** `boolean` *required* **contractRenounced** `boolean` *required* **isErc20** `boolean` *required* **isMintable** `boolean` *required* **isStrict** `boolean` *required* **firstPoolAddress** `string | null` *required* **quoteToken** `object` *required* Quote-token metadata. Its fields have the same meanings as `baseToken`. **tokenAddress** `string` *required* **name** `string` *required* **symbol** `string` *required* **decimals** `integer` *required* **logoUrl** `string | null` *required* **description** `string | null` *required* **websiteUrl** `string | null` *required* **verified** `boolean` *required* **contractRenounced** `boolean` *required* **isErc20** `boolean` *required* **isMintable** `boolean` *required* **isStrict** `boolean` *required* **firstPoolAddress** `string | null` *required* **status** `string` *required* Current market status: `active` or `paused`. **pricePrecision** `string` *required* Integer precision used to interpret native order price ticks. **sizePrecision** `string` *required* Integer precision used to interpret native base sizes. **tickSize** `string` *required* Minimum price-tick increment in native price-precision units. **minQuoteNotionalX18** `string` *required* Minimum quote notional scaled by `1e18`. **takerFeePps** `integer` *required* Configured market taker fee rate in PPS, where `10,000,000` represents 100%. This is a rate, not a charged fee amount. Zero means no configured fee. **makerFeePps** `integer` *required* Configured market maker fee rate in PPS, where `10,000,000` represents 100%. This is a rate, not a charged fee amount. Zero means no configured fee. **createdAt** `integer` *required* Market creation time in Unix seconds. **lastPrice** `string | null` *required* Price from the 24-hour summary when available; otherwise the market's latest raw trade price, with no timestamp cutoff. Returned in market price precision (pp), or `null` when neither source has a price. The 24-hour statistics retain their existing window. **priceChange24hPct** `string | null` *required* Rolling 24-hour decimal price-change ratio. For example, `"0.01"` means one percent. **volume24h** `string` *required* Rolling 24-hour quote volume scaled by `1e18`. **tradeCount24h** `integer` *required* Number of fills included in the rolling 24-hour window. The example below records the mainnet market details returned by the Data Source API; it is not a guarantee of current fees or liquidity. ```json 200 theme={null} { "feedEpoch": null, "data": { "marketAddress": "0x8121ee960066e4344a213f9ac7502395502aee7a", "symbol": "WETHUSDC", "baseToken": { "tokenAddress": "0xee8c0e9f1bffb4eb878d8f15f368a02a35481242", "name": "", "symbol": "WETH", "decimals": 18, "logoUrl": "https://d1zzuytetv7tb9.cloudfront.net/WETH.png", "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": true, "isMintable": true, "isStrict": false, "firstPoolAddress": "0x8121ee960066e4344a213f9ac7502395502aee7a" }, "quoteToken": { "tokenAddress": "0x754704bc059f8c67012fed69bc8a327a5aafb603", "name": "", "symbol": "USDC", "decimals": 6, "logoUrl": "https://d1zzuytetv7tb9.cloudfront.net/USDC.png", "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": true, "isMintable": true, "isStrict": false, "firstPoolAddress": null }, "status": "active", "pricePrecision": "10000", "sizePrecision": "10000000000", "tickSize": "100", "minQuoteNotionalX18": "10000000000000000000", "takerFeePps": 100000, "makerFeePps": 100000, "createdAt": 1792022400, "lastPrice": null, "priceChange24hPct": null, "volume24h": "0", "tradeCount24h": 0 } } ``` # Get finalized market order Source: https://docs.kuru.io/api/data-source/reference/market-orders api/data-source/openapi.yaml GET /api/v1/markets/{marketAddress}/orders Look up one order by market address and order ID. **marketAddress** `string` *required* Market contract address. Order IDs are unique within a market, not globally. **oid** `string` *required* Unsigned decimal uint64 order ID. Leading zeros are normalized. Missing, empty, malformed or repeated values return 400. Returns one finalized order in `data`, whether open, filled or cancelled. An unknown market/order pair returns 404. This is not an open-order snapshot or a WebSocket replay baseline; `feedEpoch` is null. | Field in `data` | Meaning | | - | - | | `orderId` | Decimal order ID string | | `marketAddress` | Market contract address | | `makerId` | Decimal owner user ID string | | `symbol` | Market symbol | | `isBuy` | Whether the order is a bid | | `isCancelled` | Whether it was cancelled | | `clientOrderId` | Creation correlation ID, or null; not unique | | `price` | Integer string in market price precision | | `remainingSize` | Integer string in market size precision | | `minSizeAfterBlock` | Reduce-after-block height string, or null | A cancelled order can retain positive `remainingSize`. A fully filled order can have `isCancelled: false`. # List market trades Source: https://docs.kuru.io/api/data-source/reference/market-trades api/data-source/openapi.yaml GET /api/v1/markets/{marketAddress}/trades Read finalized fills and obtain the market WebSocket cursor. > [!NOTE] > > The response below was observed for WETHUSDC on mainnet on 17 October 2026. Trades and replay cuts change as new blocks finalize; query the selected server for current state. Each item represents one fill from the taker perspective. The stable fill identity is `(marketAddress, tradeId, recordIdx)`. **marketAddress** `string` *required* Lowercase 20-byte market contract address. **limit** `integer` (default: 100) Page size from `1` through `1000`. **cursor** `string` Opaque exclusive continuation cursor from `pagination.nextCursor`. **from** `integer` Inclusive Unix time in seconds. **to** `integer` Inclusive Unix time in seconds. When both bounds are present, `to` must be greater than `from`. **feedEpoch** `integer | null` *required* Feed epoch containing `marketSeq`. **marketSeq** `string | null` *required* Finalized market sequence covered by the materialized response. **data** `array` *required* Trade fills ordered newest first by block timestamp, block number, transaction index, log index, and record index. **pagination.nextCursor** `string | null` *required* Opaque continuation cursor, or `null` when no continuation is available. `price` is an integer in market price precision (pp). `filledSize` and `remainingSize` use the market's native size precision. `isBuy=true` means the taker bought the base token. `blockTimestamp` is Unix time in seconds. When both cursor fields are non-null, install this page and subscribe to `trades@f` with the same `feedEpoch` and `marketSeq`. ```json 200 theme={null} { "feedEpoch": 0, "marketSeq": null, "data": [], "pagination": { "nextCursor": null } } ``` # List markets Source: https://docs.kuru.io/api/data-source/reference/markets api/data-source/openapi.yaml GET /api/v1/markets Browse spot markets and trailing 24-hour statistics. > [!NOTE] > > The example below shows the first WETHUSDC result from a mainnet request with `status=active&limit=1` on 17 October 2026. The continuation cursor is represented schematically because cursors expire; always use the current response's `pagination.nextCursor`. **status** `string` (default: active) `active`, `paused`, or `all`. **limit** `integer` (default: 100) Page size from `1` through `500`. **cursor** `string` Opaque exclusive continuation cursor from `pagination.nextCursor`. **feedEpoch** `null` *required* Catalog responses are not Exchange Gateway replay cuts. **data** `array` *required* Markets ordered by creation time and then market address. **marketAddress** `string` *required* Lowercase 20-byte market contract address. **symbol** `string` *required* Display symbol for the market pair. **baseToken** `object` *required* Base-token metadata. **tokenAddress** `string` *required* **name** `string` *required* **symbol** `string` *required* **decimals** `integer` *required* **logoUrl** `string | null` *required* **description** `string | null` *required* **websiteUrl** `string | null` *required* **verified** `boolean` *required* **contractRenounced** `boolean` *required* **isErc20** `boolean` *required* **isMintable** `boolean` *required* **isStrict** `boolean` *required* **firstPoolAddress** `string | null` *required* **quoteToken** `object` *required* Quote-token metadata. Its fields have the same meanings as `baseToken`. **tokenAddress** `string` *required* **name** `string` *required* **symbol** `string` *required* **decimals** `integer` *required* **logoUrl** `string | null` *required* **description** `string | null` *required* **websiteUrl** `string | null` *required* **verified** `boolean` *required* **contractRenounced** `boolean` *required* **isErc20** `boolean` *required* **isMintable** `boolean` *required* **isStrict** `boolean` *required* **firstPoolAddress** `string | null` *required* **status** `string` *required* Current market status: `active` or `paused`. **pricePrecision** `string` *required* Integer precision used to interpret native order price ticks. **sizePrecision** `string` *required* Integer precision used to interpret native base sizes. **tickSize** `string` *required* Minimum price-tick increment in native price-precision units. **minQuoteNotionalX18** `string` *required* Minimum quote notional scaled by `1e18`. **takerFeePps** `integer` *required* Configured market taker fee rate in PPS, where `10,000,000` represents 100%. This is a rate, not a charged fee amount. Zero means no configured fee. **makerFeePps** `integer` *required* Configured market maker fee rate in PPS, where `10,000,000` represents 100%. This is a rate, not a charged fee amount. Zero means no configured fee. **createdAt** `integer` *required* Market creation time in Unix seconds. **lastPrice** `string | null` *required* Price from the 24-hour summary when available; otherwise the market's latest raw trade price, with no timestamp cutoff. Returned in market price precision (pp), or `null` when neither source has a price. The 24-hour statistics retain their existing window. **priceChange24hPct** `string | null` *required* Rolling 24-hour decimal price-change ratio. For example, `"0.01"` means one percent. **volume24h** `string` *required* Rolling 24-hour quote volume scaled by `1e18`. **tradeCount24h** `integer` *required* Number of fills included in the rolling 24-hour window. **pagination** `object` *required* Pagination metadata for this page. **nextCursor** `string | null` *required* Opaque continuation cursor, or `null` when no continuation is available. The catalog is authoritative for current markets, configuration, and activity; this is a dated response example. ```json 200 theme={null} { "feedEpoch": null, "data": [ { "marketAddress": "0x8121ee960066e4344a213f9ac7502395502aee7a", "symbol": "WETHUSDC", "baseToken": { "tokenAddress": "0xee8c0e9f1bffb4eb878d8f15f368a02a35481242", "name": "", "symbol": "WETH", "decimals": 18, "logoUrl": "https://d1zzuytetv7tb9.cloudfront.net/WETH.png", "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": true, "isMintable": true, "isStrict": false, "firstPoolAddress": "0x8121ee960066e4344a213f9ac7502395502aee7a" }, "quoteToken": { "tokenAddress": "0x754704bc059f8c67012fed69bc8a327a5aafb603", "name": "", "symbol": "USDC", "decimals": 6, "logoUrl": "https://d1zzuytetv7tb9.cloudfront.net/USDC.png", "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": true, "isMintable": true, "isStrict": false, "firstPoolAddress": null }, "status": "active", "pricePrecision": "10000", "sizePrecision": "10000000000", "tickSize": "100", "minQuoteNotionalX18": "10000000000000000000", "takerFeePps": 100000, "makerFeePps": 100000, "createdAt": 1792022400, "lastPrice": null, "priceChange24hPct": null, "volume24h": "0", "tradeCount24h": 0 } ], "pagination": { "nextCursor": "" } } ``` # List user order events Source: https://docs.kuru.io/api/data-source/reference/order-events api/data-source/openapi.yaml GET /api/v1/users/{userId}/order-events Read finalized order creation, complete fills, cancellation, and RAB reduction history. > [!NOTE] > > Response JSON below is an illustrative testnet snapshot, not a live mainnet result. Use the selected server and its network-specific addresses for actual requests. Events are scoped to the resting order owner and ordered newest first by their canonical source position. `filled` means an active maker order was completely executed: the final fill left `updatedSize` equal to `"0"`. Partial executions and passive-liquidity fills are not included. A fill belongs to the resting maker's history, not the taker's, unless they are the same user. This endpoint is completion-oriented history. The Exchange Gateway `userOrders` stream's `trade` event is different: it includes both partial and complete fills. A frontend can recognize a completion from that stream when the trade's `updatedSize` is zero. For a Relay WebSocket submission whose `BROADCAST` reply was lost, a unique signed `payload.header.clientOrderId` can help correlate the action with these events. It is a 32-byte **batch-level** ID, not an enforced-unique idempotency key, so one submission can produce multiple matching rows. There is no documented server-side `clientOrderId` filter: page through the results with `pagination.nextCursor` and match the returned ID together with the account and market. Matching rows include `transactionHash` and event details. No match is not proof that the action failed: indexing may lag, the transaction may still be pending, or the action may produce no event in this resting-maker history (including a taker-only IOC). See [Relay recovery](/api/relay/errors#connection-closure-and-recovery). **userId** `string` *required* Unsigned decimal Kuru user ID. **limit** `integer` (default: 100) Page size from `1` through `500`. **cursor** `string` Opaque exclusive continuation cursor from `pagination.nextCursor`. **marketAddress** `string` Optional lowercase 20-byte market filter. **from** `integer` Inclusive Unix time in seconds. **to** `integer` Inclusive Unix time in seconds. When both bounds are present, `to` must be greater than `from`. **feedEpoch** `integer | null` *required* Feed epoch containing `globalUserSeq`. **globalUserSeq** `string | null` *required* Finalized user sequence covered by the materialized response. **data** `array` *required* Finalized order events ordered newest first. **data\[].eventKind** `string` *required* `created`, `filled`, `cancelled`, or `rab-reduced`. **data\[].orderId** `string` *required* **data\[].recordIdx** `integer` *required* **data\[].marketAddress** `string` *required* **data\[].symbol** `string` *required* **data\[].makerId** `string` *required* Resting-order owner. This matches the path `userId`. **data\[].actionUserId** `string` *required* Account that caused the mutation; the taker for `filled`. **data\[].executorAddress** `string` *required* **data\[].clientOrderId** `string | null` *required* **data\[].isBuy** `boolean` *required* Side of the resting order. **data\[].price** `string` *required* Order price in market price precision (pp). **data\[].size** `string | null` *required* Initial size for `created`, final execution quantity for `filled`, removed size for `cancelled`, and `null` for `rab-reduced`. Values use the market's native size precision. For `filled`, this is not the sum of earlier partial fills. **data\[].updatedSize** `string | null` *required* Remaining size for `created` and `rab-reduced`; always `"0"` for `filled`; `null` for `cancelled`. **data\[].minSizeAfterBlock** `string | null` *required* Optional reduce-after block captured when the order was created. **data\[].makerFeePps** `integer` *required* Maker fee rate snapshotted for `created`, or the actual maker rate for the terminal execution in `filled`; other event kinds carry zero. The denominator is `10,000,000`. **data\[].blockTimestamp** `integer` *required* Block proposal time in Unix seconds. **data\[].blockNumber** `string` *required* **data\[].transactionHash** `string | null` *required* **data\[].transactionIndex** `integer | null` *required* **data\[].logIndex** `integer | null` *required* **pagination.nextCursor** `string | null` *required* Opaque continuation cursor, or `null` when no continuation is available. When both cursor fields are non-null, the response provides the finalized user sequence cut associated with the materialized history. Pagination cursors are exclusive and retain the original response's feed epoch and user sequence. Illustrative completed-order entry (the enclosing response is unchanged): ```json theme={null} { "eventKind": "filled", "orderId": "99", "recordIdx": 1, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "4", "actionUserId": "3", "executorAddress": "0x1111111111111111111111111111111111111111", "clientOrderId": null, "isBuy": false, "price": "25000000", "size": "60000000", "updatedSize": "0", "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353771, "blockNumber": "59066947", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 2, "logIndex": 3 } ``` ```json 200 theme={null} { "feedEpoch": 18, "globalUserSeq": "84", "data": [ { "eventKind": "cancelled", "orderId": "794", "recordIdx": 2, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d18249d85e0388000000000000000000000000000000000000000000000016", "isBuy": false, "price": "25044900", "size": "1000000000", "updatedSize": null, "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353781, "blockNumber": "59066980", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 3, "logIndex": 48 }, { "eventKind": "cancelled", "orderId": "793", "recordIdx": 1, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d18249d85e0388000000000000000000000000000000000000000000000016", "isBuy": false, "price": "25019900", "size": "1000000000", "updatedSize": null, "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353781, "blockNumber": "59066980", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 3, "logIndex": 48 }, { "eventKind": "cancelled", "orderId": "792", "recordIdx": 0, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d18249d85e0388000000000000000000000000000000000000000000000016", "isBuy": false, "price": "24994900", "size": "1000000000", "updatedSize": null, "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353781, "blockNumber": "59066980", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 3, "logIndex": 48 }, { "eventKind": "created", "orderId": "794", "recordIdx": 5, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d18249a30efae8000000000000000000000000000000000000000000000013", "isBuy": false, "price": "25044900", "size": "1000000000", "updatedSize": "1000000000", "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353780, "blockNumber": "59066977", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 7, "logIndex": 62 }, { "eventKind": "cancelled", "orderId": "791", "recordIdx": 4, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d18249a30efae8000000000000000000000000000000000000000000000013", "isBuy": false, "price": "24756500", "size": "1000000000", "updatedSize": null, "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353780, "blockNumber": "59066977", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 7, "logIndex": 62 }, { "eventKind": "created", "orderId": "793", "recordIdx": 3, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d18249a30efae8000000000000000000000000000000000000000000000013", "isBuy": false, "price": "25019900", "size": "1000000000", "updatedSize": "1000000000", "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353780, "blockNumber": "59066977", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 7, "logIndex": 62 }, { "eventKind": "cancelled", "orderId": "790", "recordIdx": 2, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d18249a30efae8000000000000000000000000000000000000000000000013", "isBuy": false, "price": "24731800", "size": "1000000000", "updatedSize": null, "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353780, "blockNumber": "59066977", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 7, "logIndex": 62 }, { "eventKind": "created", "orderId": "792", "recordIdx": 1, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d18249a30efae8000000000000000000000000000000000000000000000013", "isBuy": false, "price": "24994900", "size": "1000000000", "updatedSize": "1000000000", "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353780, "blockNumber": "59066977", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 7, "logIndex": 62 }, { "eventKind": "cancelled", "orderId": "789", "recordIdx": 0, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d18249a30efae8000000000000000000000000000000000000000000000013", "isBuy": false, "price": "24707100", "size": "940000000", "updatedSize": null, "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353780, "blockNumber": "59066977", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 7, "logIndex": 62 }, { "eventKind": "created", "orderId": "791", "recordIdx": 5, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d182474ef2369800000000000000000000000000000000000000000000000a", "isBuy": false, "price": "24756500", "size": "1000000000", "updatedSize": "1000000000", "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353770, "blockNumber": "59066944", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 4, "logIndex": 9 }, { "eventKind": "cancelled", "orderId": "788", "recordIdx": 4, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d182474ef2369800000000000000000000000000000000000000000000000a", "isBuy": false, "price": "24831700", "size": "1000000000", "updatedSize": null, "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353770, "blockNumber": "59066944", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 4, "logIndex": 9 }, { "eventKind": "created", "orderId": "790", "recordIdx": 3, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d182474ef2369800000000000000000000000000000000000000000000000a", "isBuy": false, "price": "24731800", "size": "1000000000", "updatedSize": "1000000000", "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353770, "blockNumber": "59066944", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 4, "logIndex": 9 }, { "eventKind": "cancelled", "orderId": "787", "recordIdx": 2, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d182474ef2369800000000000000000000000000000000000000000000000a", "isBuy": false, "price": "24807000", "size": "1000000000", "updatedSize": null, "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353770, "blockNumber": "59066944", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 4, "logIndex": 9 }, { "eventKind": "created", "orderId": "789", "recordIdx": 1, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d182474ef2369800000000000000000000000000000000000000000000000a", "isBuy": false, "price": "24707100", "size": "1000000000", "updatedSize": "1000000000", "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353770, "blockNumber": "59066944", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 4, "logIndex": 9 }, { "eventKind": "cancelled", "orderId": "786", "recordIdx": 0, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d182474ef2369800000000000000000000000000000000000000000000000a", "isBuy": false, "price": "24782200", "size": "1000000000", "updatedSize": null, "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353770, "blockNumber": "59066944", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 4, "logIndex": 9 }, { "eventKind": "created", "orderId": "788", "recordIdx": 2, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d18244fad50cb8000000000000000000000000000000000000000000000001", "isBuy": false, "price": "24831700", "size": "1000000000", "updatedSize": "1000000000", "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353760, "blockNumber": "59066910", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 2, "logIndex": 35 }, { "eventKind": "created", "orderId": "787", "recordIdx": 1, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d18244fad50cb8000000000000000000000000000000000000000000000001", "isBuy": false, "price": "24807000", "size": "1000000000", "updatedSize": "1000000000", "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353760, "blockNumber": "59066910", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 2, "logIndex": 35 }, { "eventKind": "created", "orderId": "786", "recordIdx": 0, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d18244fad50cb8000000000000000000000000000000000000000000000001", "isBuy": false, "price": "24782200", "size": "1000000000", "updatedSize": "1000000000", "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788353760, "blockNumber": "59066910", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 2, "logIndex": 35 }, { "eventKind": "cancelled", "orderId": "688", "recordIdx": 5, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d177da35ac2e9000000000000000000000000000000000000000000000011b", "isBuy": false, "price": "24528300", "size": "1000000000", "updatedSize": null, "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788342306, "blockNumber": "59029021", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 1, "logIndex": 3 }, { "eventKind": "cancelled", "orderId": "687", "recordIdx": 4, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "makerId": "2", "actionUserId": "2", "executorAddress": "0xc41af288173214a8c19d3aa01bed10446fb6af6f", "clientOrderId": "0x18d177da35ac2e9000000000000000000000000000000000000000000000011b", "isBuy": false, "price": "24503900", "size": "1000000000", "updatedSize": null, "minSizeAfterBlock": null, "makerFeePps": 0, "blockTimestamp": 1788342306, "blockNumber": "59029021", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "transactionIndex": 1, "logIndex": 3 } ], "pagination": { "nextCursor": "eyJ2IjoxLCJyIjoidXNlci1vcmRlci1ldmVudHMiLCJmIjoiYzQxNzFlNjQzYThjZjQyNjI4YTlkM2FiY2NlMTdlZmE0NjdiYTJhNGQ5NzI2ODljOWQ5ZWE2NzU0YWY3OWFiMiIsInMiOiJhZjIwMjU0NjJlYTNiYzczMjg2MjI3ZDAyMzAyNWRhMTM3N2JmMjBjMzI2NzM5ZGM1Y2UwYjU0ODQ3OTc3YzdmIiwibyI6MCwiZSI6MTc4ODQzNDY1MX0.Sv585GhMOt_3y1JY0tY-I3PSqmM4iws4xSf27oco9zU" } } ``` # Resolve user address Source: https://docs.kuru.io/api/data-source/reference/resolve-user api/data-source/openapi.yaml GET /api/v1/users/by-address/{userAddress} Resolve a wallet address to its numeric Kuru user ID. **userAddress** `string` *required* Lowercase 20-byte wallet address. A valid address that has not been registered returns `userId: null`. A malformed address returns `400 BadRequest`. ```json 200 theme={null} { "feedEpoch": null, "data": { "userAddress": "0xfa0fff2fefdcb57c1a14d9e357feca7d999f2d1e", "userId": "2" } } ``` # Exchange Stats Source: https://docs.kuru.io/api/data-source/reference/stats Read public exchange analytics and the opt-in Stats page response. `GET /api/v1/stats` is public and read-only. No wallet or API key is required. The page response below requires the new API and Jobhub page-publication release; this reference does not establish deployment availability. ```http theme={null} GET /api/v1/stats?range=24h GET /api/v1/stats?range=30d&market=0xc9de998e272d59a19cea3783c8dd44f87a86405d ``` ## Parameters | Parameter | Meaning | | - | - | | `range` | Required for the page view: `24h`, `7d`, `30d`, `90d`, `all`. | | `market` | Optional exact Kuru market address, normalized to lowercase. Omit for all markets. | Without `range`, the existing `timeframe` / `marketAddress` analytics view and its response contract are unchanged. Do not mix the two parameter sets. Invalid, empty, duplicate or unknown parameters return 400; unknown market addresses return 404\. Errors use the existing error envelope and request ID. ## Page response The page view returns an object with `data` containing: * `range`, `bucket`, `market`, `updatedAt`, and every published market in `markets`. * `volume`, `marketVolume`, `accounts`, `capital`, `revenue`, and `throughput`. * `spreads`, including historical costs, the latest depth snapshot, and explicit `spreadAvailability` / `depthAvailability` maps. * `metadata`, including chain identity, actual range coverage, the prior range, and independent section freshness. Market entries use `id` (the address), `base`, `quote`, `logoUrl` and `listedAt`. They are ordered by all-time volume, ties by address. All markets remain available in selectors; any visual Other grouping belongs to the client. `listedAt` is null until an authoritative listing timestamp is materialized. Catalog creation time must not be presented as the listing date. Use `metadata.range.historyFrom` only as a data-since date. Dollar-valued fields are plain-dollar JSON numbers; counts and bps are numbers. The backend serializes from exact arithmetic. Unknown values are nullable; never convert them to zero. Existing analytics callers retain exact x18 string fields. ## Buckets and coverage `24h` uses hourly buckets, `7d` and `30d` daily buckets, `90d` Monday-UTC weekly buckets, and `all` calendar-month buckets. All chart points use the same ordered bucket-start grid. Trader counts describe trailing unique root accounts ending at each bucket's observed end; subaccounts are grouped by root. Existing rolling windows and completed-hour data cutoffs remain unchanged. No live current-hour bucket is added. Rolling ranges can intersect partial first and last buckets, so do not enforce the seeded mock's fixed point counts. Unavailable history is not padded with zeros. `updatedAt` is the recorded activity publication time. The data cutoff and actual coverage are in `metadata.range`; independent quote/depth clocks remain available. Previous periods are null until fully observed. All-time has no prior period; prior amounts remain null. Do not interpret a missing baseline as zero or New. TVL previous is the qualified custody value at range start. Annualize fees over covered seconds rather than the start of a partial month. ## Metric meanings Volume counts each canonical fill once. Fees are actual allocated protocol trading fees, excluding builder fees and incentive netting. Throughput counts observed fills/sec; a taker matching several makers produces several fills. The whole `marketVolume` object is exchange-wide even when `market` is selected; `metadata.marketVolumeScope` states this explicitly. Other is a source-backed remainder when all inputs are known and null when coverage is missing. Capital is exchange-wide reconciled physical custody valued in USDC, while flows are external USDC deposits and positive withdrawals. DAU/WAU/MAU count distinct root accounts; missing trailing history leaves the corresponding count null. ## Venue comparisons Venue IDs are `kuru`, `binance`, `bybit`, `jupiter`. Jupiter is a routed-swap reference on Solana. It does not provide equivalent resting-book depth here. Spread sizes are 1,000, 5,000 and 10,000 USDC. The spread table uses historical round-trip cost averages, not the latest midpoint-spread sample. Existing synchronized complete-case matching and fee/identity qualifications are retained. Missing qualified cohorts remain unavailable. When spread publication lags activity, the latest measured average remains visible with its own period in `spreads.range` and independent freshness. Use per-venue market counts, not catalog size. The common `marketCount` is null when comparison coverage differs. Depth bands are 10, 50 and 100 bps from each book's midpoint. Curves use a shared 5-bps grid through 100 bps. Truncated, stale or unsupported values remain null. Stale, unsupported and entirely unknown curves are empty. On a partial curve, an unknown side also stays null at the origin. Exclude unavailable values from rankings and leave chart gaps. Inspect availability reasons rather than assuming missing liquidity is zero. Depth is independent of the selected range. The client may poll every 60 seconds. Publications retain their existing job cadence and completed-hour resolution; use per-section freshness to qualify them. Page metrics use one database snapshot; mapped page responses are cached directly. Cache hits still refresh freshness and withdraw expired depth amounts. # Get token details Source: https://docs.kuru.io/api/data-source/reference/token api/data-source/openapi.yaml GET /api/v1/tokens/{tokenAddress} Read metadata for one supported token. > [!NOTE] > > Response JSON below is an illustrative testnet snapshot, not a live mainnet result. Use the selected server and its network-specific addresses for actual requests. **tokenAddress** `string` *required* Lowercase 20-byte token contract address. **feedEpoch** `null` *required* Token metadata is not an Exchange Gateway replay cut. **data** `object` *required* The complete token metadata object documented by [List tokens](/api/data-source/reference/tokens). ```json 200 theme={null} { "feedEpoch": null, "data": { "tokenAddress": "0xb711d972876ae19481ffd1ab2047b8e5e31bee5f", "name": "Kuru Test WETH", "symbol": "WETH", "decimals": 18, "logoUrl": null, "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": true, "isMintable": true, "isStrict": false, "firstPoolAddress": null } } ``` # List tokens Source: https://docs.kuru.io/api/data-source/reference/tokens api/data-source/openapi.yaml GET /api/v1/tokens Browse supported token metadata. > [!NOTE] > > Response JSON below is an illustrative testnet snapshot, not a live mainnet result. Use the selected server and its network-specific addresses for actual requests. **limit** `integer` (default: 100) Page size from `1` through `500`. **cursor** `string` Opaque exclusive continuation cursor from `pagination.nextCursor`. **feedEpoch** `null` *required* Token metadata is not an Exchange Gateway replay cut. **data** `array` *required* Token metadata ordered by creation time and then token address. **pagination.nextCursor** `string | null` *required* Continuation cursor, or `null`. Each token includes `tokenAddress`, `name`, `symbol`, `decimals`, `logoUrl`, `description`, `websiteUrl`, `verified`, `contractRenounced`, `isErc20`, `isMintable`, `isStrict`, and `firstPoolAddress`. ```json 200 theme={null} { "feedEpoch": null, "data": [ { "tokenAddress": "0xb01dc575a7ef75e58a05d2bde73ab79f8e7dd0be", "name": "Kuru Test USDC", "symbol": "USDC", "decimals": 6, "logoUrl": null, "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": true, "isMintable": true, "isStrict": false, "firstPoolAddress": null }, { "tokenAddress": "0x0000000000000000000000000000000000000000", "name": "Monad", "symbol": "MON", "decimals": 18, "logoUrl": null, "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": false, "isMintable": false, "isStrict": false, "firstPoolAddress": null }, { "tokenAddress": "0xb711d972876ae19481ffd1ab2047b8e5e31bee5f", "name": "Kuru Test WETH", "symbol": "WETH", "decimals": 18, "logoUrl": null, "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": true, "isMintable": true, "isStrict": false, "firstPoolAddress": null }, { "tokenAddress": "0x7bc3a5fceb95be797d57ee762b881596b3cfa992", "name": "Kuru Test cbBTC", "symbol": "cbBTC", "decimals": 8, "logoUrl": null, "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": true, "isMintable": true, "isStrict": false, "firstPoolAddress": null }, { "tokenAddress": "0x4baf98bf7a70725e73b20ea61b00271878115a4c", "name": "Kuru Test USDT", "symbol": "USDT", "decimals": 6, "logoUrl": null, "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": true, "isMintable": true, "isStrict": false, "firstPoolAddress": null }, { "tokenAddress": "0xc48194f3d9c9f6b461eb3a6acd3bfe09882dc662", "name": "Kuru Test XAUT", "symbol": "XAUT", "decimals": 6, "logoUrl": null, "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": true, "isMintable": true, "isStrict": false, "firstPoolAddress": null }, { "tokenAddress": "0x1ca0772b36e70ff54525afee1daee846cd914d02", "name": "Kuru Test NVDAx", "symbol": "NVDAx", "decimals": 18, "logoUrl": null, "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": true, "isMintable": true, "isStrict": false, "firstPoolAddress": null }, { "tokenAddress": "0x8bf70ce58a038f741b4e187adea126c8cab867c2", "name": "Kuru Test SPYx", "symbol": "SPYx", "decimals": 18, "logoUrl": null, "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": true, "isMintable": true, "isStrict": false, "firstPoolAddress": null }, { "tokenAddress": "0x251f5e6e1f4fe6e55ba285efa6518b2707c9efe0", "name": "Kuru Test QQQx", "symbol": "QQQx", "decimals": 18, "logoUrl": null, "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": true, "isMintable": true, "isStrict": false, "firstPoolAddress": null }, { "tokenAddress": "0x7da7742fcdfd472697a52b0aaff818cae3139656", "name": "Kuru Test TSLAx", "symbol": "TSLAx", "decimals": 18, "logoUrl": null, "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": true, "isMintable": true, "isStrict": false, "firstPoolAddress": null }, { "tokenAddress": "0x184659b7968bd56f0243523183c923459e757548", "name": "Kuru Test EWYx", "symbol": "EWYx", "decimals": 18, "logoUrl": null, "description": null, "websiteUrl": null, "verified": false, "contractRenounced": false, "isErc20": true, "isMintable": true, "isStrict": false, "firstPoolAddress": null } ], "pagination": { "nextCursor": null } } ``` # Get user account transfers Source: https://docs.kuru.io/api/data-source/reference/user-account-transfers GET https://api.testnet.kuru.io/api/v1/users/{userId}/account-transfers Paginated deposits, withdrawals and internal transfers with accounting-basis USDC values. **userId** `string` *required* Unsigned 64-bit account ID as a decimal string. Only this account's transfers are returned. **tokenAddress** `string` Optional token address. **eventKind** `string` Optional: deposit, withdrawal, internal_transfer. **from** `integer` Inclusive Unix-second start. **to** `integer` Inclusive Unix-second end. Must exceed from when both are supplied. **limit** `integer` (default: 100) Page size, 1–500. **cursor** `string` Opaque next-page cursor. Keep all filters and limit unchanged. Newest first by block timestamp, block number, transaction index, log index, record index and transaction hash. Pagination freezes the indexed block cutoff from the first page. Expired, mismatched or invalid cursors return 400; restart from the first page. There is no Exchange Gateway replay sequence for this history. ## Response ```json theme={null} { "feedEpoch": "0", "data": [{ "eventKind": "internal_transfer", "direction": "out", "tokenAddress": "0x1111111111111111111111111111111111111111", "symbol": "USDC", "decimals": 6, "amountRaw": "10000000", "valueUsdcX18": "10000000000000000000", "fromUserId": "14", "toUserId": "24", "payerAddress": null, "recipientAddress": null, "executorAddress": "0x2222222222222222222222222222222222222222", "emitterAddress": "0x3333333333333333333333333333333333333333", "transactionHash": "0x53495e519fd932eaf46bcf8179ddca0ebe00a8098585d6614e70de32756deb56", "transactionIndex": 1, "logIndex": 3, "recordIdx": 0, "blockNumber": "71481467", "blockTimestamp": 1792136919 }], "pagination": {"nextCursor": null} } ``` | Field | Meaning | | - | - | | `feedEpoch` | Indexed epoch as string, null before initialization. Not a replay cursor. | | `eventKind` | Original transfer kind, one of the three request-filter values. | | `direction` | `in` (incoming) or `out` (outgoing) relative to the requested user. | | `tokenAddress`, `symbol`, `decimals` | Token identity and metadata; symbol/decimals can be null if unavailable. | | `amountRaw` | Nonnegative transfer amount as an exact integer string in token atoms. | | `valueUsdcX18` | Nonnegative accounting-basis USDC value × 10¹⁸, exact integer string, or null if unavailable. | | `fromUserId`, `toUserId` | Source/destination account IDs as strings; null when absent. | | `payerAddress`, `recipientAddress`, `executorAddress` | Event-supplied wallet addresses; null when absent. | | `emitterAddress` | Contract that emitted the transfer event. | | `transactionHash` | Source transaction hash. | | `transactionIndex`, `logIndex`, `recordIdx` | Numeric source indices; recordIdx identifies a decoded record within a log. | | `blockNumber` | Block height as decimal string. | | `blockTimestamp` | Block timestamp in Unix seconds. | | `pagination.nextCursor` | Next-page token, or null at the end. | Non-USDC valuation uses the requested user's matching transfer PnL row: `floor(amount_raw × basis_price_x18 / 10^token_decimals)`. The designated first market quotes USDC. Internal-transfer sender and recipient can have different accounting bases and therefore different values for the same transfer. This is not its historical market value or realized PnL. USDC is valued directly at \$1, even without a PnL row. Zero basis returns `"0"`; missing PnL/metadata returns null, without hiding the transfer. Unknown users or empty history return `data: []` and a null nextCursor. Invalid parameters return 400; POST returns 405. Existing endpoint shapes are unchanged. ```bash theme={null} curl --get 'https://api.testnet.kuru.io/api/v1/users/14/account-transfers' \ --data-urlencode 'eventKind=internal_transfer' \ --data-urlencode 'limit=100' ``` # Get finalized user balances Source: https://docs.kuru.io/api/data-source/reference/user-balances api/data-source/openapi.yaml GET /api/v1/users/{userId}/balances Read all finalized balances or select one token. > [!NOTE] > > Response JSON below is an illustrative testnet snapshot, not a live mainnet result. Use the selected server and its network-specific addresses for actual requests. **userId** `string` *required* Unsigned decimal Kuru user ID. **tokenAddress** `string` Optional lowercase 20-byte token address. When present, `data` contains zero or one matching balance. **feedEpoch** `integer | null` *required* Feed epoch containing `globalUserSeq`. **data** `array` *required* Up to 2,000 balances ordered by token address, or zero to one entry when `tokenAddress` is supplied. **globalUserSeq** `string | null` *required* Finalized user sequence covered by the snapshot. **truncated** `boolean` *required* `true` when additional balances were omitted from an unfiltered request. `total`, `available`, and `reserved` use the token's native decimal units, and `total = available + reserved`. When both cursor fields are non-null, install the snapshot and subscribe to `userBalances@f` with the same `feedEpoch` and `globalUserSeq`. ```json 200 theme={null} { "feedEpoch": 18, "data": [ { "tokenAddress": "0xb01dc575a7ef75e58a05d2bde73ab79f8e7dd0be", "total": "9072874016", "available": "9072874016", "reserved": "0" } ], "state": "finalized", "servedView": "finalized", "globalUserSeq": null, "truncated": false } ``` # Get user fee tier Source: https://docs.kuru.io/api/data-source/reference/user-fee-tier api/data-source/openapi.yaml GET /api/v1/users/{userId}/fee-tier Read active root-account fee-tier rates, or exchange defaults when missing or inactive. Returns rates from the latest indexed `AccountFeeTierUpdated` assignment when active, otherwise exchange defaults. Subaccounts inherit the root account's tier. No query parameters or request body are accepted. **userId** `string` *required* Unsigned 64-bit Kuru account ID as a decimal string. **feedEpoch** `string | null` *required* Materialization feed epoch, or `null` before initialization. `"0"` is a valid initial epoch, not a missing-data sentinel. This is not a replay sequence. **data.userId** `string` *required* Requested account ID. **data.rootUserId** `string | null` *required* Registered root account ID. Null for an unknown or incompletely registered account. **data.accountFeeTier** `object` *required* Latest indexed assignment's rates when active. When absent or inactive, returns exchange defaults: maker 1 BPS (`"1000"` PPS), taker 2 BPS (`"2000"` PPS). A later inactive assignment supersedes any earlier active assignment. **data.accountFeeTier.makerFeePps** `string` *required* Assigned integer maker rate in protocol PPS units, with denominator `10,000,000`. For example, `"4000"` represents 0.04%. Not a token or x18 amount. **data.accountFeeTier.takerFeePps** `string` *required* Assigned integer taker rate in the same PPS units. `"7000"` represents 0.07%. These are **assigned account rates, not effective trading fees**. The endpoint does not calculate market caps, referral discounts, or builder fees. Fixed exchange defaults apply when the latest assignment is missing or inactive. The `active` boolean is no longer returned. Active assignments with zero rates retain those zero rates. Illustrative response (not a claim that this account has these rates): ```json 200 theme={null} { "feedEpoch": "0", "data": { "userId": "4", "rootUserId": "2", "accountFeeTier": { "makerFeePps": "4000", "takerFeePps": "7000" } } } ``` An unknown user returns HTTP 200 with `rootUserId` set to `null` and the default `accountFeeTier`. Invalid IDs or unknown query parameters return 400. Unsupported methods, including POST, return 405. # Get finalized user open orders Source: https://docs.kuru.io/api/data-source/reference/user-orders api/data-source/openapi.yaml GET /api/v1/users/{userId}/orders Read a user's finalized open-order snapshot and replay cursor. **userId** `string` *required* Unsigned decimal Kuru user ID. **cloid** `string` Optional 32-byte `0x`-prefixed hexadecimal client order ID. With this filter, returns matching orders, including filled and cancelled orders, across all markets for the user. IDs may be shared within a batch or reused later; the response is a list, not a unique-order lookup. Empty or malformed values return 400. Hexadecimal letter case is normalized. For order-ID lookup, use `GET /api/v1/markets/{marketAddress}/orders?oid=123`. The user endpoint does not accept `oid`. Repeated `cloid` values return 400. **feedEpoch** `integer | null` *required* Feed epoch containing `globalUserSeq`. **data** `array` *required* Up to 2,000 orders, ordered by market address and then order ID. Without `cloid`, only open orders are returned. No matches returns an empty array. **globalUserSeq** `string | null` *required* Finalized user sequence covered by the snapshot. **data\[].isCancelled** `boolean` *required* Whether the order was cancelled. A fully filled order is not necessarily cancelled; use `remainingSize` alongside this field. **data\[].clientOrderId** `string | null` *required* Creation event's 32-byte hexadecimal client order ID. Null when unavailable. Later cancellations do not overwrite this ID. **truncated** `boolean` *required* `true` when additional matching orders were omitted. This bounded snapshot does not offer pagination. `price` is an integer in market price precision (pp). `remainingSize` uses the market's native size precision. `minSizeAfterBlock` is the block height after which reduce-after-block behavior applies. For an unfiltered request, when both cursor fields are non-null, install this snapshot and subscribe to `userOrders@f` with the same `feedEpoch` and `globalUserSeq`. Do not install a `cloid` lookup as a complete open-order snapshot. This endpoint always returns finalized data. `remainingSize` is not a cancellation-status field: a cancelled order may retain a positive remaining size. ```bash theme={null} curl 'https://api.testnet.kuru.io/api/v1/users/2/orders?cloid=0x0000000000000000000000000000000000000000000000000000000000000001' ``` ```json 200 theme={null} { "feedEpoch": 18, "data": [ { "orderId": "123", "marketAddress": "0x1111111111111111111111111111111111111111", "symbol": "MONUSDC", "isBuy": true, "price": "20900", "remainingSize": "100000000", "minSizeAfterBlock": null, "isCancelled": false, "clientOrderId": "0x0000000000000000000000000000000000000000000000000000000000000001" } ], "globalUserSeq": null, "truncated": false } ``` # List user trades Source: https://docs.kuru.io/api/data-source/reference/user-trades api/data-source/openapi.yaml GET /api/v1/users/{userId}/trades Read finalized maker and taker trades with allocated fees and PnL. > [!NOTE] > > Response JSON below is an illustrative testnet snapshot, not a live mainnet result. Use the selected server and its network-specific addresses for actual requests. **userId** `string` *required* Unsigned decimal Kuru user ID. **limit** `integer` (default: 100) Page size from `1` through `500`. **cursor** `string` Opaque exclusive continuation cursor from `pagination.nextCursor`. **marketAddress** `string` Optional lowercase 20-byte market filter for trade rows only. It does not filter `data.positions`. **from** `integer` Inclusive Unix time in seconds. **to** `integer` Inclusive Unix time in seconds. When both bounds are present, `to` must be greater than `from`. **feedEpoch** `integer | null` *required* Feed epoch containing `globalUserSeq`. **globalUserSeq** `string | null` *required* Finalized user sequence covered by the materialized response. **data** `object` *required* Trade history and the complete position baseline. **Data fields** **trades** `array` *required* Maker and taker user legs ordered newest first by canonical source position. **trades\[].tradeId** `string` *required* **trades\[].recordIdx** `integer` *required* **trades\[].marketAddress** `string` *required* **trades\[].symbol** `string` *required* **trades\[].isMaker** `boolean` *required* **trades\[].isBuy** `boolean` *required* Side of this user leg. **trades\[].liquidity** `string` *required* `active` for active FIFO liquidity or `passive` for passive-band liquidity. **trades\[].price** `string` *required* Execution price in market price precision (pp). **trades\[].filledSize** `string` *required* Fill quantity in the market's native size precision. **trades\[].updatedSize** `string` *required* Remaining active-order or passive-liquidity size after the fill. **trades\[].fees** `object` *required* Actual allocated fee amounts. Every value is normalized to x18 using integer floor division. **trades\[].pnl** `object` *required* Per-fill realized PnL and the available post-trade cost-basis cut. **trades\[].blockTimestamp** `integer` *required* Block proposal time in Unix seconds. **trades\[].blockNumber** `string` *required* **trades\[].transactionHash** `string` *required* **positions** `array` *required* Position baseline across all tracked markets for this user, ordered by market address. Independent of trade pagination, market filters, and time filters. Includes tracked closed positions with zero size and cost; returns `[]` when there are no tracked positions. These are trade-accounting positions, not token balances. **Position fields** **marketAddress** `string` *required* Lowercase market address. **openSize** `string` *required* Open base inventory in native market size precision (sp). **openCost** `string` *required* Cost basis of that inventory in native quote-token units. Divide by `10^quoteTokenDecimals` for display, using the market's quote token metadata. **pagination.nextCursor** `string | null` *required* The fee fields are `makerFee`, `takerFee`, `builderFeeBase`, and `builderFeeQuote`. Inapplicable amounts are zero. These are allocated fee amounts, not PPS rates. The PnL fields are `grossRealizedPnl`, `realizedPnl`, `openSize`, and `openCost`. Realized PnL fields remain x18; `openCost` uses native quote-token units and `openSize` uses native market size precision. This matches the units of `data.positions[].openCost` and `data.positions[].openSize`. `openSize` and `openCost` are `null` when the row does not publish an authoritative post-trade position cut. On the first page, `data.positions` and the replay cursor describe the same committed state, after complete trade matches. Historical `data.trades[].pnl` values still describe their individual trades, not this current baseline. Continuation pages retain the first page's positions and replay cursor, even when newer trades arrive. When both cursor fields are non-null, install `data.positions` once as the accounting baseline and subscribe to `userTrades@f`, using `feedEpoch` and passing `globalUserSeq` as the subscription's `seq`. Do not overwrite live positions when loading additional history pages. A fresh first-page request establishes a new baseline. If either cursor field is null, the response cannot establish a replay handoff; do not interpret a missing cursor as zero. The example below illustrates the response shape; cursor values are opaque. ```json 200 theme={null} { "feedEpoch": 18, "globalUserSeq": null, "data": { "trades": [ { "tradeId": "101", "recordIdx": 1, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "isMaker": true, "isBuy": false, "liquidity": "active", "price": "24707100", "filledSize": "60000000", "updatedSize": "940000000", "fees": { "makerFee": "0", "takerFee": "0", "builderFeeBase": "0", "builderFeeQuote": "0" }, "pnl": { "grossRealizedPnl": "-327912000000000000", "realizedPnl": "-327912000000000000", "openSize": "260000000", "openCost": "65640954" }, "blockTimestamp": 1788353771, "blockNumber": "59066947", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }, { "tradeId": "98", "recordIdx": 0, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "isMaker": true, "isBuy": true, "liquidity": "active", "price": "25227200", "filledSize": "80000000", "updatedSize": "920000000", "fees": { "makerFee": "0", "takerFee": "0", "builderFeeBase": "0", "builderFeeQuote": "0" }, "pnl": { "grossRealizedPnl": "0", "realizedPnl": "0", "openSize": "320000000", "openCost": "80788866" }, "blockTimestamp": 1788342297, "blockNumber": "59028992", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }, { "tradeId": "97", "recordIdx": 0, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "isMaker": true, "isBuy": false, "liquidity": "active", "price": "25277700", "filledSize": "80000000", "updatedSize": "920000000", "fees": { "makerFee": "0", "takerFee": "0", "builderFeeBase": "0", "builderFeeQuote": "0" }, "pnl": { "grossRealizedPnl": "19736000000000000", "realizedPnl": "19736000000000000", "openSize": "240000000", "openCost": "60600794" }, "blockTimestamp": 1788342296, "blockNumber": "59028988", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }, { "tradeId": "96", "recordIdx": 0, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "isMaker": true, "isBuy": true, "liquidity": "active", "price": "25566900", "filledSize": "80000000", "updatedSize": "920000000", "fees": { "makerFee": "0", "takerFee": "0", "builderFeeBase": "0", "builderFeeQuote": "0" }, "pnl": { "grossRealizedPnl": "0", "realizedPnl": "0", "openSize": "320000000", "openCost": "80801058" }, "blockTimestamp": 1788342288, "blockNumber": "59028961", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }, { "tradeId": "95", "recordIdx": 0, "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "symbol": "WETHUSDC", "isMaker": true, "isBuy": false, "liquidity": "active", "price": "25618000", "filledSize": "80000000", "updatedSize": "920000000", "fees": { "makerFee": "0", "takerFee": "0", "builderFeeBase": "0", "builderFeeQuote": "0" }, "pnl": { "grossRealizedPnl": "375708000000000000", "realizedPnl": "375708000000000000", "openSize": "240000000", "openCost": "60342878" }, "blockTimestamp": 1788342287, "blockNumber": "59028956", "transactionHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } ], "positions": [ { "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "openSize": "260000000", "openCost": "65640954" } ] }, "pagination": { "nextCursor": "eyJ2IjoxLCJyIjoidXNlci10cmFkZXMiLCJmIjoiYzJmNThiMGRjNDQyOWQ1MjBlYzczZDgyNzRjN2I1NDUzYmViODk3NDRkMTQ3YzVmOTRiMjkzYzY0YzJkZjYxNiIsInMiOiJlZWIzM2I0ZTFmYjMyNTZmNzc5YWYxOTEwMjU5ZDE4YzQzYjliNjc5ZWQ4MzIzOTQ1MWM0ZGU5ZmMwZTkwYjg4IiwibyI6MCwiZSI6MTc4ODQzNDA0OH0.cJ6grTznYNiRPhNs2QZq3ErEyxuc7g9A9i2RTj6FmRg" } } ``` # Get best bid and offer Source: https://docs.kuru.io/api/exchange/reference/bbo api/exchange/openapi.yaml GET /api/bbo Read the top of book from a retained projection view. > [!NOTE] > > The response below was observed for WETHUSDC on mainnet on 17 October 2026. Book levels and sequence numbers change; query the selected network for current state. **symbol** `string` *required* Configured market symbol. Matching is case-insensitive. **state** `string` (default: finalized) `proposed`, `voted`, or `finalized`. Short forms `p`, `v`, and `f` are also accepted. **feedEpoch** `integer` *required* Epoch namespace for `market_seq` and `global_seq`. **data** `object` *required* Top-of-book snapshot. **symbol** `string` *required* Requested market symbol. **market_id** `string` *required* Lowercase market contract address resolved from `symbol`. **state** `string` *required* Requested state. **served_view** `string` *required* Projection view that served the request. **market_seq** `integer` *required* Market sequence represented by the response. **global_seq** `integer` *required* Global sequence represented by the response. **bid** `object | null` *required* Best bid, or `null` when the bid side is empty. A populated side contains native pp `price` and native size-precision `total_base` integer strings. **ask** `object | null` *required* Best ask, or `null` when the ask side is empty. A populated side contains native pp `price` and native size-precision `total_base` integer strings. ```json 200 theme={null} { "feedEpoch": 0, "data": { "symbol": "WETHUSDC", "market_id": "0x8121ee960066e4344a213f9ac7502395502aee7a", "state": "finalized", "served_view": "finalized", "market_seq": 0, "global_seq": 20001, "bid": null, "ask": null } } ``` # Get L2 order book Source: https://docs.kuru.io/api/exchange/reference/l2-book api/exchange/openapi.yaml GET /api/depth Read a bounded order-book snapshot from a retained projection view. > [!NOTE] > > The response below was observed for WETHUSDC on mainnet on 17 October 2026. Book levels and sequence numbers change; query the selected network for current state. Returns bids from highest to lowest price and asks from lowest to highest price. **symbol** `string` *required* Configured market symbol. Matching is case-insensitive. **levels** `integer` (default: 20) Number of levels per side, from `1` through `200`. **state** `string` (default: finalized) `proposed`, `voted`, or `finalized`. Short forms `p`, `v`, and `f` are also accepted. **feedEpoch** `integer` *required* Epoch namespace for `market_seq` and `global_seq`. **data** `object` *required* Bounded L2 snapshot. **symbol** `string` *required* Requested market symbol. **market_id** `string` *required* Lowercase market contract address resolved from `symbol`. **state** `string` *required* Requested state. **served_view** `string` *required* Projection view that served the request. **market_seq** `integer` *required* Market sequence represented by the snapshot. **global_seq** `integer` *required* Global sequence represented by the snapshot. **bids** `array` *required* Bid levels ordered by descending price. Each level contains native pp `price` and native size-precision `total_base` integer strings. **asks** `array` *required* Ask levels ordered by ascending price. Each level contains native pp `price` and native size-precision `total_base` integer strings. ```json 200 theme={null} { "feedEpoch": 0, "data": { "symbol": "WETHUSDC", "market_id": "0x8121ee960066e4344a213f9ac7502395502aee7a", "state": "finalized", "served_view": "finalized", "market_seq": 0, "global_seq": 20001, "bids": [], "asks": [] } } ``` # Get projected user balances Source: https://docs.kuru.io/api/exchange/reference/user-balances api/exchange/openapi.yaml GET /api/v1/users/{userId}/balances Read a current proposed, voted, or finalized balance snapshot. **userId** `string` *required* Unsigned decimal Kuru user ID. **state** `string` (default: finalized) `proposed`, `voted`, or `finalized`. Short forms `p`, `v`, and `f` are also accepted. **feedEpoch** `integer` *required* Epoch namespace for `globalSeq` and `globalUserSeq`. **data** `array` *required* Up to 2,000 balances in immutable snapshot order. **tokenAddress** `string` *required* Lowercase token contract address. **total** `string` *required* Checked sum of available and reserved native token units. **available** `string` *required* Free native token units. **reserved** `string` *required* Reserved native token units. **state** `string` *required* Requested projection view. **servedView** `string` *required* Projection view that served the request. **globalSeq** `integer | null` *required* Global sequence represented by the projection snapshot. **globalUserSeq** `integer | null` *required* User sequence represented by the projection snapshot. **truncated** `boolean` *required* `true` when additional balances were omitted. This gateway route does not accept a `tokenAddress` filter. ```json 200 theme={null} { "feedEpoch": 7, "data": [{ "tokenAddress": "0xb01dc575a7ef75e58a05d2bde73ab79f8e7dd0be", "total": "1200250000", "available": "1100250000", "reserved": "100000000" }], "state": "finalized", "servedView": "finalized", "globalSeq": 124367, "globalUserSeq": 2951, "truncated": false } ``` For token filtering or a finalized epoch-qualified WebSocket bootstrap, use the [Data Source user-balances route](/api/data-source/reference/user-balances). # Get projected user open orders Source: https://docs.kuru.io/api/exchange/reference/user-orders api/exchange/openapi.yaml GET /api/v1/users/{userId}/orders Read a current proposed, voted, or finalized open-order snapshot. > [!NOTE] > > Response JSON below is an illustrative testnet snapshot, not a live mainnet result. Use the selected server and its network-specific addresses for actual requests. **userId** `string` *required* Unsigned decimal Kuru user ID. **state** `string` (default: finalized) `proposed`, `voted`, or `finalized`. Short forms `p`, `v`, and `f` are also accepted. **feedEpoch** `integer` *required* Epoch namespace for `globalSeq` and `globalUserSeq`. **data** `array` *required* Up to 2,000 open orders in immutable snapshot order. **orderId** `string` *required* Protocol order ID. **marketAddress** `string` *required* Lowercase market contract address. **slotIdx** `integer` *required* Protocol slot index inside the maker page, from `0` through `255`. **symbol** `string | null` *required* Configured market symbol, or `null` when it is absent from the catalog. **isBuy** `boolean` *required* `true` for a buy order and `false` for a sell order. **orderType** `string` *required* Always `limit` in this version. **price** `string` *required* Signed integer price in market price precision (pp). **remainingSize** `string` *required* Remaining native market size units. **minSizeAfterBlock** `integer | null` *required* Block threshold associated with reduce-after-block behavior, when present. **createdAt** `integer` *required* Creation-block Unix timestamp in seconds. Retained through partial fills and checkpoint restore; matches the userOrders WebSocket snapshot creation time. **clientOrderId** `string | null` *required* Optional client-supplied order correlation ID. **state** `string` *required* Requested projection view. **servedView** `string` *required* Projection view that served the request. **globalSeq** `integer | null` *required* Global sequence represented by the projection snapshot. **globalUserSeq** `integer | null` *required* User sequence represented by the projection snapshot. **truncated** `boolean` *required* `true` when additional open orders were omitted. ```json 200 theme={null} { "feedEpoch": 7, "data": [{ "orderId": "77738308", "marketAddress": "0x0a082280e4ea3d822e23ec1186685477241a039d", "slotIdx": 3, "symbol": "WETHUSDC", "isBuy": true, "orderType": "limit", "price": "230000000", "remainingSize": "750000000000000000000", "minSizeAfterBlock": null, "clientOrderId": null, "createdAt": 1700000000 }], "state": "finalized", "servedView": "finalized", "globalSeq": 124367, "globalUserSeq": 2951, "truncated": false } ``` For a finalized REST-to-WebSocket bootstrap with an epoch-qualified cursor, use the [Data Source user-orders route](/api/data-source/reference/user-orders). # Exchange Gateway REST API Source: https://docs.kuru.io/api/exchange/rest Current projected books, balances, and open orders. The REST method playground defaults to mainnet and offers testnet in its server dropdown: ```text theme={null} Mainnet (default): https://gateway.mainnet.kuru.io Testnet: https://gateway.testnet.kuru.io ``` It exposes the latest retained proposed, voted, and finalized projections. Market history and candles are served by the [Data Source REST API](/api/data-source). > [card] [L2 order book](/api/exchange/reference/l2-book) > > Read a bounded finalized order-book snapshot. > [card] [Best bid and offer](/api/exchange/reference/bbo) > > Read the current top of book. > [card] [User balances](/api/exchange/reference/user-balances) > > Read all current spot balances in the retained snapshot. > [card] [User open orders](/api/exchange/reference/user-orders) > > Read a user's current open-order snapshot. ## Projection states `/api/depth`, `/api/bbo`, and the user snapshot routes accept `proposed`, `voted`, or `finalized`. Short forms `p`, `v`, and `f` are also accepted. ## Numeric units * Addresses are lowercase `0x`-prefixed 20-byte values. * User IDs are unsigned decimal path values. * Book sequence cursors are JSON integers. * Book prices are native pp integer strings; sizes are native sp integer strings. * Order prices are signed native pp integer strings; sizes remain native market size-precision integers. * Base sizes use the market's native `sizePrecision` domain. * Token balances use the token's native decimal domain. * Percentage fields are decimal ratios: `"0.01"` means one percent. Never parse these quantities through binary floating point. User orders and balances are bounded snapshots rather than paginated collections. Each returns at most 2,000 entries and sets `truncated` when additional entries were omitted. ## Errors Errors use one envelope: ```json theme={null} { "feedEpoch": 7, "error": { "code": "BadRequest", "message": "limit must be between 1 and 500" } } ``` Stable codes are `BadRequest`, `NotFound`, `Unsupported`, `RateLimited`, and `Internal`. # userTrades response changelog Source: https://docs.kuru.io/api/exchange/user-trades-changelog Fee, source identity, and binary layout changes for userTrades in KUR-1717. ## KUR-1717: userTrades fee and source fields This testnet change extends only `userTrades` (binary kind 9). Wire version remains **1**, so update Gateway and SDK consumers together. The updated decoder expects the new layout; it does not negotiate or decode the previous layout. | Decoded field | Previous response | Updated response | | - | - | - | | `liquidity.makerFeePps` | Absent | `number`, active FIFO only | | `effectiveTakerFeePps` | Absent | `number`, every trade | | `builderFeePps` | Absent | `number`, every trade | | `matchEnd` | Absent | `boolean`, every trade | | `txHash` | Absent | 32-byte hex string, every trade | | `txIdx` | Absent | `number`, every trade | | `logIdx` | Absent | `number`, every trade | All existing fields retain their meaning. `users` remains `[takerId, makerId]`; passive fills use maker ID `0n`. `recordIndex` keeps its existing name and source position. Prices and sizes remain in market price/size precision. Fee rates are historical event inputs in PPS, with denominator **10,000,000**. Passive fills have no `makerFeePps` field. Builder address and calculated fee/position amounts are not included. ### Binary layout All integer fields are big-endian. The first trade row still begins at frame offset 92. Row-relative offsets: | Field | Active FIFO offset | Passive-band offset | Width | | - | - | - | - | | `makerFeePps` | 98 | Not present | 4 bytes | | `txHash` | 102 | 96 | 32 bytes | | `txIdx` | 134 | 128 | 4 bytes | | `logIdx` | 138 | 132 | 4 bytes | | `effectiveTakerFeePps` | 142 | 136 | 4 bytes | | `builderFeePps` | 146 | 140 | 4 bytes | | `matchEnd` | 150 | 144 | 1 byte: 0 or 1 | Active rows grow from **98 to 151 bytes**; passive rows grow from **96 to 145 bytes**. Advance by the row's liquidity-specific size. Existing fields retain their offsets. The frame envelope, subscription request, epoch, sequence and predecessor fields are unchanged. ### Delivery and integration A packed log is normalized into separate trade records. The current projector emits one trade per publication; clients should still iterate the `trades` array. A match can span frames. Takers receive their active, passive and self fills in order; makers receive only their own fills. `matchEnd` terminates the source match, not a frame or a maker's filtered stream. One packed log can contain multiple matches. Makers do not wait for another user's terminal fill. Keep unfinished taker-match state consistent with the saved replay cursor. If that buffer is lost, replay from the cursor before the unfinished match, or bootstrap again when history is unavailable. Existing delivery and replay mechanics are unchanged. No match buffering or position accounting is added to Core or the SDK decoder. Public `trades`, `userOrders`, and other stream layouts are unchanged. ## KUR-1719: canonical event timestamps Each `trades` and `userTrades` row and each `userOrders.events` delta event now exposes `blockTimestamp: bigint`: the canonical source block-header time in Unix seconds. Live delivery, finalization promotion, and retained replay use the same original value. This is not delivery time or finalization time. An eight-byte big-endian `u64` is appended to each row/event: | Row/event | Timestamp offset | Previous size | New size | | - | - | - | - | | Market trade | 35 | 35 | 43 | | Active user trade | 151 | 151 | 159 | | Passive user trade | 145 | 145 | 153 | | Order created | 147 | 147 | 155 | | Order trade | 128 | 128 | 136 | | Order cancelled | 80 | 80 | 88 | | Order rab-reduced | 96 | 96 | 104 | Offsets are relative to each row/event. Existing fields and frame envelopes keep their offsets. Order snapshots and all other stream layouts are unchanged. Snapshot state time is not substituted for an order's historical creation time. Wire version remains 1 for the coordinated testnet rollout. Update server and decoder together; the older timestamp-free rows are incompatible with this layout. Timestamp zero is a valid Unix epoch value. Missing timestamp metadata fails server encoding; it is not replaced with zero or the current time. ## KUR-1726: open-order creation time Every `userOrders` snapshot order exposes `createdAt: bigint`, the original creation-block timestamp in Unix seconds. It remains unchanged through partial fills and subsequent order updates and survives checkpoints and restarts. The snapshot order row appends an eight-byte big-endian u64 at offset 96, increasing its size from 96 to 104 bytes. Wire version remains 1 for testnet; roll out the Gateway and SDK decoder together. Delta event layouts remain unchanged: on a `created` event, use `blockTimestamp` to initialize the order's `createdAt`; preserve that value when applying later trade or reduction events. # Exchange WebSocket API Source: https://docs.kuru.io/api/exchange/websocket Binary market and user streams with replayable sequence cursors. Browsers connect directly to `wss://gateway.mainnet.kuru.io/ws` on mainnet or `wss://gateway.testnet.kuru.io/ws` on testnet. The examples below target mainnet. One connection can multiplex market and user subscriptions. Control messages are JSON text frames; data messages are binary frames with an eight-byte subscription ID followed by a payload beginning with the `KXMD` magic bytes. Every server response carries a `feedEpoch`. The epoch is fixed for the server process and namespaces every market and user sequence. A sequence number is only meaningful together with the epoch in which it was issued. ```js theme={null} const socket = new WebSocket("wss://gateway.mainnet.kuru.io/ws"); socket.binaryType = "arraybuffer"; ``` The public frontend contract subscribes to finalized (`@f`) topics. > [card] [L2 deltas](/api/exchange/websocket-reference/l2-delta) > > Snapshot, replay, and live order-book changes. > [card] [Trades](/api/exchange/websocket-reference/trades) > > Replayable market fills. > [card] [L2 book](/api/exchange/websocket-reference/l2-book) > > Periodic complete order-book snapshots. > [card] [BBO](/api/exchange/websocket-reference/bbo) > > Periodic best bid and offer snapshots. > [card] [All mids](/api/exchange/websocket-reference/all-mids) > > Mid prices for every active market. > [card] [User orders](/api/exchange/websocket-reference/user-orders) > > Replayable order updates with periodic snapshots. > [card] [User balances](/api/exchange/websocket-reference/user-balances) > > Replayable balance updates with periodic snapshots. > [card] [User trades](/api/exchange/websocket-reference/user-trades) > > Replayable taker- and active-maker-side executions. ## Control requests Clients send control requests as UTF-8 JSON text frames. Binary frames are reserved for server data. The request object is strict: unknown keys are rejected instead of ignored. ```ts theme={null} type ExchangeWsControlRequest = | { op: "sub"; id: number; t: string; m?: string; u?: number; feedEpoch?: number; seq?: number; n?: number; g?: "none" | "tick" | "sf"; tk?: number; sf?: number; mt?: number; e?: boolean; } | { op: "unsub"; id: number } | { op: "ping"; ts?: number }; ``` The Gateway's Rust parser accepts non-negative JSON integers across the full unsigned 64-bit range unless a narrower bound is stated below. JavaScript clients must restrict number-valued controls to `Number.MAX_SAFE_INTEGER` (`9,007,199,254,740,991`) because larger JSON numbers cannot be represented exactly. Binary-frame sequence values remain `bigint`; do not lossy-convert a larger cursor to `number` when constructing a control request. | Key | Required for | Meaning | | - | - | - | | `op` | Every request | `sub`, `unsub`, or `ping` | | `id` | `sub`, `unsub` | Client-selected unsigned request and subscription ID | | `t` | `sub` | Case-sensitive compact topic string | | `m` | Market topics | Lowercase, `0x`-prefixed 20-byte market address | | `u` | User topics | Numeric Kuru user ID | | `feedEpoch` | `sub` with `seq` | Expected feed namespace; may also bind a fresh subscription without replay | | `seq` | Replayable `sub` | Last sequence already applied by the client; replay starts strictly after it | | `ts` | `ping` | Optional client timestamp echoed unchanged by `pong` | | `n` | `l2Book` only | Depth per side, `1..200`; defaults to `20` | | `g` | `l2Book` only | `none`, `tick`, or `sf`; defaults to `none` | | `tk` | `l2Book` with `g=tick` | Positive native tick grouping size | | `sf` | `l2Book` with `g=sf` | Significant-figure count from `2` through `5` | | `mt` | `l2Book` with `g=sf` and `sf=5` | Optional mantissa bucket: `1`, `2`, or `5` | | `e` | `l2Book` only | Extended L2 tuples when `true`; defaults to `false` | ### Subscribe The documentation and examples default to the finalized view. Every topic still requires an explicit view suffix: use `@f` for finalized, `@v` for voted, or `@p` for proposed. Market makers seeking earlier updates should use `@p`, or `@v` when they prefer to wait for voting. These views are available for production trading integrations, not just diagnostics. Both are tentative: use `@f` when your application requires finalized state. Track tentative changes by block ID. On `branchDropped`, undo the affected block's order, balance and trade effects; the stream does not send individual inverse business updates. Applicable lifecycle controls are included in retained replay. If replay is unavailable or the feed epoch changes, bootstrap again. Periodic user-order and balance snapshots replace state at their advertised cut; they do not replace immediate branch reconciliation. The topic determines its scope, cadence, and whether `seq` is accepted: | Finalized topic | Required selector | Duration | Replay cursor | L2 options | | - | - | - | - | - | | `l2Delta@f` | `m` | Forbidden | `MarketSeq` | Forbidden | | `trades@f` | `m` | Forbidden | `MarketSeq` | Forbidden | | `l2Book@f@` | `m` | Required, positive | Unsupported | Allowed | | `bbo@f[@]` | `m` | Optional; default `50` ms | Unsupported | Forbidden | | `allMids@f[@]` | Neither `m` nor `u` | Optional; default `50` ms | Unsupported | Forbidden | | `userOrders@f[@]` | `u` | Optional; default `300` ms | `GlobalUserSeq` | Forbidden | | `userBalances@f[@]` | `u` | Optional; default `300` ms | `GlobalUserSeq` | Forbidden | | `userTrades@f` | `u` | Forbidden | `GlobalUserSeq` | Forbidden | Replace `@f` with `@v` or `@p` to select another supported view. All other topic-specific field rules remain the same. Market subscriptions require `m` and reject `u`. User subscriptions require `u` and reject `m`. `allMids` rejects both selectors. The six L2 formatting fields are accepted together only by `l2Book`; supplying any of them to another topic returns `bad_options`. For significant-figure grouping, `g=sf` requires `sf`. `mt` is permitted only when `sf=5`. For native-tick grouping, `g=tick` requires a positive `tk` and rejects `sf` and `mt`. The ungrouped mode rejects `tk`, `sf`, and `mt`. `seq` must be greater than zero and is accepted only by the five replayable streams in the table. Whenever `seq` is present, `feedEpoch` is required. A `feedEpoch` may be supplied without `seq` to ensure a fresh subscription still belongs to the REST response's namespace. Any asserted epoch is checked before replay or subscription ownership; a mismatch returns `feed_epoch_mismatch`. Subscribe to a market stream after applying sequence `1022`: ```json theme={null} { "op": "sub", "id": 1, "t": "l2Delta@f", "m": "0x8121EE960066e4344A213F9aC7502395502aEe7a", "feedEpoch": 0, "seq": 1022 } ``` Subscribe to a user stream after applying sequence `2951`: ```json theme={null} { "op": "sub", "id": 2, "t": "userOrders@f@300", "u": 2, "feedEpoch": 0, "seq": 2951 } ``` An accepted subscription receives an acknowledgement before bootstrap, replay, or live binary frames: ```json theme={null} {"op":"ack","feedEpoch":0,"id":1,"t":"l2Delta@f"} ``` The `id` must be unique among active subscriptions on that connection. A duplicate ID or a connection subscription-cap rejection returns `bad_options`. The ID becomes reusable after a successful unsubscribe. ### User-stream delivery cadence `userOrders` and `userBalances` accept nonnegative integer millisecond durations and internally floor them to four delivery modes: | Requested duration | Effective delivery | | - | - | | `0`–`99` (including `@1`) | Immediate, without intentional coalescing | | `100`–`299` | 100 ms | | `300`–`499` | 300 ms | | `500` or greater | 500 ms | | Omitted | 300 ms | For latency-sensitive market makers, use explicit `userOrders@p@0` and `userBalances@p@0`, with branch reconciliation as described above. Flooring applies to all three views. Immediate delivery removes the batching timer, not confirmation waiting, processing or network latency. The effective duration must not exceed the configured full-snapshot interval (five seconds by default). Periodic full snapshots remain enabled in immediate mode. `userTrades` has no coalescing parameter. Other topics keep their own duration rules; the user-stream flooring does not apply to market topics. ### Unsubscribe Unsubscribe by the same client-selected ID: ```json theme={null} {"op":"unsub","id":1} ``` The operation is idempotent. The Gateway acknowledges it even when that ID is not currently active: ```json theme={null} {"op":"ack","feedEpoch":0,"id":1,"t":"unsub"} ``` ### Application ping An application-level ping may include a timestamp: ```json theme={null} {"op":"ping","ts":1784794509021} ``` The Gateway echoes `ts` when present: ```json theme={null} {"op":"pong","feedEpoch":0,"ts":1784794509021} ``` This JSON ping is separate from the native WebSocket Ping frame the Gateway sends every 15 seconds by default. Browsers answer native Ping frames with Pong automatically. ## Control responses All `ack`, `pong`, `err`, `resync`, and `resub` responses carry `feedEpoch`. Control responses are JSON text frames and are distinct from binary market and user data frames. ### Acknowledgement and pong `ack` confirms either a successful subscription or an idempotent unsubscribe. For a subscription, the acknowledgement is queued before any bootstrap, replay, or live binary data. `pong` echoes the optional timestamp from an application-level `ping`. ```json theme={null} {"op":"ack","feedEpoch":0,"id":1,"t":"l2Delta@f"} ``` ```json theme={null} {"op":"pong","feedEpoch":0,"ts":1784794509021} ``` ### Errors Invalid requests receive `err` with a stable code and a diagnostic message. `id` is optional: it is absent when parsing or validation fails before the Gateway can recover a request ID. ```json theme={null} { "op": "err", "feedEpoch": 0, "id": 1, "c": "bad_options", "msg": "seq requires feedEpoch" } ``` | Code | Meaning | | - | - | | `bad_json` | Malformed JSON, an unknown key, or an invalid `op` value | | `bad_op` | Missing `id` for `sub` or `unsub` | | `bad_topic` | Missing, malformed, unknown, or duration-incompatible topic | | `bad_market` | Missing, malformed, or forbidden market selector | | `bad_user` | Missing, malformed, or forbidden user selector | | `bad_view` | Missing or invalid view suffix | | `bad_duration` | Missing, malformed, or unsupported duration for the topic (`0` is valid for user orders/balances) | | `bad_options` | Invalid option combination, replay cursor, or connection limit | | `feed_epoch_mismatch` | Asserted epoch differs from the live server epoch | | `unsupported` | Recognized feature is unavailable, or the control-message rate limit was exceeded | ### Market resynchronization A market replay or live-join gap emits a market `resync` control. It has no subscription `id`; the affected stream is identified by topic `t` and market `m`. `seq` is the Gateway's suggested first available sequence boundary. ```json theme={null} { "op": "resync", "feedEpoch": 0, "t": "l2Delta@f", "m": "0x8121EE960066e4344A213F9aC7502395502aEe7a", "seq": 992500 } ``` Stop applying that market stream, discard its local derived state, and create a fresh subscription. For `l2Delta`, omit `seq` so the Gateway supplies a new authoritative L2 snapshot before live deltas. ### User resynchronization A user resync includes the affected subscription `id`, topic, a stable reason, and optional cursor information: ```json theme={null} { "op": "resync", "feedEpoch": 0, "id": 8, "t": "userTrades@f", "seq": 82000, "latest": 83000, "r": "history_lost" } ``` `history_lost` applies to `userTrades`, which has no authoritative snapshot with which to bridge an evicted history range. Refresh the corresponding REST history, then recreate the subscription using the supplied `feedEpoch` and `seq` as the last processed cursor when `seq` is present. `latest` is the latest sequence indexed for that exact user stream and may be absent. `userOrders` and `userBalances` first try to recover a retention gap transparently: the Gateway emits an authoritative snapshot, replays from that baseline, and continues the existing subscription without a control response. Only when it cannot establish a safe baseline does it emit: ```json theme={null} { "op": "resync", "feedEpoch": 0, "id": 6, "t": "userOrders@f@300", "seq": 82000, "latest": 83000, "r": "baseline_unavailable" } ``` On `baseline_unavailable`, discard the affected user state and resubscribe without `seq`; the Gateway will establish a new authoritative snapshot. ### Resubscription `resub` means the publisher-side subscription has already been removed. The WebSocket connection normally remains open and other subscription IDs are unaffected. ```json theme={null} { "op": "resub", "feedEpoch": 0, "id": 1, "t": "trades@f", "r": "publication_gap" } ``` The reason is `upstream_closed` when the upstream publisher or forwarding task ended unexpectedly, or `publication_gap` when lossless live delivery could no longer prove continuity. Recreate only the identified subscription, normally using a new client-selected ID and the last cursor your client durably applied. ## Sequence reconciliation `l2Delta` and market `trades` use per-market `marketSeq` cursors. User orders, balances, and trades use per-user `globalUserSeq` cursors. An exact `(market, view, topic)` or `(user, view, topic)` stream can be sparse within its sequence domain, so continuity follows the predecessor encoded in each frame, not arithmetic adjacency. Treat the replay cursor as `(feedEpoch, marketSeq)` or `(feedEpoch, globalUserSeq)`, and store it only after the corresponding payload has been applied. When `seq` is supplied in a subscription, `feedEpoch` is required. The server rejects a stale epoch with `feed_epoch_mismatch` rather than interpreting the sequence in a new namespace. For a market replay requested after sequence `R`, accept the first returned frame only when `marketSeq > R` and `previousMarketSeq` is `null` or less than or equal to `R`. After accepting that bridge frame, require each subsequent frame's `previousMarketSeq` to equal the last accepted `marketSeq` exactly. User streams apply the same rule using `globalUserSeq` and `previousGlobalUserSeq`. A predecessor may be much lower than the current sequence; never derive it by subtracting one. For market trades, use `feedEpoch` and `marketSeq` from the [Data Source market-trades response](/api/data-source/reference/market-trades). For user streams, use `feedEpoch` and `globalUserSeq` from the corresponding Data Source user response. Gateway REST responses also carry `feedEpoch`, but the supported L2 bootstrap is the snapshot emitted by `l2Delta` itself. Start an L2 stream without `seq` when you need that initial snapshot. When a sequence-linked stream reports an unrecoverable gap, stop applying updates and follow the specific `resync` or `resub` instruction rather than guessing over the missing range. User-order and user-balance retention gaps may instead be repaired transparently with an authoritative snapshot. If a binary frame carries a different `feedEpoch` from the installed client state, discard it and bootstrap again. Never compare sequence numbers across epochs. ## Binary frame header Every binary data frame starts with the same 16-byte header: | Offset | Width | Field | | - | - | - | | `0` | `4` | ASCII magic `KXMD` | | `4` | `1` | Wire version (`1`) | | `5` | `1` | Message kind | | `6` | `1` | View or finality code | | `7` | `1` | Message flags | | `8` | `8` | Unsigned `feedEpoch` | Kind-specific fields begin at byte `16`. Kinds `2` (`l2Delta`), `3` (market `trades`), and market-scoped kind `4` (`lifecycle`) share this replayable market prefix after the common header: | Offset | Width | Field | | - | - | - | | `16` | `20` | `marketAddress` | | `36` | `8` | `marketSeq` | | `44` | `8` | `previousMarketSeq`; zero means `null` | | `52` | `8` | `globalSeq` | For `l2Delta` and market `trades`, `sourceBlockNumber` occupies bytes `60..68`, `sourceBlockId` occupies bytes `68..100`, and the record count occupies bytes `100..104`. The market lifecycle body begins at byte `60`. `l2Book`, BBO, and all-mids retain 16-byte signed price fields. Delta/trade/order prices use 8-byte signed fields. All prices are native pp integers. L2 delta tuples are 61 bytes; market trade tuples are 43 bytes; user snapshot orders are 104 bytes; active/passive user trades are 159/153 bytes. Wire version remains 1 for the coordinated testnet rollout. Update clients that assumed x18 snapshot units or the intermediate widened event-price layout together with the server. > [!NOTE] > > The reference pages describe the exact objects returned by the shared > envelope decoder's `message` property. Use `decodeExchangeWsEnvelope` on socket > bytes; `decodeExchangeWsFrame` accepts only the inner payload. The decoders > preserve wire integers as `bigint`. Every > price is in native market price precision (pp); market/order/trade quantities remain native size precision. > Token balances retain native token decimals. Do not apply a second price conversion. ## Lifecycle frames Replayable streams may interleave lifecycle frames where the selected view requires them. The decoder returns the following shape: ```ts theme={null} interface ExchangeWsLifecycleEvent { action: | "blockProposed" | "blockVoted" | "blockFinalized" | "blockExecuted" | "branchDropped"; blockNumber: bigint; blockId: string; parentBlockId: string | null; dropReason: | "competingBlock" | "sourceDroppedSignal" | "parentNotCanonical" | "sourceCorrection" | null; replacementBlockId: string | null; } interface ExchangeWsMarketLifecycleFrame { wireVersion: 1; feedEpoch: bigint; view: "proposed" | "voted" | "finalized"; kind: "lifecycle"; scope: "market"; marketAddress: string; marketSeq: bigint; previousMarketSeq: bigint | null; globalSeq: bigint; event: ExchangeWsLifecycleEvent; } interface ExchangeWsUserLifecycleFrame { wireVersion: 1; feedEpoch: bigint; view: "proposed" | "voted" | "finalized"; kind: "lifecycle"; scope: "user"; userId: bigint; globalUserSeq: bigint | null; globalSeq: bigint | null; previousGlobalUserSeq: bigint | null; event: ExchangeWsLifecycleEvent; } ``` Finalized market streams contain only promoted market data and do not emit lifecycle frames. Under the current user-retention semantics, finalized user streams may still replay promoted lifecycle controls. Consumers should handle `kind: "lifecycle"` rather than assuming every user frame is a business-data frame. See the [userTrades response changelog](/api/exchange/user-trades-changelog) for fee/source fields and the coordinated version-1 testnet decoder update. ## Binary subscription envelope Every binary socket message starts with an eight-byte unsigned big-endian `id`, followed by the existing `KXMD` payload. The id is the client-selected subscription id within that socket. This applies to all streams and to snapshots, replay and live messages; one prefix identifies the entire message, including all its rows. All existing layout offsets describe the inner payload; add eight for socket offsets. Use `decodeExchangeWsEnvelope(data)` for synchronous binary decoding or `await decodeExchangeWsMessage(data)` for binary/Blob input. Both return `{ id: bigint, message }`; route `message` by `id` within the socket. The existing `decodeExchangeWsFrame` and stream-specific frame decoders accept only the inner payload after the prefix has been removed. > [!WARNING] > > See [decoder support](/sdk/installation#exchange-websocket-decoder-compatibility) before selecting an SDK decoder for these frame layouts. ```ts theme={null} import { decodeExchangeWsMessage } from "@toxicflow-labs/ts-sdk/exchange-ws"; socket.binaryType = "arraybuffer"; socket.onmessage = async ({ data }) => { if (typeof data === "string") { // Handle JSON acknowledgement and recovery controls separately. return; } const { id, message } = await decodeExchangeWsMessage(data); // id is a bigint matching the client-supplied subscription id on this socket. console.log(id, message.kind, message); }; ``` Two subscriptions to the same topic can receive identical inner payloads with different outer IDs. Route by the envelope `id`, not by topic or frame kind: an `l2Delta` subscription also receives an `l2Book` bootstrap frame. The decoded field is named `id`, not `subscriptionId`. The inner KXMD header starts at socket byte 8; its payload starts at socket byte 24. JSON control messages and WebSocket ping/pong are unchanged. Wire version stays 1 on testnet, but this is a breaking framing change: deploy the Gateway and updated socket decoder together. Unprefixed messages are not auto-detected. # All mids stream Source: https://docs.kuru.io/api/exchange/websocket-reference/all-mids Receive finalized mid prices for every active market. ```text theme={null} allMids@f[@] ``` This global snapshot stream accepts neither `m` nor `u`. The duration is optional and defaults to `50` milliseconds. ## Subscribe ```json theme={null} {"op":"sub","id":5,"t":"allMids@f@500","feedEpoch":0} ``` ## Decoded event The shape below is the inner `message` returned by `decodeExchangeWsEnvelope` or `decodeExchangeWsMessage`. Every binary socket message also carries an outer `id: bigint`, matching your subscription ID. Use it to route snapshots, replay, and live updates. See [binary subscription envelopes](/api/exchange/websocket#binary-subscription-envelope). ```ts theme={null} interface ExchangeWsAllMidsFrame { wireVersion: 1; feedEpoch: bigint; view: "finalized"; kind: "allMids"; mids: Array<{ marketAddress: string; midpoint: bigint; }>; } ``` Each entry contains a lowercase market address and its native pp midpoint. Markets without both a bid and an ask may be omitted. # BBO stream Source: https://docs.kuru.io/api/exchange/websocket-reference/bbo Receive finalized best bid and offer snapshots. ```text theme={null} bbo@f[@] ``` This market-scoped snapshot stream publishes the current best bid and offer. The duration is optional and defaults to `50` milliseconds. It does not use a replay cursor. ## Subscribe ```json theme={null} { "op": "sub", "id": 4, "t": "bbo@f@500", "m": "0x8121EE960066e4344A213F9aC7502395502aEe7a", "feedEpoch": 0 } ``` ## Decoded event The shape below is the inner `message` returned by `decodeExchangeWsEnvelope` or `decodeExchangeWsMessage`. Every binary socket message also carries an outer `id: bigint`, matching your subscription ID. Use it to route snapshots, replay, and live updates. See [binary subscription envelopes](/api/exchange/websocket#binary-subscription-envelope). ```ts theme={null} interface ExchangeWsBboLevel { price: bigint; totalBase: bigint; } interface ExchangeWsBboFrame { wireVersion: 1; feedEpoch: bigint; view: "finalized"; kind: "bbo"; marketAddress: string; marketSeq: bigint; globalSeq: bigint; stateHead: { blockNumber: bigint; blockId: string }; bid: ExchangeWsBboLevel | null; ask: ExchangeWsBboLevel | null; } ``` An empty side is `null`. `price` is a native pp integer and `totalBase` is a native sp integer. Both decode as `bigint`. # L2 book stream Source: https://docs.kuru.io/api/exchange/websocket-reference/l2-book Receive complete finalized order-book snapshots on a fixed cadence. ```text theme={null} l2Book@f@ ``` This market-scoped snapshot stream sends the current finalized book when the subscription starts and then publishes complete snapshots on the requested cadence. It does not use a replay cursor. ## Subscribe ```json theme={null} { "op": "sub", "id": 3, "t": "l2Book@f@500", "m": "0x8121EE960066e4344A213F9aC7502395502aEe7a", "feedEpoch": 0, "n": 20, "g": "sf", "sf": 5, "mt": 2, "e": false } ``` `n` is depth per side from `1` through `200`. Grouping `g` is `none`, `tick`, or `sf`. Use `tk` with tick grouping, `sf` and optional `mt` with significant figures, and `e=true` for active/passive decomposition. ## Decoded event The shape below is the inner `message` returned by `decodeExchangeWsEnvelope` or `decodeExchangeWsMessage`. Every binary socket message also carries an outer `id: bigint`, matching your subscription ID. Use it to route snapshots, replay, and live updates. See [binary subscription envelopes](/api/exchange/websocket#binary-subscription-envelope). ```ts theme={null} type ExchangeWsL2Grouping = | { kind: "none" } | { kind: "nativeTick"; tickSize: bigint } | { kind: "significantFigures"; figures: number; mantissa: number | null; }; interface ExchangeWsCompactL2Level { price: bigint; totalBase: bigint; } interface ExchangeWsExtendedL2Level extends ExchangeWsCompactL2Level { activeBase: bigint; passiveBase: bigint; activeOrderCount: number; } interface ExchangeWsL2BookFrameBase { wireVersion: 1; feedEpoch: bigint; view: "finalized"; kind: "l2Book"; marketAddress: string; marketSeq: bigint; globalSeq: bigint; stateHead: { blockNumber: bigint; blockId: string }; durationMs: bigint; maxDepthPerSide: number; grouping: ExchangeWsL2Grouping; } type ExchangeWsL2BookFrame = | (ExchangeWsL2BookFrameBase & { levelFormat: "compact"; bids: ExchangeWsCompactL2Level[]; asks: ExchangeWsCompactL2Level[]; }) | (ExchangeWsL2BookFrameBase & { levelFormat: "extended"; bids: ExchangeWsExtendedL2Level[]; asks: ExchangeWsExtendedL2Level[]; }); ``` Bids are ordered high to low and asks low to high. Prices are native pp integers; base quantities remain native integers in market size precision. The decoder performs no scaling. Native tick grouping keeps `tickSize` in protocol ticks. # L2 delta stream Source: https://docs.kuru.io/api/exchange/websocket-reference/l2-delta Bootstrap, replay, and follow finalized order-book changes. ```text theme={null} l2Delta@f ``` This is a market-scoped, replayable stream. Its cursor is `(feedEpoch, marketSeq)`. Without `seq`, the stream sends a finalized L2 snapshot, replays retained deltas after that snapshot, and then joins live updates. With `seq`, replay begins strictly after the supplied cursor and no bootstrap snapshot is sent. ## Subscribe ```json theme={null} { "op": "sub", "id": 1, "t": "l2Delta@f", "m": "0x8121EE960066e4344A213F9aC7502395502aEe7a", "feedEpoch": 0, "seq": 1022 } ``` `m` is required. `seq` is optional and must be greater than zero when supplied. `feedEpoch` is required whenever `seq` is present. Coalescing durations and L2 formatting options are not accepted. ## Decoded event The shape below is the inner `message` returned by `decodeExchangeWsEnvelope` or `decodeExchangeWsMessage`. Every binary socket message also carries an outer `id: bigint`, matching your subscription ID. Use it to route snapshots, replay, and live updates. See [binary subscription envelopes](/api/exchange/websocket#binary-subscription-envelope). ```ts theme={null} interface ExchangeWsL2DeltaFrame { wireVersion: 1; feedEpoch: bigint; view: "finalized"; kind: "l2Delta"; marketAddress: string; marketSeq: bigint; previousMarketSeq: bigint | null; globalSeq: bigint; sourceBlock: { blockNumber: bigint; blockId: string }; updates: Array<{ side: "buy" | "sell"; price: bigint; totalBaseAfter: bigint; activeBaseAfter: bigint; passiveBaseAfter: bigint; activeOrderCountAfter: number; }>; } ``` `price` is an integer in market price precision (pp). The base fields use the market's native size precision; `totalBaseAfter === 0n` deletes the level. `previousMarketSeq` is the previous publication in this exact market, view, and topic stream. A zero wire value decodes to `null`. For a replay requested after `R`, the first frame is a valid sparse bridge when `marketSeq > R` and `previousMarketSeq` is `null` or at most `R`; every later frame must point exactly to the last accepted `marketSeq`. # Market trades stream Source: https://docs.kuru.io/api/exchange/websocket-reference/trades Replay and follow finalized taker-side fills for one market. ```text theme={null} trades@f ``` This is a market-scoped, replayable stream. Its cursor is `(feedEpoch, marketSeq)`. Without `seq`, it begins with live trades. With `seq`, it replays retained fills after that cursor and then joins live delivery. ## Subscribe ```json theme={null} { "op": "sub", "id": 2, "t": "trades@f", "m": "0x8121EE960066e4344A213F9aC7502395502aEe7a", "feedEpoch": 0, "seq": 1022 } ``` ## Decoded event The shape below is the inner `message` returned by `decodeExchangeWsEnvelope` or `decodeExchangeWsMessage`. Every binary socket message also carries an outer `id: bigint`, matching your subscription ID. Use it to route snapshots, replay, and live updates. See [binary subscription envelopes](/api/exchange/websocket#binary-subscription-envelope). ```ts theme={null} interface ExchangeWsMarketTradesFrame { wireVersion: 1; feedEpoch: bigint; view: "finalized"; kind: "trades"; marketAddress: string; marketSeq: bigint; previousMarketSeq: bigint | null; globalSeq: bigint; sourceBlock: { blockNumber: bigint; blockId: string }; trades: Array<{ tradeId: bigint; recordIndex: number; takerSide: "buy" | "sell"; price: bigint; baseFilled: bigint; blockTimestamp: bigint; }>; } ``` `takerSide` is the taker's side. `price` is in native market price precision (pp); `baseFilled` remains in the market's native size precision. The stable identity of a fill is `(marketAddress, tradeId, recordIndex)`. `previousMarketSeq` links to the previous publication in this exact market, view, and topic stream; it is `null` when the wire value is zero. For a replay requested after `R`, accept the first frame when `marketSeq > R` and its predecessor is `null` or at most `R`. Subsequent frames require exact equality between `previousMarketSeq` and the last accepted `marketSeq`. ## PnL versus market trade prices This market stream supplies execution prices and sizes for market data; it does not include user IDs, historical fee rates, or match boundaries. It cannot by itself reconstruct a user's fee-adjusted PnL. Use the [user trades accounting guide](/api/exchange/websocket-reference/user-trades#calculating-client-side-pnl) for position initialization, match-level fee rounding, and buy/sell accounting. That guide also explains when the user-scoped stream lacks enough information for exact maker accounting and when to use indexed PnL instead. ## Canonical event timestamp Each decoded trade row or order delta event includes `blockTimestamp: bigint` in Unix seconds. It is the source block's canonical header timestamp and is identical in live delivery and retained replay. It is not the publication time. Order snapshot rows are unchanged. See the [event timestamp changelog](/api/exchange/user-trades-changelog#kur-1719-canonical-event-timestamps). # User balances stream Source: https://docs.kuru.io/api/exchange/websocket-reference/user-balances Follow replayable balance updates with periodic full snapshots. ```text theme={null} userBalances@[@] ``` This user-scoped stream uses `(feedEpoch, globalUserSeq)`. Without `seq`, it sends a complete finalized balance snapshot, replays retained updates after that snapshot, and then joins live delivery. It also sends a complete snapshot every five seconds by default. Incremental updates default to `300` milliseconds. Market makers seeking earlier updates can use `@p` or `@v` in production, provided they track tentative state by block ID and reconcile `branchDropped`. Use `@f` when finalized state is required. Initial snapshots are finalized; periodic snapshots use the selected view. Durations are internally floored: `0`–`99` → immediate, `100`–`299` → 100 ms, `300`–`499` → 300 ms, and `500` or greater → 500 ms. The default is 300 ms. Use `@0` for delivery without intentional batching; `@1` has the same behavior. Periodic full snapshots remain enabled. See [delivery cadence and branch reconciliation](/api/exchange/websocket#subscribe) for the view semantics and [delivery cadence](/api/exchange/websocket#user-stream-delivery-cadence) for limits. ## Subscribe ```json theme={null} {"op":"sub","id":7,"t":"userBalances@f@300","u":2,"feedEpoch":0,"seq":2951} ``` ## Decoded event The shape below is the inner `message` returned by `decodeExchangeWsEnvelope` or `decodeExchangeWsMessage`. Every binary socket message also carries an outer `id: bigint`, matching your subscription ID. Use it to route snapshots, replay, and live updates. See [binary subscription envelopes](/api/exchange/websocket#binary-subscription-envelope). ```ts theme={null} interface ExchangeWsUserBalancesFrameBase { wireVersion: 1; feedEpoch: bigint; view: "finalized"; kind: "userBalances"; userId: bigint; globalUserSeq: bigint | null; globalSeq: bigint | null; previousGlobalUserSeq: bigint | null; balances: Array<{ tokenAddress: string; freeBalance: bigint; reservedBalance: bigint; }>; } type ExchangeWsUserBalancesFrame = | (ExchangeWsUserBalancesFrameBase & { snapshot: true; stateHead: { blockNumber: bigint; blockId: string } | null; }) | (ExchangeWsUserBalancesFrameBase & { snapshot: false; sourceBlock: { blockNumber: bigint; blockId: string }; }); ``` Balance values use each token's native decimal units. A snapshot has `stateHead`; an incremental frame has `sourceBlock`. Replace local balance state when `snapshot=true`. For an explicit replay cut `R`, accept the first publication when `globalUserSeq > R` and `previousGlobalUserSeq` is `null` or at most `R`. After that sparse bridge, every subsequent `previousGlobalUserSeq` must equal the last accepted `globalUserSeq` exactly. # User orders stream Source: https://docs.kuru.io/api/exchange/websocket-reference/user-orders Follow replayable order updates with periodic full snapshots. ```text theme={null} userOrders@[@] ``` This user-scoped stream uses `(feedEpoch, globalUserSeq)`. Without `seq`, it sends a complete finalized order snapshot, replays retained updates after that snapshot, and then joins live delivery. It also sends a complete snapshot every five seconds by default. Incremental updates default to `300` milliseconds. Market makers seeking earlier updates can use `@p` or `@v` in production, provided they track tentative state by block ID and reconcile `branchDropped`. Use `@f` when finalized state is required. Initial snapshots are finalized; periodic snapshots use the selected view. Durations are internally floored: `0`–`99` → immediate, `100`–`299` → 100 ms, `300`–`499` → 300 ms, and `500` or greater → 500 ms. The default is 300 ms. Use `@0` for delivery without intentional batching; `@1` has the same behavior. Periodic full snapshots remain enabled. See [delivery cadence and branch reconciliation](/api/exchange/websocket#subscribe) for the view semantics and [delivery cadence](/api/exchange/websocket#user-stream-delivery-cadence) for limits. ## Subscribe ### Empty snapshots and nullable sequences An authoritative snapshot with `orders: []` means the user has no open orders in the selected view. Apply it by clearing the local open-order list, even if `globalSeq` or `globalUserSeq` is `null`. Order count and cursor availability are independent: * An empty snapshot can have non-null sequences after orders are cancelled or fully filled. Keep a valid `globalUserSeq`; do not discard it because the list is empty. * Null sequences indicate an unavailable or zero baseline cursor, not proof that the user has never traded. They can occur for an untouched user, before a snapshot baseline exists, or after checkpoint restoration into a new feed epoch, including for users with restored open orders. * The binary format encodes missing sequences as zero; the SDK maps zero to `null`. `globalSeq` and `globalUserSeq` need not both be null. Use `(feedEpoch, globalUserSeq)` for user-stream replay, never `globalSeq`. If `globalUserSeq` is null, do not substitute `globalSeq` or infer a cursor from the order list. Continue the current subscription's bootstrap/live flow; on a fresh connection, omit `seq` to request a new authoritative snapshot. Follow the documented predecessor checks once sequenced updates arrive. ```json theme={null} {"op":"sub","id":6,"t":"userOrders@f@300","u":2,"feedEpoch":0,"seq":2951} ``` ## Decoded event The shape below is the inner `message` returned by `decodeExchangeWsEnvelope` or `decodeExchangeWsMessage`. Every binary socket message also carries an outer `id: bigint`, matching your subscription ID. Use it to route snapshots, replay, and live updates. See [binary subscription envelopes](/api/exchange/websocket#binary-subscription-envelope). ```ts theme={null} interface ExchangeWsBlockContext { blockNumber: bigint; blockId: string; } interface ExchangeWsUserOrder { createdAt: bigint; marketAddress: string; orderId: bigint; slotIdx: number; side: "buy" | "sell"; price: bigint; remainingBase: bigint; minSizeAfterBlock: bigint | null; clientOrderId: string | null; } interface ExchangeWsUserOrderSource { txHash: string; txIdx: number; logIdx: number; recordIdx: number; } interface ExchangeWsAction { accountId: bigint; executor: string; clientOrderId: string | null; } interface ExchangeWsOperation { outcome: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10; operationIndex: number; } interface ExchangeWsTradeOperation extends ExchangeWsOperation { replacementSlot: number; } interface ExchangeWsUserTrade { action: ExchangeWsAction; operation: ExchangeWsTradeOperation | null; marketAddress: string; tradeId: bigint; recordIndex: number; users: [bigint, bigint]; // [takerId, makerId]; passive maker is 0n takerSide: "buy" | "sell"; price: bigint; baseFilled: bigint; blockTimestamp: bigint; liquidity: | { kind: "activeFifo"; slotIndex: number; orderId: bigint; makerSide: "buy" | "sell"; remainingBaseAfter: bigint; makerFeePps: number; } | { kind: "passiveBand"; lowPrice: bigint; passiveSideRemainingAfter: bigint; }; txHash: string; txIdx: number; logIdx: number; effectiveTakerFeePps: number; builderFeePps: number; matchEnd: boolean; } type ExchangeWsUserOrderEvent = | (Omit & { kind: "created"; source: ExchangeWsUserOrderSource; blockTimestamp: bigint; makerId: bigint; action: ExchangeWsAction; operation: ExchangeWsOperation | null; }) | (ExchangeWsUserTrade & { kind: "trade"; source: ExchangeWsUserOrderSource; }) | { kind: "cancelled"; action: ExchangeWsAction; operation: ExchangeWsOperation | null; source: ExchangeWsUserOrderSource; blockTimestamp: bigint; makerId: bigint; marketAddress: string; orderId: bigint; slotIdx: number; } | { kind: "rab-reduced"; source: ExchangeWsUserOrderSource; blockTimestamp: bigint; makerId: bigint; marketAddress: string; orderId: bigint; slotIdx: number; updatedSize: bigint; } | { kind: "operation-sentinel"; source: ExchangeWsUserOrderSource; blockTimestamp: bigint; marketAddress: string; action: ExchangeWsAction; operation: ExchangeWsOperation; slotIdx: number; }; interface ExchangeWsUserOrdersFrameBase { wireVersion: 1; feedEpoch: bigint; view: "finalized"; kind: "userOrders"; userId: bigint; globalUserSeq: bigint | null; globalSeq: bigint | null; previousGlobalUserSeq: bigint | null; } interface ExchangeWsUserOrdersSnapshotFrame extends ExchangeWsUserOrdersFrameBase { snapshot: true; stateHead: ExchangeWsBlockContext | null; orders: ExchangeWsUserOrder[]; } interface ExchangeWsUserOrdersDeltaFrame extends ExchangeWsUserOrdersFrameBase { snapshot: false; sourceBlock: ExchangeWsBlockContext; events: ExchangeWsUserOrderEvent[]; } type ExchangeWsUserOrdersFrame = | ExchangeWsUserOrdersSnapshotFrame | ExchangeWsUserOrdersDeltaFrame; ``` The binary decoder maps event codes `1` through `5` to `created`, `trade`, `cancelled`, `rab-reduced`, and `operation-sentinel`. Every delta event carries its exact transaction source tuple: ```ts theme={null} const frame = decodeUserOrdersFrame(binaryPayload); if (frame.snapshot) { replaceOpenOrders(frame.orders); } else { for (const event of frame.events) { applyUserOrderEvent(event); } } ``` Replace all local open-order state when `snapshot=true`. For a delta, validate `previousGlobalUserSeq`, then apply `events` in array order: For an explicit replay cut `R`, the first publication is a valid sparse bridge when `globalUserSeq > R` and `previousGlobalUserSeq` is `null` or at most `R`. After accepting it, require every subsequent `previousGlobalUserSeq` to equal the last accepted `globalUserSeq` exactly. * `created` carries the complete new open order. * `trade` carries the complete [user trade payload](/api/exchange/websocket-reference/user-trades). For `activeFifo`, update the resting maker's order using `liquidity.orderId` and `liquidity.slotIndex`, setting its remaining size to `liquidity.remainingBaseAfter`; remove it when zero. Only mutate the local order when `users[1]` matches the subscribed user. A taker's trade notification does not identify a taker resting order. Passive fills have no active order identity and must not mutate the open-order list. * `cancelled` removes the order. * `rab-reduced` sets the remaining size to `updatedSize`; remove it when that value is zero. * `operation-sentinel` reports an operation outcome without adding or removing an open order. Real order events reach the affected maker. Tagged outcomes also reach the action account, with overlapping recipients delivered once. For `created` and `cancelled`, only mutate the subscribed user's open orders when `makerId` matches that user. Tagged passive fills reach the taker, and sentinels reach the action account. Snapshots still contain only real open orders. Key each live slot by `(marketAddress, slotIdx)`. Before updating or removing a slot, verify that its current `orderId` matches the event. This prevents a late event from mutating a newer order that reused the physical slot. Use the frame's `globalUserSeq` for stream continuity; the event's source tuple identifies the causal onchain or generated record. ## Action and operation outcomes `action` identifies the action account, executor address, and optional client order ID. It is present on `created`, `trade`, `cancelled`, and `operation-sentinel`, but not `rab-reduced`. The action account is not necessarily the affected maker. `operation` is nullable on created, trade, and cancelled events. When present, it supplies `operationIndex` and an outcome code; trades additionally include `replacementSlot`. This metadata describes the operation outcome, not another fill or open order. | Outcome | Meaning | | - | - | | 1 | FILLED | | 2 | RESTED | | 3 | COMPLETED_NO_REST | | 4 | IOC_PARTIAL | | 5 | IOC_UNFILLED | | 6 | POST_ONLY_NOT_PLACED | | 7 | CANCELLED | | 8 | PROTOCOL_CANCELLED | | 9 | CANCEL_NOOP | | 10 | DUST_REMAINDER_DISCARDED | Sentinels always have operation metadata, restricted to outcomes `3`, `5`, `6`, and `9`. Use them to resolve pending actions, not to create synthetic orders. Wire version remains `1`; use the matching updated SDK decoder for these event layouts. Snapshot order rows are unchanged. Prices remain in market price precision and sizes in market size precision. ## Canonical event timestamp Each decoded trade row or order delta event includes `blockTimestamp: bigint` in Unix seconds. It is the source block's canonical header timestamp and is identical in live delivery and retained replay. It is not the publication time. Snapshot orders expose `createdAt: bigint` in Unix seconds: their original creation-block time, retained through updates and checkpoint restore. Each snapshot row is now 104 bytes, with `createdAt` appended at offset 96. On created deltas, initialize `createdAt` from `blockTimestamp`; later events do not change it. See the [event timestamp changelog](/api/exchange/user-trades-changelog#kur-1719-canonical-event-timestamps). # User trades stream Source: https://docs.kuru.io/api/exchange/websocket-reference/user-trades Replay and follow a user's taker- and active-maker-side executions. ```text theme={null} userTrades@ ``` This user-scoped stream uses `(feedEpoch, globalUserSeq)` and has no snapshot. Without `seq`, it starts at the oldest retained trade involving the user. With `seq`, replay starts strictly after that cursor before joining live delivery. Market makers can select `@p` or `@v` for earlier, tentative executions, with [branch reconciliation](/api/exchange/websocket#subscribe). Use `@f` for finalized executions. This stream has no coalescing parameter in any view. ## Subscribe ```json theme={null} {"op":"sub","id":8,"t":"userTrades@f","u":2,"feedEpoch":0,"seq":2951} ``` ## Decoded event The shape below is the inner `message` returned by `decodeExchangeWsEnvelope` or `decodeExchangeWsMessage`. Every binary socket message also carries an outer `id: bigint`, matching your subscription ID. Use it to route snapshots, replay, and live updates. See [binary subscription envelopes](/api/exchange/websocket#binary-subscription-envelope). ```ts theme={null} type ExchangeWsUserTradeLiquidity = | { kind: "activeFifo"; slotIndex: number; orderId: bigint; makerSide: "buy" | "sell"; remainingBaseAfter: bigint; makerFeePps: number; } | { kind: "passiveBand"; lowPrice: bigint; passiveSideRemainingAfter: bigint; }; interface ExchangeWsUserTradesFrame { wireVersion: 1; feedEpoch: bigint; view: "finalized"; kind: "userTrades"; userId: bigint; globalUserSeq: bigint | null; globalSeq: bigint | null; previousGlobalUserSeq: bigint | null; sourceBlock: { blockNumber: bigint; blockId: string }; trades: Array<{ marketAddress: string; tradeId: bigint; recordIndex: number; users: [bigint, bigint]; takerSide: "buy" | "sell"; price: bigint; baseFilled: bigint; blockTimestamp: bigint; liquidity: ExchangeWsUserTradeLiquidity; txHash: string; txIdx: number; logIdx: number; effectiveTakerFeePps: number; builderFeePps: number; matchEnd: boolean; action: { accountId: bigint; executor: string; clientOrderId: string | null }; operation: { outcome: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10; operationIndex: number; replacementSlot: number } | null; }>; } ``` `users` is ordered `[takerId, makerId]`. An active FIFO fill carries the resting maker's user ID and is delivered to both nonzero users. A passive fill has no individual maker and uses `0n` as the maker ID. Active fills have distinct taker and maker IDs; contracts prevent self fills. `takerSide` always describes the taker side, so the active maker's side is the opposite value. The stable identity of a fill is `(marketAddress, tradeId, recordIndex)`. For an explicit replay cut `R`, accept the first publication when `globalUserSeq > R` and `previousGlobalUserSeq` is `null` or at most `R`. After that sparse bridge, every subsequent `previousGlobalUserSeq` must equal the last accepted `globalUserSeq` exactly. ## Fees, source identity, and match boundaries Fee rates are historical event values in PPS (denominator `10_000_000`). `liquidity.makerFeePps` applies only to active makers; passive liquidity omits that field. Prices and sizes retain market price/size precision. The client calculates fees and positions; the Gateway exposes the inputs only. `sourceBlock`, `txHash`, `txIdx`, `logIdx`, and `recordIndex` identify the source record. A packed log becomes separate normalized records: the current projector emits one trade per publication, rather than packing the complete match into one `trades` array. Iterate rows in delivery order. `matchEnd: true` closes a match. A match can span multiple packed logs with intervening book/hook records; one log can also contain multiple matches. Takers receive all their active and passive fills. A maker receives only its own fills and may never receive the match's terminal record. Maker buys use the contract's per-record two-stage quote floor. For active maker sells, exact quote credit is a cumulative active-ask ceiling delta and can depend on preceding fills belonging to other makers. A maker-only stream therefore cannot always reconstruct exact quote credit or fee-adjusted positions from its own rows. Use complete ordered match data or authoritative indexed accounting for those amounts. For example, a taker 101 matching maker 202, passive liquidity, then maker 303 receives three publications. Their rows have `users` values `[101n, 202n]`, `[101n, 0n]`, and `[101n, 303n]`, with `matchEnd` values `false`, `false`, and `true`. Maker 202 receives only the first row; maker 303 receives only the third. Persist unfinished match state together with the replay cursor. If a reconnect loses that state, replay from before the unfinished match; handle a history gap by bootstrapping again. The existing epoch and predecessor rules still apply. See the [response changelog](/api/exchange/user-trades-changelog) for every added field and its binary offset. ## Canonical event timestamp Each decoded trade row or order delta event includes `blockTimestamp: bigint` in Unix seconds. It is the source block's canonical header timestamp and is identical in live delivery and retained replay. It is not the publication time. Open-order snapshot rows use their retained creation timestamp, `createdAt`. See the [event timestamp changelog](/api/exchange/user-trades-changelog#kur-1719-canonical-event-timestamps). ## Contract quote arithmetic For taker sells, quote uses two floors: `floor(floor(price * size / sp) * quoteScale / pp)`. For passive taker buys, both stages round up. For active taker buys, maintain `W = sum(price * size)` across only active fills in the match, and charge `ceil(W_after * quoteScale / (sp * pp)) - ceil(W_before * quoteScale / (sp * pp))`. Passive fills do not change `W`; reset it at `matchEnd`. Buy builder fees are `ceil(sum(size) * baseSizeMultiplier * builderFeePps / 10_000_000)` in raw base atoms. Keep raw-atom precision when updating positions; do not first round the fee to size precision. The Gateway exposes inputs and performs none of this accounting. `operation` is optional outcome metadata, not another fill or an instruction to mutate an order twice. ## Calculating client-side PnL The following is the Indexer's weighted-average, long-inventory accounting model. PnL is per user and market, denominated in that market's **quote token**; it is not automatically a USDC value. Use arbitrary-precision integer arithmetic (for example, JavaScript `bigint`), never floating-point numbers for accounting. ### 1. Start from a position baseline Read the [user trades API](/api/data-source/reference/user-trades), including `data.positions`, `feedEpoch`, and `globalUserSeq`. Subscribe strictly after that cursor using the replay rules above. Do not reapply the historical trades in the API response to its already-materialized position baseline. For each market, keep: * `B`: open inventory in raw base-token atoms. * `C`: open cost in raw quote-token atoms. * `R`: cumulative realized PnL in raw quote-token atoms (signed). * Market `pp` (price precision), `sp` (size precision), and both token decimals. Let `baseScale = 10^baseDecimals`, `quoteScale = 10^quoteDecimals`, and `baseSizeMultiplier = baseScale / sp`. API `openSize` is in size precision, so convert its exact decimal string to raw atoms by multiplying by `baseSizeMultiplier`; do not truncate fractional size units. API `openCost` already uses raw quote atoms. Convert x18 realized PnL using the quote token's decimals. Do not rebuild cost from a rounded display average entry price. `data.positions` supplies size and cost, **not cumulative realized PnL**. To display lifetime `R`, retain a verified realized-PnL baseline or reconstruct it from complete indexed history at the same cutoff; one page of trade history is not sufficient. Alternatively initialize `R = 0` and label the result as realized PnL **since the baseline**, not lifetime PnL. For quote tokens with more than 18 decimals, an x18 value can lose raw-atom precision; it cannot substitute for exact raw state when reproducing integer accounting. The baseline and replay cursor must describe the same indexed state. Preserve the epoch, accepted cursor, position state, and any unfinished match together. After an epoch change or unavailable replay history, reload the baseline. ### 2. Calculate each fill's quote and the complete match's fees Use the contract quote arithmetic above to calculate `q[i]`, the raw quote amount of fill `i`, and `b[i] = baseFilled[i] * baseSizeMultiplier`. Preserve delivery order and carry the active-ask accumulator across logs until `matchEnd`; neither a WebSocket frame nor a log boundary closes a match. With `D = 10_000_000` (PPS, parts per scale): ```text theme={null} Q = sum(q[i]) S = sum(b[i]) takerProtocolFee = ceil(Q * effectiveTakerFeePps / D) taker buy: builderBaseFee = ceil(S * builderFeePps / D) taker sell: builderQuoteFee = ceil(Q * builderFeePps / D) active maker fee for fill i = floor(q[i] * makerFeePps[i] / D) ``` Maker protocol fees are per-fill quote fees. Taker protocol fees and builder fees are computed once per complete match, not independently rounded per fill. Use the historical rates carried by the event, not current fee-tier defaults. Passive fills have no individual maker position to update. `builderFeePps` is the builder fee **rate**, not an amount. It is separate from `effectiveTakerFeePps`: apply both fees to the taker, but do not charge the builder fee to the active maker. A zero builder rate produces a zero builder fee. The buy-side builder fee is in raw **base** atoms; the sell-side builder fee is in raw **quote** atoms. Do not add amounts in these different units. To reproduce the Indexer's individual trade rows, allocate the taker protocol fee and sell-side builder fee using `q[i]` as weights; allocate the buy-side builder fee using `b[i]` as weights. For each nonterminal fill assign `floor(totalFee * weight[i] / sum(weights))`; the final fill receives the exact remaining fee. If both the fee and total weight are zero, all allocations are zero. Apply the resulting legs in order, then publish the taker's position at `matchEnd`. This preserves both fee totals and per-fill cost-basis rounding. ### 3. Apply fee-adjusted buys and sells For a **buy**, let `b` be the acquired raw base amount and `q` its raw quote amount. A taker receives `b - allocatedBuilderBaseFee`; an active maker receives `b`. Add the corresponding quote protocol fee to cost: ```text theme={null} B' = B + netBaseReceived C' = C + q + protocolQuoteFee R' = R ``` Buy fees are incorporated into inventory/cost, not immediately booked as realized PnL. In particular, a base-token builder fee reduces inventory while the quote cost remains invested. For example, a single-fill taker buy of 2 tokens for 200 USDC with `effectiveTakerFeePps = 2_000` and `builderFeePps = 10_000` incurs a 0.04 USDC protocol fee and a 0.002-token builder fee (assuming the token decimals can represent these amounts exactly). From an empty position, store 1.998 tokens of inventory and 200.04 USDC of cost. Average entry becomes `200.04 / 1.998` USDC per token, rather than `200.04 / 2`. At a 100 USDC mark, unrealized PnL is `1.998 * 100 - 200.04 = -0.24 USDC`; realized PnL is still zero. Do not also subtract the base builder fee's quote value from realized PnL: its effect is already reflected in the reduced inventory. For a **sell**, let `b` be the sold raw base amount and `f` the quote fees: maker protocol fee for a maker, or allocated taker protocol plus builder quote fees for a taker. Using the position **before** this fill: ```text theme={null} m = min(b, B) releasedCost = C if m = B floor(C * m / B) otherwise matchedGrossQuote = floor(q * m / b) matchedNetQuote = floor((q - f) * m / b) grossRealizedPnl = matchedGrossQuote - releasedCost realizedPnl = matchedNetQuote - releasedCost B' = B - m C' = C - releasedCost R' = R + realizedPnl ``` When `B = 0`, released cost and both matched quote amounts are zero. When the position closes, set `B' = C' = 0`. A sale beyond tracked inventory does not create a short position: only the matched portion contributes realized PnL. Do not subtract sell fees a second time after using `matchedNetQuote`. For a single-fill taker sell of 1 token for 110 USDC, the same rates give a 0.022 USDC protocol fee and a 0.11 USDC builder fee. Net proceeds are `110 - 0.022 - 0.11 = 109.868 USDC`. If the released cost is 100 USDC, realized PnL is 9.868 USDC. The Indexer's reported net PnL already includes these fees; clients displaying that value must not deduct them again. ### 4. Derive average entry and marked PnL ```text theme={null} averageEntryPriceX18 = floor(C * baseScale * 10^18 / (B * quoteScale)) ``` Use zero when `B = 0`. At a mark price `markPriceX18` in quote tokens per base token, the unrealized value is the marked open inventory minus open cost: ```text theme={null} markedInventoryX18 = floor(B * markPriceX18 / baseScale) openCostX18 = floor(C * 10^18 / quoteScale) unrealizedPnlX18 = markedInventoryX18 - openCostX18 totalPnlX18 = realizedPnlX18 + unrealizedPnlX18 ``` Convert signed realized PnL to x18 with integer truncation toward zero, matching the Indexer. These are quote-token values; a non-USDC quote needs its own USDC conversion before account-wide aggregation. Mark-price changes affect unrealized PnL even when this user has no new trades. For example, with no builder fee, buying 2 tokens for 200 USDC plus a 0.04 USDC protocol fee creates 2 tokens of inventory at 200.04 USDC cost. Selling 1 token for 110 USDC with a 0.022 USDC fee releases 100.02 USDC cost and realizes `110 - 0.022 - 100.02 = 9.958 USDC`. The remaining cost is 100.02 USDC. At a 110 USDC mark, unrealized PnL is 9.98 USDC and total PnL is 19.938 USDC. ### Transfers are also position changes Trades alone are insufficient to maintain the Indexer's position state. Deposits, withdrawals, and internal account transfers also adjust inventory and basis in the token's designated first market, without changing realized PnL. An incoming transfer uses the recipient's existing average cost; when there is no open position it uses the latest preceding trade price, or zero if no price exists. An outgoing transfer removes proportional cost, resetting inventory/cost to zero if it exhausts or exceeds the position. Internal transfers apply each account's own basis; they do not transfer the sender's cost basis to the recipient. Balance updates do not identify these accounting operations. Unless your client also consumes complete, ordered transfer history, refresh authoritative indexed positions rather than treating a balance delta as another trade. # API Overview Source: https://docs.kuru.io/api/introduction Reference for Kuru Exchange, Data Source, and Relay APIs. The REST playground defaults to **Monad mainnet**. Select testnet in its server dropdown before testing there. Use the corresponding [mainnet deployment](/deployments/mainnet) or [testnet deployment](/deployments/testnet) addresses, chain ID, wallet signatures, and JWT. Changing the server does not transform values already entered into a request. Response examples illustrate the schema, not live state; some recorded responses are labelled testnet snapshots. Use Relay to submit signed actions, Data Source for catalogs and finalized history, and Exchange Gateway for current projections and live updates. * [Submitting trades](/sdk/relay-onboarding): account permission, authentication, signing, and Relay submission. * [Reading market data](/api/market-data): markets, charts, trade history, and live books. * [Following account activity](/api/account-activity): balances, orders, and fills. ## Service endpoints Kuru exposes these API surfaces on both networks: | Surface | Mainnet | Testnet | | - | - | - | | Relay REST | `https://relay.mainnet.kuru.io` | `https://relay.testnet.kuru.io` | | Relay WebSocket | `wss://relay.mainnet.kuru.io/relay/ws` | `wss://relay.testnet.kuru.io/relay/ws` | | Data Source REST | `https://api.mainnet.kuru.io` | `https://api.testnet.kuru.io` | | Exchange Gateway REST | `https://gateway.mainnet.kuru.io` | `https://gateway.testnet.kuru.io` | | Exchange Gateway WebSocket | `wss://gateway.mainnet.kuru.io/ws` | `wss://gateway.testnet.kuru.io/ws` | The Data Source API returns finalized materialized reads together with the `feedEpoch` and market or user sequence needed to continue on an Exchange Gateway WebSocket stream. Exchange Gateway REST exposes the current retained projection views directly. Relay APIs separately handle authenticated submission and delivery of signed trading-wallet actions. For direct onchain integration, use the [TypeScript SDK](/sdk/overview) or [Contract Reference](/contracts/overview). For SDK-backed sponsored submissions, use [Trading-wallet signing](/sdk/trading-wallet) and [Relay](/sdk/relay). # Reading Market Data Source: https://docs.kuru.io/api/market-data Load markets, charts, trades, and a live order book. Use Data Source REST for catalogs and historical data. Use Exchange Gateway for the current book and live streams. [API Overview](/api/introduction) lists the service endpoints. ## Markets and charts Load the [market catalog](/api/data-source/reference/markets), then the selected [market's metadata](/api/data-source/reference/market). Keep its precision and token-decimal settings with your application state. Use [candles](/api/data-source/reference/candles) for historical OHLCV. Use [market trades](/api/data-source/reference/market-trades) for individual executions. Catalog responses do not provide a WebSocket replay cut. ### Mainnet market examples These active market addresses were checked against the [mainnet market catalog](https://api.mainnet.kuru.io/api/v1/markets?status=active\&limit=100) on 17 October 2026. The catalog is authoritative for current availability; do not reuse these addresses on testnet. | Symbol | Market address | | - | - | | WETHUSDC | `0x8121ee960066e4344a213f9ac7502395502aee7a` | | XAUT0USDC | `0x9d29630ae2dcf02cb0cf05e17f45d95f01f15798` | | CBBTCUSDC | `0xae8e0cf4a9ff696b5f6ec0b1339200eb4c09e422` | | SPYXUSDC | `0xbb180c8b6d3ee0b4316b224c53b80dc4e354d24f` | | MONUSDC | `0xc9de998e272d59a19cea3783c8dd44f87a86405d` | | EWYXUSDC | `0xed3727e833200c849fbd18e15ed0d091c9b0f3af` | | QQQXUSDC | `0xedf008258139ee23cf2bdb9c360f69131dc72708` | | NVDAXUSDC | `0xf3fb2ec6ffb2a24506769bfaa3ad9b1eeb7d41eb` | | TSLAXUSDC | `0xf884c7631a7150f28c139a3a9f8b669258b5b285` | ## Order book Subscribe to finalized `l2Delta@f` for the chosen market without a replay cursor. The Gateway first supplies an authoritative L2 snapshot, then deltas. Install the snapshot before applying updates. Do not bootstrap this stream by guessing a cursor from an unrelated REST response. The [L2 delta reference](/api/exchange/websocket-reference/l2-delta) owns its exact snapshot and update rules. For a simpler display that replaces the whole book periodically, use [L2 book snapshots](/api/exchange/websocket-reference/l2-book). ## Trade history into live trades Load market trades from Data Source. When both `feedEpoch` and `marketSeq` are present, install the REST result and request replay after that cut on the matching finalized market stream. Keep the epoch with the sequence. A null cursor cannot serve as a replay bootstrap. Follow the endpoint's semantics rather than treating a null value as zero. ## Reconnects and gaps Persist a cursor only after applying its data. Validate predecessor links, not arithmetic sequence adjacency. On `resync`, discard the affected derived state and bootstrap as instructed. On `resub`, recreate the removed subscription using the last durably applied cursor where supported. See [WebSocket API](/api/exchange/websocket) for control messages and binary envelopes. Decoder package availability is documented in [SDK Installation](/sdk/installation). # Relay errors and outcomes Source: https://docs.kuru.io/api/relay/errors Stable error codes, retry guidance, and transaction outcomes for Relay clients. Relay validates policy, availability, and signatures before scheduling an asynchronous broadcast. Both REST and WebSocket submission methods can fail immediately. A `BROADCAST` response means Relay accepted and scheduled the signed transaction; `eth_sendRawTransaction` may not have returned yet. It does **not** prove provider acceptance, inclusion, or execution. REST does not deliver later confirmation, replacement, or revert information, so REST clients must independently query chain receipts and reverts. A successful WebSocket submission is automatically tracked for terminal-outcome delivery on the submitting connection; it does not need a separate `transaction.subscribe` request. Branch on the stable `code`, HTTP status, and `retryable` field. Do not branch on message text. Messages are diagnostic and may change. ## Immediate response states | State | Meaning | | - | - | | `BROADCAST` | Relay accepted and scheduled the candidate for asynchronous RPC broadcast; provider acceptance is not yet proved. | | `REJECTED` | Relay rejected the request or the provider definitively rejected the candidate. | | `UNKNOWN` | Relay cannot determine whether the provider accepted the candidate (`BROADCAST_RESULT_UNKNOWN`). Reconcile the supplied candidate identity before deciding what to do. | | `SUBSCRIBED` | A WebSocket `transaction.subscribe` request found a pending transaction and is waiting for its outcome. | ## Public error codes Retry only when `retryable` is `true`, using bounded backoff and any supplied `retryAfterMs`. A `RATE_LIMITED` response is expected quota enforcement, not an outage. For a rejected WebSocket submission, retry with a **new envelope `id`** after the delay: reusing the old `id` may replay its cached rejection. This does not change the signed intent's nonce or `clientOrderId`. Reconcile `BROADCAST` and uncertain submissions before creating or retrying a logical action. See [Relay Rate Limits and Migration](/api/relay/rate-limits). | Code | HTTP | Retryable | Meaning | Recommended client action | Transport / operation | | - | -: | :-: | - | - | - | | `MALFORMED_REQUEST` | 400 | No | Invalid JSON or request shape | Fix the request | REST/WS, all methods | | `UNKNOWN_METHOD` | 400 | No | Method is not supported | Use a documented method | REST/WS | | `UNSUPPORTED_CHAIN` | 400 | No | Chain is not configured | Select a supported chain | Submission/auth | | `UNSUPPORTED_WALLET` | 400 | No | Wallet type is unsupported | Use a supported wallet | Submission/auth | | `UNSUPPORTED_MARKET` | 400 | No | Market is unsupported | Use a supported market | Trading methods | | `DEADLINE_EXPIRED` | 400 | No | Signed deadline has passed | Sign a fresh request | Submission | | `DEADLINE_TOO_FAR` | 400 | No | Deadline exceeds the allowed horizon | Use a nearer deadline | Submission | | `NONCE_OUTSIDE_WINDOW` | 400 | No | Nonce is outside the accepted window | Reconcile nonce and sign again | Submission | | `NON_INCREASING_SESSION_NONCE` | 400 | No | WS wallet-intent session nonces must strictly increase | Reconcile and send a larger nonce | WebSocket submission | | `INVALID_SIGNATURE` | 400 | No | Signature does not verify | Sign the exact canonical payload | Submission | | `INVALID_BINDING` | 400 | No | Request binding does not match | Correct wallet/order/transaction binding | Submission; outcome subscription | | `INVALID_TRIGGER_CONDITION` | 400 | No | Trigger condition is invalid | Correct trigger fields | Trigger methods | | `INVALID_7702_AUTHORIZATION` | 400 | No | EIP-7702 authorization is malformed | Correct authorization fields | Authorization-enabled methods | | `7702_CHAIN_MISMATCH` | 400 | No | Authorization chain differs from request chain | Sign for the requested chain | Authorization-enabled methods | | `7702_DELEGATE_MISMATCH` | 400 | No | Delegate differs from the configured delegate | Use the configured delegate | Authorization-enabled methods | | `7702_AUTHORITY_MISMATCH` | 400 | No | Authority differs from the wallet | Use the wallet as authority | Authorization-enabled methods | | `7702_NONCE_MISMATCH` | 400 | No | Authorization nonce is stale or incorrect | Re-read and sign current nonce | Authorization-enabled methods | | `7702_UNSUPPORTED_CODE_STATE` | 400 | No | Account code state cannot use EIP-7702 path | Use the supported account state | Authorization-enabled methods | | `INVALID_ACCOUNT_AUTHORIZATION` | 400 | No | Account signer authorization is invalid | Correct signer authorization | `account_core.authorize_account_signer_by_sig` | | `ACCOUNT_AUTH_NONCE_MISMATCH` | 400 | No | Account authorization nonce is stale | Re-read nonce and sign again | Account authorization | | `ACCOUNT_PERMISSION_DECLINED` | 400 | No | Account permission request was declined | Change authorization request | Account authorization | | `SIGNER_POLICY_DECLINED` | 400 | No | Signer rejected the policy | Changing transport or retrying unchanged will not help | Submission | | `OPERATIONAL_SIMULATION_REVERTED` | 400 | No | An opt-in operational method explicitly reverted in bounded simulation; no transaction was signed or broadcast | Refresh state and correct the request | Operational methods | | `AUTHENTICATION_FAILED` | 401 | No | JWT is missing, invalid, expired, or wallet-bound incorrectly | Obtain a new wallet-bound JWT | REST/WS protected access | | `POLICY_DECLINED` | 403 | No | Relay policy rejected the request, including an operational buffered gas estimate above its method cap | Change the request or policy inputs | Submission | | `WALLET_NOT_ALLOWLISTED` | 403 | No | Wallet is not allowlisted | Use an allowlisted wallet | REST/WS | | `WALLET_NOT_DELEGATED` | 403 | No | Wallet lacks required delegation | Install or use delegation | Submission | | `TRIGGER_REGISTRATION_DECLINED` | 403 | No | Trigger registration policy rejected | Change trigger or policy inputs | Trigger registration | | `TRANSACTION_OUTCOME_NOT_FOUND` | 404 | No | Requested outcome identity is unknown | Verify `requestId`/`txHash` | WS `transaction.subscribe` | | `METHOD_NOT_ALLOWED` | 405 | No | HTTP method is not accepted | Use the documented method | REST | | `TRIGGER_REGISTRATION_CONFLICT` | 409 | No | Trigger conflicts with an existing registration | Reconcile existing trigger | Trigger registration | | `TRANSACTION_OUTCOME_ALREADY_SUBSCRIBED` | 409 | No | This WS session already subscribed to the transaction | Reuse the existing subscription | WS `transaction.subscribe` | | `TRANSACTION_OUTCOME_EXPIRED` | 410 | No | The terminal outcome was evicted from the bounded signer store | Query the chain directly | WS `transaction.subscribe` | | `REQUEST_TOO_LARGE` | 413 | No | Request exceeds configured limits | Reduce request size | REST/WS | | `UNSUPPORTED_MEDIA_TYPE` | 415 | No | Content type is unsupported | Send JSON with the documented type | REST | | `RATE_LIMITED` | 429 | Yes | A configured rate limit was exhausted; WS rejection does not itself close the connection | Honor `retryAfterMs`, use bounded backoff with jitter, and use a new WS envelope `id` for a retry | REST/WS | | `BROADCAST_REJECTED` | 502 | No | Provider definitively rejected the candidate | Surface rejection; reconcile candidate before any new logical transaction | Submission | | `AUTHENTICATION_UNAVAILABLE` | 503 | Yes | Authentication service unavailable | Bounded backoff | Auth/protected access | | `WALLET_REGISTRY_UNAVAILABLE` | 503 | Yes | Wallet registry unavailable | Bounded backoff | REST/WS | | `STATE_UNAVAILABLE` | 503 | Yes | Required exchange-state snapshot is missing, stale, incompatible, or temporarily unavailable | Bounded backoff, then reconcile state | Submission | | `GAS_POLICY_UNAVAILABLE` | 503 | Yes | Gas policy or bounded operational estimation unavailable | Bounded backoff; do not treat a generic estimator failure as a contract revert | Submission | | `ACCESS_LIST_POLICY_UNAVAILABLE` | 503 | Yes | Access-list policy unavailable | Bounded backoff | Submission | | `SIGNER_QUEUE_FULL` | 503 | Yes | Signer admission capacity is exhausted | Back off; do not duplicate the logical request | Submission | | `SIGNER_LANE_UNAVAILABLE` | 503 | Yes | Pinned sponsor lane is unsafe (readiness, nonce reconciliation, RPC health, or contract verification) | Back off until lane health returns | Submission | | `TRIGGER_REGISTRATION_UNAVAILABLE` | 503 | Yes | Trigger registration service unavailable | Bounded backoff | Trigger registration | | `ACCOUNT_AUTHORIZATION_UNAVAILABLE` | 503 | Yes | Account authorization service unavailable | Bounded backoff | Account authorization | | `7702_PREFLIGHT_UNAVAILABLE` | 503 | Yes | EIP-7702 preflight unavailable | Bounded backoff | Authorization-enabled methods | | `BROADCAST_RESULT_UNKNOWN` | 503 | No | Relay cannot determine provider acceptance | Reconcile candidate identity; do not blindly create a new logical transaction | Submission | | `INTERNAL_DEADLINE_EXCEEDED` | 504 | Yes | Relay deadline elapsed before a result | Bounded backoff only when safe; reconcile first | REST/WS | | `INTERNAL_ERROR` | 500 | No | Unexpected Relay failure | Surface incident; retry only after reconciliation | REST/WS | `STATE_UNAVAILABLE` is about the state snapshot needed to plan safely. `SIGNER_QUEUE_FULL` is capacity exhaustion; `SIGNER_LANE_UNAVAILABLE` means the wallet's pinned sponsor lane is unsafe. `BROADCAST_REJECTED` is definitive provider rejection, while `BROADCAST_RESULT_UNKNOWN` is uncertainty. `SIGNER_POLICY_DECLINED` is a deterministic signer-policy decision; an unchanged retry will not help. ### Client flow examples Validation rejection (REST): ```json theme={null} {"code":"INVALID_SIGNATURE","message":"signature does not verify","retryable":false} ``` Successful REST submission: ```json theme={null} {"status":"BROADCAST","requestId":"0192...","txHash":"0x..."} ``` The REST response ends here; query the chain yourself for receipt, replacement, or revert. WebSocket rejection and broadcast: ```json theme={null} {"id":"req-1","status":"REJECTED","code":"POLICY_DECLINED","retryable":false} {"id":"req-2","status":"BROADCAST","requestId":"0192...","txHash":"0x..."} ``` After a successful WebSocket submission, the same connection automatically receives `transaction.outcome` with the original client `id`, Relay `requestId`, `txHash`, and `CONFIRMED`, `REVERTED`, `REPLACED`, or `UNKNOWN`. No client outcome acknowledgement is required. An immediate rejection creates no outcome subscription. A reverted custom error includes its pinned selector/name; an undecodable revert keeps `selector`/`data` and uses message `unknown`. ## WebSocket transaction outcomes An accepted WebSocket submission automatically receives an outcome on its submitting connection, using the original `id`. Use `transaction.subscribe` primarily after reconnecting, when you retained both the server-assigned `requestId` and `txHash`: ```json theme={null} {"id":"sub-1","method":"transaction.subscribe","payload":{"requestId":"0192...","txHash":"0x..."}} ``` If the transaction is still pending, Relay first responds with `{"id":"sub-1","status":"SUBSCRIBED","requestId":"0192...","txHash":"0x...","retryable":false}` and later sends its outcome. If a terminal outcome is still retained, Relay sends that outcome immediately instead of `SUBSCRIBED`. The outcome envelope is: ```json theme={null} {"type":"transaction.outcome","id":"sub-1","requestId":"0192...","status":"CONFIRMED","txHash":"0x...","blockNumber":"123","blockHash":"0x...","observedAt":"2026-10-20T00:00:00Z"} ``` `CONFIRMED` means Relay checked finality and observed a successful **outer transaction**. The currently deployed implementation does **not** prove that the intended trading-wallet action executed inside it. Reconcile the expected order, trade, and balance events or resulting state before marking a logical action complete. `REVERTED` means the outer transaction reverted; `REPLACED` means the candidate was replaced (with `replacementTxHash` when known); `UNKNOWN` means no stronger terminal result is available. Revert sources are `trace`, `historical_call`, `post_block_call` (lower confidence), or `unknown`. The signer retains the latest **4,096 terminal outcomes per signer**, shared across all users of that signer. This is a count limit, not a time-based retention guarantee: high traffic can evict an outcome quickly. Retention is in memory; do not assume replay survives a signer restart. Keep your own durable submission journal and use chain data when an outcome is no longer available. ### Connection closure and recovery The current configuration allows **64 pending outcome slots per client WebSocket**. A tracked transaction occupies one until its terminal outcome is processed for delivery, not until a client acknowledgement; no acknowledgement is required. This is configurable outstanding tracking, not a lifetime limit of 64 submissions, the separate in-flight-request limit, or a sponsor-nonce limit. Immediate submission rejections take no outcome slot. If capacity is exhausted, Relay may close the socket while registering another outcome **after** writing its `BROADCAST` response. This does not undo the scheduled broadcast or prove the transaction failed. After a disconnect, preserve all unresolved `requestId`/`txHash` pairs and the last observed `transaction.outcome`. Reconnect with a fresh wallet-bound session; resubscribe to known transactions while their outcomes are retained, and use chain receipts or state to resolve those no longer available from Relay. Use bounded, asynchronous recovery work so receipt/log lookups do not halt the trading submission loop. A roughly 50-second pause during reconnect is not a Relay-prescribed backoff; investigate the client connector's reconciliation and RPC queries. There is a harder **lost-reply gap** if the connection drops before the `BROADCAST` response supplies `requestId` and `txHash`: `transaction.subscribe` cannot look up that submission using only its WS `id`. The `id` provides connection-local correlation and duplicate handling, not durable cross-connection idempotency. There is currently no public Relay lookup by wallet plus nonce, client `id`, or `clientOrderId`; a dedicated client-order-ID lookup is planned but not live. Retrying the old `id` does not establish whether the earlier submission was scheduled or sent. For `wallet.execute_batch` and `wallet.execute_replace_by_slot_packed`, set a unique, nonzero, signed 32-byte `payload.header.clientOrderId` for each logical batch and persist it alongside the account, market, signed intent, and WS `id`. This is a **batch-level correlation ID**, not an order ID or an idempotency key; Relay does not enforce uniqueness, and one batch can yield multiple order events. If the reply is lost, page through Data Source `GET /api/v1/users/{userId}/order-events` for the traded user ID, following `pagination.nextCursor`. Filter returned rows by `clientOrderId` and confirm the account and market; matching rows can supply `transactionHash` and events. There is no documented server-side `clientOrderId` filter. The endpoint records resting-maker lifecycle events, not every taker-only IOC or other possible action. See the [order-events reference](/api/data-source/reference/order-events). **No matching event does not prove failure.** The transaction may still be pending, indexing may lag, it may have reverted, or it may have executed without an event represented by that endpoint. A signed deadline expiring later does not rule out execution before expiry. Reconcile available chain receipts, wallet nonce, trading events, and account state before resubmitting the logical action. Revert decoding recognizes Solidity `Error(string)` (`0x08c379a0`) and `Panic(uint256)` (`0x4e487b71`), plus custom errors from the pinned compiled ABI catalog. Unknown selectors retain exact `selector` and `data`, with name omitted and message `unknown`. Decoded text is bounded and untrusted. ### Outcome subscription errors `transaction.subscribe` can return `MALFORMED_REQUEST`, `INVALID_BINDING`, `TRANSACTION_OUTCOME_NOT_FOUND`, `TRANSACTION_OUTCOME_ALREADY_SUBSCRIBED`, `TRANSACTION_OUTCOME_EXPIRED`, `STATE_UNAVAILABLE`, or `INTERNAL_ERROR`. These errors refer to lookup/subscription state, not a new broadcast attempt. ## Generated custom-error appendix The following entries are generated from the pinned `AccountCore` and `KuruTradingWallet` bindings. They are decoding names only; they are not Relay error codes. | Contract | Error | Signature | Selector | | - | - | - | - | | AccountCore | AccountAlreadyRegistered | `AccountAlreadyRegistered()` | `0xcff2d5ad` | | AccountCore | AccountNotFound | `AccountNotFound()` | `0xfaba8ebe` | | AccountCore | AlreadyInitialized | `AlreadyInitialized()` | `0x0dc149f0` | | AccountCore | AssetNotEnabled | `AssetNotEnabled()` | `0xa3bd9445` | | AccountCore | BuilderApprovalExpired | `BuilderApprovalExpired()` | `0x5e65c9f4` | | AccountCore | BuilderApprovalNotFound | `BuilderApprovalNotFound()` | `0xd595f3a2` | | AccountCore | BuilderFeeTooHigh | `BuilderFeeTooHigh()` | `0x89c89cba` | | AccountCore | BuilderReferralNotFound | `BuilderReferralNotFound()` | `0xc0c83880` | | AccountCore | BuilderReferralNotImproved | `BuilderReferralNotImproved()` | `0xc152b20d` | | AccountCore | BuilderReferralTierMismatch | `BuilderReferralTierMismatch()` | `0x8c7badd7` | | AccountCore | CannotAuthorizeOwner | `CannotAuthorizeOwner()` | `0x07b32335` | | AccountCore | InsufficientBalance | `InsufficientBalance()` | `0xf4d678b8` | | AccountCore | InvalidAuthority | `InvalidAuthority()` | `0xded4370e` | | AccountCore | InvalidBuilder | `InvalidBuilder()` | `0x6d10926b` | | AccountCore | InvalidCollateral | `InvalidCollateral()` | `0xd1ef4cea` | | AccountCore | InvalidExpireTime | `InvalidExpireTime()` | `0x75e3453f` | | AccountCore | InvalidInitialization | `InvalidInitialization()` | `0xf92ee8a9` | | AccountCore | InvalidMarketConfig | `InvalidMarketConfig()` | `0xc9ae771e` | | AccountCore | InvalidSignature | `InvalidSignature()` | `0x8baa579f` | | AccountCore | InvalidSubaccount | `InvalidSubaccount()` | `0xf6391b43` | | AccountCore | MarketFeeError | `MarketFeeError()` | `0xa9269545` | | AccountCore | NativeAssetMismatch | `NativeAssetMismatch()` | `0xcd41a9e3` | | AccountCore | NewOwnerIsZeroAddress | `NewOwnerIsZeroAddress()` | `0x7448fbae` | | AccountCore | NoBuilderFees | `NoBuilderFees()` | `0xc7a51192` | | AccountCore | NoHandoverRequest | `NoHandoverRequest()` | `0x6f5e8818` | | AccountCore | NotInitializing | `NotInitializing()` | `0xd7e6bcf8` | | AccountCore | OnlySpotRouter | `OnlySpotRouter()` | `0xdec150d3` | | AccountCore | OnlyVerifiedSpotOrderBook | `OnlyVerifiedSpotOrderBook()` | `0x4266501b` | | AccountCore | ProtocolPaused | `ProtocolPaused()` | `0x44279255` | | AccountCore | Reentrancy | `Reentrancy()` | `0xab143c06` | | AccountCore | SameRootRequired | `SameRootRequired()` | `0x28cddf05` | | AccountCore | SpotFeesExceedProceeds | `SpotFeesExceedProceeds()` | `0xda77c0c4` | | AccountCore | SpotTokenNotEnabled | `SpotTokenNotEnabled()` | `0xdea2abd6` | | AccountCore | SubaccountLimitReached | `SubaccountLimitReached()` | `0xef4cdf7c` | | AccountCore | Unauthorized | `Unauthorized()` | `0x82b42900` | | AccountCore | UnauthorizedCallContext | `UnauthorizedCallContext()` | `0x9f03a026` | | AccountCore | UpgradeFailed | `UpgradeFailed()` | `0x55299b49` | | AccountCore | ZeroAddress | `ZeroAddress()` | `0xd92e233d` | | AccountCore | ZeroAmount | `ZeroAmount()` | `0x1f2a2005` | | KuruTradingWallet | DeadlineExpired | `DeadlineExpired()` | `0x1ab7da6b` | | KuruTradingWallet | InvalidBuilder | `InvalidBuilder()` | `0x6d10926b` | | KuruTradingWallet | InvalidExpireTime | `InvalidExpireTime()` | `0x75e3453f` | | KuruTradingWallet | InvalidSignature | `InvalidSignature()` | `0x8baa579f` | | KuruTradingWallet | NonceTooFarInFuture | `NonceTooFarInFuture()` | `0x8bce3a2b` | | KuruTradingWallet | NonceTooLow | `NonceTooLow()` | `0xd24d82a4` | | KuruTradingWallet | OrderIdBindingLengthMismatch | `OrderIdBindingLengthMismatch()` | `0xe64b5e50` | | KuruTradingWallet | Reentrancy | `Reentrancy()` | `0xab143c06` | | KuruTradingWallet | StaleAuthorizationEpoch | `StaleAuthorizationEpoch()` | `0x09c04c5a` | | KuruTradingWallet | TriggerNonceUsed | `TriggerNonceUsed()` | `0xbf055185` | | KuruTradingWallet | TriggerNotActive | `TriggerNotActive()` | `0xbac08cf0` | | KuruTradingWallet | Unauthorized | `Unauthorized()` | `0x82b42900` | | KuruTradingWallet | UnauthorizedKeeper | `UnauthorizedKeeper()` | `0x77b14347` | | KuruTradingWallet | UnexpectedSlotOrderId | `UnexpectedSlotOrderId()` | `0x53e12325` | | KuruTradingWallet | UnverifiedSpotMarket | `UnverifiedSpotMarket()` | `0xde616dbc` | | KuruTradingWallet | ZeroAddress | `ZeroAddress()` | `0xd92e233d` | Regenerate this appendix whenever the pinned generated bindings or ABI catalog changes. # Operational methods Source: https://docs.kuru.io/api/relay/operational Opt-in, simulation-first Relay methods for maintenance, FOK, and stored instructions. Relay's nine operational methods are **slow, opt-in routes**, not the low-latency batch or packed-slot trading path. A method's presence in this reference does not mean it is enabled on every deployment or market. Check the selected deployment's capabilities before integrating. Wallet methods that specify a market require that market to enable the method; AccountCore methods have no market scope. A code merge or testnet smoke test does not establish mainnet availability. Before signer FIFO insertion, Relay validates the typed payload and signature where applicable, then calls `eth_estimateGas` against `latest` using the actual sponsor as `from`, the canonical wallet or AccountCore target, exact calldata, zero value, and an empty access list. It supplies `estimate + ceil(estimate / 5)` gas (at least 20% headroom) and rejects estimates above the configured method cap. It never silently truncates gas or substitutes a guessed estimate. These methods do not use FastLane, exchange-state enrichment, access-list generation, or heuristic gas models. The existing fast batch/packed paths are unchanged; latency-sensitive FOK can use `wallet.execute_batch`. Simulation adds RPC latency and can become stale before inclusion. On a WebSocket, an operational request also occupies a public worker and its ordered nonce handoff can delay later trading requests on that same connection. Use REST or a separate WebSocket connection for operational work. A `BROADCAST` response only means Relay scheduled asynchronous broadcast, not RPC acceptance or execution. REST callers must inspect the receipt and events/state; WebSocket callers receive automatic terminal outcomes but must still reconcile the intended action. Operational routes require a pre-existing trading-wallet delegation. They accept neither an atomic `authorization7702` tuple nor a `makerSlotsPrimed` hint. Complete [onboarding](/sdk/relay-onboarding) first. Do not rely on every incorrect delegation state being rejected before broadcast; verify delegation and the expected on-chain events/state yourself. Methods with a signed trading `header` must use `header.accountId` equal to a scoped JWT's verified `uid` to use the [account rate tier](/api/relay/rate-limits). Headerless methods such as TWAP cancellation/finalization, signer revocation, and subaccount creation retain the wallet-based quota even with a scoped JWT. The JWT wallet remains independent of an AccountCore operation's signed `authorizer`. ## Wallet methods | Method | Scope | Effect | | - | - | - | | [Cancel orders by ID](/api/relay/reference/execute-cancel-orders-by-id) | Signed account and market | Cancel 1–62 explicit order IDs | | [Cancel all](/api/relay/reference/execute-cancel-all) | Signed account and market | Cancel resting orders in that market | | [FOK swap](/api/relay/reference/execute-fok-swap) | Signed account and market | Execute full base quantity or revert | | [Store FOK trigger](/api/relay/reference/create-fok-swap-trigger) | Signed account and market | Persist the condition hash and FOK instruction only | | [Store TWAP](/api/relay/reference/create-twap) | Signed account and market | Persist a schedule only; no slices run | | [Cancel TWAP](/api/relay/reference/cancel-twap) | Signed account and stored TWAP | Cancel a signed stored instruction | | [Finalize TWAP](/api/relay/reference/finalize-twap) | Authenticated wallet and stored TWAP | Mark expired instruction finished; no execution | FOK trigger and TWAP creation are **storage only**. Relay does not monitor conditions, schedule slices, or run a keeper for these methods. It checks the FOK condition schema/hash and discards the supplied condition bytes, so retain them yourself. `finalize_twap` only persists expiry/skipped/finished state; it does not execute slices, cancel orders, or transfer funds. > [!WARNING] > > Automated triggers, including take-profit/stop-loss (TP/SL), and TWAP execution are **not implemented** as live features; they remain work in progress. These opt-in endpoints can store instructions where enabled, but storing one will not trigger an order or execute TWAP slices. Wallet signatures use EIP-712 domain `KuruTradingWallet`, version `2`, with the delegated EOA as verifying contract. The wallet header's `authNonce` is the AccountCore authorization epoch; its immediate or one-shot `nonce` is separate. Read the method page for the exact type string and nonce namespace. For cancellation, builder and builder fee must both be zero. ## AccountCore methods | Method | Signed authority | Effect | | - | - | - | | [Revoke signer](/api/relay/reference/revoke-account-signer) | Root owner or live ADMIN | Revoke signer and advance the root authorization epoch | | [Create subaccount](/api/relay/reference/create-subaccount) | Root owner or live ADMIN/TRADE | Create the next child sequence; epoch unchanged | The frontend trading wallet supplies the Relay JWT, but **the JWT identity does not need to equal the AccountCore `authorizer`, owner/root owner, or signer being revoked**. JWT identity controls service admission and sponsorship only. A separate owner or authorized EOA signs the AccountCore EIP-712 request using domain `KuruAccountCore`, version `1`, and the configured AccountCore proxy as verifying contract. These two methods accept canonical 65-byte or ERC-2098 64-byte EOA signatures; they do not add ERC-1271 support. The older signer-grant onboarding route keeps its distinct JWT-to-new-signer binding. Read `nonce` or `authNonce` from AccountCore: these are uint256 root authorization epochs, **not** millisecond trading nonces. For subaccount creation, use the next nonzero uint16 `subaccountSeq`, wait for inclusion, then read again before creating another child. A pending creation is not assumed to have changed `latest` state for the next simulation. ## Immediate errors and recovery * `OPERATIONAL_SIMULATION_REVERTED` (HTTP 400) means the exact simulation explicitly reverted. No transaction was signed or broadcast; correct the state or request before retrying. * `POLICY_DECLINED` (HTTP 403) can mean the buffered estimate exceeded the method's gas cap. No gas amount is silently clipped. * `GAS_POLICY_UNAVAILABLE` (HTTP 503, retryable) covers estimator saturation, timeouts, malformed estimates, and transient provider failures. A generic RPC failure is not a proven contract revert. * `INTERNAL_DEADLINE_EXCEEDED` (HTTP 504) can mean the caller's deadline elapsed during estimation. Reconcile any ambiguous submission before retrying. After a successful `BROADCAST`, use the usual [Relay outcomes and recovery](/api/relay/errors) rules. A simulation is not an execution guarantee: balances, orders, permissions, and nonce state may change before inclusion. Do not blindly resubmit a FOK or account-administration operation after a lost reply. # Relay Rate Limits and Migration Source: https://docs.kuru.io/api/relay/rate-limits Account-scoped Relay login, configured request limits, and the November 4 migration. ## Scheduled rate-limit migration > [!WARNING] > > Action for trading integrations: obtain a verified `uid`-scoped JWT for each account you trade before the November 4 cutover. At cutover, **all wallet-only JWTs—including those issued earlier—immediately move to the 1 request/second sustained allowance**. There is no grace period or grandfathering. Test the scoped flow on the same network as your trading account. Relay is scheduled to complete its account-scoped rate-limit migration on **Wednesday, November 4, 2026 at 12:00 PM Eastern Time (EST, UTC−05:00; 17:00 UTC)**. At that time, requests without a verified account-scoped token will use a **1 request/second sustained per-wallet allowance**, including requests made with wallet-only JWTs issued before cutover. There is **no grace period or exception for existing tokens**. Those tokens remain valid, but their requests use the lower quota because Relay applies the limit when it processes each request, not when it issues the JWT. The new sustained rate is a scheduled change, **not a claim that the lower rate is already active**. The post-cutover burst allowance has not been announced; do not assume an instantaneous one-request ceiling. For account-scoped trading, the mainnet and testnet configuration currently specifies these *per-replica defaults*: | Quota | Sustained refill | Burst capacity | Scope | | - | -: | -: | - | | Verified root account | 250 requests/second | 250 requests | All signers and subaccounts of one root, across markets | | Verified root account + market | 250 requests/second | 250 requests | All signers and subaccounts of one root trading one market | | Wallet-only, current configuration | 250 requests/second | 250 requests | One wallet on the wallet-based path | | Unscoped wallet after cutover | 1 request/second | To be announced | Wallet and headerless operations | Both verified-account buckets must allow a trading submission. A submission costs **one request unit, not one per order** in a batch. A request admitted to the limiter still counts if a later policy check or simulation rejects it. Subaccounts share their root's budgets; separate signer keys, WebSocket connections, REST calls, or JWT renewals do not create extra root allowance within one replica. These are not guaranteed end-to-end throughput figures. Existing limits also apply, including **100 requests/second per IP**, **200 requests/second per identity**, **500 WebSocket messages/second**, and a **100-request per-method burst**. An additional shared wallet-tier bucket is configured at 1,000 requests/second with a 1,000-request burst; it does not replace the per-wallet limit. Account-specific policy overrides may change an effective allowance. Current buckets are in-memory **per Relay replica**, not a globally distributed hard quota. Limits are enforced server-side and can change for existing tokens and connections without JWT renewal. Plan to handle throttling, not to multiply connections to evade it. “Requests/second” is the sustained token refill rate; burst is a separate number of requests that can be admitted in a short interval when credit is available. A `RATE_LIMITED` response is ordinary throttling, not an outage. ## Move to account-scoped login 1. Confirm the trading wallet has live AccountCore `TRADE` authority for the exact account ID it will trade. For a child account, use that child's ID. 2. Call the unchanged public `POST /auth/challenge` for the wallet and sign the exact returned message. 3. Exchange the signed challenge at public `POST /auth/token` with an additional `uid` **string**, for example `"10"`. It must be a positive canonical uint40 decimal value, without leading zeroes or whitespace. [Token exchange](/api/relay/reference/exchange-token) shows the request. 4. Store the new JWT securely and use it for that account. Re-login with `uid` for each traded account/subaccount: adding an account ID to a submission cannot scope an already-issued unscoped JWT. Set the signed trading header's `accountId` to the token's exact `uid`. For WebSocket, also set the required upgrade query `account_id` to that same ID. 5. Exercise the same signed submissions on testnet, handle `RATE_LIMITED` with bounded retry, and reconcile broadcasts or uncertain results before submitting another logical action. Relay verifies the challenge wallet's current on-chain trading authorization for `uid` and resolves its root when issuing the token. A successful scoped JWT has a signed `kuru_account` claim with `uid`, `root_uid`, `chain_id`, and `account_core` string fields. These are Relay-issued facts; clients cannot self-assert a root ID or gain a higher allowance by merely changing a request body. The token response envelope remains `accessToken`, `tokenType`, `expiresAt`, and `wallet`; it does not return the quota or root as separate response fields. Token issuance neither registers an account nor grants on-chain permission. Renewal rechecks trading permission; contracts still enforce authorization at execution. Trading admission does not add an authorization RPC for each submission. Methods without a trading `header`—including signer onboarding/revocation, subaccount creation, and stored-trigger or TWAP cancellation/finalization—use the wallet-based quota **even with a scoped JWT**. For AccountCore operations, the signed owner/administrator `authorizer` remains independent of the JWT wallet. Do not put `uid` on `POST /auth/challenge`, rename signed `accountId`, or replace WebSocket `account_id` with `uid`. The pinned `@toxicflow-labs/ts-sdk@0.2.0` Relay `authenticate()`/`exchangeToken()` methods do not send `uid`. Until an SDK release supports scoped login, perform the two public authentication calls directly and supply the resulting token to the SDK client's `accessToken`/`setAccessToken` option, or use the documented REST/WebSocket requests directly. See [Relay SDK authentication](/sdk/relay#authenticate). ## When Relay throttles a request REST returns HTTP **429** with `code: "RATE_LIMITED"`, `retryable: true`, and `retryAfterMs`. The equivalent WebSocket request is rejected without closing the connection solely because of the new account limiter. Honor the reported delay, use bounded backoff with jitter, and pace future requests. A retried WebSocket submission needs a **new envelope `id`**, because replaying the same `id` can replay the old rejection. The envelope `id` is not a signed intent nonce, `clientOrderId`, or durable idempotency key; retain the original signed identity and reconcile state before retrying. Never blindly resubmit a `BROADCAST` or an uncertain result. Outcome pushes and `transaction.subscribe` do not consume the transaction quota, though WebSocket frame limits still apply. See [Relay errors and outcomes](/api/relay/errors). # Authorize account signer Source: https://docs.kuru.io/api/relay/reference/authorize-account-signer POST /relay Grant a secondary EOA AccountCore permission and optionally install its EIP-7702 delegation. Submits `account_core.authorize_account_signer_by_sig`. The JWT wallet, request `wallet`, payload `signer`, and optional EIP-7702 `authority` must be identical. This onboarding request has no trading `header` and uses the [wallet-based sponsorship quota](/api/relay/rate-limits) even with an account-scoped JWT. It can be submitted with a wallet-only token before the signer has `TRADE` permission; obtain a new scoped token after on-chain authorization succeeds. > [!NOTE] > > The request below is a signing template, not a broadcast-ready transaction. Replace the wallet, account, nonces, expiry, deadline, and signatures with values generated for your selected network. **requestId** `string` *required* New lowercase UUIDv7 used for correlation. It is not durable idempotency. **method** `string` *required* (default: account_core.authorize_account_signer_by_sig) Must be `account_core.authorize_account_signer_by_sig`. **wallet** `string` *required* Secondary trading EOA, matching the bearer token's wallet claim. **payload** `object` *required* AccountCore authorization signed by the account owner or a live administrator. Required fields: `account`, `authorizer`, `signer`, `permissions`, `expiry`, `nonce`, `deadline`, and `signature`. **authorization7702** `object | null` Optional EIP-7702 tuple containing `authority`, `chainId`, `delegate`, `nonce`, `yParity`, `r`, and `s`. Use `null` when already delegated. ```curl cURL theme={null} curl --request POST --url https://relay.mainnet.kuru.io/relay \ --header "Authorization: Bearer $KURU_RELAY_JWT" \ --header 'Content-Type: application/json' \ --data '{ "requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f", "method":"account_core.authorize_account_signer_by_sig", "wallet":"0x1111111111111111111111111111111111111111", "payload":{"account":"0x3333333333333333333333333333333333333333","authorizer":"0x3333333333333333333333333333333333333333","signer":"0x1111111111111111111111111111111111111111","permissions":"1","expiry":"1722592000","nonce":"0","deadline":"1720000030","signature":"0x..."}, "authorization7702":{"authority":"0x1111111111111111111111111111111111111111","chainId":"143","delegate":"0xa478b5a38aabDf8b31f0ec7443a274162214Cd18","nonce":"7","yParity":"0","r":"0x...32 bytes...","s":"0x...32 bytes..."} }' ``` ```json BROADCAST theme={null} { "requestId": "018f5ef2-88a1-7b41-a826-4b679010f87f", "status": "BROADCAST", "txHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "sponsorAddress": "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "sponsorNonce": "42", "transactionType": "SET_CODE" } ``` After broadcast, require a successful receipt, verify the EIP-7702 delegation indicator, verify `AccountSignerAuthorized`, and read the new AccountCore authorization nonce. # Cancel conditional order Source: https://docs.kuru.io/api/relay/reference/cancel-trigger POST /relay Cancel an active trigger with a newly signed cancellation intent. Submits the enabled `wallet.cancel_trigger` method. Trigger cancellation uses the unordered one-shot trigger nonce namespace, not the increasing immediate-order nonce. > [!NOTE] > > The request is a signing template. Replace the wallet, account ID, nonce, deadline, trigger ID, and signature with values generated for the selected network. **requestId** `string` *required* New lowercase UUIDv7 for correlation. **method** `string` *required* (default: wallet.cancel_trigger) Must be `wallet.cancel_trigger`. **wallet** `string` *required* Secondary trading EOA that created the trigger and matches the JWT. **payload** `object` *required* Signed cancellation containing `accountId`, `authNonce`, unused `nonce`, Unix-second `deadline`, 32-byte `triggerId`, and `signature`. **authorization7702** `object | null` Normally `null` after onboarding. ```curl cURL theme={null} curl --request POST --url https://relay.mainnet.kuru.io/relay \ --header "Authorization: Bearer $KURU_RELAY_JWT" \ --header 'Content-Type: application/json' \ --data '{"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","method":"wallet.cancel_trigger","wallet":"0x1111111111111111111111111111111111111111","payload":{"accountId":"123","authNonce":"1","nonce":"1720000000999","deadline":"1720000030","triggerId":"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","signature":"0x..."},"authorization7702":null}' ``` ```json BROADCAST theme={null} { "requestId": "018f5ef2-88a1-7b41-a826-4b679010f87f", "status": "BROADCAST", "txHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "sponsorAddress": "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "sponsorNonce": "44", "transactionType": "DYNAMIC_FEE" } ``` Verify a successful receipt and `TriggerCanceled` before treating the trigger as canceled. # Cancel TWAP instruction Source: https://docs.kuru.io/api/relay/reference/cancel-twap POST /relay Submit wallet.cancel_twap through the opt-in Relay operational path. Submits `wallet.cancel_twap` when this method is enabled for the selected deployment. This is a **slow operational method**, not the low-latency trading path. Relay validates the typed request and signature where applicable, simulates the exact call against `latest`, and only then queues a sponsored transaction. See [Operational methods](/api/relay/operational) for availability, gas, and latency rules. > [!NOTE] > > The example uses testnet WETH/USDC where a market is required, but all identities, nonces, timestamps, hashes, and signatures are illustrative. Read current state and build a fresh valid signature for the selected network. Omit `authorization7702` and `makerSlotsPrimed`; complete delegation first. **requestId** `string` *required* New lowercase UUIDv7 for request correlation. **method** `string` *required* (default: wallet.cancel_twap) Must be `wallet.cancel_twap`. **wallet** `string` *required* Trading wallet matching the bearer JWT; for AccountCore operations this is the sponsoring frontend identity, not necessarily the signed authorizer. **payload** `object` *required* Method-specific payload shown below; unknown fields are rejected. Cancel an existing TWAP for the signed account. The nonce uses the wallet's one-shot trigger/TWAP namespace, not `lastSeenOrderNonce`. Read the current authorization epoch and sign a fresh request; a successful `BROADCAST` alone does not prove cancellation. This request has an `accountId` field but **no trading `header`**. It uses the [wallet-based quota](/api/relay/rate-limits) even when the JWT is account-scoped; the payload's account ID is still checked by the contract. Sign the exact EIP-712 type below using the `KuruTradingWallet` version `2`, with the delegated trading wallet as `verifyingContract` and the selected chain ID (`143` mainnet; `10143` testnet): ```text theme={null} CancelTwapIntent(uint40 accountId,uint256 authNonce,uint64 nonce,uint64 deadline,bytes32 twapId) ``` ```curl cURL theme={null} curl --request POST --url https://relay.testnet.kuru.io/relay \ --header "Authorization: Bearer $KURU_RELAY_JWT" \ --header 'Content-Type: application/json' \ --data '{"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","method":"wallet.cancel_twap","wallet":"0x1111111111111111111111111111111111111111","payload":{"accountId":"123","authNonce":"1","nonce":"1792480000002","deadline":"1792500000","twapId":"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","signature":"0x..."}}' ``` ```json BROADCAST theme={null} {"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","status":"BROADCAST","txHash":"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","sponsorAddress":"0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","sponsorNonce":"42","transactionType":"DYNAMIC_FEE"} ``` `BROADCAST` means scheduling for asynchronous RPC broadcast, not provider acceptance or successful execution. Check the receipt and expected events/state. A failed estimate returns an immediate error with no transaction signed or broadcast. # Create batch trigger Source: https://docs.kuru.io/api/relay/reference/create-batch-trigger POST /relay Reference-only conditional batch method; automated trigger execution is not available. Submits `wallet.create_batch_trigger`, which stores readable native orders and cancellations behind a committed trigger condition. > [!WARNING] > > Conditional-order submission is not a supported live Relay flow. This versioned method is documented for reference; do not use the playground to assume it is available on either network. **requestId** `string` *required* New lowercase UUIDv7 for correlation. **method** `string` *required* (default: wallet.create_batch_trigger) Must be `wallet.create_batch_trigger`. **wallet** `string` *required* Secondary trading EOA matching the bearer JWT. **payload** `object` *required* Signed `CreateBatchTriggerIntent` with `header`, `triggerExpiry`, `conditionSchema`, `condition`, `conditionHash`, `orders`, `cancelSlotIdxs`, `expectedOrderIds`, and `signature`. **authorization7702** `object | null` Normally `null` after onboarding. `condition` must hash exactly to `conditionHash`, and its first four encoded bytes must identify the nonzero, allowlisted `conditionSchema`. `triggerExpiry` is a future Unix timestamp within the deployment horizon. ```curl cURL theme={null} curl --request POST --url https://relay.mainnet.kuru.io/relay \ --header "Authorization: Bearer $KURU_RELAY_JWT" \ --header 'Content-Type: application/json' \ --data '{"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","method":"wallet.create_batch_trigger","wallet":"0x1111111111111111111111111111111111111111","payload":{"header":{"accountId":"123","market":"0x8121ee960066e4344a213f9ac7502395502aee7a","authNonce":"1","nonce":"1720000000997","deadline":"1720000030","clientOrderId":"0x0000000000000000000000000000000000000000000000000000000000000003","builder":"0x0000000000000000000000000000000000000000","builderFeePps":"0"},"triggerExpiry":"1720003600","conditionSchema":"1","condition":"0x00000001...","conditionHash":"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","orders":[],"cancelSlotIdxs":["3"],"expectedOrderIds":["31"],"signature":"0x..."},"authorization7702":null}' ``` The example shows the complete shape but is not executable until condition data, hashes, nonces, deadlines, and signatures are generated from current state. # Create authentication challenge Source: https://docs.kuru.io/api/relay/reference/create-challenge api/relay/openapi.yaml POST /auth/challenge Create a one-time message for a secondary trading EOA to sign. Public endpoint. No JWT or `Authorization` header is required. It creates a five-minute challenge for the requested wallet; sign the returned `message` exactly as received with Ethereum `personal_sign`. This request is unchanged by account-scoped login. If you need the verified-account rate tier, add `uid` only when [exchanging the signed challenge](/api/relay/reference/exchange-token), not here. **wallet** `string` *required* Nonzero 20-byte address of the secondary trading EOA. Example: `0x1111111111111111111111111111111111111111`. ```curl cURL theme={null} curl --request POST \ --url https://relay.mainnet.kuru.io/auth/challenge \ --header 'Content-Type: application/json' \ --data '{"wallet":"0x1111111111111111111111111111111111111111"}' ``` **challengeId** `string` *required* Lowercase 128-bit challenge identifier without a `0x` prefix. **message** `string` *required* Exact UTF-8 SIWE-style message to sign with ERC-191 `personal_sign`. **expiresAt** `string` *required* Challenge expiration as an ISO 8601 timestamp. ```json 200 theme={null} { "challengeId": "8c4a11c6eb574d16972fac2a8c85a6dc", "message": "relay.mainnet.kuru.io wants you to sign in with your Ethereum account:\n0x1111111111111111111111111111111111111111\n...", "expiresAt": "2026-08-27T10:05:00Z" } ``` ```json 403 theme={null} { "code": "AUTHENTICATION_FAILED", "message": "authentication failed", "retryable": false } ``` # Store FOK swap trigger Source: https://docs.kuru.io/api/relay/reference/create-fok-swap-trigger POST /relay Store an FOK trigger through opt-in Relay; condition monitoring and execution are not implemented. Submits `wallet.create_fok_swap_trigger` when this method is enabled for the selected deployment. This is a **slow operational method**, not the low-latency trading path. Relay validates the typed request and signature where applicable, simulates the exact call against `latest`, and only then queues a sponsored transaction. See [Operational methods](/api/relay/operational) for availability, gas, and latency rules. > [!NOTE] > > The example uses testnet WETH/USDC where a market is required, but all identities, nonces, timestamps, hashes, and signatures are illustrative. Read current state and build a fresh valid signature for the selected network. Omit `authorization7702` and `makerSlotsPrimed`; complete delegation first. **requestId** `string` *required* New lowercase UUIDv7 for request correlation. **method** `string` *required* (default: wallet.create_fok_swap_trigger) Must be `wallet.create_fok_swap_trigger`. **wallet** `string` *required* Trading wallet matching the bearer JWT; for AccountCore operations this is the sponsoring frontend identity, not necessarily the signed authorizer. **payload** `object` *required* Method-specific payload shown below; unknown fields are rejected. > [!WARNING] > > Automated triggers, including TP/SL, are **not implemented** as a live feature and remain work in progress. This method only stores an instruction where enabled; it does not monitor or execute a trigger. **Storage only:** this does not register a condition monitor, schedule execution, or perform the FOK swap. The condition starts with a four-byte big-endian schema prefix; Relay verifies its schema and hash, then discards the bytes. Persist the exact condition bytes yourself. Replace the illustrative condition and hash with a matching pair. Creation uses the wallet's one-shot trigger/TWAP nonce namespace, not `lastSeenOrderNonce`; WebSocket submissions still follow connection-level increasing nonce ordering. Sign the exact EIP-712 type below using the `KuruTradingWallet` version `2`, with the delegated trading wallet as `verifyingContract` and the selected chain ID (`143` mainnet; `10143` testnet): ```text theme={null} CreateFokSwapTriggerIntent(uint40 accountId,address market,uint256 authNonce,uint64 nonce,uint64 deadline,bytes32 clientOrderId,address builder,uint32 builderFeePps,uint64 triggerExpiry,bytes32 conditionHash,uint8 side,uint96 quantity,uint32 limitPrice) ``` ```curl cURL theme={null} curl --request POST --url https://relay.testnet.kuru.io/relay \ --header "Authorization: Bearer $KURU_RELAY_JWT" \ --header 'Content-Type: application/json' \ --data '{"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","method":"wallet.create_fok_swap_trigger","wallet":"0x1111111111111111111111111111111111111111","payload":{"header":{"accountId":"123","market":"0x0A082280e4eA3D822E23Ec1186685477241A039d","authNonce":"1","nonce":"1792480000001","deadline":"1792500000","clientOrderId":"0x0000000000000000000000000000000000000000000000000000000000000001","builder":"0x0000000000000000000000000000000000000000","builderFeePps":"0"},"triggerExpiry":"1792503600","conditionSchema":"1","condition":"0x00000001...","conditionHash":"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","order":{"side":"BUY","quantity":"10000000000","limitPrice":"30000000"},"signature":"0x..."}}' ``` ```json BROADCAST theme={null} {"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","status":"BROADCAST","txHash":"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","sponsorAddress":"0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","sponsorNonce":"42","transactionType":"DYNAMIC_FEE"} ``` `BROADCAST` means scheduling for asynchronous RPC broadcast, not provider acceptance or successful execution. Check the receipt and expected events/state. A failed estimate returns an immediate error with no transaction signed or broadcast. # Create packed replacement trigger Source: https://docs.kuru.io/api/relay/reference/create-replace-trigger POST /relay Reference-only packed replacement trigger; automated execution is not available. Submits `wallet.create_replace_trigger`, which stores compact packed slot operations behind a committed trigger condition. > [!WARNING] > > Conditional-order submission is not a supported live Relay flow. This versioned method is documented for reference; do not use the playground to assume it is available on either network. **requestId** `string` *required* New lowercase UUIDv7 for correlation. **method** `string` *required* (default: wallet.create_replace_trigger) Must be `wallet.create_replace_trigger`. **wallet** `string` *required* Secondary trading EOA matching the bearer JWT. **payload** `object` *required* Signed `CreateReplaceTriggerIntent` with `header`, `triggerExpiry`, `conditionSchema`, `condition`, `conditionHash`, `packedOps`, `expectedOrderIds`, and `signature`. **authorization7702** `object | null` Normally `null` after onboarding. `packedOps` contains one to 256 canonical 32-byte words. `expectedOrderIds` must contain one binding per word. Condition validation is identical to `wallet.create_batch_trigger`. ```curl cURL theme={null} curl --request POST --url https://relay.mainnet.kuru.io/relay \ --header "Authorization: Bearer $KURU_RELAY_JWT" \ --header 'Content-Type: application/json' \ --data '{"requestId":"018f5ef2-88a1-7b41-a826-4b679010f880","method":"wallet.create_replace_trigger","wallet":"0x1111111111111111111111111111111111111111","payload":{"header":{"accountId":"123","market":"0x8121ee960066e4344a213f9ac7502395502aee7a","authNonce":"1","nonce":"1720000000998","deadline":"1720000030","clientOrderId":"0x0000000000000000000000000000000000000000000000000000000000000004","builder":"0x0000000000000000000000000000000000000000","builderFeePps":"0"},"triggerExpiry":"1720003600","conditionSchema":"1","condition":"0x00000001...","conditionHash":"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","packedOps":"0x","expectedOrderIds":["31"],"signature":"0x..."},"authorization7702":null}' ``` The example shows the complete shape but is not executable until condition data, hashes, nonces, deadlines, and signatures are generated from current state. # Create subaccount Source: https://docs.kuru.io/api/relay/reference/create-subaccount POST /relay Submit account_core.create_subaccount_by_sig through the opt-in Relay operational path. Submits `account_core.create_subaccount_by_sig` when this method is enabled for the selected deployment. This is a **slow operational method**, not the low-latency trading path. Relay validates the typed request and signature where applicable, simulates the exact call against `latest`, and only then queues a sponsored transaction. See [Operational methods](/api/relay/operational) for availability, gas, and latency rules. > [!NOTE] > > The example uses testnet WETH/USDC where a market is required, but all identities, nonces, timestamps, hashes, and signatures are illustrative. Read current state and build a fresh valid signature for the selected network. Omit `authorization7702` and `makerSlotsPrimed`; complete delegation first. **requestId** `string` *required* New lowercase UUIDv7 for request correlation. **method** `string` *required* (default: account_core.create_subaccount_by_sig) Must be `account_core.create_subaccount_by_sig`. **wallet** `string` *required* Trading wallet matching the bearer JWT; for AccountCore operations this is the sponsoring frontend identity, not necessarily the signed authorizer. **payload** `object` *required* Method-specific payload shown below; unknown fields are rejected. The root owner or an authorized ADMIN/TRADE EOA signs. For an unregistered root, only the owner may bootstrap the first child. `subaccountSeq` is the **next nonzero uint16 sequence**, not an account ID. `authNonce` is the root authorization epoch read from AccountCore, not a millisecond nonce. Creation advances the sequence, not the epoch; wait for inclusion and read the next sequence before signing another. The trading wallet's JWT is independent of the authorizer/root owner. This headerless operation uses the [wallet-based sponsorship quota](/api/relay/rate-limits), even with an account-scoped JWT. The JWT wallet need not be the signed owner or administrator. Sign the exact EIP-712 type below using the `KuruAccountCore` version `1`, with the configured AccountCore proxy as `verifyingContract` and the selected chain ID (`143` mainnet; `10143` testnet): ```text theme={null} CreateSubaccount(address rootOwner,address authorizer,uint16 subaccountSeq,uint256 authNonce,uint256 deadline) ``` ```curl cURL theme={null} curl --request POST --url https://relay.testnet.kuru.io/relay \ --header "Authorization: Bearer $KURU_RELAY_JWT" \ --header 'Content-Type: application/json' \ --data '{"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","method":"account_core.create_subaccount_by_sig","wallet":"0x1111111111111111111111111111111111111111","payload":{"rootOwner":"0x3333333333333333333333333333333333333333","authorizer":"0x3333333333333333333333333333333333333333","subaccountSeq":"2","authNonce":"1","deadline":"1792500000","signature":"0x..."}}' ``` ```json BROADCAST theme={null} {"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","status":"BROADCAST","txHash":"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","sponsorAddress":"0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","sponsorNonce":"42","transactionType":"DYNAMIC_FEE"} ``` `BROADCAST` means scheduling for asynchronous RPC broadcast, not provider acceptance or successful execution. Check the receipt and expected events/state. A failed estimate returns an immediate error with no transaction signed or broadcast. # Store TWAP instruction Source: https://docs.kuru.io/api/relay/reference/create-twap POST /relay Store a TWAP instruction through opt-in Relay; automated slice execution is not implemented. Submits `wallet.create_twap` when this method is enabled for the selected deployment. This is a **slow operational method**, not the low-latency trading path. Relay validates the typed request and signature where applicable, simulates the exact call against `latest`, and only then queues a sponsored transaction. See [Operational methods](/api/relay/operational) for availability, gas, and latency rules. > [!NOTE] > > The example uses testnet WETH/USDC where a market is required, but all identities, nonces, timestamps, hashes, and signatures are illustrative. Read current state and build a fresh valid signature for the selected network. Omit `authorization7702` and `makerSlotsPrimed`; complete delegation first. **requestId** `string` *required* New lowercase UUIDv7 for request correlation. **method** `string` *required* (default: wallet.create_twap) Must be `wallet.create_twap`. **wallet** `string` *required* Trading wallet matching the bearer JWT; for AccountCore operations this is the sponsoring frontend identity, not necessarily the signed authorizer. **payload** `object` *required* Method-specific payload shown below; unknown fields are rejected. > [!WARNING] > > Automated TWAP execution is **not implemented** and remains work in progress. This method only stores an instruction where enabled; no service schedules or submits slices. **Storage only:** Relay creates an on-chain instruction but does not monitor or execute slices. `totalQuantity` must divide evenly by a positive `sliceCount`; `intervalSeconds` is positive, `startTime` is future Unix seconds, and the computed end must fit the configured horizon. Quantity and price use native market precision. Creation uses the wallet's one-shot trigger/TWAP nonce namespace, not `lastSeenOrderNonce`; WebSocket submissions still follow connection-level increasing nonce ordering. Sign the exact EIP-712 type below using the `KuruTradingWallet` version `2`, with the delegated trading wallet as `verifyingContract` and the selected chain ID (`143` mainnet; `10143` testnet): ```text theme={null} CreateTwapIntent(uint40 accountId,address market,uint256 authNonce,uint64 nonce,uint64 deadline,bytes32 clientOrderId,address builder,uint32 builderFeePps,uint8 side,uint96 totalQuantity,uint32 limitPrice,uint64 startTime,uint32 intervalSeconds,uint32 sliceCount) ``` ```curl cURL theme={null} curl --request POST --url https://relay.testnet.kuru.io/relay \ --header "Authorization: Bearer $KURU_RELAY_JWT" \ --header 'Content-Type: application/json' \ --data '{"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","method":"wallet.create_twap","wallet":"0x1111111111111111111111111111111111111111","payload":{"header":{"accountId":"123","market":"0x0A082280e4eA3D822E23Ec1186685477241A039d","authNonce":"1","nonce":"1792480000001","deadline":"1792500000","clientOrderId":"0x0000000000000000000000000000000000000000000000000000000000000001","builder":"0x0000000000000000000000000000000000000000","builderFeePps":"0"},"config":{"side":"BUY","totalQuantity":"10000000000","limitPrice":"30000000","startTime":"1792500300","intervalSeconds":"60","sliceCount":"10"},"signature":"0x..."}}' ``` ```json BROADCAST theme={null} {"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","status":"BROADCAST","txHash":"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","sponsorAddress":"0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","sponsorNonce":"42","transactionType":"DYNAMIC_FEE"} ``` `BROADCAST` means scheduling for asynchronous RPC broadcast, not provider acceptance or successful execution. Check the receipt and expected events/state. A failed estimate returns an immediate error with no transaction signed or broadcast. # Exchange challenge for token Source: https://docs.kuru.io/api/relay/reference/exchange-token api/relay/openapi.yaml POST /auth/token Exchange a signed challenge for a short-lived wallet-bound JWT. Public endpoint. No JWT or `Authorization` header is required. It verifies the wallet's signed challenge, consumes the challenge, and returns a wallet-bound bearer token. A challenge succeeds at most once. Include optional `uid` to request a verified account-scoped JWT for the [account rate tier](/api/relay/rate-limits); leaving it out retains wallet-only login and the wallet-based rate tier. `POST /auth/challenge` is unchanged. **challengeId** `string` *required* Lowercase 32-character challenge ID returned by `POST /auth/challenge`. **signature** `string` *required* Canonical low-s, 65-byte EOA personal-sign signature. The recovery byte may be `0`/`1` or `27`/`28`. **uid** `string` Optional trading account ID as a positive canonical uint40 decimal **string**, for example `"10"`. Relay verifies the challenge wallet's current trading permission for this exact account and resolves its root. Use the child ID when trading a subaccount; do not supply a client-chosen root ID. A denied grant returns `AUTHENTICATION_FAILED`; an unavailable account read returns retryable `AUTHENTICATION_UNAVAILABLE`. ```curl cURL theme={null} curl --request POST \ --url https://relay.mainnet.kuru.io/auth/token \ --header 'Content-Type: application/json' \ --data '{"challengeId":"8c4a11c6eb574d16972fac2a8c85a6dc","signature":"0x<65-byte-signature>","uid":"10"}' ``` **accessToken** `string` *required* Short-lived wallet-bound JWT. Treat it as a secret and never log it. **tokenType** `string` *required* Always `Bearer`. **expiresAt** `string` *required* Token expiration as an ISO 8601 timestamp. Testnet tokens last one hour. **wallet** `string` *required* Address to which the JWT is bound. The response fields are unchanged for scoped login. The signed JWT additionally contains `kuru_account` with string fields `uid`, `root_uid`, `chain_id`, and `account_core`. Do not read the quota or root ID from untrusted request input. A scoped token is bound to one trading account: the signed `header.accountId` and required WebSocket `account_id` must match its `uid`. Re-login with `uid` to migrate an existing token; changing a submission alone does not scope it. Token issuance does not register the account or grant on-chain permission. ```json 200 theme={null} { "accessToken": "", "tokenType": "Bearer", "expiresAt": "2026-08-27T11:00:00Z", "wallet": "0x1111111111111111111111111111111111111111" } ``` ```json 503 theme={null} { "code": "AUTHENTICATION_UNAVAILABLE", "message": "account authorization unavailable", "retryable": true, "retryAfterMs": 1000 } ``` ```json 401 theme={null} { "code": "AUTHENTICATION_FAILED", "message": "authentication failed", "retryable": false } ``` # Execute order batch Source: https://docs.kuru.io/api/relay/reference/execute-batch POST /relay Place readable native orders, cancel maker slots, or perform both atomically. Submits `wallet.execute_batch`. Use this method for normal order entry and cancellation integrations. > [!NOTE] > > The example uses the verified mainnet WETHUSDC market, but its wallet, nonce, deadline, account ID, and signature are placeholders. Build and sign a fresh intent for the selected network before submitting. **requestId** `string` *required* New lowercase UUIDv7 for correlation. **method** `string` *required* (default: wallet.execute_batch) Must be `wallet.execute_batch`. **wallet** `string` *required* Secondary trading EOA matching the bearer JWT. **payload** `object` *required* Signed `BatchIntent` containing `header`, `orders`, `cancelSlotIdxs`, `expectedOrderIds`, and `signature`. **authorization7702** `object | null` Normally `null` after onboarding. The header requires `accountId`, `market`, `authNonce`, increasing `nonce`, Unix-second `deadline`, 32-byte `clientOrderId`, `builder`, and `builderFeePps`. Every integer is a canonical unsigned decimal string. For the [verified-account rate tier](/api/relay/rate-limits), first obtain a JWT with `uid` at `POST /auth/token`; the signed `header.accountId` must equal that verified `uid`. An unscoped wallet JWT still works but uses the wallet-based quota. Do not add `uid` to this submission envelope. Sign `BatchIntent` with the `KuruTradingWallet` EIP-712 domain: version `2`, chain ID `143` on mainnet or `10143` on testnet, and the **delegated trading EOA** as `verifyingContract` (not the shared implementation or Relay address). Version-`1` wallet signatures are invalid for the current implementation; rebuild and re-sign any pending intents created with that domain. AccountCore signer grants use their separate `KuruAccountCore` version-`1` domain. See [Trading-wallet Signing](/sdk/trading-wallet). Each native order requires `side` (`BUY`/`SELL`), `quantity`, `price`, `tif` (`GTC`/`IOC`/`FOK`), `executionInstruction` (`NONE`/`POST_ONLY`), and `minSizeAfterBlock`. Post-only requires GTC. ```curl cURL theme={null} curl --request POST --url https://relay.mainnet.kuru.io/relay \ --header "Authorization: Bearer $KURU_RELAY_JWT" \ --header 'Content-Type: application/json' \ --data '{ "requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f", "method":"wallet.execute_batch", "wallet":"0x1111111111111111111111111111111111111111", "payload":{ "header":{"accountId":"123","market":"0x8121ee960066e4344a213f9ac7502395502aee7a","authNonce":"1","nonce":"1720000000123","deadline":"1720000030","clientOrderId":"0x0000000000000000000000000000000000000000000000000000000000000001","builder":"0x0000000000000000000000000000000000000000","builderFeePps":"0"}, "orders":[{"side":"BUY","quantity":"1000000","price":"123400","tif":"GTC","executionInstruction":"POST_ONLY","minSizeAfterBlock":"0"}], "cancelSlotIdxs":[],"expectedOrderIds":[],"signature":"0x..." }, "authorization7702":null }' ``` Up to 256 orders and 62 unique cancellations are accepted. `expectedOrderIds` must be parallel to `cancelSlotIdxs`; bind cancellations to current order IDs whenever possible. ```json BROADCAST theme={null} { "requestId": "018f5ef2-88a1-7b41-a826-4b679010f87f", "status": "BROADCAST", "txHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "sponsorAddress": "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "sponsorNonce": "42", "transactionType": "DYNAMIC_FEE" } ``` # Cancel all orders in a market Source: https://docs.kuru.io/api/relay/reference/execute-cancel-all POST /relay Submit wallet.execute_cancel_all through the opt-in Relay operational path. Submits `wallet.execute_cancel_all` when this method is enabled for the selected deployment. This is a **slow operational method**, not the low-latency trading path. Relay validates the typed request and signature where applicable, simulates the exact call against `latest`, and only then queues a sponsored transaction. See [Operational methods](/api/relay/operational) for availability, gas, and latency rules. > [!NOTE] > > The example uses testnet WETH/USDC where a market is required, but all identities, nonces, timestamps, hashes, and signatures are illustrative. Read current state and build a fresh valid signature for the selected network. Omit `authorization7702` and `makerSlotsPrimed`; complete delegation first. **requestId** `string` *required* New lowercase UUIDv7 for request correlation. **method** `string` *required* (default: wallet.execute_cancel_all) Must be `wallet.execute_cancel_all`. **wallet** `string` *required* Trading wallet matching the bearer JWT; for AccountCore operations this is the sponsoring frontend identity, not necessarily the signed authorizer. **payload** `object` *required* Method-specific payload shown below; unknown fields are rejected. This cancels live resting orders for the **signed account and market** at execution time, including orders placed after signing. It does not cancel other markets, triggers, TWAP instructions, or passive positions. Cancellation requires the zero builder and fee shown. Sign the exact EIP-712 type below using the `KuruTradingWallet` version `2`, with the delegated trading wallet as `verifyingContract` and the selected chain ID (`143` mainnet; `10143` testnet): ```text theme={null} CancelAllIntent(uint40 accountId,address market,uint256 authNonce,uint64 nonce,uint64 deadline,bytes32 clientOrderId,address builder,uint32 builderFeePps) ``` ```curl cURL theme={null} curl --request POST --url https://relay.testnet.kuru.io/relay \ --header "Authorization: Bearer $KURU_RELAY_JWT" \ --header 'Content-Type: application/json' \ --data '{"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","method":"wallet.execute_cancel_all","wallet":"0x1111111111111111111111111111111111111111","payload":{"header":{"accountId":"123","market":"0x0A082280e4eA3D822E23Ec1186685477241A039d","authNonce":"1","nonce":"1792480000001","deadline":"1792500000","clientOrderId":"0x0000000000000000000000000000000000000000000000000000000000000001","builder":"0x0000000000000000000000000000000000000000","builderFeePps":"0"},"signature":"0x..."}}' ``` ```json BROADCAST theme={null} {"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","status":"BROADCAST","txHash":"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","sponsorAddress":"0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","sponsorNonce":"42","transactionType":"DYNAMIC_FEE"} ``` `BROADCAST` means scheduling for asynchronous RPC broadcast, not provider acceptance or successful execution. Check the receipt and expected events/state. A failed estimate returns an immediate error with no transaction signed or broadcast. # Cancel orders by ID Source: https://docs.kuru.io/api/relay/reference/execute-cancel-orders-by-id POST /relay Submit wallet.execute_cancel_orders_by_id through the opt-in Relay operational path. Submits `wallet.execute_cancel_orders_by_id` when this method is enabled for the selected deployment. This is a **slow operational method**, not the low-latency trading path. Relay validates the typed request and signature where applicable, simulates the exact call against `latest`, and only then queues a sponsored transaction. See [Operational methods](/api/relay/operational) for availability, gas, and latency rules. > [!NOTE] > > The example uses testnet WETH/USDC where a market is required, but all identities, nonces, timestamps, hashes, and signatures are illustrative. Read current state and build a fresh valid signature for the selected network. Omit `authorization7702` and `makerSlotsPrimed`; complete delegation first. **requestId** `string` *required* New lowercase UUIDv7 for request correlation. **method** `string` *required* (default: wallet.execute_cancel_orders_by_id) Must be `wallet.execute_cancel_orders_by_id`. **wallet** `string` *required* Trading wallet matching the bearer JWT; for AccountCore operations this is the sponsoring frontend identity, not necessarily the signed authorizer. **payload** `object` *required* Method-specific payload shown below; unknown fields are rejected. Provide 1–62 distinct, nonzero uint64 order IDs. Sign `orderIdsHash = keccak256(abi.encode(uint64[] orderIds))`, including the ABI offset and length; packed encoding is wrong. Cancellation requires the zero builder and zero fee shown. A stale or invalid order can revert the whole operation. Sign the exact EIP-712 type below using the `KuruTradingWallet` version `2`, with the delegated trading wallet as `verifyingContract` and the selected chain ID (`143` mainnet; `10143` testnet): ```text theme={null} CancelOrdersByIdIntent(uint40 accountId,address market,uint256 authNonce,uint64 nonce,uint64 deadline,bytes32 clientOrderId,address builder,uint32 builderFeePps,bytes32 orderIdsHash) ``` ```curl cURL theme={null} curl --request POST --url https://relay.testnet.kuru.io/relay \ --header "Authorization: Bearer $KURU_RELAY_JWT" \ --header 'Content-Type: application/json' \ --data '{"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","method":"wallet.execute_cancel_orders_by_id","wallet":"0x1111111111111111111111111111111111111111","payload":{"header":{"accountId":"123","market":"0x0A082280e4eA3D822E23Ec1186685477241A039d","authNonce":"1","nonce":"1792480000001","deadline":"1792500000","clientOrderId":"0x0000000000000000000000000000000000000000000000000000000000000001","builder":"0x0000000000000000000000000000000000000000","builderFeePps":"0"},"orderIds":["31","32"],"signature":"0x..."}}' ``` ```json BROADCAST theme={null} {"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","status":"BROADCAST","txHash":"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","sponsorAddress":"0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","sponsorNonce":"42","transactionType":"DYNAMIC_FEE"} ``` `BROADCAST` means scheduling for asynchronous RPC broadcast, not provider acceptance or successful execution. Check the receipt and expected events/state. A failed estimate returns an immediate error with no transaction signed or broadcast. # Execute FOK swap Source: https://docs.kuru.io/api/relay/reference/execute-fok-swap POST /relay Submit wallet.execute_fok_swap through the opt-in Relay operational path. Submits `wallet.execute_fok_swap` when this method is enabled for the selected deployment. This is a **slow operational method**, not the low-latency trading path. Relay validates the typed request and signature where applicable, simulates the exact call against `latest`, and only then queues a sponsored transaction. See [Operational methods](/api/relay/operational) for availability, gas, and latency rules. > [!NOTE] > > The example uses testnet WETH/USDC where a market is required, but all identities, nonces, timestamps, hashes, and signatures are illustrative. Read current state and build a fresh valid signature for the selected network. Omit `authorization7702` and `makerSlotsPrimed`; complete delegation first. **requestId** `string` *required* New lowercase UUIDv7 for request correlation. **method** `string` *required* (default: wallet.execute_fok_swap) Must be `wallet.execute_fok_swap`. **wallet** `string` *required* Trading wallet matching the bearer JWT; for AccountCore operations this is the sponsoring frontend identity, not necessarily the signed authorizer. **payload** `object` *required* Method-specific payload shown below; unknown fields are rejected. `order.quantity` is base size and `order.limitPrice` is a protection bound, both in native market precision. The full quantity must fill or execution reverts. This is a base-quantity marketable limit order, not an exact-input swap. Resting-order min/max notional checks do not apply to this FOK request, matching batch FOK policy. For latency-sensitive FOK, use the existing fast `wallet.execute_batch` path. Sign the exact EIP-712 type below using the `KuruTradingWallet` version `2`, with the delegated trading wallet as `verifyingContract` and the selected chain ID (`143` mainnet; `10143` testnet): ```text theme={null} FokSwapIntent(uint40 accountId,address market,uint256 authNonce,uint64 nonce,uint64 deadline,bytes32 clientOrderId,address builder,uint32 builderFeePps,uint8 side,uint96 quantity,uint32 limitPrice) ``` ```curl cURL theme={null} curl --request POST --url https://relay.testnet.kuru.io/relay \ --header "Authorization: Bearer $KURU_RELAY_JWT" \ --header 'Content-Type: application/json' \ --data '{"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","method":"wallet.execute_fok_swap","wallet":"0x1111111111111111111111111111111111111111","payload":{"header":{"accountId":"123","market":"0x0A082280e4eA3D822E23Ec1186685477241A039d","authNonce":"1","nonce":"1792480000001","deadline":"1792500000","clientOrderId":"0x0000000000000000000000000000000000000000000000000000000000000001","builder":"0x0000000000000000000000000000000000000000","builderFeePps":"0"},"order":{"side":"BUY","quantity":"10000000000","limitPrice":"30000000"},"signature":"0x..."}}' ``` ```json BROADCAST theme={null} {"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","status":"BROADCAST","txHash":"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","sponsorAddress":"0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","sponsorNonce":"42","transactionType":"DYNAMIC_FEE"} ``` `BROADCAST` means scheduling for asynchronous RPC broadcast, not provider acceptance or successful execution. Check the receipt and expected events/state. A failed estimate returns an immediate error with no transaction signed or broadcast. # Execute packed slot replacement Source: https://docs.kuru.io/api/relay/reference/execute-replace-by-slot POST /relay Execute compact 32-byte maker-slot operations. Submits `wallet.execute_replace_by_slot_packed` for clients that implement Kuru's compact slot-operation codec. For the [verified-account rate tier](/api/relay/rate-limits), obtain a JWT with `uid` at `POST /auth/token`; the signed `header.accountId` must equal that verified `uid`. A wallet-only JWT remains valid at the wallet-based quota. Do not add `uid` to the signed payload or REST envelope. > [!NOTE] > > The example uses the verified mainnet WETHUSDC market, but its wallet, nonce, deadline, account ID, packed operations, and signature are placeholders. Build and sign a fresh intent for the selected network before submitting. **requestId** `string` *required* New lowercase UUIDv7 for correlation. **method** `string` *required* (default: wallet.execute_replace_by_slot_packed) Must be `wallet.execute_replace_by_slot_packed`. **wallet** `string` *required* Secondary trading EOA matching the bearer JWT. **payload** `object` *required* Signed `ReplaceBySlotIntent` containing `header`, `packedOps`, `expectedOrderIds`, and `signature`. **authorization7702** `object | null` Normally `null` after onboarding. `packedOps` contains one to 256 canonical 32-byte words. `expectedOrderIds` must contain one uint64 decimal string per word, and target slots must be unique. Sign `ReplaceBySlotIntent` with the `KuruTradingWallet` EIP-712 domain: version `2`, chain ID `143` on mainnet or `10143` on testnet, and the **delegated trading EOA** as `verifyingContract` (not the shared implementation or Relay address). Version-`1` wallet signatures are invalid for the current implementation; rebuild and re-sign pending intents rather than resubmitting them. AccountCore signer grants use their separate `KuruAccountCore` version-`1` domain. See [Trading-wallet Signing](/sdk/trading-wallet). ### Slot binding and planning-time checks Relay checks each slot binding while planning the request, before the transaction enters the signer queue. This check reads the Relay's currently observed proposed state; it does not wait for finalization or for preceding transactions to become visible. For every packed operation, `expectedOrderIds` controls what Relay is allowed to replace: | Value | Required slot state | | - | - | | `0` | The slot must be empty | | A specific order ID | The slot must contain that exact order | | `18446744073709551615` | Accept whichever order currently occupies the slot (wildcard) | If a replacement is signed with `0` while the preceding placement is already present in proposed state, Relay rejects it because the slot is no longer empty. If it is signed with the new order ID while Relay still observes an empty slot, upstream-state lag can produce the inverse rejection. The error alone does not distinguish these cases. The signer-ordering guarantee preserves handoff order, but it does not make concurrent planning observe preceding transactions. For continuous slot replacement, use the wildcard value when “replace whatever currently occupies this slot” is the intended behavior; this avoids waiting to learn the preceding order ID. Use exact IDs only when the corresponding proposed state has been observed first. ```curl cURL theme={null} curl --request POST --url https://relay.mainnet.kuru.io/relay \ --header "Authorization: Bearer $KURU_RELAY_JWT" \ --header 'Content-Type: application/json' \ --data '{ "requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f", "method":"wallet.execute_replace_by_slot_packed", "wallet":"0x1111111111111111111111111111111111111111", "payload":{"header":{"accountId":"123","market":"0x8121ee960066e4344a213f9ac7502395502aee7a","authNonce":"1","nonce":"1720000000124","deadline":"1720000030","clientOrderId":"0x0000000000000000000000000000000000000000000000000000000000000002","builder":"0x0000000000000000000000000000000000000000","builderFeePps":"0"},"packedOps":"0x","expectedOrderIds":["31"],"signature":"0x..."}, "authorization7702":null }' ``` The signature binds `keccak256(packedOps)` and the Solidity ABI hash of `expectedOrderIds`. ```json BROADCAST theme={null} { "requestId": "018f5ef2-88a1-7b41-a826-4b679010f87f", "status": "BROADCAST", "txHash": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "sponsorAddress": "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "sponsorNonce": "43", "transactionType": "DYNAMIC_FEE" } ``` # Finalize expired TWAP Source: https://docs.kuru.io/api/relay/reference/finalize-twap POST /relay Submit wallet.finalize_twap through the opt-in Relay operational path. Submits `wallet.finalize_twap` when this method is enabled for the selected deployment. This is a **slow operational method**, not the low-latency trading path. Relay validates the typed request and signature where applicable, simulates the exact call against `latest`, and only then queues a sponsored transaction. See [Operational methods](/api/relay/operational) for availability, gas, and latency rules. > [!NOTE] > > The example uses testnet WETH/USDC where a market is required, but all identities, nonces, timestamps, hashes, and signatures are illustrative. Read current state and build a fresh valid signature for the selected network. Omit `authorization7702` and `makerSlotsPrimed`; complete delegation first. **requestId** `string` *required* New lowercase UUIDv7 for request correlation. **method** `string` *required* (default: wallet.finalize_twap) Must be `wallet.finalize_twap`. **wallet** `string` *required* Trading wallet matching the bearer JWT; for AccountCore operations this is the sponsoring frontend identity, not necessarily the signed authorizer. **payload** `object` *required* Method-specific payload shown below; unknown fields are rejected. The contract operation is permissionless, but Relay targets only the JWT-bound trading wallet. Supply only `twapId`; there is no client signature, nonce, deadline, account, market, or arbitrary target in this payload. An ACTIVE TWAP must have passed its end time. Finalization records skipped slices and FINISHED state; it does not execute slices, cancel orders, or move funds. This headerless method uses the [wallet-based sponsorship quota](/api/relay/rate-limits), even with an account-scoped JWT. No EIP-712 signature is required for this permissionless contract finalization. The bearer JWT still identifies the Relay client. ```curl cURL theme={null} curl --request POST --url https://relay.testnet.kuru.io/relay \ --header "Authorization: Bearer $KURU_RELAY_JWT" \ --header 'Content-Type: application/json' \ --data '{"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","method":"wallet.finalize_twap","wallet":"0x1111111111111111111111111111111111111111","payload":{"twapId":"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}' ``` ```json BROADCAST theme={null} {"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","status":"BROADCAST","txHash":"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","sponsorAddress":"0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","sponsorNonce":"42","transactionType":"DYNAMIC_FEE"} ``` `BROADCAST` means scheduling for asynchronous RPC broadcast, not provider acceptance or successful execution. Check the receipt and expected events/state. A failed estimate returns an immediate error with no transaction signed or broadcast. # Revoke account signer Source: https://docs.kuru.io/api/relay/reference/revoke-account-signer POST /relay Submit account_core.revoke_account_signer_by_sig through the opt-in Relay operational path. Submits `account_core.revoke_account_signer_by_sig` when this method is enabled for the selected deployment. This is a **slow operational method**, not the low-latency trading path. Relay validates the typed request and signature where applicable, simulates the exact call against `latest`, and only then queues a sponsored transaction. See [Operational methods](/api/relay/operational) for availability, gas, and latency rules. > [!NOTE] > > The example uses testnet WETH/USDC where a market is required, but all identities, nonces, timestamps, hashes, and signatures are illustrative. Read current state and build a fresh valid signature for the selected network. Omit `authorization7702` and `makerSlotsPrimed`; complete delegation first. **requestId** `string` *required* New lowercase UUIDv7 for request correlation. **method** `string` *required* (default: account_core.revoke_account_signer_by_sig) Must be `account_core.revoke_account_signer_by_sig`. **wallet** `string` *required* Trading wallet matching the bearer JWT; for AccountCore operations this is the sponsoring frontend identity, not necessarily the signed authorizer. **payload** `object` *required* Method-specific payload shown below; unknown fields are rejected. The root owner or an ADMIN-authorized EOA signs this AccountCore intent. `nonce` is the current root authorization epoch read from AccountCore, **not** a millisecond trading nonce. Successful revocation advances the epoch and invalidates previously signed trading intents. The frontend trading wallet supplies the JWT; it need not equal `authorizer`, `account`, or the revoked `signer`. This headerless operation uses the [wallet-based sponsorship quota](/api/relay/rate-limits), even with an account-scoped JWT. The JWT wallet need not be the signed owner or administrator. Sign the exact EIP-712 type below using the `KuruAccountCore` version `1`, with the configured AccountCore proxy as `verifyingContract` and the selected chain ID (`143` mainnet; `10143` testnet): ```text theme={null} RevokeAccountSigner(address account,address authorizer,address signer,uint256 nonce,uint256 deadline) ``` ```curl cURL theme={null} curl --request POST --url https://relay.testnet.kuru.io/relay \ --header "Authorization: Bearer $KURU_RELAY_JWT" \ --header 'Content-Type: application/json' \ --data '{"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","method":"account_core.revoke_account_signer_by_sig","wallet":"0x1111111111111111111111111111111111111111","payload":{"account":"0x3333333333333333333333333333333333333333","authorizer":"0x3333333333333333333333333333333333333333","signer":"0x1111111111111111111111111111111111111111","nonce":"1","deadline":"1792500000","signature":"0x..."}}' ``` ```json BROADCAST theme={null} {"requestId":"018f5ef2-88a1-7b41-a826-4b679010f87f","status":"BROADCAST","txHash":"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","sponsorAddress":"0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","sponsorNonce":"42","transactionType":"DYNAMIC_FEE"} ``` `BROADCAST` means scheduling for asynchronous RPC broadcast, not provider acceptance or successful execution. Check the receipt and expected events/state. A failed estimate returns an immediate error with no transaction signed or broadcast. # Relay Source: https://docs.kuru.io/api/relay/rest Gas sponsorship for Kuru account and trading actions. Kuru Relay sponsors gas for Kuru accounts. For most methods, an authorized EOA signs an AccountCore or trading-wallet action; Relay validates the intent, constructs the expected calldata, pays the outer transaction's gas, and schedules broadcast. The opt-in `wallet.finalize_twap` operation is a permissionless contract action without a client signature. ```text theme={null} Mainnet REST (playground default): https://relay.mainnet.kuru.io Mainnet WebSocket: wss://relay.mainnet.kuru.io/relay/ws?account_id= Testnet REST: https://relay.testnet.kuru.io Testnet WebSocket: wss://relay.testnet.kuru.io/relay/ws?account_id= ``` Select testnet in the REST playground's server dropdown when testing there. **Mainnet Relay submissions can broadcast real transactions.** Confirm the selected host, chain ID, market, signer authorization, wallet-bound JWT, and signed payload before submitting. Switching servers never re-signs an intent or exchanges a JWT between networks. Copyable cURL templates can contain a hard-coded host and illustrative fields; selecting a different playground server does not rewrite them. Request payloads containing placeholder signatures are illustrations, not executable signed actions. The sponsor cannot create or change a user's signed action. It only submits supported account and trading operations so the secondary trading wallet does not need to hold native gas tokens. Authenticate the trading wallet with the two public endpoints below, then use either the REST or WebSocket method references. See [Relay rate limits and migration](/api/relay/rate-limits) for the scheduled November 4 cutover, scoped login, and effective quotas. See [Relay errors and outcomes](/api/relay/errors) for stable error codes, retry guidance, and WebSocket transaction-outcome delivery. Read [Relay security and operating model](/api/relay/security) before deploying a signer. > [!NOTE] > > Using the TypeScript SDK? Follow [Trading-wallet signing](/sdk/trading-wallet) > and [Relay](/sdk/relay). Their testnet examples use Monad chain ID `10143`. ## Authentication The two authentication endpoints are public POST APIs. They do not require a JWT. > [card] [Create challenge](/api/relay/reference/create-challenge) > > Public endpoint that creates the exact message a secondary trading EOA must > sign. > [card] [Exchange token](/api/relay/reference/exchange-token) > > Public endpoint that verifies the signed challenge and returns a > wallet-bound JWT. Request a challenge for the secondary EOA, sign the exact returned UTF-8 message with Ethereum `personal_sign`, and exchange that signature for a short-lived JWT. Challenges expire after five minutes and can be consumed only once. Use the returned `expiresAt` rather than assuming the same JWT lifetime on both networks. For the verified-account rate tier, include the optional canonical decimal-string `uid` in **`POST /auth/token` only**; Relay checks the wallet's trading authority and issues a token scoped to that account. Without `uid`, login still works but the token uses the wallet-based rate tier. See the [migration guide](/api/relay/rate-limits). ## Rate limits The configured verified-account defaults are 250 requests/second with a 250-request burst for the root and separately for each root–market pair, subject to additional IP, identity, method, and WebSocket caps. These are per-replica limits, not guaranteed throughput. **At the scheduled November 4, 2026 noon EST cutover, the unscoped per-wallet sustained allowance will become 1 request/second**, including for wallet-only JWTs issued before cutover. There is no grace period or grandfathering; existing tokens remain valid at the lower tier. The post-cutover burst has not been announced. Read [Relay Rate Limits and Migration](/api/relay/rate-limits) before changing login or retry behavior. The JWT authenticates Relay access only. It does not grant AccountCore permission, install EIP-7702 delegation, replace method-specific signatures, or revoke on-chain rights when it expires. ## Enabled REST methods > [card] [Authorize account signer](/api/relay/reference/authorize-account-signer) > > Grant AccountCore permission and optionally install EIP-7702 delegation. > [card] [Execute order batch](/api/relay/reference/execute-batch) > > Place readable native orders, cancel slots, or perform both atomically. > [card] [Execute packed replacement](/api/relay/reference/execute-replace-by-slot) > > Submit compact 32-byte maker-slot operations. > [card] [Cancel conditional order](/api/relay/reference/cancel-trigger) > > Cancel an active trigger with a signed one-shot nonce. ## Opt-in operational methods These slow, simulation-first methods are available only where explicitly enabled. They do not replace the fast batch/packed trading path; FOK trigger and TWAP creation only **store** instructions, with no condition monitor or slice scheduler. Read the [operational-methods overview](/api/relay/operational) before integration. > [!WARNING] > > TP/SL and other automated triggers, as well as TWAP execution, are **not implemented** as live features. They are work in progress; storage-only methods do not provide automated execution. > [card] [Cancel orders by ID](/api/relay/reference/execute-cancel-orders-by-id) > > Cancel explicit order IDs. > [card] [Cancel all in market](/api/relay/reference/execute-cancel-all) > > Cancel one account's resting orders in one market. > [card] [FOK swap](/api/relay/reference/execute-fok-swap) > > Execute the full base quantity or revert. > [card] [Store FOK trigger](/api/relay/reference/create-fok-swap-trigger) > > Persist a conditional FOK instruction only. > [card] [Store TWAP](/api/relay/reference/create-twap) > > Persist a schedule only. > [card] [Cancel TWAP](/api/relay/reference/cancel-twap) > > Cancel a signed stored schedule. > [card] [Finalize TWAP](/api/relay/reference/finalize-twap) > > Record expiry; no slices are run. > [card] [Revoke account signer](/api/relay/reference/revoke-account-signer) > > Revoke with a separate AccountCore authorizer signature. > [card] [Create subaccount](/api/relay/reference/create-subaccount) > > Create the next child sequence by signature. ## Conditional actions — coming soon > [card] [Create batch trigger](/api/relay/reference/create-batch-trigger) > > Inspect the conditional native-order batch contract. > [card] [Create packed trigger](/api/relay/reference/create-replace-trigger) > > Inspect the conditional packed-replacement contract. ## WebSocket For sessions that submit many actions, connect once and send the same typed methods over a wallet-bound WebSocket. ```http theme={null} GET /relay/ws?account_id=123 HTTP/1.1 Host: relay.mainnet.kuru.io Upgrade: websocket Connection: Upgrade Authorization: Bearer ``` The JWT binds the connection to one secondary EOA, so messages omit REST's `wallet` field and replace `requestId` with a connection-local `id`. Open a separate connection for each wallet. The required `account_id` is the **Kuru trading account ID**, not the signer address. It binds exchange-state context; it does not replace JWT authentication or on-chain trading authorization. Supply exactly one positive `uint40` in canonical decimal form (for example, `123`): no leading zero, sign, or whitespace. A missing or invalid value fails the upgrade with HTTP 400 `canonical account_id is required`. For a scoped JWT, `account_id` must equal the token's verified `uid` or the upgrade fails with HTTP 401; signed trading `header.accountId` must match as well. A headerless method can still be sent on such a connection but uses the wallet-based quota. > [!NOTE] > > The WebSocket reference renders typed messages and network selection, but its browser viewer cannot open Relay's authenticated connection because the upgrade requires an `Authorization` header. Use a WebSocket client that supports custom upgrade headers to send live Relay messages. The [TypeScript SDK Relay client](/sdk/relay) currently uses REST, not this WebSocket API. Do not put JWTs in a URL query string. > [card] [Authorize account signer](/api/relay/websocket-reference/authorize-account-signer) > > Grant AccountCore trading permission. > [card] [Execute order batch](/api/relay/websocket-reference/execute-batch) > > Place orders and cancel slots. > [card] [Execute packed replacement](/api/relay/websocket-reference/execute-replace-by-slot) > > Submit compact maker-slot operations. > [card] [Cancel conditional order](/api/relay/websocket-reference/cancel-trigger) > > Cancel an active trigger. > [card] [Create batch trigger](/api/relay/websocket-reference/create-batch-trigger) > > Defined for reference but not a supported live Relay flow. > [card] [Create packed trigger](/api/relay/websocket-reference/create-replace-trigger) > > Defined for reference but not a supported live Relay flow. > [card] [Subscribe to transaction](/api/relay/websocket-reference/transaction-subscribe) > > Recover a known transaction after reconnecting. > [card] [Transaction outcome](/api/relay/websocket-reference/transaction-outcome) > > Read the terminal result delivered for a WebSocket submission. The nine opt-in operational methods also have WebSocket references in the sidebar. Their request payloads are the same as REST; the authenticated connection supplies `wallet` identity and each message uses a connection-local `id` instead of a REST `requestId`. Several messages may be in flight. Each accepted `id` receives one correlated immediate response. Immediate wallet-intent nonces must increase within a connection. A `BROADCAST` response includes the server-assigned `requestId`, sponsor nonce, and transaction hash, but it is not a terminal outcome or proof that an RPC accepted the transaction. Relay automatically delivers `transaction.outcome` on that same connection with `type: "transaction.outcome"`, the original client `id`, `requestId`, and `txHash`. Terminal statuses are `CONFIRMED`, `REVERTED`, `REPLACED`, and `UNKNOWN`. **You do not need to subscribe to your own new submission or acknowledge its outcome.** Use `transaction.subscribe` mainly after reconnecting with a known `requestId` and `txHash`. The current Relay configuration tracks at most **64 pending transaction outcomes per client WebSocket connection**. This is a configurable outstanding-outcome limit, **not** a lifetime limit of 64 submissions, a sponsor-nonce limit, or the separate in-flight-request limit. Tracking ends when a terminal outcome is processed for delivery; no client acknowledgement is needed. Immediate submission rejections do not take an outcome slot. If all slots are occupied, Relay may close the socket while registering another outcome **after** writing its `BROADCAST` response. Closing the socket does not undo the scheduled broadcast or prove the transaction failed. Bound outstanding submissions below the limit and retain each `requestId` and `txHash` for recovery. The signer retains the latest **4,096 terminal outcomes per signer**, shared across users. This is count-based, not a time guarantee; do not assume replay survives a signer restart. On reconnect, establish a new wallet-bound session and reconcile unresolved transactions by their existing identities. If the connection fell before `requestId` and `txHash` arrived, the old WS `id` cannot recover the submission across connections. Use a unique signed batch-level `payload.header.clientOrderId` and paginated [order events](/api/data-source/reference/order-events) as one reconciliation signal; absence of a match does not prove failure. Keep recovery bounded and asynchronous so receipt or log queries do not block new submissions for tens of seconds. Relay does not impose a 50-second reconnect backoff; a long pause of that kind can arise in the client connector's reconciliation path. See [Relay errors and outcomes](/api/relay/errors#websocket-transaction-outcomes) for the full outcome and recovery limits. ## Shared request rules Every `POST /relay` request includes a lowercase UUIDv7 `requestId`, an exact `method`, the secondary EOA in `wallet`, and a method-specific `payload`. Most methods require a signature; permissionless `wallet.finalize_twap` does not. `authorization7702` is available only to existing supported onboarding/trading methods, not the new operational routes. All integer request fields are canonical unsigned decimal strings. Addresses and byte values use exact-width `0x` hexadecimal. Unknown and duplicate JSON fields are rejected. The request wallet must match the bearer JWT's wallet claim. > [!WARNING] > > `BROADCAST` means Relay accepted and scheduled the signed transaction for > asynchronous RPC broadcast. The RPC call may not have returned yet. It does > not prove provider acceptance, inclusion, execution, or finality. Track the > transaction receipt and verify the expected event or state transition. # Using Hosted Relay Source: https://docs.kuru.io/api/relay/security Responsibilities and boundaries for applications using Kuru Relay. Hosted Relay validates supported signed actions, sponsors their gas, and schedules the resulting transactions for broadcast. It cannot change the action committed by a valid signature. The opt-in `wallet.finalize_twap` route is a permissionless contract action with no client signature; Relay still authenticates and scopes its caller. ## Your application's responsibilities Use a dedicated secondary EOA as the trading signer and grant it only the AccountCore permissions it needs. Keep the owner key and trading key separate. A trading permission is not a spending cap or a market allowlist. Store trading keys and JWTs securely. Your application owns nonce allocation, payload signing, receipt tracking, order reconciliation, and signer retirement. See [Delegated Trading with Relay](/sdk/relay-onboarding). ## The service operator's responsibilities The operator holds the sponsor key and manages gas budgets, transaction lanes, RPC routing, and service admission. Hosted-service clients do not need the sponsor key or control its transaction nonce. Handle the documented [Relay errors](/api/relay/errors) for admission, quotas and nonce/deadline validation. ## Authentication and permissions A Relay JWT authenticates one secondary EOA to the service. It does not grant onchain trading permission, install delegation, or replace action signatures. Expiring it does not revoke those permissions. For the verified-account rate tier, request a token with `uid` at public `POST /auth/token`. Relay verifies that wallet's current trading authorization for the exact account and signs the account/root binding into the JWT. The signed trading `header.accountId` and required WebSocket `account_id` must match the token's `uid`. A scoped JWT is still only a service-admission credential; contracts enforce permission at execution, and token issuance does not register an account or grant on-chain rights. See [Relay Rate Limits and Migration](/api/relay/rate-limits). Headerless onboarding and administrative methods keep the wallet-based quota, even with a scoped JWT; their signed owner/administrator is independent of the JWT wallet. Retiring a signer requires onchain revocation and a separate decision about resting orders and liquidity. Follow [Signer Lifecycle and Nonces](/sdk/signer-lifecycle). ## REST and WebSocket Use REST for a straightforward submission integration. WebSocket sessions support repeated actions and transaction-outcome subscriptions. The documented Relay WebSocket uses an Authorization header on the upgrade request; standard browser WebSocket constructors cannot supply that header. Browser applications should use the supported REST path, or an explicitly designed backend connection. A `BROADCAST` response is not execution or finality. Verify the receipt and resulting state, or use the documented [transaction outcomes](/api/relay/errors). Do not blindly retry an unknown result. # Authorize account signer Source: https://docs.kuru.io/api/relay/websocket-reference/authorize-account-signer Grant AccountCore permission over the wallet-bound Relay WebSocket. The connection JWT supplies the wallet identity, so the message omits REST's `wallet` field. The payload and optional EIP-7702 authorization are otherwise identical to the [REST method](/api/relay/reference/authorize-account-signer). # Cancel conditional order Source: https://docs.kuru.io/api/relay/websocket-reference/cancel-trigger Cancel an active trigger over the wallet-bound Relay WebSocket. Send `wallet.cancel_trigger` with a connection-local `id` and an unused trigger nonce. See the [REST payload reference](/api/relay/reference/cancel-trigger) for signing constraints. # Cancel TWAP instruction Source: https://docs.kuru.io/api/relay/websocket-reference/cancel-twap Submit wallet.cancel_twap over the authenticated Relay WebSocket. Send `wallet.cancel_twap` with a connection-local `id` over `wss://relay.testnet.kuru.io/relay/ws?account_id=` (or the mainnet host) and a wallet-bound JWT in the upgrade `Authorization` header. The request uses the same exact payload and signature rules as the [REST method](/api/relay/reference/cancel-twap); omit the REST `wallet` and `requestId` fields. Use the signed trading account ID as the required upgrade `account_id`. This is a slow operational request. Its bounded RPC simulation can hold later submissions on the same ordered WebSocket; use REST or a separate connection for latency-sensitive trading. `BROADCAST` only indicates asynchronous scheduling. Relay automatically sends `transaction.outcome` on this connection with the original `id`; no explicit subscription or client acknowledgement is required. Verify the intended on-chain state or events after a terminal outcome. # Create batch trigger Source: https://docs.kuru.io/api/relay/websocket-reference/create-batch-trigger Reference-only WebSocket batch trigger; automated execution is not available. > [!WARNING] > > Conditional-order submission is not a supported live Relay flow on either network. The message uses the same signed payload as the [REST method](/api/relay/reference/create-batch-trigger), replacing `requestId` and `wallet` with connection-local `id`. # Store FOK swap trigger Source: https://docs.kuru.io/api/relay/websocket-reference/create-fok-swap-trigger Store an FOK trigger over Relay WebSocket; condition monitoring and execution are not implemented. Send `wallet.create_fok_swap_trigger` with a connection-local `id` over `wss://relay.testnet.kuru.io/relay/ws?account_id=` (or the mainnet host) and a wallet-bound JWT in the upgrade `Authorization` header. The request uses the same exact payload and signature rules as the [REST method](/api/relay/reference/create-fok-swap-trigger); omit the REST `wallet` and `requestId` fields. Use the signed trading account ID as the required upgrade `account_id`. > [!WARNING] > > Automated triggers, including TP/SL, are **not implemented** as a live feature and remain work in progress. This method only stores an instruction where enabled; it does not monitor or execute a trigger. This is a slow operational request. Its bounded RPC simulation can hold later submissions on the same ordered WebSocket; use REST or a separate connection for latency-sensitive trading. `BROADCAST` only indicates asynchronous scheduling. Relay automatically sends `transaction.outcome` on this connection with the original `id`; no explicit subscription or client acknowledgement is required. Verify the intended on-chain state or events after a terminal outcome. # Create packed replacement trigger Source: https://docs.kuru.io/api/relay/websocket-reference/create-replace-trigger Reference-only WebSocket packed trigger; automated execution is not available. > [!WARNING] > > Conditional-order submission is not a supported live Relay flow on either network. The message uses the same signed payload as the [REST method](/api/relay/reference/create-replace-trigger), replacing `requestId` and `wallet` with connection-local `id`. # Create subaccount Source: https://docs.kuru.io/api/relay/websocket-reference/create-subaccount Submit account_core.create_subaccount_by_sig over the authenticated Relay WebSocket. Send `account_core.create_subaccount_by_sig` with a connection-local `id` over `wss://relay.testnet.kuru.io/relay/ws?account_id=` (or the mainnet host) and a wallet-bound JWT in the upgrade `Authorization` header. The request uses the same exact payload and signature rules as the [REST method](/api/relay/reference/create-subaccount); omit the REST `wallet` and `requestId` fields. AccountCore methods still require `account_id` at connection upgrade, but their signed payload has no market field. This is a slow operational request. Its bounded RPC simulation can hold later submissions on the same ordered WebSocket; use REST or a separate connection for latency-sensitive trading. `BROADCAST` only indicates asynchronous scheduling. Relay automatically sends `transaction.outcome` on this connection with the original `id`; no explicit subscription or client acknowledgement is required. Verify the intended on-chain state or events after a terminal outcome. # Store TWAP instruction Source: https://docs.kuru.io/api/relay/websocket-reference/create-twap Store a TWAP instruction over Relay WebSocket; automated slice execution is not implemented. Send `wallet.create_twap` with a connection-local `id` over `wss://relay.testnet.kuru.io/relay/ws?account_id=` (or the mainnet host) and a wallet-bound JWT in the upgrade `Authorization` header. The request uses the same exact payload and signature rules as the [REST method](/api/relay/reference/create-twap); omit the REST `wallet` and `requestId` fields. Use the signed trading account ID as the required upgrade `account_id`. > [!WARNING] > > Automated TWAP execution is **not implemented** and remains work in progress. This method only stores an instruction where enabled; no service schedules or submits slices. This is a slow operational request. Its bounded RPC simulation can hold later submissions on the same ordered WebSocket; use REST or a separate connection for latency-sensitive trading. `BROADCAST` only indicates asynchronous scheduling. Relay automatically sends `transaction.outcome` on this connection with the original `id`; no explicit subscription or client acknowledgement is required. Verify the intended on-chain state or events after a terminal outcome. # Execute order batch Source: https://docs.kuru.io/api/relay/websocket-reference/execute-batch Place native orders and cancel slots over the wallet-bound Relay WebSocket. Send `wallet.execute_batch` with a connection-local `id`. The signed payload follows the same constraints as the [REST method](/api/relay/reference/execute-batch). For the [verified-account rate tier](/api/relay/rate-limits), obtain the JWT with `uid` at `POST /auth/token`. The signed `header.accountId` and WebSocket upgrade `account_id` must both equal that token's verified `uid`. Rejected rate-limited retries need a new envelope `id`, not a new signed account identity. # Cancel all orders in a market Source: https://docs.kuru.io/api/relay/websocket-reference/execute-cancel-all Submit wallet.execute_cancel_all over the authenticated Relay WebSocket. Send `wallet.execute_cancel_all` with a connection-local `id` over `wss://relay.testnet.kuru.io/relay/ws?account_id=` (or the mainnet host) and a wallet-bound JWT in the upgrade `Authorization` header. The request uses the same exact payload and signature rules as the [REST method](/api/relay/reference/execute-cancel-all); omit the REST `wallet` and `requestId` fields. Use the signed trading account ID as the required upgrade `account_id`. This is a slow operational request. Its bounded RPC simulation can hold later submissions on the same ordered WebSocket; use REST or a separate connection for latency-sensitive trading. `BROADCAST` only indicates asynchronous scheduling. Relay automatically sends `transaction.outcome` on this connection with the original `id`; no explicit subscription or client acknowledgement is required. Verify the intended on-chain state or events after a terminal outcome. # Cancel orders by ID Source: https://docs.kuru.io/api/relay/websocket-reference/execute-cancel-orders-by-id Submit wallet.execute_cancel_orders_by_id over the authenticated Relay WebSocket. Send `wallet.execute_cancel_orders_by_id` with a connection-local `id` over `wss://relay.testnet.kuru.io/relay/ws?account_id=` (or the mainnet host) and a wallet-bound JWT in the upgrade `Authorization` header. The request uses the same exact payload and signature rules as the [REST method](/api/relay/reference/execute-cancel-orders-by-id); omit the REST `wallet` and `requestId` fields. Use the signed trading account ID as the required upgrade `account_id`. This is a slow operational request. Its bounded RPC simulation can hold later submissions on the same ordered WebSocket; use REST or a separate connection for latency-sensitive trading. `BROADCAST` only indicates asynchronous scheduling. Relay automatically sends `transaction.outcome` on this connection with the original `id`; no explicit subscription or client acknowledgement is required. Verify the intended on-chain state or events after a terminal outcome. # Execute FOK swap Source: https://docs.kuru.io/api/relay/websocket-reference/execute-fok-swap Submit wallet.execute_fok_swap over the authenticated Relay WebSocket. Send `wallet.execute_fok_swap` with a connection-local `id` over `wss://relay.testnet.kuru.io/relay/ws?account_id=` (or the mainnet host) and a wallet-bound JWT in the upgrade `Authorization` header. The request uses the same exact payload and signature rules as the [REST method](/api/relay/reference/execute-fok-swap); omit the REST `wallet` and `requestId` fields. Use the signed trading account ID as the required upgrade `account_id`. This is a slow operational request. Its bounded RPC simulation can hold later submissions on the same ordered WebSocket; use REST or a separate connection for latency-sensitive trading. `BROADCAST` only indicates asynchronous scheduling. Relay automatically sends `transaction.outcome` on this connection with the original `id`; no explicit subscription or client acknowledgement is required. Verify the intended on-chain state or events after a terminal outcome. # Execute packed slot replacement Source: https://docs.kuru.io/api/relay/websocket-reference/execute-replace-by-slot Submit compact maker-slot operations over the Relay WebSocket. Send `wallet.execute_replace_by_slot_packed` with a connection-local `id`. The payload follows the [REST packed-operation contract](/api/relay/reference/execute-replace-by-slot). For the [verified-account rate tier](/api/relay/rate-limits), obtain the JWT with `uid` at `POST /auth/token`. The signed `header.accountId` and WebSocket upgrade `account_id` must both equal the verified `uid`. Rejected rate-limited retries need a new envelope `id`. The same planning-time slot-binding rules apply over WebSocket: `0` requires an empty slot, a specific ID requires that exact order, and `18446744073709551615` is the wildcard for whichever order currently occupies the slot. Relay does not wait for finalization during planning, and signer ordering does not make concurrent planning observe preceding transactions. For continuous replacement, use the wildcard when that is the intended behavior; exact IDs require observing the corresponding proposed state first. # Finalize expired TWAP Source: https://docs.kuru.io/api/relay/websocket-reference/finalize-twap Submit wallet.finalize_twap over the authenticated Relay WebSocket. Send `wallet.finalize_twap` with a connection-local `id` over `wss://relay.testnet.kuru.io/relay/ws?account_id=` (or the mainnet host) and a wallet-bound JWT in the upgrade `Authorization` header. Use the same `twapId`-only payload as the [REST method](/api/relay/reference/finalize-twap); omit REST's `wallet` and `requestId` fields. The upgrade still requires a trading `account_id`, even though this permissionless contract-finalization payload has no account field or client signature. This is a slow operational request. Its bounded RPC simulation can hold later submissions on the same ordered WebSocket; use REST or a separate connection for latency-sensitive trading. `BROADCAST` only indicates asynchronous scheduling. Relay automatically sends `transaction.outcome` on this connection with the original `id`; no explicit subscription or client acknowledgement is required. Verify the intended on-chain state or events after a terminal outcome. # Revoke account signer Source: https://docs.kuru.io/api/relay/websocket-reference/revoke-account-signer Submit account_core.revoke_account_signer_by_sig over the authenticated Relay WebSocket. Send `account_core.revoke_account_signer_by_sig` with a connection-local `id` over `wss://relay.testnet.kuru.io/relay/ws?account_id=` (or the mainnet host) and a wallet-bound JWT in the upgrade `Authorization` header. The request uses the same exact payload and signature rules as the [REST method](/api/relay/reference/revoke-account-signer); omit the REST `wallet` and `requestId` fields. AccountCore methods still require `account_id` at connection upgrade, but their signed payload has no market field. This is a slow operational request. Its bounded RPC simulation can hold later submissions on the same ordered WebSocket; use REST or a separate connection for latency-sensitive trading. `BROADCAST` only indicates asynchronous scheduling. Relay automatically sends `transaction.outcome` on this connection with the original `id`; no explicit subscription or client acknowledgement is required. Verify the intended on-chain state or events after a terminal outcome. # Transaction outcome Source: https://docs.kuru.io/api/relay/websocket-reference/transaction-outcome Understand Relay's automatic and replayed terminal transaction messages. Relay sends `transaction.outcome` automatically for successful WebSocket submissions on the submitting connection. It includes the original client `id`, Relay `requestId`, and `txHash`; no explicit subscription or client acknowledgement is required. An immediate submission rejection has no outcome subscription. After a reconnect subscription, the outcome instead carries the new subscription `id`. A retained terminal outcome may arrive immediately in response to `transaction.subscribe`, without a `SUBSCRIBED` acknowledgement. Terminal statuses are `CONFIRMED`, `REVERTED`, `REPLACED`, and `UNKNOWN`. `CONFIRMED` reflects finality and successful **outer-transaction** execution, but the currently deployed implementation does not prove the intended trading-wallet action ran. Reconcile the expected trading events and resulting account/order state before treating the logical action as complete. See [Relay errors and outcomes](/api/relay/errors#websocket-transaction-outcomes) for status details and recovery limits. # Subscribe to transaction Source: https://docs.kuru.io/api/relay/websocket-reference/transaction-subscribe Recover a pending or retained Relay transaction outcome after reconnecting. Send `transaction.subscribe` with the server-assigned `requestId` and `txHash` from an earlier `BROADCAST` response. The authenticated WebSocket must be bound to the same trading wallet. This method does **not** rebroadcast the transaction. New WebSocket submissions automatically receive outcomes on their submitting connection; explicit subscription is primarily for reconnect recovery. For a pending transaction, Relay responds `SUBSCRIBED` and later sends `transaction.outcome`. If its terminal outcome is still retained, Relay sends that outcome immediately instead. Relay retains the latest **4,096 terminal outcomes per signer**, shared across users. The limit is by count, not age, and replay may be unavailable after a signer restart. If the submission response was lost before either `requestId` or `txHash` arrived, a connection-local WS `id` cannot be used as a cross-connection lookup key. See [Relay errors and outcomes](/api/relay/errors#connection-closure-and-recovery) for the CLOID and chain-state recovery path. # AccountCore Source: https://docs.kuru.io/contracts/account-core Identity, root-wide permissions, custody, and fee policy. AccountCore holds custody and identifies every root and child by a nonzero `uint40` account ID. Children are ledger entries, with no deployed contract, wallet address, or signer registry. This is a fresh-deployment model: its storage layout and API are incompatible with the former address-keyed model. Physical custody flows use an external global USD36 limiter with per-token price sources. Ordinary withdrawals consume 24-hour deposit credit, then a capped drip allowance. Approved root-owner-signed payouts bypass those pools but still require valid pricing and active releases. See [WithdrawalLimiter](/contracts/withdrawal-limiter). ## Identity and custody `rootAccountIdOf(owner)` resolves an owner's one root ID, or zero before registration. Each ID stores its owner, root ID and sequence. A root points to itself and has sequence zero; children share the root owner and have consecutive sequences starting at one. IDs and sequences are never reused. There can be at most 65,535 children per root. `getSubaccounts(rootId)` returns their IDs in creation order. Free balances and active-order reserves are keyed by account ID and token. Native MON uses `address(0)`. Trading and passive liquidity operate on each child's own balance and reserves; sharing signers does not pool collateral. The existing root-wide builder and fee policies still resolve through the target account's root ID. Positive builder fees credit the builder's root free balance, registering that root if needed, and emit `SpotReserveUpdated` before `BuilderFeeAccrued`. Builders withdraw through the root-only withdrawal API; there is no separate builder-fee claim ledger. Zero-fee attribution does not register a builder root. ## External funding There are exactly two deposit entrypoints: * `deposit(address rootOwner, address token, uint256 amount)` registers the owner's root if necessary. * `deposit(uint40 rootAccountId, address token, uint256 amount)` requires an existing root ID. Anyone may fund a root. The payer receives no authority over it. Both overloads support ERC20 and native assets. A child ID is rejected, including when its owner is the caller. SpotPeriphery exposes the same two overloads. `withdraw(uint40 rootAccountId, address token, uint256 amount, address recipient)` only accepts roots and pays the explicit recipient. Reject zero and AccountCore itself. Recipients need no registration or permissions; registered recipients receive an external payout, not internal balance credit. This replaces the three-argument signature; callers must pass their own address explicitly to retain caller payouts. The caller must be the root owner or a live root `WITHDRAW`/`ADMIN` signer. No child can withdraw, even through its owner. `transferBetweenAccounts(fromId, toId, token, amount)` moves free balance within one family. It requires the root owner or a live root `INTERNAL_TRANSFER`, `WITHDRAW` or `ADMIN` signer. Root-to-child, child-to-root and sibling transfers use the same check. Thus funding a child and withdrawing its proceeds go through the root. Reserved assets must first be released. These restrictions apply to external funding; settlement and passive-liquidity releases can credit children normally. ## One signer registry per root All grants live under the root ID. There are no child-specific signers. | Authority | Scope | | - | - | | Root owner | Full control over the family, subject to root-only external funding | | `TRADE` | Root and every current or future child: place, replace, cancel, swap, passive liquidity; also create children | | `ADMIN` | All defined roles: manage root grants, create children, trade across the family, transfer internally and withdraw from the root | | `INTERNAL_TRANSFER` | Move free balance between IDs in the same family | | `WITHDRAW` | Withdraw from the root to the explicit recipient and transfer internally within the family | The hierarchy is evaluated when checking authority: ADMIN includes TRADE, WITHDRAW and INTERNAL_TRANSFER; WITHDRAW includes INTERNAL_TRANSFER. Stored grants and authorization events retain the exact granted bits. TRADE and INTERNAL_TRANSFER do not imply higher permissions. Deposits remain permissionless funding. Expiry and revocation apply to the entire family immediately. Adding a child does not change existing grants. `isAuthorizedAccountSignerById` is the canonical trading authorization query. For delegated signers, child-ID queries only evaluate `TRADE`; check non-trading roles against the root ID. Internal family transfers authorize against that root rather than testing a child for `INTERNAL_TRANSFER`. A zero account ID in orderbook entrypoints retains the caller's own root convenience path; it never selects a root based on delegated authority. Signer administration continues to identify the root by its owner address, including the EIP-712 grant/revoke flows. Only the owner can bootstrap an unregistered root. Each successful grant or revocation increments the root's authorization epoch. `accountAuthorizationEpoch(accountId)` returns that epoch for either root or child and rejects unknown IDs. `accountSignerAuthorizationNonces(rootOwner)` provides the owner-address lookup, returning zero before registration. Signed trading actions bind both the actual target ID and this root epoch. Reauthorizing a revoked signer does not revive earlier intents or stored triggers. Creating a child does not invalidate trading intents. ## Child creation `createSubaccount(rootOwner)` accepts the owner or a live root ADMIN/TRADE signer. Only the owner can bootstrap a missing root. The signed entrypoint accepts the same authorizers, checked at execution time: ```solidity theme={null} createSubaccountBySig(rootOwner, authorizer, subaccountSeq, authNonce, deadline, signature) ``` Its EIP-712 domain is `KuruAccountCore`, version `1`, the current chain ID and AccountCore proxy address. The type is: ```text theme={null} CreateSubaccount(address rootOwner,address authorizer,uint16 subaccountSeq,uint256 authNonce,uint256 deadline) ``` `authNonce` must match the root epoch. `subaccountSeq` must equal the next sequence, so both direct and signed creation consume it. Two requests for the same sequence compete: after one succeeds, the other must be signed again. This avoids another nonce mapping. Signatures support EOAs and ERC-1271 contract authorizers through Solady. The old child-address consent flow and its typed message are removed. Names and other display metadata remain offchain. ## Contract boundaries and integration `IAccountCore` owns identity, root authorization, custody and fee policy. `ISpotBalanceAccount` exposes verified orderbook reserve and settlement operations. SpotPeriphery is unprivileged. KuruTradingWallet validates signed intents against the target ID and root epoch before forwarding through normal orderbook checks. Token configuration, fee rounding, order packing and matching economics are unchanged. Integrators must regenerate ABIs, pass IDs for balances, transfers, withdrawals and trades, and use owner addresses only for root lookup/bootstrap and root administration. Read `AccountRegistered(accountId, rootAccountId, rootOwner, subaccountSeq)` to index every account and `SubaccountCreated(rootAccountId, subaccountId, authorizer)` for creation provenance. Child IDs are not deposit addresses. SDK/frontend/indexer changes must ship with the new deployment. Source: [Account architecture at main](https://github.com/Kuru-Labs/kuru-contracts-perps/blob/42ef525/docs/AccountArchitecture.md). ## Callable reference Signatures and parameter types below are generated from the reviewed SDK 0.2.0 ABI (contract revision `cdac5ae1`). These are Solidity return values: SDK write methods return a transaction hash and require receipt reconciliation. Viem decodes small Solidity integers as numbers; the SDK normalizes account IDs to `bigint` on its account-client methods. > [accordion] rootAccountIdOf(address) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `argument0` | `address` | > > **Returns:** `uint40`. > [accordion] getAccountOwner(uint40) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `accountId` | `uint40` | > > **Returns:** `address`. > [accordion] getAccountRootId(uint40) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `accountId` | `uint40` | > > **Returns:** `uint40`. > [accordion] getAccountSubaccountSeq(uint40) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `accountId` | `uint40` | > > **Returns:** `uint16`. > [accordion] getSubaccounts(uint40) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `rootAccountId` | `uint40` | > > **Returns:** `uint40[]`. > [accordion] getBalance(uint40, address) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `accountId` | `uint40` | > | `token` | `address` | > > **Returns:** `uint256`. > [accordion] getSpotReservedBalance(uint40, address) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `accountId` | `uint40` | > | `token` | `address` | > > **Returns:** `uint256`. > [accordion] deposit(address, address, uint256) > > **Mutability:** `payable`. Permissionless funding of a root only. The owner-address overload registers a root if needed. ERC-20 assets require allowance; native MON requires exact transaction value. Pricing and token-enablement checks apply. > > | Parameter | Solidity type | > | - | - | > | `rootOwner` | `address` | > | `token` | `address` | > | `amount` | `uint256` | > > **Returns:** No Solidity return value. > [accordion] deposit(uint40, address, uint256) > > **Mutability:** `payable`. Permissionless funding of a root only. The owner-address overload registers a root if needed. ERC-20 assets require allowance; native MON requires exact transaction value. Pricing and token-enablement checks apply. > > | Parameter | Solidity type | > | - | - | > | `rootAccountId` | `uint40` | > | `token` | `address` | > | `amount` | `uint256` | > > **Returns:** No Solidity return value. > [accordion] withdraw(uint40, address, uint256, address) > > **Mutability:** `nonpayable`. Root owner or live root WITHDRAW/ADMIN authority. Debits root free balance and pays the explicit external recipient. Capacity, prices, release controls, and transfer checks apply. > > | Parameter | Solidity type | > | - | - | > | `rootAccountId` | `uint40` | > | `token` | `address` | > | `amount` | `uint256` | > | `recipient` | `address` | > > **Returns:** No Solidity return value. > [accordion] transferBetweenAccounts(uint40, uint40, address, uint256) > > **Mutability:** `nonpayable`. Root owner or live root INTERNAL_TRANSFER/WITHDRAW/ADMIN authority. Both IDs must share a root. Moves free balance only; no external token transfer. > > | Parameter | Solidity type | > | - | - | > | `fromAccountId` | `uint40` | > | `toAccountId` | `uint40` | > | `token` | `address` | > | `amount` | `uint256` | > > **Returns:** No Solidity return value. > [accordion] createSubaccount(address) > > **Mutability:** `nonpayable`. Root owner or live root TRADE/ADMIN authority; only the owner can bootstrap a missing root. Returns a new numeric child ID and does not advance the root epoch. > > | Parameter | Solidity type | > | - | - | > | `rootOwner` | `address` | > > **Returns:** `uint40 subaccountId`. > [accordion] createSubaccountBySig(address, address, uint16, uint256, uint256, bytes) > > **Mutability:** `nonpayable`. The authorizer must still be the owner or a live root TRADE/ADMIN signer. Check the next child sequence, root epoch, deadline, and AccountCore signature domain. > > | Parameter | Solidity type | > | - | - | > | `rootOwner` | `address` | > | `authorizer` | `address` | > | `subaccountSeq` | `uint16` | > | `authNonce` | `uint256` | > | `deadline` | `uint256` | > | `signature` | `bytes` | > > **Returns:** `uint40 subaccountId`. > [accordion] authorizeAccountSigner(address, address, uint32, uint64) > > **Mutability:** `nonpayable`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `account` | `address` | > | `signer` | `address` | > | `permissions` | `uint32` | > | `expiry` | `uint64` | > > **Returns:** No Solidity return value. > [accordion] authorizeAccountSignerBySig(address, address, address, uint32, uint64, uint256, uint256, bytes) > > **Mutability:** `nonpayable`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `account` | `address` | > | `authorizer` | `address` | > | `signer` | `address` | > | `permissions` | `uint32` | > | `expiry` | `uint64` | > | `nonce` | `uint256` | > | `deadline` | `uint256` | > | `signature` | `bytes` | > > **Returns:** No Solidity return value. > [accordion] revokeAccountSigner(address, address) > > **Mutability:** `nonpayable`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `account` | `address` | > | `signer` | `address` | > > **Returns:** No Solidity return value. > [accordion] revokeAccountSignerBySig(address, address, address, uint256, uint256, bytes) > > **Mutability:** `nonpayable`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `account` | `address` | > | `authorizer` | `address` | > | `signer` | `address` | > | `nonce` | `uint256` | > | `deadline` | `uint256` | > | `signature` | `bytes` | > > **Returns:** No Solidity return value. > [accordion] accountAuthorizationEpoch(uint40) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `accountId` | `uint40` | > > **Returns:** `uint256`. > [accordion] accountSignerAuthorizationNonces(address) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `rootOwner` | `address` | > > **Returns:** `uint256`. > [accordion] isAuthorizedAccountSignerById(uint40, address, uint32) > > **Mutability:** `view`. Check TRADE on the target ID. Delegated non-trading checks must use the root ID; a child query masks out those roles. > > | Parameter | Solidity type | > | - | - | > | `accountId` | `uint40` | > | `signer` | `address` | > | `permission` | `uint32` | > > **Returns:** `bool`. > [accordion] approveBuilder(address, uint32, uint64) > > **Mutability:** `nonpayable`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `builder` | `address` | > | `maxFeePps` | `uint32` | > | `expiry` | `uint64` | > > **Returns:** No Solidity return value. > [accordion] revokeBuilder(address) > > **Mutability:** `nonpayable`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `builder` | `address` | > > **Returns:** No Solidity return value. > [accordion] getBuilderApproval(address, address) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `rootAccount` | `address` | > | `builder` | `address` | > > **Returns:** `(uint32 maxFeePps, uint64 expiry, bool active)`. > [accordion] effectiveSpotMakerFeePps(uint40, uint256) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `accountId` | `uint40` | > | `marketMakerFeePps` | `uint256` | > > **Returns:** `uint32`. > [accordion] effectiveSpotTakerFeePps(uint40, uint256) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `accountId` | `uint40` | > | `marketTakerFeePps` | `uint256` | > > **Returns:** `uint32`. > [accordion] getAccountFeeTierById(uint40) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `accountId` | `uint40` | > > **Returns:** `(uint32 makerFeePps, uint32 takerFeePps, bool active) tier`. > [accordion] getBuilderReferralById(uint40) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `accountId` | `uint40` | > > **Returns:** `(address builder, uint32 makerFeePps, uint32 takerFeePps, uint64 expiry) referral`, `bool active`. > [accordion] getBuilderReferralTier(address) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `builder` | `address` | > > **Returns:** `(uint32 makerFeePps, uint32 takerFeePps, uint64 expiry, bool active)`. > [accordion] enrollBuilderReferralBySig(address, address, uint32, uint32, uint64, bytes32, uint256, bytes) > > **Mutability:** `nonpayable`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `rootAccount` | `address` | > | `builder` | `address` | > | `makerFeePps_` | `uint32` | > | `takerFeePps_` | `uint32` | > | `referralExpiry` | `uint64` | > | `nonce` | `bytes32` | > | `deadline` | `uint256` | > | `signature` | `bytes` | > > **Returns:** `uint40 rootAccountId`. > [accordion] revokeBuilderReferral(address) > > **Mutability:** `nonpayable`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `rootAccount` | `address` | > > **Returns:** No Solidity return value. > [accordion] approvedWithdrawalNonces(address) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `argument0` | `address` | > > **Returns:** `uint256`. > [accordion] withdrawalAuthorityEpoch() > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > No parameters. > > **Returns:** `uint64`. > [accordion] withdrawalLimiter() > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > No parameters. > > **Returns:** `address`. > [accordion] fulfillApprovedWithdrawal(tuple, bytes) > > **Mutability:** `nonpayable`. Only the configured withdrawal authority submits this call. It requires a root-owner signature; bypasses ordinary capacity but preserves prices, freezes, balance and transfer checks. > > | Parameter | Solidity type | > | - | - | > | `withdrawal` | `(address account, address token, address recipient, uint256 amount, uint256 nonce, uint256 deadline, uint64 authorityEpoch)` | > | `ownerSignature` | `bytes` | > > **Returns:** No Solidity return value. > [accordion] invalidateApprovedWithdrawalNonce(address, uint256) > > **Mutability:** `nonpayable`. Invalidates older approved-payout signatures. This nonce is distinct from the signer authorization epoch. > > | Parameter | Solidity type | > | - | - | > | `account` | `address` | > | `nextNonce` | `uint256` | > > **Returns:** No Solidity return value. # Integration Troubleshooting Source: https://docs.kuru.io/contracts/faq Answers for raw units, slots, approvals, balance reconciliation, and transaction failures. ## How do raw price and size units work? For a market: ```text theme={null} displayPrice = rawPrice / pricePrecision displayBaseQuantity = bookQuantity / sizePrecision rawBaseAtoms = bookQuantity * baseSizeMultiplier ``` `rawPrice` must be divisible by `tickSize`. Packed trades, active orders, and L2 quantities use normalized `bookQuantity`; token transfers and passive-liquidity amounts use raw token atoms. Quote atoms are calculated deterministically from price and normalized size using the configured precisions. Rounding depends on direction: bids use two-stage floors, passive asks use two-stage ceilings, and active asks use incremental cumulative-ceiling accounting across the match. Do not use a universal floor formula to reconstruct fills. See [OrderBook](/contracts/order-book) for the formulas; validate limits and simulate the exact call. Fee rates are PPS: `fee = amount * feePps / 10_000_000`, with the rounding boundary determined by the fee type. ## Why can free balance be lower than the wallet deposit history? `getBalance` is free balance. Active orders move assets into aggregate `spotReservedBalance`; passive mints move assets into the orderbook's position ledger. Reconcile all three buckets. ## Why use both slot index and order ID? A maker slot is reusable. The order ID changes whenever a replacement creates a new resting order. Bind asynchronous cancel and replace requests to the expected ID so a delayed action cannot affect a newer order in the same slot. ## Does a successful transaction imply the requested post-only order rested? No. A crossing `POST_ONLY` order is skipped instead of reverting the batch. Confirm the resulting slot or consume `BookUpdatesPacked`. ## Why did a swap revert after an estimate succeeded? Liquidity, balances, fee policy, RAB visibility, and hook behavior can change before execution. Stateful hooks are not simulated by `estimateSwap`. Always set `minAmountOut` and a deadline. ## Which approval is required? * ERC-20 allowance authorizes the token transfer into AccountCore. * AccountCore signer authorization controls actions on an account. * Builder approval caps optional builder fees. * Post-fill hook access is a separate protocol gate for maker callbacks. * Relay JWTs are offchain service credentials and do not replace any onchain authorization. ## What confirmation policy should an application use? Treat the transaction receipt as inclusion, then use the application's chosen chain-finality policy before exposing irreversible status. Order event reducers must be able to rewind blocks and replay by block, transaction index, and log index. # OrderBook Source: https://docs.kuru.io/contracts/order-book Matching, reserves, swaps, passive liquidity, and views. `OrderBook` is the on-chain FIFO spot book implementation. It matches native spot orders, manages resting-order reserves through `ISpotBalanceAccount`, emits packed trade/book-update events, and supports passive liquidity bands. ## Contracts * `SpotRouter` deploys spot market proxies, registers them with `AccountCore`, and administers market state. * `OrderBook` stores canonical market configuration and handles matching, cancels, packed replace, post-fill hooks, swaps, passive liquidity, and execution state. * `AccountCore` owns balances, account ids, signer permissions, builder approvals, reserves, and settlement. * `SpotPeriphery` is an optional, unprivileged facade for deposits, signed session-authorization forwarding, and multi-market swap estimates. Internally, `OrderBook` is split by responsibility rather than by product inheritance. Permanent storage and shared constants live in `OrderBookState`; later modules layer admin, pricing, events, accounts, settlement, queues, passive markers, hooks, matching, placement, packed replacement, passive-liquidity accounting, swaps, and views. The final deployed contract is `src/orderbook/OrderBook.sol`. ## Assets Spot markets may use ERC20 tokens or native MON. Native MON is represented by `address(0)` in token configuration, market parameters, internal balances, reserves, settlement, and withdrawals. Because `address(0)` is a valid asset, market existence is tracked with explicit registration flags rather than by checking whether the stored base or quote token is nonzero. Native/native markets are invalid: one side may be native MON, but base and quote must be different assets. Quote token decimals are loaded from `AccountCore` during orderbook initialization, not supplied by the market deployer. ERC20 spot tokens must expose `IERC20Metadata.decimals()` when governance enables them; native MON is fixed at 18 decimals. The cached quote scale is then used for all quote-notional, reserve, passive-liquidity, and swap math. Quote conversion is direction-aware. Resting-bid reserves, active-bid fills, and passive-bid fills floor in two deterministic stages: first `price * size / sizePrecision`, then quote-token scaling by `10 ** quoteTokenDecimals / pricePrecision`. Passive asks ceil those two stages per fill. Active asks instead accumulate the exact full-precision numerator within one match and credit each FIFO maker the incremental change in the cumulative ceil. Active-ask credits therefore sum to `ceil(sum(price * size * quoteScale) / (sizePrecision * pricePrecision))` without charging an unrelated fee recipient. `pricePrecision` remains the configured price-scale denominator; base sizing is handled by `sizePrecision`. ## Native Orders `ISpotOrderBook.NativeOrder` contains: * `side` * `quantity` * `price` * `tif` * `executionInstruction` * `minSizeAfterBlock` For native orders, `minQuoteNotional` applies to GTC, including post-only, using the submitted limit price and quantity. IOC and FOK skip this minimum because their limit price is a slippage bound and they cannot rest. All three time-in-force modes still enforce `maxQuoteNotional`, a nonzero quote notional, and the existing size and overflow checks. Spot orders do not carry product-risk flags. The packed replace flags are limited to side and ALO/post-only behavior. Packed replacements buffer queue metadata in small in-memory caches and flush those caches before any mid-batch BBO recomputation that may prune tree bits, keeping moved orders visible to matching and views. ## Exact-Input Swaps `swap` is a min-out protected exact-input taker entrypoint for aggregator-style flows. `isBuy = true` spends quote for base, and `isBuy = false` spends base for quote. The returned `SwapResult` reports the input actually used and the output actually received after fees. `minAmountOut` is the swap slippage guard: the orderbook walks available active FIFO and passive liquidity, then reverts unless the final output is high enough. Buy swaps treat `amountIn` as a fee-inclusive quote budget. The orderbook converts it once into the maximum raw quote principal. Passive asks consume their per-fill ceiled quote. Active asks consume incremental cumulative-ceil quote and carry the exact remainder across prices and FIFO heads in the match. Atomic budget can remain unused and a partial maker residual can be dust-cancelled. Passive fills debit raw input immediately but withhold output until finalization. The protocol taker fee is ceiling-rounded once on aggregate raw quote; an approved builder fee is ceiling-rounded once on aggregate base output. `estimateSwap` is a view simulation of the same exact-input intent. It shadows passive-ask ceilings and the active-ask cumulative remainder across FIFO heads, including stale chunks and dust removal, without mutating queues, balances, or passive band inventory. It cannot predict liquidity or balance changes produced by stateful hooks or state changes between estimation and execution. One swap is one fee match. A native batch or packed replacement may finalize several matches. Each match ceiling-rounds taker and builder fees once across its active and passive totals; active maker fees remain per-fill floors. Routers that only need quotes can call `SpotPeriphery.estimateSwap` or `estimateSwaps` instead of integrating with each market directly. The periphery does not execute swaps or bypass account permissions; actual `swap` calls must still come from the account or a signer authorized in `AccountCore`. ## Reserve Model Resting bids reserve quote plus the maker fee. Resting asks reserve base. Reserves are deducted from free balance when an order rests. For fills, the orderbook derives consumed reserve from the order's old size and residual size. Full fills consume the full reserve. Partial fills leave `spotReservedBalance` equal to the residual order reserve. Cancels and reductions release only the unfilled residual reserve back to free balance. Maker settlement consumes filled reserves directly from `spotReservedBalance`; filled maker funds are never temporarily credited to free balance before post-fill hooks run. Taker settlement still debits and credits free balances directly. Protocol fees accrue to the configured fee collector. Builder fees credit the builder's free AccountCore balance and leave custody through `withdraw`. ## Packed Events An action emits one `BookUpdatesPacked` or `TradesPacked` per contiguous run. Each cycle logs whichever run was appended first, then the other run. A nonempty `protocolCancelBySlots` then emits `ProtocolOrdersCancelled` after those packed logs. Trade records are 64 bytes; the final record of each nonempty match carries `MATCH_END`. Book-update records are 39 bytes. Active trade and live book records carry the order's maker-fee snapshot; passive trade and delete records carry zero. See [OrderBook indexing](/indexing/order-book) for the layouts and reconstruction rules. Batch and packed-replace terminal outcomes reuse reserved bits in those same records. A zero-delta book sentinel represents an otherwise silent IOC, POST_ONLY/ALO skip, empty packed cancel, or non-resting completion. The event signatures and record widths do not change; indexers must mask base flag bits and skip sentinels for L2/L3. ## Dust Handling FIFO fills enforce the minimum base size that can settle to at least one atomic quote unit at the matched price. Resting orders below that executable unit are canceled as dust. Once a taker order has made a real fill, any remaining taker dust below the executable unit is treated as complete for IOC/FOK semantics rather than forcing a revert or leaving a meaningless unmatched tail. Partial fills that would leave an unexecutable maker residual cancel the residual instead of leaving it at the queue head. ## Passive Liquidity Passive bands lock base and/or quote balances through `lockSpotPassiveLiquidity`. Burns and fee claims release balances back through the spot balance interface. See [Passive Liquidity Events](/matching-engine/passive-liquidity) for event indexing. Passive activity changes visible depth and must be reconstructed from execution and band-update events; see [OrderBook Events](/indexing/order-book). ## Callable reference Signatures and parameter types below are generated from the reviewed SDK 0.2.0 ABI (contract revision `cdac5ae1`). These are Solidity return values: SDK write methods return a transaction hash and require receipt reconciliation. Viem decodes small Solidity integers as numbers; the SDK normalizes account IDs to `bigint` on its account-client methods. > [accordion] getMarketParams() > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > No parameters. > > **Returns:** `uint32`, `uint96`, `uint32`, `uint96`, `uint96`, `uint256`, `uint256`. > [accordion] baseToken() > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > No parameters. > > **Returns:** `address`. > [accordion] quoteToken() > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > No parameters. > > **Returns:** `address`. > [accordion] baseSizeMultiplier() > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > No parameters. > > **Returns:** `uint96`. > [accordion] quoteTokenDecimals() > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > No parameters. > > **Returns:** `uint8`. > [accordion] passiveSpreadTicks() > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > No parameters. > > **Returns:** `uint32`. > [accordion] marketState() > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > No parameters. > > **Returns:** `uint8`. > [accordion] bestBidAsk() > > **Mutability:** `view`. Visible best prices. Empty bid is uint32 max; empty ask is zero. > > No parameters. > > **Returns:** `uint32 bid`, `uint32 ask`. > [accordion] getL2Book(uint256) > > **Mutability:** `view`. Combined visible active and passive depth. Stale-order visibility caps are already applied. > > | Parameter | Solidity type | > | - | - | > | `levels` | `uint256` | > > **Returns:** `uint32[] bidPrices`, `uint96[] bidSizes`, `uint32[] askPrices`, `uint96[] askSizes`. > [accordion] getOrderId(uint40, uint8) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > | `slotIdx` | `uint8` | > > **Returns:** `uint64 orderId`. > [accordion] getOrderMinSizeAfterBlock(uint40, uint8) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > | `slotIdx` | `uint8` | > > **Returns:** `uint32 minSizeAfterBlock`. > [accordion] batch(uint40, tuple\[], uint8\[]) > > **Mutability:** `nonpayable`. Live TRADE authority over the target account is required. Cancels run before the native orders. Post-only skips are possible in successful transactions; other validation failures can revert the whole call. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > | `orders` | `(uint8 side, uint96 quantity, uint32 price, uint8 tif, uint8 executionInstruction, uint32 minSizeAfterBlock)[]` | > | `cancelSlotIdxs` | `uint8[]` | > > **Returns:** No Solidity return value. > [accordion] batch(uint40, tuple\[], uint8\[], bytes32, tuple) > > **Mutability:** `nonpayable`. Live TRADE authority over the target account is required. Cancels run before the native orders. Post-only skips are possible in successful transactions; other validation failures can revert the whole call. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > | `orders` | `(uint8 side, uint96 quantity, uint32 price, uint8 tif, uint8 executionInstruction, uint32 minSizeAfterBlock)[]` | > | `cancelSlotIdxs` | `uint8[]` | > | `clientOrderId` | `bytes32` | > | `builderConfig` | `(address builder, uint32 feePps)` | > > **Returns:** No Solidity return value. > [accordion] batch(uint40, tuple\[], uint8\[], bytes32) > > **Mutability:** `nonpayable`. Live TRADE authority over the target account is required. Cancels run before the native orders. Post-only skips are possible in successful transactions; other validation failures can revert the whole call. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > | `orders` | `(uint8 side, uint96 quantity, uint32 price, uint8 tif, uint8 executionInstruction, uint32 minSizeAfterBlock)[]` | > | `cancelSlotIdxs` | `uint8[]` | > | `clientOrderId` | `bytes32` | > > **Returns:** No Solidity return value. > [accordion] batch(uint40, tuple\[], uint8\[], tuple) > > **Mutability:** `nonpayable`. Live TRADE authority over the target account is required. Cancels run before the native orders. Post-only skips are possible in successful transactions; other validation failures can revert the whole call. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > | `orders` | `(uint8 side, uint96 quantity, uint32 price, uint8 tif, uint8 executionInstruction, uint32 minSizeAfterBlock)[]` | > | `cancelSlotIdxs` | `uint8[]` | > | `builderConfig` | `(address builder, uint32 feePps)` | > > **Returns:** No Solidity return value. > [accordion] replaceBySlotPacked(uint40, bytes, bytes32, tuple) > > **Mutability:** `nonpayable`. Live TRADE authority required. Replacements lose queue priority. Slot indexes are reusable; use wallet expected-ID bindings for delayed signed requests. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > | `packedOps` | `bytes` | > | `clientOrderId` | `bytes32` | > | `builderConfig` | `(address builder, uint32 feePps)` | > > **Returns:** No Solidity return value. > [accordion] replaceBySlotPacked(uint40, bytes) > > **Mutability:** `nonpayable`. Live TRADE authority required. Replacements lose queue priority. Slot indexes are reusable; use wallet expected-ID bindings for delayed signed requests. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > | `packedOps` | `bytes` | > > **Returns:** No Solidity return value. > [accordion] replaceBySlotPacked(uint40, bytes, tuple) > > **Mutability:** `nonpayable`. Live TRADE authority required. Replacements lose queue priority. Slot indexes are reusable; use wallet expected-ID bindings for delayed signed requests. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > | `packedOps` | `bytes` | > | `builderConfig` | `(address builder, uint32 feePps)` | > > **Returns:** No Solidity return value. > [accordion] replaceBySlotPacked(uint40, bytes, bytes32) > > **Mutability:** `nonpayable`. Live TRADE authority required. Replacements lose queue priority. Slot indexes are reusable; use wallet expected-ID bindings for delayed signed requests. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > | `packedOps` | `bytes` | > | `clientOrderId` | `bytes32` | > > **Returns:** No Solidity return value. > [accordion] cancelAllOrders(uint40) > > **Mutability:** `nonpayable`. Cancels the target account’s active orders in this market at execution. Does not remove passive positions or automation schedules. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > > **Returns:** No Solidity return value. > [accordion] swap(uint40, bool, uint128, uint128, uint64, tuple) > > **Mutability:** `nonpayable`. Exact-input amount and minimum output use raw token atoms. The caller needs TRADE permission and free funds. Reverts on self-trade, failed slippage/deadline checks, or other execution failures. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > | `isBuy` | `bool` | > | `amountIn` | `uint128` | > | `minAmountOut` | `uint128` | > | `deadline` | `uint64` | > | `builderConfig` | `(address builder, uint32 feePps)` | > > **Returns:** `(uint128 amountInUsed, uint128 amountOut) result`. > [accordion] swap(uint40, bool, uint128, uint128, uint64) > > **Mutability:** `nonpayable`. Exact-input amount and minimum output use raw token atoms. The caller needs TRADE permission and free funds. Reverts on self-trade, failed slippage/deadline checks, or other execution failures. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > | `isBuy` | `bool` | > | `amountIn` | `uint128` | > | `minAmountOut` | `uint128` | > | `deadline` | `uint64` | > > **Returns:** `(uint128 amountInUsed, uint128 amountOut) result`. > [accordion] estimateSwap(bool, uint128, uint32) > > **Mutability:** `view`. Returns an estimated result without changing state. It cannot predict stateful hook effects or later liquidity changes. SDK 0.2.0 exposes a loosely typed helper; a direct typed ABI read preserves result types. > > | Parameter | Solidity type | > | - | - | > | `isBuy` | `bool` | > | `amountIn` | `uint128` | > | `builderFeePps` | `uint32` | > > **Returns:** `(uint128 amountInUsed, uint128 amountOut) result`. > [accordion] estimateSwap(bool, uint128) > > **Mutability:** `view`. Returns an estimated result without changing state. It cannot predict stateful hook effects or later liquidity changes. SDK 0.2.0 exposes a loosely typed helper; a direct typed ABI read preserves result types. > > | Parameter | Solidity type | > | - | - | > | `isBuy` | `bool` | > | `amountIn` | `uint128` | > > **Returns:** `(uint128 amountInUsed, uint128 amountOut) result`. > [accordion] estimateSwap(uint40, bool, uint128, uint32) > > **Mutability:** `view`. Returns an estimated result without changing state. It cannot predict stateful hook effects or later liquidity changes. SDK 0.2.0 exposes a loosely typed helper; a direct typed ABI read preserves result types. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > | `isBuy` | `bool` | > | `amountIn` | `uint128` | > | `builderFeePps` | `uint32` | > > **Returns:** `(uint128 amountInUsed, uint128 amountOut) result`. > [accordion] estimateSwap(uint40, bool, uint128) > > **Mutability:** `view`. Returns an estimated result without changing state. It cannot predict stateful hook effects or later liquidity changes. SDK 0.2.0 exposes a loosely typed helper; a direct typed ABI read preserves result types. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > | `isBuy` | `bool` | > | `amountIn` | `uint128` | > > **Returns:** `(uint128 amountInUsed, uint128 amountOut) result`. > [accordion] getPassiveBand(uint32) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `lowPrice` | `uint32` | > > **Returns:** `(uint32 lowPrice, uint32 highPrice, uint128 quoteAtLow, uint128 baseAtHigh, uint128 totalShares, uint256 feeGrowthBasePerShareX128, uint256 feeGrowthQuotePerShareX128) band`. > [accordion] getPassivePosition(uint64) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `positionId` | `uint64` | > > **Returns:** `(uint40 ownerId, uint32 lowPrice, uint32 highPrice, uint128 shares, uint256 lastFeeGrowthBaseX128, uint256 lastFeeGrowthQuoteX128) position`. > [accordion] getPostFillHook(uint40) > > **Mutability:** `view`. Use the account, permission, and execution rules described above and in the linked SDK guide. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > > **Returns:** `address hook`. > [accordion] setPostFillHook(uint40, address) > > **Mutability:** `nonpayable`. Requires live TRADE authority; a nonzero hook also needs AccountCore eligibility and valid hook code. > > | Parameter | Solidity type | > | - | - | > | `userId` | `uint40` | > | `hook` | `address` | > > **Returns:** No Solidity return value. # Contract Architecture Source: https://docs.kuru.io/contracts/overview Find every application-facing Spot V2 contract surface and its state owner. Kuru separates custody, market execution, market discovery, and signed-action execution. Read [Spot Trading](/introduction/spot) first if you are unfamiliar with the exchange's trading model. ```mermaid theme={null} flowchart TD Owner[Owner wallet] -->|Deposits and permissions| Core[AccountCore] Bot[Trading signer] -->|Signed instruction| Relay[Relay] Relay -->|Sponsored transaction| Wallet[Delegated trading-wallet EOA] Wallet -->|Authorized action| Book[Market OrderBook] Direct[Direct contract caller] --> Book Book -->|Reserves and settlement| Core Core -->|Custody flow checks| Limiter[WithdrawalLimiter] Router[SpotRouter] -->|Verified market discovery| Book ``` AccountCore holds assets and account permissions. Each market has an OrderBook that owns matching and market-local order state. SpotRouter supplies the verified market registry. KuruTradingWallet executes signed actions in a delegated EOA's context. This reference covers non-admin calls at the pinned contract revision. It omits deployment, token configuration, upgrades, fee administration, pause controls, and governance operations. | Contract | Application responsibility | | - | - | | `AccountCore` | Identity, custody, subaccounts, delegated signers, builders, referrals, balances, reserves | | `WithdrawalLimiter` | Global withdrawal capacity and per-token price validation | | `OrderBook` | Orders, cancellation, replacement, swaps, passive liquidity, maker hooks, market views | | `SpotRouter` | Verified-market and shared-dependency discovery | | `KuruTradingWallet` | EIP-7702 signed immediate actions and stored triggers, TWAP schedules, and wallet-authored data | > [!WARNING] > > Send transactions to deployed proxies or the delegated trading-wallet EOA, never to implementation addresses. Confirm addresses on [Mainnet Deployments](/deployments/mainnet) or [Testnet Deployments](/deployments/testnet) for the network you selected. ## Authorization convention Orderbook and account actions identify the economic account separately from `msg.sender`. The target account is a numeric ID. The caller must be its root owner or a root-wide signer with the required live permission. ## Native asset convention The zero address represents native MON in AccountCore and market token configuration. Native deposits send exact `msg.value`; ERC-20 deposits use allowance and transferFrom. Use [FAQ](/contracts/faq) for units, rounding, slots, confirmations, and failure handling. # SpotRouter Source: https://docs.kuru.io/contracts/spot-router Callable reference for Spot market verification and deterministic address discovery. SpotRouter is the protocol registry for markets deployed through the Router. Market creation and administration are permissioned and intentionally omitted; applications use the views below. > [accordion] verifiedSpotMarket(market) > > Check whether the Router recognizes a market. > > | Parameter | Meaning | > | - | - | > | `market` | Candidate OrderBook address. | > > **Returns:** `true` only for markets registered by this Router. > > **Integration rule:** also verify `AccountCore.verifiedSpotOrderBook(market)` or consume the canonical deployment registry. A contract at a deterministic address is not necessarily deployed or authorized. > > **SDK:** direct Router ABI read. > [accordion] whitelistedSpotTokens(token) > > Read deployment eligibility for an asset. > > Returns whether governance currently permits the token in future Router deployments. This is not a guarantee that a live market exists, nor does it replace AccountCore asset enablement. > > **SDK:** direct Router ABI read. > [accordion] spotBalanceAccountAddress() > > Read the AccountCore linked to the Router. > > Use this to verify that discovered markets settle against the expected custody contract. > > **SDK:** direct Router ABI read. > [accordion] spotOrderBookImplementation() > > Read the implementation used for future Router deployments. > > Existing market proxies may have separate upgrade history. Do not infer an existing proxy's code solely from this value; verify proxy implementation and code hash from the deployment manifest. > > **SDK:** direct Router ABI read. > [accordion] authority() > > Read the shared protocol role authority. > > This is operational metadata, not an application permission check. User-level permissions live in AccountCore. > > **SDK:** direct Router ABI read. > [accordion] computeAddress(baseToken, quoteToken, sizePrecision, pricePrecision, tickSize, passiveSpreadTicks, minQuoteNotional, maxQuoteNotional, takerFeePps, makerFeePps) > > Compute the deterministic proxy address for one exact configuration. > > Every parameter participates in the CREATE2 salt and initialization bytecode. Changing any value can change the result; the current implementation address also participates in the bytecode hash. > > **Returns:** predicted proxy address. > > **No state change:** this does not deploy or register a market. > > **Common failure mode:** treating the prediction as live. Require code at the address plus Router and AccountCore verification. > > **SDK:** direct Router ABI read. Market-registration and state-change events are covered in [Indexing SpotRouter](/indexing/spot-router). # KuruTradingWallet Source: https://docs.kuru.io/contracts/trading-wallet Version-2 execution rules, triggers, TWAP, and signed data. `KuruTradingWallet` is immutable EIP-7702 delegation logic for disposable one-click Spot trading EOAs such as Mera wallets. Each EOA owns its nonce, trigger, and TWAP state. There is no shared executor owner, submitter allowlist, or Mera-specific authorization rule. ## Authorization and Relay Model The user grants the disposable EOA a caller-selected permission mask in `AccountCore`, either directly or through `authorizeAccountSignerBySig`. Trading requires live `TRADE` permission; the wallet contract does not force that permission during enrollment and does not grant itself `ADMIN`. Every user-authorized trading intent is EIP-712 signed by the delegated EOA. The domain is: ```text theme={null} name: KuruTradingWallet version: 2 chainId: current chain verifyingContract: delegated EOA ``` Recovering the signature to `address(this)` both authenticates the Mera key and isolates signatures between delegated EOAs. Calls to the implementation address cannot reuse an EOA-domain signature. The contract also implements ERC-1271 for protocols that need to validate a wallet signature. Any address may relay immediate orders and trigger creation/cancellation. Relayers pay gas or route through a sponsor; relayer identity is deliberately absent from the signed permission model. ## Wallet-signed data `emitSignedData(bytes data, uint256 nonce, uint64 deadline, bytes signature)` lets any relayer publish opaque bytes authenticated by the delegated wallet's EOA key. It emits `SignedDataEmitted(address indexed wallet, uint256 indexed nonce, bytes data)` from the delegated EOA and returns the signed digest. This can publish a signer name during onboarding, even before AccountCore enrollment; it does not create a signer or prove current AccountCore authorization. Use the domain above (version `2`) and the EIP-712 primary type `EmitSignedData`: ```text theme={null} EmitSignedData(bytes data,uint256 nonce,uint64 deadline) ``` Supply raw bytes as `data` to the typed-data signing library; Solidity includes `keccak256(data)` in the struct hash. For a simple name, use UTF-8 bytes, e.g. `Mera bot` is `0x4d65726120626f74`. Applications needing richer metadata should agree on a versioned encoding. The contract does not interpret, restrict, or store the bytes; empty bytes are valid. All emitted data is public. Read `signedDataNonce()` before signing. It starts at zero and must match exactly, then increments on success. Nonces are wallet- and chain-local and independent of order/trigger/TWAP nonces. `deadline` is an inclusive Unix timestamp in seconds. The signature binds every field, chain, and wallet; failed submissions consume no nonce. Any relayer can submit the identical signed message first, but cannot substitute its contents. Sequential nonces prevent an older publication from being replayed after a newer one; two messages signed with the same nonce race and only one succeeds. Indexers should identify the wallet by the emitting address, recognize its trusted delegation, and correlate it with AccountCore signer events for permissions. A name is a wallet-authored label, not proof of identity, uniqueness, or approval by an account owner. Publishing and AccountCore signer enrollment are separate operations; clients must arrange batching if they need atomic onboarding. Existing delegated wallets need to delegate to the newly deployed implementation to use this method. ## Immediate Orders `executeReplaceBySlotPacked` and `executeBatch` bind the account id, verified market, target account's root authorization epoch, millisecond nonce, deadline, client order id, optional builder configuration, payload hashes, and expected order ids. Immediate nonces are monotonic per delegated EOA and chain. A nonce must be greater than `lastSeenOrderNonce` and no further in the future than `block.timestamp * 1000 + maxFutureNonceSkewMillis`. This preserves stale-quote dropping without central executor state. ## Triggers Trigger creation uses unordered one-shot nonces, allowing independent standing orders to execute in any order. Creation authenticates the signature once and stores only execution state: account, market, epoch, expiry, client ID, builder, action/status, and payload. The creation nonce, deadline, and condition commitment remain available from transaction calldata and `TriggerCreated`; they are not retained in `getTrigger`. No signature is stored or recovered again at firing. `conditionHash` remains opaque. An authorized keeper evaluates the condition off-chain and calls `executeTrigger`. Among trigger APIs, only firing consults the immutable `KeeperAuthority`; creation and cancellation remain permissionless relays. Before firing, the wallet verifies: 1. the trigger is active and unexpired; 2. the caller is a current keeper; 3. the market remains a verified Spot orderbook; 4. the target account's root authorization epoch is unchanged and `TRADE` remains live; and 5. every signed slot order-id binding still matches live orderbook state. The wallet marks the trigger fired before the external orderbook call. Transaction atomicity restores the active state if validation or forwarding reverts. Expired triggers are marked `EXPIRED` when a keeper attempts to fire them. ## Keeper Authority `KeeperAuthority` is a non-proxy, independently owned periphery registry. Its owner can grant or revoke keepers and nominate a new administrator, but ownership changes only after the nominee accepts. Contract main `0e7eb76` additionally disables ownership renunciation; this later source change is not evidence that the KeeperAuthority address in the September 29 deployment was replaced. The wallet stores an immutable registry address, so changing registries requires deploying and delegating new wallet logic. Keeper trust is narrow but real: a malicious authorized keeper can falsely claim an opaque condition was met and fire any active trigger. It cannot change the signed action, market, account, builder, expiry, or order-id bindings, and it has no special authority over immediate orders. ## Development deployment and state trust Deploy `KuruTradingWallet` with the intended AccountCore, existing keeper registry, and future-nonce skew. This development version does not preserve earlier testnet wallet storage or signatures. It uses domain version **2** and fresh ERC-7201 root `kuru.storage.KuruTradingWallet.v2`, with nonce/trigger/TWAP state keyed by chain ID. The domain change prevents version-1 intents replaying against reset nonce state; chain-keyed storage prevents standing orders executing on a different chain after creation. Stored actions are authenticated state, not proofs reverified every time they are read. Only authenticated creation can initialize them; payload/configuration are immutable thereafter. This assumes the EOA has not delegated to incompatible/untrusted code that can alter its storage. Changing delegation is not cancellation or state repair. No migration adapter or old-bytecode compatibility gate is provided. Retain independent authorization epochs and explicit cancellation for revocation. The wallet's ERC-1271 endpoint remains available to external callers, but its own intents use EOA ECDSA recovery, not a mutable external ERC-1271 validator. All mutating entrypoints share one transient reentrancy lock, cleared on return and rolled back on revert. The intended runtime must support EIP-1153, as the repository's OrderBook already requires. ## Typed cancellation and FOK orders The following methods use the existing `IntentHeader` and monotonic immediate-order nonce. Each has a distinct flat EIP-712 type; the exact schemas and executable calldata examples are in [`examples/trading-wallet.mjs`](https://github.com/Kuru-Labs/kuru-contracts-perps/blob/42ef525/docs/examples/trading-wallet.mjs). All amounts are integer market units: base quantity uses `sizePrecision`, limit price uses `pricePrecision`, and fees use the existing PPS scale. On the size-precision branch, raw base-token units equal normalized size times `baseSizeMultiplier`; do not submit token-wei quantities directly when that multiplier is not one. | Method | Signed payload and execution | | - | - | | `executeCancelOrdersById(header, orderIds, signature)` | Hashes the array as `keccak256(abi.encode(orderIds))`, resolves IDs in the market's 62 slots, and calls one cancellation-only `batch`. | | `executeCancelAll(header, signature)` | Cancels all resting orders live at execution in this account/market, including those placed after signing. | | `executeFokSwap(header, order, signature)` | `FokOrder(side, quantity, limitPrice)` becomes one native `FOK` order, with `NONE` execution instruction, zero `minSizeAfterBlock`, and no cancellation slots. | Cancellation requires a zero builder and zero fee. ID lists must contain 1–62 unique, nonzero, live IDs belonging to the signed account/market; missing/stale IDs revert the entire operation and nonce update. Partially filled live IDs cancel their remainder. No slot hints or reverse mapping are needed. Native cancellation pause rules apply: soft-paused markets allow cancellation; hard-paused markets do not. Cancel-all does not cancel triggers, TWAPs, passive positions, or orders in another market. All three methods return their signed digest and emit `IntentExecuted`. The native cancel-all entrypoint does not take a client ID: its book logs carry no signed ID, while the wallet event retains it. Correlate these by transaction, account, market, and call order. ID cancellation forwards the client ID to `batch`. Dedicated FOK methods are base-sized marketable-limit orders, not exact-input `swap()` calls. They inherit native dust tolerance: a successful FOK may leave an unfilled sub-executable remainder. They also inherit native self-order cancellation and fee/builder settlement. They do not return a filled amount. Use the actual packed trade records for fills, VWAP, and fees; a limit price is not a fee-inclusive spending cap. Existing generic `executeBatch` still supports GTC, IOC, and FOK unchanged. `createFokSwapTrigger(header, triggerExpiry, conditionHash, order, signature)` uses an unordered nonce and stores `TriggerAction.FOK_SWAP = 3`. Fire it through keeper-only `executeTrigger`, cancel through the existing signed `cancelTrigger`, and retain the existing expiry, epoch, and live authorization checks. Its signature is checked at creation only. A failed native FOK rolls back `FIRED` so the trigger remains retryable until expiry. No new condition verification is introduced. FOK trigger payloads are 17 packed bytes (`uint8 side`, `uint96 quantity`, `uint32 limitPrice`), stored inline in one word; they are not `abi.encode(FokOrder)` blobs. ## Persistent TWAP `createTwap(header, config, signature)` signs the header plus: ```solidity theme={null} struct TwapConfig { ISpotOrderBook.NativeSide side; uint96 totalQuantity; uint32 limitPrice; uint64 startTime; uint32 intervalSeconds; uint32 sliceCount; } ``` The start must be in the future. Interval/count/quantity must be positive, quantity must be exactly divisible by the count, and the derived end time must fit `uint64`. Schedule timestamps and deadlines are seconds; nonce skew remains milliseconds. The header deadline only bounds creation. Tick/notional validation and current builder approval remain authoritative in the OrderBook at execution; the client should preflight these constraints before creating a schedule. No funds are reserved on creation. For slice `i`, the execution bucket is `[startTime + i * intervalSeconds, startTime + (i + 1) * intervalSeconds)`. Only a current keeper can call `executeTwapSlice(twapId, executionReportHash)`. The wallet checks the current AccountCore epoch, live `TRADE`, and verified market. Creation already authenticated the immutable configuration, so execution neither rebuilds the creation digest nor recovers its signature. It computes the current bucket itself and executes `totalQuantity / sliceCount` at the static signed limit. Earlier missed buckets are skipped; there is no catch-up, quantity rollover, or resting child order. One successful native FOK consumes a bucket. Failure reverts all progress (including skipped-range events) and allows retry within the same bucket. The next successful attempt skips any now-past buckets. Progress advances before the market call under the shared transient reentrancy guard. The signed digest is `twapId`. Child client IDs are: ```solidity theme={null} keccak256(abi.encode("KURU_TWAP_SLICE", twapId, parentClientOrderId, uint32(sliceIndex))) ``` `getTwap` returns `TwapState(accountId, market, authNonce, clientOrderId, builder, builderFeePps, config, status, nextSliceIndex, successfulSliceCount)`. Creation nonce/deadline are in `TwapCreated`, not in the getter. Status values are `NONE=0`, `ACTIVE=1`, `CANCELED=2`, `FINISHED=3`. After schedule end, the getter projects `FINISHED` and `nextSliceIndex=sliceCount` without writing storage. `finalizeTwap` is permissionless after end and persists that transition; it reverts for unknown/already-terminal schedules. Executing the last bucket also persists `FINISHED`. `cancelTwap(accountId, authNonce, nonce, deadline, twapId, signature)` uses a fresh unordered nonce and the current AccountCore epoch/authorization. It may cancel a stored plan signed under an earlier epoch. An already time-expired plan must be finalized instead. Cancellation stops future slices. AccountCore revocation/epoch changes also prevent execution; changing delegation alone does not cancel a plan, because the EOA's storage survives. TWAP execution state is packed into five words, separately from its public input/getter structs. The stored slice quantity is computed once at creation; `getTwap` reconstructs total quantity from slice quantity times count. No creation signature, deadline, or nonce is retained per schedule. Creation/cancellation share the chain-local `usedTriggerNonce` mapping. Slice execution consumes no new user intent nonce and does not advance `lastSeenOrderNonce`. ## Events and keeper integration Index by `(chain, wallet address, twapId)`, not by implementation address. `TwapCreated` contains the header and config; `TwapSlicesSkipped` records half-open `[fromSlice,toSlice)` ranges; `TwapSliceExecuted` contains the index, requested nominal quantity, derived client ID, keeper, and opaque report hash. `TwapFinished` contains successful and skipped counts; `TwapCanceled` identifies the account and wallet. There is deliberately no onchain `filledQuantity` or `remainingQuantity` field. The service should: 1. Replay canonical creation/cancellation/finish logs and maintain an index of due schedules. 2. Use chain timestamps and live `getTwap` state; simulate immediately before submitting. 3. Maintain a pending transaction per `(chain, wallet, twapId, sliceIndex)`, reconcile receipts/replacements before retrying, and stop retries when that bucket expires. Competing keeper submissions are safe. 4. Reconcile reorgs by block hash/log identity, and finalize schedules whose last buckets expired. 5. Decode the specific deployed market's packed logs and correlate by wallet/account/market and child client ID. Each packed cycle emits the run appended first, then the other run. Filled size comes from `TradesPacked`; a nonzero `OperationOutcome` is only on the match-end record or a book sentinel. Show successful/skipped slices separately from actual filled base, VWAP, and fees. `IntentExecuted` means the immediate signature was accepted. `TriggerFired` means the trigger is terminal and is not retried. Both are emitted when the orderbook call returns, including when that order was not installed. Join them to packed logs on transaction, market, `accountId`, and `clientOrderId`. `nonce` on `IntentExecuted` is the new `lastSeenOrderNonce`; every immediate nonce at or below it is consumed. A resting order still comes only from a live `BookUpdatesPacked` record. Do not claim nominal successful-slice quantity as the actual fill: dust is explicit native behavior. For this branch's 64-byte packed trade records, filled size remains normalized; convert to raw base units using the market's multiplier before reconciling token balances. Use execution prices and the deployed market's fee/rounding rules for quote value and VWAP, not the schedule's limit price. Overlapping schedules compete for balances. Dedicated trading subaccounts avoid unintended interaction with maker orders. One transaction per slice and up to 62 getter calls per ID cancellation are the main gas costs. Frontend and keeper-service deployment are separate from this contract change. Use the [SDK signing guide](/sdk/trading-wallet) for integration and [signer lifecycle](/sdk/signer-lifecycle) for nonce allocation. # WithdrawalLimiter Source: https://docs.kuru.io/contracts/withdrawal-limiter Capacity, price validation, and owner-approved payouts. AccountCore owns balances and payouts. Its bound WithdrawalLimiter owns ordinary global USD capacity and token price-source reads. Every payout is synchronous and all-or-nothing. ## Ordinary capacity Withdrawals consume the oldest unexpired deposit credit first, then a capped allowance that accrues per second. Credit expires after 24 hours and is consumed once. Deposits do not refill the allowance; trades, fees, internal transfers, and unsolicited token transfers create no credit. `capacityUsd18` and `ratePerSecondUsd18` are configuration units. Flow valuation and the available bucket use USD36. Convert configuration to USD36 by multiplying by `1e18`. A configuration update first accrues under the old settings, then clamps to the new capacity; raising capacity grants no new credit. ## Prices and custody Each supported token has a configured price source. Deposits and ordinary or approved withdrawals require a positive, fresh, nonfuture price. Mainnet uses the [mainnet price-source bindings](/deployments/mainnet#price-sources), including Chainlink feeds for MON, USDC, WETH, and cbBTC and Kuru-published references for the other assets. Testnet uses [Kraken-backed ManualPriceSource contracts](/deployments/testnet#price-sources) with a 300-second maximum age. A source's existence does not prove its latest quote is currently usable. Standard nonrebasing assets with exact custody receipts and debits are supported. Pricing and token amount precision are distinct; deposits round down and withdrawals round up when valuation must discard precision. Native MON uses the zero-address sentinel. Global or token withdrawal freezes block ordinary and approved payouts. Protocol pause also blocks deposits. Time continues passing during a freeze or pause; resuming grants no additional credit. ## Previews `previewWithdrawal` reports valuation and capacity at the read state. It does not check every caller permission, reserve funds, reserve capacity, guarantee the recipient transfer, or guarantee the eventual transaction will succeed. Query free balance and permissions separately and simulate the exact payout. ## Authority-approved payout The root owner signs `ApprovedWithdrawal(address account,address token,address recipient,uint256 amount,uint256 nonce,uint256 deadline,uint64 authorityEpoch)` using AccountCore's version-1 domain. Here `account` is the root owner address. A delegate cannot substitute its signature for the owner's signature. The dedicated authority submits `fulfillApprovedWithdrawal`. The payout bypasses deposit credit and drip consumption, but preserves pricing, free-balance, freeze, pause, nonce, deadline, and transfer checks. Children must transfer funds to the root first. The approved-withdrawal nonce and authority epoch are separate from trading authorization epochs. See the [source specification](https://github.com/Kuru-Labs/kuru-contracts-perps/blob/42ef525/docs/Withdrawals.md) for exact arithmetic and source validation. The [mainnet](/deployments/mainnet) and [testnet](/deployments/testnet) deployment pages identify their respective limiters; do not assume a documented configuration value is live capacity. # Mainnet Deployments Source: https://docs.kuru.io/deployments/mainnet Contract addresses, tokens, market parameters, and price sources for Monad mainnet. This reference includes the current AccountCore and OrderBook implementations and the addresses and parameters from the [15 October 2026 mainnet deployment record](https://gist.github.com/devblixt/0093a81e9fc21b6c96e74ac3d3eb08e9). The [testnet reference](/deployments/testnet) lists the separate test deployment. Check live onchain state before sending transactions because administrative parameters can change. ## Network | Setting | Value | | - | - | | Network | Monad mainnet | | Chain ID | `143` | | RPC | `https://rpc.monad.xyz` | | Explorer | [https://monadvision.com](https://monadvision.com) | | Gas token | MON, 18 decimals | ## Contract addresses | Component | Address | Purpose | | - | - | - | | AccountCore proxy | `0x264123a9B96Cc1193944cC25C188f1bD3dFa670e` | ERC-20 spender; custody, deposits, withdrawals, accounts and signers | | WithdrawalLimiter proxy | `0xF059F4AAb49Bd3AFB62134145EeAF38Fe103F0eA` | Withdrawal budget and token-to-price-source mappings | | SpotRouter proxy | `0xBdDF3556701B7ECca5d69416CFfd7F86D37E52b3` | Market registration and administration | | KuruTradingWallet implementation | `0xa478b5a38aabDf8b31f0ec7443a274162214Cd18` | EIP-7702 delegation target | Approve and deposit tokens into **AccountCore**. Send direct trading calls to the **market address** below. Signed trading-wallet actions execute through the delegated EOA; KuruTradingWallet is its EIP-7702 implementation. ## Markets All nine markets quote USDC (`0x754704Bc059F8C67012fEd69BC8A327a5aafb603`, 6 decimals). There is no USDT/USDC market in this deployment. | Market | OrderBook address | | - | - | | MON/USDC | `0xc9dE998e272d59a19CEA3783C8dd44f87A86405D` | | WETH/USDC | `0x8121EE960066e4344A213F9aC7502395502aEe7a` | | cbBTC/USDC | `0xAE8E0cf4A9ff696b5f6EC0B1339200EB4c09E422` | | XAUt0/USDC | `0x9d29630Ae2DCf02cB0Cf05e17F45D95f01f15798` | | NVDAx/USDC | `0xf3FB2ec6ffb2A24506769bfaA3aD9B1EeB7D41Eb` | | SPYx/USDC | `0xBb180c8B6D3eE0b4316B224C53B80dC4e354d24F` | | QQQx/USDC | `0xEdf008258139ee23cf2bDB9C360f69131dC72708` | | TSLAx/USDC | `0xf884c7631a7150F28c139a3A9f8B669258b5b285` | | EWYx/USDC | `0xED3727e833200c849fbd18e15eD0D091c9B0F3aF` | ### Market parameters | Market | sizePrecision | pricePrecision | tickSize | passiveSpreadTicks | Passive spread (\$) | | - | - | - | - | - | - | | MON/USDC | 10000000000 | 100000000 | 100 | 100 | \$0.0001 | | WETH/USDC | 10000000000 | 10000 | 100 | 100 | \$1 | | cbBTC/USDC | 100000000 | 1000 | 100 | 100 | \$10 | | XAUt0/USDC | 1000000 | 10000 | 100 | 100 | \$1 | | NVDAx/USDC | 10000000000 | 10000 | 100 | 10 | \$0.1 | | SPYx/USDC | 10000000000 | 10000 | 100 | 10 | \$0.1 | | QQQx/USDC | 10000000000 | 10000 | 100 | 10 | \$0.1 | | TSLAx/USDC | 10000000000 | 10000 | 100 | 10 | \$0.1 | | EWYx/USDC | 10000000000 | 10000 | 100 | 10 | \$0.1 | Dollar spreads assume USDC = \$1. Passive spread is a configured market parameter, not the live bid/ask spread. Order quantity uses `sizePrecision`; order price uses `pricePrecision` and must align to `tickSize`. Deposits and withdrawals use token decimals. ### Fees and order limits | Parameter | Value | Contract value | | - | - | - | | Default maker fee | 1 bps | `defaultSpotMakerFeePps = 1000` | | Default taker fee | 2 bps | `defaultSpotTakerFeePps = 2000` | | Market maker/taker caps | 100 bps each | `makerFeePps = 100000`, `takerFeePps = 100000` | | Minimum quote notional | 10 USDC | `minQuoteNotional = 10000000` | | Maximum quote notional | 5,000,000 USDC | `maxQuoteNotional = 5000000000000` | AccountCore default fees are enabled. The 100-bps market values cap the applicable fees; the default trading rates are **1 bps maker / 2 bps taker**. Account-specific tiers and builder fees can affect the final charge. Fee rates use a denominator of `10000000`. See [OrderBook](/contracts/order-book) for fee calculation. The inclusive 10-USDC minimum applies to GTC orders, including post-only orders, at admission before fees. Native IOC and FOK orders are exempt from this minimum; the maximum notional and nonzero quote-notional checks still apply. The minimum does not apply to each partial fill. ## Tokens | Token | Address | Decimals | | - | - | - | | USDC | `0x754704Bc059F8C67012fEd69BC8A327a5aafb603` | 6 | | MON | `0x0000000000000000000000000000000000000000` | 18 | | WETH | `0xEE8c0E9f1BFFb4Eb878d8f15f368A02a35481242` | 18 | | cbBTC | `0xd18B7EC58Cdf4876f6AFebd3Ed1730e4Ce10414b` | 8 | | XAUt0 | `0x01bFF41798a0BcF287b996046Ca68b395DbC1071` | 6 | | NVDAx | `0xc845b2894dBddd03858fd2D643B4eF725fE0849d` | 18 | | SPYx | `0x90A2a4c76b5D8c0bc892A69EA28Aa775a8f2dD48` | 18 | | QQQx | `0xa753A7395cAe905Cd615Da0B82A53E0560f250af` | 18 | | TSLAx | `0x8aD3c73F833d3F9A523aB01476625F269aEB7Cf0` | 18 | | EWYx | `0x299c95Eb52BFd5Bc98d924bCE17197b64864589B` | 18 | MON is native: use `address(0)` as the token identifier and send `msg.value` with an AccountCore deposit. Do not transfer MON to the zero address. All five xStocks tokens have **18 decimals** and use **10^10 size precision** for orders. ## Price sources These USD sources value deposits and withdrawals; trade prices come from the orderbook. USDC has its own USD price rather than a fixed \$1 valuation. | Token | Price source address | Source | Maximum observation age | | - | - | - | - | | MON | `0x949b4C63901A72013E4195F0e110ee660892f116` | Chainlink MON/USD | 70 minutes | | USDC | `0x8Eee8E00bB25948F10ca4f4f3a80FC982244AdF6` | Chainlink USDC/USD | 70 minutes | | WETH | `0x64796C7Bc079cB9E2acd0844d4E487d8a0C8F864` | Chainlink ETH/USD | 70 minutes | | cbBTC | `0xA006f7Ef1E366cB60A3D5701Bb25c0fa0586F698` | Chainlink BTC/USD | 70 minutes | | XAUt0 | `0x6FC71cf5A846AE343D71112632d16C978B59FEB5` | Kuru-published USD reference | 5 minutes | | NVDAx | `0x587B1103b3282dcF32110bd0EB8A1cc6097d71ec` | Kuru-published USD reference | 5 minutes | | SPYx | `0xA6589464443419C70a05d1F457F4941D678b235C` | Kuru-published USD reference | 5 minutes | | QQQx | `0x36E43bA74243e49fbeB847fF16f7E20302a0C62E` | Kuru-published USD reference | 5 minutes | | TSLAx | `0x532Dc864931896aCFb2C719c163e4BE61874C2bC` | Kuru-published USD reference | 5 minutes | | EWYx | `0xD89be8ed6F7190b3d0522d7Df8d43B430b8a3E14` | Kuru-published USD reference | 5 minutes | WETH uses ETH/USD and cbBTC uses BTC/USD at 1:1. The maximum age is the contract acceptance limit, not a publication schedule. Stale observations can prevent deposits or withdrawals until fresh prices become available. > [accordion] Implementation and authority addresses > > | Component | Address | Purpose | > | - | - | - | > | ProtocolAuthority | `0x15db88bAc73D856B3ca53683F82058826A3b6E8f` | Governance, ops and emergency role registry | > | KeeperAuthority | `0xbc36eC07800150489f9ED0f86a2d3E27Ca36980e` | Trading-wallet keeper authorization | > | AccountCore implementation | `0xB52deBaD718730eE0a4C12C28E70d346dbCc9E5B` | Implementation behind AccountCore proxy | > | WithdrawalLimiter implementation | `0x64E621868318a68DfD1F374EC75bd3Cd5B72b349` | Implementation behind limiter proxy | > | SpotRouter implementation | `0x70DD3E2F643A187D34eD54a58AFEdF717464FCD9` | Implementation behind router proxy | > | Shared OrderBook implementation | `0x05F6A84C7c43176C83F2DBC99670281987DEb4AC` | Implementation behind all nine market proxies | > | KuruFastLanePeriphery | `0x86400a84364e167b933b18e1484369679cDbEcA9` | FastLane execution adapter for the current trading wallet | > > Use the AccountCore, WithdrawalLimiter and SpotRouter proxies above for contract calls. Their implementation addresses identify the code behind those proxies. # Testnet Setup Source: https://docs.kuru.io/deployments/setup Prepare a wallet, test assets, and the right integration versions. Use Monad testnet, chain ID `10143`, with a dedicated test wallet. The [deployment reference](/deployments/testnet) contains the current AccountCore, market, token, and wallet addresses. ## Fund your wallet You need testnet MON for transactions you submit yourself and the test assets used by your chosen market. The current deployment uses admin-mintable dummy ERC-20s and has no public token faucet. Request those assets from your Kuru integration contact. ## Choose your route For a first contract integration, install the [reviewed SDK release](/sdk/installation) and follow [First Trade](/sdk/quickstart). Direct transactions do not require a hosted Relay login. For sponsored trading, follow [Delegated Trading with Relay](/sdk/relay-onboarding). For frontend data, start with [Reading Market Data](/api/market-data) and [Account Activity](/api/account-activity). ## Before sending a transaction Check the chain ID, target proxy, token decimals, market precision, and current market state. Read available funds and live permissions. Await successful receipts, then reconcile the resulting balance and order state. # Testnet Deployments Source: https://docs.kuru.io/deployments/testnet Contract addresses, tokens, market parameters, and price feeds for Monad testnet. Use these addresses for the current Kuru Spot testnet deployment. For a first integration, follow [Testnet Setup](/deployments/setup) and [First Trade](/sdk/quickstart). ## Network | Setting | Value | | - | - | | Network | Monad testnet | | Chain ID | `10143` | | RPC | `https://testnet-rpc.monad.xyz` | | Explorer | [https://testnet.monadvision.com](https://testnet.monadvision.com) | | Gas token | MON, 18 decimals | ## Contract addresses | Component | Address | Purpose | | - | - | - | | AccountCore proxy | `0xe08573a1Ecc4aa507c9626071fA0c4513caf7906` | ERC-20 spender; custody, deposits, withdrawals, accounts, signers, internal transfers | | WithdrawalLimiter proxy | `0x8cF002a44CeD91Ab93A5E4E6F893F1f7b5a9c0e5` | Global withdrawal budget, per-token oracle bindings, capacity previews | | SpotRouter proxy | `0x008200AD02fCb7020B019D11Cbabd32FecE1De78` | Market deployment/registration and market administration | | KuruTradingWallet implementation | `0xC400874c327eD8f2d6933d77e98b3a358D79ab96` | EIP-7702 delegated trading logic | | AccountCore implementation | `0x53ef3c1749a7f966Bf6Be2ed84f854A878b34522` | Implementation behind AccountCore proxy | Approve and deposit tokens into **AccountCore**. Send trading calls to the **market address** below. The KuruTradingWallet address is the EIP-7702 delegation target; signed wallet actions execute through the delegated EOA. ## Markets All markets quote USDC (`0xb01DC575a7ef75e58A05D2bde73ab79f8e7dd0Be`, 6 decimals). | Market | OrderBook address | | - | - | | MON/USDC | `0xD2F64EaF7E85688802d24C18ea268C365533b344` | | WETH/USDC | `0x0A082280e4eA3D822E23Ec1186685477241A039d` | | cbBTC/USDC | `0x87A177348710BE5cc1B025ce20CABAB267C90Bf6` | | USDT/USDC | `0xF72dD31A8a73629860Cbbb78a58BcA3C6462FC2f` | | XAUT/USDC | `0xC251fb72974a178f58F68cD7Ef7A510FA469feA9` | | NVDAx/USDC | `0xE9C2B9E0F296dbeC9dcc3C8F0F64928F2F8bC081` | | SPYx/USDC | `0x185Af307dAfd968033337A0180E66B920B4b05Ca` | | QQQx/USDC | `0x6679386F98437f02f5Cad51E6835e93C002213d9` | | TSLAx/USDC | `0x7A53BB8d8A8765418FfE331A02BF5984264922AA` | | EWYx/USDC | `0xB353E3bAe839a125EcDF482d3149231E91c7040c` | ### Market parameters | Market | sizePrecision | pricePrecision | tickSize | passiveSpreadTicks | Passive spread (\$) | | - | - | - | - | - | - | | MON/USDC | 10000000000 | 100000000 | 100 | 100 | \$0.0001 | | WETH/USDC | 10000000000 | 10000 | 100 | 100 | \$1 | | cbBTC/USDC | 100000000 | 1000 | 100 | 100 | \$10 | | USDT/USDC | 1000000 | 100000000 | 100 | 100 | \$0.0001 | | XAUT/USDC | 1000000 | 10000 | 100 | 100 | \$1 | | NVDAx/USDC | 10000000000 | 10000 | 100 | 10 | \$0.10 | | SPYx/USDC | 10000000000 | 10000 | 100 | 10 | \$0.10 | | QQQx/USDC | 10000000000 | 10000 | 100 | 10 | \$0.10 | | TSLAx/USDC | 10000000000 | 10000 | 100 | 10 | \$0.10 | | EWYx/USDC | 10000000000 | 10000 | 100 | 10 | \$0.10 | Dollar spreads assume USDC = \$1. Passive spread is a configured market parameter, not the live bid/ask spread. Order quantity uses `sizePrecision`; order price uses `pricePrecision` and must align to `tickSize`. Deposits and withdrawals use token decimals. ### Fees and order limits | Parameter | Value | Contract value | | - | - | - | | Maker fee | 0 bps | `makerFeePps = 0` | | Taker fee | 2 bps | `takerFeePps = 2000` | | Minimum quote notional | 10 USDC | `minQuoteNotional = 10000000` | | Maximum quote notional | 5,000,000 USDC | `maxQuoteNotional = 5000000000000` | Fee rates use a denominator of `10000000`. The inclusive 10-USDC minimum applies to GTC orders, including post-only orders, at admission before fees. Native IOC and FOK orders are exempt from this minimum; the maximum notional and nonzero quote-notional checks still apply. The minimum does not apply to each partial fill. Account-specific fee tiers and builder fees can affect the final charge; see [OrderBook](/contracts/order-book). ## Tokens These ERC-20s are mintable test tokens with no underlying backing. Request them from your Kuru integration contact. | Token | Address | Decimals | | - | - | - | | USDC | `0xb01DC575a7ef75e58A05D2bde73ab79f8e7dd0Be` | 6 | | MON | `0x0000000000000000000000000000000000000000` | 18 | | WETH | `0xB711D972876AE19481fFD1AB2047B8e5E31BEe5F` | 18 | | cbBTC | `0x7bC3a5FCEB95bE797D57eE762B881596B3cfA992` | 8 | | USDT | `0x4BAF98Bf7a70725e73B20ea61b00271878115A4c` | 6 | | XAUT | `0xc48194f3d9C9f6B461eB3a6aCd3bFe09882dc662` | 6 | | NVDAx | `0x1cA0772B36E70ff54525afee1DAEe846Cd914D02` | 18 | | SPYx | `0x8BF70Ce58A038f741b4e187ADea126c8cAB867c2` | 18 | | QQQx | `0x251f5e6e1F4fe6E55BA285EfA6518B2707C9EFE0` | 18 | | TSLAx | `0x7DA7742FCdFD472697A52B0Aaff818CAe3139656` | 18 | | EWYx | `0x184659b7968Bd56f0243523183c923459e757548` | 18 | MON is native: use `address(0)` as the token identifier and send `msg.value` with an AccountCore deposit. Do not transfer MON to the zero address. All five xStocks test tokens have **18 decimals** and use **10^10 size precision** for orders. ## Price sources All assets use Kraken-backed USD price feeds with a **5-minute maximum age**. These feeds value deposits and withdrawals; trade prices come from the orderbook. USDC is priced independently rather than fixed at \$1. | Token | Price source address | Kraken pair | | - | - | - | | USDC | `0x29064f22175DBD7394aC7a61e3CC42Fb377175B7` | USDC/USD | | MON | `0xC04Eb468d897bb1b543316DdD891D6988Bd7a9f2` | MON/USD | | WETH | `0x31ed90038A9Dd392E722644b5D6ca579F6adD4CB` | ETH/USD | | cbBTC | `0x14F3BC859ee8186cFc8eAb3FA265EdFF372688cD` | BTC/USD | | USDT | `0xbC78aE7F2af29508C73f2c5e399A35cF675A2B2B` | USDT/USD | | XAUT | `0xD004a407B74774F6af8C33756bF0d77C0AA366Db` | XAUT/USD | | NVDAx | `0x8d57Ed0dB408dD9070B64A7f3E342918759a5706` | NVDAx/USD | | SPYx | `0x46dc38474332E6A90a4d4De992f44E5A184C677e` | SPYx/USD | | QQQx | `0xaAF16f6f23a913bbE6DaA5f3658FBd53Cc62f09D` | QQQx/USD | | TSLAx | `0xa79d18CA2aE83D9Ff574Cfdca39aFB99965cfc08` | TSLAx/USD | | EWYx | `0x30dC3DBed2aA61D7aEd85484F855E33bDf76aC9E` | EWYx/USD | WETH uses ETH/USD and cbBTC uses BTC/USD at 1:1. XAUT uses the Kraken XAUT token price. Stale prices can prevent deposits or withdrawals until fresh prices become available. > [accordion] Implementation and authority addresses > > | Component | Address | Purpose | > | - | - | - | > | ProtocolAuthority | `0xb8EF6b8C854524E4253AE37CbD8Cae11cA401d7e` | Governance, ops and emergency role registry | > | KeeperAuthority | `0x39175d4e1F80d6D9fA2806c16B1117aa64757E02` | Trading-wallet keeper authorization | > | WithdrawalLimiter implementation | `0xaDaE49FA31Cc63378581C3975ddBc2AbE2e61022` | Implementation behind limiter proxy | > | SpotRouter implementation | `0xb62B28815C0c7f0F97fe6a17D4C582dF2Ee48B8d` | Implementation behind router proxy | > | Shared OrderBook implementation | `0xf9f74bF55EE277a35DceD86e7d4d94c0deBEBc78` | Implementation behind all ten market proxies | > > Use the AccountCore, WithdrawalLimiter and SpotRouter proxies above for contract calls. Their implementation addresses identify the code behind those proxies. # What is Kuru? Source: https://docs.kuru.io/index Explore Kuru Spot V2 on Monad mainnet and testnet, with guides for trading, accounts, APIs, and the SDK. Kuru is a decentralized spot exchange built on Monad. You can buy and sell tokens through an onchain order book, choosing the price and amount you want to trade. ## Trading on Kuru Each market pairs two assets. On WETH/USDC, for example, you spend USDC to buy WETH or sell WETH to receive USDC. Orders match against available liquidity, with better prices executing first. You can place a limit order at your chosen price, trade against existing liquidity, or provide liquidity for other traders. Your order's settings determine whether an unfilled amount stays open or is canceled. ## Explore the exchange > [card] [Spot trading](/introduction/spot) > > Understand markets, prices, and how a trade happens. > [card] [Accounts and balances](/accounts/overview) > > Learn where your funds are held and how open orders use them. > [card] [Order types](/matching-engine/order-types) > > Choose how and when your order can execute. > [card] [Passive liquidity events](/matching-engine/passive-liquidity) > > Understand passive execution and event indexing. ## Accessing Kuru These docs cover Kuru on Monad mainnet, with testnet available for integration testing. The public Spot V2 frontend is live for trading, including [One Click Trading](/accounts/one-click-trading). Developers can also use the [mainnet deployment](/deployments/mainnet), [APIs](/api/introduction), and [SDK](/sdk/overview). See [Getting Started](/introduction/getting-started) for network-specific preparation. ## Building on Kuru The [API](/api/introduction) and [SDK](/sdk/overview) sections cover integration: submitting trades, reading market data, and building applications. Start there when you are ready to write code. # AccountCore Events Source: https://docs.kuru.io/indexing/account-core Reconstruct ID-based accounts, balances, and root-wide permissions. Process logs in block, transaction, and log order, and retain block hashes for rollback. Account IDs are persistent numeric identities; a child has no account address. ## Identity and permissions | Event | Reducer action | | - | - | | `AccountRegistered(accountId, rootAccountId, rootOwner, subaccountSeq)` | Store the ID, owner, root, and sequence; root sequence is zero | | `SubaccountCreated(rootAccountId, subaccountId, authorizer)` | Record child creation and actor provenance | | Signer authorization/revocation events | Update the root grant and epoch; apply it to all family members | Creating a child does not increment the authorization epoch. Preserve the exact stored permission bits and apply role implications when evaluating effective access. Use the current exported AccountCore ABI for parameter ordering and indexed fields. ## Balances Use deposit, withdrawal, and internal-transfer events for activity history. `SpotReserveUpdated` provides absolute free and active-order-reserved balances. Apply every snapshot in log order; the last snapshot for an ID/token within a transaction is its final state. Deposits credit roots. Withdrawals debit roots and pay an explicit external recipient. Internal transfers move free balance between IDs in one family. A registered recipient of a withdrawal still receives an external payout, not ledger credit. Passive inventory is separate from free and order-reserved balance. Join the market's position/band events for a complete portfolio. ## Builder fees Positive fees credit the builder's root free balance. AccountCore can register that root during accrual. The balance snapshot precedes `BuilderFeeAccrued`; record fee attribution but do not add it to a second claim ledger or double-credit the snapshot. Zero-fee attribution need not create a builder root. Builder withdrawals follow normal root custody events. ## Withdrawal controls Index the limiter binding, token price-source bindings, drip configuration, withdrawal freezes, dedicated withdrawal authority/epoch, and approved-withdrawal events using their emitting contracts' current ABIs. Limiter capacity and oracle freshness depend on time, so stored events alone are not a current executable-withdrawal quote. Use [WithdrawalLimiter](/contracts/withdrawal-limiter) for the distinction between ordinary capacity and approved payouts. # OrderBook Events Source: https://docs.kuru.io/indexing/order-book Packed records, operation outcomes, and canonical book reconstruction. This reference follows the merged OrderBook implementation at `cdac5ae1`. Packed record widths remain unchanged: trade records are 64 bytes and book records are 39 bytes. Their outcome bits now explain operations that may not create a resting order. Start with [SDK Events](/sdk/events) if you only need to decode receipts. Read the reducers below when maintaining your own book or fill history. This guide describes how to index Spot orderbooks from events. The orderbook emits separate streams for active FIFO orders, passive bands, swaps, account accounting, and market configuration. A production indexer should process logs in `blockNumber, transactionIndex, logIndex` order and should handle chain reorgs by rolling back all derived state for orphaned blocks. The core active-order events are: * `TradesPacked(accountId, executor, clientOrderId, effectiveTakerFeePps, builder, builderFeePps, packedTrades)` * `BookUpdatesPacked(accountId, executor, clientOrderId, packedUpdates)` The core passive-liquidity events are: * `PassiveBandUpdated(...)` * `PassiveLiquidityMinted(...)` * `PassiveLiquidityBurned(...)` * `PassiveFeesClaimed(...)` `SpotSwap` is a taker-level execution summary. It is useful for user history and analytics, but it is not sufficient for orderbook mirroring. ## Market Discovery Index these events to discover markets and maintain configuration state: * `SpotRouter.SpotMarketRegistered(orderBook, baseToken, quoteToken, operator, sizePrecision, pricePrecision, minQuoteNotional, tickSize, passiveSpreadTicks, quoteTokenDecimals, takerFeePps, makerFeePps)` * `AccountCore.SpotMarketRegistered(orderBook, baseToken, quoteToken, registrar)` * `SpotRouter.SpotMarketStateUpdated(orderBook, previousState, newState, operator)` * `OrderBook.MarketStateUpdated(previousState, newState)` * `AccountCore.SpotTokenConfigured(token, decimals, enabled, operator)` * `SpotRouter.SpotTokenWhitelisted(token, status, operator)` * `AccountCore.DefaultSpotFeesUpdated(makerFeePps, takerFeePps, active, operator)` * `AccountCore.AccountFeeTierUpdated(rootAccountId, makerFeePps, takerFeePps, active, operator)` * `AccountCore.BuilderReferralTierUpdated(builder, makerFeePps, takerFeePps, expiry, active, operator)` * `AccountCore.BuilderReferralUpdated(rootAccountId, builder, actor, makerFeePps, takerFeePps, expiry, active)` * `AccountCore.FeeCollectorUpdated(oldFeeCollector, newFeeCollector, operator)` — state * `AccountCore.ProtocolStateUpdated(previousPaused, paused, operator)` — state * `AccountCore.PostFillHookAccessUpdated(accountId, allowed, operator)` — state * `SpotRouter.SpotMarketUpgraded(orderBook, newImplementation, operator)` — state `operator` on these config events is provenance. It does not replace the new value as the stored state. For each `orderBook`, cache: * `baseToken` * `quoteToken` * `pricePrecision` * `sizePrecision` * `baseSizeMultiplier` * `tickSize` * `passiveSpreadTicks` * `quoteTokenDecimals` * current market state `getMarketParams()` returns common price/size/notional/fee fields. Spot-specific fields such as `baseToken`, `quoteToken`, `quoteTokenDecimals`, `baseSizeMultiplier`, and `passiveSpreadTicks` are public getters on `OrderBook`. The router event is the canonical deployment signal and includes `sizePrecision`, `pricePrecision`, `minQuoteNotional`, `tickSize`, `passiveSpreadTicks`, `quoteTokenDecimals`, and market-level `takerFeePps` / `makerFeePps`. `minQuoteNotional` is raw quote atoms. The AccountCore event confirms settlement authorization. For liveness changes, the nested orderbook event remains the market-state mutation while the outer router event identifies the real operator. Forwarded ownership proposes emit the book's `OwnershipTransferStarted` log and `SpotRouter.ManagedContractOwnershipTransferStarted` with the router caller. Accept emits `OwnershipTransferred` and, when the router accepts a reclaim, `ManagedContractOwnershipTransferred`. ## Packed Trade Records `TradesPacked` contains one or more 64-byte records. Each record is two 256-bit words. Word 0: * `userId`: bits `255:216` * `slotIdx`: bits `215:208` * `makerFlags`: bits `207:200` * `price`: bits `199:168` * `fillSize`: bits `167:72` * `orderId`: bits `71:8` * `operationIndex`: bits `7:0` (meaningful only when outcome is nonzero) Word 1: * `updatedSize`: bits `255:160` * `makerFeePps`: bits `159:136` (`uint24`) * `replacementSlot`: bits `135:128` (meaningful only when outcome is nonzero) * reserved: bits `127:64` * `tradeId`: bits `63:0` `makerFlags & 1 == 1` means the maker side was buying, so the trade hit a bid and the taker sold base. `makerFlags & 1 == 0` means the maker side was selling, so the trade hit an ask and the taker bought base. `makerFlags & 2 != 0` marks a passive-band fill. Passive records use `userId = 0`, `slotIdx = 0` for passive bid fills, `slotIdx = 1` for passive ask fills, and `orderId = lowPrice`. `makerFlags & 4 != 0` marks the final record of one successfully finalized match. A swap has one match. Each native order that matches, and each packed replacement that matches, has its own match. A crossing `POST_ONLY` never opens a match. A crossing ALO does not match. Empty matches add no marker. Every nonempty match ends at exactly one marked record, including passive-only and hook-replenished matches. `(makerFlags >> 3) & 0x1f` is the terminal `OperationOutcome`. A nonzero outcome appears only on a `MATCH_END` record. It binds that match to `operationIndex`; `replacementSlot` is the caller-selected packed-replace slot or `0xff` for a native batch order. For fill-plus-rest, both this trade record and the resulting live book record carry `RESTED` and the same operation index. Swap matches keep outcome zero. Active records carry the resting order's snapshotted `makerFeePps`. Passive records carry zero because passive LP spread accounting is not an active maker protocol fee. For active FIFO records, `updatedSize` is the maker order's remaining size after the fill. It is zero when the slot was removed by the fill or by a residual cancellation. For passive records, `updatedSize` is the remaining visible size on the filled side after the fill. It is tape context. Band inventory and displayed passive depth come from `PassiveBandUpdated`, not from this field. Use `TradesPacked` for the complete active plus passive trade tape. Each record's `tradeId` is a monotonic market-local fill id. A stable individual fill key is: ```text theme={null} chainId, orderBook, tradeId ``` `recordIndex` remains useful for preserving execution order inside one packed event, but it is not part of the canonical fill identity. To compute raw quote notional offchain, first classify the record by side and passive flag. Active bids and passive bids use the market's two-stage floor: ```text theme={null} priceSizeUnits = floor(price * fillSize / sizePrecision) quoteAmount = floor(priceSizeUnits * 10^quoteTokenDecimals / pricePrecision) rawBaseAmount = fillSize * baseSizeMultiplier ``` Passive asks replace both floors with ceilings for each record. Active asks share one exact accumulator within a match. Reset `N = 0` after every `MATCH_END`; for each active-ask record in execution order use: ```text theme={null} n = price * fillSize * 10^quoteTokenDecimals D = sizePrecision * pricePrecision quoteAmount = ceil((N + n) / D) - ceil(N / D) N += n ``` Passive records do not contribute to `N`. This reconstructs the exact quote credited to each active ask maker and the quote charged to the taker. FIFO order determines which active maker receives a rounding atom. `fillSize` and `updatedSize` remain normalized orderbook quantities. AccountCore settlement, swap results, passive-liquidity amounts, and token custody use raw token atoms. The multiplier is exact and immutable for a fresh market: ```text theme={null} baseSizeMultiplier = 10^baseTokenDecimals / sizePrecision ``` Split records at `MATCH_END`. For each match, sum raw quote `Q`, convert and sum raw base `B`, and the per-active-record maker fee floors. With `PPS = 10_000_000`: ```text theme={null} takerFeeQuote = ceil(Q * effectiveTakerFeePps / PPS) buyBuilderFeeBase = ceil(B * builderFeePps / PPS) sellBuilderFeeQuote = ceil(Q * builderFeePps / PPS) makerFeeQuote = sum(floor(recordQuote * makerFeePps / PPS)) ``` The action-level fee context applies to every delimited match in that packed event. The match markers are necessary because ceiling once per match differs from ceiling once across the whole batch. ## Packed Active Book Updates `BookUpdatesPacked` contains one or more 39-byte records. Each record is: * a 32-byte header word * a trailing 4-byte `minSizeAfterBlock` * a trailing 3-byte `makerFeePps` Header word: * `userId`: bits `255:216` * `slotIdx`: bits `215:208` * `bookFlags`: bits `207:200` * `price`: bits `199:168` * `size`: bits `167:72` * `orderId`: bits `71:8` * `operationIndex`: bits `7:0` (meaningful only when outcome is nonzero) Trailing bytes: * `minSizeAfterBlock`: uint32, big-endian * `makerFeePps`: uint24, big-endian `bookFlags & 1 == 1` means maker buy/bid. `bookFlags & 1 == 0` means maker sell/ask. `bookFlags & 0x80 != 0` means the slot is live after this update. `(bookFlags >> 1) & 0x1f` is the terminal `OperationOutcome`; bit 6 remains reserved. Always mask these fields rather than comparing the complete flags byte. Live records carry the live order's `price`, `size`, `orderId`, side, `minSizeAfterBlock`, and snapshotted maker fee. The rate remains per record because hook-generated updates in one action can belong to different makers. Non-live records carry the removed contribution's `price`, `size`, side, and `orderId`; `minSizeAfterBlock` and `makerFeePps` are zero. The `size` in a non-live record is the non-trade amount removed from visible active depth. This is usually the full cancelled/replaced order size. Pure full fills do not emit a matching `BookUpdatesPacked` delete because the executed size is already represented by `TradesPacked`. An outcome-tagged non-live record with `userId = 0`, `price = 0`, `size = 0`, `orderId = 0`, and zero trailers is an operation sentinel, not a book delta. Its `slotIdx` is the packed-replace target or `0xff` for a native order. Record the outcome and skip the record entirely for L2 and L3. ## Per-Operation Outcomes Numeric outcome codes are stable protocol schema: | Code | Outcome | Meaning | | -: | - | - | | 0 | `NONE` | Ordinary maker, hook, swap, or maintenance record; ignore operation metadata | | 1 | `FILLED` | Requested quantity fully executed | | 2 | `RESTED` | A new live order exists | | 3 | `COMPLETED_NO_REST` | Fills are kept and no remainder is rested. With no fill, the book record is a zero-fill cross | | 4 | `IOC_PARTIAL` | IOC executed partially and discarded its remainder | | 5 | `IOC_UNFILLED` | IOC executed zero | | 6 | `POST_ONLY_NOT_PLACED` | Native POST_ONLY or packed ALO would cross | | 7 | `CANCELLED` | User-requested live cancellation | | 8 | `PROTOCOL_CANCELLED` | Governance/ops/emergency cancellation | | 9 | `CANCEL_NOOP` | Packed cancel targeted an empty slot | | 10 | `DUST_REMAINDER_DISCARDED` | A real fill left a sub-unit taker remainder | `COMPLETED_NO_REST` does not mean the submitted order was fully filled. It means matching is complete for this operation, any successful fills remain committed, and the residual is deliberately not placed because the limit still crosses a best price at which matching could not make progress. Its receipt therefore has the actual summed executed quantity, `restingQuantity = 0`, and no new order id. When at least one fill exists, the outcome is on the `TradesPacked` `MATCH_END` record. When nothing filled, the same code is on `BookUpdatesPacked` and is read as a zero-fill cross: nothing executed, the limit still crosses, and nothing is rested. [Outcomes on TradesPacked](#outcomes-on-tradespacked) and [Outcomes on BookUpdatesPacked](#outcomes-on-bookupdatespacked) list every case for each event. Operation order is deterministic: * `replaceBySlotPacked`: index in `packedOps` * `batch`: every `cancelSlotIdxs` entry first, followed by every native order * `protocolCancelBySlots`: index in `slotIdxs` Self-match cleanup during a native or packed-replace match is not an additional input operation. Its book DELETE carries outcome `NONE` and must be applied to L2/L3 normally. The incoming order keeps its original operation index and later receives its own terminal result. For example, a self-only IOC produces an untagged self-order DELETE followed by an `IOC_UNFILLED` sentinel for the IOC. Exact-input `swap` instead enables self-trade reversion, so its transaction reverts rather than performing this cleanup. Post-fill hook cancels, replacements, and replenishments are also maker-side effects rather than separate submitted operations. Their DELETE and LIVE book records carry outcome `NONE`, have no meaningful operation index, and remain canonical L2/L3 changes. If a hook-created order is consumed synchronously, its fill remains inside the parent taker match. Intermediate fill records remain untagged; only the final `MATCH_END` carries the parent operation's outcome and index. Do not create separate operation receipts for hook actions. Packed logs are one log per contiguous run. A cycle holds at most one book run and one trade run. The run appended first is emitted first. A fill followed by a hook emits `TradesPacked` and then `BookUpdatesPacked`. A cancel or rest followed by a fill emits `BookUpdatesPacked` and then `TradesPacked`. A second run of either kind starts the next cycle. Apply the logs in that receipt order. A `TradesPacked` does not have to end with `MATCH_END`; the flag is on the last fill of a match and can be in a later trade log. A hook replenish is appended after the fill that freed its slot, so that fill is emitted before the live. `updatedSize = 0` clears the slot while that order id is still the occupant. The following live is then the only order on the slot. `batch` permits at most 256 total cancellations plus orders. Packed replacements already permit at most 62 unique slots. For log-only reconstruction, callers should provide a nonzero `clientOrderId` that is unique per orderbook call within one transaction. A transaction can call the same book more than once, so `transactionHash` plus a zero or reused client id is not a unique action key. In that case an indexer must use the transaction call trace/call ordinal rather than merging records by client id. Build a receipt keyed by `(chainId, orderBook, actionKey, operationIndex)`, where `actionKey` is the unique client id or traced call ordinal. Sum `fillSize` from the prior `MATCH_END` through a tagged `MATCH_END` for `executedQuantity`. A tagged live book record supplies `restingQuantity = size` and `newOrderId = orderId`. All other outcomes imply zero resting quantity and no new order id. IOC unfilled quantity remains `submittedQuantity - executedQuantity`, using the submitted calldata or signed intent. Hard validation failures and a FOK with nonzero executable remaining quantity revert the whole transaction, so they have no surviving operation record. A post-fill remainder below one executable unit is instead discarded as dust; the FOK succeeds and emits `DUST_REMAINDER_DISCARDED`. Use the transaction receipt for reverted failures. Each successful operation ends in exactly one tagged record. The exception is `RESTED` after a fill, which tags both the `MATCH_END` trade record and the new live book record with the same `operationIndex`. The sections below list every case twice: first per event, then per operation. `test/spot/SpotOutcomeScenarioTest.t.sol` has a test for each case. ### Outcomes on TradesPacked Only the `MATCH_END` record of a `batch` order or a `replaceBySlotPacked` operation carries a nonzero outcome. Every other trade record has outcome `NONE`, including every `swap` record. ```mermaid theme={null} flowchart TD row["TradesPacked record"] --> last{"MATCH_END of a batch order
or packed replace?"} last -->|"no, or a swap record"| none["NONE"] last -->|yes| remaining{"Size left
after matching?"} remaining -->|no| dust{"Sub-unit leftover
dropped?"} dust -->|yes| dustOut["DUST_REMAINDER_DISCARDED"] dust -->|no| filled["FILLED"] remaining -->|yes| ioc{"Native IOC?"} ioc -->|yes| partial["IOC_PARTIAL"] ioc -->|"no: GTC or packed replace"| cross{"Leftover still crosses
the opposite best price?"} cross -->|yes| noRest["COMPLETED_NO_REST"] cross -->|no| rested["RESTED
the new live book record is also RESTED"] ``` | Outcome | Native `batch` order, `replacementSlot = 0xff` | Packed replace, `replacementSlot` = target slot | | - | - | - | | `NONE` | Every record of the match before `MATCH_END` | Same | | `FILLED` | GTC, IOC, or FOK executed its full size | Executed its full size | | `DUST_REMAINDER_DISCARDED` | GTC, IOC, or FOK had a real fill, then dropped a leftover below one executable unit | Same | | `IOC_PARTIAL` | IOC filled some size and discarded the rest | Does not occur | | `RESTED` | GTC filled some size, and the leftover no longer crosses, so it rests | Same | | `COMPLETED_NO_REST` | GTC filled some size, but the leftover still crosses the opposite best price, so it is not placed | Same | * The tagged record can be a passive record (`makerFlags & 2 != 0`) when the match ends on a passive band. Its outcome, `operationIndex`, and `replacementSlot` still apply; `userId`, `slotIdx`, and `orderId` use the passive encoding. * In a packed replace, the old order's delete is `NONE` whenever the result is on the trade record. * `IOC_UNFILLED`, `POST_ONLY_NOT_PLACED`, `CANCELLED`, `PROTOCOL_CANCELLED`, and `CANCEL_NOOP` never appear on `TradesPacked`. An operation with no fill has no trade record, so its outcome is on `BookUpdatesPacked`. ### Outcomes on BookUpdatesPacked Every book record is one of three kinds: * live: `bookFlags & 0x80 != 0` * delete: not live, and `userId != 0` * sentinel: not live, and `userId = 0` Apply live and delete records to L2 and L3 whatever their outcome. Never apply a sentinel. ```mermaid theme={null} flowchart LR row["BookUpdatesPacked record"] --> kind{"Record kind"} kind -->|live| liveBy{"Placed by"} liveBy -->|"the operation"| rested["RESTED"] liveBy -->|"a post-fill hook"| liveNone["NONE"] kind -->|"delete, userId != 0"| deleteBy{"Removed by"} deleteBy -->|"batch cancel or packed cancel-only"| cancelled["CANCELLED"] deleteBy -->|protocolCancelBySlots| protocol["PROTOCOL_CANCELLED"] deleteBy -->|"packed ALO that still crosses"| aloDelete["POST_ONLY_NOT_PLACED"] deleteBy -->|"packed replace with no fill
that still crosses"| zeroFillDelete["COMPLETED_NO_REST
zero-fill cross"] deleteBy -->|"self-match cleanup, cancelAllOrders,
hook cancel, or a replaced old order"| deleteNone["NONE"] kind -->|"sentinel, userId = 0"| sentinelBy{"Operation"} sentinelBy -->|"native POST_ONLY would cross"| s1["POST_ONLY_NOT_PLACED
slot 0xff"] sentinelBy -->|"native IOC with no fill"| s2["IOC_UNFILLED
slot 0xff"] sentinelBy -->|"native GTC with no fill
that still crosses"| s3["COMPLETED_NO_REST
slot 0xff"] sentinelBy -->|"packed ALO would cross,
empty slot"| s4["POST_ONLY_NOT_PLACED
target slot"] sentinelBy -->|"packed cancel-only,
empty slot"| s5["CANCEL_NOOP
target slot"] sentinelBy -->|"packed replace with no fill
that still crosses, empty slot"| s6["COMPLETED_NO_REST
target slot"] ``` Live records: | Case | Outcome | | - | - | | Native `POST_ONLY` that does not cross | `RESTED` | | Native GTC with no fill whose limit does not cross when it is placed | `RESTED` | | Native GTC that filled some size, with a leftover that no longer crosses | `RESTED`. The `MATCH_END` trade record is also `RESTED` | | Packed replace, including ALO, with no fill whose limit does not cross when it is placed | `RESTED`. A live old order is removed first by a `NONE` delete | | Packed replace that filled some size, with a leftover that no longer crosses | `RESTED`. The `MATCH_END` trade record is also `RESTED`, and a live old order is removed by a `NONE` delete | | Post-fill hook replenish or replacement order | `NONE` | Delete records: | Case | Outcome | | - | - | | `batch` cancel of a live slot | `CANCELLED` | | Packed cancel-only of a live slot | `CANCELLED` | | `protocolCancelBySlots` of a live slot | `PROTOCOL_CANCELLED`, followed by `ProtocolOrdersCancelled` after the packed logs | | Packed ALO on a live slot that still crosses after its old order is removed | `POST_ONLY_NOT_PLACED` | | Packed replace on a live slot with no fill that still crosses (zero-fill cross) | `COMPLETED_NO_REST` | | Old order of a packed replace whose result is on another record: `FILLED`, `DUST_REMAINDER_DISCARDED`, `RESTED`, or trade-side `COMPLETED_NO_REST` | `NONE` | | Self-match cleanup during a `batch` or packed-replace match | `NONE` | | `cancelAllOrders` | `NONE` | | Post-fill hook cancel of the order it replaces | `NONE` | Sentinel records: | Case | Outcome | `slotIdx` | | - | - | - | | Native `POST_ONLY` that would cross | `POST_ONLY_NOT_PLACED` | `0xff` | | Native IOC that executed nothing: its limit did not reach the best price, the opposite side was empty, its size could not execute there, or it only removed the caller's own orders | `IOC_UNFILLED` | `0xff` | | Native GTC that executed nothing and still crosses (zero-fill cross) | `COMPLETED_NO_REST` | `0xff` | | Packed ALO that would cross, on an empty slot | `POST_ONLY_NOT_PLACED` | target | | Packed cancel-only of an empty slot | `CANCEL_NOOP` | target | | Packed replace on an empty slot that executed nothing and still crosses (zero-fill cross) | `COMPLETED_NO_REST` | target | For packed replace, empty means empty when that operation runs. A slot that was live at submission but was removed earlier in the same call by self-match cleanup counts as empty, and that removal is its own `NONE` delete. Every sentinel has this shape: ```text theme={null} live = false isBuy, bit 6 = 0 outcome = COMPLETED_NO_REST, IOC_UNFILLED, POST_ONLY_NOT_PLACED, or CANCEL_NOOP userId = 0 price = 0 size = 0 orderId = 0 minSizeAfterBlock = 0 makerFeePps = 0 slotIdx = 0xff for a native order, otherwise the replace target (0-61) operationIndex = the operation's index in the call; 0 is valid ``` Identify a sentinel by `live = false` and `userId = 0`. Account ids start at 1, so a real record never has `userId = 0`. The outcome alone is not enough, because `POST_ONLY_NOT_PLACED` and `COMPLETED_NO_REST` also tag real deletes. The log's `accountId`, `executor`, and `clientOrderId` are still set. `FILLED`, `IOC_PARTIAL`, and `DUST_REMAINDER_DISCARDED` never appear on `BookUpdatesPacked`. Dust is cleared by `updatedSize = 0` on the trade record. Some calls emit no book record at all. A `batch` or protocol cancel of an empty slot reverts the whole call. An empty protocol slot list, `cancelAllOrders` with nothing live, and an empty packed replace succeed without records. ### Outcomes by operation The same cases, grouped by what was submitted. Each row names the outcome and the records that carry it. "Tagged `MATCH_END`" is the last trade record of the operation's match. "Sentinel" is the zero-delta book record described above. ```mermaid theme={null} flowchart LR order["Native batch order"] --> postOnly{"POST_ONLY?"} postOnly -->|yes| poCross{"Would cross?"} poCross -->|yes| poSkip["POST_ONLY_NOT_PLACED
TradesPacked: none
BookUpdatesPacked: sentinel, userId 0,
slot 0xff, outcome POST_ONLY_NOT_PLACED"] poCross -->|no| poRest["RESTED
TradesPacked: none
BookUpdatesPacked: live record, outcome RESTED,
new orderId, size = order size"] postOnly -->|no| remaining{"Size left
after matching?"} remaining -->|no| dust{"Sub-unit leftover
dropped?"} dust -->|yes| dustOut["DUST_REMAINDER_DISCARDED
TradesPacked: tagged MATCH_END, outcome
DUST_REMAINDER_DISCARDED, replacementSlot 0xff
BookUpdatesPacked: none"] dust -->|no| filled["FILLED
TradesPacked: tagged MATCH_END, outcome FILLED,
replacementSlot 0xff
BookUpdatesPacked: none"] remaining -->|yes| tif{"Time in force"} tif -->|FOK| fok["Whole call reverts
Nothing is emitted"] tif -->|IOC| iocFill{"Filled any?"} iocFill -->|yes| iocPartial["IOC_PARTIAL
TradesPacked: tagged MATCH_END, outcome
IOC_PARTIAL, replacementSlot 0xff
BookUpdatesPacked: none"] iocFill -->|no| iocNone["IOC_UNFILLED
TradesPacked: none
BookUpdatesPacked: sentinel, userId 0,
slot 0xff, outcome IOC_UNFILLED"] tif -->|GTC| gtcCross{"Leftover still crosses?"} gtcCross -->|no| gtcRest["RESTED
TradesPacked: if it filled, tagged MATCH_END,
outcome RESTED, replacementSlot 0xff
BookUpdatesPacked: live record, outcome RESTED,
new orderId, size = leftover"] gtcCross -->|yes| gtcFill{"Filled any?"} gtcFill -->|yes| noRest["COMPLETED_NO_REST
TradesPacked: tagged MATCH_END, outcome
COMPLETED_NO_REST, replacementSlot 0xff
BookUpdatesPacked: none"] gtcFill -->|no| zeroFill["COMPLETED_NO_REST, zero-fill cross
TradesPacked: none
BookUpdatesPacked: sentinel, userId 0,
slot 0xff, outcome COMPLETED_NO_REST"] ``` ```mermaid theme={null} flowchart LR op["Packed replace op"] --> cancelOnly{"Cancel-only?"} cancelOnly -->|"yes, slot live"| cancelled["CANCELLED
TradesPacked: none
BookUpdatesPacked: delete of the old order,
outcome CANCELLED"] cancelOnly -->|"yes, slot empty"| noop["CANCEL_NOOP
TradesPacked: none
BookUpdatesPacked: sentinel, userId 0,
slot = target, outcome CANCEL_NOOP"] cancelOnly -->|no| crosses{"Crosses once its
old order is removed?"} crosses -->|yes| alo{"ALO?"} alo -->|"yes, slot live"| aloDelete["POST_ONLY_NOT_PLACED
TradesPacked: none
BookUpdatesPacked: delete of the old order,
outcome POST_ONLY_NOT_PLACED"] alo -->|"yes, slot empty"| aloSentinel["POST_ONLY_NOT_PLACED
TradesPacked: none
BookUpdatesPacked: sentinel, userId 0,
slot = target, outcome POST_ONLY_NOT_PLACED"] alo -->|no| remaining{"Size left
after matching?"} remaining -->|no| dust{"Sub-unit leftover
dropped?"} dust -->|yes| dustOut["DUST_REMAINDER_DISCARDED
TradesPacked: tagged MATCH_END, outcome
DUST_REMAINDER_DISCARDED, replacementSlot = target
BookUpdatesPacked: NONE delete of the old order
if the slot was live"] dust -->|no| filled["FILLED
TradesPacked: tagged MATCH_END, outcome FILLED,
replacementSlot = target
BookUpdatesPacked: NONE delete of the old order
if the slot was live"] remaining -->|yes| cross{"Leftover still crosses?"} cross -->|no| rested["RESTED
TradesPacked: if it filled, tagged MATCH_END,
outcome RESTED, replacementSlot = target
BookUpdatesPacked: NONE delete of the old order
if the slot was live, then live record,
outcome RESTED, size = leftover"] cross -->|yes| fillAny{"Filled any?"} fillAny -->|yes| noRest["COMPLETED_NO_REST
TradesPacked: tagged MATCH_END, outcome
COMPLETED_NO_REST, replacementSlot = target
BookUpdatesPacked: NONE delete of the old order
if the slot was live"] fillAny -->|"no, slot live"| zeroFillDelete["COMPLETED_NO_REST, zero-fill cross
TradesPacked: none
BookUpdatesPacked: delete of the old order,
outcome COMPLETED_NO_REST"] fillAny -->|"no, slot empty"| zeroFillSentinel["COMPLETED_NO_REST, zero-fill cross
TradesPacked: none
BookUpdatesPacked: sentinel, userId 0,
slot = target, outcome COMPLETED_NO_REST"] crosses -->|no| rest["RESTED
TradesPacked: none
BookUpdatesPacked: NONE delete of the old order
if the slot was live, then live record,
outcome RESTED, new orderId"] ``` Every tagged record carries the operation's `operationIndex`. Self-match cleanup can add `NONE` deletes of the caller's own orders before the result; apply them to L2 and L3 normally. Native GTC order (`replacementSlot = 0xff`): | Result | Outcome | TradesPacked | BookUpdatesPacked | | - | - | - | - | | Did not cross, rested | `RESTED` | None | Tagged live | | Removed only its own orders, then rested | `RESTED` | None | `NONE` delete per own order, then tagged live | | Filled in full | `FILLED` | Tagged `MATCH_END` | None | | Filled, then dropped a leftover below one executable unit | `DUST_REMAINDER_DISCARDED` | Tagged `MATCH_END` | None | | Filled some, and the leftover no longer crosses, so it rests | `RESTED` | Tagged `MATCH_END` | Tagged live | | Filled some, but the leftover still crosses | `COMPLETED_NO_REST` | Tagged `MATCH_END` | None | | Filled nothing, and the limit still crosses (zero-fill cross) | `COMPLETED_NO_REST` | None | Sentinel, slot `0xff` | Native IOC order (`replacementSlot = 0xff`): | Result | Outcome | TradesPacked | BookUpdatesPacked | | - | - | - | - | | Filled in full | `FILLED` | Tagged `MATCH_END` | None | | Filled, then dropped a leftover below one executable unit | `DUST_REMAINDER_DISCARDED` | Tagged `MATCH_END` | None | | Filled some and discarded the rest | `IOC_PARTIAL` | Tagged `MATCH_END` | None | | Filled nothing: the limit did not reach the best price, the opposite side was empty, or its size could not execute there | `IOC_UNFILLED` | None | Sentinel, slot `0xff` | | Removed only its own orders | `IOC_UNFILLED` | None | `NONE` delete per own order, then sentinel, slot `0xff` | Native FOK order (`replacementSlot = 0xff`): | Result | Outcome | TradesPacked | BookUpdatesPacked | | - | - | - | - | | Filled in full | `FILLED` | Tagged `MATCH_END` | None | | Filled, then dropped a leftover below one executable unit | `DUST_REMAINDER_DISCARDED` | Tagged `MATCH_END` | None | | Executable size left | Whole call reverts | None | None | Native `POST_ONLY` order (GTC only): | Result | Outcome | TradesPacked | BookUpdatesPacked | | - | - | - | - | | Did not cross, rested | `RESTED` | None | Tagged live | | Would cross | `POST_ONLY_NOT_PLACED` | None | Sentinel, slot `0xff` | Packed replace (`replacementSlot` and sentinel slot are the target slot): | Result | Outcome | TradesPacked | BookUpdatesPacked | | - | - | - | - | | Did not cross, or stopped crossing once its old order was removed; rested | `RESTED` | None | `NONE` delete of a live old order, then tagged live | | Filled in full | `FILLED` | Tagged `MATCH_END` | `NONE` delete of a live old order | | Filled, then dropped a leftover below one executable unit | `DUST_REMAINDER_DISCARDED` | Tagged `MATCH_END` | `NONE` delete of a live old order | | Filled some, and the leftover no longer crosses, so it rests | `RESTED` | Tagged `MATCH_END` | `NONE` delete of a live old order, then tagged live | | Filled some, but the leftover still crosses | `COMPLETED_NO_REST` | Tagged `MATCH_END` | `NONE` delete of a live old order | | Filled nothing, the limit still crosses, and the slot was live (zero-fill cross) | `COMPLETED_NO_REST` | None | Tagged delete of the old order | | Filled nothing, the limit still crosses, and the slot was empty (zero-fill cross) | `COMPLETED_NO_REST` | None | Sentinel | Packed ALO replace: | Result | Outcome | TradesPacked | BookUpdatesPacked | | - | - | - | - | | Did not cross, or stopped crossing once its old order was removed; rested | `RESTED` | None | `NONE` delete of a live old order, then tagged live | | Still crosses, and the slot was live | `POST_ONLY_NOT_PLACED` | None | Tagged delete of the old order | | Still crosses, and the slot was empty | `POST_ONLY_NOT_PLACED` | None | Sentinel | Packed cancel-only (size 0): | Result | Outcome | TradesPacked | BookUpdatesPacked | | - | - | - | - | | Slot was live | `CANCELLED` | None | Tagged delete | | Slot was empty, including one cleared earlier in the same call | `CANCEL_NOOP` | None | Sentinel | Cancels outside packed replace: | Operation | Outcome | TradesPacked | BookUpdatesPacked | | - | - | - | - | | `batch` cancel of a live slot, indexed before the batch's orders | `CANCELLED` | None | Tagged delete | | `protocolCancelBySlots` of a live slot | `PROTOCOL_CANCELLED` | None | Tagged delete, then `ProtocolOrdersCancelled` | | `cancelAllOrders` | None | None | `NONE` delete per live order | | `batch` or protocol cancel of an empty slot | Whole call reverts | None | None | No operation outcome: | Operation | TradesPacked | BookUpdatesPacked | | - | - | - | | `swap` | `NONE` on every record, including `MATCH_END` | None | | Post-fill hook replenish or replacement | None | `NONE` live | | Post-fill hook cancel of the order it replaces | None | `NONE` delete | When a match has several fills, only its last record is tagged. When that last fill is against a passive band, the tagged record is the passive record. ## Active L2 Book Maintain active FIFO depth as: ```text theme={null} activeBidDepth[price] = uint256 activeAskDepth[price] = uint256 ``` For every non-passive `TradesPacked` record, apply one of these two rules: ```text theme={null} updatedSize > 0: activeDepth[side][price] -= fillSize updatedSize = 0: remove that order's remaining visible size at price ``` `updatedSize > 0` is a partial fill. The remainder stays, so only `fillSize` leaves the level. `updatedSize = 0` removes the order. `fillSize` can be smaller than the size still on the level. The difference is dust, below one quote atom, and it is not a separate `BookUpdatesPacked` delete. Drop the order's whole remaining visible size, not only `fillSize`. A fresh order and a stale order use this same dust rule. A stale order is already capped before the fill. At the first block where `block.number > minSizeAfterBlock`, set ```text theme={null} visibleSize = min(orderSize, minimumExecutableSizeAtPrice(price, minQuoteNotional)) ``` The size above that cap is not a trade and not a book delete. The later fill's `fillSize` and `updatedSize` are relative to `visibleSize`. `updatedSize = 0` removes what is left of that cap, including dust inside the cap. Do not subtract the original order size again. For every passive `TradesPacked` record, do not touch the active FIFO maps and do not change passive band inventory or passive L2 depth. The record is the tape: price, side, and `fillSize`. `PassiveBandUpdated` is emitted during the match, as soon as the band changes, and is already the inventory after the fill. The trade log is buffered and emitted later. Persisted band inventory comes only from that snapshot. Applying the snapshot and then subtracting `fillSize`, or writing `updatedSize` on top of it, removes the fill a second time. For every non-sentinel `BookUpdatesPacked` record: ```text theme={null} if live: activeDepth[side][price] += size else: activeDepth[side][price] -= size ``` `BookUpdatesPacked` does not mirror trade-induced partial or full fills. It describes newly resting liquidity, non-trade removals, and tagged zero-delta operation sentinels. Do not treat `TradesPacked` as optional for active L2. Trade records are the only source of execution-induced active depth reduction. Examples: ```text theme={null} New resting order: Book live ask 50_000 size 1 L2: ask[50_000] += 1 User cancel: Book delete bid 49_000 size 2 L2: bid[49_000] -= 2 Full fill: Trade ask 50_000 fill 1 updatedSize 0 L2: ask[50_000] -= 1 Partial fill: Trade ask 50_000 fill 0.4 updatedSize 0.6 L2: ask[50_000] -= 0.4 Dust remainder, fresh or stale: Trade fill 0.4 updatedSize 0 L2 removes the order's remaining visible size, not only 0.4 No BookUpdatesPacked for the dust Replace old bid with new ask: Book delete bid 49_000 size 2 oldOrderId Book live ask 51_000 size 1 newOrderId L2: bid[49_000] -= 2 L2: ask[51_000] += 1 ``` `getL2Book(levels)` returns combined active plus passive visible depth. Use it as a periodic checksum for top-of-book state, not as the primary event stream. ## Active L3 Book And Orders Maintain active order state keyed by: ```text theme={null} orderBook, userId, slotIdx ``` Maintain historical order identity keyed by: ```text theme={null} orderBook, userId, slotIdx, orderId ``` Slots are reused, so `orderId` is required for order history. For `BookUpdatesPacked`: ```text theme={null} if outcome != NONE and userId == 0 and price == 0 and size == 0: record operation result and skip L3 mutation if live: upsert activeOrders[(userId, slotIdx)] = { orderId, side, price, size, minSizeAfterBlock, makerFeePps } else: clear activeOrders[(userId, slotIdx)] ``` For `TradesPacked`: ```text theme={null} orderHistory[(userId, slotIdx, orderId)].filled += fillSize orderHistory[(userId, slotIdx, orderId)].lastTradePrice = price orderHistory[(userId, slotIdx, orderId)].remainingAfterTrade = updatedSize if updatedSize == 0: clear activeOrders[(userId, slotIdx)] else: activeOrders[(userId, slotIdx)].size = updatedSize ``` Interpret common lifecycle patterns as: ```text theme={null} Book live with new orderId: order opened, replaced, hook-created, or residual incoming order rested Trade updatedSize > 0: partial fill Trade updatedSize = 0: full fill or fill plus residual cancellation; clear the active slot/order, including leftover dust. There is no extra book delete for that dust. Book delete without same-action trade: explicit cancel, replace removal, self-match cleanup, protocol cancel, cancelAllOrders, or ALO discard of an old live order Book delete followed by Book live same userId/slotIdx with different orderId: replacement of that slot, by a packed replace or by a hook replacing the sibling slot. The filled slot of a hook has no delete Trade updatedSize = 0 followed by Book live same userId/slotIdx with a new orderId: hook replenishment of the filled slot. The fill frees the slot; the live is the new order ``` ## Soft skips A successful `batch` or `replaceBySlotPacked` can return without installing the requested order. The skip is a book record, not a missing log. Crossing `POST_ONLY`: * no trade and no order id * one zero-delta `BookUpdatesPacked` sentinel, outcome `POST_ONLY_NOT_PLACED`, slot `0xff` * `clientOrderId` is on that log Crossing ALO replace: * the new order is not inserted and does not match * a live slot emits one non-live delete of the old order, outcome `POST_ONLY_NOT_PLACED`, plus `SpotReserveUpdated` for the released reserve * an empty slot emits one zero-delta sentinel, outcome `POST_ONLY_NOT_PLACED`, with that slot index A real replace on that slot is a delete followed by a live record with a new `orderId`. A lone `POST_ONLY_NOT_PLACED` delete is the ALO discard. A lone zero-fill cross delete is a GTC replace that filled nothing and still crosses. A lone `CANCELLED` delete is a user cancel. A lone `PROTOCOL_CANCELLED` delete is a protocol cancel. `cancelAllOrders` deletes are untagged. Zero-fill cross (`COMPLETED_NO_REST` with no trade): * the order is GTC, matching leaves size unfilled, and the limit still crosses the opposite best price * nothing is rested * a native order emits one sentinel, slot `0xff` * a packed replace of a live slot emits one tagged delete of the old order * a packed replace of an empty slot emits one sentinel on that target slot * this is not `CANCEL_NOOP`, which is a packed cancel of an already empty slot Batch cancels run before the new orders. A cancel followed by a crossing `POST_ONLY` emits the cancel delete and then the `POST_ONLY_NOT_PLACED` sentinel. The new order is absent. Other orders in the same action still emit their own trades and live records. A missing live record is per order, not per transaction. Install an order only from a live `BookUpdatesPacked` record. `BookUpdatesPacked.accountId` is the action account, not necessarily the maker whose slot changed. Use `userId` in each record for maker identity. Its indexed `executor` is the immediate authenticated caller. Provenance fields use these meanings consistently: * `executor`: immediate authenticated action caller * `authorizer`: principal whose direct authority or EIP-712 signature was validated * `actor`: economic or protocol principal responsible for a mixed-path update * `operator`: caller that passed a governance, ops, or emergency role check These additions do not reorder existing logs. Nested orderbook/ownership events remain where they were; router provenance events follow the successful forwarded call. Passive band updates still occur during matching, while action-level packed events flush at the end. Process transaction logs strictly by `logIndex`. `clientOrderId` is a user-supplied batch-level correlation id. It is emitted with packed event batches but is not stored on-chain in the orderbook. Each `TradesPacked` record's `tradeId` is protocol-generated and canonical for trade lookup. ## `minSizeAfterBlock` `minSizeAfterBlock` is present on live book updates. It is zero when inactive. When nonzero, a fresh order must have `minSizeAfterBlock >= block.number` at placement time. A stale order is one where: ```text theme={null} minSizeAfterBlock != 0 && block.number > minSizeAfterBlock ``` The order is not removed automatically at the beginning of the block. It changes only when touched by matching or explicit cancellation. Indexers that maintain executable L2 should apply the stale visibility cap at block start: ```text theme={null} visibleSize = min(orderSize, minimumExecutableSizeAtPrice(price, minQuoteNotional)) ``` The on-chain `getL2Book` view applies this cap to each stale FIFO order before aggregating depth at the price level. The stored order and its full reserve remain unchanged until matching or cancellation touches it. When a stale order is later touched by matching, events are emitted relative to that visible size: * the executed portion is in `TradesPacked.fillSize` * a remaining live visible residual is in `TradesPacked.updatedSize` * a cancelled visible dust residual is cleared by `updatedSize = 0`, the same as a non-stale dust remainder. There is no extra `BookUpdatesPacked` delete. Hidden stale excess above the visible size is released internally but is not emitted as an active L2 delete, because it was already removed from executable L2 at block start. ## Passive Liquidity Passive liquidity is not represented as maker slots. It does not emit `BookUpdatesPacked`. Passive fills are represented by passive-flagged `TradesPacked` records. Maintain passive band state keyed by: ```text theme={null} orderBook, lowPrice ``` From `PassiveBandUpdated(lowPrice, baseAtHigh, quoteAtLow, totalShares)`: ```text theme={null} passiveBands[lowPrice] = { baseAtHigh, quoteAtLow, totalShares } ``` `baseAtHigh` is the stored normalized size, the same unit as an active order's `fillSize`. Raw base atoms are `baseAtHigh * baseSizeMultiplier`. `quoteAtLow` and `totalShares` are unchanged: quote inventory is raw atoms, and shares are the band's share supply. `getPassiveBand().baseAtHigh` is still raw atoms, so do not treat the view and the event as the same unit. A zero `baseAtHigh`, zero `quoteAtLow`, and zero `totalShares` update means the band is empty. Replace the stored band from this event. Do not also apply the later passive `TradesPacked` record as an inventory delta. Passive depth contributes to L2 at two prices: ```text theme={null} bid price = lowPrice ask price = lowPrice + passiveSpreadTicks * tickSize refPrice = floor((lowPrice + ask price) / 2) ``` Recompute both displayed sizes from the latest `PassiveBandUpdated` snapshot. A nonzero `quoteAtLow` or `baseAtHigh` can still display as zero. Quote and base conversions use the same floors as the contract: ```text theme={null} quoteAmount(price, size) = floor(floor(price * size / sizePrecision) * 10^quoteTokenDecimals / pricePrecision) baseFromQuote(price, quoteAmount) = floor(floor(quoteAmount * pricePrecision / 10^quoteTokenDecimals) * sizePrecision / price) ``` Bid size: ```text theme={null} if quoteAtLow == 0 or lowPrice == 0: bidSize = 0 else: raw = baseFromQuote(lowPrice, quoteAtLow) raw = min(raw, uint128.max / baseSizeMultiplier) bidSize = min(raw, uint96.max) edgeQuote = quoteAmount(lowPrice, bidSize) principalBase = baseFromQuote(refPrice, edgeQuote) if edgeQuote == 0 or principalBase == 0: bidSize = 0 ``` Ask size: ```text theme={null} if baseAtHigh == 0: askSize = 0 else: askSize = min(baseAtHigh, uint96.max) if quoteAmount(refPrice, askSize) == 0: askSize = 0 ``` The ask gate is the midpoint, `refPrice`, not the ask price. A size that converts to a nonzero quote at the ask and to zero at the midpoint is hidden. After the low-price conversion, bid size is capped so raw base cannot exceed `uint128.max / baseSizeMultiplier`, then capped at `uint96.max`, and is shown only when settlement can pay both the edge quote at `lowPrice` and the principal base at `refPrice`. Combined L2 is: ```text theme={null} bidDepth[price] = activeBidDepth[price] + passiveBidDepth[price] askDepth[price] = activeAskDepth[price] + passiveAskDepth[price] ``` Passive LP position/accounting events: * `PassiveLiquidityMinted(userId, positionId, executor, lowPrice, baseAmount, quoteAmount, shares)` * `PassiveLiquidityBurned(userId, positionId, executor, sharesBurned, basePrincipalOut, quotePrincipalOut, baseFeeOut, quoteFeeOut)` * `PassiveFeesClaimed(userId, positionId, executor, baseFeeOut, quoteFeeOut)` Use those for LP position history. Use `PassiveBandUpdated` for passive depth. ## Passive Trade Records A passive trade is a `TradesPacked` record with `makerFlags & 2 != 0`. Fields: * `userId = 0` * `slotIdx = 0` for passive bid, `1` for passive ask * `orderId = lowPrice` * `price = execution price` * `fillSize = base filled` * `updatedSize = remaining visible size on the filled side after the fill` Passive execution quote is side-dependent. Passive bids floor both stages; passive asks ceil both stages: ```text theme={null} passive bid: priceSizeUnits = floor(price * fillSize / sizePrecision) quoteAmount = floor(priceSizeUnits * 10^quoteTokenDecimals / pricePrecision) passive ask: priceSizeUnits = ceil(price * fillSize / sizePrecision) quoteAmount = ceil(priceSizeUnits * 10^quoteTokenDecimals / pricePrecision) ``` For taker buys, gross quote debit is: ```text theme={null} quoteAmount + takerFeeQuote ``` For taker sells, net quote credit is: ```text theme={null} quoteAmount - takerFeeQuote - builderFeeQuote ``` Do not write `updatedSize` or `fillSize` into band inventory or L2 depth. Those come from `PassiveBandUpdated`. `updatedSize` matches the filled side's post-fill displayed size and is tape context only. A passive fill also changes the other leg, which this record does not carry. Passive LP fee growth tracks only passive spread economics. Protocol taker fees and builder fees are visible through AccountCore settlement/builder fee events, not through passive band fee growth. ## Swaps And Mixed Liquidity `SpotSwap(userId, executor, isBuy, amountInUsed, amountOut, minAmountOut)` is a summary of the taker's exact-input swap settlement. Its amounts are attributable to that swap's fills, rather than the account's whole balance change during the call. For a swap that touches active FIFO liquidity, active fills are emitted later in the same transaction through `TradesPacked` and `BookUpdatesPacked`. For a swap that touches passive liquidity, passive fills are emitted later in the same transaction as passive-flagged `TradesPacked` records, while passive inventory snapshots still emit `PassiveBandUpdated`. Mixed active/passive swaps can produce all of these in one transaction. Active and passive trade records share one packed trade stream, so their relative execution order is the record order inside `TradesPacked`. `PassiveBandUpdated` logs are emitted immediately when passive inventory changes. Therefore: * active and passive trade records are ordered relative to each other within `TradesPacked` * `SpotSwap` gives the final taker-level amount summary * persisted passive inventory comes only from `PassiveBandUpdated` * the passive `TradesPacked` record is the tape for that fill: price, size, and side. It does not change inventory again `SpotSwap` deliberately does not repeat fee rates. Its corresponding `TradesPacked` event is the canonical action fee context. ## AccountCore Indexing AccountCore is the custody, account, permission, builder, and fee-tier ledger behind the Spot orderbooks. Index it as a separate subsystem and join it to orderbook events by `accountId`, `userId`, `rootId`, `token`, and `orderBook`. ### Account Identity Maintain: ```text theme={null} rootAccountIdOf[rootOwner] = rootId accountsById[accountId] = { rootOwner, rootId, subaccountSeq } subaccountsByRoot[rootId] = uint40[] ``` `AccountRegistered(accountId, rootAccountId, rootOwner, subaccountSeq)` is the canonical identity event. All three fields before the sequence are indexed. Apply it as: ```text theme={null} accountsById[accountId] = { rootOwner, rootId: rootAccountId, subaccountSeq } if subaccountSeq == 0: rootAccountIdOf[rootOwner] = accountId else: subaccountsByRoot[rootAccountId].push(accountId) ``` Roots have `rootAccountId == accountId` and sequence zero. Children have positive sequences, the same owner as their root, and no separate address. `SubaccountCreated(rootAccountId, subaccountId, authorizer)` records who authorized creation (the verified signer for relayed creation). All three fields are indexed. Use it for provenance, without appending the child twice. Creation does not change the root signer epoch. Orderbook `userId` and AccountCore `accountId` share the same global ID space. ### Signers And Permissions Maintain one registry and epoch per root ID: ```text theme={null} signers[rootId][signer] = { permissions, expiry } authorizationEpoch[rootId] = uint256 ``` `AccountSignerAuthorized(accountId, signer, authorizer, permissions, expiry)` replaces the root grant. `AccountSignerRevoked(accountId, signer, authorizer)` removes it. Both advance that root's epoch by one. The account ID in either event is always the root ID. `authorizer` records who granted or revoked the signer; it is provenance, not part of the registry key. Permission bits are `1 << 0` TRADE, `1 << 2` INTERNAL_TRANSFER, `1 << 3` WITHDRAW and `1 << 4` ADMIN. Root owners control the family. ADMIN includes TRADE, WITHDRAW and INTERNAL_TRANSFER; WITHDRAW includes INTERNAL_TRANSFER. TRADE authority (whether granted directly or inherited from ADMIN) applies to every existing and future child. ADMIN also manages root grants and permits child creation. Root withdrawals and family transfers check authority against the root. No grant can enable child external withdrawals or deposits. Authorization events contain the exact granted mask, not its expanded permissions. Preserve those bits in the indexed registry and apply the hierarchy above when computing effective authority. Expiry/revocation applies to the whole grant, including every inherited permission. Expiry is evaluated at use time: zero means no expiry; otherwise the grant is live through its expiry timestamp. Do not delete expired grants from indexed history. `accountAuthorizationEpoch(accountId)` resolves the root epoch for both roots and children; use it with the target ID when building signed trading intents. ### Spot Token And Market Config Maintain: ```text theme={null} spotTokens[token] = { decimals, enabled } spotRouter = address spotMarkets[orderBook] = { baseToken, quoteToken, verified, sizePrecision, pricePrecision, minQuoteNotional, tickSize, passiveSpreadTicks, quoteTokenDecimals, takerFeePps, makerFeePps } ``` Events. These update config state. `operator` is history only. * `SpotTokenConfigured(token, decimals, enabled, operator)` * `SpotRouterUpdated(oldRouter, newRouter, operator)` * `SpotRouter.SpotMarketRegistered(orderBook, baseToken, quoteToken, operator, sizePrecision, pricePrecision, minQuoteNotional, tickSize, passiveSpreadTicks, quoteTokenDecimals, takerFeePps, makerFeePps)` * `AccountCore.SpotMarketRegistered(orderBook, baseToken, quoteToken, registrar)` * `SpotRouter.SpotMarketUpgraded(orderBook, newImplementation, operator)` — state is the market implementation * `AccountCore.FeeCollectorUpdated(oldFeeCollector, newFeeCollector, operator)` — state is the fee collector * `AccountCore.ProtocolStateUpdated(previousPaused, paused, operator)` — state is whether AccountCore is paused * `AccountCore.PostFillHookAccessUpdated(accountId, allowed, operator)` — state is whether that account may set a post-fill hook `SpotTokenConfigured` is a snapshot of cached token metadata. Decimals are read by governance configuration and are immutable for already-seen tokens. Native asset is `address(0)` and uses 18 decimals. The two `SpotMarketRegistered` events are different ABIs. The router event is the create-market config source of truth (`minQuoteNotional` is raw quote atoms; `takerFeePps` / `makerFeePps` are market defaults and may be overridden by account or builder tiers). The AccountCore event only confirms settlement authority: ```text theme={null} spotMarkets[orderBook].verified = true spotMarkets[orderBook].baseToken / quoteToken = pair ``` ### Free And Reserved Balances Maintain two balances per `(accountId, token)`: ```text theme={null} freeBalance[accountId][token] reservedBalance[accountId][token] ``` Free balance is withdrawable/spendable balance. Reserved balance is active maker-order escrow. Passive LP inventory is neither free nor active-order reserved; track it from passive position/band events. AccountCore emits a mix of activity events and snapshots: * `Deposit(accountId, token, payer, amount)` records who funded the account. * `Withdrawal(accountId, token, recipient, amount)` records who received the asset. * `InternalAccountTransfer(fromAccountId, toAccountId, token, executor, amount)` records who moved free balance; use the accompanying snapshots for balances. * `SpotReserveUpdated(userId, token, freeBalance, reservedBalance)` is an authoritative snapshot for that AccountCore id/token pair. Use `SpotReserveUpdated` to maintain balances: ```text theme={null} Deposit: history only; the preceding SpotReserveUpdated snapshot is the balance Withdrawal: history only; the preceding SpotReserveUpdated snapshot is the balance InternalAccountTransfer: history only; the two preceding SpotReserveUpdated snapshots are the balances, one for fromAccountId and one for toAccountId SpotReserveUpdated: accountId = event.userId freeBalance[accountId][token] = freeBalance from event reservedBalance[accountId][token] = reservedBalance from event ``` `Deposit`, `Withdrawal`, and `InternalAccountTransfer` are activity/provenance events. The same operation emits `SpotReserveUpdated` first; an internal transfer emits one snapshot per distinct account before `InternalAccountTransfer`. Self-transfers revert. Do not apply the activity amount on top of that snapshot. `SpotReserveUpdated` is emitted for reserve, release, batched reserve deltas, active maker settlement, active/passive taker settlement, passive lock/release, deposits, withdrawals, and internal account transfers. Since it is a snapshot, it replaces the stored free and reserved balances for that account and token. ### Trade Settlement Balance Derivation Not every settlement leg emits an AccountCore balance event. For exact portfolio indexing, use `SpotReserveUpdated` as the balance and use the orderbook events as history. `SpotSwap` reports the swap's settlement contribution: ```text theme={null} if isBuy: freeBalance[account][quoteToken] -= amountInUsed freeBalance[account][baseToken] += amountOut else: freeBalance[account][baseToken] -= amountInUsed freeBalance[account][quoteToken] += amountOut ``` These are attribution equations, not additional balance updates. `finalizeSpotMatch` emits the taker's authoritative `SpotReserveUpdated` snapshots before `SpotSwap`. These equations describe the swap leg, not necessarily the account's final delta for the transaction. Authorized post-fill hooks can transfer funds or trade on another market before the outer swap completes. Apply those independent actions separately, and prefer the authoritative `SpotReserveUpdated` snapshots for final free and reserved balances. For active maker fills, AccountCore emits `SpotReserveUpdated` snapshots for both the token whose reserve was consumed and the token the maker received. Apply those snapshots. The shape of each snapshot is: ```text theme={null} maker ask filled: base event: reserved base decreases quote event: free quote increases by quoteAmount - makerFeeQuote maker bid filled: quote event: reserved quote decreases and any reserve dust returns to free quote base event: free base increases by baseAmount ``` Do not also apply those amounts as a second balance delta. To audit the numbers, use the `makerFeePps` stored in the active trade record. It is the effective maker fee snapshotted when the resting order was created. Passive LP inventory changes are represented by `PassiveBandUpdated`, not by passive-flagged `TradesPacked` records and not by per-LP AccountCore balance events. The trade record is the fill tape. The taker's free-balance change is the `SpotReserveUpdated` pair from `finalizeSpotMatch`, not a second application of `SpotSwap`. For passive fills, the taker's passive input and output are included in `SpotSwap` exactly once. Protocol fees credited to `feeCollector` do not have a dedicated fee-accrual event. The fee collector's `SpotReserveUpdated` snapshot is the balance. A `MATCH_END` sum can audit that snapshot; it must not be added on top of it. ### Passive Custody And LP Positions Passive liquidity locks free balances into band inventory: * `PassiveLiquidityMinted(...)` describes the provider id, position id, low price, deposited base/quote, and shares. * `PassiveLiquidityBurned(...)` describes principal and fee amounts released. * `PassiveFeesClaimed(...)` describes fee-only releases. * `SpotReserveUpdated(...)` gives the provider's free-balance snapshot for each base/quote token whose free balance changed during AccountCore lock or release. Maintain LP position state from passive orderbook events, and maintain free balances from `SpotReserveUpdated`. Do not treat passive inventory as `reservedBalance`; `reservedBalance` is only active maker-order escrow. ### Builders Maintain: ```text theme={null} builderApprovals[rootId][builder] = { rootAccount, maxFeePps, expiry, active } builderReferralTiers[builder] = { makerFeePps, takerFeePps, expiry, active } builderReferrals[rootId] = { rootAccount, builder, makerFeePps, takerFeePps, expiry, active } ``` Builder free balance comes from `SpotReserveUpdated`, not from adding `BuilderFeeAccrued.amount`. Events: * `BuilderApprovalUpdated(rootAccountId, builder, maxFeePps, expiry, active)` * `BuilderReferralTierUpdated(builder, makerFeePps, takerFeePps, expiry, active, operator)` * `BuilderReferralUpdated(rootAccountId, builder, actor, makerFeePps, takerFeePps, expiry, active)` * `BuilderFeeAccrued(builder, asset, takerAccountId, orderBook, builderFeePps, amount)` * `SpotReserveUpdated(builderAccountId, asset, freeBalance, reservedBalance)` on positive accrual * `Withdrawal(builderAccountId, asset, recipient, amount)` when the builder withdraws `BuilderFeeAccrued` is also the builder-attribution event. One event is emitted per finalized match when a builder context is present. `amount == 0` remains valid for an approved zero-fee builder flow and does not credit the builder's free balance. `orderBook` identifies the settlement source and `builderFeePps` is the exact match rate represented by the amount. On approval: ```text theme={null} builderApprovals[rootUserId][builder] = { rootAccount, maxFeePps, expiry, active } ``` On referral tier update: ```text theme={null} builderReferralTiers[builder] = { makerFeePps, takerFeePps, expiry, active } ``` Builder referral tiers are enrollable only while `active` and unexpired. A finite user referral must expire at or before the tier expiry, and `referralExpiry == 0` is only valid when the tier expiry is also `0`. On fee accrual (`amount > 0`): ```text theme={null} register builder root if needed builderId = rootAccountIdOf(builder) balances[builderId][asset] += amount emit SpotReserveUpdated, BuilderFeeAccrued ``` The snapshot is the canonical balance; `BuilderFeeAccrued` is history only and must not be applied a second time. `amount == 0` emits `BuilderFeeAccrued` and no `SpotReserveUpdated`, because the builder's free balance does not change. On withdraw: ```text theme={null} balances[builderId][asset] -= amount emit SpotReserveUpdated, Withdrawal ``` The snapshot is the canonical balance; `Withdrawal` is history only and must not be applied a second time. Builder approvals are root-level. Subaccounts inherit the root approval through their `rootId`. Expiry is checked at execution time, so retain expired approvals and mark them unusable in views when `block.timestamp > expiry`. Builder referral tiers and enrollments are a separate fee-discount system, not the builder-fee approval system. A tier says what protocol maker/taker fee (in pps) a builder is allowed to sponsor. A referral enrollment snapshots that tier onto a root account after a builder-signed EIP-712 authorization. Subaccounts inherit the root referral through `rootId`. Treat a referral as live only when `active == true`, `builder != address(0)`, and `expiry == 0 || block.timestamp <= expiry`. Revocation and governance clears emit `BuilderReferralUpdated(..., active=false)` with the stored builder/fee/expiry values that were cleared. Builder fee assets depend on trade direction: ```text theme={null} taker buy: builder fee is paid in base taker sell: builder fee is paid in quote ``` For `amount == 0`, the same asset rule applies for attribution even though the builder's free balance does not change. ### Fee Tiers Maintain: ```text theme={null} defaultSpotFees = { makerFeePps, takerFeePps, active } accountFeeTier[rootId] = { makerFeePps, takerFeePps, active } builderReferralTier[builder] = { makerFeePps, takerFeePps, expiry, active } builderReferral[rootId] = { builder, makerFeePps, takerFeePps, expiry, active } ``` Events: * `DefaultSpotFeesUpdated(makerFeePps, takerFeePps, active, operator)` * `AccountFeeTierUpdated(rootAccountId, makerFeePps, takerFeePps, active, operator)` * `BuilderReferralTierUpdated(builder, makerFeePps, takerFeePps, expiry, active, operator)` * `BuilderReferralUpdated(rootAccountId, builder, actor, makerFeePps, takerFeePps, expiry, active)` Effective spot fee for an account is: ```text theme={null} currentEffective = marketFee if account root tier active: currentEffective = min(currentEffective, account root tier maker/taker fee) else if default spot fees active: currentEffective = min(currentEffective, default maker/taker fee) if root builder referral live: currentEffective = min(currentEffective, referral maker/taker fee) effectiveFee = currentEffective ``` For makers, snapshot the effective maker fee when an order is placed. For takers, use the effective taker fee at execution time. Referral expiry and revocation therefore affect new taker actions immediately, while already resting maker orders keep the maker fee snapshot stored in their order flags. ## Maker And Operational Metadata Index these for maker management and operational dashboards. State events change stored configuration. History-only events explain who did it, or repeat a change that another event already applies. State: * `MakerRegistered(userId)` * `PostFillHookUpdated(userId, hook, executor)` — state is the hook address. `executor` is history only. * `PostFillHookGasLimitUpdated(oldGasLimit, newGasLimit, operator)` — state is the gas stipend. `operator` is history only. * `PostFillHookMinQuoteNotionalUpdated(oldMinQuoteNotional, newMinQuoteNotional, operator)` — state is the hook minimum notional. `operator` is history only. * `PostFillHookAccessUpdated(accountId, allowed, operator)` — state is the account's hook permission. `operator` is history only. * `FeeCollectorUpdated(oldFeeCollector, newFeeCollector, operator)` — state is the fee collector. `operator` is history only. * `ProtocolStateUpdated(previousPaused, paused, operator)` — state is the protocol pause. `operator` is history only. * `SpotMarketUpgraded(orderBook, newImplementation, operator)` — state is the market implementation. `operator` is history only. * `OwnershipTransferred(previousOwner, newOwner)` * `AuthorityUpdated(oldAuthority, newAuthority)` — emitted by `AccountCore` and `SpotRouter` when their stored pointer moves. Live books do not emit this; they read the current owner's `authority()`. * `GovernanceUpdated(oldGovernance, newGovernance)` * `OpsUpdated(oldOps, newOps)` * `EmergencyUpdated(oldEmergency, newEmergency)` History only: * `MakerPagePrimed(userId, primedCount)` * `QueuePagesPrimed(caller, centerPrice, groupsAround, wordsPerGroup, pagesPrimed, wordsPrimed)` * `ProtocolOrdersCancelled(userId, operator, clientOrderId, slotIdxs)` is the privileged-action audit summary. It is emitted after that call's packed logs. Removed order ids and sizes remain canonical in the corresponding `PROTOCOL_CANCELLED` book records. Do not apply this event as a second cancel. ## Processing Checklist For each market, `_emitPackedEvents` logs one packed event per contiguous run. Each cycle emits the run that was appended first, then the other run. A nonempty `protocolCancelBySlots` emits `ProtocolOrdersCancelled` after that call's packed logs. Forward each packed log as it appears. 1. Walk packed logs in receipt order. Apply each log before the next one. 2. Decode the records in that log, in record order. 3. Extract tagged operation outcomes and merge trade/live carriers by operation index. 4. Record zero-delta sentinels, but do not apply them to L2 or L3. 5. Transaction success, `IntentExecuted`, and `TriggerFired` do not imply a resting order. Apply an order only from a live `BookUpdatesPacked` record. A `POST_ONLY_NOT_PLACED` sentinel or delete means that order was not installed. 6. Apply active L2 additions/removals from non-sentinel `BookUpdatesPacked` records. 7. Apply active L3/order-state upserts and deletes from non-sentinel book records. 8. Apply active L2 trade deltas from non-passive `TradesPacked` records. 9. Store active and passive trade tape records from `TradesPacked`. 10. Replace passive band state from `PassiveBandUpdated` and recompute affected passive bid/ask depth from that snapshot. Do not also apply passive `TradesPacked` records to inventory. 11. Store passive trade records from passive-flagged `TradesPacked` records as tape only. 12. Store `SpotSwap` summaries. 13. Apply `SpotReserveUpdated` snapshots for balances. Keep `Deposit`, `Withdrawal`, `InternalAccountTransfer`, `BuilderFeeAccrued`, and `SpotSwap` as history. 14. Periodically compare top levels with `getL2Book(levels)`. Full active L3 reconstruction requires replaying from market deployment because there is no complete on-chain iterator for all maker slots. If an indexer starts midstream, it can use `getL2Book()` to seed top-of-book aggregate L2, but it cannot reconstruct historical maker-slot state without older logs. ## Scenario coverage `test/spot/SpotOutcomeScenarioTest.t.sol` has one test for every end state in the native-batch and packed-replace graphs above. The live-slot tests check the `NONE` delete of the old order. The empty-slot tests check that no book record is emitted, except `RESTED`, which checks the live record. Each test compares the book records byte for byte and checks the trade outcome, `MATCH_END`, and `replacementSlot`. ### Native batch order | End state | Test | | - | - | | Post-only would cross: no trade, sentinel on slot `0xff` | `test_PostOnly_WouldCross_EmitsPostOnlyNotPlacedSentinel` | | Post-only does not cross: no trade, live `RESTED` | `test_PostOnly_NoCross_RestsTaggedLive` | | `FILLED`: tagged `MATCH_END`, no book record | `test_Gtc_FullFill_TagsFilledOnMatchEnd`, `test_Ioc_FullFill_TagsFilled`, `test_Fok_FullFill_TagsFilled` | | `DUST_REMAINDER_DISCARDED`: tagged `MATCH_END`, no book record | `test_Gtc_FillThenDust_TagsDustRemainderDiscarded`, `test_Ioc_FillThenDust_TagsDustRemainderDiscarded`, `test_Fok_FillThenDust_TagsDustRemainderDiscarded` | | FOK with leftover: the call reverts | `test_Fok_ExecutableLeftover_RevertsWholeCall` | | `IOC_PARTIAL`: tagged `MATCH_END`, no book record | `test_Ioc_PartialFill_TagsIocPartial` | | `IOC_UNFILLED`: no trade, sentinel on slot `0xff` | `test_Ioc_LimitDoesNotReachBest_EmitsIocUnfilledSentinel`, `test_Ioc_EmptyOppositeSide_EmitsIocUnfilledSentinel`, `test_Ioc_SizeNotExecutableAtBest_EmitsIocUnfilledSentinel` | | GTC rests, with a fill and without one | `test_Gtc_PartialFillThenRest_TagsTradeAndLiveRested`, `test_Gtc_NoCross_RestsTaggedLive` | | GTC filled, leftover still crosses: tagged `MATCH_END`, no book record | `test_Gtc_PartialFillStillCrossing_TagsTradeCompletedNoRest` | | GTC filled nothing and still crosses: no trade, sentinel on slot `0xff` | `test_Gtc_ZeroFillStillCrossing_EmitsZeroFillCrossSentinel` | ### Packed replace | End state | Live slot | Empty slot | | - | - | - | | `CANCELLED` / `CANCEL_NOOP` | `test_Replace_CancelOnlyLiveSlot_TagsCancelledDelete` | `test_Replace_CancelOnlyEmptySlot_EmitsCancelNoopSentinel` | | Does not cross, `RESTED` | `test_Replace_NonCrossingLiveSlot_UntaggedDeleteThenTaggedLive` | `test_Replace_NonCrossingEmptySlot_TaggedLiveOnly` | | ALO still crosses | `test_Replace_AloStillCrossingOnLiveSlot_TagsOldDeletePostOnlyNotPlaced` | `test_Replace_AloCrossOnEmptySlot_EmitsPostOnlyNotPlacedSentinel` | | `FILLED` | `test_Replace_FullFill_TagsFilledWithTargetSlot` | `test_Replace_FullFillOnEmptySlot_TagsFilledWithoutBookRecord` | | `DUST_REMAINDER_DISCARDED` | `test_Replace_FillThenDustOnLiveSlot_TagsDustAndUntaggedOldDelete` | `test_Replace_FillThenDust_TagsDustRemainderDiscarded` | | `RESTED` after a fill | `test_Replace_PartialFillThenRest_TagsTradeAndLiveRested` | `test_Replace_PartialFillThenRestOnEmptySlot_TagsTradeAndLiveRested` | | `RESTED` after matching with no fill | `test_Replace_NoFillAfterMatchingThenRestOnLiveSlot_UntaggedDeletesThenTaggedLive` | `test_Replace_CrossingOnlyItsOwnOldOrder_UntaggedDeleteThenTaggedLive` | | `COMPLETED_NO_REST` with fills | `test_Replace_PartialFillStillCrossing_TagsTradeCompletedNoRest` | `test_Replace_PartialFillStillCrossingOnEmptySlot_TagsTradeWithoutBookRecord` | | Zero-fill cross | `test_Replace_ZeroFillCrossOnLiveSlot_TagsOldDeleteZeroFillCross` | `test_Replace_ZeroFillCrossOnEmptySlot_EmitsZeroFillCrossSentinel` | # Building an Indexer Source: https://docs.kuru.io/indexing/overview Build a reorg-safe reducer for Kuru Spot accounts, markets, orders, trades, and liquidity. Use this section when you operate your own event-derived state store. Applications using Kuru's hosted [market data](/api/market-data) and [account data](/api/account-activity) do not need to implement these reducers just to start an integration. The goal is to reconstruct account balances, orders, executions, and liquidity positions from chain events, with enough provenance to undo and replay state after a reorg. Index AccountCore as the custody ledger, each OrderBook as a market ledger, SpotRouter as the market registry, and each delegated trading-wallet EOA as its own intent store. ## Ordering and identity Process logs in `(blockNumber, transactionIndex, logIndex)` order. Preserve block hash and parent hash so every derived write can be rolled back on a reorg. Canonical keys include: ```text theme={null} account: (chainId, accountId) active slot: (chainId, market, userId, slotIdx) order history: (chainId, market, userId, slotIdx, orderId) fill: (chainId, market, tradeId) passive band: (chainId, market, lowPrice) position: (chainId, market, positionId) trigger: (chainId, wallet, triggerId) ``` Slots are reused. Never identify historical orders without `orderId`. ## Bootstrap 1. Start from the component and market `fromBlock` values on [Testnet Deployments](/deployments/testnet). 2. Discover markets from SpotRouter registration events and confirm them against AccountCore registration. 3. Cache immutable market fields and current application-visible configuration. 4. Replay all logs in order. 5. Periodically compare balances, active slots, band state, and top-of-book views against the chain. ## Source precedence * `TradesPacked` is required for execution-induced active and passive depth changes. * `BookUpdatesPacked` covers newly resting state and non-trade removals. * `MATCH_END` partitions fee and settlement groups inside one packed action. * `SpotReserveUpdated` is an AccountCore post-state snapshot. Apply every snapshot in log order; do not also apply `Deposit`, `Withdrawal`, or transfer as a second balance mutation. * `PassiveBandUpdated` is the passive inventory snapshot. * `SpotSwap` is a taker summary, not a complete trade tape. Unknown record lengths, flags, enum values, or implementation code hashes must fail closed into an unsupported-version path rather than being decoded heuristically. # Indexing SpotRouter Source: https://docs.kuru.io/indexing/spot-router Discover verified markets and track application-visible market configuration events. Start at the router's deployment block and process: | Event | Reducer action | | - | - | | `SpotMarketRegistered(orderBook, baseToken, quoteToken, operator)` | Add the market candidate and pair | | `SpotMarketStateUpdated(orderBook, previousState, newState, operator)` | Replace routed market state and retain operator provenance | | `SpotTokenWhitelisted(token, status, operator)` | Replace deployment-eligibility metadata | | `SpotOBImplementationUpdated(oldImplementation, newImplementation, operator)` | Update future-deployment implementation metadata | | `ManagedContractOwnershipTransferred(managedContract, previousOwner, newOwner, operator)` | Record routed ownership change | A router registration is the canonical deployment signal. Do not enable settlement until the corresponding AccountCore `SpotMarketRegistered` confirms the orderbook, base, and quote relationship. For market-state changes, the nested OrderBook `MarketStateUpdated` is the actual market mutation; the later SpotRouter event supplies the initiating operator. Process both in transaction log order. Cache each market's immutable getters at discovery: base, quote, price and size precision, tick, quote decimals, passive spread, and notional limits. Re-read implementation and market-state pointers after their relevant events. # Indexing KuruTradingWallet Source: https://docs.kuru.io/indexing/trading-wallet Track signed intents and trigger lifecycle per delegated trading-wallet EOA. EIP-7702 executes wallet logic and storage in the delegated EOA's context. The event `address` is therefore the wallet EOA; never aggregate trigger storage under the shared implementation address. | Event | Reducer action | | - | - | | `IntentExecuted(intentHash, wallet, accountId, market, clientOrderId, nonce)` | Record successful immediate action and advance observed nonce | | `TriggerCreated(triggerId, wallet, accountId, market, clientOrderId, nonce, expiry, conditionHash, action)` | Insert `ACTIVE` trigger | | `TriggerCanceled(triggerId, wallet, accountId)` | Set `CANCELED` | | `TriggerFired(triggerId, keeper, executionReportHash)` | Set `FIRED` and retain keeper report hash | | `TriggerExpired(triggerId)` | Set `EXPIRED` | Key triggers by `(chainId, wallet, triggerId)`. A trigger ID is the EIP-712 creation digest. Join the resulting OrderBook action by transaction and `clientOrderId`, but treat the digest and orderbook-generated trade IDs as canonical identities. Expiry and AccountCore permission expiry can make an `ACTIVE` record non-executable without emitting an event. Present stored status separately from derived executability. Authorization changes invalidate old triggers through the AccountCore authorization epoch. Index `lastSeenOrderNonce`, `usedTriggerNonce`, and `getTrigger` from the delegated wallet address when reconciling state. ## TWAP schedules Key schedules by `(chainId, wallet, twapId)`. `TwapCreated` contains the signed header and config. `TwapSliceExecuted` identifies the slice, requested quantity, child client ID, keeper and report hash; reconcile actual fills from the market logs rather than treating requested quantity as settled quantity. `TwapSlicesSkipped` records skipped interval ranges. `TwapCanceled` stops the schedule; `TwapFinished` records successful and skipped counts. Failed transactions do not persist slice progress. No catch-up or quantity rollover occurs. ## Wallet-authored data `SignedDataEmitted(wallet, nonce, data)` publishes opaque public bytes. Use the emitting delegated EOA, chain, and sequential data nonce as provenance. A wallet-authored label is not proof of account permission; join AccountCore signer state separately. ## Version and state Wallet v2 stores nonce, trigger and TWAP state separately per chain. Trigger creation nonce, deadline and condition commitment are available from calldata/events rather than all being retained by `getTrigger`. Do not infer them from nonexistent getter fields. The creation signature is verified once; live authority and epoch checks still apply when a keeper fires. # Getting Started Source: https://docs.kuru.io/introduction/getting-started Mainnet and testnet access, and what you need before your first trade. Kuru is deployed on Monad mainnet and testnet. The public Spot V2 frontend is live for trading, including [One Click Trading](/accounts/one-click-trading). Developers can also integrate through the APIs and SDK. The interactive REST playground defaults to **mainnet**, where signed writes may submit real transactions; switch it to testnet before experimenting. You can explore [Spot Trading](/introduction/spot), [Order Types](/matching-engine/order-types), and [Accounts](/accounts/overview) before setting up an integration. ## Choose a network Use the [mainnet deployment](/deployments/mainnet) and live market catalog for production integrations. Use [testnet setup](/deployments/setup) and [testnet deployments](/deployments/testnet) for rehearsal. Keep contract addresses, chain IDs, assets, JWTs, and signatures on the same network. ## Preparing for testnet You will need a dedicated test wallet, testnet MON for transactions you submit yourself, and Kuru test assets for the market you want to trade. Testnet tokens are not the production versions of those assets. The [testnet setup guide](/deployments/setup) identifies the network, deployment, and funding prerequisites. The current deployment uses admin-mintable test tokens and has no public token faucet. Confirm token access with your Kuru integration contact before starting the tutorial. ## Your first integration Developers can follow [First Trade](/sdk/quickstart) to deposit assets, place a limit order, check the result, and cancel its unfilled remainder. The tutorial uses testnet; switch to mainnet configuration only when you intend to trade production assets. For a bot or application that uses a separate trading signer and sponsored gas, continue with [Delegated Trading with Relay](/sdk/relay-onboarding). ## Before placing an order Understand which asset you are buying or selling, how much of your balance the order needs, and what happens if it fills only partially. [Balances and Open Orders](/accounts/balances-and-reservations) walks through an example. # Spot Trading Source: https://docs.kuru.io/introduction/spot Understand markets, prices, and buying and selling tokens. Spot trading exchanges the assets themselves. Buying WETH on the WETH/USDC market spends USDC and adds WETH to your balance. Selling WETH does the reverse. ## Markets and prices Each market pairs two assets. In WETH/USDC, WETH is the asset being bought or sold, and USDC is the asset used to price and pay for it. A price of 2,500 means one WETH costs 2,500 USDC. Buying 0.1 WETH at that price costs 250 USDC before fees. ## The order book The order book contains buy and sell orders at different prices. Buy orders specify what buyers are willing to pay; sell orders specify what sellers are willing to accept. A trade occurs when an incoming order can match available liquidity at an acceptable price. An order can fill immediately, fill partially, or remain open waiting for another trader. Its behavior depends on its price, the available liquidity, and the order type you select. ## Choosing your price A limit order sets the highest price you will pay when buying or the lowest price you will accept when selling. For example, a limit order to buy WETH at 2,500 USDC can execute at 2,500 or lower. It will not buy at 2,510. Any unfilled amount can remain on the order book, depending on the order's settings. Other settings let you require immediate execution or ensure your order only adds liquidity. See [Order Types](/matching-engine/order-types). ## Funds committed to orders Open orders reserve the funds needed to execute them. Those funds are unavailable for another order or withdrawal while reserved. When an order fills, the corresponding funds are exchanged. Canceling its unfilled portion makes the remaining reserved funds available again. Continue to [Accounts](/accounts/overview) for funding and balances, or [How Orders Match](/matching-engine/overview) for execution rules. # Fees Source: https://docs.kuru.io/matching-engine/fees The published 14-day volume tiers, maker and taker charges, and application fees. Trading fees depend on whether an execution adds or removes liquidity and on the fee policy that applies to the account and market. ## Makers and takers A resting limit order provides liquidity and pays the applicable maker fee when it fills. An incoming order that executes against available liquidity is taker flow. A limit order can do both: part may trade immediately as a taker, while the remaining amount rests and later fills as a maker. A post-only order is intended to provide liquidity only. ## Published fee schedule | Tier | 14-day volume | Taker fee | Maker fee | | -: | -: | -: | -: | | 0 | Base tier | 2 bps | 1 bp | | 1 | >\$2 million | 1.4 bps | 0.75 bps | | 2 | >\$10 million | 0.95 bps | 0.5 bps | | 3 | >\$30 million | 0.6 bps | 0.3 bps | | 4 | >\$100 million | 0.35 bps | 0.15 bps | | 5 | >\$250 million | 0.2 bps | 0 bps | | 6 | >\$500 million | 0.1 bps | 0 bps | One basis point is 0.01%. The threshold signs above follow the supplied schedule; read the account's assigned tier rather than inferring it solely from a locally calculated volume. The current [mainnet deployment](/deployments/mainnet#fees-and-order-limits) has 1 bp maker and 2 bps taker defaults, matching tier 0. Its 100 bp market fields are caps, not the normal charge. For example, on a 250 USDC trade, tier 0 costs 0.05 USDC as a taker or 0.025 USDC as a maker before token-unit rounding. At tier 1, the same notional costs 0.035 USDC as a taker or 0.01875 USDC as a maker. These calculations illustrate the schedule, not a live quote. Actual charges use the effective account and market rates and the token's smallest units. The [user fee-tier API](/api/data-source/reference/user-fee-tier) reports the latest indexed account assignment; it does not calculate market caps, referral discounts, or builder fees. Direct contract integrations can read `effectiveSpotMakerFeePps` and `effectiveSpotTakerFeePps` for the account and market. ## Buy and sell accounting Protocol trading fees are charged in the quote asset. For a WETH/USDC buy, allow for the USDC price of the purchase and the applicable protocol fee. For a sell, the protocol fee reduces the USDC proceeds. Resting buy orders reserve maker-fee headroom along with the purchase amount. Canceling the unfilled remainder releases its remaining reservation; it does not refund fees on trades already executed. ## Application fees An application may request an additional builder fee within an approval granted by the account owner. This is separate from the protocol's maker or taker fee. On a buy, a builder fee is charged from the base-asset output; on a sell, it is charged from quote proceeds. Review both charges when comparing the amount spent with the amount received. ## For integrators Use effective fee reads rather than assuming the deployment rate is the account's final rate. Maker fees are recorded per active fill; taker and builder fee rounding follows execution-match boundaries. See [AccountCore](/contracts/account-core) for fee policy and [OrderBook indexing](/indexing/order-book) for exact reconstruction. # Order Book and Priority Source: https://docs.kuru.io/matching-engine/order-book-and-matching Price priority, queue position, partial fills, and replacements. The order book contains resting buy and sell orders. Better prices execute first. Among resting limit orders at the same price, older orders execute before newer ones. This is first-in, first-out, or FIFO, priority. ## An example queue Alice places a sell order for 1 WETH at 2,500 USDC. Ben later places another sell order at the same price. If a buyer takes 0.5 WETH and there is no passive liquidity at that price, Alice's order fills partially; Ben's remains unchanged. A sell order at 2,490 would execute before either of them because it offers a better price to the buyer. Passive liquidity at the same price has priority over resting limit orders. ## Partial fills An order can execute through several trades. Its remaining amount stays open until it fills, is canceled, or is removed under an applicable execution rule. Very small residual amounts that cannot settle to one smallest unit of the payment token are removed as dust. This matters when reconciling the final remainder of an order. ## Replacing an order Replacing an order creates a new order and loses the old queue position, even if the price stays the same. The new resting order joins the back of its price level. An account can have up to 62 active order slots in each market. Fully filled or canceled orders free a slot for reuse. For implementation details about reusable slots and order identities, see [Orders, Cancellation, and Replacement](/sdk/orders-and-cancellation). # Order Types Source: https://docs.kuru.io/matching-engine/order-types Choose whether an order waits, trades immediately, or only provides liquidity. An order's price sets what you are willing to pay or accept. Its execution settings determine what happens when it reaches the market and whether an unfilled amount can stay open. ## Limit orders A limit order buys at your specified price or lower, or sells at your specified price or higher. It can execute immediately when suitable liquidity is available. A good-till-canceled (GTC) order leaves its executable unfilled remainder on the book until it fills or is canceled. **Example:** You want to buy 1 WETH for no more than 2,500 USDC each. If only 0.4 WETH is available within that limit, that amount can fill and the remaining 0.6 can rest at your limit price. ## Immediate-or-cancel An immediate-or-cancel (IOC) order fills as much as it can immediately within its price limit. Any unfilled remainder is discarded. Use it when you want available liquidity now and do not want an open order left behind. ## Fill-or-kill A fill-or-kill (FOK) order requires its executable quantity to fill immediately. Otherwise, the batch reverts. A tiny remainder that cannot be settled after a real fill counts as complete under the engine's dust rules. Use it when a partial executable fill would not meet your objective. ## Post-only Post-only ensures that an order only adds resting liquidity. If it would immediately trade against the live book, Kuru skips that order instead of placing it. It does not convert it into a taker order. **Example:** The lowest sell price is 2,500 USDC. A post-only buy at 2,500 would cross, so it is skipped. A buy below the available sell prices can rest, subject to the other order checks. Post-only is used with GTC. A successful submission does not by itself prove that the order was placed. ## Minimum order notional GTC orders, including post-only, must satisfy the market's minimum quote notional at their limit price. Native IOC and FOK orders can be smaller than this minimum. Maximum-notional, nonzero-notional, and price/quantity validity checks still apply. See [OrderBook](/contracts/order-book#native-orders) for the contract rules. ## Trading against available liquidity You can submit an immediately executable limit order with a price bound, or use an exact-input swap with a minimum acceptable output. Kuru's native order interface has no separate market-order enum. An exact-input swap is a separate trading flow. Read [Self-Trade Prevention](/matching-engine/self-trade-prevention) before using it from an account that also has resting orders. | Your objective | Setting to consider | | - | - | | Wait for your chosen price | GTC limit order | | Take available liquidity without leaving an order | IOC | | Require the executable quantity to fill now | FOK | | Only add liquidity | Post-only GTC | Market makers can also use [Reduce After Block](/matching-engine/reduce-after-block) to limit how much of a stale quote remains executable. ## Conditional orders — coming soon > [!WARNING] > > Automated trigger functionality—including take-profit/stop-loss (TP/SL) and other condition-based orders—is **not implemented** as a live trading feature. It is work in progress. Do not rely on a stored trigger to monitor a condition or place an order. Conditional execution is **not available as a supported automated trading flow yet**. Where enabled, Relay can [store a signed FOK trigger](/api/relay/reference/create-fok-swap-trigger), but this does not register a monitor or keeper. Do not assume a trigger will execute merely because its condition becomes true: execution needs an operating keeper, valid authorization, sufficient funds, and a market that can accept the action. ## TWAP orders — coming soon > [!WARNING] > > Automated TWAP execution is **not implemented**. Creating a TWAP instruction only stores it; no service schedules or submits its slices. This functionality is work in progress. Time-weighted average price (TWAP) execution is also **work in progress**. Where enabled, Relay can [store a signed TWAP instruction](/api/relay/reference/create-twap), but it does not run any slices. [Finalization](/api/relay/reference/finalize-twap) only records expiry/skipped/finished state. The deployed contracts do not, by themselves, provide a live scheduling or keeper service. Until automated execution launches, use currently supported order types for live trading. # How Orders Match Source: https://docs.kuru.io/matching-engine/overview How Kuru finds liquidity and executes a trade. When you submit an order, Kuru looks for available liquidity at a price your order accepts. A buy takes the lowest available sell price first. A sell takes the highest available buy price first. ## Two sources of liquidity Liquidity comes from resting limit orders and passive liquidity positions. The matching engine considers both when finding the best price. Resting orders specify a price and remaining amount. Passive positions supply liquidity through price bands whose inventory changes as trades occur. ## Price comes first Suppose you want to buy 1 WETH at a limit of 2,500 USDC. If 0.4 WETH is offered at 2,490 and another 0.6 at 2,500, the order can fill across both prices. It does not pay 2,500 for the amount available at 2,490. If there is not enough liquidity within your price limit, the remaining amount follows the rules of your [order type](/matching-engine/order-types). ## Priority at the same price At the same price, passive liquidity executes before resting limit orders. Resting limit orders then execute in the order they joined that price level: earlier orders fill first. See [Order Book and Priority](/matching-engine/order-book-and-matching) for partial fills and replacements, and [Passive Liquidity Events](/matching-engine/passive-liquidity) for passive execution and indexing. # Passive Liquidity Events Source: https://docs.kuru.io/matching-engine/passive-liquidity Understand how passive bands affect execution and which events to index. The matching engine can execute against passive price bands as well as resting limit orders. A band's base and quote inventory changes when trades execute against it. ## How trades use the liquidity The band exposes buy or sell liquidity at its active edge. Kuru compares that price with resting limit orders and executes the best available price first. At an equal price, passive liquidity executes before resting limit orders. ## Indexing passive activity Use `TradesPacked` to reconstruct execution-induced changes to active and passive depth. `PassiveBandUpdated` supplies the band's inventory snapshot. Key a band by `(chainId, market, lowPrice)`; do not infer its inventory solely from order-placement events. See [Order-book indexing](/indexing/order-book) and [SDK events](/sdk/events) for event fields and replay guidance. # Post-Fill Hooks Source: https://docs.kuru.io/matching-engine/post-fill-hooks Integrate synchronous maker callbacks for bounded quote refreshes. A maker may configure one hook contract for its account after protocol access has been granted. The maker or a `TRADE` signer calls `setPostFillHook(userId, hook)`; clearing to the zero address is always permitted. ## Trigger boundary A hook is staged when a fill removes an active maker slot: * full fill; * partial fill whose residual is removed as dust; or * stale RAB touch that consumes the complete exposed chunk. A partial fill that leaves a live residual does not trigger the hook. Staged hooks run after the current price boundary is exhausted or the taker finishes, before the engine recomputes BBO. `PostFillContext` supplies the maker ID, market, filled slot and order, post-fill/pre-refresh BBO, and advisory remaining taker size. A returned plan may replenish the filled slot, replace an opposite-side slot, or do both. Every quote must remain post-only and pass normal tick, size, reserve, and hook-minimum checks. ## Failure and side-effect boundary Callback reverts, callback out-of-gas, malformed output, and invalid returned refresh plans are caught so matching can continue. This is not a sandbox: when a callback returns successfully, any authorized external side effects it performed persist and can still cause the outer action to fail later. Hook quotes reserve from true free balance or reserve released by a sibling replacement in the same refresh. They cannot reuse the reserve consumed by the fill that triggered the hook. The gas limit bounds each callback, not the total number of callbacks or same-transaction replenishments. Taker size and transaction gas remain the outer bounds. # Reduce After Block Source: https://docs.kuru.io/matching-engine/reduce-after-block Limit the executable amount of a quote after a chosen block. Reduce After Block (RAB) lets a market maker reduce the amount exposed by a stale quote after a chosen block. It is an order setting, not a separate order type. ## How it works Until the selected block has passed, the order remains fully executable. Afterward, the order exposes at most the smallest amount that meets the market's minimum order value at that price. For example, if an order is much larger than the market minimum, a stale quote can still execute a market-minimum portion. The rest is released when the engine touches and reduces it. ## It does not cancel the order Passing the threshold does not update the stored order or immediately release its reserved funds. The order must be touched, canceled, or replaced before that state changes. A stale quote can still trade at its old price. Use cancellation when the objective is to remove the quote entirely. ## Reading depth Stored order state can retain the original size until the order is touched. The current onchain `getL2Book` and best-price views already account for stale-order visibility, so do not cap their returned depth a second time. An indexer reconstructing the book from stored orders must apply the visibility rule as blocks advance. Developers: the field is `minSizeAfterBlock`. Zero disables the policy. A nonzero value must exceed the placement block; reduction applies when `block.number > minSizeAfterBlock`. See the [OrderBook reference](/contracts/order-book) and [indexing guide](/indexing/order-book) for exact reduction and replay rules. # Self-Trade Prevention Source: https://docs.kuru.io/matching-engine/self-trade-prevention What happens when your trade encounters your own resting order. Self-trade prevention controls what happens when an incoming trade reaches liquidity owned by the same trading account. ## Limit-order flows For native orders and packed replacements, Kuru cancels the conflicting resting maker order and continues matching. It does not record a trade between the account and itself. For example, if you already have a sell order open and submit a buy that reaches it, the resting sell is canceled before matching continues to other liquidity. ## Swaps For an exact-input swap, encountering the same account's resting order reverts the transaction with a self-trade error. The swap does not cancel that order and continue. If you use both quoting and swaps in one account, check for conflicting orders before swapping. ## Which identity matters? The rule follows the trading account, not the wallet that submits the transaction. Two authorized bots trading for the same account can therefore encounter each other's orders. See [Subaccounts](/accounts/subaccounts) for separating balances and trading activity, and [SDK Swaps](/sdk/swaps) for integration details. # Accounts and Funding Source: https://docs.kuru.io/sdk/accounts Use numeric account IDs for custody and root-owner addresses for administration. AccountCore holds assets and records balances by numeric account ID. Read [Accounts](/accounts/overview) for the user-facing model first. All snippets here use the [reviewed SDK release](/sdk/installation). ## Register and fund a root ```typescript theme={null} const amount = parseUnits("100", tokenDecimals); const approval = await kuru.account.approveErc20({ token, spender: accountCore, amount }); const approvalReceipt = await publicClient.waitForTransactionReceipt({ hash: approval }); if (approvalReceipt.status !== "success") throw new Error("Approval reverted"); const deposit = await kuru.account.depositToOwner({ rootOwner: owner.address, token, amount }); const depositReceipt = await publicClient.waitForTransactionReceipt({ hash: deposit }); if (depositReceipt.status !== "success") throw new Error("Deposit reverted"); const rootAccountId = await kuru.account.getRootAccountId({ rootOwner: owner.address }); ``` `depositToOwner` can register an owner that has no root yet. `deposit({ rootAccountId, token, amount })` funds an existing root. Anyone can pay, but the payer receives no account authority. A child ID is rejected. Native MON uses `NATIVE_TOKEN_ADDRESS`; the request builder attaches the transaction value. ## Read balances ```typescript theme={null} const free = await kuru.account.getBalance({ accountId, token }); const reserved = await kuru.account.getSpotReservedBalance({ accountId, token }); ``` These methods accept root or child IDs. Passive inventory is accounted for separately. IDs are `bigint` at the SDK boundary; token amounts are raw token units. ## Transfer within a family ```typescript theme={null} await kuru.account.transferBetweenAccounts({ fromAccountId: rootAccountId, toAccountId: childAccountId, token, amount, }); ``` The same call handles child-to-root and sibling transfers. Both IDs must share a root. The caller must be the owner or have `INTERNAL_TRANSFER`, `WITHDRAW`, or `ADMIN` authority. Transfer only free balance. ## Withdraw to a wallet ```typescript theme={null} await kuru.account.withdraw({ rootAccountId, token, amount, recipient: owner.address }); ``` Withdrawals accept only a root ID and require an explicit external recipient. A successful return from the SDK is a transaction hash: await and check its receipt. Pricing, capacity, freezes, balance, and permission checks still apply. See [WithdrawalLimiter](/contracts/withdrawal-limiter). ## Signers and builders Signer administration identifies the root by its owner address: ```typescript theme={null} await kuru.account.authorizeAccountSigner({ account: owner.address, signer, permissions: AccountPermission.TRADE, expiry: deadlineSeconds(86_400), }); ``` This grant covers every account in the family. See [Signer Reference](/sdk/signer-reference) for implied permissions and authorization epochs. Builder approvals are root-wide. Positive builder fees credit the builder's ordinary root free balance, registering the root if needed. There is no separate claimable-fee ledger or claim method; builders use ordinary root withdrawals. # Market and Account Data Source: https://docs.kuru.io/sdk/data Use the data APIs alongside the contract and Relay SDK. A trading application needs both submission and observation. The contract SDK and Relay handle actions; the data services provide market lists, books, histories, balances, and order updates. ## Choose the source | UI or strategy input | Starting point | Live updates | | - | - | - | | Market selector | Data Source markets and tokens | Refresh catalog as needed | | Chart | Data Source candles | Refresh candles; market trades for new executions | | Order book | Gateway `l2Delta` subscription supplies its own snapshot | Continue deltas on that subscription | | Recent trades | Data Source market trades | Gateway market trades with the response's replay cursor | | Balances | Data Source user balances | Gateway user balances | | Open orders | Data Source user orders | Gateway user orders | | Execution history | Data Source user trades | Gateway user trades | Follow [Reading Market Data](/api/market-data) and [Following Account Activity](/api/account-activity) for the sequence and recovery rules. ## SDK compatibility See [Installation](/sdk/installation#exchange-websocket-decoder-compatibility) for decoder support and [Exchange WebSocket](/api/exchange/websocket) for binary frame layouts. REST can be consumed with your application's HTTP client. Preserve integer strings and use `bigint` for arithmetic rather than binary floating point. ## Convert at the display boundary Divide order prices by market `pricePrecision`, order quantities by `sizePrecision`, and token balances by the token's decimal scale. Some summary fields use x18 units; follow each endpoint's field description. These domains are not interchangeable. For WETH/USDC in the documented deployment, price `25000000` at precision `10000` is 2,500 USDC/WETH; quantity `1000000000` at size precision `10000000000` is 0.1 WETH; USDC balance `250000000` at six decimals is 250 USDC. Read current metadata rather than hardcoding these scales. The balances API's `total` is available plus order-reserved balance. Passive inventory must be added from position data when displaying a portfolio-wide total. # SDK Errors Source: https://docs.kuru.io/sdk/errors Handle SDK validation failures, simulation reverts, submission failures, and receipts. `KuruSdkError` contains a stable `code` and optional `cause`. Current codes cover missing or invalid addresses, hex and byte lengths, signatures, integer widths, missing wallet clients, signer and nonce resolution, unsupported signers, wallet-intent validation, and contract-error decoding. ```typescript theme={null} import { decodeKuruContractError, KuruSdkError } from "@toxicflow-labs/ts-sdk"; try { await kuru.spot.batch(params); } catch (error) { if (error instanceof KuruSdkError) console.error(error.code, error.message); throw error; } ``` Use `decodeKuruContractError(revertData)` for Kuru custom errors. Preserve the original viem error and transaction inputs in logs; decoded names alone may omit the failing call context. Separate four states in application logic: 1. local input validation failed; 2. simulation reverted; 3. submission failed or was replaced; 4. transaction was included and either succeeded or reverted. Do not retry writes blindly. Re-read nonce, slot order ID, balance, allowance, deadline, and receipt state before rebuilding an action. # Events and Operation Outcomes Source: https://docs.kuru.io/sdk/events Decode receipts without confusing successful submission with a resting order. Use `decodeKuruEventLog` to identify ABI events, then `decodeTradesPacked` or `decodeBookUpdatesPacked` for their packed payloads. Mixed receipts may contain unrelated token logs; only ignore a decoding failure when the emitting address/event is outside the integration's expected scope. ## Operation outcomes Trade records remain 64 bytes; book records remain 39 bytes. Outcome information occupies previously reserved bits. The SDK exposes `outcome`, operation correlation, and sentinel identification. | Value | Outcome | | - | - | | 0 | `NONE` | | 1 | `FILLED` | | 2 | `RESTED` | | 3 | `COMPLETED_NO_REST` | | 4 | `IOC_PARTIAL` | | 5 | `IOC_UNFILLED` | | 6 | `POST_ONLY_NOT_PLACED` | | 7 | `CANCELLED` | | 8 | `PROTOCOL_CANCELLED` | | 9 | `CANCEL_NOOP` | | 10 | `DUST_REMAINDER_DISCARDED` | Mask the base flags rather than comparing a full flag byte to a single value. Book outcomes use a one-bit shift; trade outcomes use a three-bit shift. Operation index and replacement-slot fields are meaningful according to the outcome record's context. ## Book state and match completion Zero-delta book sentinels report otherwise silent outcomes. Record the outcome but skip the sentinel for L2 and L3 changes. Ordinary live and delete records still mutate book state. `MATCH_END` closes a nonempty match's fee-accounting boundary. It does not by itself mean the incoming order filled completely. In particular, the final record may be a passive fill carrying the parent operation's outcome. Use [OrderBook Events](/indexing/order-book) for exact layouts, passive/active settlement, and reducer ordering. Use AccountCore balance snapshots to reconcile custody independently. # Installation and Configuration Source: https://docs.kuru.io/sdk/installation Use an SDK build that matches the latest account and wallet APIs. The examples use **`@toxicflow-labs/ts-sdk@0.2.0`**. Install the package, then configure a client with the current testnet AccountCore address below. ## Install the reviewed release Use Node.js 22.18 or later: ```bash theme={null} npm install @toxicflow-labs/ts-sdk@0.2.0 viem@2.51.3 ``` The examples compile against this published artifact. No source checkout is required. Earlier `0.1.1` installations do not provide the new account API. ## Configure clients ```typescript theme={null} import { createKuruClient } from "@toxicflow-labs/ts-sdk"; import { createPublicClient, createWalletClient, http } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { monadTestnet } from "viem/chains"; const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); const transport = http(process.env.RPC_URL); const publicClient = createPublicClient({ chain: monadTestnet, transport }); const walletClient = createWalletClient({ account, chain: monadTestnet, transport }); const kuru = createKuruClient({ publicClient, walletClient, account, addresses: { accountCore: "0xe08573a1Ecc4aa507c9626071fA0c4513caf7906" }, }); ``` This is a local-script example. Browser integrations should use the user's wallet provider; never embed an owner key in a frontend bundle. Validate environment variables before creating a client; the [first-trade example](/sdk/quickstart) does so. ## Exchange WebSocket decoder compatibility SDK 0.2.0 exports `@toxicflow-labs/ts-sdk/exchange-ws` for the earlier stream format. It does not decode the newer 256-bit balance fields, action/operation metadata and operation-sentinel records documented in [Exchange WebSocket](/api/exchange/websocket). The package pin above is for the contract examples. Trading-wallet signatures use EIP-712 domain version `2`; AccountCore administration uses version `1`. # SDK Method Reference Source: https://docs.kuru.io/sdk/method-reference Practical reference for clients, requests, account and Spot actions, wallet intents, Relay helpers, events, errors, and utilities. This reference targets SDK `0.2.0`, which publishes the account and wallet-v2 APIs from `f73ee41`. Follow [Installation](/sdk/installation) for release and Gateway decoder compatibility. ## Common conventions * Addresses are `` `0x${string}` `` values. * Contract integers use `bigint`; small enum/bitmap fields use `number` where stated. * A write returns a transaction hash. Await a receipt separately. * Every write accepts optional `account` and `simulate`; simulation is enabled by default. * Account methods accept optional `accountCore`; otherwise the configured address is used. * Spot methods always receive the market address. * `clientOrderId` is optional opaque correlation data, not an idempotency key. ## Client construction > [accordion] createKuruClient(config) > > Construct the combined AccountCore and Spot client. > > | Config field | Required | Meaning | > | - | -: | - | > | `publicClient` | yes | Viem client used for reads and write simulation. | > | `walletClient` | for writes | Viem client used to submit transactions. | > | `account` | for writes unless overridden | Default local or JSON-RPC account. | > | `addresses.accountCore` | for account calls | Default AccountCore address. | > | `addresses.spotRouter` | no | Stored protocol address for consumers that need it. | > | `simulateWrites` | no | Defaults to `true`. | > > **Returns:** `{ account, spot }` focused clients. > [accordion] createAccountClient(config) / createSpotClient(config) > > Construct only one focused client. > > They accept the same shared config and return the same method objects exposed under `createKuruClient`. ## Account client | Method | Required domain fields | Purpose | | - | - | - | | `getRootAccountId` | `rootOwner` | Owner address to root ID; zero before registration | | `getAccountOwner` / `getAccountRootId` / `getAccountSubaccountSeq` | `accountId` | Resolve numeric account identity | | `getSubaccounts` | `rootAccountId` | Child IDs in creation order | | `getBalance` / `getSpotReservedBalance` | `accountId`, `token` | Free / active-order reserved funds | | `getAccountAuthorizationEpoch` | `accountId` | Root epoch shared by the family | | `getSignerAuthorizationNonce` | `account` (root owner) | Root epoch for administration; zero before registration | | `isAuthorizedAccountSignerById` | `accountId`, `signer`, `permission` | Check trading on the target ID; check delegated non-trading roles on the root ID | | `depositToOwner` | `rootOwner`, `token`, `amount` | Register if needed, then fund root | | `deposit` | `rootAccountId`, `token`, `amount` | Fund an existing root | | `withdraw` | `rootAccountId`, `token`, `amount`, `recipient` | External payout subject to permissions and limiter | | `transferBetweenAccounts` | `fromAccountId`, `toAccountId`, `token`, `amount` | Move free funds within a family | | `createSubaccount` | `rootOwner` | Create a child ledger entry | | `createSubaccountBySig` | `rootOwner`, `authorizer`, `subaccountSeq`, `authNonce`, `deadline`, `signature` | Submit signed child creation | | `authorizeAccountSigner` | `account` (root owner), `signer`, `permissions`, `expiry` | Replace a root-wide grant | | `revokeAccountSigner` | `account` (root owner), `signer` | Remove a grant | | `getBuilderApproval` | `rootAccount`, `builder` | Read the root's fee cap and expiry | | `approveBuilder` / `revokeBuilder` | `builder`; approval also needs `maxFeePps`, `expiry` | Control acceptable application fees | | `getWithdrawalLimiter` | optional `accountCore` | Resolve the bound limiter | | `getApprovedWithdrawalNonce` | `rootOwner` | Read the approved-payout nonce | | `getWithdrawalAuthorityEpoch` | optional `accountCore` | Read dedicated authority version | | `getPostFillHookAccess` / `setPostFillHookAccess` | `accountId`; setter also `allowed` | Hook eligibility; setter requires protocol authority | `authorizeAccountSignerBySig` and `revokeAccountSignerBySig` add the live authorizer, nonce, deadline, and signature. Use the exported typed-data builders. Child creation uses the root's next sequence, not a child-address consent signature. `approveErc20` and `allowance` operate on the token. Native deposits attach `value` automatically. Writes return transaction hashes; check receipts separately. Request builders provide calldata without sending. Positive builder fees are ordinary root free balance. Builders use `withdraw`; there is no separate claim ledger. ### Approved payout helpers Use `buildApprovedWithdrawalTypedData`, `buildFulfillApprovedWithdrawalRequest`, `buildInvalidateApprovedWithdrawalNonceRequest`, and `buildPreviewWithdrawalRequest`. A capacity preview is not complete transaction validation. See [WithdrawalLimiter](/contracts/withdrawal-limiter). ## Spot client ### Market conversion Read `pricePrecision`, `sizePrecision`, and `tickSize` from `getMarketParams`. Use viem's `parseUnits` and `formatUnits` with the decimal exponent represented by each power-of-ten precision, then reject prices not divisible by `tickSize`. See [Orders and Cancellation](/sdk/orders-and-cancellation) for a complete example. ### Spot reads > [accordion] getMarketParams(\{ market }) > > Read precision, tick, notional, and market fee configuration. > > Returns a seven-value tuple: price precision, size precision, tick size, minimum quote notional, maximum quote notional, taker fee PPS, maker fee PPS. > [accordion] bestBidAsk(\{ market }) > > Read best stored bid and ask. > > Returns `[bid, ask]` as numbers. Empty bid is `0xffff_ffff`; empty ask is `0`. > [accordion] getL2Book(\{ market, levels }) > > Read combined visible active and passive depth. > > Returns bid price/size and ask price/size arrays. The onchain view applies stale-order visibility caps. Indexers maintaining their own book must apply the same rules. > [accordion] getOrderId(\{ market, userId, slotIdx }) > > Read the live order ID in a maker slot. > > Returns `0n` for an empty slot. Use the value for optimistic concurrency and > wallet expected-ID bindings. > [accordion] getOrderMinSizeAfterBlock(\{ market, userId, slotIdx }) > > Read a slot's RAB block threshold. > > Returns `0` when disabled or empty. > [accordion] getPassiveBand(\{ market, lowPrice }) > > Read aggregate passive band state. > > Returns inventory, shares, band edges, and fee-growth accumulators. > [accordion] getPassivePosition(\{ market, positionId }) > > Read a passive position. > > Returns owner ID, band edges, shares, and fee checkpoints. > [accordion] estimateSwap(\{ market, userId?, isBuy, amountIn, builderFeePps? }) > > Estimate an exact-input swap. > > Supplying `userId` applies that account's effective fee policy. The estimate cannot predict hook side effects or intervening state changes. ### Orders and swaps > [accordion] batch(\{ market, userId, orders, cancelSlotIdxs?, clientOrderId?, builderConfig?\[, account, simulate] }) > > Execute cancellations and native orders. > > Each order accepts side (`buy`/`sell` or enum), quantity, price, TIF, optional execution instruction, and optional `minSizeAfterBlock`. Inputs are normalized and range-checked before simulation. > > Returns the transaction hash. Decode `TradesPacked` and `BookUpdatesPacked` from the receipt for outcomes. > [accordion] cancelBySlots(\{ market, userId, cancelSlotIdxs, clientOrderId?\[, account, simulate] }) > > Cancel explicit maker slots through a cancellation-only batch. > > Empty slots are ignored. For race-sensitive systems, use current order IDs in > application state or the trading-wallet expected-ID flow. > [accordion] cancelAllOrders(\{ market, userId\[, account, simulate] }) > > Cancel all active slots in one market. > > Passive positions are unaffected. > [accordion] protocolCancelBySlots(...) > > Build or submit the protocol-restricted cancellation path. > > This export exists for authorized protocol operators. Ordinary applications > should use `cancelBySlots`. > [accordion] replaceBySlotPacked(\{ market, userId, packedOps, clientOrderId?, builderConfig?\[, account, simulate] }) > > Apply packed slot operations. > > Construct `packedOps` with `encodePackedReplaceOp(s)` and > `encodePackedCancelOp`; do not hand-build bit layouts in application code. > [accordion] swap(\{ market, userId, isBuy, amountIn, minAmountOut, deadline, builderConfig?\[, account, simulate] }) > > Execute an exact-input swap. > > For buys, input is quote and output is base. For sells, input is base and output is quote. Always set slippage and deadline explicitly. Every Spot write/read with overload selection also has a `build*Request` export. Request builders select the exact ABI overload and return unsent call data. ### Order encoding | Export | Use | | - | - | | `normalizeNativeSide`, `normalizeNativeTif`, `normalizeNativeExecInstruction` | Convert string/enum input and reject invalid values. | | `normalizeNativeOrder(s)` | Normalize full native order payloads. | | `encodePackedReplaceOp` | Encode one 32-byte cancel/replace operation. | | `encodePackedReplaceOps` | Concatenate and validate multiple operations. | | `encodePackedCancelOp` | Encode a strict slot cancellation. | ## Trading-wallet signing The wallet namespace prepares and signs contract-compatible EIP-712 payloads; it does not decide TP/SL or TWAP conditions. > [accordion] prepareReplaceBySlotIntent(input) / prepareBatchIntent(input) > > Normalize, validate, hash, and build an immediate wallet intent. > > Inputs include wallet address, chain ID, header, exact action payload, and expected order IDs. Returns normalized values, component hashes, typed data, and final digest without signing. > [accordion] prepareCreateReplaceTriggerIntent(input) / prepareCreateBatchTriggerIntent(input) > > Prepare a stored trigger creation intent. > > Adds `triggerExpiry` and opaque `conditionHash`. Array sizes, slot bindings, > packed payload shape, integer ranges, and header invariants are validated > locally. > [accordion] prepareCancelTriggerIntent(input) > > Prepare an unordered-nonce trigger cancellation. > > Binds wallet, chain, account ID, auth epoch, nonce, deadline, and trigger ID. > [accordion] signReplaceBySlotIntent / signBatchIntent / signCreateReplaceTriggerIntent / signCreateBatchTriggerIntent / signCancelTriggerIntent > > Prepare and sign one wallet intent. > > Each accepts its intent input plus a `WalletIntentSigner`. The SDK normalizes > the signature, recovers the signer, and rejects a signer that does not match > the delegated wallet address. > [accordion] createLocalAccountWalletIntentSigner(account) / createWalletClientIntentSigner(walletClient, account) > > Adapt viem signers to WalletIntentSigner. > > Use the local adapter for `LocalAccount`; use the wallet-client adapter for > injected/JSON-RPC wallets. > [accordion] signPreparedWalletIntent(intent, signer) / recoverWalletIntentSigner(typedData, signature) > > Low-level signing and verification helpers. > > Use these when storing prepared intent metadata before obtaining a signature. > [accordion] signEip7702Authorization / hashEip7702Authorization / createLocalAccountAuthorizationSigner > > Prepare EIP-7702 delegation authorization. > > This surface handles delegation authorization only. Wallet intent signatures are separate EIP-712 messages. Typed-data builders and hash helpers are exported individually for audit/replay: `tradingWalletDomain`, the corresponding `build*TypedData` functions, `hashPackedOperations`, `hashExpectedOrderIds`, `hashCancelSlotIndexes`, `hashNativeOrders`, and `normalizeAndHashNativeOrders`. ## Relay client The SDK contains a transport client and strict request serializers. See [Relay](/sdk/relay) for the signing-to-submission flow and [Relay API documentation](/api/relay/rest) for canonical service endpoints and wire schemas. > [accordion] createKuruRelayClient(config) > > Construct a Relay REST client. > > | Field | Meaning | > | - | - | > | `baseUrl` | Absolute HTTP(S) service URL without query/fragment. | > | `fetch` | Optional fetch implementation; defaults to `globalThis.fetch`. | > | `timeoutMs` | Optional request timeout, `1..120000`; default 10 seconds. | > | `signer` | Optional personal-message signer for challenge authentication. | > | `accessToken` / `tokenProvider` | Optional authentication token source. | > | `requestIdSource`, `now` | Optional deterministic test hooks. | > [accordion] requestChallenge(wallet\[, options]) / exchangeToken(challengeId, signature\[, options]) / authenticate(options?) > > Run challenge-based Relay authentication. > > `authenticate` performs the full challenge, personal-message signature, token > exchange, wallet-match validation, and optional token retention. In SDK > `0.2.0`, it does not pass the optional `uid` to `POST /auth/token`; see > [scoped Relay login](/sdk/relay#authenticate) before high-throughput trading. > [accordion] submit(request\[, options]) > > Validate and submit any already-built Relay request. > > Rejects malformed wire values before network I/O, resolves a live access > token, validates response request ID, and returns `RelayBroadcastResponse` or > throws `KuruRelayError`. > [accordion] executeReplaceBySlot / executeBatch / createReplaceTrigger / createBatchTrigger / cancelTrigger / authorizeAccountSigner > > Build and submit a typed Relay action in one call. > > Each method assigns a UUIDv7 request ID when absent, serializes integers as > canonical decimal strings, submits, and validates the broadcast response. > [accordion] createRequestId / getAccessToken / setAccessToken / clearAccessToken > > Manage request correlation and retained authentication state. > > Token state is in-memory per client. Persist tokens only as appropriate for the application, honor `expiresAt`, and explicitly authenticate again when required; the SDK never refreshes a token implicitly. Standalone builders mirror the high-level methods: `buildExecuteReplaceBySlotRelayRequest`, `buildExecuteBatchRelayRequest`, `buildCreateReplaceTriggerRelayRequest`, `buildCreateBatchTriggerRelayRequest`, `buildCancelTriggerRelayRequest`, and `buildAuthorizeAccountSignerRelayRequest`. Authentication adapters are `createLocalAccountRelaySigner`, `createWalletClientRelaySigner`, `resolveRelayAuthenticationWallet`, and `signRelayChallenge`. ## Events > [accordion] decodeKuruEventLog(log\[, abi]) > > Decode one AccountCore, SpotRouter, OrderBook, or trading-wallet log. > > Accepts `{ address, data, topics }`. The default ABI is `combinedKuruAbi()`. It throws when the log does not match; catch only when intentionally scanning mixed receipts. > [accordion] decodeTradesPacked(packedTrades) > > Decode concatenated 64-byte trade records. > > Returns typed records with maker identity, flags, price, fill size, final > resting size, fee snapshot, and trade ID. Invalid length throws. > [accordion] decodeBookUpdatesPacked(packedUpdates) > > Decode concatenated 39-byte book records. > > Returns complete live/deletion records including RAB threshold and maker-fee snapshot. ## Errors and utilities | Export | Behavior | | - | - | | `KuruSdkError` | Local configuration, validation, signing, and transaction setup error with stable `code`. | | `decodeKuruContractError(data[, abi])` | Decode revert bytes into `{ errorName, args }`; throws `CONTRACT_ERROR_DECODE_FAILED` if unsupported. | | `KuruRelayError` | Relay input, authentication, HTTP, malformed-response, or service-rejection error with structured metadata. | | `toBigInt`, `assertUint`, `assertUintNumber` | Canonical unsigned integer conversion/range checks. | | `unixSecondsNow`, `unixMillisecondsNow`, `deadlineSeconds` | Time/deadline helpers returning `bigint`. | | `emptyClientOrderId`, `clientOrderIdFromString`, `normalizeClientOrderId` | Canonical bytes32 correlation helpers. | | `executeWrite`, `readContract`, `withValue`, `resolveWritableAccount` | Low-level viem transaction utilities used by focused clients. | | `requireConfiguredAddress` | Resolve configured/override contract addresses or throw `ADDRESS_REQUIRED`. | | `createRelayRequestId`, `isRelayRequestId`, `assertRelayRequestId` | UUIDv7 request-ID helpers. | ## Namespaces and ABI exports The package root re-exports the public functions and types. Namespaced imports are also available as `account`, `spot`, `tradingWallet`, `relay`, `events`, `products`, and `utils`. Contract ABIs are exposed under `abi` and `generated`; `CONTRACTS_COMMIT` identifies the ABI source revision. ## Additional wallet-v2 actions Prepare typed intents with `prepareCancelAllIntent`, `prepareCancelOrdersByIdIntent`, `prepareFokSwapIntent`, `prepareCreateFokSwapTriggerIntent`, `prepareCreateTwapIntent`, `prepareCancelTwapIntent`, or `prepareEmitSignedDataIntent`. Sign with `signPreparedWalletIntent` and encode direct calls with `buildWalletActionRequest`. `buildExecuteTwapSliceRequest` and `buildFinalizeTwapRequest` encode keeper/lifecycle calls. These direct-contract builders do not add hosted Relay endpoints. ## Relay encryption helpers The Relay SDK provides `requestEncryptionKey`, `encryptRelayPrivateKey`, and `decryptRelayPrivateKey` for the service's encrypted-key transport. Use the returned encryption key identifier and expiry when preparing a request. This is distinct from owner-signed EIP-712 action submission and is not required for the direct first-trade tutorial. # Orders, Cancellation, and Replacement Source: https://docs.kuru.io/sdk/orders-and-cancellation Place native orders and perform slot-bound cancellation and replacement. ```typescript theme={null} import { abi } from "@toxicflow-labs/ts-sdk"; import { parseUnits } from "viem"; function precisionDecimals(precision: bigint): number { const value = precision.toString(); if (!/^10*$/.test(value)) throw new Error(`Unsupported precision: ${precision}`); return value.length - 1; } const [pricePrecision, sizePrecision, tickSize] = await publicClient.readContract({ address: market, abi: abi.orderBookAbi, functionName: "getMarketParams" }); const price = parseUnits("12.34", precisionDecimals(BigInt(pricePrecision))); if (price % BigInt(tickSize) !== 0n) throw new Error("Price is off tick"); const quantity = parseUnits("1", precisionDecimals(sizePrecision)); await kuru.spot.batch({ market, userId, orders: [{ side: "buy", quantity, price, tif: "gtc", executionInstruction: "postOnly", minSizeAfterBlock: 0n }], cancelSlotIdxs: [], clientOrderId }); ``` The SDK accepts enum names or exported numeric constants and validates integer widths. It does not validate market tick, notional, balance, or live-book conditions locally; write simulation handles contract validation. ## Packed replacement ```typescript theme={null} import { encodePackedReplaceOps } from "@toxicflow-labs/ts-sdk"; const packedOps = encodePackedReplaceOps([ { slotIdx: 2, side: "sell", price: parseUnits("12.5", precisionDecimals(BigInt(pricePrecision))), size: parseUnits("0.5", precisionDecimals(sizePrecision)), postOnly: true }, { slotIdx: 5 } // cancel ]); await kuru.spot.replaceBySlotPacked({ market, userId, packedOps, clientOrderId }); ``` `cancelBySlots` builds an empty-order `batch`; `cancelAllOrders` calls the dedicated entrypoint. Read the current `getOrderId` before submitting asynchronous slot operations. `protocolCancelBySlots` and its request builder are exported but require the contract's protocol cancellation authority. Ordinary applications should not call them. # Developer Overview Source: https://docs.kuru.io/sdk/overview Choose a starting point for building on Kuru. Use these guides to implement the concepts described in the [general docs](/introduction/spot). The TypeScript SDK builds contract calls, prepares signatures, submits supported Relay requests, and decodes onchain events. ## Start here > [card] [First trade](/sdk/quickstart) > > Configure a client, fund an account, place an order, and cancel it. > [card] [Delegated trading](/sdk/relay-onboarding) > > Authorize a secondary signer and connect it to Relay. > [card] [Market and account data](/sdk/data) > > Choose REST reads and WebSocket subscriptions. > [card] [Contract architecture](/contracts/overview) > > Understand custody, execution, and signed-action boundaries. ## SDK responsibilities The SDK accepts caller-provided viem public and wallet clients. `kuru.account` handles account operations; `kuru.spot` handles market operations. Lower-level request builders support applications that separate construction, signing, and submission. Your application owns transaction confirmation, order reconciliation, nonce allocation, and strategy decisions. A returned transaction hash is not a confirmed order. ## Advanced integrations Use the [method reference](/sdk/method-reference) for callable SDK surfaces, [contract reference](/contracts/overview) for direct calls, and [indexing guide](/indexing/overview) if you need to reconstruct state yourself. Package compatibility and the distinction between the published release and the reviewed release are covered in [Installation](/sdk/installation). # First Trade Source: https://docs.kuru.io/sdk/quickstart Fund a test account, place a post-only order, inspect its result, and cancel the remainder. This walkthrough uses direct transactions on the current Monad testnet MON/USDC market. It needs no Relay account. Use a dedicated owner with no existing orders in that market and no other process trading for it. ## Before you run Install the [reviewed SDK release](/sdk/installation), obtain test MON for gas and dummy USDC, and check [Testnet Setup](/deployments/setup). This script sends real testnet transactions and deposits the amount you choose. Re-running it deposits that amount again. Set these environment values through your local secret manager or shell environment: | Variable | Meaning | | - | - | | PRIVATE_KEY | Dedicated test owner's key | | RPC_URL | Monad testnet RPC | | LIMIT_PRICE | Maximum USDC per MON, as a decimal string | | BASE_QUANTITY | MON quantity, as a decimal string | | DEPOSIT_USDC | USDC to deposit, including sufficient fee headroom | The current minimum notional is 10 USDC; the script reads bounds from the market. Choose a valid tick-aligned price and enough funds for the buy reservation and maker fee. A post-only order can be skipped if it crosses when executed, or can fill after resting before cancellation. Use test funds and inspect the outcome. From a local docs checkout, run: ```bash theme={null} node --experimental-strip-types examples/src/first-order.ts ``` ## Complete example ```typescript theme={null} import { abi, createKuruClient, decodeKuruEventLog, decodeBookUpdatesPacked, NativeExecInstruction, NativeSide, NativeTif } from "@toxicflow-labs/ts-sdk"; import { createPublicClient, createWalletClient, http, parseUnits, type Hash } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { monadTestnet } from "viem/chains"; function required(name: string): string { const value = process.env[name]; if (!value) throw new Error(`Set ${name}`); return value; } const account = privateKeyToAccount(required("PRIVATE_KEY") as `0x${string}`); const transport = http(required("RPC_URL")); const publicClient = createPublicClient({ chain: monadTestnet, transport }); const walletClient = createWalletClient({ account, chain: monadTestnet, transport }); if (await publicClient.getChainId() !== 10143) throw new Error("Expected Monad testnet"); // Dedicated tutorial owner; do not run another trading process for this account. const accountCore = "0xe08573a1Ecc4aa507c9626071fA0c4513caf7906"; const market = "0xD2F64EaF7E85688802d24C18ea268C365533b344"; // MON/USDC const token = "0xb01DC575a7ef75e58A05D2bde73ab79f8e7dd0Be"; // Test USDC const kuru = createKuruClient({ publicClient, walletClient, account, addresses: { accountCore } }); async function confirmed(hash: Hash) { const receipt = await publicClient.waitForTransactionReceipt({ hash }); if (receipt.status !== "success") throw new Error(`Transaction reverted: ${hash}`); return receipt; } function scaleDecimals(scale: bigint): number { if (!/^10*$/.test(scale.toString())) throw new Error("Expected power-of-ten precision"); return scale.toString().length - 1; } const [priceScale, sizeScale, tick, minQuote, maxQuote] = await publicClient.readContract({ address: market, abi: abi.orderBookAbi, functionName: "getMarketParams" }); const price = parseUnits(required("LIMIT_PRICE"), scaleDecimals(BigInt(priceScale))); const quantity = parseUnits(required("BASE_QUANTITY"), scaleDecimals(sizeScale)); const decimals = await publicClient.readContract({ address: token, abi: abi.erc20MetadataAbi, functionName: "decimals" }); const amount = parseUnits(required("DEPOSIT_USDC"), decimals); if (price <= 0n || price > 0xffff_ffffn || price % BigInt(tick) !== 0n || quantity <= 0n || quantity >= (1n << 96n) || amount <= 0n) throw new Error("Invalid price, tick, quantity or deposit"); const quote = (price * quantity / sizeScale) * 10n ** BigInt(decimals) / BigInt(priceScale); if (quote < minQuote || quote > maxQuote) throw new Error("Order outside market notional bounds"); let userId = await kuru.account.getRootAccountId({ rootOwner: account.address }); if (userId !== 0n) { const ids = await Promise.all(Array.from({ length: 62 }, (_, slotIdx) => kuru.spot.getOrderId({ market, userId, slotIdx }))); if (ids.some(id => id !== 0n)) throw new Error("Use an account without existing orders in this market"); } await confirmed(await kuru.account.approveErc20({ token, spender: accountCore, amount })); await confirmed(await kuru.account.depositToOwner({ rootOwner: account.address, token, amount })); userId = await kuru.account.getRootAccountId({ rootOwner: account.address }); const receipt = await confirmed(await kuru.spot.batch({ market, userId, orders: [{ side: NativeSide.BUY, quantity, price, tif: NativeTif.GTC, executionInstruction: NativeExecInstruction.POST_ONLY, minSizeAfterBlock: 0n }], cancelSlotIdxs: [], })); // Decode only market logs; a successful post-only action can still place no order. for (const log of receipt.logs) { if (log.address.toLowerCase() !== market.toLowerCase()) continue; const event = decodeKuruEventLog(log); if (event.eventName === "BookUpdatesPacked") { const args = event.args as unknown as { packedUpdates: `0x${string}` }; console.log(decodeBookUpdatesPacked(args.packedUpdates)); } } // This dedicated account began with no live orders; inspect all slots instead of assuming slot zero. for (let slotIdx = 0; slotIdx < 62; slotIdx++) { const orderId = await kuru.spot.getOrderId({ market, userId, slotIdx }); if (orderId === 0n) continue; await confirmed(await kuru.spot.cancelBySlots({ market, userId, cancelSlotIdxs: [slotIdx] })); } console.log({ accountId: userId, free: await kuru.account.getBalance({ accountId: userId, token }), reserved: await kuru.account.getSpotReservedBalance({ accountId: userId, token }) }); ``` ## What to check Every transaction must have a successful receipt. A successful post-only submission does not guarantee an open order: inspect operation outcomes and current slots. The script scans all 62 slots rather than assuming the first order occupies slot zero. Cancellation releases only the remaining reservation; it cannot reverse fills. Funds remain inside AccountCore after the tutorial. Use [Accounts and Funding](/sdk/accounts) to withdraw them, subject to current withdrawal checks. For concurrent production workers, bind cancellations to live order IDs using the wallet's signed action flow, and follow [Signer Lifecycle](/sdk/signer-lifecycle). This tutorial's slot cleanup relies on exclusive use of its dedicated account. # Relay Source: https://docs.kuru.io/sdk/relay Authenticate a trading wallet and submit signed Kuru actions through the TypeScript SDK. `@toxicflow-labs/ts-sdk/relay` authenticates a secondary trading EOA with Relay and submits already signed trading-wallet or AccountCore payloads. It does not create wallet-intent signatures for you; use [Trading-wallet signing](/sdk/trading-wallet) first. All testnet examples use Monad chain ID `10143` and the Relay testnet URL `https://relay.testnet.kuru.io`. This SDK Relay client submits over REST. For direct WebSocket integration, connect to `wss://relay.testnet.kuru.io/relay/ws?account_id=` (or `wss://relay.mainnet.kuru.io/relay/ws?account_id=` on mainnet) with a wallet-bound JWT in the `Authorization` upgrade header. `account_id` is the Kuru trading account ID, not the signer address; for a scoped JWT it must match the token's verified `uid`. See the [Relay WebSocket overview](/api/relay/rest#websocket) for its canonical format and outcome behavior. The SDK does not currently provide a Relay WebSocket transport. ## Authenticate `authenticate()` requests Relay's one-time challenge, signs its exact UTF-8 message with `personal_sign`, exchanges it for a JWT, validates the wallet binding, and retains the token on the client. In SDK `0.2.0`, this helper exchanges the challenge **without** `uid`, so it produces a wallet-only token. That remains suitable for initial signer onboarding, but after the [scheduled rate-limit cutover](/api/relay/rate-limits) it uses the lower wallet-based quota. Once the signer has AccountCore `TRADE` permission, obtain a scoped token for each account/subaccount it trades. ```typescript theme={null} import { privateKeyToAccount } from "viem/accounts"; import { createKuruRelayClient, createLocalAccountRelaySigner, } from "@toxicflow-labs/ts-sdk/relay"; const tradingWallet = privateKeyToAccount( process.env.TRADING_WALLET_KEY as `0x${string}`, ); const relay = createKuruRelayClient({ baseUrl: "https://relay.testnet.kuru.io", signer: createLocalAccountRelaySigner(tradingWallet), timeoutMs: 5_000, }); const session = await relay.authenticate(); console.log(session.wallet, session.expiresAt); ``` Until the SDK supports the `uid` token parameter, use its challenge/signing helpers and call the public token endpoint directly: ```typescript theme={null} import { signRelayChallenge } from "@toxicflow-labs/ts-sdk/relay"; const uid = "10"; // exact trading account ID; use the child ID for a subaccount const challenge = await relay.requestChallenge(tradingWallet.address); const signature = await signRelayChallenge( challenge.message, createLocalAccountRelaySigner(tradingWallet), ); const response = await fetch("https://relay.testnet.kuru.io/auth/token", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ challengeId: challenge.challengeId, signature, uid }), }); if (!response.ok) throw new Error(`Relay token exchange failed: ${response.status}`); const scoped = (await response.json()) as { accessToken: string; expiresAt: string; wallet: string; }; if (scoped.wallet.toLowerCase() !== tradingWallet.address.toLowerCase()) { throw new Error("Relay token wallet mismatch"); } if (Date.parse(scoped.expiresAt) <= Date.now()) { throw new Error("Relay token is expired"); } relay.setAccessToken(scoped.accessToken); ``` Keep the new token secret and refresh it through the same `uid` flow before expiry. The token response does not separately return a root ID or quota; Relay signs the verified account/root binding into the JWT. `uid` is for `POST /auth/token`, not for `POST /auth/challenge` or a trading request envelope. Set the signed intent's `header.accountId` to the exact `uid`. The account-scoped login verifies current trading permission but does not register the account or grant permission. Headerless onboarding and operational requests still use wallet-based quotas, regardless of this token. Use `createWalletClientRelaySigner(walletClient, tradingWalletAddress)` for an injected or embedded wallet. The SDK does not authenticate, refresh tokens, re-sign payloads, or retry state-changing submissions implicitly. ## Sign and submit After the signed `intent` is ready, submission is one Relay REST request and no chain RPC. The client assigns a UUIDv7 request ID unless you provide one. ```typescript theme={null} // intent is the SignedWalletIntent returned by signBatchIntent(...). const broadcast = await relay.executeBatch({ intent }); console.log(broadcast.txHash, broadcast.transactionType); ``` > [!WARNING] > > `BROADCAST` means Relay accepted and scheduled the sponsored transaction for > asynchronous RPC broadcast. It does not prove provider acceptance or that the > target action executed. Wait for the transaction receipt and verify the > expected event or state change. ## SDK method mapping | Signed value | Relay client method | Relay API reference | | - | - | - | | AccountCore signer authorization, optionally plus EIP-7702 authorization | `authorizeAccountSigner` | [Authorize account signer](/api/relay/reference/authorize-account-signer) | | `SignedWalletIntent` | `executeReplaceBySlot` | [Execute packed replacement](/api/relay/reference/execute-replace-by-slot) | | `SignedWalletIntent` | `executeBatch` | [Execute order batch](/api/relay/reference/execute-batch) | | `SignedWalletIntent` | `createReplaceTrigger` | [Create packed trigger](/api/relay/reference/create-replace-trigger) | | `SignedWalletIntent` | `createBatchTrigger` | [Create batch trigger](/api/relay/reference/create-batch-trigger) | | `SignedWalletIntent` | `cancelTrigger` | [Cancel conditional order](/api/relay/reference/cancel-trigger) | Relay trigger creation (`createReplaceTrigger` and `createBatchTrigger`) is disabled. The SDK provides the corresponding signing interfaces for contract integrations. Relay also defines nine [opt-in operational methods](/api/relay/operational), including cancel-by-ID, cancel-all, FOK, stored FOK trigger/TWAP actions, signer revocation, and subaccount creation. They use bounded RPC simulation and are slower than the batch/packed path. The SDK Relay client does **not** currently expose wrappers for these new methods; use the documented REST or authenticated WebSocket envelopes with separately prepared, exact EIP-712 signatures. In particular, AccountCore revocation and child creation use a separate owner/admin/TRADE authorizer signature with the AccountCore version-1 domain; the frontend trading-wallet JWT does not grant that authority. ## Runnable examples The SDK repository has one runnable source file per Relay method. Each signs its payload first, authenticates the trading EOA, then sends the matching Relay request: * [`authorize-account-signer.ts`](https://github.com/Kuru-Labs/ts-sdk/blob/main/examples/relay/authorize-account-signer.ts) * [`execute-replace-by-slot.ts`](https://github.com/Kuru-Labs/ts-sdk/blob/main/examples/relay/execute-replace-by-slot.ts) * [`execute-batch.ts`](https://github.com/Kuru-Labs/ts-sdk/blob/main/examples/relay/execute-batch.ts) * [`create-replace-trigger.ts`](https://github.com/Kuru-Labs/ts-sdk/blob/main/examples/relay/create-replace-trigger.ts) * [`create-batch-trigger.ts`](https://github.com/Kuru-Labs/ts-sdk/blob/main/examples/relay/create-batch-trigger.ts) * [`cancel-trigger.ts`](https://github.com/Kuru-Labs/ts-sdk/blob/main/examples/relay/cancel-trigger.ts) Set the current account and market inputs explicitly before running an example. The testnet deployment addresses and chain ID `10143` are listed in [Testnet Deployments](/deployments/testnet). ## Errors and retries `KuruRelayError.kind` distinguishes input, authentication, HTTP, transport, timeout, cancellation, Relay rejection, and malformed-response failures. A Relay rejection includes safe response metadata such as `retryable`, `retryAfterMs`, and `candidateTxHash`. Do not blindly retry a state-changing request. Reconcile the prior request ID and any candidate transaction hash, then use a fresh signature or consciously reuse the same request ID only when the Relay API's idempotency behavior is understood. # Delegated Trading with Relay Source: https://docs.kuru.io/sdk/relay-onboarding Fund an owner account, authorize a secondary signer, and submit signed actions. Use a funded owner account and a separate secondary EOA for trading. Relay submits supported signed actions and sponsors their gas. The secondary EOA uses KuruTradingWallet through EIP-7702 delegation. ## Before you start Complete [Testnet Setup](/deployments/setup), [Installation](/sdk/installation), and the funding steps in [First Trade](/sdk/quickstart). Keep owner and trading keys separate. ## Who signs what? | Item | Signed by | Effect | | - | - | - | | AccountCore authorization | Owner or live administrator | Grants trading permission across the owner’s account family | | EIP-7702 authorization | Secondary EOA | Installs KuruTradingWallet delegation on that EOA | | Relay challenge | Secondary EOA | Obtains a wallet-bound service JWT | | Order intent | Secondary EOA | Authorizes a specific trading action | These are separate authorizations. A JWT cannot replace AccountCore permission or an order signature. ## 1. Read the funded account Read `getRootAccountId({ rootOwner: owner.address })`, the current available balance, and `getSignerAuthorizationNonce({ account: owner.address })`. The order's account ID identifies the funded owner account, not the secondary signer. ## 2. Prepare both onboarding authorizations Use `buildAuthorizeAccountSignerTypedData` with the owner account, secondary signer, `TRADE` permission, current AccountCore nonce, expiry, and deadline. Have the owner sign that typed data. Read the secondary EOA's pending transaction count for its EIP-7702 authority nonce. Sign an authorization for the KuruTradingWallet implementation from [Testnet Deployments](/deployments/testnet), on chain `10143`. If this EOA is **already delegated to an older or unsupported implementation**, do not assume Relay can combine its re-delegation with the AccountCore grant. Relay may reject that path with `7702_UNSUPPORTED_CODE_STATE` before broadcasting. Use a fresh secondary EOA, or submit the existing EOA's signed EIP-7702 re-delegation through a separately funded sender. Confirm the new delegation on-chain, then submit the owner-signed AccountCore grant through Relay with `authorization7702: null`. A re-delegation changes the wallet implementation; it does not itself grant `TRADE` permission or migrate old wallet signatures and storage. See [Relay errors](/api/relay/errors) and [Trading-wallet Signing](/sdk/trading-wallet). Do not default either nonce to zero. See [Trading-wallet Signing](/sdk/trading-wallet) for the signing helpers. ## 3. Authenticate and submit Authenticate the secondary EOA with `relay.authenticate()`. Submit the owner-signed grant and the secondary EOA's delegation authorization using `relay.authorizeAccountSigner`. This first login is intentionally wallet-only: the signer cannot receive a verified `uid` token before its AccountCore trading grant is live. Onboarding uses the wallet-based sponsorship quota even if a scoped JWT is supplied. After the grant is confirmed, [log in again with the funded account's `uid`](/api/relay/rate-limits#move-to-account-scoped-login) for account-scoped trading. The signed owner/administrator authorizer is not required to be the JWT wallet. The typed example in `examples/src/relay-authorize-account-signer.ts` reads both nonces before signing. From a local checkout of these docs, provide `RPC_URL`, `ACCOUNT_OWNER_KEY`, `TRADING_WALLET_KEY`, `KURU_ACCOUNT_CORE`, and `KURU_TRADING_WALLET_DELEGATE`, then run: ```bash theme={null} node --experimental-strip-types examples/src/relay-authorize-account-signer.ts ``` Load secrets through your local environment or secret manager; do not put them in documentation, source files, or shell command arguments. ## 4. Verify onboarding A broadcast response is only submission. Require a successful receipt, check the secondary EOA's EIP-7702 delegation target, and read back its `TRADE` permission. Read the AccountCore authorization nonce again: granting the signer advances it. Use this new authorization nonce in subsequently signed order intents. Previously prepared intents may now be stale. ## 5. Sign and submit an order Read market precision, tick, and notional constraints. Allocate an immediate-action nonce using the policy in [Signer Lifecycle and Nonces](/sdk/signer-lifecycle), then create an intent with `signBatchIntent` and submit it with `relay.executeBatch`. Before the first trading submission, use a new account-scoped JWT for the exact account being traded. Its verified `uid` must equal the signed intent's `header.accountId`; for a WebSocket connection, its `account_id` upgrade parameter must match too. The SDK 0.2.0 `authenticate()` helper does not yet send `uid`; see [scoped authentication](/sdk/relay#authenticate) for the direct token-exchange step. The same batch method supports cancellation. Bind cancellation slots to current order IDs when the instruction must target a specific order. Verify the actual resting-order state; post-only crossing can be skipped in a successful transaction. See [Relay Submission](/sdk/relay) for the SDK method map and [Orders, Cancellation, and Replacement](/sdk/orders-and-cancellation) for order construction. ## 6. Retire or rotate the signer Stop new signing, reconcile submitted work, and decide whether to cancel outstanding orders. Revoke the old signer with owner authority and verify the permission is no longer live. Revocation does not remove resting orders or liquidity positions. Follow the [signer lifecycle](/sdk/signer-lifecycle) when bringing the replacement online. # Signer Lifecycle and Nonces Source: https://docs.kuru.io/sdk/signer-lifecycle Manage signer grants, concurrent intent creation, and key rotation. Use one owner account for custody and a separate EOA for delegated trading. Grant only the needed permissions. The permission values and authorization methods are in [Signer Reference](/sdk/signer-reference). ## Separate nonce domains | Value | Scope | Source | | - | - | - | | EIP-7702 authority nonce | Secondary EOA's transaction sequence | Pending transaction count of that EOA | | AccountCore authorization epoch | Root and every child in its family | `accountAuthorizationEpoch(accountId)` or root-owner nonce lookup | | Immediate order nonce | Delegated trading-wallet EOA and chain, across its accounts and markets | `lastSeenOrderNonce()` called at that EOA | | Trigger and TWAP creation/cancellation nonce | Delegated EOA and chain, shared unordered one-shot use | `usedTriggerNonce(nonce)` | | Signed-data nonce | Delegated EOA and chain, sequential publication | `signedDataNonce()` | Read wallet-local storage at the delegated EOA, not at the shared implementation. Immediate order nonces must increase strictly; they do not have to increase by exactly one. ## Allocating immediate nonces `Date.now()` alone is not an allocator: concurrent requests can receive the same millisecond value. Maintain an atomic allocator per trading EOA, shared by every worker using it. For each allocation: 1. Read the latest observed onchain nonce and the highest durably allocated local nonce. 2. Choose the maximum of the current millisecond timestamp, the chain nonce plus one, and the locally allocated nonce plus one. 3. Verify it is within the contract's future-skew bound and the hosted Relay's admitted nonce window. 4. Persist the reservation before signing or handing the intent to another worker. The contract's `maxFutureNonceSkewMillis()` bounds the nonce relative to block time. If the clock or allocation sequence is too far ahead, wait and reconcile; do not keep incrementing rejected values. Handle Relay nonce and deadline errors using the [error reference](/api/relay/errors). ## Submission ordering Unique increasing nonces do not guarantee execution order. If a higher nonce executes first, a lower outstanding nonce can become invalid. For an initial integration, submit and confirm one immediate action at a time for each trading wallet. A higher-throughput integration needs explicit ordering and reconciliation across workers and connections. A reconnect does not reset the onchain nonce. Preserve pending intents and the allocator's durable high-water mark across restarts. ## Refresh authorization state Signer grants and revocations advance the root authorization epoch, invalidating older intents across the family, including other signers’ intents. Creating a child does not advance the epoch. After a permission change, read the new nonce and rebuild affected intents. Confirm both live permission and expiry at execution time. ## Rotation and retirement 1. Stop the old signer from creating instructions. 2. Reconcile submitted transactions. Cancel orders or remove liquidity if the strategy is stopping; do not assume revocation performs cleanup. 3. Revoke the old signer using the owner or a live administrator. 4. Confirm the receipt and verify `isAuthorizedAccountSignerById` is false. 5. Authorize and onboard the replacement signer, then read the latest account authorization nonce. 6. Resume with new signatures and the replacement wallet's own nonce state. If the old key is compromised, revoke promptly; do not wait for the old signer to cooperate. Handle resting orders using the owner's authority. Separately remove hosted-service access through the operator's admission process. JWT expiry ends a Relay session. It does not revoke AccountCore permissions or remove EIP-7702 delegation. # Signer Reference Source: https://docs.kuru.io/sdk/signer-reference Root-wide permission bits, administration, and authorization epochs. All signer grants belong to a root and cover its current and future children. There are no per-child grants. | Permission | Bit | Effective authority | | - | - | - | | `TRADE` | `1 << 0` | Trade, manage passive liquidity and permitted hooks, create children | | `INTERNAL_TRANSFER` | `1 << 2` | Move free balances inside the family | | `WITHDRAW` | `1 << 3` | Root withdrawals to an explicit recipient; includes internal transfers | | `ADMIN` | `1 << 4` | Manage signers; includes all defined roles | An expiry of zero means no expiry. A nonzero expiry is a Unix timestamp evaluated at execution. Stored grants and events contain the exact granted bits; authority checks apply the implications above. ## Administration Use `authorizeAccountSigner` and `revokeAccountSigner` with `account: rootOwner`. Signed variants use the AccountCore version-1 EIP-712 domain and the current owner-address authorization nonce. Anyone may submit a valid signature, but the authorizer must still have authority when it executes. Each successful grant or revocation advances the root epoch. Read it for any family member with `getAccountAuthorizationEpoch({ accountId })`. For signer administration, `getSignerAuthorizationNonce({ account: rootOwner })` returns the same root state, or zero before registration. Creating a child does not change the epoch. Reauthorizing a revoked signer does not revive its previous intents or stored triggers. ## Check live authority ```typescript theme={null} const allowed = await kuru.account.isAuthorizedAccountSignerById({ accountId, signer, permission: AccountPermission.TRADE, }); const authNonce = await kuru.account.getAccountAuthorizationEpoch({ accountId }); ``` Check `TRADE` against the actual target root or child ID. For a delegated signer, child-ID queries mask out non-trading permissions; check `ADMIN`, `WITHDRAW`, and `INTERNAL_TRANSFER` against the root ID. Internal transfers and signer administration also authorize against the root. Check one permission bit at a time. A signed message, Relay JWT, or installed EIP-7702 delegation is not proof of live AccountCore permission. # Creating Subaccounts Source: https://docs.kuru.io/sdk/subaccounts Create ID-based trading balances and fund them from the root. A child is an AccountCore ledger entry with a numeric ID. It has no wallet address, deployment, private key, or child-specific signer registry. ## Direct creation ```typescript theme={null} const hash = await kuru.account.createSubaccount({ rootOwner: owner.address }); const receipt = await publicClient.waitForTransactionReceipt({ hash }); if (receipt.status !== "success") throw new Error("Creation reverted"); const rootAccountId = await kuru.account.getRootAccountId({ rootOwner: owner.address }); const children = await kuru.account.getSubaccounts({ rootAccountId }); ``` Use the receipt's `SubaccountCreated` event to identify this transaction's child if several workers can create children concurrently. Do not infer it from the last element of a later list read. The owner or a live root `TRADE`/`ADMIN` signer may create a child. Only the owner may bootstrap an unregistered root. Creating a child does not advance the root authorization epoch. ## Signed creation `buildCreateSubaccountTypedData` binds `rootOwner`, `authorizer`, the next `subaccountSeq`, current root `authNonce`, and `deadline`. The owner or authorized root signer signs; there is no child consent signature. Submit with `createSubaccountBySig`. Read the next sequence and epoch before signing. Two requests for the same sequence compete, so rebuild the losing request after one succeeds. The sequence is a `uint16`; a root supports at most 65,535 children. IDs and sequences are never reused. The domain is `KuruAccountCore`, version `1`, chain ID, and AccountCore proxy address. EOA and ERC-1271 authorizers are supported by the contract. ## Funding and withdrawals Deposit into the root, then use `transferBetweenAccounts` with numeric source and destination IDs. Transfer child proceeds back to the root before withdrawing externally. Orders and positions remain attached to their original ID. All children inherit the root's signers and fee policy. For exact signatures, see [AccountCore](/contracts/account-core). # SDK Swaps Source: https://docs.kuru.io/sdk/swaps Estimate and execute exact-input Spot swaps with explicit slippage protection. ```typescript theme={null} import { abi } from "@toxicflow-labs/ts-sdk"; import { formatUnits, parseUnits } from "viem"; const quoteDecimals = await publicClient.readContract({ address: quoteToken, abi: abi.erc20MetadataAbi, functionName: "decimals" }); const amountIn = parseUnits("10", quoteDecimals); const quote = await publicClient.readContract({ address: market, abi: abi.orderBookAbi, functionName: "estimateSwap", args: [Number(userId), true, amountIn], }); const minAmountOut = quote.amountOut * 995n / 1000n; if (minAmountOut === 0n) throw new Error("No usable nonzero output quote"); await kuru.spot.swap({ market, userId, isBuy: true, amountIn, minAmountOut, deadline: BigInt(Math.floor(Date.now() / 1000) + 60) }); ``` For buys, parse `amountIn` with the quote token's decimals. For sells, use the base token's decimals. The estimate returns `amountInUsed` and `amountOut` in token atoms. The SDK swap write returns a transaction hash, not that result struct. Await a successful receipt and read `SpotSwap` or the resulting balances for actual amounts. Format token amounts with `formatUnits` and the corresponding token decimals. The typed ABI read above avoids the SDK 0.2.0 estimate helper’s `unknown` return type. `userId` is a uint40, so conversion to a JavaScript number is exact once its range has been validated. Estimation uses current chain state but cannot predict stateful post-fill-hook output or later state changes. Always use a deadline and nonzero slippage bound appropriate to the application. # Trading-wallet Signing Source: https://docs.kuru.io/sdk/trading-wallet Sign version-2 intents for a delegated trading EOA. KuruTradingWallet is EIP-7702 logic used by a secondary EOA. The EOA signs actions; a relayer submits them; AccountCore checks the EOA's live root-wide permission over the target account. ## Domains and identity | Signature | Domain name | Version | Verifying contract | | - | - | - | - | | Trading action, trigger, TWAP, signed data | `KuruTradingWallet` | `2` | Delegated EOA address | | AccountCore grant, revocation, child creation, approved withdrawal | `KuruAccountCore` | `1` | AccountCore proxy | Use SDK typed-data builders rather than hand-maintaining type hashes. Wallet v2 uses fresh storage and chain-local state. Old wallet signatures and storage are not migrated into this model. ## Immediate actions The header binds the actual target account ID, market, root authorization epoch, millisecond nonce, deadline, and correlation ID. Read `getAccountAuthorizationEpoch({ accountId })` before signing. Allocate nonces durably per delegated EOA and chain; see [Signer Lifecycle](/sdk/signer-lifecycle). SDK intent helpers include `signBatchIntent` and `signReplaceBySlotIntent`. For additional actions, use `prepareCancelOrdersByIdIntent`, `prepareCancelAllIntent`, or `prepareFokSwapIntent`, then `signPreparedWalletIntent` and `buildWalletActionRequest`. Verify market precision, notional constraints, permissions, and live order bindings before signing. Cancel-by-ID accepts 1–62 unique live order IDs and reverts the complete action on a stale or invalid target. Cancel-all operates on the target account's live orders in that market at execution time, including orders placed after signing. It does not cancel triggers, TWAP schedules, or passive positions. Despite its name, the wallet FOK swap is a base-quantity marketable limit order, not the OrderBook exact-input swap. Dust rules still apply. Reconcile actual packed fills. ## Triggers > [!WARNING] > > Automated triggers, including TP/SL, are **not implemented** as a live feature and remain work in progress. Contract-level storage and execution rules below do not imply that a condition-monitoring keeper is deployed. Trigger creation authenticates the signature once. Firing checks keeper authority, live trading permission, unchanged root epoch, expiry, verified market, and applicable order bindings. The creation signature is not recovered again at firing. The opt-in Relay [FOK trigger creation route](/api/relay/reference/create-fok-swap-trigger) only stores the signed instruction and condition hash. It does **not** monitor the condition or register a keeper; retain the condition bytes for your own integration. `getTrigger` contains execution state. The creation nonce, deadline, and condition commitment are available from calldata/events rather than retained as getter fields. Any future automated execution would require an offchain keeper to evaluate the condition; the Relay storage route does not supply one. ## TWAP > [!WARNING] > > Automated TWAP slice execution is **not implemented** and remains work in progress. A stored schedule does not execute trades on its own. A signed schedule binds total quantity, limit price, future start, interval, and slice count. Quantity must divide into equal slices. Each interval permits its corresponding FOK slice. No catch-up or rollover occurs; a reverted attempt may be retried in the same interval. Creating a schedule reserves no funds. The opt-in Relay [TWAP creation route](/api/relay/reference/create-twap) only stores the schedule; it does **not** run slices. Its [finalization route](/api/relay/reference/finalize-twap) records expired/skipped/finished state without executing trades or transferring funds. Contract capabilities and a stored schedule do not imply a deployed scheduler. ## Signed data `emitSignedData` publishes opaque, public bytes authenticated by the delegated wallet, such as a display label. Its sequential `signedDataNonce` is separate from trading, trigger, and TWAP nonces. This event neither grants permissions nor proves current account access. The [contract reference](/contracts/trading-wallet) contains the precise execution rules. The [Relay guide](/sdk/relay) identifies the available transport methods; contract support alone does not imply a hosted endpoint.