Calimero Client SDKs
Client SDKs that let you interact with Calimero nodes from code using Python, Rust, or frontend stacks like Next.js, React, TypeScript, and Vite. Use them to build developer tools, monitoring, and automation around Calimero.
Overview
Section titled “Overview”Calimero provides three client SDKs for different language ecosystems:
| SDK | Language | Repository | Authentication Support | Primary Use Cases |
|---|---|---|---|---|
| Rust Client | Rust | core/crates/client | Full support | Sidecar tools, CLI utilities, developer tools |
| Python Client | Python | calimero-client-py | Full support | Automation scripts, monitoring tools, developer tools |
| JavaScript Client | TypeScript/JavaScript | calimero-client-js | Full support | Web apps, browser extensions, Node.js tools |
Use Cases
Section titled “Use Cases”Sidecar Tools
Section titled “Sidecar Tools”Tools that run alongside Calimero nodes to provide additional functionality:
- Metrics collectors - Export node metrics to Prometheus, DataDog, etc.
- Log aggregators - Process and forward node logs
- Health checkers - Monitor node health and alert on issues
- Backup services - Periodically backup node state
- Monitoring dashboards - Custom dashboards for node status
Developer Tools
Section titled “Developer Tools”Utilities for development and testing:
- Test scripts - Automated testing of Calimero applications
- Deployment tools - Scripts for deploying and managing applications
- Debugging tools - Utilities for inspecting node state
- Development helpers - Scaffolding and code generation tools
Automation & CI/CD
Section titled “Automation & CI/CD”Automated workflows for DevOps:
- CI pipelines - Automated testing and deployment
- Release automation - Scripts for packaging and releasing
- Health monitoring - Automated health checks and alerts
- Data migration - Scripts for migrating data between nodes
Rust Client SDK
Section titled “Rust Client SDK”The Rust client SDK (core/crates/client) provides a trait-based abstraction for interacting with Calimero nodes. It’s designed for building command-line tools, sidecar services, and developer utilities.
Features
Section titled “Features”- Trait-based design - Flexible authentication and storage backends
- Async/await support - Full async support with
tokio - Comprehensive API - Access to all Calimero admin endpoints
- Error handling - Robust error types and handling
- Type safety - Strongly typed with Rust’s type system
Installation
Section titled “Installation”Add to your Cargo.toml:
[dependencies]calimero-client = { path = "../core/crates/client" }# Or from crates.io using "cargo add calimero-client"# calimero-client = "0.9.0"Quick Start
Section titled “Quick Start”use calimero_client::{create_connection, create_client, AuthMode, ConnectionInfo};use calimero_client::traits::{ClientAuthenticator, ClientStorage};use url::Url;
#[tokio::main]async fn main() -> eyre::Result<()> { // Create connection let api_url = Url::parse("http://localhost:2528")?; let authenticator = CliAuthenticator::new(); let storage = FileStorage::new();
let connection = ConnectionInfo::new( api_url, Some("node1".to_string()), authenticator, storage, );
// Create client let client = Client::new(connection)?;
// List contexts let contexts = client.list_contexts().await?; println!("Found {} contexts", contexts.data.len());
// List applications let apps = client.list_applications().await?; println!("Found {} applications", apps.data.len());
Ok(())}Authentication
Section titled “Authentication”use calimero_client::{AuthMode, ConnectionInfo};
let connection = ConnectionInfo::new( api_url, Some("node1".to_string()), CliAuthenticator::new(), FileStorage::new(),);API Examples
Section titled “API Examples”Context Management
Section titled “Context Management”// List all contextslet contexts = client.list_contexts().await?;
// Get specific contextlet context = client.get_context(&context_id).await?;
// Create new contextlet create_request = CreateContextRequest { application_id: app_id, protocol: "near".to_string(), params: Some(json!({"network": "testnet"}).to_string()),};let new_context = client.create_context(create_request).await?;
// Delete contextclient.delete_context(&context_id).await?;Application Management
Section titled “Application Management”// List applicationslet apps = client.list_applications().await?;
// Get applicationlet app = client.get_application(&app_id).await?;
// Install development applicationlet install_request = InstallDevApplicationRequest { path: "/path/to/app.wasm".to_string(), metadata: None,};client.install_dev_application(install_request).await?;
// Uninstall applicationclient.uninstall_application(&app_id).await?;Function Execution
Section titled “Function Execution”use calimero_client::client::Client;
// Execute function via JSON-RPClet result = client.execute_function( &context_id, "set_value", r#"{"key": "test", "value": "hello"}"#, &executor_public_key,).await?;Blob Management
Section titled “Blob Management”// Upload bloblet data = b"Hello, Calimero!".to_vec();let blob_info = client.upload_blob(data, Some(&context_id)).await?;
// List blobslet blobs = client.list_blobs().await?;
// Get blob infolet info = client.get_blob_info(&blob_id).await?;
// Delete blobclient.delete_blob(&blob_id).await?;Architecture
Section titled “Architecture”The Rust client uses a trait-based design for flexibility:
pub trait ClientAuthenticator { async fn authenticate(&self, url: &Url) -> Result<JwtToken>; // ...}
pub trait ClientStorage { async fn load_tokens(&self, node_name: &str) -> Result<Option<JwtToken>>; async fn save_tokens(&self, node_name: &str, tokens: &JwtToken) -> Result<()>; // ...}
pub struct Client<A, S>where A: ClientAuthenticator, S: ClientStorage,{ connection: ConnectionInfo<A, S>,}This allows you to implement custom authenticators and storage backends for your specific use case.
Error Handling
Section titled “Error Handling”use calimero_client::errors::ClientError;
match client.list_contexts().await { Ok(response) => println!("Success: {:?}", response), Err(ClientError::Network { message }) => { eprintln!("Network error: {}", message); } Err(ClientError::Authentication { message }) => { eprintln!("Auth error: {}", message); } Err(e) => eprintln!("Error: {:?}", e),}Related Documentation
Section titled “Related Documentation”- Repository:
calimero-network/core/crates/client - Source code:
core/crates/client/src
Python Client SDK
Section titled “Python Client SDK”The Python client SDK (calimero-client-py) provides Python bindings built with PyO3 for high-performance integration with Calimero nodes. Perfect for automation scripts, monitoring tools, and developer utilities.
Features
Section titled “Features”- High performance - Built with Rust and PyO3 for optimal performance
- Comprehensive API - Full access to Calimero Network functionality
- Type safety - Strongly typed Python bindings
- Async support - Built-in async/await support
- Easy installation - Simple
pip install
Installation
Section titled “Installation”$: pip install calimero-client-py> ...> Successfully installed calimero-client-py-0.3.0Quick Start
Section titled “Quick Start”import asynciofrom calimero_client_py import create_connection, create_client, AuthMode
async def main(): # Create connection connection = create_connection( api_url="http://localhost:2528", node_name="node1", )
client = create_client(connection)
contexts = client.list_contexts() print(f"✓ Found contexts: {contexts}")
applications = client.list_applications() print(f"✓ Found applications: {applications}")
if __name__ == "__main__": asyncio.run(main())Authentication
Section titled “Authentication”For local development with merod the auth is disabled so you can write any value for JWT access and refresh tokens.
$: python main.py> Starting authentication...> Please authenticate at: http://localhost:2528/> Enter access token: <ANY_VALUE>> Enter refresh token (optional): <ANY_VALUE>>> ✓ Found contexts: {'data': {'contexts': [{'applicationId': ....> ...> ✓ Found applications: {'data': {'apps': [{'blob': {'bytecode': 'Ca2zM5hue4Te2EYQnKmigkN7WcQHzBCuLFVSJ7zQte58', ' ...> ...API Examples
Section titled “API Examples”Context Management
Section titled “Context Management”# List all contextscontexts = client.list_contexts()
# Get specific contextcontext = client.get_context(context_id)
# Create new contextcontext = client.create_context( application_id="<APP_ID>", protocol="near", params='{"network": "testnet"}')
# Delete contextclient.delete_context(context_id)Application Management
Section titled “Application Management”# List applicationsapps = client.list_applications()
# Get applicationapp = client.get_application(app_id)
# Install development applicationresponse = client.install_dev_application( path="absolute/path/to/app.wasm", metadata=None)
# Uninstall applicationclient.uninstall_application(app_id)Function Execution
Section titled “Function Execution”# Execute function via JSON-RPCresult = client.execute_function( context_id=context_id, method="set_value", args='{"key": "test", "value": "hello"}', executor_public_key=executor_public_key)Blob Management
Section titled “Blob Management”# Upload blobwith open("file.dat", "rb") as f: data = f.read()blob_info = client.upload_blob(data, context_id=context_id)
# List blobsblobs = client.list_blobs()
# Get blob infoinfo = client.get_blob_info(blob_id)
# Delete blobclient.delete_blob(blob_id)Error Handling
Section titled “Error Handling”from calimero_client_py import ClientError
try: contexts = client.list_contexts()except ClientError as e: if e.error_type == "Network": print(f"Network error: {e.message}") elif e.error_type == "Authentication": print(f"Auth error: {e.message}") else: print(f"Error: {e.message}")Related Documentation
Section titled “Related Documentation”- Repository:
calimero-network/calimero-client-py - PyPI Package:
calimero-client-py - README:
calimero-client-py/README.md
JavaScript Client SDK
Section titled “JavaScript Client SDK”The JavaScript client SDK (calimero-client-js) provides TypeScript/JavaScript bindings with full authentication support. Ideal for web applications, browser extensions, and Node.js tools.
Features
Section titled “Features”- Full authentication - JWT token management, wallet-based auth, React components
- Real-time updates - WebSocket and SSE subscriptions
- TypeScript support - Full type definitions
- React components - Pre-built UI components for authentication
- Browser & Node.js - Works in both environments
Installation
Section titled “Installation”# npmnpm install @calimero-network/calimero-client
# yarnyarn add @calimero-network/calimero-client
# pnpmpnpm add @calimero-network/calimero-clientQuick Start
Section titled “Quick Start”Basic Setup
Section titled “Basic Setup”The rpcClient allows you to make RPC calls to your node:
// KV Store exampleimport { setAppEndpointKey, setApplicationId, rpcClient,} from "@calimero-network/calimero-client";
// Configure node URL and application IDsetAppEndpointKey('http://localhost:2528');setApplicationId('APP_ID');
const contextId = 'CONTEXT_ID';const executorPublicKey = 'PUBLIC_KEY';
// Args = { key: string, value: string }// Output = { result: string }const setResponse = await rpcClient.execute<Args, Output>( { contextId, method: 'set', argsJson: { key: 'test', value: 'test' }, executorPublicKey, }, { headers: { 'Content-Type': 'application/json' }, timeout: 10000 });
const getResponse = await rpcClient.execute<Args, Output>( { contextId, method: 'get', argsJson: { key: 'test' }, executorPublicKey, }, { headers: { 'Content-Type': 'application/json' }, timeout: 10000 });Authentication Flow
Section titled “Authentication Flow”import { AppMode, CalimeroProvider CalimeroConnectButton, useCalimero,} from "@calimero-network/calimero-client";
const APPLICATION_ID = "<APPLICATION_ID>";const APPLICATION_PAHT = "<APPLICATION_PATH>";
// Wrap application logic in CalimeroProvider// CalimeroConnectButton -> handles connection to node; JWT generation and callback// Logout -> handles state cleanup and kills the connection to the nodefunction App() { const { logout } = useCalimero(); return ( <CalimeroProvider clientApplicationId={APPLICATION_ID} mode={AppMode.MultiContext} applicationPath={APPLICATION_PATH} > <YourApp /> <CalimeroConnectButton /> <button onClick={() => logout()}>Logout</button> </CalimeroProvider> );}Authentication
Section titled “Authentication”The JavaScript client has full authentication support including:
- JWT token management - Automatic token storage and refresh
- Wallet-based authentication - Support for NEAR wallet
- React components - Pre-built UI components (
CalimeroConnectButton,SetupModal) - Manual token handling - Direct token management APIs
Complete Authentication Flow
Section titled “Complete Authentication Flow”import { Routes, Route, useNavigate } from "react-router-dom";import { AppMode, CalimeroProvider CalimeroConnectButton, useCalimero,} from "@calimero-network/calimero-client";
function AuthPage() { return <CalimeroConnectButton />;}
function HomePage() { const { logout } = useCalimero(); return ( <Wrapper> <App> <button onClick={() => logout()}>Logout</button> </Wrapper> )}
function App() { const { isAuthenticated } = useCalimero(); const navigate = useNavigate();
useEffect(() => { if (isAuthenticated) { navigate("/home"); } else { navigate("/auth"); } }, [isAuthenticated]);
return ( <CalimeroProvider clientApplicationId={APPLICATION_ID} mode={AppMode.MultiContext} applicationPath={APPLICATION_PATH} > <Routes> <Route path="/auth" element={<AuthPage />} /> <Route path="/home" element={<HomePage />} /> </Routes> </CalimeroProvider> );}Manual Token Usage
Section titled “Manual Token Usage”import { setAccessToken, getJWTObject, rpcClient} from '@calimero-network/calimero-client';
// Set your tokensetAccessToken('your-jwt-token-here');
// Get contextId and executorPublicKey from the tokenconst jwt = getJWTObject();const contextId = jwt?.context_id;const executorPublicKey = jwt?.executor_public_key;
// Use the clientconst response = await rpcClient.execute<Args, Output>( { contextId, method: 'get', argsJson: { key: 'test' }, executorPublicKey, }, { headers: { 'Content-Type': 'application/json' }, timeout: 10000 });API Examples
Section titled “API Examples”The WsSubscriptionsClient enables real-time updates through WebSocket connections:
WebSocket Subscriptions
Section titled “WebSocket Subscriptions”import { useCalimero, getContextId } from "@calimero-network/calimero-client";import { WsSubscriptionsClient } from '@calimero-network/calimero-client';
const { app } = useCalimero();
const eventCallback = useCallback(async (event: WebSocketEvent) => { eventListenersRef.current.forEach((event: WebSocketEvent) => { // handle event console.log(event); }); }, []);
const subscriptionsClient = new WsSubscriptionsClient( process.env.NEXT_PUBLIC_API_URL, '/ws');// Subscripe to context eventsapp.subscribeToEvents([getContextId()], eventCallback);// Unsubscribe from context eventsapp.unsubscribeFromEvents([getContextId()]);SSE Subscriptions
Section titled “SSE Subscriptions”The SseSubscriptionsClient provides an HTTP-based alternative for real-time updates using Server-Sent Events:
import { SseSubscriptionsClient } from '@calimero-network/calimero-client';
const sseClient = new SseSubscriptionsClient( // e.g. http://localhost:2528 "<NODE-URL>", '/sse');
// Connect to SSE endpointawait sseClient.connect();// Subscribe to specific contextsawait sseClient.subscribe(["<APPLICATION_ID>"]);
// Handle incoming eventssseClient.addCallback((event) => { console.log('Received SSE event:', event);});
// Unsubscribe from contextsawait sseClient.unsubscribe(["<APPLICATION_ID>"]);
// Clean upsseClient.disconnect();Admin API
Section titled “Admin API”The Admin API allows you to call node functionalities. These can be: fetch context, fetch applications, fetch identities, create context, install application, others…
// apiClient automatically checks login authentication status so it needs to be paired with// CalimeroProvider and CalimeroConnectButton from previous stepsimport { apiClient,} from "@calimero-network/calimero-client";// fetch all contexts on the nodeconst contexts = await apiClient.node().getContexts();// fetch all installed applicationsconst applications = await apiClient.node().getInstalledApplications();// install applicaion on the node from a hosted URLconst installationResponse = await apiClient.node().installApplication("<APPLICATION_URL_PATH>");// fetch all root keys on the nodeconst rootKeys = await apiClient.admin().getRootKeys();// fetch all client keys on the nodeconst rootKeys = await apiClient.admin().getClientKeys();// revoke client keyconst rootKeys = await apiClient.admin().revokeClientKey("<ROOT_KEY_ID>","<CLIENT_ID>");...Error Handling
Section titled “Error Handling”try { const response = await rpcClient().execute<Args, Output>(...); if (response.error) { // Handle RPC error console.error('RPC Error:', response.error.message); } else { // Process successful response console.log('Result:', response.result); }} catch (error) { // Handle network or other errors console.error('Request failed:', error);}Best Practices
Section titled “Best Practices”Token Management
- Use
CalimeroProvider and CalimeroConnectButtonfor login and automatic token refresh - Store sensitive information in environment variables
- Never expose tokens in client-side code
Connection Management
- Always clean up WebSocket connections when done
- Use unique connection IDs for multiple connections
- Implement reconnection logic for production
Error Handling
- Always check for errors in RPC responses
- Implement proper error boundaries in React
- Log errors appropriately for debugging
Related Documentation
Section titled “Related Documentation”- Repository:
calimero-network/calimero-client-js - NPM Package:
@calimero-network/calimero-client - README:
calimero-client-js/README.md
Comparison
Section titled “Comparison”| Feature | Rust Client | Python Client | JavaScript Client |
|---|---|---|---|
| Language | Rust | Python | TypeScript/JavaScript |
| Performance | High (native) | High (Rust bindings) | Good (JavaScript) |
| Authentication | ⚠️ Planned | ⚠️ Planned | ✅ Full support |
| Async Support | ✅ Tokio | ✅ asyncio | ✅ Native |
| Type Safety | ✅ Rust types | ✅ Python types | ✅ TypeScript |
| React Components | ❌ | ❌ | ✅ |
| WebSocket | ✅ | ✅ | ✅ |
| SSE | ✅ | ✅ | ✅ |
| Best For | CLI tools, sidecars | Scripts, automation | Web apps, browsers |
Choosing the Right SDK
Section titled “Choosing the Right SDK”Choose Rust Client if:
- Building command-line tools or sidecar services
- Need maximum performance
- Already using Rust in your stack
- Building developer utilities
Choose Python Client if:
- Building automation scripts or monitoring tools
- Working with Python-based tooling
- Need quick prototyping
- Building CI/CD pipelines
Choose JavaScript Client if:
- Building web applications or browser extensions
- Need authentication flows
- Want React components
- Building user-facing applications
Related Topics
Section titled “Related Topics”- meroctl CLI - Command-line interface for Calimero
- Introduction - Understanding Calimero’s core concepts
- Contexts - Working with contexts
- Identity - Authentication and identity management