Create a new PerpetualsAccount wrapper.
Raw account object with positions and equity data.
Account cap or partial vault cap object containing ownership and collateral metadata.
Optionalconfig: CallerConfig
Optional CallerConfig (network, auth, etc.).
Optionalapi: AftermathApi
Optional shared AftermathApi provider instance
used to derive serialized transaction kinds (txKind) from
Transaction objects.
ReadonlyaccountRaw account object with positions and equity data.
ReadonlyaccountAccount cap or partial vault cap object containing ownership and collateral metadata.
Optional ReadonlyapiOptional shared AftermathApi provider instance
used to derive serialized transaction kinds (txKind) from
Transaction objects.
The mutable configuration used for subsequent requests.
Get the account cap object ID, if this is a direct account.
Direct accounts are controlled via an on-chain “cap” object. Vault-backed accounts are controlled via vault caps and do not expose a direct account-cap ID.
ObjectId of the account cap.
Get the numeric perpetuals account ID.
This is the protocol-level identifier (bigint-derived) used across API calls.
PerpetualsAccountId for this account.
Get the underlying account object ID.
This is the on-chain object that holds the account's state and positions.
ObjectId of the account object.
Convenience accessor for the account's available collateral (in coin units).
This is the amount of collateral not currently locked/allocated across markets, as represented by the backend response.
Available collateral as a number.
Build an allocate-collateral transaction, moving collateral from this
account into a specific market (clearing house).
Works for both account-backed and vault-backed accounts.
Amount of collateral to allocate.
Market to allocate collateral to.
Optionalsponsor?: PerpetualsSponsorConfigOptionaltx?: TransactionOptional transaction to extend.
Transaction response containing a tx.
Build a cancel-and-place-orders transaction for this account.
Atomically cancels existing orders and places new ones in a single transaction. Useful for rebalancing order grids or replacing stale orders without intermediate exposure.
Transaction response containing tx.
Preview the effects of canceling orders across one or more markets.
This is commonly used to:
collateralChange values)If marketIdsToData is empty, this returns a trivial preview with:
marketIdsToData: {}OptionalabortSignal: AbortSignal
Optional AbortSignal to cancel the request.
Either:
{ marketIdsToData }, or{ error }.Build a cancel-orders transaction for this account.
Each market in marketIdsToData supplies:
orderIds: the orders to cancel in that marketcollateralChange: collateral adjustment to apply alongside cancellationleverage: leverage context used for estimating/validating constraints server-sideNotes:
Mapping from market IDs to cancel payloads.
Optionalsponsor?: PerpetualsSponsorConfigOptionaltx?: TransactionOptional transaction to extend.
Transaction response containing tx.
Build a cancel-stop-orders transaction for this account.
This cancels stop-order objects/tickets by their object IDs. These IDs are returned by stop-order query endpoints (see getStopOrderDatas).
Optionalsponsor?: PerpetualsSponsorConfigArray of stop-order ticket IDs to cancel.
Optionaltx?: TransactionOptional transaction to extend.
Transaction response containing tx.
Build a cancel-twap-orders transaction for this account.
This cancels TWAP order objects by their object IDs.
The input can include an existing transaction to extend and the TWAP order object IDs to cancel.
Transaction response containing tx.
Fetch paginated collateral-change history for this account, including deposits, withdrawals, funding settlements, liquidations, etc.
Pagination:
beforeTimestampCursor to fetch older entries.nextBeforeTimestampCursor to continue pagination.Optional cursor for pagination.
Optional limit per page.
ApiPerpetualsAccountCollateralHistoryResponse containing
an array of changes and a nextBeforeTimestampCursor.
Build a create-twap-orders transaction for this account.
Transaction response containing tx.
Build a deallocate-collateral transaction, moving collateral from a
specific market back to this account.
Works for both account-backed and vault-backed accounts.
Amount of collateral to deallocate.
Market to deallocate collateral from.
Optionalsponsor?: PerpetualsSponsorConfigOptionaltx?: TransactionOptional transaction to extend.
Transaction response containing a tx.
Build a deposit-collateral transaction for this account.
For non-vault accounts, this endpoint constructs a transaction that:
Note: Vault accounts are currently not supported and will throw.
OptionalisSponsoredTx?: booleanOptional flag indicating whether the transaction is gas-sponsored.
Optionalsponsor?: PerpetualsSponsorConfigOptionaltx?: TransactionOptional existing transaction to extend. If omitted, a new Transaction is created under the hood.
Amount of collateral to deposit, if paying directly from the wallet.
Transaction object argument referencing a
coin to deposit (mutually exclusive with depositAmount).
Transaction response containing a tx.
Preview the effects of allocating/deallocating collateral for the position in a given market.
Semantics:
collateralChange previews allocation (moving collateral into the market).collateralChange previews deallocation (moving collateral out of the market).The target collateral change (a positive number for allocating collateral, negative for deallocating collateral).
Market of whose position you want to allocate/deallocate collateral to/from.
OptionalabortSignal: AbortSignal
Optional AbortSignal to cancel the request.
Either:
{ updatedPosition, collateralChange }, or{ error }.Build an edit-stop-orders transaction for this account.
This endpoint lets you update existing stop orders in batch.
Notes:
Full updated stop-order payloads to apply.
Optional transaction to extend.
Optionaltx?: TransactionOptional transaction to extend.
Transaction response containing tx.
Build an edit-twap-orders transaction for this account.
newTwapOrders maps each TWAP order object id to the edit to apply.
The input maps each TWAP order ID to its edit and can include an existing transaction to extend.
Transaction response containing tx.
Build a transaction that grants an Agent Wallet (assistant permissions) for this perpetuals account.
The returned transaction must be signed and submitted by the account admin wallet.
After execution, recipientAddress can execute supported trading actions on behalf of this account.
Agent wallets can perform all supported actions except:
Wallet address to receive agent permissions.
Optionaltx?: TransactionOptional existing Transaction to append to. If omitted, a new Transaction is used.
Fetch historical margin snapshots for this account over a time range.
This endpoint returns time-series margin data suitable for charting UI such as equity and available collateral over time.
Notes:
ApiPerpetualsAccountMarginHistoryBody without accountId.
ApiPerpetualsAccountMarginHistoryResponse containing marginHistoryDatas.
Fetch paginated order history for this account.
This endpoint is distinct from getOrderDatas:
getOrderDatas resolves current/pending orders based on the snapshot.getOrderHistory returns historical order events (fills, cancels, etc.)
over time with cursor-based pagination.Optional cursor for pagination.
Optional limit per page.
ApiPerpetualsAccountOrderHistoryResponse containing a list of
orders and a nextBeforeTimestampCursor.
Preview the effects of placing a limit order (without building a tx).
The preview simulates:
OptionalabortSignal: AbortSignal
Optional AbortSignal to cancel the request.
Either an error message or a preview object similar to getPlaceMarketOrderPreview.
Build a place-limit-order transaction for this account.
Similar to getPlaceMarketOrderTx, but uses limit order semantics:
price and orderType.Notes:
hasPosition is derived from local account state; refresh the account if needed.Transaction response containing tx.
Preview the effects of placing a market order (without building a tx).
This is a read-only API call that runs the protocol’s pricing / margin / slippage logic against the current market state and your account/vault context.
OptionalabortSignal: AbortSignal
Optional AbortSignal to cancel the request.
Either an error message or a preview including:
updatedPositionpriceSlippage, percentSlippagefilledSize, filledSizeUsdpostedSize, postedSizeUsdcollateralChangeexecutionPriceBuild a place-market-order transaction for this account.
This is the primary entrypoint for opening/closing positions via market orders. It automatically:
hasPosition based on the current account state for the given market.slTp input.Important behavioral notes:
hasPosition is derived from the local PerpetualsAccountObject snapshot.
If the snapshot is stale, consider re-fetching the account first./perpetuals/vault/... and uses
vaultId as the identity discriminator. For direct accounts, it uses accountId.See SdkPerpetualsPlaceMarketOrderInputs for details. Notably:
marketId, side, size, collateralChange, reduceOnlyleverageslTp paramstx to extendTransaction response containing tx.
Preview the effects of placing a scale order (without building a tx).
A scale order distributes total size across multiple limit orders spaced between a start and end price. The preview simulates:
OptionalabortSignal: AbortSignal
Optional AbortSignal to cancel the request.
Either an error message or a preview object similar to getPlaceMarketOrderPreview.
Build a place-scale-order transaction for this account.
A scale order distributes a total size across multiple limit orders
evenly spaced between a start and end price. An optional sizeSkew
parameter controls whether the distribution is uniform or weighted.
Transaction response containing tx.
Build a place-sl-tp-orders transaction for this account.
This helper constructs SL/TP stop orders for an existing position
in a given market. If the account has no position for marketId, this
throws an error.
Implementation details:
positionSide for the API so SL/TP orders are bound to closing logic
(i.e. they should trigger on the opposite side of the open position).Transaction response containing tx.
Build a place-stop-orders transaction for this account.
This allows placing one or more stop orders in a single transaction, optionally with a dedicated gas coin and a sponsored gas flag.
Typical usage:
Transaction response containing tx.
Build a transaction that revokes an Agent Wallet (assistant capability) from this perpetuals account.
The returned transaction must be signed and submitted by the account admin wallet. After execution, the revoked wallet immediately loses its delegated permissions.
Object ID of the assistant capability to revoke.
Optionaltx?: TransactionOptional existing Transaction to append to. If omitted, a new Transaction is used.
Preview the effects of setting leverage for a given market.
The preview returns:
updatedPosition)collateralChange)Target leverage value.
Market whose leverage you want to adjust.
OptionalabortSignal: AbortSignal
Optional AbortSignal to cancel the request.
Either:
{ updatedPosition, collateralChange }, or{ error }.Build a set-leverage transaction for a given market.
This updates the effective leverage for the position (or potential position)
in marketId, and optionally adjusts collateral in tandem.
Notes:
Net collateral change to apply alongside the leverage update.
Target leverage value.
Market whose leverage to adjust.
Optionalsponsor?: PerpetualsSponsorConfigOptionaltx?: TransactionOptional transaction to extend.
Transaction response containing tx.
Fetch stop-order ticket data for this account, using an off-chain signed payload.
Typical flow:
Serialized message that was signed (e.g. JSON string).
OptionalmarketIds?: string[]Optional subset of markets to filter results by.
Signature over bytes.
ApiPerpetualsStopOrderDatasResponse containing stopOrderDatas.
Build a deterministic message payload to sign when querying stop orders from the backend.
This payload is intended to be signed off-chain and then submitted to
getStopOrderDatas as a proof of account ownership.
Important:
account_id to be a decimal string. This code
normalizes the bigint accountId by stripping the trailing n.Optionalinputs: { marketIds: string[] }
Optional list of market IDs to scope the query.
An object describing the action and account/market IDs, suitable for message signing.
Build a transfer-collateral transaction between two Perpetuals accounts.
Only supported for direct accounts, not vault-backed accounts.
Optionalsponsor?: PerpetualsSponsorConfigOptionaltoAccountCapId?: stringDestination account ID.
Amount of collateral to transfer.
Optionaltx?: TransactionOptional transaction to extend.
Transaction response containing a tx.
Fetch TWAP-order data for this account, using an off-chain signed payload.
Serialized message that was signed.
OptionalmarketIds?: string[]Optional subset of markets to filter results by.
Signature over bytes.
ApiPerpetualsTwapOrderDatasResponse containing twapOrderDatas.
Build a withdraw-collateral transaction for this account.
For non-vault accounts, this endpoint constructs a transaction to:
recipientAddress (otherwise coin is left
as a transaction argument).Note: Vault accounts are currently not supported and will throw.
OptionalrecipientAddress?: stringOptional address to receive the withdrawn coins directly.
Optionalsponsor?: PerpetualsSponsorConfigOptionaltx?: TransactionOptional transaction to extend (defaults to new Transaction()).
Amount of collateral to withdraw.
A response containing tx and the coinOutArg where the
withdrawn coins end up if recipientAddress is not used.
Check whether this PerpetualsAccount is vault-backed.
true if the underlying accountCap is a vault cap; otherwise false.
Filter a list of stop orders to only include non-SL/TP orders.
A stop order is considered SL/TP if it appears in the combined set of SL/TP orders across all markets (see slTpStopOrderDatas).
Matching uses the stop-order object ID, so bigint fields and field ordering do not affect classification.
Full array of stop-order ticket data.
An array of non-SL/TP stop orders, or undefined if none exist.
Filter stop orders for a single market to only include non-SL/TP orders.
Uses slTpStopOrderDatasForPosition under the hood.
Market ID to filter for.
Full list of stop orders.
Non-SL/TP stop orders for the given market, or undefined if none exist.
Flattens all pending position orders into reusable order data records.
The returned sizes remain fixed-point bigint values. The order side is decoded from each order ID, and the market ID comes from its position.
One PerpetualsOrderData record for each pending order.
Resolve the owner wallet address of this account or vault.
walletAddress field.ownerAddress.Naming note:
walletAddress for direct ownership. For vault-backed accounts
the analogous field is ownerAddress.Owner wallet SuiAddress.
Find the current position for a given market ID, if any.
Market ID to search for.
PerpetualsPosition if found, otherwise undefined.
Extract all SL/TP-style stop orders across all markets for this account.
SL/TP orders are stop orders which:
slTp payload, andThis combines:
i64MaxBigInt)i64MaxBigInt)The "full vs partial" distinction is a protocol convention: some systems encode “close entire position” using a sentinel max size.
Full list of stop-order tickets.
Array of SL/TP stop orders, or undefined if none exist.
Splits SL/TP stop orders linked to one limit order into full and partial closes.
A full close uses the protocol's Casting.i64MaxBigInt size sentinel.
Orders below that sentinel are returned as partial closes. The method does
not require a market ID because the link is carried by slTp.limitOrderId.
Limit order ID referenced by the SL/TP tickets.
Stop-order tickets to inspect.
Full close and partial close matches. Each result is undefined
when no matching order exists.
Categorize stop orders for a specific market into:
i64MaxBigInt) if any.i64MaxBigInt).SL/TP stop orders are defined as:
slTp field is present.stopLossPrice or takeProfitPrice is set.Notes on matching:
baseAssetAmount === 0 (no effective position), the method returns no SL/TP orders.Market to categorize stop orders for.
Full list of stop orders.
Object containing:
fullSlTpOrder (if any)partialSlTpOrders (if any, otherwise undefined)StaticapiReturns the canonical Aftermath API host for a Sui network.
To target a custom or local host, pass baseUrl in CallerConfig to the
constructor instead.
The Sui network whose host to return.
The network's HTTPS or local HTTP API host.
StaticdefaultReturns the canonical Sui fullnode URL for a network.
The network whose fullnode URL to return. undefined
defaults to mainnet.
The network's fullnode URL.
High-level wrapper around a single Perpetuals account or vault account.
This class encapsulates:
You typically do not construct
PerpetualsAccountdirectly. Instead, use Perpetuals.getAccount or Perpetuals.getAccounts, which fetch all required on-chain data and wrap it for you: