RathRath Finance
SDK Reference

Register WebSocket

SDK method to register a WebSocket connection and retrieve connection details for real-time communication with Tachyon.

registerWebsocket()

Registers a WebSocket for a user and returns the connection details needed to establish a real-time connection with the Tachyon relay service.

const wsConfig = await tachyon.registerWebsocket();

Returns: Promise<WebsocketRegistrationResponse> - Response of registered websocket

WebsocketRegistrationResponse Properties:

  • wsUrl: WebSocket URL to connect to
  • apiKey: User-specific persistent API key for authentication

Usage Examples

Basic WebSocket Connection

import { Tachyon } from '@rathfi/tachyon'

// Initialize Tachyon client
const tachyon = new Tachyon({
  apiKey: 'YOUR_API_KEY',
})

// Register WebSocket and get connection details
const wsConfig = await tachyon.registerWebsocket()
console.log('WebSocket URL:', wsConfig.wsUrl)
console.log('API Key:', wsConfig.apiKey)

// Connect to WebSocket
const ws = new WebSocket(wsConfig.wsUrl, {
  headers: {
    'x-ws-token': wsConfig.apiKey,
  },
})

ws.on('open', () => {
  console.log('WebSocket connected!')
})

ws.on('message', (data) => {
  const message = JSON.parse(data.toString())
  console.log('Received:', message)
})

ws.on('close', () => {
  console.log('WebSocket disconnected')
})

ws.on('error', (error) => {
  console.error('WebSocket error:', error)
})

Browser Usage

import { Tachyon } from '@rathfi/tachyon'

const tachyon = new Tachyon({
  apiKey: 'YOUR_API_KEY',
})

// Register and connect
const wsConfig = await tachyon.registerWebsocket()

// Create WebSocket connection (browsers don't support custom headers in constructor)
// The token must be passed as a query parameter or handled differently
const ws = new WebSocket(wsConfig.wsUrl)

ws.onopen = () => {
  console.log('WebSocket connected!')
}

ws.onmessage = (event) => {
  const message = JSON.parse(event.data)
  console.log('Received:', message)
  
  if (message.error) {
    console.error('Error:', message.error)
  }
}

ws.onclose = () => {
  console.log('WebSocket disconnected')
}

ws.onerror = (error) => {
  console.error('WebSocket error:', error)
}

// Send a message
ws.send(JSON.stringify({ type: 'ping', data: 'Hello!' }))

Sending and Receiving Messages

const wsConfig = await tachyon.registerWebsocket()

const ws = new WebSocket(wsConfig.wsUrl, {
  headers: {
    'x-ws-token': wsConfig.apiKey,
  },
})

ws.on('open', () => {
  // Send a message to the server
  ws.send(JSON.stringify({
    type: 'subscribe',
    chainId: 8453,
  }))
})

ws.on('message', (data) => {
  const message = JSON.parse(data.toString())
  
  // Handle initial connection message
  if (message.message === 'WebSocket connected!') {
    console.log('Successfully connected to Tachyon relay')
  }
  
  // Handle echo responses
  if (message.echo) {
    console.log('Echo from server:', message.echo)
  }
  
  // Handle errors
  if (message.error) {
    console.error('Server error:', message.error)
  }
})

Monitoring Transaction Updates

const wsConfig = await tachyon.registerWebsocket()

const ws = new WebSocket(wsConfig.wsUrl, {
  headers: {
    'x-ws-token': wsConfig.apiKey,
  },
})

// Submit a transaction
const txId = await tachyon.relay({
  chainId: 8453,
  to: '0x3dbE34f2C21b3B2980d4dc53f3c7E51e39663F49',
  value: '1',
  callData: '0x',
})

console.log('Transaction submitted:', txId)

// Listen for real-time updates
ws.on('message', (data) => {
  const message = JSON.parse(data.toString())
  
  // Handle transaction status updates
  if (message.type === 'tx-update' && message.txId === txId) {
    console.log('Transaction status:', message.status)
    
    if (message.executionTxHash) {
      console.log('Execution hash:', message.executionTxHash)
    }
  }
})

Connection with Automatic Reconnection

let ws: WebSocket
let wsConfig: any
let reconnectAttempts = 0
const MAX_RECONNECT_ATTEMPTS = 5

async function connectWebSocket() {
  try {
    // Register WebSocket (reuse config if already registered)
    if (!wsConfig) {
      wsConfig = await tachyon.registerWebsocket()
    }
    
    ws = new WebSocket(wsConfig.wsUrl, {
      headers: {
        'x-ws-token': wsConfig.apiKey,
      },
    })
    
    ws.on('open', () => {
      console.log('WebSocket connected!')
      reconnectAttempts = 0
    })
    
    ws.on('message', (data) => {
      const message = JSON.parse(data.toString())
      console.log('Received:', message)
    })
    
    ws.on('close', () => {
      console.log('WebSocket closed')
      attemptReconnect()
    })
    
    ws.on('error', (error) => {
      console.error('WebSocket error:', error)
    })
  } catch (error) {
    console.error('Failed to connect:', error)
    attemptReconnect()
  }
}

function attemptReconnect() {
  if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
    reconnectAttempts++
    const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000)
    console.log(`Reconnecting in ${delay}ms... (attempt ${reconnectAttempts})`)
    setTimeout(connectWebSocket, delay)
  } else {
    console.error('Max reconnection attempts reached')
  }
}

// Initialize connection
connectWebSocket()

Authentication

The WebSocket connection requires authentication using the x-ws-token header with the API key returned from registerWebsocket(). If authentication fails, the connection will be closed with an "Unauthorized" error message.

Important: The API key returned from registerWebsocket() is user-specific and persistent. Store it securely and reuse it for subsequent connections.

On this page