aftermath-ts-sdk - v3.3.3
    Preparing search index...

    High-level client for interacting with Aftermath Perpetuals.

    This class exposes a typed, ergonomic interface over the Perpetuals HTTP API and websocket endpoints, including:

    • Market discovery (getAllMarkets, getMarkets, getMarket)
    • Vault discovery (getAllVaults, getVaults, getVault)
    • Account & position data (getAccount, getAccounts, getAccountObjects)
    • Ownership queries (getOwnedAccountCaps, getOwnedVaultCaps)
    • Historical data & stats (getMarketCandleHistory, getMarkets24hrStats)
    • Pricing helpers (getPrices, getLpCoinPrices)
    • Transaction builders (getCreateAccountTx, getCreateVaultCapTx, getCreateVaultTx)
    • Websocket feeds (openUpdatesWebsocketStream, openMarketCandlesWebsocketStream)

    Typical usage via the root SDK:

    import { Aftermath } from "@aftermath/sdk";

    const afSdk = await Aftermath.create({ network: "MAINNET" });

    const perps = afSdk.Perpetuals();

    // Fetch markets for a given collateral coin type
    const markets = await perps.getAllMarkets({
    collateralCoinType: "0x2::sui::SUI",
    });

    // Fetch account + positions for a given account cap
    const [accountCap] = await perps.getOwnedAccountCaps({
    walletAddress: "0x...",
    });

    const account = await perps.getAccount({ accountCap });

    // Build a create-account transaction (not signed or sent)
    const createAccountTx = await perps.getCreateAccountTx({
    walletAddress: "0x...",
    collateralCoinType: "0x2::sui::SUI",
    });

    Hierarchy (View Summary)

    Index

    Optional shared AftermathApi provider instance. When provided, transaction-building helpers can derive serialized txKind from a Transaction object via api.Transactions().fetchBase64TxKindFromTx.

    config: CallerConfig

    The mutable configuration used for subsequent requests.

    OrderUtils: typeof PerpetualsOrderUtils = PerpetualsOrderUtils

    Helper namespace for order-specific utilities such as parsing order IDs, extracting price bits, etc.

    This is a direct alias of PerpetualsOrderUtils.

    • Fetch all perpetual markets for a given collateral coin type.

      This method returns wrapped PerpetualsMarket instances, not the raw market structs. Each instance provides additional helpers for pricing, margin, and order parsing.

      Parameters

      • inputs: { collateralCoinType: string }
        • collateralCoinType: string

          Coin type used as collateral, e.g. "0x2::sui::SUI".

      Returns Promise<{ markets: PerpetualsMarket[] }>

      Object containing markets.

      const { markets } = await perps.getAllMarkets({
      collateralCoinType: "0x2::sui::SUI",
      });
    • Fetch all vaults on the current network.

      Vaults are managed accounts that can hold positions; LPs deposit collateral and receive an LP coin (see pricing helpers like getLpCoinPrices).

      Returns Promise<{ vaults: PerpetualsVault[] }>

      Object containing vaults.

      const { vaults } = await perps.getAllVaults();
      
    • Build a transaction to claim accumulated integrator fees from a vault.

      This endpoint creates a transaction that allows an integrator to claim the fees they have earned from orders placed on behalf of users. Fees accumulate in the integrator's global vault (across all markets) and can be claimed at any moment. The fees are proportional to the taker volume generated by the users' orders that the integrator submitted.

      If a recipientAddress is provided, the claimed fees will be automatically transferred to that address. Otherwise, the coin outputs are exposed as transaction arguments for further use in the transaction (one per non-zero collateral balance).

      The resulting transaction must be signed by the integrator and executed on-chain.

      Returns Promise<
          Omit<
              ApiPerpetualsBuilderCodesClaimIntegratorVaultFeesTxResponse,
              "txKind",
          > & { tx: Transaction },
      >

      ApiPerpetualsBuilderCodesClaimIntegratorVaultFeesTxResponse containing txKind and optionally coinOutArgs.

      // Claim with automatic transfer to recipient
      const response = await perps.getClaimBuilderCodeIntegratorVaultFeesTx({
      integratorId: 7,
      recipientAddress: "0x...",
      });

      // Claim with coin outputs for further use
      const response = await perps.getClaimBuilderCodeIntegratorVaultFeesTx({
      integratorId: 7,
      });
      // response.coinOutArgs can be used in subsequent transaction commands
    • Build a create-account transaction for Aftermath Perpetuals.

      When deferShare is true, the response includes a deferred object with accountArg, sharePolicyArg, adminCapArg, and collateralCoinType so you can compose additional commands (grant-agent-wallet, transfer-cap) before calling getShareAccountTx to finalize.

      Parameters

      • inputs: Omit<ApiPerpetualsCreateAccountBody, "txKind"> & { tx?: Transaction }
        • walletAddress

          Wallet address that will own the new account.

        • collateralCoinType

          Collateral coin type used by the account.

        • deferShare

          When true, returns deferred args without sharing yet.

        • tx

          Optional Transaction to extend.

        • Optionaltx?: Transaction

          Optional Transaction to extend.

      Returns Promise<
          Omit<ApiPerpetualsCreateAccountResponse, "txKind"> & { tx: Transaction },
      >

      tx plus optional deferred containing argument references when deferred.

    • Build a transaction to create an integrator configuration.

      This endpoint creates a transaction that allows a user to grant permission to an integrator to receive fees on orders placed on their behalf. The user specifies a maximum integrator fee that the integrator can charge. The integrator can then include their id and fee (up to the maximum) when placing orders for the user.

      The resulting transaction must be signed by the account owner and executed on-chain.

      Returns Promise<Omit<ApiTransactionResponse, "txKind"> & { tx: Transaction }>

      SdkTransactionResponse with tx.

      const tx = await perps.getCreateBuilderCodeIntegratorConfigTx({
      accountId: 123n,
      integratorId: 7,
      maxIntegratorFee: 0.001, // 0.1% max fee
      });
    • Build a create-vault transaction.

      This creates a new vault plus its on-chain metadata and initial LP supply seeded by the initial deposit.

      Deposit input:

      • Use initialDepositAmount to have the API select/merge coins as needed, OR
      • Use initialDepositCoinArg if you already have a coin argument in a larger tx.

      Metadata:

      • Stored on-chain (or in a referenced object) as part of vault creation.
      • extraFields allows forward-compatible additions (e.g. social links).

      Parameters

      • inputs: {
            coinMetadataId: string;
            collateralCoinType: string;
            forceWithdrawDelayMs: bigint;
            isSponsoredTx?: boolean;
            lockPeriodMs: bigint;
            metadata: {
                curatorLogoUrl?: string;
                curatorName?: string;
                curatorUrl?: string;
                description: string;
                extraFields?: Record<string, string>;
                name: string;
            };
            performanceFeePercentage: number;
            sponsor?: PerpetualsSponsorConfig;
            treasuryCapId: string;
            tx?: Transaction;
            walletAddress: string;
        } & (
            | { initialDepositAmount: bigint }
            | { initialDepositCoinArg: TransactionObjectArgument }
        )
        • coinMetadataId: string

          Coin metadata object id obtained from create vault cap tx

        • collateralCoinType: string

          Collateral coin type for deposits.

        • forceWithdrawDelayMs: bigint

          Delay before forced withdrawals can be processed.

        • OptionalisSponsoredTx?: boolean

          Whether this tx is sponsored (gas paid by another party).

        • lockPeriodMs: bigint

          Lock-in period for deposits in milliseconds.

        • metadata: {
              curatorLogoUrl?: string;
              curatorName?: string;
              curatorUrl?: string;
              description: string;
              extraFields?: Record<string, string>;
              name: string;
          }

          Vault display metadata (name, description, curator info).

          • OptionalcuratorLogoUrl?: string

            An image url for the Vault's curator. Ideally their logo.

          • OptionalcuratorName?: string

            The Vault curator's name.

          • OptionalcuratorUrl?: string

            A url for the Vault's curator. Ideally their website.

          • description: string

            A verbose description of the Vault.

          • OptionalextraFields?: Record<string, string>

            Extra / optional fields for future extensibility. Recommended keys include: twitter_url.

          • name: string

            A human-readable name for the Vault.

        • performanceFeePercentage: number

          Fraction of profits taken as curator fee.

        • Optionalsponsor?: PerpetualsSponsorConfig
        • treasuryCapId: string

          Treasury cap object id obtained from create vault cap tx

        • Optionaltx?: Transaction

          Optional Transaction to extend.

        • walletAddress: string

          Address of vault owner/curator.

        • { initialDepositAmount: bigint }
          • initialDepositAmount: bigint

            Initial deposit amount (mutually exclusive with initialDepositCoinArg).

        • { initialDepositCoinArg: TransactionObjectArgument }
          • initialDepositCoinArg: TransactionObjectArgument

            Transaction object argument referencing the deposit coin.

      Returns Promise<Omit<ApiTransactionResponse, "txKind"> & { tx: Transaction }>

      SdkTransactionResponse with tx.

    • Calculate rewards and rebates for one or more perpetuals accounts.

      Computes per-account maker and taker reward allocations, fee-tier rebates, and volume-based metrics. When accountIds is omitted or empty, all eligible accounts are included.

      Note: All data returned is for the current epoch only.

      Parameters

      • inputs: ApiPerpetualsCurrentRebateRewardsBody

        Request body for calculating rewards and rebates for perpetuals accounts.

        This corresponds to POST /api/perpetuals/rebates/rewards.

        Given maker and taker reward pools and a list of accounts, computes per-account reward allocations and fee-tier rebates. When accountIds is omitted or empty, all eligible accounts are included.

        Note: All data returned is for the current epoch only.

        • OptionalaccountIds?: bigint[]

          Optional account filter. Omit or pass an empty array for all eligible accounts.

        • calculationVariables: PerpetualsCalculationVariables

          Coefficients used to compute Q-scores and taker shares.

        • totalMakerRewards: number

          Total maker reward pool to distribute among eligible market makers.

        • totalTakerRewards: number

          Total taker reward pool to distribute among eligible takers.

      Returns Promise<ApiPerpetualsCurrentRebateRewardsResponse>

      ApiPerpetualsCurrentRebateRewardsResponse with per-account reward and rebate data.

      const { totalQScoreFinal, rewards } = await perps.getCurrentRebateRewards({
      totalMakerRewards: 10000,
      totalTakerRewards: 5000,
      });
    • Build a transaction that grants an Agent Wallet permission on a Perpetuals account.

      Supports two methods:

      • Method 1 (existing account): Provide accountId to look up an existing shared account.
      • Method 2 (composed flow): Provide deferred with the argument references from a deferred getCreateAccountTx call.

      Parameters

      • inputs: Omit<ApiPerpetualsGrantAgentWalletTxBody, "txKind"> & { tx?: Transaction }
        • recipientAddress

          Wallet address to receive agent permissions.

        • accountId

          Perpetuals account ID (Method 1).

        • deferred

          Deferred account args from getCreateAccountTx (Method 2).

        • tx

          Optional transaction to extend.

        • Optionaltx?: Transaction

          Optional transaction to extend.

      Returns Promise<Omit<ApiTransactionResponse, "txKind"> & { tx: Transaction }>

      Transaction response containing a tx.

    • Fetch a single market by ID.

      Internally calls getMarkets and returns the first entry.

      Parameters

      • inputs: { marketId: string }
        • marketId: string

          The market (clearing house) object ID.

      Returns Promise<{ market: PerpetualsMarket }>

      Object containing market.

      If the backend returns an empty list for the given marketId, this will still attempt to return markets[0] (which would be undefined). Callers may want to validate the result.

      const { market } = await perps.getMarket({ marketId: "0x..." });
      
    • Fetch multiple markets by ID.

      Backend note:

      • The API supports returning orderbooks. This SDK currently constructs PerpetualsMarket from the returned marketDatas[].market.

      Parameters

      • inputs: { marketIds: string[] }
        • marketIds: string[]

          Array of market object IDs to fetch.

      Returns Promise<{ markets: PerpetualsMarket[] }>

      Object containing markets in the same order as marketIds.

      const { markets } = await perps.getMarkets({
      marketIds: ["0x..A", "0x..B"],
      });
    • Fetch the latest prices for one or more markets.

      Returns base, collateral, order book mid, and mark prices for each requested market.

      Parameters

      • inputs: { marketIds: string[] }
        • marketIds: string[]

          List of market IDs to query.

      Returns Promise<ApiPerpetualsMarketsPricesResponse>

      ApiPerpetualsMarketsPricesResponse containing marketsPrices.

      If marketIds is empty, returns { marketsPrices: [] } without making an API call.

    • Build a transaction to share a Perpetuals account that was created with deferred sharing.

      This finalizes the account creation flow by consuming the AccountSharePolicy and sharing the Account object. Call this after composing additional commands (grant-agent-wallet, transfer-cap) with the args returned by getCreateAccountTx.

      Pass the deferred fields (accountArg, sharePolicyArg, adminCapArg, collateralCoinType) from the deferred object returned by getCreateAccountTx.

      Parameters

      • inputs: Omit<ApiPerpetualsShareAccountBody, "txKind"> & { tx?: Transaction }
        • accountArg

          Account argument from deferred create.

        • sharePolicyArg

          Share policy argument from deferred create.

        • adminCapArg

          Admin cap argument from deferred create.

        • collateralCoinType

          Collateral type for the account.

        • sponsor

          Optional sponsorship config.

        • tx

          Optional transaction to extend.

        • Optionaltx?: Transaction

          Optional transaction to extend.

      Returns Promise<Omit<ApiTransactionResponse, "txKind"> & { tx: Transaction }>

      Transaction response containing a tx.

    • Build a transaction to transfer a Perpetuals capability object (cap) to another wallet.

      Supports two methods:

      • Method 1: Provide capObjectId to transfer an existing on-chain object.
      • Method 2: Provide composed with the PTB argument and capability type from a deferred PTB composition (e.g., from getCreateAccountTx with deferShare=true).

      Parameters

      • inputs: Omit<ApiPerpetualsTransferCapTxBody, "txKind"> & { tx?: Transaction }
        • recipientAddress

          Recipient wallet address that should receive the cap.

        • capObjectId

          Object ID of the capability to transfer (Method 1).

        • composed

          Composed PTB argument + capability type (Method 2).

        • tx

          Optional transaction to extend.

        • Optionaltx?: Transaction

          Optional transaction to extend.

      Returns Promise<Omit<ApiTransactionResponse, "txKind"> & { tx: Transaction }>

      Transaction response containing a tx.

    • Fetch multiple vaults by ID.

      Parameters

      • inputs: { vaultIds: string[] }
        • vaultIds: string[]

          Array of vault object IDs.

      Returns Promise<{ vaults: PerpetualsVault[] }>

      Object containing vaults in the same order as vaultIds.

    • Fetch the current network-wide Perpetuals vault protocol configuration.

      The returned limits are sourced from the on-chain configuration exposed by the service. Consumers should use these values instead of hardcoded vault limits because governance or package upgrades may change them.

      Parameters

      • OptionalabortSignal: AbortSignal

        Optional signal used to cancel the request.

      Returns Promise<PerpetualsVaultsConfig>

      The current vault protocol limits for this client's network.

    • Open a market-candles websocket stream for a single market/interval: /perpetuals/ws/market-candles/{market_id}/{interval_ms}.

      The stream emits PerpetualsWsCandleResponseMessage messages, typically containing the latest candle for the specified interval.

      Parameters

      • args: {
            interval: PerpetualsCandleResolution;
            marketId: string;
            onClose?: (ev: CloseEvent) => void;
            onError?: (ev: Event) => void;
            onMessage: (msg: PerpetualsWsCandleResponseMessage) => void;
            onOpen?: (ev: Event) => void;
        }
        • interval: PerpetualsCandleResolution
        • marketId: string

          Market ID to subscribe to. The input contains the candle interval in milliseconds.

        • OptionalonClose?: (ev: CloseEvent) => void

          Optional hook called when the websocket closes.

        • OptionalonError?: (ev: Event) => void

          Optional hook called on websocket error.

        • onMessage: (msg: PerpetualsWsCandleResponseMessage) => void

          Handler for incoming candle updates.

        • OptionalonOpen?: (ev: Event) => void

          Optional hook called when the websocket opens.

      Returns { close: () => void; ws: WebSocket }

      A controller containing the raw websocket and a close() helper.

      const stream = perps.openMarketCandlesWebsocketStream({
      marketId: "0x...",
      intervalMs: 60_000,
      onMessage: ({ lastCandle }) => console.log(lastCandle),
      });
    • Open the main updates websocket: /perpetuals/ws/updates.

      The stream emits PerpetualsWsUpdatesResponseMessage envelopes and supports multiple subscription types. This method returns a small controller with convenience subscribe/unsubscribe functions.

      Subscription types supported by the controller:

      • market: market state updates
      • user: user account updates (optionally including stop orders)
      • oracle: oracle price updates
      • orderbook: orderbook deltas
      • marketOrders: public market trades/orders
      • userOrders: user trade/order events
      • userCollateralChanges: user collateral change events
      • topOfOrderbook: bucketed orderbook snapshots (top of orderbook)

      Parameters

      • args: {
            onClose?: (ev: CloseEvent) => void;
            onError?: (ev: Event) => void;
            onMessage: (env: PerpetualsWsUpdatesResponseMessage) => void;
            onOpen?: (ev: Event) => void;
        }
        • OptionalonClose?: (ev: CloseEvent) => void

          Optional handler for the close event.

        • OptionalonError?: (ev: Event) => void

          Optional handler for the error event.

        • onMessage: (env: PerpetualsWsUpdatesResponseMessage) => void

          Handler for parsed messages from the websocket.

        • OptionalonOpen?: (ev: Event) => void

          Optional handler for the open event.

      Returns {
          close: () => void;
          subscribeMarket: (__namedParameters: { marketId: string }) => void;
          subscribeMarketCandles: (
              __namedParameters: {
                  interval: PerpetualsCandleResolution;
                  marketId: string;
              },
          ) => void;
          subscribeMarketOrders: (__namedParameters: { marketId: string }) => void;
          subscribeOracle: (__namedParameters: { marketId: string }) => void;
          subscribeOrderbook: (__namedParameters: { marketId: string }) => void;
          subscribeTopOfOrderbook: (
              __namedParameters: {
                  bucketsNumber: number;
                  marketId: string;
                  priceBucketSize: number;
              },
          ) => void;
          subscribeUser: (
              __namedParameters: {
                  accountId: bigint;
                  withStopOrders:
                      | { bytes: string; signature: string; walletAddress: string }
                      | undefined;
              },
          ) => void;
          subscribeUserCollateralChanges: (
              __namedParameters: { accountId: bigint },
          ) => void;
          subscribeUserOrders: (__namedParameters: { accountId: bigint }) => void;
          unsubscribeMarket: (__namedParameters: { marketId: string }) => void;
          unsubscribeMarketCandles: (
              __namedParameters: {
                  interval: PerpetualsCandleResolution;
                  marketId: string;
              },
          ) => void;
          unsubscribeMarketOrders: (__namedParameters: { marketId: string }) => void;
          unsubscribeOracle: (__namedParameters: { marketId: string }) => void;
          unsubscribeOrderbook: (__namedParameters: { marketId: string }) => void;
          unsubscribeTopOfOrderbook: (
              __namedParameters: {
                  bucketsNumber: number;
                  marketId: string;
                  priceBucketSize: number;
              },
          ) => void;
          unsubscribeUser: (
              __namedParameters: {
                  accountId: bigint;
                  withStopOrders:
                      | { bytes: string; signature: string; walletAddress: string }
                      | undefined;
              },
          ) => void;
          unsubscribeUserCollateralChanges: (
              __namedParameters: { accountId: bigint },
          ) => void;
          unsubscribeUserOrders: (__namedParameters: { accountId: bigint }) => void;
          ws: WebSocket;
      }

      A controller object containing:

      • ws: underlying WebSocket
      • subscribe/unsubscribe helpers for each subscription type
      • close(): closes the websocket
      • close: () => void
      • subscribeMarket: (__namedParameters: { marketId: string }) => void

        Subscription helpers

        Each helper sends a structured subscription message of the form: { action: "subscribe" | "unsubscribe", subscriptionType: { ... } }

      • subscribeMarketCandles: (
            __namedParameters: {
                interval: PerpetualsCandleResolution;
                marketId: string;
            },
        ) => void
      • subscribeMarketOrders: (__namedParameters: { marketId: string }) => void
      • subscribeOracle: (__namedParameters: { marketId: string }) => void
      • subscribeOrderbook: (__namedParameters: { marketId: string }) => void
      • subscribeTopOfOrderbook: (
            __namedParameters: {
                bucketsNumber: number;
                marketId: string;
                priceBucketSize: number;
            },
        ) => void
      • subscribeUser: (
            __namedParameters: {
                accountId: bigint;
                withStopOrders:
                    | { bytes: string; signature: string; walletAddress: string }
                    | undefined;
            },
        ) => void
      • subscribeUserCollateralChanges: (__namedParameters: { accountId: bigint }) => void
      • subscribeUserOrders: (__namedParameters: { accountId: bigint }) => void
      • unsubscribeMarket: (__namedParameters: { marketId: string }) => void
      • unsubscribeMarketCandles: (
            __namedParameters: {
                interval: PerpetualsCandleResolution;
                marketId: string;
            },
        ) => void
      • unsubscribeMarketOrders: (__namedParameters: { marketId: string }) => void
      • unsubscribeOracle: (__namedParameters: { marketId: string }) => void
      • unsubscribeOrderbook: (__namedParameters: { marketId: string }) => void
      • unsubscribeTopOfOrderbook: (
            __namedParameters: {
                bucketsNumber: number;
                marketId: string;
                priceBucketSize: number;
            },
        ) => void
      • unsubscribeUser: (
            __namedParameters: {
                accountId: bigint;
                withStopOrders:
                    | { bytes: string; signature: string; walletAddress: string }
                    | undefined;
            },
        ) => void
      • unsubscribeUserCollateralChanges: (__namedParameters: { accountId: bigint }) => void
      • unsubscribeUserOrders: (__namedParameters: { accountId: bigint }) => void
      • ws: WebSocket
    • Returns the canonical Aftermath API host for a Sui network.

      To target a custom or local host, pass baseUrl in CallerConfig to the constructor instead.

      Parameters

      • network: SuiNetwork

        The Sui network whose host to return.

      Returns string

      The network's HTTPS or local HTTP API host.

    • Construct a collateral-specialized Move event type string.

      Many Move events are generic over a collateral coin type. This helper appends <collateralCoinType> to a base eventType.

      Parameters

      • inputs: { collateralCoinType: string; eventType: string }
        • collateralCoinType: string

          Collateral coin type (e.g. "0x2::sui::SUI").

        • eventType: string

          Base event type without type parameters.

      Returns string

      Fully-qualified event type string.

    • Convert a floating-point lot/tick size to its fixed-point representation (9 decimals).

      Parameters

      • lotOrTickSize: number

        Floating-point size.

      Returns bigint

      Fixed-point size as bigint.

    • Convert a fixed-point lot/tick size (9 decimals) to a number.

      Parameters

      • lotOrTickSize: bigint

        Fixed-point size as bigint.

      Returns number

      Floating-point size.

    • Determine the logical order side (Bid/Ask) from a signed base asset amount.

      Parameters

      • inputs: { baseAssetAmount: number }
        • baseAssetAmount: number

          Position base size. Positive/zero => Bid (long), negative => Ask (short).

      Returns PerpetualsOrderSide

      PerpetualsOrderSide.

    • Convert a floating-point price into a fixed-point PerpetualsOrderPrice using 9 decimal places of precision.

      Parameters

      • inputs: { price: number }
        • price: number

          Price as a float.

      Returns bigint

      Fixed-point order price.