Perpetuals
Complete API Reference for the Perpetuals Class
Overview
The Perpetuals class is the main entry point for all perpetuals-related operations in the Aftermath Finance SDK. It provides a comprehensive interface for:
Discovering and querying perpetual markets
Managing trading accounts and vaults
Fetching historical data and statistics
Building transactions for on-chain operations
Streaming real-time data via WebSocket
Builder-code approvals and rebate tooling
This class extends the Caller base class with the "perpetuals" route prefix, meaning all HTTP calls resolve under /perpetuals/... and WebSocket calls under /perpetuals/ws/....
Typical Usage:
import { Aftermath } from "aftermath-ts-sdk";
const afSdk = await Aftermath.create({ network: "MAINNET" });
const perps = afSdk.Perpetuals();Constructor
constructor
Creates a new Perpetuals client instance.
Parameters:
config(optional):CallerConfigConfiguration object containing:
network: Use"MAINNET"for Aftermath PerpetualsaccessToken: Optional authentication tokenOther caller-specific settings
Provider(optional):AftermathApiShared provider instance used for transaction building
When provided, transaction builder methods can derive serialized
txKindfromTransactionobjectsEnables the
Provider.Transactions().fetchBase64TxKindFromTx()functionality
Remarks:
This class extends
Callerwith the"perpetuals"route prefixHTTP calls resolve under
/perpetuals/...WebSocket calls resolve under
/perpetuals/ws/...Typically accessed via
afSdk.Perpetuals()rather than direct construction
Example:
Static Properties
OrderUtils
Helper namespace for order-specific utilities such as parsing order IDs and extracting price information.
Available Methods:
price(orderId: PerpetualsOrderId): PerpetualsOrderPrice- Extract the encoded price from an order IDisAsk(orderId: PerpetualsOrderId): boolean- Determine if an order is an ask (sell) orderAdditional order parsing utilities
Example:
Market Discovery Methods
getAllMarkets
Fetch all perpetual markets for a given collateral coin type.
Parameters:
collateralCoinType:CoinTypeThe coin type used as collateral (e.g.,
"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC")Must be a fully qualified Move type identifier
All returned markets will use this collateral type
Returns:
Object containing:
markets:PerpetualsMarket[]Array of wrapped market instances
Each market contains market parameters, current state, and helper methods
Example:
Use Cases:
Market Discovery: List all available markets for a collateral type
Price Comparison: Compare prices across different markets
Market Selection: Let users choose which market to trade
Dashboard Display: Show market overview with key metrics
getMarket
Fetch a single market by its ID.
Parameters:
marketId:PerpetualsMarketId(which isObjectId)The market (clearing house) object ID on the Sui blockchain
This is the unique identifier for the market
Format: 32-byte hex string with
0xprefix
Returns:
Object containing:
market:PerpetualsMarketSingle wrapped market instance
Contains all market parameters, state, and helper methods
Throws/Edge Cases:
If the backend returns an empty list for the given
marketId, this will still attempt to returnmarkets[0]which would beundefinedCallers should validate the result to ensure the market exists
Example:
Use Cases:
Direct Market Access: When you know the exact market ID
Deep Linking: Navigate directly to a specific market
Market Refresh: Update data for a single market
Trading Interface: Display detailed market information
getMarkets
Fetch multiple markets by their IDs in a single API call.
Parameters:
marketIds:PerpetualsMarketId[]Array of market object IDs to fetch
Can include any number of market IDs
Do not depend on input order; current market responses are sorted by symbol
Returns:
Object containing:
markets:PerpetualsMarket[]Array of wrapped market instances
Match returned markets by
marketId, not array position
Example:
Use Cases:
Batch Fetching: Efficiently fetch multiple markets at once
Multi-Market Display: Show data for several markets simultaneously
Comparison Tools: Compare metrics across different markets
Portfolio View: Display all markets where user has positions
Dynamic Vault Configuration
getVaultsConfig
Fetches the current deployment-driven vault limits from POST /api/perpetuals/vaults/config. The request sends {}. Integer-like values return as JavaScript bigint; decimal limits remain numbers.
Use this method instead of hard-coding lock periods, minimum deposits, market counts, or pending-order limits. PerpetualsVault.constants has been removed.
Vault Discovery Methods
getAllVaults
Fetch all vaults on the current network.
What are Vaults? Vaults are managed accounts that accept user deposits (LP tokens), trade across multiple markets, and support withdrawals via a request flow. LPs deposit collateral and receive LP coins representing their share of the vault. The vault manager (curator) trades on behalf of LPs and may charge a performance fee.
Parameters:
None - fetches all vaults regardless of collateral type or status.
Returns:
Object containing:
vaults:PerpetualsVault[]Array of all vaults on the network
Each vault instance provides access to vault parameters, trading account, and transaction builders
Example:
Use Cases:
Vault Discovery: Browse all available vaults
Investment Research: Compare vault strategies and fees
LP Dashboard: Display vault metrics for liquidity providers
Curator Analytics: Analyze vault ecosystem
getVault
Fetch a single vault by its object ID.
Parameters:
vaultId:ObjectIdThe vault's unique, onchain identifier
Format: 32-byte hex string with
0xprefix
Returns:
Object containing:
vault:PerpetualsVaultSingle wrapped vault instance
Provides access to vault configuration, trading account, and transaction builders
Example:
Use Cases:
Direct Vault Access: When you know the exact vault ID
Vault Detail Page: Display comprehensive vault information
LP Portfolio: Show vault details for deposited vaults
Curator Dashboard: Manage a specific vault
getVaults
Fetch multiple vaults by their IDs in a single API call.
Parameters:
vaultIds:ObjectId[]Unbounded array of vault object IDs to fetch
Order is preserved in the response
Returns:
Object containing:
vaults:PerpetualsVault[]Array of wrapped vault instances, returned in the same order as input
vaultIds
Example:
Use Cases:
Batch Vault Fetching: Efficiently fetch multiple vaults
Portfolio Management: Display all vaults where user has deposits
Comparison Tools: Compare multiple vault strategies
Analytics Dashboard: Aggregate vault metrics
Account Management Methods
getAccount
Convenience helper to fetch a single account (positions + account object) from an account cap.
What is an Account Cap? An account cap is an owned-object that represents control over a perpetuals account. It can be:
PerpetualsAccountCap: Direct ownership of a personal trading account
PerpetualsPartialVaultCap: Derived from a vault cap, representing the vault's trading account
Parameters:
accountCap:PerpetualsAccountCap | PerpetualsPartialVaultCapAccount cap or partial vault cap object to derive account metadata from
Contains:
accountId,collateralCoinType,accountObjectIdObtained from
getOwnedAccountCaps()or vault operations
marketIds(optional):PerpetualsMarketId[]List of market IDs to filter positions by
If provided, only positions in these markets are returned
If omitted, all positions are returned
Returns:
Object containing:
account:PerpetualsAccountWrapped account instance with:
Account snapshot (positions, balances, equity)
Ownership/cap metadata
Transaction builder methods
Helper functions
Example:
Use Cases:
Account Dashboard: Display user's account overview
Trading Interface: Access account for placing orders
Portfolio Management: View all positions and balances
Position Monitoring: Check margin ratios and PnL
getAccounts
Fetch one or more accounts (positions + account objects) from account caps.
How it Works:
Calls
getAccountObjects()to fetch raw account data by account IDsLocally pairs returned account objects with input
accountCapsConstructs
PerpetualsAccountinstances wrapping both data and metadata
The returned PerpetualsAccount instances encapsulate:
Account snapshot (positions, balances, equity)
Ownership/cap metadata (accountId, collateral type, vaultId)
Transaction builder methods
Helper functions
Parameters:
accountCaps:(PerpetualsAccountCap | PerpetualsPartialVaultCap)[]Array of account caps or partial vault cap objects
Each cap contains ownership and identification data
Can mix direct account caps and vault caps
marketIds(optional):PerpetualsMarketId[]List of market IDs to filter positions by
Applies to all accounts in the request
Useful for focused portfolio views
Returns:
Object containing:
accounts:PerpetualsAccount[]Array of wrapped account instances
Returned in the same order as input
accountCapsEach element corresponds to the cap at the same index
Example:
Use Cases:
Multi-Account Dashboard: Display all user accounts
Portfolio Aggregation: Calculate total portfolio metrics
Account Comparison: Compare performance across accounts
Bulk Operations: Prepare multiple accounts for batch processing
getAccountObjects
Fetch raw account objects (including positions) for one or more account IDs. This is the lower-level primitive used by getAccounts.
When to use:
When you only have account IDs (not caps)
When you need raw data without the wrapper layer
For custom processing or integration
Parameters:
accountIds:PerpetualsAccountId[]List of numeric account IDs to query (bigint values)
Each ID uniquely identifies an account
Example:
[123n, 456n, 789n]
marketIds(optional):PerpetualsMarketId[]List of market IDs to filter positions by
If provided, only positions in these markets are included
Applies to all accounts in the request
Returns:
ApiPerpetualsAccountPositionsResponse containing:
accounts:PerpetualsAccountObject[]Array of raw account objects
Each object contains:
accountId: The account IDpositions: Array of position dataavailableCollateral: Free collateral amounttotalEquity: Total account equityOther account state fields
Edge Cases:
If
accountIdsis empty, returns{ accounts: [] }without making an API call
Example:
Use Cases:
Low-Level Data Access: When you need raw account data
Custom Integrations: Building custom account wrappers
Analytics: Processing account data for reports
Bulk Queries: Efficiently fetch many accounts by ID
Ownership Query Methods
getOwnedAccountCaps
Fetch all account caps (perpetuals accounts) owned by a wallet, optionally filtered by collateral coin types.
What are Account Caps? Account caps are ownership objects that represent control over perpetuals trading accounts. They contain:
Account ID (numeric identifier)
Account Object ID (on-chain object)
Collateral coin type
Owner wallet address
Returned values are Account Caps, not a snapshot of the full account. To fetch account positions and balances, use getAccount() or getAccounts().
Parameters:
walletAddress:SuiAddressOwner wallet address to query
Must be a valid Sui address (32-byte hex with
0xprefix)Returns caps owned by this address
collateralCoinTypes(optional):CoinType[]Optional list of collateral coin types to filter by
Only returns caps for accounts using these collateral types
Example:
["0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC", "0x...::usdc::USDC"]If omitted, returns caps for all collateral types
Returns:
ApiPerpetualsOwnedAccountCapsResponse containing:
accounts:PerpetualsAccountCap[]Array of account cap objects
Each cap contains:
objectId: Cap object IDaccountId: Numeric account IDaccountObjectId: Account object IDcollateralCoinType: Collateral typewalletAddress: Owner address
Example:
Use Cases:
Account Discovery: Find all accounts owned by a user
Wallet Integration: List user's trading accounts
Multi-Account Management: Display account switcher
Onboarding: Check if user has an account before trading
getOwnedVaultCaps
Fetch all vault caps owned by a wallet.
What are Vault Caps? Vault caps represent ownership/administrative authority over a vault. Holders of a vault cap can:
Update vault parameters (fees, lock periods)
Process user withdrawals
Withdraw performance fees
Manage vault positions
Parameters:
walletAddress:SuiAddressOwner wallet address to query
Must be a valid Sui address
Returns vault caps owned by this address
Returns:
ApiPerpetualsOwnedVaultCapsResponse containing:
vaultCaps:PerpetualsVaultCap[]Array of vault cap objects
Each cap contains:
objectId: Cap object IDvaultId: Vault object IDaccountId: Vault's trading account IDaccountObjectId: Account object IDcollateralCoinType: Vault's collateral typeownerAddress: Vault owner address
Example:
Use Cases:
Vault Management: Find vaults owned/managed by a curator
Curator Dashboard: Display all managed vaults
Administrative Access: Verify vault ownership before operations
Portfolio Management: Track performance across managed vaults
getOwnedVaultWithdrawRequests
Fetch all pending vault withdrawal requests created by a given wallet.
What are Withdrawal Requests? When LPs want to exit a vault, they create a withdrawal request. These requests:
Are subject to lock periods (preventing immediate withdrawal)
May be processed by the vault owner in batches
Can be cancelled before processing
Have slippage protection (minimum collateral out)
Parameters:
walletAddress:SuiAddressWallet address that created the withdrawal requests
Returns all pending requests for this address
Must be a valid Sui address
Returns:
ApiPerpetualsVaultOwnedWithdrawRequestsResponse containing:
withdrawRequests:PerpetualsVaultWithdrawRequest[]Array of pending withdrawal request objects
Each request contains:
objectId: Request object IDvaultId: Vault being withdrawn fromlpCoinAmount: Amount of LP coins to burnminCollateralAmountOut: Minimum collateral to receivecreatedAt: Timestamp when request was createduserAddress: User who created the request
Example:
Use Cases:
Withdrawal Tracking: Monitor pending vault withdrawals
User Dashboard: Display withdrawal request status
Request Management: Update or cancel pending requests
Liquidity Planning: Understand pending outflows for vault managers
getOwnedVaultLpCoins
Fetch all Perpetuals vault LP coins owned by a wallet.
What are LP Coins? When users deposit collateral into a vault, they receive LP (Liquidity Provider) coins representing their share of the vault. These coins:
Represent proportional ownership of vault assets
Can be burned to withdraw collateral (via withdrawal request)
Appreciate/depreciate based on vault performance
Are transferable (can be sent to other addresses)
Are owned directly by end users
Parameters:
walletAddress:SuiAddressOwner wallet address to query
Returns LP coins owned by this address
Must be a valid Sui address
vaultIds(optional):ObjectId[]Optional list of vault IDs to filter by
Only returns LP coins for these specific vaults
If omitted, returns LP coins for all vaults
Returns:
ApiPerpetualsVaultOwnedLpCoinsResponse containing:
lpCoins:PerpetualsVaultLpCoin[]Array of LP coin objects
Each coin contains:
objectId: Coin object IDvaultId: Vault the coin belongs tobalance: Amount of LP coinscoinType: Full coin type (includes vault ID)
Example:
Use Cases:
Portfolio Display: Show user's vault investments
Withdrawal Planning: Determine available LP coins for withdrawal
Performance Tracking: Calculate investment value over time
Asset Management: Monitor vault allocations
getAdminAccountCaps
Fetch account caps by their cap object IDs.
When to use:
When you have specific cap object IDs
For direct cap lookup without knowing the owner
For cached/stored cap references
Parameters:
accountCapIds:ObjectId[]List of account cap object IDs to fetch
Each ID uniquely identifies a cap on-chain
Must be valid 32-byte hex strings with
0xprefix
Returns:
ApiPerpetualsAccountCapsResponse containing:
accountCaps:PerpetualsAccountCap[]Array of account cap objects
Returned in the same order as input
accountCapIdsEach cap contains full ownership and metadata
Example:
Use Cases:
Direct Cap Lookup: When you have stored cap IDs
Deep Linking: Navigate to account from cap ID in URL
Cached References: Fetch caps from persistent storage
Permission Verification: Check cap ownership
getOwnedVaultAssistantCaps
Fetches vault assistant capabilities owned by a wallet. These caps let an agent wallet construct supported vault-account transactions without receiving owner withdrawal authority.
Historical Data & Statistics Methods
getMarketCandleHistory
Fetch historical OHLCV (Open, High, Low, Close, Volume) candle data for a single market.
Parameters:
marketId:PerpetualsMarketIdMarket ID to query candle history for
Must be a valid market object ID
fromTimestamp:TimestampStart timestamp in milliseconds (inclusive)
Unix epoch time (e.g.,
Date.now())Data begins from this time
toTimestamp:TimestampEnd timestamp in milliseconds (exclusive)
Unix epoch time
Data ends before this time
resolution:PerpetualsCandleResolutionCandle interval as a timeframe label
Supported values:
1m,5m,15m,30m,1h,4h,12h,1d,3d,1w, and1mo
Returns:
ApiPerpetualsMarketCandleHistoryResponse containing:
candles:PerpetualsMarketCandleDataPoint[]Array of candle data points
Each candle contains:
timestamp: Candle start timeopen: Opening pricehigh: Highest pricelow: Lowest priceclose: Closing pricevolume: Trading volume
Sorted chronologically (oldest to newest)
Example:
Use Cases:
Chart Visualization: Display price charts with OHLC data
Technical Analysis: Calculate indicators (SMA, EMA, RSI, etc.)
Historical Performance: Analyze price movements over time
Backtesting: Test trading strategies on historical data
getMarketFundingHistory
Fetch historical funding data for a market using the current market/funding-history endpoint. Funding and candle timestamps are milliseconds.
getMarkets24hrStats
Fetch 24-hour statistics for multiple markets.
What's Included:
24-hour volume
Price change (absolute and percentage)
High/low prices
Open/close prices
Number of trades
Parameters:
marketIds:PerpetualsMarketId[]Array of market IDs to query statistics for
Can query multiple markets simultaneously
Stats returned in corresponding order
Returns:
ApiPerpetualsMarkets24hrStatsResponse containing:
marketsStats:PerpetualsMarket24hrStats[]Array of 24-hour statistics
One entry per input market ID
Each stat object contains:
marketId: Market identifiervolume24h: Trading volume in last 24hpriceChange24h: Price change percentagepriceChangeAbsolute24h: Absolute price changehigh24h: Highest pricelow24h: Lowest priceopen24h: Opening priceclose24h: Closing price (most recent)trades24h: Number of trades
Example:
Use Cases:
Market Overview Dashboard: Display 24h performance metrics
Top Movers: Show biggest gainers/losers
Volume Analysis: Identify most liquid markets
Performance Tracking: Monitor market activity
Pricing Methods
getPrices
Fetch the latest oracle prices (base asset and collateral) for one or more markets.
What Prices are Returned:
Base Price: Current oracle price of the underlying asset (e.g., BTC, ETH)
Collateral Price: Current price of the collateral asset (e.g., USD value of SUI)
These prices are used for:
Position valuation
PnL calculations
Margin requirements
Liquidation price determination
Parameters:
marketIds:ObjectId[]List of market IDs to query prices for
Can request prices for multiple markets simultaneously
Prices returned in corresponding order
Returns:
ApiPerpetualsMarketsPricesResponse containing:
marketsPrices: Array of price objectsOne entry per input market ID
Each object contains:
marketId: Market identifierbasePrice: Oracle price of base assetcollateralPrice: Price of collateral asset
Example:
Use Cases:
Position Valuation: Calculate current position values
PnL Calculation: Determine unrealized profits/losses
Price Monitoring: Track oracle price movements
Liquidation Checks: Compare prices to liquidation thresholds
getLpCoinPrices
Fetch LP coin prices (in collateral units) for a set of vaults.
What is LP Coin Price? The LP coin price represents how much collateral one LP token is worth. This price:
Changes based on vault performance (trading PnL)
Increases when vault makes profits
Decreases when vault has losses
Accounts for performance fees
Formula:
Parameters:
vaultIds:ObjectId[]List of vault IDs to query LP prices for
Can request prices for multiple vaults simultaneously
Prices returned in corresponding order
Returns:
ApiPerpetualsVaultLpCoinPricesResponse containing:
lpCoinPrices: Array of LP price objectsOne entry per input vault ID
Each object contains:
vaultId: Vault identifierpriceInCollateral: Price of one LP coin in collateral unitstimestamp: When price was calculated
Example:
Use Cases:
Portfolio Valuation: Calculate total vault investment value
Performance Tracking: Monitor vault returns over time
Withdrawal Planning: Estimate collateral received when withdrawing
Vault Comparison: Compare LP prices across vaults
Transaction Builder Methods
getCreateAccountTx
Build a create-account transaction for Aftermath Perpetuals.
What This Does: Creates a new perpetuals trading account for a user. The account:
Is owned by the specified wallet address
Uses the specified collateral type
Can be used to trade in markets with matching collateral
Receives an account cap NFT representing ownership
This transaction must be signed and executed by the wallet. The account cap will be minted to the wallet address.
Parameters:
walletAddress:SuiAddressWallet address that will own the new account
This address will receive the account cap NFT
Must be a valid Sui address (32-byte hex with
0xprefix)
collateralCoinType:CoinTypeCollateral coin type the account will use
Must be a supported collateral type (e.g.,
"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC")Account can only trade in markets using this collateral
Cannot be changed after account creation
tx(optional):TransactionOptional existing transaction to extend
If provided, create-account commands are appended to this transaction
Useful for batching multiple operations
Returns:
SdkTransactionResponse containing:
tx:TransactionTransaction object ready to be signed and executed
Contains the create-account command
Can be further modified before signing
Example:
Use Cases:
User Onboarding: Create first trading account for new users
Multi-Collateral Setup: Create accounts for different collateral types
Wallet Integration: Build account creation flow in dApp
Batch Operations: Combine account creation with other transactions
getGrantAgentWalletTx
Builds an account-level agent-wallet grant transaction. It accepts either an existing numeric accountId or the deferred arguments returned by getCreateAccountTx({ deferShare: true }).
getShareAccountTx
Finalizes deferred account creation by consuming accountArg, adminCapArg, sharePolicyArg, and collateralCoinType. Use it after composing any grant or cap-transfer commands into the same PTB.
getCreateVaultCapTx
Build a create-vault-cap transaction.
What This Does: Creates a vault cap, which is an ownership/admin object for interacting with vault management flows. This is a prerequisite step before creating the actual vault. The transaction returns:
A coin metadata object ID
A treasury cap object ID
These IDs are needed as inputs for getCreateVaultTx.
Parameters:
walletAddress:SuiAddressVault owner/curator address
Will receive the vault cap NFT
Must be a valid Sui address
collateralCoinType:CoinTypeCollateral coin type for the vault
Vault will only accept this collateral type
Example:
"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC"
Returns:
SdkTransactionResponse containing:
tx:TransactionTransaction object ready to sign and execute
After execution, extract
coinMetadataIdandtreasuryCapIdfrom transaction effects
Example:
Use Cases:
Vault Creation: First step in creating a new vault
Curator Onboarding: Set up new vault managers
Multi-Vault Management: Create multiple vaults for different strategies
getCreateVaultTx
Build a create-vault transaction.
What This Does: Creates a new vault with:
On-chain metadata (name, description, curator info)
Initial LP supply seeded by the initial deposit
Configurable parameters (lock period, fees, delays)
Prerequisites:
Must have executed
getCreateVaultCapTxfirstNeed
coinMetadataIdandtreasuryCapIdfrom that transaction
Parameters:
walletAddress:SuiAddressVault owner/curator address
Must match the address used in
getCreateVaultCapTx
metadata: Object containing:name:string- Human-readable vault namedescription:string- Verbose vault descriptioncuratorName(optional):string- Curator's namecuratorUrl(optional):string- Curator's websitecuratorLogoUrl(optional):string- Curator's logo image URLextraFields(optional):Record<string, string>- Additional metadataRecommended keys:
twitter_url,discord_url,telegram_url
coinMetadataId:ObjectIdCoin metadata object ID from
getCreateVaultCapTxtransaction
treasuryCapId:ObjectIdTreasury cap object ID from
getCreateVaultCapTxtransaction
collateralCoinType:CoinTypeCollateral coin type (must match vault cap)
lockPeriodMs:bigintLock-in period for deposits in milliseconds
Depositors must wait this long before withdrawing
Maximum: 2 months (5,184,000,000 ms)
performanceFeePercentage:PercentageFraction of profits taken as curator fee (0 to 0.2)
Example:
0.1= 10%Maximum: 20% (0.2)
forceWithdrawDelayMs:bigintDelay before forced withdrawals can be processed
In milliseconds
Maximum: 1 day (86,400,000 ms)
tx(optional):TransactionOptional existing transaction to extend
isSponsoredTx(optional):booleanWhether this transaction is gas-sponsored
Initial Deposit (choose one):
initialDepositAmount:BalanceDeposit amount in base units
API will select/merge coins as needed
initialDepositCoinArg:TransactionObjectArgumentTransaction object argument for deposit coin
Use when you have a coin arg from previous tx commands
Returns:
SdkTransactionResponse containing:
tx:Transaction- Transaction ready to sign and execute
Example:
Use Cases:
Vault Deployment: Launch new trading vaults
Strategy Diversification: Create vaults with different risk profiles
Curator Platform: Enable users to become vault managers
Institutional Offering: Deploy managed trading products
getTransferCapTx
Build a transfer-cap transaction that transfers a Perpetuals capability object to another wallet.
What This Does:
Transfers ownership of a perpetuals capability (account cap or vault cap) to a different wallet address. This changes the controlling wallet for the account or vault.
This action is irreversible without access to the recipientAddress. Triple check the recipientAddress before executing.
Important:
Transaction must be signed by the current cap owner
Can transfer both account caps and vault caps
Recipient immediately gains full control over the account/vault
Original owner loses all access after transfer
Transfer is permanent and cannot be undone
Parameters:
recipientAddress:SuiAddressWallet address that should receive the capability
This wallet will become the new owner
capObjectId:ObjectIdObject ID of the capability to transfer
Can be an account cap ID or vault cap ID
tx(optional):TransactionExisting transaction to extend
Returns:
Object containing:
tx:Transaction- Transaction ready to sign and execute
Example:
Use Cases:
Account Migration: Move accounts between wallets
Ownership Transfer: Transfer account/vault to new owner
Organization Changes: Transfer to new team member or entity
Estate Planning: Transfer assets to designated recipients
Account Consolidation: Move multiple accounts to single wallet
Vault Handoff: Transfer vault management to new manager
Rebate Methods
getCurrentRebateRewards
Calculates current-epoch maker and taker reward allocations.
getCsvRebates
Returns a CSV rebate report and supports owner-level aggregation.
getReferralCsvRebates
Returns the referral rebate CSV.
Builder Code Integration Methods
These methods support protocol integrators who want to earn fees on user orders. Integrators can:
Register once globally through the native API
Get users to approve them as integrators
Submit orders on behalf of users with integrator fees
One-Time Integrator Registration
The v3 SDK does not expose a high-level registration method. Register through the native API:
Registration is global rather than per market. The transaction sender is the integrator, and the protocol assigns a numeric integratorId.
getCreateBuilderCodeIntegratorConfigTx
Build a transaction to create an integrator configuration.
What This Does: Allows a user to grant permission to an integrator to receive fees on orders placed on their behalf. The user specifies the maximum integrator fee that can be charged.
Parameters:
accountId: User's numeric perpetuals account IDintegratorId: Numeric ID assigned during global integrator registrationmaxIntegratorFee: Maximum additional fee the integrator can chargeExample:
0.0005= 0.05% = 5 basis points
Example:
The transaction must be signed by the account owner.
getRemoveBuilderCodeIntegratorConfigTx
Build a transaction to remove an integrator configuration. Once revoked, orders for that account can no longer charge a fee for that integratorId.
Example:
Only the account owner can remove an integrator approval.
getBuilderCodeIntegratorConfig
Fetch integrator configuration for a specific account and integrator.
Returns:
exists: Whether the integrator is approvedmaxIntegratorFee: Maximum fee if approved; otherwisenull
Example:
Adding Builder Codes to Orders
Supported native order builders accept:
The per-order integratorFee cannot exceed the user's approved maxIntegratorFee. SL/TP and stop orders can carry their own builder code independently of the parent order.
The previous per-market integrator vaults and fee-claim flow have been removed. Do not use getCreateBuilderCodeIntegratorVaultTx, getClaimBuilderCodeIntegratorVaultFeesTx, or getBuilderCodeIntegratorVaults against the current service.
WebSocket Methods
openUpdatesWebsocketStream
Open the main updates websocket for real-time perpetuals data: /perpetuals/ws/updates.
What This Provides: A WebSocket stream that emits PerpetualsWsUpdatesResponseMessage envelopes and supports multiple subscription types. Returns a controller with convenience subscribe/unsubscribe functions.
For raw wire-level details, see the dedicated WebSockets page. For account and execution streams, prefer these SDK helpers over hand-rolled JSON because the helper methods encapsulate the current subscription payloads and optional auth material.
Supported Subscription Types:
market: Market state updates (prices, funding rates)
user: User account updates (optionally including stop orders)
oracle: Oracle price updates
orderbook: Orderbook deltas (bids/asks changes)
marketOrders: Public market trades/orders
userOrders: User-specific trade/order events
userCollateralChanges: User collateral change events
topOfOrderbook: Bucketed top-of-book snapshots
marketCandles: Live candles using timeframe labels
Parameters:
onMessage:(env: PerpetualsWsUpdatesResponseMessage) => voidHandler for parsed messages from the websocket
Called whenever a message is received
Message type varies based on subscriptions
onOpen(optional):(ev: Event) => voidHandler for the
openeventCalled when WebSocket connection establishes
onError(optional):(ev: Event) => voidHandler for the
erroreventCalled on WebSocket errors
onClose(optional):(ev: CloseEvent) => voidHandler for the
closeeventCalled when WebSocket closes
Returns:
WebSocketController object containing:
ws: UnderlyingWebSocketinstanceSubscription helpers (all methods):
subscribeMarket({ marketId })/unsubscribeMarket({ marketId })subscribeUser({ accountId, withStopOrders })/unsubscribeUser({ accountId, withStopOrders })subscribeOracle({ marketId })/unsubscribeOracle({ marketId })subscribeOrderbook({ marketId })/unsubscribeOrderbook({ marketId })subscribeMarketOrders({ marketId })/unsubscribeMarketOrders({ marketId })subscribeUserOrders({ accountId })/unsubscribeUserOrders({ accountId })subscribeUserCollateralChanges({ accountId })/unsubscribeUserCollateralChanges({ accountId })subscribeTopOfOrderbook({ marketId, priceBucketSize, bucketsNumber })/ matching unsubscribesubscribeMarketCandles({ marketId, interval })/ matching unsubscribe
close(): Close the WebSocket
Example:
Use Cases:
Live Trading Interface: Real-time price and orderbook updates
Market Monitoring: Track multiple markets simultaneously
Trading Bots: Receive order and position updates
Analytics Dashboard: Real-time market data visualization
openMarketCandlesWebsocketStream
This helper connects to the unified /api/perpetuals/ws/updates socket and subscribes with marketCandles. The old dedicated /ws/market-candles/{market_id}/{interval_ms} route no longer exists.
Authenticated user subscriptions use the same reusable terms signature as stop-order and TWAP reads. User update payloads can include both stopOrders and twapOrders.
Use subscribeMarketCandles({ marketId, interval }) on the controller returned by openUpdatesWebsocketStream when you want candles multiplexed with other subscriptions.
Static Helper Methods
These methods provide utility functions for price/size conversion and order parsing.
positionSide
Determine the logical order side (Bid/Ask) from a signed base asset amount.
Logic:
Positive or zero amount = Bid (long position)
Negative amount = Ask (short position)
Parameters:
baseAssetAmount:numberPosition base size (signed)
Positive = long, Negative = short
Returns:
PerpetualsOrderSide.Bidfor long positionsPerpetualsOrderSide.Askfor short positions
Example:
orderPriceFromEvent
Compute the effective trade price from a FilledTakerOrderEvent.
Formula:
Parameters:
orderEvent:FilledTakerOrderEventFilled taker order event containing deltas
Returns:
Trade price as a number
Example:
orderPriceFromOrderId
Extract the floating-point price from an encoded order ID.
Implementation:
Uses
PerpetualsOrderUtils.price()to extract fixed-point priceConverts to float using
orderPriceToPrice()
Parameters:
orderId:PerpetualsOrderIdEncoded order ID (bigint)
Returns:
Price as a floating-point number
Example:
priceToOrderPrice
Convert a floating-point price to fixed-point order price using 9 decimal places of precision.
Precision: 9 decimals (multiply by 1e9)
Parameters:
price:numberPrice as a float
Returns:
Fixed-point order price (bigint)
Example:
orderPriceToPrice
Convert a fixed-point order price to floating-point.
Parameters:
orderPrice:PerpetualsOrderPriceFixed-point order price (bigint with 9 decimals)
Returns:
Price as a float
Example:
lotOrTickSizeToNumber
Convert fixed-point lot/tick size (9 decimals) to a number.
Parameters:
lotOrTickSize:bigintFixed-point size (9 decimal precision)
Returns:
Floating-point size
Example:
lotOrTickSizeToBigInt
Convert floating-point lot/tick size to fixed-point representation (9 decimals).
Parameters:
lotOrTickSize:numberFloating-point size
Returns:
Fixed-point size (bigint)
Example:
orderIdToSide
Infer the order side from an encoded order ID.
Implementation: Uses PerpetualsOrderUtils.isAsk() to determine side.
Parameters:
orderId:PerpetualsOrderIdEncoded order ID
Returns:
PerpetualsOrderSide.Askif ask orderPerpetualsOrderSide.Bidif bid order
Example:
eventTypeForCollateral
Construct a collateral-specialized Move event type string.
What This Does: Many Move events are generic over a collateral coin type. This helper appends <collateralCoinType> to a base eventType.
Parameters:
eventType:stringBase event type without type parameters
collateralCoinType:CoinTypeCollateral coin type
Returns:
Fully-qualified event type string
Example:
Last updated