For the complete documentation index, see llms.txt. This page is also available as Markdown.

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): CallerConfig

    • Configuration object containing:

      • network: Use "MAINNET" for Aftermath Perpetuals

      • accessToken: Optional authentication token

      • Other caller-specific settings

  • Provider (optional): AftermathApi

    • Shared provider instance used for transaction building

    • When provided, transaction builder methods can derive serialized txKind from Transaction objects

    • Enables the Provider.Transactions().fetchBase64TxKindFromTx() functionality

Remarks:

  • This class extends Caller with the "perpetuals" route prefix

  • HTTP 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 ID

  • isAsk(orderId: PerpetualsOrderId): boolean - Determine if an order is an ask (sell) order

  • Additional order parsing utilities

Example:


Market Discovery Methods

getAllMarkets

Fetch 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: CoinType

    • The 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:

  1. Market Discovery: List all available markets for a collateral type

  2. Price Comparison: Compare prices across different markets

  3. Market Selection: Let users choose which market to trade

  4. Dashboard Display: Show market overview with key metrics


getMarket

Fetch a single market by its ID.

Internally calls getMarkets with a single-element array and returns the first entry.

Parameters:

  • marketId: PerpetualsMarketId (which is ObjectId)

    • The market (clearing house) object ID on the Sui blockchain

    • This is the unique identifier for the market

    • Format: 32-byte hex string with 0x prefix

Returns:

Object containing:

  • market: PerpetualsMarket

    • Single 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 return markets[0] which would be undefined

  • Callers should validate the result to ensure the market exists

Example:

Use Cases:

  1. Direct Market Access: When you know the exact market ID

  2. Deep Linking: Navigate directly to a specific market

  3. Market Refresh: Update data for a single market

  4. Trading Interface: Display detailed market information


getMarkets

Fetch multiple markets by their IDs in a single API call.

The production route returns marketDatas[], and the SDK constructs each PerpetualsMarket from marketDatas[].market. Static metadata is nullable, including displayName. The current OpenAPI response component for this route is stale and incorrectly describes orderbooks.

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:

  1. Batch Fetching: Efficiently fetch multiple markets at once

  2. Multi-Market Display: Show data for several markets simultaneously

  3. Comparison Tools: Compare metrics across different markets

  4. 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:

  1. Vault Discovery: Browse all available vaults

  2. Investment Research: Compare vault strategies and fees

  3. LP Dashboard: Display vault metrics for liquidity providers

  4. Curator Analytics: Analyze vault ecosystem


getVault

Fetch a single vault by its object ID.

Internally calls getVaults with a single-element array and returns the first entry.

Parameters:

  • vaultId: ObjectId

    • The vault's unique, onchain identifier

    • Format: 32-byte hex string with 0x prefix

Returns:

Object containing:

  • vault: PerpetualsVault

    • Single wrapped vault instance

    • Provides access to vault configuration, trading account, and transaction builders

Example:

Use Cases:

  1. Direct Vault Access: When you know the exact vault ID

  2. Vault Detail Page: Display comprehensive vault information

  3. LP Portfolio: Show vault details for deposited vaults

  4. 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:

  1. Batch Vault Fetching: Efficiently fetch multiple vaults

  2. Portfolio Management: Display all vaults where user has deposits

  3. Comparison Tools: Compare multiple vault strategies

  4. 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

Internally calls getAccounts with a single-element array and returns the first entry.

Parameters:

  • accountCap: PerpetualsAccountCap | PerpetualsPartialVaultCap

    • Account cap or partial vault cap object to derive account metadata from

    • Contains: accountId, collateralCoinType, accountObjectId

    • Obtained 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: PerpetualsAccount

    • Wrapped account instance with:

      • Account snapshot (positions, balances, equity)

      • Ownership/cap metadata

      • Transaction builder methods

      • Helper functions

Example:

Use Cases:

  1. Account Dashboard: Display user's account overview

  2. Trading Interface: Access account for placing orders

  3. Portfolio Management: View all positions and balances

  4. Position Monitoring: Check margin ratios and PnL


getAccounts

Fetch one or more accounts (positions + account objects) from account caps.

How it Works:

  1. Calls getAccountObjects() to fetch raw account data by account IDs

  2. Locally pairs returned account objects with input accountCaps

  3. Constructs PerpetualsAccount instances 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 accountCaps

    • Each element corresponds to the cap at the same index

