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
Integrator fee management and collection
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 = new Aftermath("MAINNET");
await afSdk.init();
const perps = afSdk.Perpetuals();Constructor
constructor
constructorCreates a new Perpetuals client instance.
Parameters:
config(optional):CallerConfigConfiguration object containing:
network: The Sui network ("MAINNET", "TESTNET", "DEVNET", or "LOCAL")accessToken: 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
OrderUtilsHelper 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
getAllMarketsFetch all perpetual markets for a given collateral coin type.
This method returns wrapped PerpetualsMarket instances, not raw market structs. Each instance provides additional helpers for pricing, margin calculations, and order parsing.
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
getMarketFetch a single market by its ID.
Internally calls getMarkets with a single-element array and returns the first entry.
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
getMarketsFetch multiple markets by their IDs in a single API call.
The API supports returning orderbooks along with market data. This SDK currently constructs PerpetualsMarket instances from the returned marketDatas[].market field.
Parameters:
marketIds:PerpetualsMarketId[]Array of market object IDs to fetch
Can include any number of market IDs
Order is preserved in the response
Returns:
Object containing:
markets:PerpetualsMarket[]Array of wrapped market instances
Returned in the same order as the input
marketIdsarrayEach element corresponds to the market ID at the same index
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
Vault Discovery Methods
getAllVaults
getAllVaultsFetch 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
getVaultFetch a single vault by its object ID.
Internally calls getVaults with a single-element array and returns the first entry.
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
getVaultsFetch 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
getAccountConvenience 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
Internally calls getAccounts with a single-element array and returns the first entry.
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
getAccountsFetch 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
getAccountObjectsFetch raw account objects (including positions) for one or more account IDs. This is the lower-level primitive used by getAccounts.
Difference from getAccounts:
getAccountObjects: Takes account IDs, returns raw data structuresgetAccounts: Takes account caps, returns wrappedPerpetualsAccountinstances
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
getOwnedAccountCapsFetch 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
getOwnedVaultCapsFetch 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
getOwnedVaultWithdrawRequestsFetch 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
getOwnedVaultLpCoinsFetch 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
getAccountCaps
getAccountCapsFetch account caps by their cap object IDs.
Difference from getOwnedAccountCaps:
getOwnedAccountCaps: Queries by wallet address (finds all caps owned by an address)getAccountCaps: Queries by cap object IDs (direct lookup)
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
Historical Data & Statistics Methods
getMarketCandleHistory
getMarketCandleHistoryFetch 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
intervalMs:numberCandle interval in milliseconds
Common intervals:
60000= 1 minute300000= 5 minutes900000= 15 minutes3600000= 1 hour14400000= 4 hours86400000= 1 day
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
getMarkets24hrStats
getMarkets24hrStatsFetch 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
getPricesFetch 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
getLpCoinPricesFetch 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
getCreateAccountTxBuild 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
getCreateVaultCapTx
getCreateVaultCapTxBuild 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.
This is step 1 of 2 for vault creation. After executing this transaction, use the returned object IDs to call 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
getCreateVaultTxBuild 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
getTransferCapTxBuild 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
Builder Code Integration Methods
These methods support protocol integrators who want to earn fees on user orders. Integrators can:
Get users to approve them as integrators
Submit orders on behalf of users with integrator fees
Collect accumulated fees from vaults
Want to learn more about Builder Codes? Read more.
getCreateBuilderCodeIntegratorConfigTx
getCreateBuilderCodeIntegratorConfigTxBuild 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 a maximum taker fee that the integrator can charge.
Workflow:
User executes this transaction to approve an integrator
Integrator can then place orders for the user (via API or other means)
When placing orders, integrator includes their address and fee (up to max)
Integrator earns fees proportional to taker volume generated
The transaction must be signed by the account owner.
Parameters:
accountId:PerpetualsAccountIdUser's perpetuals account ID (bigint)
The account that will grant integrator permission
integratorAddress:SuiAddressIntegrator's wallet address
Address that will receive accumulated fees
maxTakerFee:PercentageMaximum taker fee the integrator can charge (as a fraction)
Example:
0.001= 0.1% = 10 basis pointsIntegrator cannot charge more than this amount
Returns:
SdkTransactionResponse containing:
tx:Transaction- Transaction ready for user to sign
Example:
Use Cases:
Trading Platform Integration: Allow platforms to charge fees
Referral Programs: Enable fee-sharing with referrers
White-Label Solutions: Build branded trading interfaces with revenue share
API Access: Grant programmatic trading access with fee collection
getRemoveBuilderCodeIntegratorConfigTx
getRemoveBuilderCodeIntegratorConfigTxBuild a transaction to remove an integrator configuration.
What This Does: Removes an integrator's approval to collect fees on orders placed on behalf of the user. Once revoked:
Integrator can no longer submit orders with integrator fees
User can re-approve the integrator later if desired
Existing accumulated fees can still be claimed by integrator
The transaction must be signed by the account owner.
Parameters:
accountId:PerpetualsAccountIdUser's perpetuals account ID
Account to remove integrator approval from
integratorAddress:SuiAddressIntegrator's wallet address to revoke
Returns:
SdkTransactionResponse containing:
tx:Transaction- Transaction ready for user to sign
Example:
Use Cases:
Permission Management: Revoke untrusted integrators
Platform Migration: Remove old platform approvals
Security: Revoke access if integrator is compromised
Fee Negotiation: Remove to renegotiate terms
getCreateBuilderCodeIntegratorVaultTx
getCreateBuilderCodeIntegratorVaultTxBuild a transaction to initialize an integrator fee vault for a specific market.
What This Does: Creates a vault where an integrator's fees will accumulate for a specific market (clearing house). This is a one-time setup operation that must be performed before the integrator can claim fees from that market.
Workflow:
Integrator executes this transaction (once per market)
Vault is created on-chain for that market
As integrator submits orders, fees accumulate in the vault
Integrator can later claim fees using
getClaimBuilderCodeIntegratorVaultFeesTx
The transaction must be signed by the integrator.
Parameters:
marketId:PerpetualsMarketIdMarket (clearing house) to create vault for
One vault needed per market
integratorAddress:SuiAddressIntegrator's wallet address
Owner of the fee vault
Returns:
SdkTransactionResponse containing:
tx:Transaction- Transaction ready for integrator to sign
Example:
Use Cases:
Integrator Onboarding: Initialize fee collection infrastructure
Multi-Market Setup: Create vaults for all active markets
New Market Support: Add vault when new market launches
Platform Expansion: Enable fee collection across markets
getClaimBuilderCodeIntegratorVaultFeesTx
getClaimBuilderCodeIntegratorVaultFeesTxBuild a transaction to claim accumulated integrator fees from a vault.
What This Does: Allows an integrator to claim the fees they have earned from orders placed on behalf of users. Fees accumulate in a vault specific to each market and can be claimed at any time.
How Fees Work:
Fees are proportional to taker volume generated by users' orders
Integrator specifies fee when submitting orders (up to user-approved max)
Fees accumulate automatically in the vault
Can be claimed at any time by the integrator
Parameters:
marketId:PerpetualsMarketIdMarket to claim fees from
Must have a vault created via
getCreateBuilderCodeIntegratorVaultTx
integratorAddress:SuiAddressIntegrator's wallet address
Must be the vault owner
recipientAddress(optional):SuiAddressAddress to receive claimed fees
If provided: fees automatically transferred to recipient
If omitted: coin output exposed as transaction argument for further use
Returns:
ApiPerpetualsBuilderCodesClaimIntegratorVaultFeesTxResponse containing:
txKind: Transaction kindcoinOutArg(optional): Transaction argument for the claimed coinOnly present if
recipientAddressnot providedCan be used in subsequent transaction commands
Example:
Use Cases:
Revenue Collection: Claim earned fees from trading volume
Automated Claiming: Set up scheduled fee collection
Multi-Market Claiming: Collect fees across all markets
Fee Compounding: Reinvest fees into other protocols
getBuilderCodeIntegratorConfig
getBuilderCodeIntegratorConfigFetch integrator configuration for a specific account and integrator.
What This Queries: Whether an integrator has been approved by an account to collect fees on orders placed on behalf of the account. If approved, returns the maximum taker fee the integrator is authorized to charge.
Use Cases:
Verify integrator permissions before placing orders
Display authorized integrators in UIs
Validate requested fees don't exceed approved maximum
Parameters:
accountId:PerpetualsAccountIdAccount ID to check integrator approval for
integratorAddress:SuiAddressIntegrator address to check
Returns:
ApiPerpetualsBuilderCodesIntegratorConfigResponse containing:
exists:boolean- Whether integrator is approvedmaxTakerFee:number- Maximum fee if approved (otherwise may be 0 or undefined)
Example:
Use Cases:
Permission Verification: Check approval before submitting orders
UI Display: Show approved integrators and their fee caps
Fee Validation: Ensure requested fees don't exceed approved max
Integrator Dashboard: Display approval status across accounts
getBuilderCodeIntegratorVaults
getBuilderCodeIntegratorVaultsFetch accumulated integrator vault fees across multiple markets.
What This Queries: The total fees an integrator has earned and accumulated in their vaults across one or more markets. Integrators earn fees proportional to the taker volume generated by orders they submit on behalf of users.
How Fees Accumulate:
Integrator submits orders for users (who have approved them)
Orders execute and generate taker volume
Fees (percentage of volume) accumulate in per-market vaults
Integrator can claim anytime using
getClaimBuilderCodeIntegratorVaultFeesTx
Parameters:
marketIds:PerpetualsMarketId[]Markets to query fees for
One vault exists per market
integratorAddress:SuiAddressIntegrator's wallet address
Returns:
ApiPerpetualsBuilderCodesIntegratorVaultsResponse containing:
integratorVaults: Array of vault data objectsOne entry per market
Each object contains:
marketId: Market identifierfees: Accumulated fees in collateral unitsOther vault metadata
Example:
Use Cases:
Revenue Tracking: Monitor total earned fees
Fee Dashboard: Display claimable fees per market
Claiming Strategy: Identify which markets to claim from
Performance Analysis: Analyze fee generation across markets
WebSocket Methods
openUpdatesWebsocketStream
openUpdatesWebsocketStreamOpen 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.
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
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 })
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
openMarketCandlesWebsocketStreamOpen a market-candles websocket stream for a single market/interval: /perpetuals/ws/market-candles/{market_id}/{interval_ms}.
What This Provides: A WebSocket stream that emits PerpetualsWsCandleResponseMessage messages, typically containing the latest candle for the specified interval.
Parameters:
marketId:PerpetualsMarketIdMarket ID to subscribe to
Only candles for this market are emitted
intervalMs:numberCandle interval in milliseconds
Common intervals:
60000= 1 minute300000= 5 minutes900000= 15 minutes3600000= 1 hour86400000= 1 day
onMessage:(msg: PerpetualsWsCandleResponseMessage) => voidHandler for incoming candle updates
Called when a new candle is available
onOpen(optional):(ev: Event) => voidHandler for the
openevent
onError(optional):(ev: Event) => voidHandler for the
errorevent
onClose(optional):(ev: CloseEvent) => voidHandler for the
closeevent
Returns:
WebSocketController object containing:
ws: UnderlyingWebSocketinstanceclose(): Close the WebSocket
Example:
Use Cases:
Live Charts: Real-time price chart updates
Price Alerts: Trigger notifications on price movements
Multi-Timeframe Analysis: Monitor multiple intervals simultaneously
Trading Bots: React to candle closes for strategy execution
Static Helper Methods
These methods provide utility functions for price/size conversion and order parsing.
positionSide
positionSideDetermine 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
orderPriceFromEventCompute the effective trade price from a FilledTakerOrderEvent.
Formula:
Parameters:
orderEvent:FilledTakerOrderEventFilled taker order event containing deltas
Returns:
Trade price as a number
Example:
orderPriceFromOrderId
orderPriceFromOrderIdExtract 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
priceToOrderPriceConvert 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
orderPriceToPriceConvert 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
lotOrTickSizeToNumberConvert fixed-point lot/tick size (9 decimals) to a number.
Parameters:
lotOrTickSize:bigintFixed-point size (9 decimal precision)
Returns:
Floating-point size
Example:
lotOrTickSizeToBigInt
lotOrTickSizeToBigIntConvert floating-point lot/tick size to fixed-point representation (9 decimals).
Parameters:
lotOrTickSize:numberFloating-point size
Returns:
Fixed-point size (bigint)
Example:
orderIdToSide
orderIdToSideInfer 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
eventTypeForCollateralConstruct 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