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

    High-level wrapper around a single Perpetuals account or vault account.

    This class encapsulates:

    • Transaction builders for:
      • Collateral actions (deposit, withdraw, allocate, deallocate, transfer)
      • Orders (market/limit, cancel, stop orders, SL/TP, set leverage)
    • Read-only account helpers:
      • Stop-order message signing
      • Order & stop-order metadata
      • Collateral & trade history
    • Convenience helpers to:
      • Fetch and categorize SL/TP stop orders
      • Resolve account/vault identifiers and owner addresses

    You typically do not construct PerpetualsAccount directly. Instead, use Perpetuals.getAccount or Perpetuals.getAccounts, which fetch all required on-chain data and wrap it for you:

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

    const perps = afSdk.Perpetuals();
    const [accountCap] = await perps.getOwnedAccountCaps({
    walletAddress: "0x...",
    });

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

    // Build a deposit transaction
    const depositTx = await account.getDepositCollateralTx({
    depositAmount: BigInt("1000000000"),
    });

    Hierarchy (View Summary)

    Index

    Raw account object with positions and equity data.

    Account cap or partial vault cap object containing ownership and collateral metadata.

    Optional shared AftermathApi provider instance used to derive serialized transaction kinds (txKind) from Transaction objects.

    config: CallerConfig

    The mutable configuration used for subsequent requests.

    • Get the account cap object ID, if this is a direct account.

      Direct accounts are controlled via an on-chain “cap” object. Vault-backed accounts are controlled via vault caps and do not expose a direct account-cap ID.

      Returns string

      ObjectId of the account cap.

      If called for a vault-backed account.

    • Get the numeric perpetuals account ID.

      This is the protocol-level identifier (bigint-derived) used across API calls.

      Returns bigint

      PerpetualsAccountId for this account.

    • Get the underlying account object ID.

      This is the on-chain object that holds the account's state and positions.

      Returns string

      ObjectId of the account object.

    • Convenience accessor for the account's available collateral (in coin units).

      This is the amount of collateral not currently locked/allocated across markets, as represented by the backend response.

      Returns number

      Available collateral as a number.

    • Build an allocate-collateral transaction, moving collateral from this account into a specific market (clearing house).

      Works for both account-backed and vault-backed accounts.

      Parameters

      • inputs: {
            allocateAmount: bigint;
            marketId: string;
            sponsor?: PerpetualsSponsorConfig;
            tx?: Transaction;
        }
        • allocateAmount: bigint

          Amount of collateral to allocate.

        • marketId: string

          Market to allocate collateral to.

        • Optionalsponsor?: PerpetualsSponsorConfig
        • Optionaltx?: Transaction

          Optional transaction to extend.

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

      Transaction response containing a tx.

    • Build a cancel-orders transaction for this account.

      Each market in marketIdsToData supplies:

      • orderIds: the orders to cancel in that market
      • collateralChange: collateral adjustment to apply alongside cancellation
      • leverage: leverage context used for estimating/validating constraints server-side

      Notes:

      • Cancels are applied per market; some markets may succeed while others fail depending on API/on-chain validation (returned as a transaction failure at execution).
      • If you need to understand the effect prior to building a tx, use getCancelOrdersPreview.

      Parameters

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

      Transaction response containing tx.

    • Build a cancel-stop-orders transaction for this account.

      This cancels stop-order objects/tickets by their object IDs. These IDs are returned by stop-order query endpoints (see getStopOrderDatas).

      Parameters

      • inputs: { sponsor?: PerpetualsSponsorConfig; stopOrderIds: string[]; tx?: Transaction }
        • Optionalsponsor?: PerpetualsSponsorConfig
        • stopOrderIds: string[]

          Array of stop-order ticket IDs to cancel.

        • Optionaltx?: Transaction

          Optional transaction to extend.

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

      Transaction response containing tx.

    • Build a deallocate-collateral transaction, moving collateral from a specific market back to this account.

      Works for both account-backed and vault-backed accounts.

      Parameters

      • inputs: {
            deallocateAmount: bigint;
            marketId: string;
            sponsor?: PerpetualsSponsorConfig;
            tx?: Transaction;
        }
        • deallocateAmount: bigint

          Amount of collateral to deallocate.

        • marketId: string

          Market to deallocate collateral from.

        • Optionalsponsor?: PerpetualsSponsorConfig
        • Optionaltx?: Transaction

          Optional transaction to extend.

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

      Transaction response containing a tx.

    • Build a deposit-collateral transaction for this account.

      For non-vault accounts, this endpoint constructs a transaction that:

      • Optionally extends an existing Transaction, and
      • Deposits collateral into the Perpetuals account.

      Note: Vault accounts are currently not supported and will throw.

      Parameters

      • inputs: { isSponsoredTx?: boolean; sponsor?: PerpetualsSponsorConfig; tx?: Transaction } & (
            | { depositAmount: bigint }
            | { depositCoinArg: TransactionObjectArgument }
        )
        • OptionalisSponsoredTx?: boolean

          Optional flag indicating whether the transaction is gas-sponsored.

        • Optionalsponsor?: PerpetualsSponsorConfig
        • Optionaltx?: Transaction

          Optional existing transaction to extend. If omitted, a new Transaction is created under the hood.

        • { depositAmount: bigint }
          • depositAmount: bigint

            Amount of collateral to deposit, if paying directly from the wallet.

        • { depositCoinArg: TransactionObjectArgument }
          • depositCoinArg: TransactionObjectArgument

            Transaction object argument referencing a coin to deposit (mutually exclusive with depositAmount).

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

      Transaction response containing a tx.

      const { tx } = await account.getDepositCollateralTx({
      depositAmount: BigInt("1000000000"),
      });
    • Preview the effects of allocating/deallocating collateral for the position in a given market.

      Semantics:

      • Positive collateralChange previews allocation (moving collateral into the market).
      • Negative collateralChange previews deallocation (moving collateral out of the market).

      Parameters

      • inputs: { collateralChange: bigint; marketId: string }
        • collateralChange: bigint

          The target collateral change (a positive number for allocating collateral, negative for deallocating collateral).

        • marketId: string

          Market of whose position you want to allocate/deallocate collateral to/from.

      • OptionalabortSignal: AbortSignal

        Optional AbortSignal to cancel the request.

      Returns Promise<
          | { collateralChange: number; updatedPosition: PerpetualsPosition }
          | { error: string },
      >

      Either:

      • { updatedPosition, collateralChange }, or
      • { error }.
    • Build an edit-stop-orders transaction for this account.

      This endpoint lets you update existing stop orders in batch.

      Notes:

      • You must provide the full updated stop-order objects (including object IDs).
      • This is typically used to adjust trigger prices, sizes, expiries, or the embedded limit-order parameters.

      Parameters

      • inputs: Omit<ApiPerpetualsEditStopOrdersBody, "accountObjectId" | "txKind"> & {
            tx?: Transaction;
        }
        • stopOrders

          Full updated stop-order payloads to apply.

        • tx

          Optional transaction to extend.

        • Optionaltx?: Transaction

          Optional transaction to extend.

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

      Transaction response containing tx.

    • Build a transaction that grants an Agent Wallet (assistant permissions) for this perpetuals account.

      The returned transaction must be signed and submitted by the account admin wallet. After execution, recipientAddress can execute supported trading actions on behalf of this account.

      Agent wallets can perform all supported actions except:

      • withdrawing collateral, and
      • granting or revoking other agent wallets.

      Parameters

      • inputs: { recipientAddress: string; tx?: Transaction }
        • recipientAddress: string

          Wallet address to receive agent permissions.

        • Optionaltx?: Transaction

          Optional existing Transaction to append to. If omitted, a new Transaction is used.

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

      If this instance represents a vault account (agent wallets are account-only).

    • Build a place-market-order transaction for this account.

      This is the primary entrypoint for opening/closing positions via market orders. It automatically:

      • Injects the account/vault identity into the payload.
      • Derives hasPosition based on the current account state for the given market.
      • Optionally attaches SL/TP stop orders via the slTp input.

      Important behavioral notes:

      • hasPosition is derived from the local PerpetualsAccountObject snapshot. If the snapshot is stale, consider re-fetching the account first.
      • For vault-backed accounts, the API routes to /perpetuals/vault/... and uses vaultId as the identity discriminator. For direct accounts, it uses accountId.

      Parameters

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

      Transaction response containing tx.

      const { tx } = await account.getPlaceMarketOrderTx({
      marketId: "0x...",
      side: PerpetualsOrderSide.Bid,
      size: BigInt("1000000000"),
      collateralChange: 10,
      reduceOnly: false,
      });
    • Build a transaction that revokes an Agent Wallet (assistant capability) from this perpetuals account.

      The returned transaction must be signed and submitted by the account admin wallet. After execution, the revoked wallet immediately loses its delegated permissions.

      Parameters

      • inputs: { accountCapId: string; tx?: Transaction }
        • accountCapId: string

          Object ID of the assistant capability to revoke.

        • Optionaltx?: Transaction

          Optional existing Transaction to append to. If omitted, a new Transaction is used.

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

      If this instance represents a vault account (agent wallets are account-only).

    • Preview the effects of setting leverage for a given market.

      The preview returns:

      • The position after the leverage change (updatedPosition)
      • The collateral delta required/produced (collateralChange)

      Parameters

      • inputs: { leverage: number; marketId: string }
        • leverage: number

          Target leverage value.

        • marketId: string

          Market whose leverage you want to adjust.

      • OptionalabortSignal: AbortSignal

        Optional AbortSignal to cancel the request.

      Returns Promise<
          | { collateralChange: number; updatedPosition: PerpetualsPosition }
          | { error: string },
      >

      Either:

      • { updatedPosition, collateralChange }, or
      • { error }.
    • Build a set-leverage transaction for a given market.

      This updates the effective leverage for the position (or potential position) in marketId, and optionally adjusts collateral in tandem.

      Notes:

      • Leverage changes may be constrained by protocol risk limits and current position state.
      • If you want to understand the effect first, use getSetLeveragePreview.

      Parameters

      • inputs: {
            collateralChange: number;
            leverage: number;
            marketId: string;
            sponsor?: PerpetualsSponsorConfig;
            tx?: Transaction;
        }
        • collateralChange: number

          Net collateral change to apply alongside the leverage update.

        • leverage: number

          Target leverage value.

        • marketId: string

          Market whose leverage to adjust.

        • Optionalsponsor?: PerpetualsSponsorConfig
        • Optionaltx?: Transaction

          Optional transaction to extend.

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

      Transaction response containing tx.

    • Fetch stop-order ticket data for this account, using an off-chain signed payload.

      Typical flow:

      1. Call getStopOrdersMessageToSign to construct a deterministic payload
      2. Sign the payload with the wallet
      3. Provide the signed payload to this method to fetch stop order data

      Parameters

      • inputs: { bytes: string; marketIds?: string[]; signature: string }
        • bytes: string

          Serialized message that was signed (e.g. JSON string).

        • OptionalmarketIds?: string[]

          Optional subset of markets to filter results by.

        • signature: string

          Signature over bytes.

      Returns Promise<ApiPerpetualsStopOrderDatasResponse>

      ApiPerpetualsStopOrderDatasResponse containing stopOrderDatas.

    • Build a deterministic message payload to sign when querying stop orders from the backend.

      This payload is intended to be signed off-chain and then submitted to getStopOrderDatas as a proof of account ownership.

      Important:

      • The returned payload is not a Sui transaction; it is an off-chain “authentication” message.
      • The backend expects account_id to be a decimal string. This code normalizes the bigint accountId by stripping the trailing n.

      Parameters

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

          Optional list of market IDs to scope the query.

      Returns { account_id: string; action: string; clearing_house_ids: string[] }

      An object describing the action and account/market IDs, suitable for message signing.

      const message = account.getStopOrdersMessageToSign({ marketIds: ["0x..."] });
      const { signature } = await wallet.signMessage({
      message: new TextEncoder().encode(JSON.stringify(message)),
      });
    • Build a transfer-collateral transaction between two Perpetuals accounts.

      Only supported for direct accounts, not vault-backed accounts.

      Parameters

      • inputs: {
            sponsor?: PerpetualsSponsorConfig;
            toAccountCapId?: string;
            toAccountId: bigint;
            transferAmount: bigint;
            tx?: Transaction;
        }
        • Optionalsponsor?: PerpetualsSponsorConfig
        • OptionaltoAccountCapId?: string
        • toAccountId: bigint

          Destination account ID.

        • transferAmount: bigint

          Amount of collateral to transfer.

        • Optionaltx?: Transaction

          Optional transaction to extend.

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

      Transaction response containing a tx.

    • Fetch TWAP-order data for this account, using an off-chain signed payload.

      Parameters

      • inputs: { bytes: string; marketIds?: string[]; signature: string }
        • bytes: string

          Serialized message that was signed.

        • OptionalmarketIds?: string[]

          Optional subset of markets to filter results by.

        • signature: string

          Signature over bytes.

      Returns Promise<ApiPerpetualsTwapOrderDatasResponse>

      ApiPerpetualsTwapOrderDatasResponse containing twapOrderDatas.

    • Build a withdraw-collateral transaction for this account.

      For non-vault accounts, this endpoint constructs a transaction to:

      • Withdraw collateral from the Perpetuals account, and
      • Optionally transfer it to a recipientAddress (otherwise coin is left as a transaction argument).

      Note: Vault accounts are currently not supported and will throw.

      Parameters

      • inputs: {
            recipientAddress?: string;
            sponsor?: PerpetualsSponsorConfig;
            tx?: Transaction;
            withdrawAmount: bigint;
        }
        • OptionalrecipientAddress?: string

          Optional address to receive the withdrawn coins directly.

        • Optionalsponsor?: PerpetualsSponsorConfig
        • Optionaltx?: Transaction

          Optional transaction to extend (defaults to new Transaction()).

        • withdrawAmount: bigint

          Amount of collateral to withdraw.

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

      A response containing tx and the coinOutArg where the withdrawn coins end up if recipientAddress is not used.

      const { tx, coinOutArg } = await account.getWithdrawCollateralTx({
      withdrawAmount: BigInt("1000000000"),
      });
    • Resolve the owner wallet address of this account or vault.

      • For direct accounts, returns the cap's walletAddress field.
      • For vault-backed accounts, returns the vault cap's ownerAddress.

      Naming note:

      • Some types use walletAddress for direct ownership. For vault-backed accounts the analogous field is ownerAddress.

      Returns string

      Owner wallet SuiAddress.

    • Extract all SL/TP-style stop orders across all markets for this account.

      SL/TP orders are stop orders which:

      • Have an slTp payload, and
      • Target the opposite side of the current position.

      This combines:

      • "Full" SL/TP orders (size >= i64MaxBigInt)
      • "Partial" SL/TP orders (size < i64MaxBigInt)

      The "full vs partial" distinction is a protocol convention: some systems encode “close entire position” using a sentinel max size.

      Parameters

      Returns PerpetualsStopOrderData[] | undefined

      Array of SL/TP stop orders, or undefined if none exist.

    • Splits SL/TP stop orders linked to one limit order into full and partial closes.

      A full close uses the protocol's Casting.i64MaxBigInt size sentinel. Orders below that sentinel are returned as partial closes. The method does not require a market ID because the link is carried by slTp.limitOrderId.

      Parameters

      Returns {
          fullSlTpOrder: PerpetualsStopOrderData | undefined;
          partialSlTpOrders: PerpetualsStopOrderData[] | undefined;
      }

      Full close and partial close matches. Each result is undefined when no matching order exists.

    • Categorize stop orders for a specific market into:

      • A "full" SL/TP order (size >= i64MaxBigInt) if any.
      • A set of "partial" SL/TP orders (size < i64MaxBigInt).

      SL/TP stop orders are defined as:

      • Market ID matches the input market.
      • slTp field is present.
      • Order side is opposite of the position side.
      • At least a stopLossPrice or takeProfitPrice is set.

      Notes on matching:

      • The side comparison uses the current position side derived from the account snapshot.
      • If baseAssetAmount === 0 (no effective position), the method returns no SL/TP orders.

      Parameters

      Returns {
          fullSlTpOrder: PerpetualsStopOrderData | undefined;
          partialSlTpOrders: PerpetualsStopOrderData[] | undefined;
      }

      Object containing:

      • fullSlTpOrder (if any)
      • partialSlTpOrders (if any, otherwise undefined)
    • 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.