Example:

Use Cases:

  1. Multi-Account Dashboard: Display all user accounts

  2. Portfolio Aggregation: Calculate total portfolio metrics

  3. Account Comparison: Compare performance across accounts

  4. 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.

Difference from getAccounts:

  • getAccountObjects: Takes account IDs, returns raw data structures

  • getAccounts: Takes account caps, returns wrapped PerpetualsAccount instances

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 ID

      • positions: Array of position data

      • availableCollateral: Free collateral amount

      • totalEquity: Total account equity

      • Other account state fields

Edge Cases:

  • If accountIds is empty, returns { accounts: [] } without making an API call

Example:

Use Cases:

  1. Low-Level Data Access: When you need raw account data

  2. Custom Integrations: Building custom account wrappers

  3. Analytics: Processing account data for reports

  4. 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

Parameters:

  • walletAddress: SuiAddress

    • Owner wallet address to query

    • Must be a valid Sui address (32-byte hex with 0x prefix)

    • 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 ID

      • accountId: Numeric account ID

      • accountObjectId: Account object ID

      • collateralCoinType: Collateral type

      • walletAddress: Owner address

Example:

Use Cases:

  1. Account Discovery: Find all accounts owned by a user

  2. Wallet Integration: List user's trading accounts

  3. Multi-Account Management: Display account switcher

  4. 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: SuiAddress

    • Owner 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 ID

      • vaultId: Vault object ID

      • accountId: Vault's trading account ID

      • accountObjectId: Account object ID

      • collateralCoinType: Vault's collateral type

      • ownerAddress: Vault owner address

Example:

Use Cases:

  1. Vault Management: Find vaults owned/managed by a curator

  2. Curator Dashboard: Display all managed vaults

  3. Administrative Access: Verify vault ownership before operations

  4. 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: SuiAddress

    • Wallet 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 ID

      • vaultId: Vault being withdrawn from

      • lpCoinAmount: Amount of LP coins to burn

      • minCollateralAmountOut: Minimum collateral to receive

      • createdAt: Timestamp when request was created

      • userAddress: User who created the request

Example:

Use Cases:

  1. Withdrawal Tracking: Monitor pending vault withdrawals

  2. User Dashboard: Display withdrawal request status

  3. Request Management: Update or cancel pending requests

  4. 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: SuiAddress

    • Owner 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 ID

      • vaultId: Vault the coin belongs to

      • balance: Amount of LP coins

      • coinType: Full coin type (includes vault ID)

Example:

Use Cases:

  1. Portfolio Display: Show user's vault investments

  2. Withdrawal Planning: Determine available LP coins for withdrawal

  3. Performance Tracking: Calculate investment value over time

  4. Asset Management: Monitor vault allocations


getAdminAccountCaps

Fetch account caps by their cap object IDs.

Difference from getOwnedAccountCaps:

  • getOwnedAccountCaps: Queries by wallet address (finds all caps owned by an address)

  • getAdminAccountCaps: 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 0x prefix

Returns:

ApiPerpetualsAccountCapsResponse containing:

  • accountCaps: PerpetualsAccountCap[]

    • Array of account cap objects

    • Returned in the same order as input accountCapIds

    • Each cap contains full ownership and metadata

Example:

Use Cases:

  1. Direct Cap Lookup: When you have stored cap IDs

  2. Deep Linking: Navigate to account from cap ID in URL

  3. Cached References: Fetch caps from persistent storage

  4. 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: PerpetualsMarketId

    • Market ID to query candle history for

    • Must be a valid market object ID

  • fromTimestamp: Timestamp

    • Start timestamp in milliseconds (inclusive)

    • Unix epoch time (e.g., Date.now())

    • Data begins from this time

  • toTimestamp: Timestamp

    • End timestamp in milliseconds (exclusive)

    • Unix epoch time

    • Data ends before this time

  • resolution: PerpetualsCandleResolution

    • Candle interval as a timeframe label

    • Supported values: 1m, 5m, 15m, 30m, 1h, 4h, 12h, 1d, 3d, 1w, and 1mo

Returns:

