BackendWebSocketService Actions
13 actions registered.
BackendWebSocketService:addChannelCallback
Package: @metamask/core-backend
Register a callback for specific channels (local callback only, no server subscription)
Key Difference from subscribe():
-
addChannelCallback(): Registers a local callback without creating a server-side subscription. The callback triggers on ANY message matching the channel name, regardless of subscriptionId. Useful for system-wide notifications or when you don't control the subscription lifecycle. -
subscribe(): Creates a proper server-side subscription with a subscriptionId. The callback only triggers for messages with the matching subscriptionId. Includes proper lifecycle management (unsubscribe, automatic cleanup on disconnect).
When to use addChannelCallback():
- Listening to system-wide notifications (e.g., 'system-notifications.v1')
- Monitoring channels where subscriptions are managed elsewhere
- Debug/logging scenarios where you want to observe all channel messages
When to use subscribe() instead:
- Creating new subscriptions that need server-side registration
- When you need proper cleanup via unsubscribe
- Most application use cases (recommended approach)
Parameters:
| Name | Description |
|---|---|
options | Channel callback configuration |
options.channelName | Channel name to match exactly |
options.callback | Function to call when channel matches |
Handler signature:
(options: {
channelName: string;
callback: (notification: ServerNotificationMessage) => void;
}) => void
BackendWebSocketService:channelHasSubscription
Package: @metamask/core-backend
Checks if a channel has a subscription
Parameters:
| Name | Description |
|---|---|
channel | The channel name to check |
Returns: True if the channel has a subscription, false otherwise
Handler signature:
(channel: string) => boolean
BackendWebSocketService:connect
Package: @metamask/core-backend
Establishes WebSocket connection with smart reconnection behavior
Connection Requirements (all must be true):
- Feature enabled (isEnabled() = true)
- Basic functionality enabled (isBasicFunctionality() = true)
- Wallet unlocked (checked by getBearerToken)
- User signed in (checked by getBearerToken)
Platform code should call this when app opens/foregrounds. Automatically called on KeyringController:unlock event.
Returns: Promise that resolves when connection is established
Handler signature:
() => Promise<void>
BackendWebSocketService:disconnect
Package: @metamask/core-backend
Closes the WebSocket and cancels a queued reconnect.
The timer is cleared before the early return. Lock, sign-out, and Basic
Functionality off all call this, including when the socket is already gone
and onclose will not run. clearTimeout has to run first: assigning
#reconnectTimer to null leaves the callback scheduled.
Handler signature:
() => void
BackendWebSocketService:findSubscriptionsByChannelPrefix
Package: @metamask/core-backend
Finds all subscriptions that have channels starting with the specified prefix
Parameters:
| Name | Description |
|---|---|
channelPrefix | The channel prefix to search for (e.g., "account-activity.v1") |
Returns: Array of subscription info for matching subscriptions
Handler signature:
(channelPrefix: string) => WebSocketSubscription[]
BackendWebSocketService:forceReconnection
Package: @metamask/core-backend
Forces a WebSocket reconnection to clean up subscription state
This method is useful when subscription state may be out of sync and needs to be reset. It performs a controlled disconnect-then-reconnect sequence:
- Disconnects cleanly to trigger subscription cleanup
- Schedules reconnection with exponential backoff to prevent rapid loops
- All subscriptions will be cleaned up automatically on disconnect
Use cases:
- Recovering from subscription/unsubscription issues
- Cleaning up orphaned subscriptions
- Forcing a fresh subscription state
Returns: Promise that resolves when disconnection is complete (reconnection is scheduled)
Handler signature:
() => Promise<void>
BackendWebSocketService:getChannelCallbacks
Package: @metamask/core-backend
Get all registered channel callbacks (for debugging)
Returns: Array of all registered channel callbacks
Handler signature:
() => ChannelCallback[]
BackendWebSocketService:getConnectionInfo
Package: @metamask/core-backend
Gets current connection information
Returns: Current connection status and details
Handler signature:
() => WebSocketConnectionInfo
BackendWebSocketService:removeChannelCallback
Package: @metamask/core-backend
Remove a channel callback
Parameters:
| Name | Description |
|---|---|
channelName | The channel name returned from addChannelCallback |
Returns: True if callback was found and removed, false otherwise
Handler signature:
(channelName: string) => boolean
BackendWebSocketService:sendMessage
Package: @metamask/core-backend
Sends a message through the WebSocket (fire-and-forget, no response expected)
This is a low-level method for sending messages without waiting for a response.
Most consumers should use sendRequest() instead, which handles request-response
correlation and provides proper error handling with timeouts.
Use this method only when:
- You don't need a response from the server
- You're implementing custom message protocols
- You need fine-grained control over message timing
Parameters:
| Name | Description |
|---|---|
message | The message to send |
Handler signature:
(message: ClientRequestMessage) => void
BackendWebSocketService:sendRequest
Package: @metamask/core-backend
Sends a request and waits for a correlated response (recommended for most use cases)
This is the recommended high-level method for request-response communication. It automatically handles:
- Request ID generation and correlation
- Response matching with timeout protection
- Automatic reconnection on timeout
- Proper cleanup of pending requests
Parameters:
| Name | Description |
|---|---|
message | The request message (can include optional requestId for testing) |
Returns: Promise that resolves with the response data
Handler signature:
(message: Omit<ClientRequestMessage, 'data'> & {
data?: Omit<ClientRequestMessage['data'], 'requestId'> & {
requestId?: string;
};
}) => Promise<Type>
BackendWebSocketService:subscribe
Package: @metamask/core-backend
Create and manage a subscription with server-side registration (recommended for most use cases)
This is the recommended subscription API for high-level services. It creates a proper server-side subscription and routes notifications based on subscriptionId.
Key Features:
- Creates server-side subscription with unique subscriptionId
- Callback triggered only for messages with matching subscriptionId
- Automatic lifecycle management (cleanup on disconnect)
- Includes unsubscribe method for proper cleanup
- Request-response pattern with error handling
When to use subscribe():
- Creating new subscriptions (account activity, price updates, etc.)
- When you need proper cleanup/unsubscribe functionality
- Most application use cases
When to use addChannelCallback() instead:
- System-wide notifications without server-side subscription
- Observing channels managed elsewhere
- Debug/logging scenarios
Parameters:
| Name | Description |
|---|---|
options | Subscription configuration |
options.channels | Array of channel names to subscribe to |
options.callback | Callback function for handling notifications |
options.requestId | Optional request ID for testing (will generate UUID if not provided) |
options.channelType | Channel type identifier |
Returns: Subscription for the channels the gateway accepted. failed lists the channels it refused. A response that accepts nothing rejects.
Handler signature:
(options: {
/** Channel names to subscribe to */
channels: string[];
/** Channel type with version (e.g., 'account-activity.v1') for tracing and monitoring */
channelType: string;
/** Handler for incoming notifications */
callback: (notification: ServerNotificationMessage) => void;
/** Optional request ID for testing (will generate UUID if not provided) */
requestId?: string;
}) => Promise<WebSocketSubscription>
BackendWebSocketService:unsubscribeChannels
Package: @metamask/core-backend
Remove these channels from the server.
Channels stored on the same subscription go out in one unsubscribe frame. A channel the server does not have is skipped. A refusal on one subscription does not skip the others.
Channels the gateway refuses are returned in failed and stay stored. The
caller decides whether to retry or give up. A request that fails outright,
or a reply that does not acknowledge the removal, rejects instead.
Parameters:
| Name | Description |
|---|---|
channels | Fully-qualified channel names to close. |
Returns: The channels the gateway refused to close.
Handler signature:
(channels: readonly string[]) => Promise<UnsubscribeResult>