### Initialize Node.js Examples Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/vendor/kluster/kaspa-wasm-web/README.md For Node.js examples, especially when building from source, you need to initialize a local configuration by running `node init`. This command creates a `config.json` file containing a private key for use across examples. Dependencies like TypeScript types and W3C websocket modules are installed via `npm install`. ```bash cd wasm ./build-release cd examples npm install node init node nodejs/javascript/general/rpc.js ``` -------------------------------- ### Serve Web Examples Locally Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/vendor/kluster/kaspa-wasm-web/README.md To run web examples, you need to serve them from a local web server. This is necessary because the examples use relative paths and WASM32 cannot be loaded using the `file://` protocol. Any web server can be used, and an example using `http-server` is provided. ```bash cargo install http-server http-server ``` -------------------------------- ### Install Project Dependencies with npm Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/README.md This command navigates to the project directory and installs all necessary dependencies using npm. Ensure you have Node.js 18.17 or later installed. ```bash cd react-starter npm install ``` -------------------------------- ### Start Development Server with npm Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/README.md This command starts the development server for the Next.js application. After running this, you can access the application at http://localhost:3000 in your browser. ```bash npm run dev ``` -------------------------------- ### RPC Client Start Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Starts the RpcClient and establishes the necessary connections to the Kaspa node. This method should be called after initialization and before making RPC calls. ```typescript await rpc.start(); ``` -------------------------------- ### Build Kaspa Documentation from Source Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/vendor/kluster/kaspa-wasm-web/README.md To generate documentation from source, you need to have Rust installed. This process involves installing `typedoc` globally, then running the `./build-docs` script. The script first builds the WASM32 SDK and then generates the typedoc documentation, which will be located in the `docs/typedoc/` directory. ```bash npm install -g typedoc ./build-docs ``` -------------------------------- ### POST /startRpcServices Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Starts background RPC services for the Kaspa node. These services are typically started automatically when connecting. ```APIDOC ## POST /startRpcServices ### Description Start background RPC services (automatically started when invoking RpcClient.connect). ### Method POST ### Endpoint /startRpcServices ### Parameters #### Query Parameters - **None** #### Request Body - **None** ### Request Example ```json {} ``` ### Response #### Success Response (200) - **message** (string) - Confirmation that RPC services have started. #### Response Example ```json { "message": "RPC services started successfully." } ``` ``` -------------------------------- ### UtxoProcessor: Start and Stop Processing Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Manages the lifecycle of the UtxoProcessor. The start() method initiates the processing of UTXO and other notifications, while stop() terminates it. These methods are crucial for managing wallet data synchronization. ```typescript const processor = new UtxoProcessor(js_value); await processor.start(); // ... processing logic ... await processor.stop(); ``` -------------------------------- ### Get Fee Estimate (Experimental) Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Provides feerate estimates (experimental). ```APIDOC ## Get Fee Estimate (Experimental) ### Description Feerate estimates (experimental). See IGetFeeEstimateExperimentalRequest, IGetFeeEstimateExperimentalResponse. ### Method GET (assumed) ### Endpoint /getFeeEstimateExperimental ### Parameters #### Query Parameters - **targetBlocks** (number) - Optional - The number of blocks to target for the fee estimation. ### Request Example ```json { "targetBlocks": 1 } ``` ### Response #### Success Response (200) - **feeEstimate** (number) - The estimated fee in sompi per sompi/byte. #### Response Example ```json { "feeEstimate": 1000 } ``` ``` -------------------------------- ### GET /getServerInfo Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Retrieves information about the Kaspa server, including its version, protocol version, and network identifier. This is an alternative for wRPC clients. ```APIDOC ## GET /getServerInfo ### Description Retrieves information about the Kaspa server. Returned information: Version of the Kaspa server, protocol version, network identifier. For wRPC clients, use RpcClient.getServerInfo. ### Method GET ### Endpoint /getServerInfo ### Parameters #### Query Parameters - **None** #### Request Body - **None** ### Request Example ```json {} ``` ### Response #### Success Response (200) - **version** (string) - The version of the Kaspa server. - **protocolVersion** (string) - The protocol version supported by the server. - **networkId** (string) - The identifier of the Kaspa network. #### Response Example ```json { "version": "1.0.0", "protocolVersion": "7", "networkId": "mainnet" } ``` ``` -------------------------------- ### RPC Client Get Server Info Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Fetches detailed information about the Kaspa RPC server. This can include server status, capabilities, and configuration details. ```typescript await rpc.getServerInfo(request); ``` -------------------------------- ### Connect to RPC Server Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Connects to the Kaspa RPC server. Starts a background task that connects and reconnects if the connection is terminated. Use disconnect() to terminate the connection. ```APIDOC ## Connect to RPC Server ### Description Connect to the Kaspa RPC server. This function starts a background task that connects and reconnects to the server if the connection is terminated. Use disconnect() to terminate the connection. See IConnectOptions interface for more details. ### Method Not specified ### Endpoint N/A ### Parameters #### Request Body - **options** (object) - Optional - Connection options. - **reconnectInterval** (number) - Optional - Interval in milliseconds for reconnection attempts. - **timeout** (number) - Optional - Connection timeout in milliseconds. ### Request Example ```json { "options": { "reconnectInterval": 5000, "timeout": 10000 } } ``` ### Response #### Success Response (200) Returned information: None (connection is established in the background). #### Response Example (No specific response body mentioned.) ``` -------------------------------- ### Get Fee Estimate (Experimental) Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Provides feerate estimates (experimental). Throws an error on RPC error, server-side error, or incorrect arguments. ```APIDOC ## POST /mmostars/kaspa-nextjs-vibecoding-starterkit/getFeeEstimateExperimental ### Description Provides feerate estimates (experimental). ### Method POST ### Endpoint /mmostars/kaspa-nextjs-vibecoding-starterkit/getFeeEstimateExperimental ### Parameters #### Request Body - **request** (object) - Required - Request object for experimental fee estimation. - **targetBlocks** (number) - Optional - The number of blocks to confirm within. - **includeAll** (boolean) - Optional - Whether to include all fee estimates. ### Response #### Success Response (200) - **feeEstimate** (object) - Estimated fee information. - **satoshiPerVirtualSec** (number) - Estimated satoshi per virtual byte. #### Response Example ```json { "feeEstimate": { "satoshiPerVirtualSec": 1000 } } ``` ``` -------------------------------- ### RPC Client Get Virtual Chain From Block Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Retrieves the virtual chain information starting from a specified block. This helps in understanding the state of the DAG from a particular point in history. ```typescript await rpc.getVirtualChainFromBlock(request); ``` -------------------------------- ### RPC Client Get Block Template Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Requests a block template from the Kaspa node, which is used for mining. This template contains the necessary information to start mining a new block. ```typescript await rpc.getBlockTemplate(request); ``` -------------------------------- ### RpcClient Initialization and Connection Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Demonstrates how to initialize the RpcClient and establish a connection to a Kaspa node, either directly or through a resolver. ```APIDOC ## RpcClient Initialization and Connection ### Description This section details how to create an instance of the `RpcClient` and connect to the Kaspa network. You can connect directly to a node by providing its URL or use a `Resolver` to connect to a community-maintained public node infrastructure. ### Methods - `new RpcClient(config?: IRpcConfig): RpcClient` - `connect(args?: ConnectSettings): Promise` ### Parameters #### `IRpcConfig` Interface - `url` (string) - Optional - The URL of the Kaspa node to connect to. Defaults to the network's default port if not provided. - `resolver` (Resolver) - Optional - An instance of the `Resolver` class to connect via public nodes. - `networkId` (string) - Required when using a resolver - Specifies the Kaspa network (e.g., "mainnet"). - `rpcCore` (RpcCore) - Optional - Allows for advanced configuration of the RPC core. - `isMobile` (boolean) - Optional - Flag indicating if the client is running in a mobile environment. #### `ConnectSettings` (for `connect` method) - `reconnect` (boolean) - Optional - Specifies if the client should attempt to reconnect upon disconnection. ### Request Example (Direct Connection) ```javascript let rpc = new RpcClient({ url: "127.0.0.1", networkId: "mainnet", }); await rpc.connect(); ``` ### Request Example (Connection via Resolver) ```javascript let rpc = new RpcClient({ resolver: new Resolver(), networkId: "mainnet", }); await rpc.connect(); ``` ### Response - **Success Response (200)**: The `connect` method returns a `Promise` which resolves upon successful connection. ### Error Handling - Connection errors will be thrown as exceptions and can be caught using a `try...catch` block. ``` -------------------------------- ### CreateWriteStreamOptions Class Definition Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Options for creating a writable stream. This class configures parameters like auto_close, emit_close, encoding, fd, flags, mode, and start for write streams. It includes methods to get and set these properties and a free method. ```typescript class CreateWriteStreamOptions { constructor(auto_close?: boolean, emit_close?: boolean, encoding?: string, fd?: number, flags?: string, mode?: number, start?: number); get auto_close(): boolean; set auto_close(value: boolean); get emit_close(): boolean; set emit_close(value: boolean); get encoding(): string; set encoding(value: string); get fd(): number; set fd(value: number); get flags(): string; set flags(value: string); get mode(): number; set mode(value: number); get start(): number; set start(value: number); free(): void; } ``` -------------------------------- ### Get Server Info (wRPC) Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Retrieves information about the Kaspa server, including version, protocol version, and network identifier. This is intended for wRPC clients. ```APIDOC ## GET /server/info ### Description Retrieves information about the Kaspa server, including version, protocol version, and network identifier. ### Method GET ### Endpoint /server/info ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **version** (string) - The version of the Kaspa server. - **protocolVersion** (string) - The protocol version of the Kaspa server. - **networkId** (string) - The network identifier of the Kaspa server. #### Response Example ```json { "version": "1.0.0", "protocolVersion": "5", "networkId": "mainnet" } ``` ``` -------------------------------- ### Wallet Class Initialization Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Initializes a new Wallet instance with the provided configuration. ```APIDOC ## new Wallet(config) ### Description Initializes a new Wallet instance with the provided configuration. ### Method Constructor ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **config** (IWalletConfig) - Required - Configuration object for the wallet. ### Request Example ```json { "config": { "networkId": "mainnet", "storagePath": "/path/to/wallet/data" } } ``` ### Response #### Success Response (200) * **Wallet** (Wallet) - An instance of the Wallet class. #### Response Example ```json { "instance": "" } ``` ``` -------------------------------- ### GET /getInfo Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Retrieves general information about the Kaspa node, including its version, protocol version, and network identifier. Primarily intended for gRPC clients. ```APIDOC ## GET /getInfo ### Description Retrieves general information about the Kaspa node, including its version, protocol version, and network identifier. This call is primarily used by gRPC clients. ### Method GET ### Endpoint /getInfo ### Parameters #### Query Parameters - **None** #### Request Body - **None** ### Request Example ```json {} ``` ### Response #### Success Response (200) - **version** (string) - The version of the Kaspa node. - **protocolVersion** (string) - The protocol version supported by the node. - **networkId** (string) - The identifier of the Kaspa network. #### Response Example ```json { "version": "1.0.0", "protocolVersion": "7", "networkId": "mainnet" } ``` ``` -------------------------------- ### RPC Client Initialization Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Create a new RPC client with optional Encoding and a url. ```APIDOC ## Create RPC Client ### Description Create a new RPC client with optional Encoding and a url. See IRpcConfig interface for more details. ### Method Not specified (assumed constructor or factory function) ### Endpoint N/A ### Parameters #### Query Parameters - **url** (string) - Optional - The URL of the RPC server. - **encoding** (Encoding) - Optional - The encoding to use for communication. ### Request Example ```json { "url": "http://localhost:1234/rpc", "encoding": "json" } ``` ### Response #### Success Response (200) - **RpcClient** - An instance of the RPC client. #### Response Example ```json { "rpcClient": "[RpcClient Object]" } ``` ``` -------------------------------- ### Wallet Class Initialization and Methods Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md This snippet outlines the constructor and various methods available on the Wallet class. These methods cover operations like account management (create, enumerate, import, export), transaction processing (send, broadcast, estimate), and wallet configuration. ```typescript new Wallet(config): Wallet accountsActivate(request): Promise accountsCommitReveal(request): Promise accountsCommitRevealManual(request): Promise accountsCreate(request): Promise accountsCreateNewAddress(request): Promise accountsDeactivate(request): Promise accountsDiscovery(request): Promise accountsEnsureDefault(request): Promise accountsEnumerate(request): Promise accountsEstimate(request): Promise accountsGet(request): Promise accountsGetUtxos(request): Promise accountsImport(request): Promise accountsPskbBroadcast(request): Promise accountsPskbSend(request): Promise accountsPskbSign(request): Promise accountsRename(request): Promise accountsSend(request): Promise accountsTransfer(request): Promise addEventListener(callback): void addEventListener(event, callback?): any(eventData): void addressBookEnumerate(request): Promise batch(request): Promise connect(args?): Promise disconnect(): Promise exists(name?): Promise feeRateEstimate(request): Promise feeRatePollerDisable(request): Promise feeRatePollerEnable(request): Promise flush(request): Promise free(): void getStatus(request): Promise prvKeyDataCreate(request): Promise prvKeyDataEnumerate(request): Promise prvKeyDataGet(request): Promise prvKeyDataRemove(request): Promise removeEventListener(event, callback?): void retainContext(request): Promise setNetworkId(network_id): void start(): Promise stop(): Promise toJSON(): Object toString(): string transactionsDataGet(request): Promise transactionsReplaceMetadata(request): Promise transactionsReplaceNote(request): Promise walletChangeSecret(request): Promise walletClose(request): Promise walletCreate(request): Promise walletEnumerate(request): Promise walletExport(request): Promise walletImport(request): Promise walletOpen(request): Promise walletReload(request): Promise ``` -------------------------------- ### RPC Client Get Current Block Color Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Gets the current block color information. Kaspa uses block colors to differentiate between different types of blocks or phases in the network. ```typescript await rpc.getCurrentBlockColor(request); ``` -------------------------------- ### Get Fee Estimate Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Provides feerate estimates. ```APIDOC ## Get Fee Estimate ### Description Feerate estimates. See IGetFeeEstimateRequest, IGetFeeEstimateResponse. ### Method GET (assumed) ### Endpoint /getFeeEstimate ### Parameters #### Query Parameters - **targetBlocks** (number) - Optional - The number of blocks to target for the fee estimation. ### Request Example ```json { "targetBlocks": 1 } ``` ### Response #### Success Response (200) - **feeEstimate** (number) - The estimated fee in sompi per sompi/byte. #### Response Example ```json { "feeEstimate": 1000 } ``` ``` -------------------------------- ### Connect to Kaspa Network using RpcContext Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/README.md An example React component demonstrating how to use the `useRpc` hook from `RpcContext` to connect to the Kaspa network. It handles connection status and displays a message accordingly. Requires React and the `RpcContext` provider. ```typescript import { useRpc } from "@/context/RpcContext"; import { useEffect } from "react"; function MyComponent() { const { rpc, isConnected, connect } = useRpc(); useEffect(() => { if (!isConnected) { connect(); } }, [isConnected, connect]); if (!isConnected) { return
Connecting to Kaspa network...
; } return
Connected to Kaspa!
; } ``` -------------------------------- ### Get Headers Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Retrieves block headers from the Kaspa BlockDAG. ```APIDOC ## Get Headers ### Description Retrieves block headers from the Kaspa BlockDAG. See IGetHeadersRequest, IGetHeadersResponse. ### Method GET (assumed) ### Endpoint /getHeaders ### Parameters #### Query Parameters - **startHash** (string) - Optional - The hash of the first block header to retrieve. - **endHash** (string) - Optional - The hash of the last block header to retrieve. - **limit** (number) - Optional - The maximum number of block headers to retrieve. ### Request Example ```json { "limit": 5, "startHash": "0xabc123...", "endHash": "0xfedcba..." } ``` ### Response #### Success Response (200) - **headers** (array of objects) - A list of block header information. #### Response Example ```json { "headers": [ { "hash": "...", "timestamp": 1678886400, ... }, { "hash": "...", "timestamp": 1678886300, ... } ] } ``` ``` -------------------------------- ### Manage Kaspa RPC Connections with TypeScript Source: https://context7.com/mmostars/kaspa-nextjs-vibecoding-starterkit/llms.txt Demonstrates how to initialize and manage connections to the Kaspa blockchain network using the RpcProvider and useRpc hook from the provided context. It handles connection states like connecting, connected, and errors, allowing for programmatic connection and disconnection. ```typescript "use client"; import { RpcProvider, useRpc } from "@/context/RpcContext"; import { useEffect } from "react"; // Wrap your app with RpcProvider function App() { return ( ); } // Use the RPC client in components function YourComponent() { const { rpc, isConnected, isConnecting, error, connect, disconnect, url } = useRpc(); useEffect(() => { // Connect to mainnet on mount if (!isConnected && !isConnecting) { connect(); } }, [isConnected, isConnecting, connect]); if (isConnecting) { return
Connecting to Kaspa network...
; } if (error) { return
Connection error: {error}
; } if (isConnected) { return (

Connected to: {url}

); } return ; } ``` -------------------------------- ### Function: initSync Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Synchronously initializes the Wasm module. ```APIDOC ## POST /initSync ### Description Instantiates the given module synchronously, which can either be bytes or a precompiled WebAssembly.Module. Passing SyncInitInput directly is deprecated. ### Method POST ### Endpoint `/initSync` ### Parameters #### Request Body - **module** (SyncInitInput) - Required - The module to initialize. Passing SyncInitInput directly is deprecated. ### Request Example ```json { "module": "" } ``` ### Response #### Success Response (200) - **output** (InitOutput) - The output of the initialization. #### Response Example ```json { "output": { "instance": "", "module": "" } } ``` ``` -------------------------------- ### Get Current Network Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Retrieves the current network configuration. ```APIDOC ## Get Current Network ### Description Retrieves the current network configuration. See IGetCurrentNetworkRequest, IGetCurrentNetworkResponse. ### Method GET (assumed) ### Endpoint /getCurrentNetwork ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **network** (string) - The name of the current network (e.g., "mainnet", "testnet", "devnet"). #### Response Example ```json { "network": "mainnet" } ``` ``` -------------------------------- ### Node RPC: Resolver Usage with RpcClient Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Demonstrates how to initialize an RpcClient using the Resolver class to connect to Kaspa wRPC endpoints. It shows two methods: using integrated public URLs and specifying custom resolver URLs. This is crucial for establishing communication with Kaspa network nodes. ```typescript let rpc = RpcClient({ resolver: new Resolver(), networkId : "mainnet"}); let rpc = RpcClient({ resolver: new Resolver({urls: ["",...]}), networkId : "mainnet"}); ``` -------------------------------- ### Get Current Block Color Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Checks if a block is blue or not. ```APIDOC ## Get Current Block Color ### Description Checks if block is blue or not. See IGetCurrentBlockColorRequest, IGetCurrentBlockColorResponse. ### Method GET (assumed) ### Endpoint /getCurrentBlockColor ### Parameters #### Query Parameters - **hash** (string) - Required - The hash of the block. ### Request Example ```json { "hash": "0xf4184fc596403b9d638783cf57adfe4c75c605f6356f2f090798637091c10721" } ``` ### Response #### Success Response (200) - **isBlue** (boolean) - True if the block is blue, false otherwise. #### Response Example ```json { "isBlue": true } ``` ``` -------------------------------- ### RPC Client Connection Attempt Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Shows how to initiate a connection to the Kaspa node using the RpcClient and handle potential connection errors. It's important to wrap the connect call in a try-catch block to manage network issues gracefully. ```typescript try { await rpc.connect(); } catch (err) { console.log("Error connecting:", err); } ``` -------------------------------- ### Get Connections Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Retrieves current number of network connections. ```APIDOC ## Get Connections ### Description Retrieves current number of network connections. See IGetConnectionsRequest, IGetConnectionsResponse. ### Method GET (assumed) ### Endpoint /getConnections ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **connectionCount** (number) - The current number of network connections. #### Response Example ```json { "connectionCount": 15 } ``` ``` -------------------------------- ### Get Blocks Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Retrieves multiple blocks from the Kaspa BlockDAG. ```APIDOC ## Get Blocks ### Description Retrieves multiple blocks from the Kaspa BlockDAG. See IGetBlocksRequest, IGetBlocksResponse. ### Method GET (assumed) ### Endpoint /getBlocks ### Parameters #### Query Parameters - **startHash** (string) - Optional - The hash of the first block to retrieve. - **endHash** (string) - Optional - The hash of the last block to retrieve. - **limit** (number) - Optional - The maximum number of blocks to retrieve. ### Request Example ```json { "limit": 10, "startHash": "0xabc123...", "endHash": "0xfedcba..." } ``` ### Response #### Success Response (200) - **blocks** (array of objects) - A list of block information. #### Response Example ```json { "blocks": [ { "hash": "...", "timestamp": 1678886400, ... }, { "hash": "...", "timestamp": 1678886300, ... } ] } ``` ``` -------------------------------- ### Initialize Kaspa RpcClient in Node.js Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/vendor/kluster/kaspa-wasm-web/README.md This JavaScript code illustrates how to initialize and use the `RpcClient` in a Node.js environment. It includes a shim for the W3C WebSocket module, which is necessary when building WASM libraries for Node.js from source. The `RpcClient` is configured with the server URL, encoding type, and network, and then used to connect, fetch information, and disconnect. ```javascript // // W3C WebSocket module shim // this is provided by NPM `kaspa` module and is only needed // if you are building WASM libraries for NodeJS from source // // @ts-ignore // globalThis.WebSocket = require('websocket').w3cwebsocket; // let { RpcClient, Encoding, initConsolePanicHook } = require('./kaspa'); // enabling console panic hooks allows WASM to print panic details to console // initConsolePanicHook(); // enabling browser panic hooks will create a full-page DIV with panic details // this is useful for mobile devices where console is not available // initBrowserPanicHook(); // if port is not specified, it will use the default port for the specified network const rpc = new RpcClient({ url: "127.0.0.1", encoding: Encoding.Borsh, network : "testnet-10" }); (async () => { try { await rpc.connect(); let info = await rpc.getInfo(); console.log(info); } finally { await rpc.disconnect(); } })(); ``` -------------------------------- ### Get Block Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Retrieves a specific block from the Kaspa BlockDAG. ```APIDOC ## Get Block ### Description Retrieves a specific block from the Kaspa BlockDAG. See IGetBlockRequest, IGetBlockResponse. ### Method GET (assumed) ### Endpoint /getBlock ### Parameters #### Query Parameters - **hash** (string) - Required - The hash of the block to retrieve. - **includeTransactionInfo** (boolean) - Optional - Whether to include transaction information. ### Request Example ```json { "hash": "0xf4184fc596403b9d638783cf57adfe4c75c605f6356f2f090798637091c10721", "includeTransactionInfo": true } ``` ### Response #### Success Response (200) - **block** (object) - Information about the requested block. #### Response Example ```json { "block": { "hash": "0xf4184fc596403b9d638783cf57adfe4c75c605f6356f2f090798637091c10721", "parentHashes": ["..."], "timestamp": 1678886400, "blueScore": 1000, "difficulty": 5000000000, "size": 1024, "transactions": [...] } } ``` ``` -------------------------------- ### RPC Client Event Listener Example Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Demonstrates how to register and handle events for the RpcClient, such as 'connect' and 'disconnect'. Event listeners are crucial for managing the connection state and responding to network events. Re-subscription to Kaspa node notifications is required upon reconnection. ```typescript rpc.addEventListener("connect", async (event) => { console.log("Connected to", rpc.url); await rpc.subscribeDaaScore(); }); rpc.addEventListener("disconnect", (event) => { console.log("Disconnected from", rpc.url); }); ``` -------------------------------- ### Wallet API: Account Creation Arguments Interface Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Defines the arguments interface for creating a new account. It specifically supports BIP32 derivation and allows for optional private key data arguments. ```typescript interface IAccountCreateArgs { args: IAccountCreateArgsBip32; prvKeyDataArgs?: IPrvKeyDataArgs; type: "bip32"; } ``` -------------------------------- ### Keypair Generation and Address Conversion Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Illustrates the creation and usage of Keypair objects for managing cryptographic keys. It shows how to generate a new random Keypair, derive addresses from its public key using different ECDSA methods, and create a Keypair from a private key. ```typescript let address = keypair.toAddress(NetworkType.MAINNET); let addressECDSA = keypair.toAddressECDSA(NetworkType.MAINNET); ``` ```typescript let privkey = new PrivateKey(hexString); let keypair = privkey.toKeypair(); ``` ```typescript let keypair = Keypair.random(); ``` -------------------------------- ### Get Block Template Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Generates a new block template for mining. ```APIDOC ## Get Block Template ### Description Generates a new block template for mining. See IGetBlockTemplateRequest, IGetBlockTemplateResponse. ### Method GET (assumed) ### Endpoint /getBlockTemplate ### Parameters #### Query Parameters - **miningAddress** (string) - Required - The address to which the coinbase transaction should pay the block's reward. ### Request Example ```json { "miningAddress": "kaspa:qqq428q5l6d06x3u953z6k3720030y2988278z74f746u7k2v2h44z722922074" } ``` ### Response #### Success Response (200) - **blockTemplate** (object) - Information about the block template. #### Response Example ```json { "blockTemplate": { "header": { "version": 1, "parentHashes": [...], "acceptedIDMerkleRoot": "...", "hashMerkleRoot": "...", "transactionMerkleRoot": "...", "witness": [], "index": 0, "timestamp": 1678886400, "bits": "...", "nonce": 0, "daaScore": 12345 }, "difficulty": 5000000000, "parentHashes": [...] } } ``` ``` -------------------------------- ### Get Balances By Addresses Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Retrieves balances for multiple addresses in the Kaspa BlockDAG. ```APIDOC ## Get Balances By Addresses ### Description Retrieves balances for multiple addresses in the Kaspa BlockDAG. See IGetBalancesByAddressesRequest, IGetBalancesByAddressesResponse. ### Method GET (assumed) ### Endpoint /getBalancesByAddresses ### Parameters #### Query Parameters - **addresses** (array of strings) - Required - A list of Kaspa addresses. ### Request Example ```json { "addresses": [ "kaspa:qqq428q5l6d06x3u953z6k3720030y2988278z74f746u7k2v2h44z722922074", "kaspa:qqyq82q5l6d06x3u953z6k3720030y2988278z74f746u7k2v2h44z722922074" ] } ``` ### Response #### Success Response (200) - **balances** (object) - An object where keys are addresses and values are their balances. #### Response Example ```json { "balances": { "kaspa:qqq428q5l6d06x3u953z6k3720030y2988278z74f746u7k2v2h44z722922074": 1000000000, "kaspa:qqyq82q5l6d06x3u953z6k3720030y2988278z74f746u7k2v2h44z722922074": 500000000 } } ``` ``` -------------------------------- ### Type: InitInput Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Represents the input type for initialization, which can be a RequestInfo, URL, Response, BufferSource, or WebAssembly.Module. ```APIDOC ## Type: InitInput ### Description Represents the input type for initialization, which can be a RequestInfo, URL, Response, BufferSource, or WebAssembly.Module. ### Signature `InitInput: RequestInfo | URL | Response | BufferSource | WebAssembly.Module` ``` -------------------------------- ### Get Balance By Address Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Retrieves the balance of a specific address in the Kaspa BlockDAG. ```APIDOC ## Get Balance By Address ### Description Retrieves the balance of a specific address in the Kaspa BlockDAG. See IGetBalanceByAddressRequest, IGetBalanceByAddressResponse. ### Method GET (assumed) ### Endpoint /getBalanceByAddress ### Parameters #### Query Parameters - **address** (string) - Required - The Kaspa address. ### Request Example ```json { "address": "kaspa:qqq428q5l6d06x3u953z6k3720030y2988278z74f746u7k2v2h44z722922074" } ``` ### Response #### Success Response (200) - **balance** (number) - The balance of the specified address. #### Response Example ```json { "balance": 1000000000 } ``` ``` -------------------------------- ### getVirtualChainFromBlock RPC Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Retrieves the virtual chain information starting from a specified block hash. ```APIDOC ## POST /rpc ### Description Gets the virtual chain of blocks from a given starting block hash. ### Method POST ### Endpoint /rpc ### Parameters #### Request Body - **includeAcceptedTransactionIds** (boolean) - Required - Whether to include accepted transaction IDs. - **startHash** (string) - Required - The hash of the starting block. ### Request Example ```json { "method": "getVirtualChainFromBlock", "params": { "includeAcceptedTransactionIds": true, "startHash": "startBlockHash" } } ``` ### Response #### Success Response (200) - **acceptedTransactionIds** (IAcceptedTransactionIds[]) - List of accepted transaction IDs. - **addedChainBlockHashes** (string[]) - Hashes of blocks added to the chain. - **removedChainBlockHashes** (string[]) - Hashes of blocks removed from the chain. #### Response Example ```json { "result": { "acceptedTransactionIds": [], "addedChainBlockHashes": ["blockHash1", "blockHash2"], "removedChainBlockHashes": ["blockHash3"] } } ``` ``` -------------------------------- ### Load Kaspa WASM in Web App Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/vendor/kluster/kaspa-wasm-web/README.md This HTML snippet demonstrates how to load the Kaspa WASM module in a web application. It uses dynamic import to load the `kaspa-wasm.js` file and then initializes the WASM module by providing the `kaspa-wasm_bg.wasm` file path. The `kaspa.version()` function is then called to log the version. ```html ``` -------------------------------- ### Core RPC Methods Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Provides a list and descriptions of core RPC methods available through the RpcClient for interacting with the Kaspa network. ```APIDOC ## Core RPC Methods ### Description This section lists the primary methods available on the `RpcClient` instance to interact with the Kaspa node and retrieve network information. ### Available Methods #### Block and DAG Information - **`getBlock(request: GetBlockRequest): Promise`**: Retrieves information about a specific block. - **`getBlockCount(request?: GetBlockCountRequest): Promise`**: Gets the total number of blocks in the DAG. - **`getBlockDagInfo(request?: GetBlockDagInfoRequest): Promise`**: Retrieves detailed information about the block DAG. - **`getBlocks(request: GetBlocksRequest): Promise`**: Retrieves a list of blocks. - **`getBlockTemplate(request: GetBlockTemplateRequest): Promise`**: Gets a block template for mining. #### Account and UTXO Management - **`getBalanceByAddress(request: GetBalanceByAddressRequest): Promise`**: Retrieves the balance for a specific address. - **`getBalanceByAddresses(request: GetBalanceByAddressesRequest): Promise`**: Retrieves balances for multiple addresses. - **`getUtxosByAddresses(request: GetUtxosByAddressesRequest): Promise`**: Retrieves unspent transaction outputs (UTXOs) for given addresses. #### Network and Peer Information - **`estimateNetworkHashesPerSecond(request: EstimateNetworkHashesPerSecondRequest): Promise`**: Estimates the network's hash rate. - **`getCoinSupply(request?: GetCoinSupplyRequest): Promise`**: Retrieves the total coin supply. - **`getConnectedPeerInfo(request?: GetConnectedPeerInfoRequest): Promise`**: Gets information about connected peers. - **`getConnections(request?: GetConnectionsRequest): Promise`**: Retrieves a list of network connections. - **`getCurrentNetwork(request?: GetCurrentNetworkRequest): Promise`**: Gets the current network ID. - **`getFeeEstimate(request?: GetFeeEstimateRequest): Promise`**: Estimates the transaction fee. - **`getFeeEstimateExperimental(request?: GetFeeEstimateRequest): Promise`**: Provides an experimental fee estimation. - **`getInfo(request?: GetInfoRequest): Promise`**: Retrieves general information about the Kaspa node. - **`getMempoolEntries(request?: GetMempoolEntriesRequest): Promise`**: Gets all entries in the mempool. - **`getMempoolEntriesByAddresses(request: GetMempoolEntriesByAddressesRequest): Promise`**: Gets mempool entries for specific addresses. - **`getMempoolEntry(request: GetMempoolEntryRequest): Promise`**: Retrieves a single mempool entry. - **`getMetrics(request?: GetMetricsRequest): Promise`**: Retrieves performance metrics. - **`getPeerAddresses(request?: GetPeerAddressesRequest): Promise`**: Gets a list of peer addresses. - **`getServerInfo(request?: GetServerInfoRequest): Promise`**: Retrieves information about the RPC server. - **`getSyncStatus(request?: GetSyncStatusRequest): Promise`**: Gets the current synchronization status of the node. #### Transaction Submission - **`submitTransaction(request: SubmitTransactionRequest): Promise`**: Submits a transaction to the network. - **`submitTransactionReplacement(request: SubmitTransactionReplacementRequest): Promise`**: Submits a replacement for an existing transaction. #### Peer Management - **`addPeer(request: AddPeerRequest): Promise`**: Adds a peer to the node's known peers list. - **`ban(request: BanRequest): Promise`**: Bans a specific peer. - **`unban(request: UnbanRequest): Promise`**: Unbans a previously banned peer. #### Other Utilities - **`estimateNetworkHashesPerSecond(request: EstimateNetworkHashesPerSecondRequest): Promise`**: Estimates the network's current hash rate. - **`free(): void`**: Frees resources used by the RPC client (NodeJS specific). - **`ping(request?: PingRequest): Promise`**: Sends a ping request to the server. - **`shutdown(request?: ShutdownRequest): Promise`**: Shuts down the RPC client. - **`start(): Promise`**: Starts the RPC client service. - **`stop(): Promise`**: Stops the RPC client service. - **`submitBlock(request: SubmitBlockRequest): Promise`**: Submits a mined block to the network. *Note: Specific request and response types (e.g., `GetBlockRequest`, `GetBlockResponse`) are defined elsewhere in the Kaspa RPC schema.* ``` -------------------------------- ### Wallet Get Status API Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Retrieves the current status of the wallet connection and synchronization. ```APIDOC ## GET /wallet/status ### Description Fetches the current operational status of the wallet, including whether it is connected to a network, if the connection is open, and its synchronization state. An optional context name can be provided. ### Method GET ### Endpoint /wallet/status ### Parameters #### Query Parameters - **name** (string) - Optional - An optional name for the context, used for retaining context information. ### Request Example ``` GET /wallet/status?name=mycontext ``` ### Response #### Success Response (200) - **context** (string) - Optional - The retained context identifier, if provided and used. - **isConnected** (boolean) - Required - Indicates if the wallet is currently connected to a network. - **isOpen** (boolean) - Required - Indicates if the wallet connection is open. - **isSynced** (boolean) - Required - Indicates if the wallet is synchronized with the network. - **networkId** (NetworkId) - Optional - The identifier of the network the wallet is connected to. - **url** (string) - Optional - The URL of the Kaspa node the wallet is connected to. #### Response Example ```json { "isConnected": true, "isOpen": true, "isSynced": true, "networkId": "mainnet", "url": "http://localhost:16110" } ``` ``` -------------------------------- ### getSubnetwork RPC Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Handles requests to get subnetwork information and returns the associated data. ```APIDOC ## POST /rpc ### Description Retrieves information about a specific subnetwork. ### Method POST ### Endpoint /rpc ### Parameters #### Request Body - **subnetworkId** (string) - Required - The ID of the subnetwork to retrieve. ### Request Example ```json { "method": "getSubnetwork", "params": { "subnetworkId": "someSubnetworkId" } } ``` ### Response #### Success Response (200) - **gasLimit** (bigint) - The gas limit for the subnetwork. #### Response Example ```json { "result": { "gasLimit": "1000000000" } } ``` ``` -------------------------------- ### Generate and Submit Kaspa Transactions Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Demonstrates how to use the Generator to create and submit transactions. It accumulates UTXO entries, generates transactions until a target amount is met or maximum transaction mass is reached, and handles daisy-chained transactions. The process involves signing each pending transaction with private keys and submitting it via RPC. ```typescript let generator = new Generator({ utxoEntries : [...], changeAddress : "kaspa:...", outputs : [ { amount : kaspaToSompi(10.0), address: "kaspa:..."}, { amount : kaspaToSompi(20.0), address: "kaspa:..."}, ... ], priorityFee : 1000n, }); let pendingTransaction; while(pendingTransaction = await generator.next()) { await pendingTransaction.sign(privateKeys); await pendingTransaction.submit(rpc); } let summary = generator.summary(); console.log(summary); ``` -------------------------------- ### Get Sync Status Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Obtains basic information about the synchronization status of the Kaspa node. ```APIDOC ## GET /sync/status ### Description Obtains basic information about the synchronization status of the Kaspa node. ### Method GET ### Endpoint /sync/status ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **isSyncing** (boolean) - Indicates if the node is currently syncing. - **syncedBlockHash** (string) - The hash of the block the node is synced to, if synced. - **syncedBlockHeight** (integer) - The height of the block the node is synced to, if synced. #### Response Example ```json { "isSyncing": true, "syncedBlockHash": null, "syncedBlockHeight": 0 } ``` ``` -------------------------------- ### WasiOptions Class Source: https://github.com/mmostars/kaspa-nextjs-vibecoding-starterkit/blob/main/kaspa_wasm_sdk_documentation.md Options for WebAssembly System Interface (WASI). ```APIDOC ## WasiOptions Class ### Description Options for WebAssembly System Interface (WASI). ### Methods - `new WasiOptions(args, env, preopens): WasiOptions` - `get args(): any[]` - `set args(value): void` - `get env(): object` - `set env(value): void` - `free(): void` - `new(preopens): WasiOptions` ```