PerpsController Actions
145 actions registered.
PerpsController:acknowledgeRecoveredDispatch
Package: @metamask/perps-controller
Acknowledge ONE recovered-dispatch outcome by its stable id, after refreshing venue state. Throws when the active provider has no durable dispatch state or the id no longer matches. Lighter scopes IDs to wallet/network/account/key and accepts legacy IDs only when unambiguous across local account ledgers. Acknowledgment removes one stored outcome, never an unresolved dispatch or a TP/SL journal, and authorizes no retry. Rejects account, network, provider or lifecycle changes while readiness or acknowledgment completes. A stale rejection after provider success does not undo removal in the issuing account. Re-list outcomes before acting again. Provider rejections propagate unchanged.
Parameters:
| Name | Description |
|---|---|
recoveryId | Opaque stable id from getRecoveredDispatches. |
Returns: Resolves when the outcome is acknowledged.
Handler signature:
(recoveryId: string) => Promise<void>
PerpsController:approveSubscriptionBuilderFee
Deprecated
Package: @metamask/perps-controller
Approve the dedicated subscription builder outside order submission.
Deprecated: ADR 0064 replaced the dedicated subscription builder with cloid marking on the standard builder, so there is nothing left to approve. Kept as a no-op so clients still calling it keep building while they migrate; remove it once cloid marking is verified in shadow mode. Resolves true, not false. The method answers "is the subscription builder ready?", and the honest answer is now "nothing needs approving" — a false would read as a setup failure to a caller that branches on it and could block a waiver that is already fully in effect.
Returns: Always true; no approval is required.
Handler signature:
() => Promise<boolean>
PerpsController:calculateFees
Package: @metamask/perps-controller
Calculate trading fees through the active provider route. Each provider owns its fee policy. An explicit provider route overrides the active/default provider used by placement.
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: The fee calculation result for the trade.
Handler signature:
(params: FeeCalculationParams) => Promise<FeeCalculationResult>
PerpsController:calculateLiquidationPrice
Package: @metamask/perps-controller
Calculate liquidation price for a position Uses provider-specific formulas based on protocol rules
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: A promise that resolves to the string result.
Handler signature:
(params: LiquidationPriceParams) => Promise<string>
PerpsController:calculateMaintenanceMargin
Package: @metamask/perps-controller
Calculate maintenance margin for a specific asset Returns a percentage (e.g., 0.0125 for 1.25%)
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: A promise that resolves to the numeric result.
Handler signature:
(params: MaintenanceMarginParams) => Promise<number>
PerpsController:cancelOrder
Package: @metamask/perps-controller
Cancel an existing order
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: The cancellation result with status.
Handler signature:
(params: CancelOrderParams) => Promise<CancelOrderResult>
PerpsController:cancelOrders
Package: @metamask/perps-controller
Cancel multiple orders in parallel Batch version of cancelOrder() that cancels multiple orders simultaneously
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: Per-order results, plus status: all, partial or none.
Handler signature:
(params: CancelOrdersParams) => Promise<WithBatchOperationStatus<CancelOrdersResult>>
PerpsController:clearAgentSigners
Package: @metamask/perps-controller
Forget every HyperLiquid agent, set or resolved, so the next L1 action
asks providerCredentials.hyperliquid.getAgentSigner again; an answer
still pending is discarded too. Call it when the wallet locks (with
getAgentSigner returning null while locked) and nothing signs with an
agent until it returns one again. Like every controller action, it is
available through the messenger once init has run.
Handler signature:
() => void
PerpsController:clearAttributionContext
Package: @metamask/perps-controller
Clear the stored attribution context.
Handler signature:
() => void
PerpsController:clearDepositResult
Package: @metamask/perps-controller
Clear the last deposit result after it has been shown to the user
Handler signature:
() => void
PerpsController:clearPendingTradeConfiguration
Package: @metamask/perps-controller
Clear pending trade configuration for a market on a venue
Parameters:
| Name | Description |
|---|---|
symbol | Market symbol |
providerId | Optional venue the configuration was saved for. Defaults to the live effective venue, or the active/saved default venue before initialization. |
Handler signature:
(symbol: string, providerId?: PerpsProviderType) => void
PerpsController:clearPendingTransactionRequests
Package: @metamask/perps-controller
Clear pending/bridging withdrawal and deposit requests This is useful when users want to clear stuck pending indicators Called by Reset Account feature in settings
Handler signature:
() => void
PerpsController:clearWithdrawResult
Package: @metamask/perps-controller
Handler signature:
() => void
PerpsController:closePosition
Package: @metamask/perps-controller
Close a position (partial or full) Thin delegation to TradingService
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: The order result from the close position request.
Handler signature:
(params: ClosePositionParams) => Promise<OrderResult>
PerpsController:closePositions
Package: @metamask/perps-controller
Close multiple positions in parallel Batch version of closePosition() that closes multiple positions simultaneously
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: Per-position results, plus status: all, partial or none.
Handler signature:
(params: ClosePositionsParams) => Promise<WithBatchOperationStatus<ClosePositionsResult>>
PerpsController:completeWithdrawalFromHistory
Package: @metamask/perps-controller
Complete a specific withdrawal detected via transaction history polling (FIFO queue). Called when a completed withdrawal appears in the transaction history matching a pending request.
Uses FIFO matching: oldest pending withdrawal is matched with first completed withdrawal in history that happened after its submission time.
Parameters:
| Name | Description |
|---|---|
withdrawalRequestId | The ID of the pending withdrawal request to mark as complete. |
completedWithdrawal | The completed withdrawal data from the history API. |
completedWithdrawal.txHash | The on-chain transaction hash. |
completedWithdrawal.amount | The withdrawal amount. |
completedWithdrawal.timestamp | The completion timestamp from the history API. |
completedWithdrawal.asset | The asset symbol (e.g. USDC). |
Handler signature:
(withdrawalRequestId: string, completedWithdrawal: {
txHash: string;
amount: string;
timestamp: number;
asset?: string;
}) => void
PerpsController:depositWithConfirmation
Package: @metamask/perps-controller
Simplified deposit method that prepares transaction for confirmation screen No complex state tracking - just sets a loading flag
Parameters:
| Name | Description |
|---|---|
params | Parameters for the deposit flow |
params.amount | Optional deposit amount |
params.placeOrder | If true, uses addTransaction instead of submit to avoid navigation |
Returns: An object containing a promise that resolves to the transaction hash.
Handler signature:
(params?: DepositWithConfirmationParams) => Promise<{
result: Promise<string>;
}>
PerpsController:depositWithOrder
Package: @metamask/perps-controller
Same as depositWithConfirmation - prepares transaction for confirmation screen.
Returns: A promise that resolves to the string result.
Handler signature:
() => Promise<{
result: Promise<string>;
}>
PerpsController:disconnect
Package: @metamask/perps-controller
Disconnect provider and cleanup subscriptions Call this when navigating away from Perps screens to prevent battery drain
Handler signature:
() => Promise<void>
PerpsController:editOrder
Package: @metamask/perps-controller
Edit an existing order Thin delegation to TradingService
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: The updated order result with order ID and status.
Handler signature:
(params: EditOrderParams) => Promise<OrderResult>
PerpsController:estimateCrossLiquidation
Package: @metamask/perps-controller
Estimate the liquidation price of the Cross position an order would
leave: an opening, or an add, reduce or flip of the market's position.
Never rejects: price, none when no price liquidates it at the
account's collateral, or unavailable with a typed reason.
Parameters:
| Name | Description |
|---|---|
params | The proposed Cross order. |
Returns: The typed estimate.
Handler signature:
(params: EstimateCrossLiquidationParams) => Promise<CrossLiquidationEstimate>
PerpsController:fetchHistoricalCandles
Package: @metamask/perps-controller
Fetch historical candle data Thin delegation to MarketDataService
Parameters:
| Name | Description |
|---|---|
options | The configuration options. |
options.symbol | The trading pair symbol. |
options.interval | The candle interval period. |
options.limit | Maximum number of items to fetch. |
options.endTime | End timestamp in milliseconds. |
Returns: The historical candle data for the requested symbol and interval.
Handler signature:
(options: {
symbol: string;
interval: CandlePeriod;
limit?: number;
endTime?: number;
}) => Promise<CandleData>
PerpsController:flipPosition
Package: @metamask/perps-controller
Flip position (reverse direction while keeping size and leverage)
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: The order result from the position flip.
Handler signature:
(params: FlipPositionParams) => Promise<OrderResult>
PerpsController:getAccountState
Package: @metamask/perps-controller
Get account state (balances, etc.) Thin delegation to MarketDataService
For standalone mode, bypasses getActiveProvider() to allow account state queries without full perps initialization (e.g., for checking if user has perps funds)
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: A promise that resolves to the result.
Handler signature:
(params?: GetAccountStateParams) => Promise<AccountState>
PerpsController:getAccountSupport
Package: @metamask/perps-controller
Return whether the selected account can submit actions through the active provider route. Providers without an account-support check remain supported for backward compatibility.
Parameters:
| Name | Description |
|---|---|
params | Optional provider route. |
Returns: The provider-owned account support result.
Handler signature:
(params?: GetAccountSupportParams) => Promise<PerpsAccountSupport>
PerpsController:getActiveProvider
Package: @metamask/perps-controller
Get the currently active provider. In aggregated mode, returns AggregatedPerpsProvider which routes to underlying providers. In single provider mode, returns HyperLiquidProvider directly.
Returns: The active provider (aggregated wrapper or direct provider based on mode)
Handler signature:
() => PerpsProvider
PerpsController:getActiveProviderOrNull
Package: @metamask/perps-controller
Get the currently active provider, returning null if not available Use this method when the caller can gracefully handle a missing provider (e.g., UI components during initialization or reconnection)
Returns: The active provider, or null if not initialized/reinitializing
Handler signature:
() => PerpsProvider | null
PerpsController:getAttachedOrderGroups
Package: @metamask/perps-controller
List durable attached identities for the selected provider and account.
Returns: Stored intent without venue writes, signer setup or automatic replay.
Handler signature:
() => Promise<AttachedOrderGroup[]>
PerpsController:getAttributionContext
Package: @metamask/perps-controller
Get a copy of the current attribution context.
Returns: A shallow copy of the stored attribution context.
Handler signature:
() => PerpsAttributionContext
PerpsController:getAvailableDexs
Package: @metamask/perps-controller
Get list of available HIP-3 builder-deployed DEXs
Parameters:
| Name | Description |
|---|---|
params | Optional parameters for filtering |
Returns: Array of DEX names
Handler signature:
(params?: GetAvailableDexsParams) => Promise<string[]>
PerpsController:getBlockExplorerUrl
Package: @metamask/perps-controller
Get block explorer URL for an address or just the base URL
Parameters:
| Name | Description |
|---|---|
address | Optional address to append to the base URL |
Returns: Block explorer URL
Handler signature:
(address?: string) => string
PerpsController:getCachedMarketDataForActiveProvider
Package: @metamask/perps-controller
Read cached market data for the currently active provider (or aggregated). Returns null when no valid cache exists or when cache has expired.
Parameters:
| Name | Description |
|---|---|
options | Optional settings. |
options.skipTTL | When true, bypass the 5-minute TTL check. Used during initial render so disk-hydrated structural data (with placeholder prices) is returned regardless of age. |
Returns: The cached market data array, or null if no valid cache.
Handler signature:
(options?: {
skipTTL?: boolean;
}) => PerpsMarketData[] | null
PerpsController:getCachedUserDataForActiveProvider
Package: @metamask/perps-controller
Read cached user data for the currently active provider (or aggregated). Returns null when no valid cache exists, cache has expired, or address does not match the currently selected EVM account.
Parameters:
| Name | Description |
|---|---|
options | Optional settings. |
options.skipTTL | When true, bypass the 60s staleness check. Used during initial render so disk-hydrated user data (positions/orders) is returned regardless of age, avoiding a skeleton flash. |
Returns: The cached user data, or null if no valid cache.
Handler signature:
(options?: {
skipTTL?: boolean;
}) => {
positions: Position[];
orders: Order[];
accountState: AccountState | null;
} | null
PerpsController:getChaseOrderOwnership
Package: @metamask/perps-controller
Observe durable ownership for an exact Chase handle through one provider. Starts no signing, transport, continuation, cancellation or durable writes. Original owner/child IDs are observations, never permission for cleanup in a different context. Providers without durable history report unsupported.
Parameters:
| Name | Description |
|---|---|
input | Opaque handle, explicit route and optional original owner. |
Returns: Complete local child history, unsupported, or explicit absence.
Handler signature:
(input: GetChaseOrderOwnershipParams) => Promise<PerpsChaseOrderOwnership>
PerpsController:getChaseOrders
Package: @metamask/perps-controller
Read the active provider's retained Chase lifecycle snapshots. Providers without an emulated Chase implementation return an empty list.
Returns: Current Chase session snapshots.
Handler signature:
() => Promise<ChaseOrder[]>
PerpsController:getCurrentNetwork
Package: @metamask/perps-controller
Get current network (mainnet/testnet)
Returns: Either 'mainnet' or 'testnet' based on the current configuration.
Handler signature:
() => 'mainnet' | 'testnet'
PerpsController:getFunding
Package: @metamask/perps-controller
Get historical user funding history (funding payments) Thin delegation to MarketDataService
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
options | Optional call modifiers. |
options.forceRefresh | Bypass the request-coalesce cache end-to-end (user-initiated refresh). |
Returns: Array of historical funding payments.
Handler signature:
(params?: GetFundingParams, options?: {
forceRefresh?: boolean;
}) => Promise<Funding[]>
PerpsController:getHistoricalPortfolio
Package: @metamask/perps-controller
Get historical portfolio data Thin delegation to MarketDataService
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: The historical portfolio data points.
Handler signature:
(params?: GetHistoricalPortfolioParams) => Promise<HistoricalPortfolioResult>
PerpsController:getMarginAdjustmentLimits
Package: @metamask/perps-controller
Get how much margin an isolated position can take in (maxAdd, what the
venue's isolated margin update accepts) and release (maxRemove),
through the active provider route used by order placement. Never throws;
failures report an unavailable status.
Parameters:
| Name | Description |
|---|---|
params | Market and optional provider route. |
Returns: The limits, or a typed unavailable result.
Handler signature:
(params: GetMarginAdjustmentLimitsParams) => Promise<MarginAdjustmentLimits>
PerpsController:getMarginMode
Package: @metamask/perps-controller
Get the saved margin mode (Isolated/Cross) for a market on the current network. Clients should still let a venue-enforced mode take priority.
Parameters:
| Name | Description |
|---|---|
symbol | Market symbol |
providerId | Optional venue the mode was saved for. Defaults to the live effective venue (active/saved default before initialization). |
Returns: The saved margin mode or undefined if not set
Handler signature:
(symbol: string, providerId?: PerpsProviderType) => MarginMode | undefined
PerpsController:getMarginModeLock
Package: @metamask/perps-controller
Get the margin mode the market is currently locked to by an open position or resting order, through the active provider route used by order placement. Never throws; failures report an unavailable status.
Parameters:
| Name | Description |
|---|---|
params | Market and optional provider route. |
Returns: The provider-reported margin-mode lock.
Handler signature:
(params: GetMarginModeLockParams) => Promise<PerpsMarginModeLock>
PerpsController:getMarketCategories
Package: @metamask/perps-controller
Get the ordered list of all market categories for HIP-3 markets. Returns a stable, explicitly ordered array so the UI can render category filter tabs without deriving order from config insertion.
Returns: Ordered array of MarketTypeFilter values. Does not include the 'all' or 'new' sentinels — those are separate UI controls.
Handler signature:
() => MarketTypeFilter[]
PerpsController:getMarketDataWithPrices
Package: @metamask/perps-controller
Get market data with prices (includes price, volume, 24h change). Optionally filter by category, sort, and limit the results.
For standalone mode, bypasses getActiveProvider() to allow market data queries without full perps initialization (e.g., for background preloading on app start)
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
params.standalone | Whether to use standalone mode. |
params.categories | Filter to markets matching any of these categories. |
params.sortBy | Sort results by this field. |
params.direction | Sort direction (default: desc). |
params.limit | Maximum number of results to return. |
Returns: A promise that resolves to the market data.
Handler signature:
(params?: GetMarketDataWithPricesParams) => Promise<PerpsMarketData[]>
PerpsController:getMarketFilterPreferences
Package: @metamask/perps-controller
Get saved market filter preferences Handles backward compatibility with legacy string format
Returns: The saved sort option ID and direction.
Handler signature:
() => {
optionId: SortOptionId;
direction: SortDirection;
}
PerpsController:getMarketMeta
Package: @metamask/perps-controller
Get venue metadata (margin tiers, delisted, max leverage, isolated-only)
for one market, or for every market when symbol is omitted. Reads the
provider's own market list, which Hyperliquid builds from its session
meta cache, never a Terminal snapshot. In aggregated mode it reads one
venue: providerId, else the default provider.
Parameters:
| Name | Description |
|---|---|
params | Optional market and provider route. |
Returns: One market's metadata when symbol is set, otherwise a list.
Handler signature:
(params: GetMarketMetaParams & {
symbol: string;
}) => Promise<PerpsMarketMeta>
PerpsController:getMarkets
Package: @metamask/perps-controller
Get available markets with optional filtering Thin delegation to MarketDataService
For standalone mode, bypasses getActiveProvider() to allow market discovery without full perps initialization (e.g., for discovery banners on spot screens)
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: Array of available markets matching the filter criteria.
Handler signature:
(params?: GetMarketsParams) => Promise<MarketInfo[]>
PerpsController:getMaxLeverage
Package: @metamask/perps-controller
Get maximum leverage allowed for an asset
Parameters:
| Name | Description |
|---|---|
asset | The asset identifier. |
providerId | Optional provider route for aggregated markets. |
Returns: A promise that resolves to the numeric result.
Handler signature:
(asset: string, providerId?: PerpsProviderType) => Promise<number>
PerpsController:getMaxSlippage
Package: @metamask/perps-controller
Get the user's max slippage tolerance in basis points.
Returns: The configured max slippage bps, or undefined if never set (callers should default to 300 bps / 3%).
Handler signature:
() => number | undefined
PerpsController:getOpenOrders
Package: @metamask/perps-controller
Get currently open orders (real-time status) Thin delegation to MarketDataService
For standalone mode, bypasses getActiveProvider() to allow open order queries without full perps initialization (e.g., for background preloading)
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: A promise that resolves to the result.
Handler signature:
(params?: GetOrdersParams) => Promise<Order[]>
PerpsController:getOrderBookGrouping
Package: @metamask/perps-controller
Get saved order book grouping for a market
Parameters:
| Name | Description |
|---|---|
symbol | Market symbol |
providerId | Optional venue the grouping was saved for. Defaults to the live effective venue (active/saved default before initialization). |
Returns: The saved grouping value or undefined if not set
Handler signature:
(symbol: string, providerId?: PerpsProviderType) => number | undefined
PerpsController:getOrderBookPreferences
Package: @metamask/perps-controller
Get market-agnostic Pro order-book display preferences.
Returns: The current order-book display preferences.
Handler signature:
() => OrderBookPreferences
PerpsController:getOrderCapabilities
Package: @metamask/perps-controller
Get order capabilities through the active provider route used by order placement. The query waits for in-flight initialization and reports an explicit unavailable status when no provider route can answer reliably.
Parameters:
| Name | Description |
|---|---|
params | Market and optional provider route. |
Returns: Provider-owned order capabilities.
Handler signature:
(params: GetOrderCapabilitiesParams) => Promise<PerpsOrderCapabilities>
PerpsController:getOrderFills
Package: @metamask/perps-controller
Get historical user fills (trade executions) Thin delegation to MarketDataService
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
options | Optional call modifiers. |
options.forceRefresh | Bypass the request-coalesce cache end-to-end (user-initiated refresh). |
Returns: Array of historical trade executions (fills).
Handler signature:
(params?: GetOrderFillsParams, options?: {
forceRefresh?: boolean;
}) => Promise<OrderFill[]>
PerpsController:getOrders
Package: @metamask/perps-controller
Get historical user orders (order lifecycle) Thin delegation to MarketDataService
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
options | Optional call modifiers. |
options.forceRefresh | Bypass the request-coalesce cache end-to-end (user-initiated refresh). |
Returns: Array of historical orders.
Handler signature:
(params?: GetOrdersParams, options?: {
forceRefresh?: boolean;
}) => Promise<Order[]>
PerpsController:getPendingManualRecoveries
Package: @metamask/perps-controller
List TP/SL protection changes the active provider parked for explicit manual re-establishment. Providers without durable settlement state return an empty list. Lighter includes previous-key and pre-initialization journals for the selected wallet/account, waits for any in-flight key selection and keeps failed-setup obligations visible. A current-key update does not clear an earlier key's unfinished journal.
Returns: Pending manual-recovery entries.
Handler signature:
() => Promise<PerpsPendingManualRecovery[]>
PerpsController:getPendingTradeConfiguration
Package: @metamask/perps-controller
Get pending trade configuration for a market Returns undefined if config doesn't exist or has expired.
Parameters:
| Name | Description |
|---|---|
symbol | Market symbol |
providerId | Optional venue the configuration was saved for. Defaults to the live effective venue, or the active/saved default venue before initialization. |
Returns: Pending trade configuration or undefined
Handler signature:
(symbol: string, providerId?: PerpsProviderType) => {
amount?: string;
leverage?: number;
takeProfitPrice?: string;
stopLossPrice?: string;
limitPrice?: string;
orderType?: OrderType;
reduceOnly?: boolean;
direction?: OrderDirection;
selectedPaymentToken?: PerpsSelectedPaymentToken | null;
} | undefined
PerpsController:getPositions
Package: @metamask/perps-controller
Get current positions Thin delegation to MarketDataService
For standalone mode, bypasses getActiveProvider() to allow position queries without full perps initialization (e.g., for showing positions on token details page)
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: Array of open positions for the active provider.
Handler signature:
(params?: GetPositionsParams) => Promise<Position[]>
PerpsController:getProLayoutPreferences
Package: @metamask/perps-controller
Get the user's pro-mode layout preferences (network-independent).
Returns: The current pro-mode layout preferences.
Handler signature:
() => ProLayoutPreferences
PerpsController:getProviderHealth
Package: @metamask/perps-controller
Get one provider's health, in any mode: aggregated mode reports each venue separately, so a Lighter outage never reads as HyperLiquid's.
Parameters:
| Name | Description |
|---|---|
providerId | Provider to report on. |
Returns: Its health; unavailable when it is not registered.
Handler signature:
(providerId: PerpsProviderType) => PerpsProviderHealth
PerpsController:getPublicTrades
Package: @metamask/perps-controller
Read a market's most recent public trades (every user's trades, not only the account's fills), newest first, from the active provider.
Every trade has the same shape on every provider and carries its
providerId. If the active provider changes before the venue answers,
or in aggregated mode the default provider changes before an unrouted
read answers, this resolves to an empty list, so a previous provider's
trades never reach a client that already moved on.
Parameters:
| Name | Description |
|---|---|
params | Market, optional limit (default 50) and provider route. |
Returns: The trades, newest first.
Handler signature:
(params: GetPublicTradesParams) => Promise<PublicTrade[]>
PerpsController:getRecentlyViewedMarkets
Package: @metamask/perps-controller
Get recently viewed markets for the current network.
Returns up to PERPS_CONSTANTS.RecentlyViewedMarketsLimit references, ordered newest-first, filtered to entries within the last PERPS_CONSTANTS.RecentlyViewedMarketsTtlMs (24 hours). Returns an empty array when no qualifying entries exist.
Returns: Ordered array of saved market references.
Handler signature:
() => string[]
PerpsController:getRecoveredDispatches
Package: @metamask/perps-controller
READ-ONLY list of the active provider's recovered-dispatch outcomes (previously ambiguous submissions later resolved). Providers without durable dispatch state return an empty list. Lighter scans the bounded local trading-slot range, including skipped keys, without signing or changing quarantine. After controller initialization, this works before Lighter signer initialization and after signer setup failure; an in-flight selection settles first. Preserve opaque recovery IDs exactly. Raw pending dispatches report unknown with acknowledgeable:false and cannot be cleared by acknowledgment, including current-session in-flight submissions. Listing starts no background reconciliation. A later financial action re-checks authoritative state for all account slots before dispatch and remains blocked while an obligation is unresolved.
Returns: Pending recovered-dispatch outcomes, with their original key slot when supplied by the provider.
Handler signature:
() => Promise<PerpsRecoveredDispatch[]>
PerpsController:getScaleOrderGroups
Package: @metamask/perps-controller
Read durable Scale groups without placing or replaying any child.
Returns: Groups belonging to the issuing controller context.
Handler signature:
() => Promise<ScaleOrderGroup[]>
PerpsController:getScalePriceLadder
Package: @metamask/perps-controller
Build a Scale price ladder using the active provider's venue rules.
Parameters:
| Name | Description |
|---|---|
params | Market, ladder bounds, count, optional sizing and explicit route. |
Returns: Provider-normalized prices with sizingPreview when supported, or a typed unavailable result.
Handler signature:
(params: GetScalePriceLadderParams) => Promise<PerpsScalePriceLadder>
PerpsController:getSelectedOrderType
Package: @metamask/perps-controller
Get the selected order type shared by every market.
Returns: The selected order type.
Handler signature:
() => OrderType
PerpsController:getState
Package: @metamask/perps-controller
The action which can be used to retrieve the state of the
PerpsController.
Handler signature:
() => PerpsControllerState
PerpsController:getTradeConfiguration
Package: @metamask/perps-controller
Get saved trade configuration for a market on a venue
Parameters:
| Name | Description |
|---|---|
symbol | The trading pair symbol. |
providerId | Optional venue the configuration was saved for. Defaults to the live effective venue, or the active/saved default venue before initialization. |
Returns: The resulting string value.
Handler signature:
(symbol: string, providerId?: PerpsProviderType) => {
leverage?: number;
} | undefined
PerpsController:getTwapOrders
Package: @metamask/perps-controller
Read venue-backed TWAP lifecycle records through the active provider. Providers without native TWAP history return an empty list.
Returns: Current and terminal TWAP schedules with slice fills.
Handler signature:
() => Promise<TwapOrder[]>
PerpsController:getUserDataSnapshot
Package: @metamask/perps-controller
Fetch, validate, and atomically cache a complete user-data snapshot. This remains callable after mount so consumers can seed their live channel from one coherent positions/orders/account result.
Returns: The accepted user-data snapshot.
Handler signature:
() => Promise<PerpsUserDataSnapshot>
PerpsController:getVisibleCandleCount
Package: @metamask/perps-controller
Get the number of candles shown in Lite and Pro chart viewports.
Returns: The visible candle count.
Handler signature:
() => number
PerpsController:getWatchlistMarkets
Package: @metamask/perps-controller
Get all watchlist markets for the current network
Returns: Saved market references for the current network.
Handler signature:
() => string[]
PerpsController:getWebSocketConnectionState
Package: @metamask/perps-controller
Get the current WebSocket connection state from the active provider. Used by the UI to monitor connection health and show notifications.
Returns: The current WebSocket connection state, or DISCONNECTED if not supported
Handler signature:
() => WebSocketConnectionState
PerpsController:getWithdrawalProgress
Package: @metamask/perps-controller
Get current withdrawal progress
Returns: The withdrawal progress, last update timestamp, and active withdrawal ID.
Handler signature:
() => {
progress: number;
lastUpdated: number;
activeWithdrawalId: string | null;
}
PerpsController:getWithdrawalRoutes
Package: @metamask/perps-controller
Get supported withdrawal routes - returns complete asset and routing information
Returns: Array of supported asset routes for withdrawals.
Handler signature:
() => AssetRoute[]
PerpsController:init
Package: @metamask/perps-controller
Initialize the PerpsController providers Must be called before using any other methods Prevents double initialization with promise caching
Returns: A promise that resolves when the operation completes.
Handler signature:
() => Promise<void>
PerpsController:invalidateSubscriptionBenefits
Package: @metamask/perps-controller
Drop the cached subscription benefits snapshot.
Call this when the identity behind the benefits changes — sign-out, or a profile switch. The snapshot carries no profile identity of its own, so without this it keeps answering for the previous profile until the next successful refresh. The next fee resolution reports the waiver as unavailable, so it is withheld until preview or lifecycle hydration.
Handler signature:
() => void
PerpsController:isCurrentlyReinitializing
Package: @metamask/perps-controller
Check if the controller is currently reinitializing
Returns: true if providers are being reinitialized
Handler signature:
() => boolean
PerpsController:isFirstTimeUserOnCurrentNetwork
Package: @metamask/perps-controller
Check if user is first-time for the current network
Returns: True if the condition is met.
Handler signature:
() => boolean
PerpsController:isWatchlistMarket
Package: @metamask/perps-controller
Check if a market is in the watchlist on the current network
Parameters:
| Name | Description |
|---|---|
symbol | The trading pair symbol. |
marketKey | Optional cross-venue key for a grouped market. |
venues | Original rows from the group, used to match a legacy favorite. |
legacyProvider | Venue that owned saved symbols before grouping. |
Returns: Whether the reference is saved.
Handler signature:
(symbol: string, marketKey?: string, venues?: readonly PerpsMarketData[], legacyProvider?: PerpsProviderType) => boolean
PerpsController:markFirstOrderCompleted
Package: @metamask/perps-controller
Handler signature:
() => void
PerpsController:markTutorialCompleted
Package: @metamask/perps-controller
Mark that the user has completed the tutorial/onboarding This prevents the tutorial from showing again
Handler signature:
() => void
PerpsController:placeOrder
Package: @metamask/perps-controller
Place a new order Thin delegation to TradingService
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: The order result with order ID and status.
Handler signature:
(params: OrderParams) => Promise<OrderResult>
PerpsController:prepareTradingWallet
Package: @metamask/perps-controller
Run the active provider's deferred trading setup ahead of the first order (HyperLiquid account migration, builder fee and referral; Lighter venue-key registration), so its signatures happen in one guided session, such as agent setup, instead of at order time. The builder fee and Lighter's registration are signed by the main account; with an agent, the referral and the account migration are L1 actions the agent signs.
Returns: ready: true when none of these steps will need a signature again before the first order, and only while an account is selected and the main account can sign, whichever provider answered (including providers without deferred setup, for example in aggregated mode). A HyperLiquid referral whose MetaMask referral code is not ready yet is checked again at the next call, not before orders, so it does not hold it back. Otherwise ready: false, without an error while a step will be asked again (a declined HyperLiquid migration, builder fee or Lighter registration, or a step the agent could not sign), or with: - KEYRING_LOCKED when the main account cannot sign, before or during setup; - EXCHANGE_ACCOUNT_NOT_FOUND for a wallet with no account on the venue yet; - NO_ACCOUNT_SELECTED when no account is selected; - PROVIDER_LIFECYCLE_STALE when the provider disconnected or the account changed during setup; - provider-tagged UNKNOWN_ERROR when HyperLiquid refused the builder fee approval for a reason signing again cannot fix (for example the builder wallet cannot be approved). The venue sentence stays on the error cause and in the debug log; it is not logged to Sentry, and the approval is not asked for again until the provider disconnects; - otherwise a provider-tagged code for the error that stopped setup, which is logged. Text that is not a known code becomes UNKNOWN_ERROR.
Handler signature:
() => Promise<ReadyToTradeResult>
PerpsController:previewPositionModify
Package: @metamask/perps-controller
Project the position that would remain after a proposed order. Margin and liquidation availability are independent: a missing liquidation does not hide a valid margin projection. Hyperliquid projects Cross positions against the account's Cross collateral.
Parameters:
| Name | Description |
|---|---|
params | Live position plus the proposed order. |
Returns: Discriminated preview of the resulting position.
Handler signature:
(params: PositionModifyPreviewParams) => Promise<PositionModifyPreviewResult>
PerpsController:reconcileChaseOrderCancellation
Package: @metamask/perps-controller
Reconcile one retained exact Chase cancellation without any new cancellation. Unsupported providers are never routed to ordinary financial cancellation.
Parameters:
| Name | Description |
|---|---|
input | Original handle, owner, child and transaction identity. |
Returns: Proven terminal state, unresolved cleanup or unsupported capability.
Handler signature:
(input: ReconcileChaseOrderCancellationParams) => Promise<ReconcileChaseOrderCancellationResult>
PerpsController:reconcileRecoveredDispatches
Package: @metamask/perps-controller
Explicit non-financial reconciliation with local persistence. Never signs, retries or acknowledges dispatches. Unsupported providers return their local listed state, or an empty list when neither capability is available. Rejects account, network or provider changes while controller readiness, reconciliation or fallback listing completes. Provider rejections propagate unchanged.
Returns: Newly scoped pending and recovered dispatches.
Handler signature:
() => Promise<PerpsRecoveredDispatch[]>
PerpsController:reconnect
Package: @metamask/perps-controller
Manually trigger a WebSocket reconnection attempt. Used by the UI retry button when connection is lost.
Handler signature:
() => Promise<void>
PerpsController:recordMarketViewed
Package: @metamask/perps-controller
Record that the user viewed a market.
The market reference is prepended to the per-network recently-viewed list (newest-first). Any existing entry for the same reference, or for its legacy alias, is removed first so there are no duplicates. The list is then capped at PERPS_CONSTANTS.RecentlyViewedMarketsLimit.
Parameters:
| Name | Description |
|---|---|
symbol | The trading pair symbol (e.g. 'BTC', 'ETH', 'xyz:TSLA'). |
marketKey | Optional cross-venue key for a grouped market. |
venues | Original rows from the group, used to match a legacy entry. |
legacyProvider | Venue that owned saved symbols before grouping. |
Handler signature:
(symbol: string, marketKey?: string, venues?: readonly PerpsMarketData[], legacyProvider?: PerpsProviderType) => void
PerpsController:refreshEligibility
Package: @metamask/perps-controller
Handler signature:
() => Promise<void>
PerpsController:replacePositionTPSLLeg
Package: @metamask/perps-controller
Replace only the take profit or only the stop loss of an existing
position. The other leg is left as it is, and the new leg keeps protecting
the whole position. Providers that cannot do this reject with
TPSL_LEG_REPLACE_UNSUPPORTED.
Parameters:
| Name | Description |
|---|---|
params | The leg, its new trigger price and optional limit price. |
Returns: The order result from the leg replacement.
Handler signature:
(params: ReplacePositionTPSLLegParams) => Promise<OrderResult>
PerpsController:resetFirstTimeUserState
Package: @metamask/perps-controller
Reset first-time user state for both networks This is useful for testing the tutorial flow Called by Reset Account feature in settings
Handler signature:
() => void
PerpsController:resetSelectedPaymentToken
Package: @metamask/perps-controller
Reset the selected payment token to Perps balance (null). Call when leaving the Perps order view so the next visit defaults to Perps balance.
Handler signature:
() => void
PerpsController:resolveRecoveryProtection
Package: @metamask/perps-controller
Execute an explicit successor for one selected durable protection obligation.
Parameters:
| Name | Description |
|---|---|
params | Owning provider, opaque source ID and new protection intent. |
Returns: Settled, unresolved or unsupported recovery result.
Handler signature:
(params: ResolveRecoveryProtectionParams) => Promise<PerpsRecoveryProtectionResult>
PerpsController:resolveWithdrawalRoute
Package: @metamask/perps-controller
Report the venue a withdrawal will sign on, using the same provider
resolution and the same refusal as withdraw.
While several venues are registered, a withdrawal without an explicit
venue is refused with PROVIDER_ROUTE_REQUIRED rather than falling back
to the routing default. This query reports that refusal as a
route_required result instead of throwing, so callers cannot mistake it
for a provider error or fail open around it. An explicit route that names
an unknown venue, or that conflicts with the active direct provider,
still throws PROVIDER_NOT_FOUND, matching getAccountSupport.
Note that a no-argument getAccountSupport read routes through the
routing default even when withdraw would refuse; use this method to
learn which venue a withdrawal would actually use.
Parameters:
| Name | Description |
|---|---|
params | Optional provider route, matching the route withdraw accepts. |
Returns: The resolved venue, or the route-required refusal.
Handler signature:
(params?: ResolveWithdrawalRouteParams) => Promise<WithdrawalRoute>
PerpsController:reviewAttachedOrderGroups
Package: @metamask/perps-controller
Review native attached lifecycle through provider-owned read authority.
Returns: Exact venue identities without financial replay or key registration.
Handler signature:
() => Promise<AttachedOrderGroup[]>
PerpsController:reviewRecoveryVenue
Package: @metamask/perps-controller
Review fresh venue positions and orders for one issuing provider context. Auth signing may be required; registration and financial writes are forbidden.
Parameters:
| Name | Description |
|---|---|
params | Owning provider route. |
params.providerId | Explicit provider identifier. |
Returns: Strict venue review or honest unsupported capability.
Handler signature:
(params?: {
providerId?: PerpsProviderType;
}) => Promise<PerpsRecoveryVenueReview>
PerpsController:reviewScaleOrderGroups
Package: @metamask/perps-controller
Reconcile durable Scale groups for an explicitly selected provider.
Parameters:
| Name | Description |
|---|---|
params | Issuing provider route. |
params.providerId | Provider to review. |
Returns: Fresh durable groups; never replays placement.
Handler signature:
(params?: {
providerId?: PerpsProviderType;
}) => Promise<ScaleOrderGroup[]>
PerpsController:saveMarginMode
Package: @metamask/perps-controller
Save the margin mode (Isolated/Cross) picked for a market on a venue on
the current network. Values other than isolated or cross are ignored.
Parameters:
| Name | Description |
|---|---|
symbol | Market symbol |
marginMode | Margin mode to persist |
providerId | Optional venue to key the mode under. Defaults to the live effective venue (active/saved default before initialization). |
Handler signature:
(symbol: string, marginMode: MarginMode, providerId?: PerpsProviderType) => void
PerpsController:saveMarketFilterPreferences
Package: @metamask/perps-controller
Save market filter preferences
Parameters:
| Name | Description |
|---|---|
optionId | Sort/filter option ID |
direction | Sort direction ('asc' or 'desc') |
Handler signature:
(optionId: SortOptionId, direction: SortDirection) => void
PerpsController:saveOrderBookGrouping
Package: @metamask/perps-controller
Save order book grouping for a market on a venue
Parameters:
| Name | Description |
|---|---|
symbol | Market symbol |
grouping | Price grouping value |
providerId | Optional venue to key the grouping under. Defaults to the live effective venue (active/saved default before initialization). |
Handler signature:
(symbol: string, grouping: number, providerId?: PerpsProviderType) => void
PerpsController:savePendingTradeConfiguration
Package: @metamask/perps-controller
Save pending trade configuration for a market This is a temporary configuration that expires after 30 seconds.
Parameters:
| Name | Description |
|---|---|
symbol | Market symbol |
config | Pending trade configuration (includes optional selected payment token from Pay row) |
config.amount | The amount value. |
config.leverage | The leverage multiplier. |
config.takeProfitPrice | The take profit price. |
config.stopLossPrice | The stop loss price. |
config.limitPrice | The limit price. |
config.orderType | The order type. |
config.reduceOnly | Whether the order may only reduce a position. |
config.direction | Long or short. |
config.selectedPaymentToken | The selected payment token. |
providerId | Optional venue to key the configuration under. Defaults to the live effective venue, or the active/saved default venue before initialization. |
Handler signature:
(symbol: string, config: {
amount?: string;
leverage?: number;
takeProfitPrice?: string;
stopLossPrice?: string;
limitPrice?: string;
orderType?: OrderType;
reduceOnly?: boolean;
direction?: OrderDirection;
/** When user used pay-with-token in PerpsPayRow: minimal token shape to restore selection */
selectedPaymentToken?: PerpsSelectedPaymentToken | null;
}, providerId?: PerpsProviderType) => void
PerpsController:saveTradeConfiguration
Package: @metamask/perps-controller
Save trade configuration for a market on a venue
Parameters:
| Name | Description |
|---|---|
symbol | Market symbol |
leverage | Leverage value |
providerId | Optional venue to key the configuration under. Defaults to the live effective venue, or the active/saved default venue before initialization. |
Handler signature:
(symbol: string, leverage: number, providerId?: PerpsProviderType) => void
PerpsController:setAgentSigner
Package: @metamask/perps-controller
Sign HyperLiquid L1 actions (orders, cancels, leverage, ...) for a main
account on a network with an approved agent, or pin them to the main
account with null (getAgentSigner is then not asked for that account and
network until clearAgentSigners). User-signed actions stay on the main
account, and the agent is never used for another account or network. The
controller keeps the binding across provider re-creation (a provider or
network switch, or re-initialization), so it can also be set before
init. Like every controller action, it is available through the
messenger once init has run.
Parameters:
| Name | Description |
|---|---|
account | The main account and network the agent is approved for. |
agentSigner | The host-owned agent signer, or null to pin the main account. |
Handler signature:
(account: PerpsAgentAccount, agentSigner: PerpsAgentSigner | null) => void
PerpsController:setAttributionContext
Package: @metamask/perps-controller
Set the transient UTM / discovery attribution context. Replaces any previously set context. Held in-memory only — not persisted.
Parameters:
| Name | Description |
|---|---|
context | The attribution context (UTM fields) to store. |
Handler signature:
(context: PerpsAttributionContext) => void
PerpsController:setDefaultProvider
Package: @metamask/perps-controller
Set the default provider used by aggregated-mode routing.
Persists the choice and, when the active provider is the aggregated
wrapper, updates its routing default in place. Unlike switchProvider
this never re-initializes the controller or reconnects provider transports:
default-routed streams move, but both venues stay connected and per-venue
writes are unaffected.
Parameters:
| Name | Description |
|---|---|
providerId | The provider to use as the aggregated default. |
Returns: The result with the new default provider.
Handler signature:
(providerId: PerpsProviderType) => SetDefaultProviderResult
PerpsController:setLiveDataConfig
Package: @metamask/perps-controller
Configure live data throttling
Parameters:
| Name | Description |
|---|---|
config | The configuration object. |
Handler signature:
(config: Partial<LiveDataConfig>) => void
PerpsController:setMaxSlippage
Package: @metamask/perps-controller
Set the user's max slippage tolerance in basis points.
Parameters:
| Name | Description |
|---|---|
bps | Max slippage in basis points (e.g. 300 = 3%). Clamped to 10–1000, snapped to step of 10. |
Handler signature:
(bps: number) => void
PerpsController:setOrderBookPreferences
Package: @metamask/perps-controller
Update market-agnostic Pro order-book display preferences.
Parameters:
| Name | Description |
|---|---|
patch | Partial order-book preferences to update. |
Handler signature:
(patch: Partial<OrderBookPreferences>) => void
PerpsController:setPerpsMode
Package: @metamask/perps-controller
Set the Perps interface mode (lite/pro).
Parameters:
| Name | Description |
|---|---|
mode | The mode to switch to. |
Handler signature:
(mode: PerpsMode) => void
PerpsController:setProLayoutPreferences
Package: @metamask/perps-controller
Update the user's pro-mode layout preferences.
Patch-style setter: only the provided fields are updated, the rest are preserved. This keeps the signature stable as new layout fields are added.
Parameters:
| Name | Description |
|---|---|
patch | Partial set of pro-mode layout preferences to update. |
Handler signature:
(patch: Partial<ProLayoutPreferences>) => void
PerpsController:setSelectedOrderType
Package: @metamask/perps-controller
Set the selected order type shared by every market.
Parameters:
| Name | Description |
|---|---|
orderType | The selected order type. |
Handler signature:
(orderType: OrderType) => void
PerpsController:setSelectedPaymentToken
Package: @metamask/perps-controller
Set the selected payment token for the Perps order/deposit flow. Pass null or a token with description PERPS_CONSTANTS.PerpsBalanceTokenDescription to select Perps balance. Only required fields (address, chainId) are stored in state; description and symbol are optional.
Parameters:
| Name | Description |
|---|---|
token | The token identifier. |
Handler signature:
(token: PerpsSelectedPaymentToken | null) => void
PerpsController:setVisibleCandleCount
Package: @metamask/perps-controller
Set the number of candles shown in Lite and Pro chart viewports.
Parameters:
| Name | Description |
|---|---|
count | Requested visible candle count. |
Handler signature:
(count: number) => void
PerpsController:startEligibilityMonitoring
Package: @metamask/perps-controller
Resume eligibility monitoring after onboarding completes. Clears the deferred flag and triggers an immediate eligibility check using the current remote feature flag state.
Handler signature:
() => void
PerpsController:startMarketDataPreload
Package: @metamask/perps-controller
Start background market data preloading. Fetches market data immediately and refreshes every 5 minutes. Watches for isTestnet and hip3ConfigVersion changes to re-preload.
Handler signature:
() => void
PerpsController:stopEligibilityMonitoring
Package: @metamask/perps-controller
Stops geo-blocking eligibility monitoring. Call this when the user disables basic functionality (e.g. useExternalServices becomes false). Prevents geolocation calls until startEligibilityMonitoring() is called again. Safe to call multiple times.
Handler signature:
() => void
PerpsController:stopMarketDataPreload
Package: @metamask/perps-controller
Stop background market data preloading.
Handler signature:
() => void
PerpsController:submitLighterTransfer
Package: @metamask/perps-controller
Send an L2 transfer from the user's Lighter account to another Lighter account, as a provider that moves funds out of Lighter (for example a Relay withdrawal) quotes it.
Always goes through the Lighter provider, whichever provider is active,
as long as it is registered or is the active provider. Exposed as the
PerpsController:submitLighterTransfer messenger action.
Parameters:
| Name | Description |
|---|---|
params | The transfer to sign and send. It fails when eoa is not the selected wallet. |
Returns: Whether Lighter accepted the transfer.
Handler signature:
(params: LighterTransferParams) => Promise<LighterTransferResult>
PerpsController:subscribeToAccount
Package: @metamask/perps-controller
Subscribe to live account updates. Updates controller state (Redux) when new account data arrives so consumers like usePerpsBalanceTokenFilter (PayWithModal) see the latest balance.
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: A cleanup function to remove the subscription.
Handler signature:
(params: SubscribeAccountParams) => () => void
PerpsController:subscribeToAvailableToTrade
Package: @metamask/perps-controller
Stream one market's per-side available to trade, as the venue reports it, through the provider route used by order placement. The venue pushes a new value when the market's position, leverage or mark price changes.
The callback only ever receives venue values. Until the first arrives the
value is unknown (undefined in clients). When no provider is active, the
route conflicts with the active provider, or the provider cannot read the
value from its venue, this returns a no-op cleanup and the value stays
unknown.
Parameters:
| Name | Description |
|---|---|
params | Market, optional route/account, callback and error handler. |
Returns: A cleanup function to remove the subscription.
Handler signature:
(params: SubscribeAvailableToTradeParams) => () => void
PerpsController:subscribeToCandles
Package: @metamask/perps-controller
Subscribe to live candle updates
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: A cleanup function to remove the subscription.
Handler signature:
(params: SubscribeCandlesParams) => () => void
PerpsController:subscribeToChaseOrderLists
Package: @metamask/perps-controller
Keep running and history chase lists for the active provider. Ended
chases stay in history after the provider drops them, up to
CHASE_ORDER_CONFIG.HistoryLimit.
Parameters:
| Name | Description |
|---|---|
params | Listener and optional error listener. |
Returns: A cleanup function that stops reads.
Handler signature:
(params: SubscribeChaseOrderListsParams) => () => void
PerpsController:subscribeToConnectionState
Package: @metamask/perps-controller
Subscribe to WebSocket connection state changes from the active provider. The listener will be called immediately with the current state and whenever the state changes.
Parameters:
| Name | Description |
|---|---|
listener | Callback function that receives the new connection state and reconnection attempt |
Returns: Unsubscribe function to remove the listener, or no-op if not supported
Handler signature:
(listener: (state: WebSocketConnectionState, reconnectionAttempt: number) => void) => () => void
PerpsController:subscribeToLiveTwapOrders
Package: @metamask/perps-controller
Keep one merged, live TWAP list for the active provider: reads and the
venue stream merged by schedule, execution totals raised from slice
fills, and re-reads while a schedule runs. Split it with
partitionTwapOrders. Follows the selected account.
Parameters:
| Name | Description |
|---|---|
params | Listener and optional error listener. |
Returns: A cleanup function that stops reads and the stream.
Handler signature:
(params: SubscribeLiveTwapOrdersParams) => () => void
PerpsController:subscribeToOICaps
Package: @metamask/perps-controller
Subscribe to open interest cap updates Zero additional network overhead - data comes from existing webData3 subscription
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: A cleanup function to remove the subscription.
Handler signature:
(params: SubscribeOICapsParams) => () => void
PerpsController:subscribeToOrderBook
Package: @metamask/perps-controller
Subscribe to full order book updates with multiple depth levels Creates a dedicated L2Book subscription for real-time order book data
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: A cleanup function to remove the subscription.
Handler signature:
(params: SubscribeOrderBookParams) => () => void
PerpsController:subscribeToOrderFills
Package: @metamask/perps-controller
Subscribe to live order fill updates
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: A cleanup function to remove the subscription.
Handler signature:
(params: SubscribeOrderFillsParams) => () => void
PerpsController:subscribeToOrders
Package: @metamask/perps-controller
Subscribe to live order updates
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: A cleanup function to remove the subscription.
Handler signature:
(params: SubscribeOrdersParams) => () => void
PerpsController:subscribeToPositions
Package: @metamask/perps-controller
Subscribe to live position updates
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: A cleanup function to remove the subscription.
Handler signature:
(params: SubscribePositionsParams) => () => void
PerpsController:subscribeToPrices
Package: @metamask/perps-controller
Subscribe to live price updates
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: A cleanup function to remove the subscription.
Handler signature:
(params: SubscribePricesParams) => () => void
PerpsController:subscribeToProviderHealth
Package: @metamask/perps-controller
Watch one provider's health. The callback receives the current value at once, then each change. In an aggregated session a controller re-initialization rebinds it to the replacement provider; otherwise callers resubscribe after re-initialization, as with other streams.
Parameters:
| Name | Description |
|---|---|
params | Provider to watch and the callback. |
params.providerId | Provider to watch. |
params.callback | Receives each health snapshot. |
Returns: Cleanup function.
Handler signature:
({ providerId, callback, }: SubscribeProviderHealthParams) => () => void
PerpsController:subscribeToPublicTrades
Package: @metamask/perps-controller
Stream a market's public trades (every user's trades) from the active provider, like the other market-data subscriptions.
The callback receives each batch of new trades the venue pushes, newest
first. Only a subscription that opens the venue channel may first
receive the venue's recent trades; one that joins a market another
subscription already streams receives only new trades. Seed the list with
getPublicTrades and dedupe batches on id. Nothing is delivered
after the returned cleanup runs, after the provider that opened the
stream stops being the active one (provider
switch, testnet toggle, reinitialization), or for any other symbol.
Subscribe again once the new provider is active. In aggregated mode an
unrouted stream follows the default provider: setDefaultProvider moves
it to the new venue, like subscribeToCandles. On Hyperliquid, like
subscribeToCandles, the stream is not restored after the client
service reconnects its WebSocket and onError is not called, so
resubscribe after a reconnect.
When no provider is active, the route conflicts with the active provider, or the provider has no public trade feed, this returns a no-op cleanup and never calls back.
Parameters:
| Name | Description |
|---|---|
params | Market, optional route, callback and error handler. |
Returns: A cleanup function to remove the subscription.
Handler signature:
(params: SubscribePublicTradesParams) => () => void
PerpsController:subscribeToTwapOrders
Package: @metamask/perps-controller
Stream TWAP lifecycle updates through the active provider.
Providers without a native TWAP push channel do not implement this; the
returned no-op cleanup lets a client fall back to polling getTwapOrders
without branching on provider identity.
Parameters:
| Name | Description |
|---|---|
params | Subscription parameters including callback and account ID. |
Returns: A cleanup function to remove the subscription.
Handler signature:
(params: SubscribeTwapOrdersParams) => () => void
PerpsController:suspendChaseOrders
Package: @metamask/perps-controller
Stop Chase repricing for app backgrounding. HyperLiquid leaves current children resting. The bounded Lighter probe attempts exact cancellation and reports canceled or termination_pending rather than a resting status.
Returns: Chase snapshots after suspension.
Handler signature:
() => Promise<ChaseOrder[]>
PerpsController:switchProvider
Package: @metamask/perps-controller
Switch to a different provider Uses a full reinit approach: disconnect() → update state → init() This ensures complete state reset including WebSocket connections and caches.
Parameters:
| Name | Description |
|---|---|
providerId | The provider identifier. |
Returns: The switch result with success status and active provider.
Handler signature:
(providerId: PerpsActiveProviderMode) => Promise<SwitchProviderResult>
PerpsController:toggleTestnet
Package: @metamask/perps-controller
Toggle between testnet and mainnet
Returns: The toggle result with success status and current network mode.
Handler signature:
() => Promise<ToggleTestnetResult>
PerpsController:toggleWatchlistMarket
Package: @metamask/perps-controller
Toggle watchlist status for a market.
Updates local state immediately (optimistic UI) and then syncs the new watchlist to AuthenticatedUserStorageService. If the remote write fails, the local state is reverted so it stays consistent with AUS.
When the user is unauthenticated, or the active provider is not yet supported by the AUS schema, the controller continues operating with local-persisted state only — no error is surfaced to the caller.
Watchlist markets are stored per network (testnet/mainnet).
Parameters:
| Name | Description |
|---|---|
symbol | The trading pair symbol. |
marketKey | Optional cross-venue key for a grouped market. |
venues | Original rows from the group, used to match a legacy favorite. |
legacyProvider | Venue that owned saved symbols before grouping. |
Handler signature:
(symbol: string, marketKey?: string, venues?: readonly PerpsMarketData[], legacyProvider?: PerpsProviderType) => Promise<void>
PerpsController:updateMargin
Package: @metamask/perps-controller
Update margin for an existing position (add or remove)
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: The margin update result.
Handler signature:
(params: UpdateMarginParams) => Promise<MarginResult>
PerpsController:updatePositionTPSL
Package: @metamask/perps-controller
Update TP/SL for an existing position
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: The order result from the TP/SL update.
Handler signature:
(params: UpdatePositionTPSLParams) => Promise<OrderResult>
PerpsController:updateWithdrawalProgress
Package: @metamask/perps-controller
Update withdrawal progress (persistent across navigation)
Parameters:
| Name | Description |
|---|---|
progress | The progress indicator. |
activeWithdrawalId | The active withdrawal ID. |
Handler signature:
(progress: number, activeWithdrawalId?: string | null) => void
PerpsController:updateWithdrawalStatus
Package: @metamask/perps-controller
Update withdrawal request status when it completes, or remove it on failure.
This is called when a withdrawal is matched with a completed withdrawal from the API.
When status is failed, the request is removed from the queue (not retained).
Parameters:
| Name | Description |
|---|---|
withdrawalId | The withdrawal transaction ID. |
status | The current status. |
txHash | The transaction hash. |
Handler signature:
(withdrawalId: string, status: 'completed' | 'failed', txHash?: string) => void
PerpsController:validateClosePosition
Package: @metamask/perps-controller
Validate close position parameters according to protocol-specific rules
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: A promise that resolves to the result.
Handler signature:
(params: ClosePositionParams) => Promise<{
isValid: boolean;
error?: string;
}>
PerpsController:validateOrder
Package: @metamask/perps-controller
Validate order parameters according to protocol-specific rules
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: True if the condition is met.
Handler signature:
(params: OrderParams) => Promise<{
isValid: boolean;
error?: string;
}>
PerpsController:validateWithdrawal
Package: @metamask/perps-controller
Validate withdrawal parameters according to protocol-specific rules
Parameters:
| Name | Description |
|---|---|
params | The operation parameters. |
Returns: True if the condition is met.
Handler signature:
(params: WithdrawParams) => Promise<{
isValid: boolean;
error?: string;
}>
PerpsController:withdraw
Package: @metamask/perps-controller
Withdraw funds from trading account
The withdrawal process varies by provider and may involve:
- Direct on-chain transfers
- Bridge operations
- Multi-step validation processes
Check the specific provider documentation for detailed withdrawal flows.
Parameters:
| Name | Description |
|---|---|
params | Withdrawal parameters |
Returns: WithdrawResult with withdrawal ID and tracking info
Handler signature:
(params: WithdrawParams) => Promise<WithdrawResult>