@kcoin/kaspa-web3.js
v1.1.4
Published
[](https://github.com/kaspa-kcoin/kaspa-web3.js/actions/workflows/test.yml) [;
await client.connect();Using a Resolver
import { RpcClient, NetworkId, Resolver } from '@kcoin/kaspa-web3.js';
const client = new RpcClient({
resolver: new Resolver(),
// resolver: Resolver.createWithEndpoints([your-endpoints]),
// Resolver will test the endpoints and select the fastest one.
networkId: NetworkId.Mainnet
});
await client.connect();Sending KAS
To send KAS, create and submit a transaction using the Generator:
import { RpcClient, Generator, NetworkId, kaspaToSompi, Fees, SendKasParams } from '@kcoin/kaspa-web3.js';
// Initialize the RpcClient
const rpcClient = new RpcClient({
endpoint: 'ws://localhost:18210' // Replace with your actual endpoint
});
// Define transaction parameters
const SENDER_ADDR = 'kaspatest:qzzzvv57j68mcv3rsd2reshhtv4rcw4xc8snhenp2k4wu4l30jfjxlgfr8qcz';
const RECEIVER_ADDR = 'kaspatest:qrjcg7hsgjapumpn8egyu6544qzdqs2lssas4nfwewl55lnenr5pyzd7cmyx6';
const networkId = NetworkId.Testnet10;
const amount = kaspaToSompi(10); // Convert KAS to Sompi
const priorityFees = new Fees(kaspaToSompi(0.02)); // Optional priority fee
const privateKey = 'your-private-key-hex'; // WARNING: Never hardcode private keys in production code
// Perform the transaction
async function sendKAS() {
try {
await rpcClient.connect(); // Ensure the RpcClient is connected
const utxos = await rpcClient.getUtxosByAddress(SENDER_ADDR);
const sendKasParams = new SendKasParams(SENDER_ADDR, amount, RECEIVER_ADDR, networkId, priorityFees);
const generator = new Generator(sendKasParams.toGeneratorSettings(utxos));
while (true) {
const transaction = generator.generateTransaction();
if (!transaction) break;
transaction.sign([privateKey]);
const response = await rpcClient.submitTransaction({
transaction: transaction.toSubmittableJsonTx(),
allowOrphan: false
});
}
const finalTransactionId = generator.summary().finalTransactionId!.toHex();
console.log('Final Transaction ID:', finalTransactionId);
} catch (error) {
console.error('Transaction failed:', error);
}
}
sendKAS();KRC-20 Token Operations
This section provides examples of how to deploy, mint, and transfer KRC-20 tokens using the Krc20RpcClient class.
Prerequisites
- Ensure you have a valid private key for the operations.
- Set up your environment with the necessary dependencies and configurations.
Example Scripts
Deploy a KRC-20 Token: deploy.ts
- Demonstrates how to deploy a new KRC-20 token with specified parameters.
Mint KRC-20 Tokens: mint.ts
- Shows how to mint additional tokens to a specified address.
Transfer KRC-20 Tokens: transfer.ts
- Illustrates transferring tokens from one address to another.
Running the Scripts
To run any of the scripts, use the following command:
bun run examples/krc20/<script-name>.tsReplace <script-name> with the name of the script you want to execute (e.g., deploy, mint, or transfer).
Event Subscriptions
You can subscribe to various events using the RpcClient.
Subscribe to Block Added Notifications
await client.subscribeBlockAdded();
await client.addEventListener(RpcEventType.BlockAdded, (eventData) => {
console.log('Block added:', eventData);
});Unsubscribe from Block Added Notifications
await client.unsubscribeBlockAdded();Error Handling
The RpcClient provides error handling for RPC requests. Ensure to catch errors when making requests:
try {
const response = await client.getCurrentNetwork();
console.log(response);
} catch (error) {
console.error('Error fetching network info:', error);
}FAQ
Kaspa Web3.js implements transaction construction, signing, and related hashing. It includes the following components:
Keypair: Represents a pair of public and private keys used for cryptographic operations.TxScriptBuilder: A utility for constructing transaction scripts.RpcClient: A client for interacting with the Kaspa blockchain via WebSocket JSON-RPC requests.Generator: A class for generating transactions, including inputs, outputs, and fees.Resolver: A utility for resolving network endpoints and selecting the fastest one.Krc20RpcClient: A specialized RPC client for interacting with KRC-20 tokens on the Kaspa blockchain.
RpcClient only supports WebSocket with JSON serialization. It includes the full implementation of RPC methods and subscribe-related interfaces.
- GRPC does not support duplex communication in browsers.
- Borsh serialization encoded WebSocket can become incompatible with minor changes in node data structures, making it difficult to maintain.
- JSON serialization provides better compatibility, so kaspa-web3.js exclusively uses JSON WebSocket.
Dependencies
@noble/curves: ^1.7.0@noble/hashes: ^1.6.1@noble/secp256k1: ^2.2.1buffer: ^6.0.3toml: ^3.0.0websocket-heartbeat-js: ^1.1.3
Contributing
Contributions are welcome! Please open an issue or submit a pull request for any improvements or bug fixes.
License
This project is licensed under the MIT License.
Donations
If you find this project useful and would like to support its development, you can send KAS donations to the following address:
kaspa:qzyrvjcaama3ecf8reg7evxxz0pl80nx9fwas5rcw5udqj4x2jyf26jufex4z