ApiPerpetualsMarketCandleHistoryResponse containing:

  • candles: PerpetualsMarketCandleDataPoint[]

    • Array of candle data points

    • Each candle contains:

      • timestamp: Candle start time

      • open: Opening price

      • high: Highest price

      • low: Lowest price

      • close: Closing price

      • volume: Trading volume

    • Sorted chronologically (oldest to newest)

Example:

Use Cases:

  1. Chart Visualization: Display price charts with OHLC data

  2. Technical Analysis: Calculate indicators (SMA, EMA, RSI, etc.)

  3. Historical Performance: Analyze price movements over time

  4. 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 identifier

      • volume24h: Trading volume in last 24h

      • priceChange24h: Price change percentage

      • priceChangeAbsolute24h: Absolute price change

      • high24h: Highest price

      • low24h: Lowest price

      • open24h: Opening price

      • close24h: Closing price (most recent)

      • trades24h: Number of trades

Example:

Use Cases:

  1. Market Overview Dashboard: Display 24h performance metrics

  2. Top Movers: Show biggest gainers/losers

  3. Volume Analysis: Identify most liquid markets

  4. 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 objects

    • One entry per input market ID

    • Each object contains:

      • marketId: Market identifier

      • basePrice: Oracle price of base asset

      • collateralPrice: Price of collateral asset

Example:

Use Cases:

  1. Position Valuation: Calculate current position values

  2. PnL Calculation: Determine unrealized profits/losses

  3. Price Monitoring: Track oracle price movements

  4. 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 objects

    • One entry per input vault ID

    • Each object contains:

      • vaultId: Vault identifier

      • priceInCollateral: Price of one LP coin in collateral units

      • timestamp: When price was calculated

Example:

Use Cases:

  1. Portfolio Valuation: Calculate total vault investment value

  2. Performance Tracking: Monitor vault returns over time

  3. Withdrawal Planning: Estimate collateral received when withdrawing

  4. 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

Parameters:

  • walletAddress: SuiAddress

    • Wallet 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 0x prefix)

  • collateralCoinType: CoinType

    • Collateral 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): Transaction

    • Optional existing transaction to extend

    • If provided, create-account commands are appended to this transaction

    • Useful for batching multiple operations

Returns:

SdkTransactionResponse containing:

  • tx: Transaction

    • Transaction object ready to be signed and executed

    • Contains the create-account command

    • Can be further modified before signing

Example:

Use Cases:

  1. User Onboarding: Create first trading account for new users

  2. Multi-Collateral Setup: Create accounts for different collateral types

  3. Wallet Integration: Build account creation flow in dApp

  4. 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.

This is step 1 of 2 for vault creation. After executing this transaction, use the returned object IDs to call getCreateVaultTx.

Parameters:

  • walletAddress: SuiAddress

    • Vault owner/curator address

    • Will receive the vault cap NFT

    • Must be a valid Sui address

  • collateralCoinType: CoinType

    • Collateral coin type for the vault

    • Vault will only accept this collateral type

    • Example: "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC"

Returns:

SdkTransactionResponse containing:

  • tx: Transaction

    • Transaction object ready to sign and execute

    • After execution, extract coinMetadataId and treasuryCapId from transaction effects

Example:

Use Cases:

  1. Vault Creation: First step in creating a new vault

  2. Curator Onboarding: Set up new vault managers

  3. 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 getCreateVaultCapTx first

  • Need coinMetadataId and treasuryCapId from that transaction

