@blouflash/nimiq-rpc@2.1.2
JSON-RPC Client for the Nimiq Albatross Blockchain
Nimiq RPC Client for TypeScript
A fully typed Nimiq RPC client for every javascript runtime.
Table of Contents
How to use
Installation
deno:
deno add jsr:@blouflash/nimiq-rpc
npm:
npx jsr add @blouflash/nimiq-rpc
pnpm:
pnpm dlx jsr add @blouflash/nimiq-rpc
Usage
It is structured the same way as the Rust RPC Client
import { NimiqRPCClient } from '@blouflash/nimiq-rpc' const client = new NimiqRPCClient(); // async/await based example http call try { const result = await client.blockchain.getEpochNumber(); console.log("Result:", result); } catch (error) { if (error instanceof JSONRPCError) { console.error("JSON-RPC Error:", error); } else { console.error("An unknown error occurred:", error); } } // Promise based example http call client.blockchain.getBlockNumber().then((result) => { console.log("Result:", result); }).catch((error) => { if (error instanceof JSONRPCError) { console.error("JSON-RPC Error:", error); } else { console.error("An unknown error occurred:", error); } }); // async/await based example ws stream call const subscribtion = await client.blockchainStreams.subscribeForBlockHashes( { onMessage: (result) => { console.log("onMessage", result); }, onError: (error) => { console.error("onError", error); }, onConnectionError: (error) => { console.error("onConnectionError", error); }, }, { maxReconnects: 5, reconnectTimeout: 1000, callTimeout: 10000 }, // optional { filter: (_data) => true }, // optional ); console.log(subscribtion.getSubscriptionId()); subscribtion.close();
Auth
Auth is not supported however you can use a proxy like nginx and pass the auth token via query url. I recommend to use tls.
const client = new NimiqRPCClient("http://localhost/?token=mysecrettoken", "ws://localhost/ws?token=mysecrettoken");
NGINX Config:
http { server { listen 80; location / { # Check the token from the query parameter (?token=...) if ($arg_token != "mysecrettoken") { return 403; # Deny if the token is missing or invalid } # Forward valid requests to the node proxy_pass http://127.0.0.1:8648; } location /ws { # Check the token from the query parameter (?token=...) if ($arg_token != "mysecrettoken") { return 403; # Deny if the token is missing or invalid } proxy_pass http://127.0.0.1:8648; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_read_timeout 3600; } } }
Modules
BlockchainClient
The BlockchainClient class provides methods to interact with the blockchain.
Methods
getBlockNumber(options): Returns the block number for the current head.getBatchNumber(options): Returns the batch number for the current head.getEpochNumber(options): Returns the epoch number for the current head.getBlockByHash(hash, params, options): Tries to fetch a block given its hash.getBlockByNumber(blockNumber, params, options): Tries to fetch a block given its number.getLatestBlock(params, options): Returns the block at the head of the main chain.getSlotAt(blockNumber, params, options): Returns the information for the slot owner at the given block height and offset.getTransactionByHash(hash, options): Fetches the transaction(s) given the hash.getTransactionsByBlockNumber(blockNumber, options): Fetches the transaction(s) given the block number.getTransactionsByBatchNumber(batchIndex, options): Fetches the transaction(s) given the batch number.getTransactionsByAddress(address, params, options): Fetches the transaction(s) given the address.getInherentsByBlockNumber(blockNumber, options): Returns all the inherents (including reward inherents) given the block number.getInherentsByBatchNumber(batchIndex, options): Returns all the inherents (including reward inherents) given the batch number.getAccountByAddress(address, options): Tries to fetch the account at the given address.getAccounts(options): Fetches all accounts in the accounts tree.getActiveValidators(options): Returns a collection of the currently active validator's addresses and balances.getCurrentPenalizedSlots(options): Returns the currently penalized slots.getPreviousPenalizedSlots(options): Returns the previously penalized slots.getValidatorByAddress(address, options): Tries to fetch a validator information given its address.getValidators(options): Fetches all validators in the staking contract.getStakersByValidatorAddress(address, options): Fetches all stakers for a given validator.getStakerByAddress(address, options): Tries to fetch a staker information given its address.
Example Usage
import { NimiqRPCClient } from '@blouflash/nimiq-rpc' const client = new NimiqRPCClient(); // Example usage for getBlockNumber client.blockchain.getBlockNumber().then((result) => { console.log("Block Number:", result); }).catch((error) => { console.error("Error:", error); }); // Example usage for getBlockByHash client.blockchain.getBlockByHash("some-block-hash").then((result) => { console.log("Block by Hash:", result); }).catch((error) => { console.error("Error:", error); });
BlockchainStream
The BlockchainStream class provides methods to interact with the Nimiq Albatross Node's blockchain streams.
Methods
subscribeForBlockHashes(wsCallbacks, options, streamOptions): Subscribes to block hash events.subscribeForElectionBlocks(params, wsCallbacks, options): Subscribes to election blocks.subscribeForMicroBlocks(params, wsCallbacks, options): Subscribes to micro blocks.subscribeForMacroBlocks(params, wsCallbacks, options): Subscribes to macro blocks.subscribeForBlocks(params, wsCallbacks, options, streamOptions): Subscribes to all blocks.subscribeForValidatorElectionByAddress(params, wsCallbacks, options, streamOptions): Subscribes to pre epoch validators events.subscribeForLogsByAddressesAndTypes(params, wsCallbacks, options, streamOptions): Subscribes to log events related to a given list of addresses and log types.
Example Usage
import { NimiqRPCClient } from '@blouflash/nimiq-rpc' const client = new NimiqRPCClient(); // Example usage for subscribeForBlockHashes const subscription = await client.blockchainStreams.subscribeForBlockHashes( { onMessage: (result) => { console.log("Block Hash:", result); }, onError: (error) => { console.error("Error:", error); }, onConnectionError: (error) => { console.error("Connection Error:", error); }, } ); console.log("Subscription ID:", subscription.getSubscriptionId()); subscription.close();
ConsensusClient
The ConsensusClient class provides methods to interact with the consensus layer of the blockchain.
Methods
isConsensusEstablished(options): Returns a boolean specifying if we have established consensus with the network.getRawTransactionInfo(params, options): Given a serialized transaction, it will return the corresponding transaction struct.sendRawTransaction(params, options): Sends a raw transaction to the network.createTransaction(params, options): Creates a serialized transaction.sendTransaction(params, options): Sends a transaction.sendSyncTransaction(params, options): Sends a transaction and waits for confirmation.createNewVestingTransaction(params, options): Returns a serialized transaction creating a new vesting contract.sendNewVestingTransaction(params, options): Sends a transaction creating a new vesting contract to the network.sendSyncNewVestingTransaction(params, options): Sends a transaction creating a new vesting contract to the network and waits for confirmation.createRedeemVestingTransaction(params, options): Returns a serialized transaction redeeming a vesting contract.sendRedeemVestingTransaction(params, options): Sends a transaction redeeming a vesting contract.sendSyncRedeemVestingTransaction(params, options): Sends a transaction redeeming a vesting contract and waits for confirmation.createNewHtlcTransaction(params, options): Returns a serialized transaction creating a new HTLC contract.sendNewHtlcTransaction(params, options): Sends a transaction creating a new HTLC contract.sendSyncNewHtlcTransaction(params, options): Sends a transaction creating a new HTLC contract and waits for confirmation.createRedeemRegularHtlcTransaction(params, options): Returns a serialized transaction redeeming an HTLC contract.sendRedeemRegularHtlcTransaction(params, options): Sends a transaction redeeming an HTLC contract.sendSyncRedeemRegularHtlcTransaction(params, options): Sends a transaction redeeming a new HTLC contract and waits for confirmation.createRedeemTimeoutHtlcTransaction(params, options): Returns a serialized transaction redeeming a HTLC contract using theTimeoutResolvemethod.sendRedeemTimeoutHtlcTransaction(params, options): Sends a transaction redeeming a HTLC contract using theTimeoutResolvemethod to network.sendSyncRedeemTimeoutHtlcTransaction(params, options): Sends a transaction redeeming a HTLC contract using theTimeoutResolvemethod to network and waits for confirmation.createRedeemEarlyHtlcTransaction(params, options): Returns a serialized transaction redeeming a HTLC contract using theEarlyResolvemethod.sendRedeemEarlyHtlcTransaction(params, options): Sends a transaction redeeming a HTLC contract using theEarlyResolvemethod.sendSyncRedeemEarlyHtlcTransaction(params, options): Sends a transaction redeeming a HTLC contract using theEarlyResolvemethod and waits for confirmation.signRedeemEarlyHtlcTransaction(params, options): Returns a serialized signature that can be used to redeem funds from a HTLC contract using theEarlyResolvemethod.createNewStakerTransaction(params, options): Returns a serializednew_stakertransaction.sendNewStakerTransaction(params, options): Sends anew_stakertransaction.sendSyncNewStakerTransaction(params, options): Sends anew_stakertransaction and waits for confirmation.createStakeTransaction(params, options): Returns a serializedstaketransaction.sendStakeTransaction(params, options): Sends astaketransaction.sendSyncStakeTransaction(params, options): Sends astaketransaction and waits for confirmation.createUpdateStakerTransaction(params, options): Returns a serializedupdate_stakertransaction.sendUpdateStakerTransaction(params, options): Sends aupdate_stakertransaction.sendSyncUpdateStakerTransaction(params, options): Sends aupdate_stakertransaction and waits for confirmation.createSetActiveStakeTransaction(params, options): Returns a serializedset_active_staketransaction.sendSetActiveStakeTransaction(params, options): Sends aset_active_staketransaction.sendSyncSetActiveStakeTransaction(params, options): Sends aset_active_staketransaction and waits for confirmation.createRetireStakeTransaction(params, options): Returns a serializedretire_staketransaction.sendRetireStakeTransaction(params, options): Sends aretire_staketransaction.sendSyncRetireStakeTransaction(params, options): Sends aretire_staketransaction and waits for confirmation.createRemoveStakeTransaction(params, options): Returns a serializedremove_staketransaction.sendRemoveStakeTransaction(params, options): Sends aremove_staketransaction.sendSyncRemoveStakeTransaction(params, options): Sends aremove_staketransaction and waits for confirmation.createNewValidatorTransaction(params, options): Returns a serializednew_validatortransaction.sendNewValidatorTransaction(params, options): Sends anew_validatortransaction.sendSyncNewValidatorTransaction(params, options): Sends anew_validatortransaction and waits for confirmation.createUpdateValidatorTransaction(params, options): Returns a serializedupdate_validatortransaction.sendUpdateValidatorTransaction(params, options): Sends aupdate_validatortransaction.sendSyncUpdateValidatorTransaction(params, options): Sends aupdate_validatortransaction and waits for confirmation.createDeactivateValidatorTransaction(params, options): Returns a serializedinactivate_validatortransaction.sendDeactivateValidatorTransaction(params, options): Sends ainactivate_validatortransaction.sendSyncDeactivateValidatorTransaction(params, options): Sends ainactivate_validatortransaction and waits for confirmation.createReactivateValidatorTransaction(params, options): Returns a serializedreactivate_validatortransaction.sendReactivateValidatorTransaction(params, options): Sends areactivate_validatortransaction.sendSyncReactivateValidatorTransaction(params, options): Sends areactivate_validatortransaction and waits for confirmation.createRetireValidatorTransaction(params, options): Returns a serializedretire_validatortransaction.sendRetireValidatorTransaction(params, options): Sends aretire_validatortransaction.sendSyncRetireValidatorTransaction(params, options): Sends aretire_validatortransaction and waits for confirmation.createDeleteValidatorTransaction(params, options): Returns a serializeddelete_validatortransaction.sendDeleteValidatorTransaction(params, options): Sends adelete_validatortransaction.sendSyncDeleteValidatorTransaction(params, options): Sends adelete_validatortransaction and waits for confirmation.
Example Usage
import { NimiqRPCClient } from '@blouflash/nimiq-rpc' const client = new NimiqRPCClient(); // Example usage for isConsensusEstablished client.consensus.isConsensusEstablished().then((result) => { console.log("Consensus Established:", result); }).catch((error) => { console.error("Error:", error); }); // Example usage for sendTransaction const transactionParams = { wallet: "wallet-address", recipient: "recipient-address", value: 1000, fee: 1, absoluteValidityStartHeight: 100 }; client.consensus.sendTransaction(transactionParams).then((result) => { console.log("Transaction Sent:", result); }).catch((error) => { console.error("Error:", error); });
MempoolClient
The MempoolClient class provides methods to interact with the Nimiq Albatross Node's mempool.
Methods
pushTransaction(params, options): Pushes the given serialized transaction to the local mempool.mempoolContent(params, options): Content of the mempool.mempool(options): Obtains the mempool content in fee per byte buckets.getMinFeePerByte(options): Obtains the minimum fee per byte as per mempool configuration.getTransactionFromMempool(hash, options): Fetches a transaction from the mempool given its hash.
Example Usage
import { NimiqRPCClient } from '@blouflash/nimiq-rpc' const client = new NimiqRPCClient(); // Example usage for pushTransaction const transactionParams = { transaction: "serialized-transaction", withHighPriority: true }; client.mempool.pushTransaction(transactionParams).then((result) => { console.log("Transaction Pushed:", result); }).catch((error) => { console.error("Error:", error); }); // Example usage for mempoolContent client.mempool.mempoolContent({ includeTransactions: true }).then((result) => { console.log("Mempool Content:", result); }).catch((error) => { console.error("Error:", error); });
NetworkClient
The NetworkClient class provides methods to interact with the Nimiq Albatross Node's network.
Methods
getPeerId(options): The peer ID for our local peer.getPeerCount(options): Returns the number of peers.getPeerList(options): Returns a list with the IDs of all our peers.
Example Usage
import { NimiqRPCClient } from '@blouflash/nimiq-rpc' const client = new NimiqRPCClient(); // Example usage for getPeerId client.network.getPeerId().then((result) => { console.log("Peer ID:", result); }).catch((error) => { console.error("Error:", error); }); // Example usage for getPeerCount client.network.getPeerCount().then((result) => { console.log("Peer Count:", result); }).catch((error) => { console.error("Error:", error); });
PolicyClient
The PolicyClient class provides methods to interact with the Nimiq Albatross Node's policy.
Methods
getPolicyConstants(options): Gets a bundle of policy constants.getEpochAt(blockNumber, options): Returns the epoch number at a given block number (height).getEpochIndexAt(blockNumber, options): Returns the epoch index at a given block number.getBatchAt(blockNumber, options): Returns the batch number at a given block number (height).getBatchIndexAt(blockNumber, options): Returns the batch index at a given block number.getElectionBlockAfter(blockNumber, options): Gets the number (height) of the next election macro block after a given block number (height).getElectionBlockBefore(blockNumber, options): Gets the block number (height) of the preceding election macro block before a given block number (height).getLastElectionBlock(blockNumber, options): Gets the block number (height) of the last election macro block at a given block number (height).isElectionBlockAt(blockNumber, options): Gets a boolean expressing if the block at a given block number (height) is an election macro block.getMacroBlockAfter(blockNumber, options): Gets the block number (height) of the next macro block after a given block number (height).getMacroBlockBefore(blockNumber, options): Gets the block number (height) of the preceding macro block before a given block number (height).getLastMacroBlock(blockNumber, options): Gets the block number (height) of the last macro block at a given block number (height).isMacroBlockAt(blockNumber, options): Gets a boolean expressing if the block at a given block number (height) is a macro block.isMicroBlockAt(blockNumber, options): Gets the block number (height) of the next micro block after a given block number (height).getFirstBlockOfEpoch(epochIndex, options): Gets the block number (height) of the first block of the given epoch (which is always a micro block).getBlockAfterReportingWindow(blockNumber, options): Gets the block number of the first block of the given reporting window (which is always a micro block).getBlockAfterJail(blockNumber, options): Gets the block number of the first block of the given jail (which is always a micro block).getFirstBlockOfBatch(batchIndex, options): Gets the block number of the first block of the given batch (which is always a micro block).getElectionBlockOfEpoch(epochIndex, options): Gets the block number of the election macro block of the given epoch (which is always the last block).getMacroBlockOfBatch(batchIndex, options): Gets the block number of the macro block (checkpoint or election) of the given batch (which is always the last block).getFirstBatchOfEpoch(blockNumber, options): Gets a boolean expressing if the batch at a given block number (height) is the first batch of the epoch.getSupplyAt(params, options): Gets the supply at a given time (as Unix time) in Lunas (1 NIM = 100,000 Lunas).
Example Usage
import { NimiqRPCClient } from '@blouflash/nimiq-rpc' const client = new NimiqRPCClient(); // Example usage for getPolicyConstants client.policy.getPolicyConstants().then((result) => { console.log("Policy Constants:", result); }).catch((error) => { console.error("Error:", error); }); // Example usage for getEpochAt client.policy.getEpochAt(1000).then((result) => { console.log("Epoch at Block 1000:", result); }).catch((error) => { console.error("Error:", error); });
SerdeHelper
The SerdeHelper class provides methods to serialize and deserialize data.
Methods
serializeToHex(params, options): Serializes a byte array to a hexadecimal string.deserializeFromHex(params, options): Deserializes a hexadecimal string to a byte array.
Example Usage
import { NimiqRPCClient } from '@blouflash/nimiq-rpc' const client = new NimiqRPCClient(); // Example usage for serializeToHex const data = new Uint8Array([1, 2, 3, 4]); client.serdeHelper.serializeToHex({ data }).then((result) => { console.log("Serialized Hex:", result); }).catch((error) => { console.error("Error:", error); }); // Example usage for deserializeFromHex const hexString = "01020304"; client.serdeHelper.deserializeFromHex({ hexString }).then((result) => { console.log("Deserialized Data:", result); }).catch((error) => { console.error("Error:", error); });
ValidatorClient
The ValidatorClient class provides methods to interact with the Nimiq Albatross Node's validator.
Methods
getAddress(options): Returns our validator address.getSigningKey(options): Returns our validator signing key.getVotingKey(options): Returns our validator voting key.setAutomaticReactivation(params, options): Updates the configuration setting to automatically reactivate our validator.isElected(options): Returns whether our validator is elected.isSynced(options): Returns whether our validator is synced.
Example Usage
import { NimiqRPCClient } from '@blouflash/nimiq-rpc' const client = new NimiqRPCClient(); // Example usage for getAddress client.validator.getAddress().then((result) => { console.log("Validator Address:", result); }).catch((error) => { console.error("Error:", error); }); // Example usage for isElected client.validator.isElected().then((result) => { console.log("Is Elected:", result); }).catch((error) => { console.error("Error:", error); });
WalletClient
The WalletClient class provides methods to interact with the Nimiq Albatross Node's wallet.
Methods
importRawKey(params, options): Imports a raw key into the wallet.isAccountImported(address, options): Checks if an account is imported.listAccounts(options): Lists all imported accounts.lockAccount(address, options): Locks an account.createAccount(params, options): Creates a new account.unlockAccount(address, params, options): Unlocks an account.isAccountUnlocked(address, options): Checks if an account is unlocked.sign(params, options): Signs a message with an account's key.verifySignature(params, options): Verifies a signature.removeAccount(address, options): Removes an account.
Example Usage
import { NimiqRPCClient } from '@blouflash/nimiq-rpc' const client = new NimiqRPCClient(); // Example usage for importRawKey const keyParams = { keyData: "raw-key-data", passphrase: "passphrase" }; client.wallet.importRawKey(keyParams).then((result) => { console.log("Imported Key Address:", result); }).catch((error) => { console.error("Error:", error); }); // Example usage for createAccount const accountParams = { passphrase: "passphrase" }; client.wallet.createAccount(accountParams).then((result) => { console.log("Created Account:", result); }).catch((error) => { console.error("Error:", error); });
ZkpComponentClient
The ZkpComponentClient class provides methods to interact with the Nimiq Albatross Node's ZKP component.
Methods
getZkpState(options): Returns the latest header number, block number and proof.
Example Usage
import { NimiqRPCClient } from '@blouflash/nimiq-rpc' const client = new NimiqRPCClient(); // Example usage for getZkpState client.zkpComponent.getZkpState().then((result) => { console.log("ZKP State:", result); }).catch((error) => { console.error("Error:", error); });
License
Released under MIT by @blouflashdb.
Add Package
deno add jsr:@blouflash/nimiq-rpc
Import symbol
import * as nimiq_rpc from "@blouflash/nimiq-rpc";
Import directly with a jsr specifier
import * as nimiq_rpc from "jsr:@blouflash/nimiq-rpc";
Add Package
pnpm i jsr:@blouflash/nimiq-rpc
pnpm dlx jsr add @blouflash/nimiq-rpc
Import symbol
import * as nimiq_rpc from "@blouflash/nimiq-rpc";
Add Package
yarn add jsr:@blouflash/nimiq-rpc
yarn dlx jsr add @blouflash/nimiq-rpc
Import symbol
import * as nimiq_rpc from "@blouflash/nimiq-rpc";
Add Package
vlt install jsr:@blouflash/nimiq-rpc
Import symbol
import * as nimiq_rpc from "@blouflash/nimiq-rpc";
Add Package
npx jsr add @blouflash/nimiq-rpc
Import symbol
import * as nimiq_rpc from "@blouflash/nimiq-rpc";
Add Package
bunx jsr add @blouflash/nimiq-rpc
Import symbol
import * as nimiq_rpc from "@blouflash/nimiq-rpc";