Demos Network Specifications
  • Introduction
    • What is Demos Network
    • Demos Network Architecture
  • FAQ
  • Cookbook
    • Project setup
      • Run the project (MacOS)
      • Run the project (Windows)
        • WSL 2 Setup on Windows (10 and 11 only)
        • Issue Troubleshooting
      • Run the project (Ubuntu)
  • SDK
    • Getting Started
    • WebSDK
      • Authentication
        • FIDO2 Passkeys
          • Under the Hood: FIDO2 Passkeys
      • NodeCalls
      • Transactions
        • Creating a transaction
        • Signing a transaction
        • Broadcasting a transaction
      • L2PS SDK
        • The l2ps module
        • Interacting with the L2PS
        • L2PS Messaging System
      • Instant Messaging
        • What is the Instant Messaging Protocol?
        • Architecture Overview
        • Encryption
        • Quickstart
        • Message Types
        • API Reference
        • FAQ
    • Cross Chain
      • General layout of the XM SDKs
      • EVM
      • BTC
      • Solana
      • MultiversX (EGLD)
      • NEAR
      • IBC
      • TON
      • XRPL
      • The XMScript
      • Identities
    • Demoswork
    • Cookbook
      • Demoswork
        • Creating work steps
        • Conditional Operation
        • Base Operation
        • Signing and broadcasting
      • Transactions
        • Crosschain Transaction
        • Native Transactions
      • SWAP
        • Crosschain SWAP
    • Web2
      • Quick Start
      • DAHR API Reference
        • Types
      • Making Requests
      • Identities
        • Twitter
        • GitHub
    • API Reference
    • Bridges
      • Rubic Bridge Test
    • Post Quantum Cryptography
  • Backend
    • Internal Mechanisms
      • Network Time Synchronization
      • Cross Context Identities
    • Global Change Registry
      • GCR Structure
      • How is GCR Synced?
    • Consensus Mechanism
      • Unparalleled Scalability
      • Decentralization in PoR-BFT
      • Enhanced Security
      • Comparative Advantage
      • Addressing Potential Criticisms
      • Conclusion
    • Communications Stack
    • L2PS (Subnet) Framework
      • How are L2PS transactions handled?
    • Miscellaneous
      • Browsing the Postgres DB via psql
    • Bridges
      • Rubic Bridge
    • Developers Testbed
      • Setting up the environment
      • Setting up the repository
      • Installing dependencies
      • Node Configuration
      • Running the node
  • Frontend
    • Demos Providers Discovery Mechanism
Powered by GitBook
On this page
  1. SDK
  2. WebSDK
  3. Instant Messaging

API Reference

The MessagingPeer class is the core component of the Instant Messaging Protocol. It handles connection to the signaling server, peer discovery, message exchange, and encryption/decryption.

Constructor

constructor(config: MessagingPeerConfig)

Creates a new MessagingPeer instance.

Parameters:

  • config: Configuration object containing:

    • serverUrl: WebSocket URL of the signaling server (the Demos Node managing the messenger instance)

    • clientId: Unique identifier for this peer

    • publicKey: Public key for encryption/decryption

Example:

const peer = new MessagingPeer({
    serverUrl: "ws://your-signaling-server:3005",
    clientId: "your-unique-id",
    publicKey: mlKemAes.publicKey,
})

Methods

connect

async connect(): Promise<void>

Connects to the signaling server and registers the peer.

Returns: Promise that resolves when connected and registered

Example:

await peer.connect()

disconnect

disconnect(): void

Disconnects from the signaling server.

Example:

peer.disconnect()

register

register(): void

Registers the peer with the signaling server.

Example:

peer.register()

registerAndWait

async registerAndWait(): Promise<void>

Registers the peer with the signaling server and waits for confirmation.

Returns: Promise that resolves when registration is confirmed

Example:

await peer.registerAndWait()

discoverPeers

async discoverPeers(): Promise<string[]>

Discovers all connected peers.

Returns: Array of peer IDs

Example:

const peers = await peer.discoverPeers()
console.log("Available peers:", peers)

sendMessage

async sendMessage(targetId: string, message: string): Promise<void>

Sends an encrypted message to a specific peer.

Parameters:

  • targetId: ID of the target peer

  • message: Message to send

Example:

await peer.sendMessage("target-peer-id", "Hello from me!")

requestPublicKey

async requestPublicKey(peerId: string): Promise<Uint8Array>

Requests a peer's public key.

Parameters:

  • peerId: ID of the peer whose public key to request

Returns: The peer's public key as a Uint8Array

