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

Creates a new Perpetuals client instance.

Parameters:

  • config (optional): CallerConfig

    • Configuration object containing:

      • network: The Sui network ("MAINNET", "TESTNET", "DEVNET", or "LOCAL")

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

circle-info

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.

circle-info

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.

circle-info

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 marketIds array

    • Each element corresponds to the market ID at the same index

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


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.

circle-info

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

circle-info

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.

circle-info

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

circle-exclamation

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


getAccountCaps

Fetch account caps by their cap object IDs.

circle-info

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


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

  • intervalMs: number

    • Candle interval in milliseconds

    • Common intervals:

      • 60000 = 1 minute

      • 300000 = 5 minutes

      • 900000 = 15 minutes

      • 3600000 = 1 hour

      • 14400000 = 4 hours

      • 86400000 = 1 day

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


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

circle-exclamation

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


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.

circle-info

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.

circle-exclamation

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


Builder Code Integration Methods

These methods support protocol integrators who want to earn fees on user orders. Integrators can:

  1. Get users to approve them as integrators

  2. Submit orders on behalf of users with integrator fees

  3. Collect accumulated fees from vaults

circle-info

Want to learn more about Builder Codes? Read more.

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 a maximum taker fee that the integrator can charge.

Workflow:

  1. User executes this transaction to approve an integrator

  2. Integrator can then place orders for the user (via API or other means)

  3. When placing orders, integrator includes their address and fee (up to max)

  4. Integrator earns fees proportional to taker volume generated

circle-exclamation

Parameters:

  • accountId: PerpetualsAccountId

    • User's perpetuals account ID (bigint)

    • The account that will grant integrator permission

  • integratorAddress: SuiAddress

    • Integrator's wallet address

    • Address that will receive accumulated fees

  • maxTakerFee: Percentage

    • Maximum taker fee the integrator can charge (as a fraction)

    • Example: 0.001 = 0.1% = 10 basis points

    • Integrator cannot charge more than this amount

Returns:

SdkTransactionResponse containing:

  • tx: Transaction - Transaction ready for user to sign

Example:

Use Cases:

  1. Trading Platform Integration: Allow platforms to charge fees

  2. Referral Programs: Enable fee-sharing with referrers

  3. White-Label Solutions: Build branded trading interfaces with revenue share

  4. API Access: Grant programmatic trading access with fee collection


getRemoveBuilderCodeIntegratorConfigTx

Build 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

circle-exclamation

Parameters:

  • accountId: PerpetualsAccountId

    • User's perpetuals account ID

    • Account to remove integrator approval from

  • integratorAddress: SuiAddress

    • Integrator's wallet address to revoke

Returns:

SdkTransactionResponse containing:

  • tx: Transaction - Transaction ready for user to sign

Example:

Use Cases:

  1. Permission Management: Revoke untrusted integrators

  2. Platform Migration: Remove old platform approvals

  3. Security: Revoke access if integrator is compromised

  4. Fee Negotiation: Remove to renegotiate terms


getCreateBuilderCodeIntegratorVaultTx

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

  1. Integrator executes this transaction (once per market)

  2. Vault is created on-chain for that market

  3. As integrator submits orders, fees accumulate in the vault

  4. Integrator can later claim fees using getClaimBuilderCodeIntegratorVaultFeesTx

circle-exclamation

Parameters:

  • marketId: PerpetualsMarketId

    • Market (clearing house) to create vault for

    • One vault needed per market

  • integratorAddress: SuiAddress

    • Integrator's wallet address

    • Owner of the fee vault

Returns:

SdkTransactionResponse containing:

  • tx: Transaction - Transaction ready for integrator to sign

Example:

Use Cases:

  1. Integrator Onboarding: Initialize fee collection infrastructure

  2. Multi-Market Setup: Create vaults for all active markets

  3. New Market Support: Add vault when new market launches

  4. Platform Expansion: Enable fee collection across markets


getClaimBuilderCodeIntegratorVaultFeesTx

Build 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: PerpetualsMarketId

    • Market to claim fees from

    • Must have a vault created via getCreateBuilderCodeIntegratorVaultTx

  • integratorAddress: SuiAddress

    • Integrator's wallet address

    • Must be the vault owner

  • recipientAddress (optional): SuiAddress

    • Address 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 kind

  • coinOutArg (optional): Transaction argument for the claimed coin

    • Only present if recipientAddress not provided

    • Can be used in subsequent transaction commands

Example:

Use Cases:

  1. Revenue Collection: Claim earned fees from trading volume

  2. Automated Claiming: Set up scheduled fee collection

  3. Multi-Market Claiming: Collect fees across all markets

  4. Fee Compounding: Reinvest fees into other protocols


getBuilderCodeIntegratorConfig

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

    • Account ID to check integrator approval for

  • integratorAddress: SuiAddress

    • Integrator address to check

Returns:

ApiPerpetualsBuilderCodesIntegratorConfigResponse containing:

  • exists: boolean - Whether integrator is approved

  • maxTakerFee: number - Maximum fee if approved (otherwise may be 0 or undefined)

Example:

Use Cases:

  1. Permission Verification: Check approval before submitting orders

  2. UI Display: Show approved integrators and their fee caps

  3. Fee Validation: Ensure requested fees don't exceed approved max

  4. Integrator Dashboard: Display approval status across accounts


getBuilderCodeIntegratorVaults

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

  1. Integrator submits orders for users (who have approved them)

  2. Orders execute and generate taker volume

  3. Fees (percentage of volume) accumulate in per-market vaults

  4. Integrator can claim anytime using getClaimBuilderCodeIntegratorVaultFeesTx

Parameters:

  • marketIds: PerpetualsMarketId[]

    • Markets to query fees for

    • One vault exists per market

  • integratorAddress: SuiAddress

    • Integrator's wallet address

Returns:

ApiPerpetualsBuilderCodesIntegratorVaultsResponse containing:

  • integratorVaults: Array of vault data objects

    • One entry per market

    • Each object contains:

      • marketId: Market identifier

      • fees: Accumulated fees in collateral units

      • Other vault metadata

Example:

Use Cases:

  1. Revenue Tracking: Monitor total earned fees

  2. Fee Dashboard: Display claimable fees per market

  3. Claiming Strategy: Identify which markets to claim from

  4. Performance Analysis: Analyze fee generation across markets


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.

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

  • 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

Open 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: PerpetualsMarketId

    • Market ID to subscribe to

    • Only candles for this market are emitted

  • intervalMs: number

    • Candle interval in milliseconds

    • Common intervals:

      • 60000 = 1 minute

      • 300000 = 5 minutes

      • 900000 = 15 minutes

      • 3600000 = 1 hour

      • 86400000 = 1 day

  • onMessage: (msg: PerpetualsWsCandleResponseMessage) => void

    • Handler for incoming candle updates

    • Called when a new candle is available

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

    • Handler for the open event

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

    • Handler for the error event

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

    • Handler for the close event

Returns:

WebSocketController object containing:

  • ws: Underlying WebSocket instance

  • close(): Close the WebSocket

Example:

Use Cases:

  1. Live Charts: Real-time price chart updates

  2. Price Alerts: Trigger notifications on price movements

  3. Multi-Timeframe Analysis: Monitor multiple intervals simultaneously

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

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