Parameters:

  • walletAddress: SuiAddress

    • Vault owner/curator address

    • Must match the address used in getCreateVaultCapTx

  • metadata: Object containing:

    • name: string - Human-readable vault name

    • description: string - Verbose vault description

    • curatorName (optional): string - Curator's name

    • curatorUrl (optional): string - Curator's website

    • curatorLogoUrl (optional): string - Curator's logo image URL

    • extraFields (optional): Record<string, string> - Additional metadata

      • Recommended keys: twitter_url, discord_url, telegram_url

  • coinMetadataId: ObjectId

    • Coin metadata object ID from getCreateVaultCapTx transaction

  • treasuryCapId: ObjectId

    • Treasury cap object ID from getCreateVaultCapTx transaction

  • collateralCoinType: CoinType

    • Collateral coin type (must match vault cap)

  • lockPeriodMs: bigint

    • Lock-in period for deposits in milliseconds

    • Depositors must wait this long before withdrawing

    • Maximum: 2 months (5,184,000,000 ms)

  • performanceFeePercentage: Percentage

    • Fraction of profits taken as curator fee (0 to 0.2)

    • Example: 0.1 = 10%

    • Maximum: 20% (0.2)

  • forceWithdrawDelayMs: bigint

    • Delay before forced withdrawals can be processed

    • In milliseconds

    • Maximum: 1 day (86,400,000 ms)

  • tx (optional): Transaction

    • Optional existing transaction to extend

  • isSponsoredTx (optional): boolean

    • Whether this transaction is gas-sponsored

  • Initial Deposit (choose one):

    • initialDepositAmount: Balance

      • Deposit amount in base units

      • API will select/merge coins as needed

    • initialDepositCoinArg: TransactionObjectArgument

      • Transaction 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:

  1. Vault Deployment: Launch new trading vaults

  2. Strategy Diversification: Create vaults with different risk profiles

  3. Curator Platform: Enable users to become vault managers

  4. 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.

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: SuiAddress

    • Wallet address that should receive the capability

    • This wallet will become the new owner

  • capObjectId: ObjectId

    • Object ID of the capability to transfer

    • Can be an account cap ID or vault cap ID

  • tx (optional): Transaction

    • Existing transaction to extend

Returns:

Object containing:

  • tx: Transaction - Transaction ready to sign and execute

Example:

Use Cases:

  1. Account Migration: Move accounts between wallets

  2. Ownership Transfer: Transfer account/vault to new owner

  3. Organization Changes: Transfer to new team member or entity

  4. Estate Planning: Transfer assets to designated recipients

  5. Account Consolidation: Move multiple accounts to single wallet

  6. 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:

  1. Register once globally through the native API

  2. Get users to approve them as integrators

  3. Submit orders on behalf of users with integrator fees

Want to learn more about Builder Codes? Read more.

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 ID

  • integratorId: Numeric ID assigned during global integrator registration

  • maxIntegratorFee: Maximum additional fee the integrator can charge

    • Example: 0.0005 = 0.05% = 5 basis points

Example:


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:


getBuilderCodeIntegratorConfig

Fetch integrator configuration for a specific account and integrator.

Returns:

  • exists: Whether the integrator is approved

  • maxIntegratorFee: Maximum fee if approved; otherwise null

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.


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) => void

    • Handler for parsed messages from the websocket

    • Called whenever a message is received

    • Message type varies based on subscriptions

  • onOpen (optional): (ev: Event) => void

    • Handler for the open event

    • Called when WebSocket connection establishes

  • onError (optional): (ev: Event) => void

    • Handler for the error event

    • Called on WebSocket errors

  • onClose (optional): (ev: CloseEvent) => void

    • Handler for the close event

    • Called when WebSocket closes

Returns:

WebSocketController object containing:

  • ws: Underlying WebSocket instance

  • Subscription 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 unsubscribe

    • subscribeMarketCandles({ marketId, interval }) / matching unsubscribe

  • close(): Close the WebSocket

Example:

Use Cases:

  1. Live Trading Interface: Real-time price and orderbook updates

  2. Market Monitoring: Track multiple markets simultaneously

  3. Trading Bots: Receive order and position updates

  4. 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: number

    • Position base size (signed)

    • Positive = long, Negative = short

Returns:

  • PerpetualsOrderSide.Bid for long positions

  • PerpetualsOrderSide.Ask for short positions

Example:


orderPriceFromEvent

Compute the effective trade price from a FilledTakerOrderEvent.

Formula:

Parameters:

  • orderEvent: FilledTakerOrderEvent

    • Filled 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 price

  • Converts to float using orderPriceToPrice()

Parameters:

  • orderId: PerpetualsOrderId

    • Encoded 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: number

    • Price as a float

Returns:

  • Fixed-point order price (bigint)

Example:


orderPriceToPrice

Convert a fixed-point order price to floating-point.

Parameters:

  • orderPrice: PerpetualsOrderPrice

    • Fixed-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: bigint

    • Fixed-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: number

    • Floating-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: PerpetualsOrderId

    • Encoded order ID

Returns:

  • PerpetualsOrderSide.Ask if ask order

  • PerpetualsOrderSide.Bid if 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: string

    • Base event type without type parameters

  • collateralCoinType: CoinType

    • Collateral coin type

Returns:

  • Fully-qualified event type string

Example:

Last updated