Example:

const publicKey = await peer.requestPublicKey("target-peer-id")

respondToServer

respondToServer(questionId: string, response: any): void

Responds to a server question.

Parameters:

  • questionId: ID of the question to respond to

  • response: Response to send back to the server

Example:

peer.respondToServer("question-123", { answer: "This is my answer" })

sendToServerAndWait

async sendToServerAndWait<T = any>(
    message: Message,
    expectedResponseType: Message["type"],
    options: {
        timeout?: number
        errorHandler?: (error: any) => void
        retryCount?: number
        filterFn?: (message: Message) => boolean
    } = {},
): Promise<T>

Sends a message to the server and waits for a specific response type.

Parameters:

  • message: Message to send

  • expectedResponseType: Type of response to wait for

  • options: Additional options:

    • timeout: Timeout in milliseconds (default: 10000)

    • errorHandler: Custom error handler

    • retryCount: Number of retry attempts

    • filterFn: Function to filter messages by additional criteria

Returns: The response payload

Example:

// Basic usage
const response = await peer.sendToServerAndWait(
    {
        type: "custom_action",
        payload: { someData: "value" },
    },
    "custom_action_success",
)

// With retry logic
const response = await peer.sendToServerAndWait(
    {
        type: "custom_action",
        payload: { someData: "value" },
    },
    "custom_action_success",
    {
        retryCount: 3,
        timeout: 5000,
    },
)

// With custom error handling
const response = await peer.sendToServerAndWait(
    {
        type: "custom_action",
        payload: { someData: "value" },
    },
    "custom_action_success",
    {
        errorHandler: error => {
            console.error("Custom error handling:", error)
        },
    },
)

// With filtering
const response = await peer.sendToServerAndWait(
    {
        type: "custom_action",
        payload: { someData: "value" },
    },
    "custom_action_success",
    {
        filterFn: message => message.payload.someProperty === expectedValue,
    },
)

Event Handlers

onMessage

onMessage(handler: (message: any, fromId: string) => void): void

Registers a handler for incoming messages.

Parameters:

  • handler: Function to call when a message is received

Example:

peer.onMessage((message, fromId) => {
    console.log(`Message from ${fromId}:`, message)
})

onServerQuestion

onServerQuestion(handler: (question: any, questionId: string) => void): void

Registers a handler for server questions.

Parameters:

  • handler: Function to call when a server question is received

Example:

peer.onServerQuestion((question, questionId) => {
    console.log("Server asked:", question)

    // Process the question and prepare a response
    const response = { answer: "This is my answer" }

    // Send the response back to the server
    peer.respondToServer(questionId, response)
})

onError

onError(handler: (error: { type: string; details: string }) => void): void

Registers a handler for errors.

Parameters:

  • handler: Function to call when an error occurs

Example:

peer.onError(error => {
    console.error(`Error: ${error.type} - ${error.details}`)
})

onPeerDisconnected

onPeerDisconnected(handler: (peerId: string) => void): void

Registers a handler for peer disconnection events.

Parameters:

  • handler: Function to call when a peer disconnects

Example:

peer.onPeerDisconnected(peerId => {
    console.log(`Peer disconnected: ${peerId}`)
})

onConnectionStateChange

onConnectionStateChange(handler: (state: "connected" | "disconnected" | "reconnecting") => void): void

Registers a handler for connection state changes.

Parameters:

  • handler: Function to call when the connection state changes

Example:

peer.onConnectionStateChange(state => {
    console.log(`Connection state changed: ${state}`)
})

Message Types

The Instant Messaging Protocol supports various message types:

  • "register": Register a new peer with the server

  • "discover": Request a list of all connected peers

  • "message": Encrypted peer-to-peer messages

  • "peer_disconnected": Notification when a peer disconnects

  • "request_public_key": Request a peer's public key

  • "public_key_response": Response containing a peer's public key

  • "server_question": Question from the server to a peer

  • "peer_response": Response from a peer to a server question

  • "debug_question": Debug message to trigger a server question

  • "error": Error notification with details

Message Interface

export interface Message {
    type:
        | "register"
        | "discover"
        | "message"
        | "peer_disconnected"
        | "request_public_key"
        | "public_key_response"
        | "server_question"
        | "peer_response"
        | "debug_question"
        | "error"
    payload: any
}

MessagingPeerConfig Interface

export interface MessagingPeerConfig {
    serverUrl: string
    clientId: string
    publicKey: Uint8Array
PreviousMessage TypesNextFAQ

Last updated 1 month ago