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

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

> **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.md).

## 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.md) for a complete example.

### Spot reads

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

> **bestBidAsk(\{ market })**
>
> Read best stored bid and ask.
>
> Returns `[bid, ask]` as numbers. Empty bid is `0xffff_ffff`; empty ask is `0`.

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

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

> **getOrderMinSizeAfterBlock(\{ market, userId, slotIdx })**
>
> Read a slot's RAB block threshold.
>
> Returns `0` when disabled or empty.

> **getPassiveBand(\{ market, lowPrice })**
>
> Read aggregate passive band state.
>
> Returns inventory, shares, band edges, and fee-growth accumulators.

> **getPassivePosition(\{ market, positionId })**
>
> Read a passive position.
>
> Returns owner ID, band edges, shares, and fee checkpoints.

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

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

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

> **cancelAllOrders(\{ market, userId\[, account, simulate] })**
>
> Cancel all active slots in one market.
>
> Passive positions are unaffected.

> **protocolCancelBySlots(...)**
>
> Build or submit the protocol-restricted cancellation path.
>
> This export exists for authorized protocol operators. Ordinary applications
> should use `cancelBySlots`.

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

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

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

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

> **prepareCancelTriggerIntent(input)**
>
> Prepare an unordered-nonce trigger cancellation.
>
> Binds wallet, chain, account ID, auth epoch, nonce, deadline, and trigger ID.

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

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

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

> **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.md) for the signing-to-submission flow and [Relay API documentation](/api/relay/rest.md) for canonical service endpoints and wire schemas.

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

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

> **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`.

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

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

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

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

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


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