Creates a new Perpetuals client.
Optionalconfig: CallerConfig
Optional caller configuration (network, auth token, etc.).
Optionalapi: AftermathApi
Optional shared AftermathApi provider instance. When
provided, transaction-building helpers can derive serialized txKind
from a Transaction object via api.Transactions().fetchBase64TxKindFromTx.
This class extends Caller with the "perpetuals" route prefix, meaning:
/perpetuals/.../perpetuals/ws/...Optional ReadonlyapiOptional shared AftermathApi provider instance. When
provided, transaction-building helpers can derive serialized txKind
from a Transaction object via api.Transactions().fetchBase64TxKindFromTx.
The mutable configuration used for subsequent requests.
Static ReadonlyOrderHelper namespace for order-specific utilities such as parsing order IDs, extracting price bits, etc.
This is a direct alias of PerpetualsOrderUtils.
Convenience helper to fetch a single account (positions + account object) from an account cap.
Internally calls getAccounts and returns the first entry.
Account cap or partial vault cap object to derive account metadata from.
OptionalmarketIds?: string[]Optional list of markets to filter positions by.
Object containing account.
Fetch raw account objects (including positions) for one or more account IDs.
This is the lower-level primitive used by getAccounts.
Request body for fetching positions for a set of accounts.
marketIds can be supplied as an optimization hint to limit the markets
included in each account's returned positions array.
Perpetuals account IDs to query.
OptionalmarketIds?: string[]Optional market filter applied to each account's positions.
ApiPerpetualsAccountPositionsResponse containing accounts.
Fetch one or more accounts (positions + account objects) from account caps.
This composes:
accountCapsThe returned PerpetualsAccount instances encapsulate:
Array of account caps or partial vault cap objects.
OptionalmarketIds?: string[]Optional list of market IDs to filter positions by.
Object containing accounts in the same order as accountCaps.
Fetch account caps by their account IDs.
The input contains the list of account IDs to fetch.
ApiPerpetualsAccountCapsResponse containing caps.
Fetch all perpetual markets for a given collateral coin type.
This method returns wrapped PerpetualsMarket instances, not the raw market structs. Each instance provides additional helpers for pricing, margin, and order parsing.
Coin type used as collateral, e.g. "0x2::sui::SUI".
Object containing markets.
Fetch all vaults on the current network.
Vaults are managed accounts that can hold positions; LPs deposit collateral and receive an LP coin (see pricing helpers like getLpCoinPrices).
Object containing vaults.
Fetch integrator configuration for a specific account and integrator.
This endpoint queries whether an integrator has been approved by an account to collect fees on orders placed on behalf of the account. If approved, it returns the maximum integrator fee the integrator is authorized to charge. This information is useful for:
ApiPerpetualsBuilderCodesIntegratorConfigResponse containing
maxIntegratorFee and exists flag.
Fetch accumulated integrator vault fees.
This endpoint queries the total fees an integrator has earned and accumulated in their global vault, grouped by collateral coin type. Integrators earn fees proportional to the taker volume generated by orders they submit on behalf of users. These fees can be claimed at any time using getClaimBuilderCodeIntegratorVaultFeesTx.
This information is useful for:
ApiPerpetualsBuilderCodesIntegratorVaultsResponse containing
a vector of per-collateral vault data with accumulated fees.
const vaultFees = await perps.getBuilderCodeIntegratorVaults({
integratorId: 7,
});
for (const vault of vaultFees.integratorVaults) {
console.log(`${vault.collateralCoinType}: ${vault.fees} collateral units claimable`);
}
const totalFeesUsd = vaultFees.integratorVaults.reduce((sum, vault) => sum + vault.feesUsd, 0);
console.log(`Total claimable (USD): ${totalFeesUsd}`);
Build a transaction to claim accumulated integrator fees from a vault.
This endpoint creates a transaction that allows an integrator to claim the fees they have earned from orders placed on behalf of users. Fees accumulate in the integrator's global vault (across all markets) and can be claimed at any moment. The fees are proportional to the taker volume generated by the users' orders that the integrator submitted.
If a recipientAddress is provided, the claimed fees will be automatically
transferred to that address. Otherwise, the coin outputs are exposed as transaction
arguments for further use in the transaction (one per non-zero collateral balance).
The resulting transaction must be signed by the integrator and executed on-chain.
ApiPerpetualsBuilderCodesClaimIntegratorVaultFeesTxResponse containing
txKind and optionally coinOutArgs.
// Claim with automatic transfer to recipient
const response = await perps.getClaimBuilderCodeIntegratorVaultFeesTx({
integratorId: 7,
recipientAddress: "0x...",
});
// Claim with coin outputs for further use
const response = await perps.getClaimBuilderCodeIntegratorVaultFeesTx({
integratorId: 7,
});
// response.coinOutArgs can be used in subsequent transaction commands
Build a create-account transaction for Aftermath Perpetuals.
When deferShare is true, the response includes a deferred object with
accountArg, sharePolicyArg, adminCapArg, and collateralCoinType so you
can compose additional commands (grant-agent-wallet, transfer-cap) before calling
getShareAccountTx to finalize.
Wallet address that will own the new account.
Collateral coin type used by the account.
When true, returns deferred args without sharing yet.
Optional Transaction to extend.
Optionaltx?: TransactionOptional Transaction to extend.
tx plus optional deferred containing argument references when deferred.
Build a transaction to create an integrator configuration.
This endpoint creates a transaction that allows a user to grant permission to an integrator to receive fees on orders placed on their behalf. The user specifies a maximum integrator fee that the integrator can charge. The integrator can then include their id and fee (up to the maximum) when placing orders for the user.
The resulting transaction must be signed by the account owner and executed on-chain.
SdkTransactionResponse with tx.
Build a transaction to initialize an integrator's global fee vault.
This endpoint creates a transaction that initializes the global vault where an integrator's fees accumulate across all markets. This is a one-time setup that must be performed before the integrator can claim fees. The integrator's identity is taken from the transaction sender on-chain.
The resulting transaction must be signed by the integrator and executed on-chain.
SdkTransactionResponse with tx.
Build a create-vault-cap transaction.
A vault cap is an ownership/admin object for interacting with vault management flows. This method returns a transaction kind that mints/creates that cap.
SdkTransactionResponse with tx.
Build a create-vault transaction.
This creates a new vault plus its on-chain metadata and initial LP supply seeded by the initial deposit.
Deposit input:
initialDepositAmount to have the API select/merge coins as needed, ORinitialDepositCoinArg if you already have a coin argument in a larger tx.Metadata:
extraFields allows forward-compatible additions (e.g. social links).Coin metadata object id obtained from create vault cap tx
Collateral coin type for deposits.
Delay before forced withdrawals can be processed.
OptionalisSponsoredTx?: booleanWhether this tx is sponsored (gas paid by another party).
Lock-in period for deposits in milliseconds.
Vault display metadata (name, description, curator info).
OptionalcuratorLogoUrl?: stringAn image url for the Vault's curator. Ideally their logo.
OptionalcuratorName?: stringThe Vault curator's name.
OptionalcuratorUrl?: stringA url for the Vault's curator. Ideally their website.
A verbose description of the Vault.
OptionalextraFields?: Record<string, string>Extra / optional fields for future extensibility.
Recommended keys include: twitter_url.
A human-readable name for the Vault.
Fraction of profits taken as curator fee.
Optionalsponsor?: PerpetualsSponsorConfigTreasury cap object id obtained from create vault cap tx
Optionaltx?: TransactionOptional Transaction to extend.
Address of vault owner/curator.
Initial deposit amount (mutually exclusive with initialDepositCoinArg).
Transaction object argument referencing the deposit coin.
SdkTransactionResponse with tx.
Generate a CSV-formatted rebate report for perpetuals market makers.
Computes per-account reward allocations and fee-tier rebate adjustments,
returning the result as a CSV string. When aggregated is true, the CSV
groups rewards by owner address instead of per-account.
Note: All data returned is for the current epoch only.
ApiPerpetualsCreateCsvRebatesResponse containing the CSV string.
Calculate rewards and rebates for one or more perpetuals accounts.
Computes per-account maker and taker reward allocations, fee-tier rebates,
and volume-based metrics. When accountIds is omitted or empty, all eligible
accounts are included.
Note: All data returned is for the current epoch only.
Request body for calculating rewards and rebates for perpetuals accounts.
This corresponds to POST /api/perpetuals/rebates/rewards.
Given maker and taker reward pools and a list of accounts, computes
per-account reward allocations and fee-tier rebates.
When accountIds is omitted or empty, all eligible accounts are included.
Note: All data returned is for the current epoch only.
OptionalaccountIds?: bigint[]Optional account filter. Omit or pass an empty array for all eligible accounts.
Coefficients used to compute Q-scores and taker shares.
Total maker reward pool to distribute among eligible market makers.
Total taker reward pool to distribute among eligible takers.
ApiPerpetualsCurrentRebateRewardsResponse with per-account reward and rebate data.
Build a transaction that grants an Agent Wallet permission on a Perpetuals account.
Supports two methods:
accountId to look up an existing shared account.deferred with the argument references
from a deferred getCreateAccountTx call.Wallet address to receive agent permissions.
Perpetuals account ID (Method 1).
Deferred account args from getCreateAccountTx (Method 2).
Optional transaction to extend.
Optionaltx?: TransactionOptional transaction to extend.
Transaction response containing a tx.
Build a transaction that grants assistant permissions for a vault.
Fetch LP coin prices (in collateral units) for a set of vaults.
Request body for fetching LP coin prices for a set of vaults.
LP coin price is typically expressed in USD per 1 LP token (native units adjusted
using lpCoinDecimals on the vault object).
Vault object IDs whose LP prices are queried.
ApiPerpetualsVaultLpCoinPricesResponse containing lpCoinPrices.
Fetch a single market by ID.
Internally calls getMarkets and returns the first entry.
The market (clearing house) object ID.
Object containing market.
Fetch historical OHLCV candle data for a single market.
Request payload for fetching historical candle (OHLCV) data for a given perpetuals market.
Start of the time range to query, as a Unix timestamp in milliseconds.
Identifier of the perpetuals market whose candles you want to fetch.
Must be a valid on-chain market ID.
Candle resolution as a CCXT-style timeframe label (e.g. "1m", "1h", "1d").
End of the time range to query, as a Unix timestamp in milliseconds.
ApiPerpetualsMarketCandleHistoryResponse containing candle points.
This is currently implemented on the Perpetuals root client, but it may be relocated to PerpetualsMarket in the future.
Fetch historical funding rate data for a single market.
Request payload for fetching historical funding rate data for a given perpetuals market.
Start of the time range to query (Unix timestamp in milliseconds).
Optionallimit?: numberMaximum number of funding points to return.
Market ID to query. Must be a valid on-chain market ID.
End of the time range to query (Unix timestamp in milliseconds).
ApiPerpetualsMarketFundingHistoryResponse containing
funding history points.
Fetch multiple markets by ID.
Backend note:
marketDatas[].market.Array of market object IDs to fetch.
Object containing markets in the same order as marketIds.
Fetch 24-hour volume and price change stats for multiple markets.
Returns volume, price change, and the latest base, collateral, mid, and mark prices for each requested market.
Market IDs to query.
ApiPerpetualsMarkets24hrStatsResponse.
Fetch all account caps (perpetuals accounts) owned by a wallet, optionally filtered by collateral coin types.
Returned values are “caps” (ownership objects), not full account snapshots. To fetch account positions, use getAccount or getAccounts.
Request body for fetching all account caps owned by a given wallet.
OptionalcollateralCoinTypes?: string[]Optional collateral coin types used to filter the returned caps.
Wallet whose owned account-cap objects are queried.
ApiPerpetualsOwnedAccountCapsResponse containing accounts.
Fetch all vault assistant caps owned by a wallet.
Assistant caps grant a non-owner wallet the ability to operate a vault on behalf of the owner. The returned caps are structurally identical to regular vault caps (PerpetualsVaultCap) and can be used to construct a PerpetualsAccount that signs vault transactions with the assistant's wallet.
Request body for fetching vault assistant capability objects owned by a wallet.
Assistant caps let a non-owner wallet operate a vault on behalf of the owner. They are structurally identical to regular vault caps but grant a narrower permission set.
Wallet whose owned assistant capabilities are queried.
ApiPerpetualsOwnedVaultAssistantCapsResponse containing
assistant caps.
Fetch all vault caps owned by a wallet.
Vault caps represent ownership/administrative authority over a vault.
Request body for fetching vault capability objects owned by a wallet.
Vault caps are typically owned by the vault creator/owner and are required for privileged vault actions (processing withdrawals, updating parameters, etc.).
Wallet whose owned vault capabilities are queried.
ApiPerpetualsOwnedVaultCapsResponse containing vault caps.
Fetch all Perpetuals vault LP coins owned by a wallet.
This returns coin objects (or summaries) representing LP token holdings. Use getLpCoinPrices to value them in collateral units.
ApiPerpetualsVaultOwnedLpCoinsResponse.
Fetch all pending vault withdrawal requests created by a given wallet.
Withdraw requests are typically created when LPs request to exit a vault and may be subject to lock periods / delays depending on vault configuration.
Request body for fetching withdrawal requests for a given wallet across its vault positions.
Wallet whose vault withdrawal requests are queried.
ApiPerpetualsVaultOwnedWithdrawRequestsResponse containing requests.
Fetch the latest prices for one or more markets.
Returns base, collateral, order book mid, and mark prices for each requested market.
List of market IDs to query.
ApiPerpetualsMarketsPricesResponse containing marketsPrices.
Generate a CSV-formatted referral rebate report.
Calculates referrer commissions and referee discounts based on trading fees within the specified epoch, returning the result as a CSV string.
ApiPerpetualsCreateReferralCsvRebatesResponse containing the CSV string.
Build a transaction to remove an integrator configuration.
This endpoint creates a transaction that removes an integrator's approval to
collect fees on orders placed on behalf of the user. Once revoked, the integrator
will no longer be able to submit orders with integrator fees for this account.
The user can re-approve the integrator at any time by calling
getCreateIntegratorConfigTx again.
The resulting transaction must be signed by the account owner and executed on-chain.
SdkTransactionResponse with tx.
Build a transaction that revokes a vault assistant capability.
Build a transaction to share a Perpetuals account that was created with deferred sharing.
This finalizes the account creation flow by consuming the AccountSharePolicy
and sharing the Account object. Call this after composing additional commands
(grant-agent-wallet, transfer-cap) with the args returned by getCreateAccountTx.
Pass the deferred fields (accountArg, sharePolicyArg, adminCapArg,
collateralCoinType) from the deferred object returned by getCreateAccountTx.
Account argument from deferred create.
Share policy argument from deferred create.
Admin cap argument from deferred create.
Collateral type for the account.
Optional sponsorship config.
Optional transaction to extend.
Optionaltx?: TransactionOptional transaction to extend.
Transaction response containing a tx.
Build a transaction to transfer a Perpetuals capability object (cap) to another wallet.
Supports two methods:
capObjectId to transfer an existing on-chain object.composed with the PTB argument and capability type
from a deferred PTB composition (e.g., from getCreateAccountTx with deferShare=true).Recipient wallet address that should receive the cap.
Object ID of the capability to transfer (Method 1).
Composed PTB argument + capability type (Method 2).
Optional transaction to extend.
Optionaltx?: TransactionOptional transaction to extend.
Transaction response containing a tx.
Fetch a single vault by ID.
Internally calls getVaults and returns the first entry.
Vault object ID.
Object containing vault.
Fetch multiple vaults by ID.
Array of vault object IDs.
Object containing vaults in the same order as vaultIds.
Fetch the current network-wide Perpetuals vault protocol configuration.
The returned limits are sourced from the on-chain configuration exposed by the service. Consumers should use these values instead of hardcoded vault limits because governance or package upgrades may change them.
OptionalabortSignal: AbortSignal
Optional signal used to cancel the request.
The current vault protocol limits for this client's network.
Open a market-candles websocket stream for a single market/interval:
/perpetuals/ws/market-candles/{market_id}/{interval_ms}.
The stream emits PerpetualsWsCandleResponseMessage messages, typically containing the latest candle for the specified interval.
Market ID to subscribe to. The input contains the candle interval in milliseconds.
OptionalonClose?: (ev: CloseEvent) => voidOptional hook called when the websocket closes.
OptionalonError?: (ev: Event) => voidOptional hook called on websocket error.
Handler for incoming candle updates.
OptionalonOpen?: (ev: Event) => voidOptional hook called when the websocket opens.
A controller containing the raw websocket and a close() helper.
Open the main updates websocket: /perpetuals/ws/updates.
The stream emits PerpetualsWsUpdatesResponseMessage envelopes and supports multiple subscription types. This method returns a small controller with convenience subscribe/unsubscribe functions.
Subscription types supported by the controller:
market: market state updatesuser: user account updates (optionally including stop orders)oracle: oracle price updatesorderbook: orderbook deltasmarketOrders: public market trades/ordersuserOrders: user trade/order eventsuserCollateralChanges: user collateral change eventstopOfOrderbook: bucketed orderbook snapshots (top of orderbook)OptionalonClose?: (ev: CloseEvent) => voidOptional handler for the close event.
OptionalonError?: (ev: Event) => voidOptional handler for the error event.
Handler for parsed messages from the websocket.
OptionalonOpen?: (ev: Event) => voidOptional handler for the open event.
A controller object containing:
ws: underlying WebSocketclose(): closes the websocketSubscription helpers
Each helper sends a structured subscription message of the form:
{ action: "subscribe" | "unsubscribe", subscriptionType: { ... } }
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.
StaticeventConstruct a collateral-specialized Move event type string.
Many Move events are generic over a collateral coin type. This helper appends
<collateralCoinType> to a base eventType.
Collateral coin type (e.g. "0x2::sui::SUI").
Base event type without type parameters.
Fully-qualified event type string.
StaticlotConvert a floating-point lot/tick size to its fixed-point representation (9 decimals).
Floating-point size.
Fixed-point size as bigint.
StaticlotConvert a fixed-point lot/tick size (9 decimals) to a number.
Fixed-point size as bigint.
Floating-point size.
StaticorderInfer the order side from an encoded order ID.
Encoded order ID.
PerpetualsOrderSide.
StaticorderCompute the effective trade price from a FilledTakerOrderEvent.
Uses the ratio: quoteAssetDelta / baseAssetDelta.
Filled taker order event.
Trade price.
StaticorderExtract the floating-point price from an encoded order ID.
Internally uses PerpetualsOrderUtils.price and converts the fixed-point
PerpetualsOrderPrice into a number.
Encoded order ID.
Price as a number.
StaticorderConvert a fixed-point PerpetualsOrderPrice to a float price.
Fixed-point order price.
Price as a float.
StaticpositionDetermine the logical order side (Bid/Ask) from a signed base asset amount.
Position base size. Positive/zero => Bid (long), negative => Ask (short).
PerpetualsOrderSide.
StaticpriceConvert a floating-point price into a fixed-point PerpetualsOrderPrice using 9 decimal places of precision.
Price as a float.
Fixed-point order price.
High-level client for interacting with Aftermath Perpetuals.
This class exposes a typed, ergonomic interface over the Perpetuals HTTP API and websocket endpoints, including:
getAllMarkets,getMarkets,getMarket)getAllVaults,getVaults,getVault)getAccount,getAccounts,getAccountObjects)getOwnedAccountCaps,getOwnedVaultCaps)getMarketCandleHistory,getMarkets24hrStats)getPrices,getLpCoinPrices)getCreateAccountTx,getCreateVaultCapTx,getCreateVaultTx)openUpdatesWebsocketStream,openMarketCandlesWebsocketStream)Typical usage via the root SDK: