Introduction
@electrum-cash/network is a lightweight JavaScript
library that lets you connect Electrum
servers.
It offers encrypted connections by default,
performs the expected protocol version negotiation and
automatically keeps your connection alive until your close it.
Installation
Install the library with NPM:
Usage
Usage with NodeJS
Before you can use the library you need to include it in your project.
const { ElectrumClient } = require('@electrum-cash/network');
Usage on Web
To use the library on the web, use the ESM import syntax and include the ElectrumTransport
import:
import { ElectrumClient, ElectrumTransport } from '@electrum-cash/network';
Connecting to a server
After you have imported the library you need to initialize and connect the client by configuring your application identifier and protocol version.
const electrumClient = new ElectrumClient('Electrum client example', '1.4.1', 'bch.imaginary.cash');
await electrumClient.connect();
To connect to an electrum server from a web browser, use the ElectrumTransport
import to use the WSS port
and scheme
:
const electrumClient = new ElectrumClient(
'Electrum client example', '1.4.1', 'bch.imaginary.cash',
ElectrumTransport.WSS.Port, ElectrumTransport.WSS.Scheme
);
Request information
Once your ElectrumClient
is connected and ready, you can call methods:
For a list of methods you can use, refer to the Electrum Cash documentation.
const transactionID = '4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251';
const transactionHex = await electrumClient.request('blockchain.transaction.get', transactionID);
console.log(transactionHex);
Subscribe to notifications.
Once your ElectrumClient
is connected and ready, you can set up subscriptions to get notifications on events:
For a list of methods you can subscribe to, refer to the Electrum Cash documentation.
const handleNotifications = function(data)
{
if(data.method === 'blockchain.headers.subscribe')
{
console.log(data);
}
}
electrumClient.on('notification', handleNotifications);
await electrumClient.subscribe('blockchain.headers.subscribe');
Shutting down
When you're done and don't want to be connected anymore you can disconnect the server:
await electrumClient.disconnect();
Documentation
For a complete list of methods and parameters, read the API documentation.
Support and communication
If you need help with how to use the library or just want to talk about electrum-cash, you can find us on Telegram and Discord.
Notes
The keep-alive functionality of this library only works when the protocol version is 1.2 or higher.