Skip to Content
Symmio Trading-SDK — the SDK surface for builders on Arbitrum
ReactAccountLayer hooks

AccountLayer hooks

React-query wrappers over @symmio/trading-core’s AccountLayer slice.

The page is split into two groups:

  • Reads — TanStack useQuery-shaped hooks. Same call = same cached result. Refetch on invalidation.
  • Writes — TanStack useMutation-shaped hooks. Trigger mutate / mutateAsync, watch isPending / data / error, and let the hook invalidate the affected reads for you.

Every write also has a paired useSimulateXyz — see Simulate then write.

Account timelock hooks are documented in Account timelocks.

Reads

useUserSubAccounts

Read a user’s subaccounts. Returns react-query’s full UseQueryResult shape.

import { useUserSubAccounts, useWalletAccount } from "@symmio/trading-react"; const { address } = useWalletAccount(); const { data, isLoading, error, refetch } = useUserSubAccounts({ user: address }); if (!address) return <p>Connect a wallet.</p>; if (isLoading) return <Spinner />; if (error) return <ErrorView kind={error.kind} message={error.message} />; return ( <ul> {data?.map((sub) => ( <li key={sub.accountAddress}>{sub.name}</li> ))} </ul> );

Parameters

NameTypeDefaultNotes
userAddress?undefinedEOA whose subaccounts to fetch. The query is disabled while this is undefined, so you can pass the connected address without a manual enabled guard.
offsetbigint?0nPagination offset.
limitbigint?200nPagination cap.
chainIdnumber?config defaultOptional chain override.
queryobject?undefinedTanStack Query overrides, including enabled.

Return type

UseQueryResult<readonly SubAccountDetail[], SymmioRequestError> — every field react-query exposes, with the SDK error type.

useAccountBalanceOf

Read the account’s available balance — deposited collateral idle on the account. For the instant (lowcap) flow this is the trading balance: deposits credit it, instant opens spend it, and withdrawals draw from it. Under the hood: balanceOf(account) on the SYMMIO diamond. See Balance Model.

import { formatEther } from "viem"; import { useAccountBalanceOf } from "@symmio/trading-react"; const { data, isLoading, error } = useAccountBalanceOf({ account }); if (isLoading) return <Spinner />; if (error) return <ErrorView kind={error.kind} message={error.message} />; return <span>{data === undefined ? "-" : formatEther(data)}</span>;

Parameters

NameTypeDefaultNotes
accountAddress?undefinedAccount address passed to balanceOf. The query is disabled while undefined.
chainIdnumber?config defaultOptional chain override.
queryobject?undefinedTanStack Query overrides.
configConfig?provider valueOptional config override.
liveboolean?falseSubscribe to the account’s on-chain settle notifications and refetch on each open/close settle (a shared WebSocket; requires the provider tree).

Return type

UseQueryResult<bigint, SymmioRequestError>.

The value is in the protocol’s 18-decimal internal units (not the collateral token’s decimals) — use formatEther / formatUnits(value, 18) to display.

useAccountBalanceInfo

Read the account’s classic-pool (allocated) balance info — collateral allocated to this account, plus the CVA / LF / margin locks currently held against it. Instant opens do not spend this pool — the instant flow trades from the available balance (useAccountBalanceOf); see Balance Model. Under the hood: balanceInfoOfPartyA(account) on the SYMMIO diamond.

import { formatEther } from "viem"; import { useAccountBalanceInfo } from "@symmio/trading-react"; const { data } = useAccountBalanceInfo({ account }); return <span>{data ? formatEther(data.allocatedBalance) : "-"}</span>;

Parameters

NameTypeDefaultNotes
accountAddress?undefinedAccount address passed as PartyA to balanceInfoOfPartyA. The query is disabled while undefined.
chainIdnumber?config defaultOptional chain override.
queryobject?undefinedTanStack Query overrides.
configConfig?provider valueOptional config override.
liveboolean?falseSame as useAccountBalanceOf, and it also refetches on any frame whose vaAddress equals account (the account’s Virtual Account just settled).

Return type

UseQueryResult<AccountBalanceInfo, SymmioRequestError>.

