> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kuru.io/llms.txt
> Use this file to discover all available pages before exploring further.

# 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

<AccordionGroup>
  <Accordion title="createKuruClient(config)" description="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>

  <Accordion title="createAccountClient(config) / createSpotClient(config)" description="Construct only one focused client.">
    They accept the same shared config and return the same method objects exposed under `createKuruClient`.
  </Accordion>
</AccordionGroup>

## 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

<AccordionGroup>
  <Accordion title="getMarketParams({ market })" description="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>

  <Accordion title="bestBidAsk({ market })" description="Read best stored bid and ask.">
    Returns `[bid, ask]` as numbers. Empty bid is `0xffff_ffff`; empty ask is `0`.
  </Accordion>

  <Accordion title="getL2Book({ market, levels })" description="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>

  <Accordion title="getOrderId({ market, userId, slotIdx })" description="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>

  <Accordion title="getOrderMinSizeAfterBlock({ market, userId, slotIdx })" description="Read a slot's RAB block threshold.">
    Returns `0` when disabled or empty.
  </Accordion>

  <Accordion title="getPassiveBand({ market, lowPrice })" description="Read aggregate passive band state.">
    Returns inventory, shares, band edges, and fee-growth accumulators.
  </Accordion>

  <Accordion title="getPassivePosition({ market, positionId })" description="Read a passive position.">
    Returns owner ID, band edges, shares, and fee checkpoints.
  </Accordion>

  <Accordion title="estimateSwap({ market, userId?, isBuy, amountIn, builderFeePps? })" description="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.
  </Accordion>
</AccordionGroup>

### Orders and swaps

<AccordionGroup>
  <Accordion title="batch({ market, userId, orders, cancelSlotIdxs?, clientOrderId?, builderConfig?[, account, simulate] })" description="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>

  <Accordion title="cancelBySlots({ market, userId, cancelSlotIdxs, clientOrderId?[, account, simulate] })" description="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>

  <Accordion title="cancelAllOrders({ market, userId[, account, simulate] })" description="Cancel all active slots in one market.">
    Passive positions are unaffected.
  </Accordion>

  <Accordion title="protocolCancelBySlots(...)" description="Build or submit the protocol-restricted cancellation path.">
    This export exists for authorized protocol operators. Ordinary applications
    should use `cancelBySlots`.
  </Accordion>

  <Accordion title="replaceBySlotPacked({ market, userId, packedOps, clientOrderId?, builderConfig?[, account, simulate] })" description="Apply packed slot operations.">
    Construct `packedOps` with `encodePackedReplaceOp(s)` and
    `encodePackedCancelOp`; do not hand-build bit layouts in application code.
  </Accordion>

  <Accordion title="swap({ market, userId, isBuy, amountIn, minAmountOut, deadline, builderConfig?[, account, simulate] })" description="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.
  </Accordion>
</AccordionGroup>

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.

<AccordionGroup>
  <Accordion title="prepareReplaceBySlotIntent(input) / prepareBatchIntent(input)" description="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>

  <Accordion title="prepareCreateReplaceTriggerIntent(input) / prepareCreateBatchTriggerIntent(input)" description="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>

  <Accordion title="prepareCancelTriggerIntent(input)" description="Prepare an unordered-nonce trigger cancellation.">
    Binds wallet, chain, account ID, auth epoch, nonce, deadline, and trigger ID.
  </Accordion>

  <Accordion title="signReplaceBySlotIntent / signBatchIntent / signCreateReplaceTriggerIntent / signCreateBatchTriggerIntent / signCancelTriggerIntent" description="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>

  <Accordion title="createLocalAccountWalletIntentSigner(account) / createWalletClientIntentSigner(walletClient, account)" description="Adapt viem signers to WalletIntentSigner.">
    Use the local adapter for `LocalAccount`; use the wallet-client adapter for
    injected/JSON-RPC wallets.
  </Accordion>

  <Accordion title="signPreparedWalletIntent(intent, signer) / recoverWalletIntentSigner(typedData, signature)" description="Low-level signing and verification helpers.">
    Use these when storing prepared intent metadata before obtaining a signature.
  </Accordion>

  <Accordion title="signEip7702Authorization / hashEip7702Authorization / createLocalAccountAuthorizationSigner" description="Prepare EIP-7702 delegation authorization.">
    This surface handles delegation authorization only. Wallet intent signatures are separate EIP-712 messages.
  </Accordion>
</AccordionGroup>

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.

<AccordionGroup>
  <Accordion title="createKuruRelayClient(config)" description="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>

  <Accordion title="requestChallenge(wallet[, options]) / exchangeToken(challengeId, signature[, options]) / authenticate(options?)" description="Run challenge-based Relay authentication.">
    `authenticate` performs the full challenge, personal-message signature, token
    exchange, wallet-match validation, and optional token retention.
  </Accordion>

  <Accordion title="submit(request[, options])" description="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>

  <Accordion title="executeReplaceBySlot / executeBatch / createReplaceTrigger / createBatchTrigger / cancelTrigger / authorizeAccountSigner" description="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>

  <Accordion title="createRequestId / getAccessToken / setAccessToken / clearAccessToken" description="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.
  </Accordion>
</AccordionGroup>

Standalone builders mirror the high-level methods: `buildExecuteReplaceBySlotRelayRequest`, `buildExecuteBatchRelayRequest`, `buildCreateReplaceTriggerRelayRequest`, `buildCreateBatchTriggerRelayRequest`, `buildCancelTriggerRelayRequest`, and `buildAuthorizeAccountSignerRelayRequest`. Authentication adapters are `createLocalAccountRelaySigner`, `createWalletClientRelaySigner`, `resolveRelayAuthenticationWallet`, and `signRelayChallenge`.

## Events

<AccordionGroup>
  <Accordion title="decodeKuruEventLog(log[, abi])" description="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>

  <Accordion title="decodeTradesPacked(packedTrades)" description="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>

  <Accordion title="decodeBookUpdatesPacked(packedUpdates)" description="Decode concatenated 39-byte book records.">
    Returns complete live/deletion records including RAB threshold and maker-fee snapshot.
  </Accordion>
</AccordionGroup>

## 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.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.