Klave logo

SCP APIs

This section describes several useful APIs of the SCP class.

Create SCP with logger, connect, test, close and reset

import { Key, SCP } from '@secretarium/connector';

async function main() {

    // We create the new connector context and provide the console as a logger
    const context = new SCP({logger: console});
    // We create a new connection key or provide an existing one
    const myKey = await Key.createKey()
    // We start the connection to Klave
    const connection = await context.connect('wss://on.klave.network', myKey)
    // Check the connection
    const isConnected = context.isConnected()
    // Check the endpoint
    const endpoint = context.getEndPoint()
    // Close the connection
    context.close()
    // Reset the connection
    context.reset()
}

main()
import asyncio
from secretarium_connector import SCP, Key

async def main():

     # Create or retrieve a logger named 'typescript.connector'
    logger = logging.getLogger("typescript.connector")
    # Set the logging level for this logger
    logger.setLevel(logging.DEBUG)
    # Create a file handler
    file_handler = logging.FileHandler('python_connector.log')
    file_handler.setLevel(logging.DEBUG)
    # Create a formatter and set it for the handler
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler.setFormatter(formatter)
    # Add the handler to the logger
    logger.addHandler(file_handler)

    #We create the new connector context with the defined logger
    context = SCP(SCPOptions(logger))
    #We create a new connection key or provide an existing one
    myKey = await Key.createKey()
    #We start the connection to Klave
    connection = await context.connect('wss://on.klave.network', myKey)
    #Check the connection
    isConnected = context.isConnected()
    #Check the endpoint
    endpoint = context.getEndPoint()
    #Close the connection
    context.close()
    #Reset the connection
    context.reset()


asyncio.run(main())
use std::{collections::HashMap, time::Duration};
use tokio::time::sleep;
use klave_connector::{SCP, Key};

#[tokio::main]
async fn main() {   
    //Read file from connectionKeys folder
    let key = match Key::import_jwk("<Use your own Key>", "klave") {
        Ok(key) => {
            println!("Key imported successfully.");
            key
        }
        Err(e) => {
            eprintln!("Failed to import key: {}", e);
            return;
        }
    };
    
    let mut client = SCP::new(KLAVE_TEST, Some(&key), None);

    // Connect to the WebSocket (this will now perform the default handshake)
    match client.connect().await {
        Ok(_) => println!("WebSocket client connected successfully."),
        Err(e) => {
            eprintln!("Failed to connect WebSocket client: {}", e);            
        }
    };

    // Simulate sending messages after some delay
    sleep(Duration::from_secs(2)).await;

    println!("Sending a transaction with custom callbacks...");
    let mut tx = client.new_tx("<your-app>", "version", None, None).await;
    tx.on_error(|request_id, error_message| {
        eprintln!("Transaction error occurred. RequestId: {:?}, Error: {:?}", request_id, error_message);
    });
    tx.on_executed(|request_id, message| {
        eprintln!("Transaction executed. RequestId: {:?}, Message: {:?}", request_id, message);
    });
    tx.on_result(|request_id, result| {
        eprintln!("LMB Result 1: RequestId: {:?}, Result: {:?}", request_id, result);
    });
    tx.on_result(|request_id, result| {
        eprintln!("LMB Result 2: RequestId: {:?}, Result: {:?}", request_id, result);
    });
    let _ = tx.send().await;

    sleep(Duration::from_secs(5)).await;

    println!("Sending a transaction with default callbacks...");
    let tx_default = client.new_tx("<your-app>", "version", None, None).await;
    let _ = tx_default.send().await;

    sleep(Duration::from_secs(5)).await;

    println!("Sending periodic calls...");
    let tx3_periodic = client.new_periodic_tx("<your-app>", "version", None, None, 5).await;
    let _ = tx3_periodic.send().await;

    // Keep the main task alive until you decide to close the connection
    println!("Press Enter to close the WebSocket connection from main app.");
    let mut buffer = String::new();
    match std::io::stdin().read_line(&mut buffer).map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync + 'static>) {
        Ok(_) => println!("Received input: {}", buffer),
        Err(e) => eprintln!("Failed to read input: {}", e),
    };

    // Close the connection
    match client.close().await {
        Ok(_) => println!("WebSocket client closed successfully."),
        Err(e) => eprintln!("Failed to close WebSocket client: {}", e),
    };

    println!("WebSocket client finished in main app.");        
}

Callbacks onError and onStateChange

import { Key, SCP } from '@secretarium/connector';

async function main() {

    const context = new SCP();
    context.onStateChange(state => console.log("SCP new state: " + state));
    context.onError(err => console.log("SCP error: " + err))

    const myKey = await Key.createKey()
    const connection = await context.connect('wss://on.klave.network', myKey)
}

main()
import asyncio
from secretarium_connector import SCP, Key

async def main():

    context = SCP()
    context.onError(lambda error: print(f"SCP error: {error}"))
    context.onStateChange(lambda state: print(f"SCP new state: {state}"))

    myKey = await Key.createKey()
    connection = await context.connect('wss://on.klave.network', myKey)

asyncio.run(main())
Edit on GitHub

Last updated on