interface AccountBalanceInfo { allocatedBalance: bigint; lockedCVA: bigint; lockedLF: bigint; lockedPartyAMM: bigint; lockedPartyBMM: bigint; pendingLockedCVA: bigint; pendingLockedLF: bigint; pendingLockedPartyAMM: bigint; pendingLockedPartyBMM: bigint; }

All fields are in the protocol’s 18-decimal internal units (not the collateral token’s decimals).

usePredictedNextVirtualAccount

Predict the deterministic address of the Virtual Account (VA) a SubAccount will create for its next (isolationType, symbolId) position — before the trade lands on-chain and the VA exists. In lowcap, an instant open isolates each position into its own VA; the AccountLayer derives that address up front, so you can sign against it early. The main use: attaching TP/SL in the same flow as an instant open (the TP/SL order must be signed against the VA, not the SubAccount). Pair the side with isolationTypeForSide(positionType) to pick the isolation type.

import { isolationTypeForSide, PositionType, usePredictedNextVirtualAccount } from "@symmio/trading-react"; const positionType = side === "long" ? PositionType.LONG : PositionType.SHORT; const { data: predictedVa } = usePredictedNextVirtualAccount({ subAccount, isolationType: isolationTypeForSide(positionType), // MARKET_LONG / MARKET_SHORT symbolId: BigInt(market.symbol_id), }); // predictedVa → pass as `virtualAccount` to a TP/SL attached at open.

Parameters

NameTypeDefaultNotes
subAccountAddress?undefinedThe SubAccount that will open the position.
isolationTypeVirtualAccountIsolationType?undefinedIsolation bucket for the VA — use isolationTypeForSide(positionType).
symbolIdbigint?undefinedSolver market id of the position.
chainIdnumber?config defaultOptional chain override.
queryobject?undefinedTanStack Query overrides.
configConfig?provider valueOptional config override.

The query is disabled until subAccount, isolationType, and symbolId are all set. The prediction is stable per (subAccount, isolationType, symbolId) only until the SubAccount’s virtual nonce advances (i.e. it opens that isolation), so a short staleTime applies — override via query.staleTime.

Return type

UseQueryResult<Address, SymmioRequestError> — the predicted VA address.

Virtual-account reads

In lowcap trading every isolated position lives in its own Virtual Account (VA), the on-chain partyA of its quotes. These hooks read a subaccount’s VAs. Each is disabled until its required inputs are set, chainId defaults to the connected chain, and errors are normalized to SymmioRequestError. Pass chainId explicitly in an app whose wallet may sit on another chain.

HookReadsDisabled until
useVirtualAccountsOfSubAccountThe VAs with their market, parent and isolation type — getVirtualAccountsOfSubAccountsubAccount
useVirtualAccountsAddressesOfSubAccountThe VA addresses — getVirtualAccountsAddressesOfSubAccountsubAccount
useVirtualAccountsCountOfSubAccountHow many VAs, to page past 200 — getVirtualAccountsCountOfSubAccountsubAccount
useVirtualAccountOne VA’s detail, cached indefinitely — getVirtualAccountaccount
useActiveVirtualAccountByKeyThe VA active for a market and side, or null — getActiveVirtualAccountByKeysubAccount, isolationType, symbolId
useSubAccountVirtualNonceThe nonce the next VA derives from — getSubAccountVirtualNoncesubAccount
import { useVirtualAccountsOfSubAccount, VIRTUAL_ACCOUNT_ISOLATION_TYPE } from "@symmio/trading-react"; const { data: vas } = useVirtualAccountsOfSubAccount({ subAccount, chainId }); const longs = vas?.filter((va) => va.isolationType === VIRTUAL_ACCOUNT_ISOLATION_TYPE.MARKET_LONG);

Each returns react-query’s UseQueryResult with the core action’s return type. Pagination (offset, limit) and TanStack query overrides pass through.

Writes

useAllocate and useDeallocate are relayable: pass gasless: true in the mutation variables to sign the write as an InstantLayer operation and let the relayer pay the gas. useEditAccountName is not — it always takes the wallet path. See Gasless hooks.

Every hook below returns react-query’s UseMutationResult — call mutate(inputs) (or mutateAsync), watch isPending / data / error, and the hook invalidates the reads it affected on your behalf.

Building the instant (lowcap) flow? You need neither useAllocate nor useDeallocate. Instant trading spends the available balance; allocating moves funds into the classic pool and reduces what an instant open can use. Fund with useDeposit, exit with the withdraw hooks. See Balance Model.

useAllocate

Allocate a subaccount’s available balance into its allocated (tradeable) balance. The call inputs (account, amount) are passed to mutate; amount is in 18 decimals.

import { useAllocate } from "@symmio/trading-react"; const { mutate, isPending, isSuccess, data, error } = useAllocate(); <button onClick={() => mutate({ account: "0xsub...", amount: 1_000000000000000000n })} disabled={isPending}> {isPending ? "Sending…" : "Allocate"} </button>; { isSuccess && <p>tx: {data.hash}</p>; }

Options

interface UseAllocateParameters { waitForReceipt?: boolean; // default true — mutation resolves only after the receipt is mined confirmations?: number; // default 1 }

Cache invalidation

On success, the hook invalidates the subaccount’s useAccountBalanceInfo and useAccountBalanceOf queries in the active QueryClient, so allocated and available balances rerender automatically.

Dry run

useSimulateAllocate() runs the same call through simulateContract without sending — useful to surface a would-be revert before prompting the wallet.

useDeallocate

Deallocate a subaccount’s allocated (tradeable) balance back into its available balance — the reverse of useAllocate. The hook fetches a fresh Muon uPnL signature automatically before submitting (the contract requires it to prove the subaccount stays solvent), unless you pass one as upnlSig. amount is in 18 decimals.

import { useDeallocate } from "@symmio/trading-react"; const { mutate, isPending, isSuccess, data, error } = useDeallocate(); <button onClick={() => mutate({ account: "0xsub...", amount: 1_000000000000000000n })} disabled={isPending}> {isPending ? "Sending…" : "Deallocate"} </button>; { isSuccess && <p>tx: {data.hash}</p>; }

Options

interface UseDeallocateParameters { waitForReceipt?: boolean; // default true — mutation resolves only after the receipt is mined confirmations?: number; // default 1 }

Cache invalidation

On success, the hook invalidates the subaccount’s useAccountBalanceInfo and useAccountBalanceOf queries in the active QueryClient, so allocated and available balances rerender automatically.

Muon signature & cooldown

The hook calls getDeallocateUpnlSig for you unless you pass a upnlSig variable. Deallocate is subject to the on-chain debounce — it reverts until the account’s useWithdrawCooldownOf timestamp plus useDeallocateDebounceTime has passed — and the result must keep the subaccount solvent; both surface as a normalized SymmioRequestError. useSimulateDeallocate() dry-runs the call (supply a upnlSig there — it does not auto-fetch).

useEditAccountName

Submit a rename transaction.

import { useEditAccountName } from "@symmio/trading-react"; const { mutate, isPending, isSuccess, data, error } = useEditAccountName(); <button onClick={() => mutate({ account: "0xsub...", name: "Trading bot" })} disabled={isPending}> {isPending ? "Sending…" : "Rename"} </button>; { isSuccess && <p>tx: {data.hash}</p>; } { error?.kind === "user-rejected" ? null : error && <p>{error.message}</p>; }

Options

interface UseEditAccountNameOptions { waitForReceipt?: boolean; // default true — mutation resolves only after the receipt is mined confirmations?: number; // default 1 }

Cache invalidation

On success, the hook invalidates every cached useUserSubAccounts query in the active QueryClient, so mounted lists rerender with the new name automatically. No manual invalidation needed.

Why this hook needs a connected wallet

The hook reads useSymmioWalletClient() under the hood. If the user is disconnected or on the wrong chain, calling mutate throws a SymmioRequestError with kind: "sdk" before any contract call is made. UIs typically gate the button on useWalletAccount().isOnExpectedChain to avoid the error path entirely.

Account timelocks

For protected writes, pass the optional timelock mutation variable to useAllocate, useDeallocate, useAddMargin, useRemoveMargin, or useDeleteSubAccount. When omitted, the automatic route may discover and authorize a protected write; pass automaticTimelock: false to the hook to retain the ordinary write route. useProtectedCall executes one raw Core or AccountLayer call; useTimelockApprovalProvider creates the standard HTTP provider for the selected solver, and useTimelockSelector looks up an SDK policy selector by function name. useScheduledCallMatch checks that a single scheduled raw call matches its execution payload. See the execution reference for one-attempt authorization, receipt recovery and Muon-signature handling.

useProtectedFunction executes any of the 22 named functions with ABI-typed arguments and explicit timelock authorization. useProtectedFunctionCatalog provides their target and ABI inputs to build an inspector. Successful receipts refresh the affected reads; approval requests are never automatically retried. useProtectedFunctionEncoder exposes the same pure encoder for preflight validation before the app creates an attempt or shows a wallet prompt.

useExecuteAccountCalls executes named Core calls atomically and accepts the optional per-call batch timelock authorization. It waits for a receipt by default, does not retry automatically and refreshes affected reads only after confirmation.

The React package exposes the same provider-neutral timelock flow as core:

HookPurpose
useSelectorTimelockRead the unlocker and delay configured for one root-account selector.
useSetupTimelocksConfigure or update selector policy on the root account.
useClearTimelocksRemove selector policies from the root account.
useRequestTimelockApprovalSign and send exactly one approval request; automatic retries are disabled.
useScheduleTimelockOpSchedule exact raw operation calldata for delayed fallback execution.
useTimelockScheduleStateRead the derived readyAt and expiresAt execution window.
useCancelTimelockOpCancel a pending fallback schedule.
useExecuteTimelockOpExecute wrapped AccountLayer calldata with signed approvals or a mature schedule.
useTimelockPolicyResolve root/VA and read all 22 selector statuses in one pass.
useTimelockRouteSelect normal, approval or delayed handling for one operation using solver configuration and on-chain policy.
useAutomaticTimelockRecoveryObserve and acknowledge a reconciled automatic operation on a root account.
useTimelockedCoreCallEncoderReturn the Core-call wrapper encoder for exact delayed execution calldata.
useSetupTimelockPolicyConfigure with safe defaults; return confirmed receipt and separate indexing status.
useEarlyWithdrawObtain one approval and execute an owner-wallet withdrawal; preserve recovery data on error.

Automatic route selection

The standard protected write hooks automatically inspect the selected deployment and selector before issuing an approval. Existing explicit timelock mutation inputs always take precedence. On chains or solvers explicitly configured without support, the previous plain write path is preserved. If solver discovery fails, an on-chain selector read can still establish that the operation is unlocked; if it cannot, the hook returns an error rather than assuming a plain write is safe. For app-owned routing, pass automaticTimelock: false in the hook options. Integrations with another provider can pass { capability, provider, deadline?, onApproval? } instead; keep the provider object stable during the operation and persist approvals in onApproval when recovery must survive reload.

After positive solver discovery, React retains its validated capability for the QueryClient lifetime, scoped to the chain, AccountLayer and solver deployment. Each new operation still checks the current account policy and requests its own approval when needed. A failed or incomplete /info refresh does not silently downgrade known support; replacing or clearing the QueryClient starts discovery again. After a standard approval transport reports an unavailable service, React performs one background /info read without retrying the approval request; an ambiguous approval still requires reconciliation.

For multi-call writes, each protected inner call receives a distinct authorization. Automatic handling does not schedule a delayed operation or retry an ambiguous approval request; use the explicit scheduling hooks after reconciling any earlier attempt. The default request deadline is five minutes after the current chain block time.

Automatic hooks coordinate attempts for the same root account within their shared QueryClient. After an uncertain result, useAutomaticTimelockRecovery({ rootAccount, chainId }) exposes status: "reconciliation"; call clearAfterReconciliation() only after independently determining the outcome. A pending operation cannot be cleared. A confirmed receipt releases the attempt automatically; a broadcast-only result requires reconciliation. This state is in memory and is not shared across browser tabs or reloads. Applications must maintain a durable journal and cross-tab lock when those guarantees are required, including while switching to app-owned routing.

The React entry point also re-exports getTimelockRecoveryTransactionHash, hasTimelockSubmissionEvidence, isDefiniteGaslessSimulationRejection, isDefiniteTimelockApprovalRejection, and isUnsubmittedTimelockWalletRejection for application recovery glue. These are the same pure classifiers documented in the Core errors and recovery reference; they do not submit, retry, or mutate React state.

For fee allowance operations, OPERATIONAL_FEE_LIST_PRICE_MULTIPLIER is also available from the React package; its value comes from core.

useTimelockRoute({ account, selector, chainId, solverId }) checks the solver’s timelockApproval capability and the selected root-account policy. Pass enabled: false to skip discovery and policy reads. An explicit disabled capability retains the normal route. When the setting is unspecified, the hook discovers Enigma support from /info or accepts supplied provider metadata. If support is still unknown and discovery fails, it returns error instead of assuming the normal route. A protected selector with a matching online provider returns approval; an unavailable /info before a request returns delayed when support is already known; inconsistent metadata or a failed chain read returns error. A provider other than Enigma may supply capability and provider explicitly.

Call run with a normal write callback and a protected write callback. For approval, supply the request deadline and onApproval to persist the issued approval. A delayed result is not a completed write: ask the user to schedule the exact raw calldata with useScheduleTimelockOp, track useTimelockScheduleState, then execute or cancel with the corresponding hooks. Never reuse calldata containing a short-lived signature after it expires.

The hook prevents another attempt within the mounted instance after an ambiguous protected outcome; it does not persist state, coordinate tabs, or reconcile past attempts. The application must persist the approval and transaction recovery context before submission and restore it after reload. Call clearReconciledAttempt() only after the earlier operation is independently reconciled. Approval rejections and ambiguous submissions do not automatically start a schedule.

High-level hooks

import { useTimelockPolicy, useSetupTimelockPolicy, useEarlyWithdraw } from "@symmio/trading-react"; const policy = useTimelockPolicy({ account, chainId }); const setup = useSetupTimelockPolicy(); const withdrawal = useEarlyWithdraw(); async function configure() { const result = await setup.mutateAsync({ account, chainId, indexer }); // Confirmation is not indexing: wait unless policy.ready && indexing === "indexed". return result; } async function withdraw() { return withdrawal.mutateAsync({ account, chainId, withdrawal: { method: "withdraw", amount }, deadline, onApproval: persistApproval, }); }
HookInputs / mutation variablesResult
useTimelockPolicyUseTimelockPolicyParameters = core GetTimelockPolicyOptions plus optional config.UseQueryResult<TimelockPolicyReport, SymmioRequestError>.
useSetupTimelockPolicyOptional ConfigParameter; mutate with SetupTimelockPolicyParameters.UseMutationResult<TimelockSetupResult, SymmioRequestError, SetupTimelockPolicyParameters>. Always confirms setup.
useEarlyWithdrawOptional WriteParameters (config, receipt controls); mutate with EarlyWithdrawParameters.UseMutationResult<EarlyWithdrawWriteResult, SymmioRequestError, EarlyWithdrawParameters>.

EarlyWithdrawWriteResult combines core EarlyWithdrawResult with WriteResult (receipt and optional gasless recovery handle). The default waits for the receipt; waitForReceipt: false returns a submission and does not invalidate caches as confirmed. All timelock writes disable automatic retries even when the application sets a global mutation retry default. A confirmation error retains the approval and hash in error.cause (EarlyWithdrawExecutionError); do not repeat issuance. The error keeps the underlying kind and code: relay failures remain api, and mined reverts remain TransactionRevertedError with kind: "contract-revert", code: "TRANSACTION_REVERTED", hash and receipt. Wallet rejection remains user-rejected; an unclassified timeout remains unknown. Recovery context stays in cause without replacing the failure classification.

See core policy for indexing semantics and core withdrawal for parameter descriptions.

Low-level hooks

accountLayerAbi is also available from @symmio/trading-react when a React consumer needs to encode or decode an AccountLayer operation. It is the same version-pinned ABI exported by core; it does not query or verify a deployment.

import { accountLayerAbi } from "@symmio/trading-react"; import { encodeFunctionData } from "viem"; const clearCallData = encodeFunctionData({ abi: accountLayerAbi, functionName: "clearTimelocks", args: [rootAccount, [selector]], });

useSelectorTimelock(UseSelectorTimelockParameters) returns UseQueryResult<SelectorTimelock, SymmioRequestError>; inputs are core selector query options plus optional config. useTimelockScheduleState(UseTimelockScheduleStateParameters) likewise accepts core schedule query options plus config and returns UseQueryResult<TimelockScheduleState, SymmioRequestError>.

The five low-level write hooks (useSetupTimelocks, useClearTimelocks, useScheduleTimelockOp, useCancelTimelockOp, useExecuteTimelockOp) accept optional WriteParameters and return a mutation of WriteResult with the corresponding core action’s parameter type. useRequestTimelockApproval instead accepts optional ConfigParameter, mutates with RequestTimelockApprovalParameters, and returns ValidatedTimelockApproval, not a receipt. Every error is normalized to SymmioRequestError.

import { useExecuteTimelockOp, useRequestTimelockApproval, useTimelockScheduleState } from "@symmio/trading-react"; import { encodeTimelockedCoreCall } from "@symmio/trading-core"; const approval = useRequestTimelockApproval(); const execute = useExecuteTimelockOp(); const schedule = useTimelockScheduleState({ account: rootAccount, callData: rawCoreCallData, }); async function executeApproved() { const result = await approval.mutateAsync({ provider, capability, account, rootAccount, callData: rawCoreCallData, deadline: requestDeadline, }); await execute.mutateAsync({ account: rootAccount, innerCallData: encodeTimelockedCoreCall(account, rawCoreCallData), approvals: [result.signedApproval], gasless: true, }); }

The read hooks require their identifying inputs instead of silently disabling on missing values. After a confirmed write, the mutation hooks invalidate the affected policy or schedule reads. Confirmed execution refreshes balances and the inner operation’s affected reads, using the same domain rules as gasless batches. For example, a wrapped withdrawal refreshes withdrawal reads, while deleteSubAccount refreshes account lists, addresses, counts, and account details. Other deployment caches are unchanged. A rejected, reverted, or unconfirmed execution does not trigger these refreshes.

Deleting a timelocked sub-account

Use the existing approval and execution hooks for a protected deletion. Encode deleteSubAccount(subAccount) with accountLayerAbi; send that raw calldata to useRequestTimelockApproval, then pass it unchanged as innerCallData to useExecuteTimelockOp with the returned signed approval. This is an AccountLayer call, so do not wrap it in _call. Use the root account for approval and execution authority. A previously scheduled deletion can instead execute with empty approvals once its delay has matured and before its grace period expires.

These hooks do not choose a fallback or request a second approval automatically. Normal deletion restrictions still apply; a timelock approval does not bypass balance, position, ownership, or virtual-account checks. The execution action simulates the full wrapper by default before wallet submission; relay submission continues to use the shared gasless pipeline. Only a successful receipt means the deletion completed. The unwrapped useDeleteSubAccount hook remains unchanged; it does not acquire timelock approvals on the caller’s behalf.

The approval hook never retries the provider POST. Treat a timeout as ambiguous unless the provider offers an explicit reconciliation mechanism. See the full core workflow for root-versus-VA handling, fallback scheduling, independent Core cooldown, and gasless delegation.

If a decoded contract revert reports TimelockOpNotApprovedOrScheduled, React normalizes it to a contract-revert with code TIMELOCK_REQUIRED, preserving the original error as its cause. Other contract reverts retain their existing classification.

Account creation: recovery and cache ownership

To make a relayed creation recoverable, pass gasless.idempotencyKey in the mutation variables — one key per user action, saved before calling — and call the mutation again with the same key after an unknown outcome. The hook forwards the key unchanged; your app keeps the pending record. See Recovering gasless writes.

On success, all owner variants of account-list, address-list and account-count queries are invalidated. The signing identity may be a session key or a host embedded wallet, so invalidation must not assume wagmi’s connected address owns the new account. Application-specific balance caches remain the host’s responsibility.

Last updated on