### Initialize Smoldot Client and Add a Chain (JavaScript) Source: https://github.com/smol-dot/smoldot/blob/main/wasm-node/javascript/README.md Demonstrates how to start a Smoldot client, load a chain specification from a file, add the chain to the client, send a JSON-RPC request, and retrieve the response. This example requires the 'fs' module for file reading. ```javascript import * as smoldot from 'smoldot'; import fs from 'fs'; // Load a string chain specification. const chainSpec = fs.readFileSync('./westend.json', 'utf8'); // A single client can be used to initialize multiple chains. const client = smoldot.start(); const chain = await client.addChain({ chainSpec }); chain.sendJsonRpc('{"jsonrpc":"2.0","id":1,"method":"system_name","params":[]}'); // Wait for a JSON-RPC response to come back. This is typically done in a loop in the background. const jsonRpcResponse = await chain.nextJsonRpcResponse(); console.log(jsonRpcResponse) // Later: // chain.remove(); ``` -------------------------------- ### Run Full Node CLI Source: https://context7.com/smol-dot/smoldot/llms.txt Instructions on how to install and run the smoldot full node binary. This includes commands for installation via cargo and running the node with a chain specification, as well as options for customizing the JSON-RPC server address and client limit. ```bash # Install the full node cargo install --locked smoldot-full-node # Run with a chain specification smoldot-full-node run --path-to-chain-spec ./polkadot.json # Run with custom JSON-RPC server address smoldot-full-node run \ --path-to-chain-spec ./polkadot.json \ --json-rpc-address 0.0.0.0:9944 \ --json-rpc-max-clients 128 ``` -------------------------------- ### Full Node CLI - Running the Full Node Source: https://context7.com/smol-dot/smoldot/llms.txt Instructions on how to install and run the smoldot full node binary, including options for specifying the chain specification and JSON-RPC server address. ```APIDOC ## Full Node CLI - Running the Full Node ### Description This section provides instructions for installing and running the smoldot full node binary. It covers basic installation and how to launch the node with a specified chain specification and custom JSON-RPC server configurations. ### Method Command-line execution ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```bash # Install the full node cargo install --locked smoldot-full-node # Run with a chain specification smoldot-full-node run --path-to-chain-spec ./polkadot.json # Run with custom JSON-RPC server address smoldot-full-node run \ --path-to-chain-spec ./polkadot.json \ --json-rpc-address 0.0.0.0:9944 \ --json-rpc-max-clients 128 ``` ### Response #### Success Response (200) N/A (CLI execution) #### Response Example N/A ``` -------------------------------- ### Smoldot Full Node Run Commands Source: https://context7.com/smol-dot/smoldot/llms.txt Examples of running the smoldot-full-node with different configurations for networking, logging, database, and temporary mode. ```APIDOC ## Run with custom networking smoldot-full-node run \ --path-to-chain-spec ./polkadot.json \ --listen-addr /ip4/0.0.0.0/tcp/30333 \ --additional-bootnode /ip4/127.0.0.1/tcp/30334/p2p/12D3KooWExample... ### Description Runs the node with a specified chain specification, listen address, and additional bootnodes for network connection. ### Method `run` (command-line executable) ### Parameters #### Path Parameters None #### Query Parameters None #### Command-line Arguments - `--path-to-chain-spec` (string) - Required - Path to the chain specification file. - `--listen-addr` (string) - Required - Network address to listen on. - `--additional-bootnode` (string) - Optional - Additional bootnode to connect to. --- ## Run with custom logging and database settings smoldot-full-node run \ --path-to-chain-spec ./polkadot.json \ --log-level debug \ --output logs \ --database-cache-size 512M ### Description Configures the node with custom logging level, output directory for logs, and database cache size. ### Method `run` (command-line executable) ### Parameters #### Path Parameters None #### Query Parameters None #### Command-line Arguments - `--path-to-chain-spec` (string) - Required - Path to the chain specification file. - `--log-level` (string) - Optional - Sets the logging verbosity (e.g., `debug`, `info`, `warn`). - `--output` (string) - Optional - Directory to store log files. - `--database-cache-size` (string) - Optional - Size of the database cache (e.g., `512M`). --- ## Run in temporary mode (no disk storage) smoldot-full-node run \ --path-to-chain-spec ./polkadot.json \ --tmp ### Description Runs the node in temporary mode, meaning no data will be persisted to disk. ### Method `run` (command-line executable) ### Parameters #### Path Parameters None #### Query Parameters None #### Command-line Arguments - `--path-to-chain-spec` (string) - Required - Path to the chain specification file. - `--tmp` (boolean) - Optional - Enables temporary mode (no disk storage). ``` -------------------------------- ### Start Smoldot with Bytecode in Browser Worker (TypeScript) Source: https://github.com/smol-dot/smoldot/blob/main/wasm-node/javascript/README.md This snippet demonstrates how to initialize smoldot in a browser environment using a worker. It involves creating a worker, establishing message channels for communication, and starting smoldot with pre-compiled bytecode. The `bytecode` is passed as a Promise, and `portToWorker` is used for inter-thread communication. ```typescript import * as smoldot from 'smoldot/no-auto-bytecode'; const worker = new Worker(new URL('./worker.js', import.meta.url)); const bytecode = new Promise((resolve) => { worker.onmessage = (event) => resolve(event.data); }); const { port1, port2 } = new MessageChannel(); worker.postMessage(port1, [port1]); const client = smoldot.startWithBytecode({ bytecode, portToWorker: port2, }); ``` -------------------------------- ### Initialize and Connect: Client::new() and add_chain() (Rust) Source: https://context7.com/smol-dot/smoldot/llms.txt Illustrates initializing the smoldot light client in Rust using `Client::new()` and adding chains with `add_chain()`. This setup is crucial for establishing connections to specified blockchains like Polkadot and its associated parachains. ```rust use smoldot_light::{Client, AddChainConfig, AddChainConfigJsonRpc, platform::DefaultPlatform}; use core::num::NonZero; fn main() { // Initialize logging env_logger::Builder::from_env( env_logger::Env::default().default_filter_or("info") ).init(); // Create the client with default platform bindings let mut client = Client::new(DefaultPlatform::new( env!("CARGO_PKG_NAME").into(), env!("CARGO_PKG_VERSION").into(), )); // Add Polkadot relay chain let polkadot_spec = include_str!("../chain-specs/polkadot.json"); let smoldot_light::AddChainSuccess { chain_id: polkadot_id, json_rpc_responses: polkadot_rpc, } = client.add_chain(AddChainConfig { specification: polkadot_spec, database_content: "", user_data: (), potential_relay_chains: std::iter::empty(), json_rpc: AddChainConfigJsonRpc::Enabled { max_pending_requests: NonZero::new(128).unwrap(), max_subscriptions: 1024, }, }).expect("Failed to add Polkadot chain"); let mut polkadot_rpc = polkadot_rpc.unwrap(); // Add Asset Hub parachain let asset_hub_spec = include_str!("../chain-specs/polkadot_asset_hub.json"); let smoldot_light::AddChainSuccess { chain_id: asset_hub_id, json_rpc_responses: asset_hub_rpc, } = client.add_chain(AddChainConfig { specification: asset_hub_spec, database_content: "", user_data: (), potential_relay_chains: [polkadot_id].into_iter(), json_rpc: AddChainConfigJsonRpc::Enabled { max_pending_requests: NonZero::new(128).unwrap(), max_subscriptions: 1024, }, }).expect("Failed to add Asset Hub chain"); println!("Connected to Polkadot and Asset Hub!"); } ``` -------------------------------- ### Run Smoldot as JSON-RPC WebSocket Server in Deno Source: https://context7.com/smol-dot/smoldot/llms.txt This TypeScript code demonstrates how to initialize a smoldot client, load a chain specification, and start a JSON-RPC WebSocket server on port 9944 using Deno. It handles incoming WebSocket connections, upgrades them, and manages JSON-RPC requests and responses between the client and the smoldot chain. Errors like 'Queue full' are handled gracefully. ```typescript import * as smoldot from 'https://deno.land/x/smoldot2/index-deno.js'; // Load chain specification const chainSpec = await Deno.readTextFile('./polkadot.json'); // Initialize smoldot client const client = smoldot.start({ maxLogLevel: 3, cpuRateLimit: 0.5, logCallback: (level, target, message) => { const ts = new Date().toISOString(); console.log(`[${ts}] [${target}] ${message}`); } }); // Pre-load chain for faster client connections await client.addChain({ chainSpec, disableJsonRpc: true }); // Start WebSocket server const listener = Deno.listen({ port: 9944 }); console.log('JSON-RPC server listening on ws://127.0.0.1:9944'); for await (const conn of listener) { handleConnection(conn); } async function handleConnection(conn: Deno.Conn) { const httpConn = Deno.serveHttp(conn); for await (const event of httpConn) { if (event.request.headers.get('upgrade') === 'websocket') { const { socket, response } = Deno.upgradeWebSocket(event.request); // Create dedicated chain instance for this client const chain = await client.addChain({ chainSpec }); // Forward JSON-RPC responses to WebSocket (async () => { for await (const msg of chain.jsonRpcResponses) { if (socket.readyState === WebSocket.OPEN) { socket.send(msg); } } })(); // Handle incoming JSON-RPC requests socket.onmessage = (e) => { if (typeof e.data === 'string') { try { chain.sendJsonRpc(e.data); } catch (err) { if (err instanceof smoldot.QueueFullError) { socket.send(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32000, message: 'Queue full' } })); } } } }; socket.onclose = () => { chain.remove(); console.log('Client disconnected'); }; event.respondWith(response); } } } ``` -------------------------------- ### Interact with New chainHead JSON-RPC API (JavaScript) Source: https://context7.com/smol-dot/smoldot/llms.txt This JavaScript code demonstrates how to use the newer, more efficient chainHead JSON-RPC API for light clients. It includes examples for following the chain head, querying storage, making runtime calls, retrieving block bodies, managing pinned blocks, and broadcasting transactions. Requires a 'chain' object with a 'sendJsonRpc' method. ```javascript // Follow chain head with runtime updates chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'chainHead_v1_follow', params: [true] // withRuntime: true })); // After receiving subscription ID from follow response: const subscriptionId = 'abc123...'; // Query storage at a specific block chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'chainHead_v1_storage', params: [ subscriptionId, '0xblockhash...', // blockHash [{ key: '0xstoragekey...', type: 'value' }], // storageKeys null // childTrie ] })); // Make a runtime call chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 3, method: 'chainHead_v1_call', params: [ subscriptionId, '0xblockhash...', // blockHash 'Metadata_metadata', // method '0x' // call parameters ] })); // Get block body chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 4, method: 'chainHead_v1_body', params: [subscriptionId, '0xblockhash...'] })); // Unpin blocks to free memory chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 5, method: 'chainHead_v1_unpin', params: [subscriptionId, ['0xhash1...', '0xhash2...']] })); // Stop following chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 6, method: 'chainHead_v1_unfollow', params: [subscriptionId] })); // Transaction broadcast API chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 7, method: 'transaction_v1_broadcast', params: ['0xsignedextrinsic...'] })); ``` -------------------------------- ### Rust API - Client Initialization and Chain Addition Source: https://context7.com/smol-dot/smoldot/llms.txt Explains how to initialize the Smoldot light client and add chains using the `smoldot-light` crate in Rust. Includes configuration for JSON-RPC. ```APIDOC ## Rust API - Client Initialization and Chain Addition ### Description This section covers the initialization of the Smoldot light client and the process of adding chains using the `smoldot-light` Rust crate. It details the configuration options for chain specifications and JSON-RPC. ### Method `Client::new()`, `client.add_chain()` ### Endpoint N/A (Rust library functions) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A (Configuration is passed via struct parameters) ### Request Example ```rust use smoldot_light::{Client, AddChainConfig, AddChainConfigJsonRpc, platform::DefaultPlatform}; use core::num::NonZero; fn main() { // Initialize logging env_logger::Builder::from_env( env_logger::Env::default().default_filter_or("info") ).init(); // Create the client with default platform bindings let mut client = Client::new(DefaultPlatform::new( env!("CARGO_PKG_NAME").into(), env!("CARGO_PKG_VERSION").into(), )); // Add Polkadot relay chain let polkadot_spec = include_str!("../chain-specs/polkadot.json"); let smoldot_light::AddChainSuccess { chain_id: polkadot_id, json_rpc_responses: polkadot_rpc, } = client.add_chain(AddChainConfig { specification: polkadot_spec, database_content: "", user_data: (), potential_relay_chains: std::iter::empty(), json_rpc: AddChainConfigJsonRpc::Enabled { max_pending_requests: NonZero::new(128).unwrap(), max_subscriptions: 1024, }, }).expect("Failed to add Polkadot chain"); let mut polkadot_rpc = polkadot_rpc.unwrap(); // Add Asset Hub parachain let asset_hub_spec = include_str!("../chain-specs/polkadot_asset_hub.json"); let smoldot_light::AddChainSuccess { chain_id: asset_hub_id, json_rpc_responses: asset_hub_rpc, } = client.add_chain(AddChainConfig { specification: asset_hub_spec, database_content: "", user_data: (), potential_relay_chains: [polkadot_id].into_iter(), json_rpc: AddChainConfigJsonRpc::Enabled { max_pending_requests: NonZero::new(128).unwrap(), max_subscriptions: 1024, }, }).expect("Failed to add Asset Hub chain"); println!("Connected to Polkadot and Asset Hub!"); } ``` ### Response #### Success Response (200) N/A (Function calls return results directly or via `Result` types) #### Response Example N/A ``` -------------------------------- ### Run Smoldot Node with Custom Logging and Database Settings Source: https://context7.com/smol-dot/smoldot/llms.txt This command shows how to run the smoldot full node with custom logging levels, output directory for logs, and a specified database cache size. This is helpful for performance tuning and log management. ```bash smoldot-full-node run \ --path-to-chain-spec ./polkadot.json \ --log-level debug \ --output logs \ --database-cache-size 512M ``` -------------------------------- ### Run Smoldot Node with Custom Networking Source: https://context7.com/smol-dot/smoldot/llms.txt This command demonstrates how to run the smoldot full node with a custom chain specification, listen address, and an additional bootnode. It's useful for setting up specific network configurations. ```bash smoldot-full-node run \ --path-to-chain-spec ./polkadot.json \ --listen-addr /ip4/0.0.0.0/tcp/30333 \ --additional-bootnode /ip4/127.0.0.1/tcp/30334/p2p/12D3KooWExample... ``` -------------------------------- ### JavaScript API - Chain Management and Client Termination Source: https://context7.com/smol-dot/smoldot/llms.txt Demonstrates how to add a chain, interact with it using JSON-RPC, save chain database for faster reconnection, disconnect from a specific chain, and terminate the entire client. ```APIDOC ## JavaScript API - Chain Management and Client Termination ### Description This section details the process of managing chains and terminating the Smoldot client in JavaScript. It covers adding a chain, sending JSON-RPC requests, saving chain data, removing a specific chain, and finally terminating the client to release resources. ### Method `smoldot.start()`, `client.addChain()`, `chain.sendJsonRpc()`, `chain.nextJsonRpcResponse()`, `chain.remove()`, `client.terminate()` ### Endpoint N/A (Client-side JavaScript API) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **chainSpec** (object) - Required - The chain specification for adding a new chain. ### Request Example ```javascript import * as smoldot from 'smoldot'; const client = smoldot.start(); const chain = await client.addChain({ chainSpec }); // ... use the chain ... // Save database for faster reconnection next time chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 99, method: 'chainHead_unstable_finalizedDatabase', params: [10000000] // Max database size in bytes })); const dbResponse = await chain.nextJsonRpcResponse(); localStorage.setItem('chain-db', JSON.parse(dbResponse).result); // Disconnect from this specific chain chain.remove(); // Terminate the entire client (disconnects all chains) await client.terminate(); ``` ### Response #### Success Response (200) N/A (API calls are asynchronous and results are handled via returned promises or subsequent events) #### Response Example N/A ``` -------------------------------- ### Initialize Smoldot Client (TypeScript) Source: https://context7.com/smol-dot/smoldot/llms.txt Initializes a new Smoldot client instance to manage blockchain network connections. Supports basic and advanced configurations including log levels, CPU rate limits, network restrictions, and custom log handlers. ```typescript import * as smoldot from 'smoldot'; // Basic initialization with default options const client = smoldot.start(); // Advanced initialization with custom options const client = smoldot.start({ // Maximum log level: 1=Error, 2=Warn, 3=Info, 4=Debug, 5=Trace maxLogLevel: 3, // CPU rate limit (0.0 to 1.0) - limits average CPU usage cpuRateLimit: 0.5, // Network restrictions forbidTcp: false, // Disable TCP connections forbidWs: false, // Disable WebSocket connections forbidNonLocalWs: false, // Disable non-localhost WebSocket forbidWss: false, // Disable secure WebSocket forbidWebRtc: false, // Disable WebRTC connections // Custom log handler logCallback: (level, target, message) => { const timestamp = new Date().toISOString(); console.log(`[${timestamp}] [${target}] ${message}`); } }); ``` -------------------------------- ### Smoldot Client Initialization Source: https://context7.com/smol-dot/smoldot/llms.txt Initializes a new Smoldot client instance. This client manages connections to multiple blockchain networks, handling networking, synchronization, and JSON-RPC processing internally. It can be configured with various options to control logging, resource usage, and network restrictions. ```APIDOC ## JavaScript/TypeScript API ### start() - Initialize the Smoldot Client **Description**: Creates a new smoldot client instance that can manage connections to multiple blockchain networks. The client handles all networking, synchronization, and JSON-RPC processing internally. **Method**: `smoldot.start(options?: StartOptions) **Parameters**: #### Options Object (`StartOptions`) - **maxLogLevel** (number) - Optional - Maximum log level: 1=Error, 2=Warn, 3=Info, 4=Debug, 5=Trace. - **cpuRateLimit** (number) - Optional - CPU rate limit (0.0 to 1.0) - limits average CPU usage. - **forbidTcp** (boolean) - Optional - Disable TCP connections. Defaults to `false`. - **forbidWs** (boolean) - Optional - Disable WebSocket connections. Defaults to `false`. - **forbidNonLocalWs** (boolean) - Optional - Disable non-localhost WebSocket. Defaults to `false`. - **forbidWss** (boolean) - Optional - Disable secure WebSocket. Defaults to `false`. - **forbidWebRtc** (boolean) - Optional - Disable WebRTC connections. Defaults to `false`. - **logCallback** (function) - Optional - Custom log handler function with signature `(level, target, message) => void`. ### Request Example ```typescript import * as smoldot from 'smoldot'; // Basic initialization with default options const client = smoldot.start(); // Advanced initialization with custom options const client = smoldot.start({ maxLogLevel: 3, cpuRateLimit: 0.5, forbidTcp: false, forbidWs: false, forbidNonLocalWs: false, forbidWss: false, forbidWebRtc: false, logCallback: (level, target, message) => { const timestamp = new Date().toISOString(); console.log(`[${timestamp}] [${target}] ${message}`); } }); ``` ### Response **Success Response**: - **client** (`SmoldotClient`) - The initialized Smoldot client instance. ``` -------------------------------- ### Interact with Legacy Substrate JSON-RPC API (JavaScript) Source: https://context7.com/smol-dot/smoldot/llms.txt This JavaScript code snippet demonstrates how to construct and send JSON-RPC requests to interact with the legacy Substrate API. It covers various methods for chain, state, system, transaction, and subscription queries. Ensure you have a 'chain' object available with a 'sendJsonRpc' method. ```javascript // Chain methods const methods = [ // Block queries { method: 'chain_getBlockHash', params: [0] }, // Get block hash by number { method: 'chain_getHeader', params: [] }, // Get latest header { method: 'chain_getBlock', params: ['0x...'] }, // Get full block { method: 'chain_getFinalizedHead', params: [] }, // Get finalized block hash // State queries { method: 'state_getMetadata', params: [] }, // Get runtime metadata { method: 'state_getRuntimeVersion', params: [] }, // Get runtime version { method: 'state_getStorage', params: ['0x...'] }, // Get storage value { method: 'state_getKeysPaged', params: ['0x', 10] }, // Paginated key query { method: 'state_call', params: ['Api_method', '0x'] }, // Runtime API call // System queries { method: 'system_chain', params: [] }, // Chain name { method: 'system_chainType', params: [] }, // Chain type { method: 'system_name', params: [] }, // Node name { method: 'system_version', params: [] }, // Node version { method: 'system_health', params: [] }, // Node health status { method: 'system_properties', params: [] }, // Chain properties { method: 'system_peers', params: [] }, // Connected peers { method: 'system_nodeRoles', params: [] }, // Node roles // Transaction methods { method: 'author_submitExtrinsic', params: ['0x...'] }, // Submit transaction { method: 'author_pendingExtrinsics', params: [] }, // Pending transactions // Subscription methods { method: 'chain_subscribeNewHeads', params: [] }, // New block headers { method: 'chain_subscribeFinalizedHeads', params: [] }, // Finalized headers { method: 'chain_subscribeAllHeads', params: [] }, // All block headers { method: 'state_subscribeRuntimeVersion', params: [] }, // Runtime changes { method: 'state_subscribeStorage', params: [['0x...']] }, // Storage changes { method: 'author_submitAndWatchExtrinsic', params: ['0x...'] }, // Watch transaction ]; // Send requests for (const req of methods) { chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: Math.random(), method: req.method, params: req.params })); } ``` -------------------------------- ### Legacy JSON-RPC API Source: https://context7.com/smol-dot/smoldot/llms.txt Provides access to standard Substrate JSON-RPC methods for compatibility with existing tools. Includes methods for chain, state, system, and transaction management, as well as subscriptions. ```APIDOC ## Legacy JSON-RPC API Smoldot supports the standard Substrate JSON-RPC methods for compatibility with existing tools. ### Supported Methods #### Chain Methods - `chain_getBlockHash` (params: [blockNumber]) - Get block hash by number. - `chain_getHeader` (params: []) - Get latest header. - `chain_getBlock` (params: [blockHash]) - Get full block. - `chain_getFinalizedHead` (params: []) - Get finalized block hash. #### State Methods - `state_getMetadata` (params: []) - Get runtime metadata. - `state_getRuntimeVersion` (params: []) - Get runtime version. - `state_getStorage` (params: [storageKey]) - Get storage value. - `state_getKeysPaged` (params: [pallet, count]) - Paginated key query. - `state_call` (params: [runtimeApiMethod, encodedParams]) - Runtime API call. #### System Methods - `system_chain` (params: []) - Chain name. - `system_chainType` (params: []) - Chain type. - `system_name` (params: []) - Node name. - `system_version` (params: []) - Node version. - `system_health` (params: []) - Node health status. - `system_properties` (params: []) - Chain properties. - `system_peers` (params: []) - Connected peers. - `system_nodeRoles` (params: []) - Node roles. #### Transaction Methods - `author_submitExtrinsic` (params: [encodedExtrinsic]) - Submit transaction. - `author_pendingExtrinsics` (params: []) - Get pending transactions. #### Subscription Methods - `chain_subscribeNewHeads` (params: []) - Subscribe to new block headers. - `chain_subscribeFinalizedHeads` (params: []) - Subscribe to finalized block headers. - `chain_subscribeAllHeads` (params: []) - Subscribe to all block headers. - `state_subscribeRuntimeVersion` (params: []) - Subscribe to runtime version changes. - `state_subscribeStorage` (params: [storageKeys]) - Subscribe to storage changes. - `author_submitAndWatchExtrinsic` (params: [encodedExtrinsic]) - Submit and watch an extrinsic. ### Request Example ```javascript // Example of sending a JSON-RPC request const request = { jsonrpc: '2.0', id: Math.random(), method: 'chain_getBlockHash', params: [0] }; chain.sendJsonRpc(JSON.stringify(request)); ``` ### Response Example (Success) ```json { "jsonrpc": "2.0", "result": "0x...", "id": 1 } ``` ### Response Example (Error) ```json { "jsonrpc": "2.0", "error": { "code": -32601, "message": "Method not found" }, "id": null } ``` ``` -------------------------------- ### Run Smoldot Node in Temporary Mode Source: https://context7.com/smol-dot/smoldot/llms.txt This command illustrates running the smoldot full node in temporary mode, which means it will not use disk storage. This is ideal for testing or scenarios where persistence is not required. ```bash smoldot-full-node run \ --path-to-chain-spec ./polkadot.json \ --tmp ``` -------------------------------- ### Rust API - Sending JSON-RPC Requests Source: https://context7.com/smol-dot/smoldot/llms.txt Details how to send JSON-RPC requests to a connected chain and process the responses using the `smoldot-light` crate in Rust. ```APIDOC ## Rust API - Sending JSON-RPC Requests ### Description This section explains how to send JSON-RPC requests to a blockchain client and handle the incoming responses using the `smoldot-light` Rust crate. It covers querying chain information, subscribing to events, and processing results and notifications. ### Method `client.json_rpc_request()`, `responses.next()` ### Endpoint N/A (Rust library functions) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A (JSON-RPC payload is a string argument) ### Request Example ```rust use smoldot_light::{Client, ChainId, JsonRpcResponses}; use futures_lite::FutureExt; async fn query_chain( client: &mut Client, chain_id: ChainId, mut responses: JsonRpcResponses, ) { // Query system information client.json_rpc_request( r#"{"jsonrpc":"2.0","id":1,"method":"system_chain","params":[]}"#, chain_id, ).unwrap(); // Get chain name if let Some(response) = responses.next().await { println!("Chain response: {}", response); } // Subscribe to finalized heads client.json_rpc_request( r#"{"jsonrpc":"2.0","id":2,"method":"chain_subscribeFinalizedHeads","params":[]}"#, chain_id, ).unwrap(); // Query storage client.json_rpc_request( r#"{"jsonrpc":"2.0","id":3,"method":"state_getMetadata","params":[]}"#, chain_id, ).unwrap(); // Process all responses loop { if let Some(response) = responses.next().await { let json: serde_json::Value = serde_json::from_str(&response).unwrap(); if let Some(result) = json.get("result") { println!("Result: {:?}", result); } if let Some(params) = json.get("params") { // This is a subscription notification println!("Notification: {:?}", params); } } else { break; } } } ``` ### Response #### Success Response (200) N/A (Responses are streamed asynchronously) #### Response Example ```json { "jsonrpc": "2.0", "result": "Polkadot", "id": 1 } ``` ```json { "jsonrpc": "2.0", "result": { "metadata": { "version": 14, "//": "..." } }, "id": 3 } ``` ```json { "jsonrpc": "2.0", "method": "chain_newFinalizedHead", "params": [ "0x..." ] } ``` ``` -------------------------------- ### Cleanup: Disconnect Chains and Terminate Client (TypeScript) Source: https://context7.com/smol-dot/smoldot/llms.txt Demonstrates how to properly disconnect from a specific chain using `chain.remove()` and terminate the entire smoldot client with `client.terminate()` to free up resources. It also shows how to save chain database for faster reconnections. ```typescript import * as smoldot from 'smoldot'; const client = smoldot.start(); const chain = await client.addChain({ chainSpec }); // ... use the chain ... // Save database for faster reconnection next time chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 99, method: 'chainHead_unstable_finalizedDatabase', params: [10000000] // Max database size in bytes })); const dbResponse = await chain.nextJsonRpcResponse(); localStorage.setItem('chain-db', JSON.parse(dbResponse).result); // Disconnect from this specific chain chain.remove(); // Terminate the entire client (disconnects all chains) await client.terminate(); ``` -------------------------------- ### New JSON-RPC API (chainHead v1) Source: https://context7.com/smol-dot/smoldot/llms.txt A newer, more efficient JSON-RPC specification designed for light clients, offering methods for following chain heads, querying storage, making runtime calls, and managing blocks. ```APIDOC ## New JSON-RPC API (chainHead v1) Smoldot also supports the newer, more efficient JSON-RPC specification designed for light clients. ### Methods #### `chainHead_v1_follow` **Description**: Starts following the chain head, optionally including runtime updates. **Parameters**: - `withRuntime` (boolean) - Required - Whether to include runtime updates in the follow stream. **Request Example**: ```javascript chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'chainHead_v1_follow', params: [true] // withRuntime: true })); ``` #### `chainHead_v1_storage` **Description**: Queries storage at a specific block. **Parameters**: - `subscriptionId` (string) - Required - The ID obtained from `chainHead_v1_follow`. - `blockHash` (string) - Required - The hash of the block to query. - `storageItems` (array) - Required - An array of storage items to query, each with `key` and `type`. - `childTrie` (string | null) - Optional - The child trie to query from. **Request Example**: ```javascript const subscriptionId = 'abc123...'; chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'chainHead_v1_storage', params: [ subscriptionId, '0xblockhash...', // blockHash [{ key: '0xstoragekey...', type: 'value' }], // storageItems null // childTrie ] })); ``` #### `chainHead_v1_call` **Description**: Makes a runtime call at a specific block. **Parameters**: - `subscriptionId` (string) - Required - The ID obtained from `chainHead_v1_follow`. - `blockHash` (string) - Required - The hash of the block to execute the call against. - `runtimeApiMethod` (string) - Required - The name of the runtime API method to call. - `encodedParams` (string) - Required - The encoded parameters for the runtime API method. **Request Example**: ```javascript const subscriptionId = 'abc123...'; chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 3, method: 'chainHead_v1_call', params: [ subscriptionId, '0xblockhash...', // blockHash 'Api_method', // runtimeApiMethod '0x' // encodedParams ] })); ``` #### `chainHead_v1_body` **Description**: Retrieves the block body for a given block hash. **Parameters**: - `subscriptionId` (string) - Required - The ID obtained from `chainHead_v1_follow`. - `blockHash` (string) - Required - The hash of the block whose body is to be retrieved. **Request Example**: ```javascript const subscriptionId = 'abc123...'; chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 4, method: 'chainHead_v1_body', params: [subscriptionId, '0xblockhash...'] })); ``` #### `chainHead_v1_unpin` **Description**: Unpins blocks, allowing them to be garbage collected to free memory. **Parameters**: - `subscriptionId` (string) - Required - The ID obtained from `chainHead_v1_follow`. - `blockHashes` (array) - Required - An array of block hashes to unpin. **Request Example**: ```javascript const subscriptionId = 'abc123...'; chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 5, method: 'chainHead_v1_unpin', params: [subscriptionId, ['0xhash1...', '0xhash2...']] })); ``` #### `chainHead_v1_unfollow` **Description**: Stops following the chain head and cleans up resources. **Parameters**: - `subscriptionId` (string) - Required - The ID obtained from `chainHead_v1_follow`. **Request Example**: ```javascript const subscriptionId = 'abc123...'; chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 6, method: 'chainHead_v1_unfollow', params: [subscriptionId] })); ``` #### `transaction_v1_broadcast` **Description**: Broadcasts a signed extrinsic to the network. **Parameters**: - `signedExtrinsic` (string) - Required - The signed extrinsic in hexadecimal format. **Request Example**: ```javascript chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 7, method: 'transaction_v1_broadcast', params: ['0xsignedextrinsic...'] })); ``` ``` -------------------------------- ### Compile Bytecode and Run Smoldot in Worker (TypeScript) Source: https://github.com/smol-dot/smoldot/blob/main/wasm-node/javascript/README.md This snippet shows the worker-side implementation for smoldot. It compiles the smoldot bytecode using `compileBytecode` and sends it to the main thread. It also sets up an `onmessage` handler to receive messages from the main thread and pass them to `smoldot.run`. ```typescript // `worker.ts` import * as smoldot from 'smoldot/worker'; import { compileBytecode } from 'smoldot/bytecode'; compileBytecode().then((bytecode) => postMessage(bytecode)) onmessage = (msg) => smoldot.run(msg.data); ``` -------------------------------- ### Send JSON-RPC Requests (Rust) Source: https://context7.com/smol-dot/smoldot/llms.txt Details how to send JSON-RPC requests to a connected blockchain using `client.json_rpc_request()` in Rust. This function allows for querying chain information, subscribing to events, and interacting with chain state. ```rust use smoldot_light::{Client, ChainId, JsonRpcResponses}; use futures_lite::FutureExt; async fn query_chain( client: &mut Client, chain_id: ChainId, mut responses: JsonRpcResponses, ) { // Query system information client.json_rpc_request( r#"{"jsonrpc":"2.0","id":1,"method":"system_chain","params":[]}"#, chain_id, ).unwrap(); // Get chain name if let Some(response) = responses.next().await { println!("Chain response: {}", response); } // Subscribe to finalized heads client.json_rpc_request( r#"{"jsonrpc":"2.0","id":2,"method":"chain_subscribeFinalizedHeads","params":[]}"#, chain_id, ).unwrap(); // Query storage client.json_rpc_request( r#"{"jsonrpc":"2.0","id":3,"method":"state_getMetadata","params":[]}"#, chain_id, ).unwrap(); // Process all responses loop { if let Some(response) = responses.next().await { let json: serde_json::Value = serde_json::from_str(&response).unwrap(); if let Some(result) = json.get("result") { println!("Result: {:?}", result); } if let Some(params) = json.get("params") { // This is a subscription notification println!("Notification: {:?}", params); } } else { break; } } } ``` -------------------------------- ### Connect to Blockchain with Smoldot (TypeScript) Source: https://context7.com/smol-dot/smoldot/llms.txt Connects to a blockchain network using its chain specification and optionally links parachains to relay chains. Returns a `Chain` object for JSON-RPC interactions. Handles chain specifications loaded from files and supports cached database content for faster synchronization. ```typescript import * as smoldot from 'smoldot'; import fs from 'fs'; const client = smoldot.start(); // Load chain specification (obtained from substrate node: `substrate build-spec --raw`) const polkadotSpec = fs.readFileSync('./polkadot.json', 'utf-8'); try { // Add a relay chain (e.g., Polkadot) const polkadotChain = await client.addChain({ chainSpec: polkadotSpec, // Optional: Provide cached database for faster sync databaseContent: localStorage.getItem('polkadot-db') || undefined, // Optional: Limit JSON-RPC queue size (prevents memory issues) jsonRpcMaxPendingRequests: 128, jsonRpcMaxSubscriptions: 1024, }); // Add a parachain (requires relay chain reference) const assetHubSpec = fs.readFileSync('./asset-hub.json', 'utf-8'); const assetHubChain = await client.addChain({ chainSpec: assetHubSpec, potentialRelayChains: [polkadotChain], // Link to relay chain }); console.log('Connected to Polkadot and Asset Hub!'); } catch (error) { if (error instanceof smoldot.AddChainError) { console.error('Failed to add chain:', error.message); } } ``` -------------------------------- ### JSON-RPC Communication with Smoldot (TypeScript) Source: https://context7.com/smol-dot/smoldot/llms.txt Enables JSON-RPC communication with a connected blockchain. Use `sendJsonRpc()` to send requests and `nextJsonRpcResponse()` or the `jsonRpcResponses` async iterator to receive responses and notifications. Supports methods like `chain_getBlockHash` and subscriptions such as `chain_subscribeNewHeads`. ```typescript import * as smoldot from 'smoldot'; const client = smoldot.start(); const chain = await client.addChain({ chainSpec: polkadotSpec }); // Send a JSON-RPC request chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'chain_getBlockHash', params: [0] // Get genesis block hash })); // Wait for and process the response const response = await chain.nextJsonRpcResponse(); const parsed = JSON.parse(response); console.log('Genesis hash:', parsed.result); // Subscribe to new block headers using async iterator chain.sendJsonRpc(JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'chain_subscribeNewHeads', params: [] })); // Process responses and notifications for await (const message of chain.jsonRpcResponses) { const data = JSON.parse(message); if (data.params?.result?.number) { console.log('New block:', parseInt(data.params.result.number, 16)); } } ```