types.ts
Overview
The [types.ts](/projects/291/69107) file defines TypeScript types and utility type-guard functions primarily related to handling WebSocket responses and parsed Solana blockchain transactions. It provides strong typing for WebSocket subscription messages, transaction data structures, and balances, facilitating safer and clearer interaction with Solana's Web3.js library and WebSocket communication.
Key functionalities include:
Typing of parsed Solana transactions excluding the slot number.
Interfaces representing JSON-RPC 2.0 WebSocket subscription responses.
Type guards to differentiate between subscription response types.
A type describing native SOL balance with pricing information.
This file acts as a foundational type-definition module to ensure consistent and error-resistant handling of Solana blockchain transaction and WebSocket data within the application.
Detailed Explanation
Type Aliases and Interfaces
Transaction
export type Transaction = Omit<ParsedTransactionWithMeta, 'slot'>
Description: Represents a parsed Solana transaction with metadata, explicitly omitting the
slotfield.Source Type:
ParsedTransactionWithMetafrom@solana/web3.js— a detailed transaction object including signatures, instructions, metadata, and the block slot.Use Case: When the slot number is either managed separately or irrelevant, this type provides a cleaner transaction object without the slot.
WebsocketSubscribeResponse<T = unknown>
export interface WebsocketSubscribeResponse<T = unknown> {
jsonrpc: '2.0'
id: string
method: string
result: T
}
Description: Represents a standard JSON-RPC 2.0 subscription response message received over WebSocket.
Properties:
jsonrpc: Version of JSON-RPC protocol; fixed as'2.0'.id: Unique identifier correlating response to request.method: The JSON-RPC method name.result: Generic result data, parameterized byT.
Use Case: Used for initial subscription acknowledgments or calls returning a value, such as subscription IDs.
WebsocketResponse
export interface WebsocketResponse {
jsonrpc: '2.0'
method: string
params: Params
}
Description: Represents push notification messages delivered over WebSocket subscriptions.
Properties:
jsonrpc: JSON-RPC version, fixed'2.0'.method: The notification method name.params: Object containing subscription data.
Use Case: Used to handle incoming subscription events, such as logs or transaction updates.
Internal Interfaces: Params and Result
interface Params {
subscription: number
result: Result
}
interface Result {
value: Logs
context: {
slot: number
}
}
Params:
subscription: The subscription ID linked to the notification.result: The actual notification payload.
Result:
value: ContainsLogsdata from@solana/web3.jsrepresenting log entries for a transaction.context: Metadata including theslotnumber where the data was recorded.
Use Case: Helps structure the payload of subscription event data pushed from Solana WebSocket.
NativeBalance
export type NativeBalance = {
lamports: number
price_per_sol: number
total_price: number
}
Description: Represents the balance information of native SOL tokens.
Properties:
lamports: Amount held in lamports (1 SOL = 1,000,000,000 lamports).price_per_sol: Current price of 1 SOL (presumably USD or another fiat).total_price: Total fiat value calculated aslamports / 1e9 * price_per_sol.
Use Case: Used to represent wallet balances with pricing for UI display or calculations.
Functions
isWebsocketResponse
export const isWebsocketResponse = (data: unknown): data is WebsocketResponse => {
return Boolean(typeof data === 'object' && data && 'method' in data && 'params' in data)
}
Purpose: Type guard to verify if a given
dataobject conforms to theWebsocketResponseinterface.Parameters:
data— any unknown value, typically a parsed JSON message.
Returns:
trueifdatahasmethodandparamskeys, indicating it is a WebSocket notification response.Usage Example:
const msg: unknown = JSON.parse(incomingMessage);
if (isWebsocketResponse(msg)) {
// TypeScript narrows type of msg to WebsocketResponse here
console.log(msg.method, msg.params.subscription);
}
isWebsocketSubscribeResponse
export const isWebsocketSubscribeResponse = (data: unknown): data is WebsocketSubscribeResponse<number> => {
return Boolean(typeof data === 'object' && data && 'result' in data && typeof data.result === 'number')
}
Purpose: Type guard to check if
datais a WebSocket subscription response with a numeric subscription ID.Parameters:
data— unknown input, usually a parsed JSON-RPC message.
Returns:
trueifdata.resultis a number, indicating a subscription response.Usage Example:
const msg: unknown = JSON.parse(incomingMessage);
if (isWebsocketSubscribeResponse(msg)) {
console.log('Subscription ID:', msg.result);
}
Implementation Details and Algorithms
The file uses TypeScript's advanced typing features (
Omit, generics, type guards) to provide precise typings and runtime type validation.The type guards rely on simple property existence and type checks (
'in'operator,typeof) to discriminate message shapes from untyped JSON data.The design aligns with the JSON-RPC 2.0 specification for WebSocket interaction, handling both subscription confirmation and event notification messages.
The omission of the
slotfield in theTransactiontype indicates that slot management is handled separately in the application, which may optimize data flow or caching.
Interaction with Other Parts of the System
This file imports
LogsandParsedTransactionWithMetatypes from the@solana/web3.jslibrary, reflecting integration with the Solana blockchain SDK.Types declared here are used by WebSocket client modules that subscribe to Solana events, enabling typed handling of blockchain logs and transactions.
The
NativeBalancetype supports wallet or portfolio modules displaying user balances and their fiat value.The file underpins WebSocket message processing layers, ensuring that incoming JSON-RPC messages are correctly identified and parsed before business logic consumes them.
Visual Diagram: Flowchart of WebSocket Message Handling Types
flowchart TD
A[Incoming WebSocket Data] --> B{Is WebsocketSubscribeResponse?}
B -- Yes --> C[Handle Subscription Response]
B -- No --> D{Is WebsocketResponse?}
D -- Yes --> E[Handle Notification Response]
D -- No --> F[Unknown Message Type]
subgraph Types
B
D
end
subgraph Handlers
C
E
F
end
The diagram illustrates how incoming WebSocket messages are type-checked using
isWebsocketSubscribeResponseandisWebsocketResponseto determine handling paths.
Summary
[types.ts](/projects/291/69107) provides essential typing and validation utilities for handling Solana WebSocket JSON-RPC messages and transaction data. Its well-defined interfaces and type guards improve type safety and clarity in processing blockchain event streams and subscription responses, serving as a foundational piece in the application's Solana integration layer.