read.cash Log in
@JonathanSilverblood edited

electrum-cash: working with balances

Introduction Electrum-cash is a javascript/typescript library for communicating with electrum servers. https://www.npmjs.com/package/electrum-cash/library This example demonstrates how to get the balance of an address and how to get notified of changes to the balance of an address, using `v1.4.3` of the electrum protocol. *To keep the example simple and clear, the code to set up and close a connection is omitted.* Fetch current balance To get the current balance for an address, send a `blockchain.address.get_balance` **request** to the server with the **address** as the first parameter. // The address we want to get balance for. const address = 'qr4aadjrpu73d2wxwkxkcrt6gqxgu6a7usxfm96fst'; // Request the balance from the server. const balance = await electrum.request('blockchain.address.get_balance', address); // Print out the current balance, in satoshis. console.log(`Balance for '${address}' is ${balance.confirmed} satoshis confirmed, and ${balance.unconfirmed} satoshis unconfirmed.`); *Example output for an existing wallet with a balance:* Balance for 'qr4aadjrpu73d2wxwkxkcrt6gqxgu6a7usxfm96fst' is 1165925 satoshis confirmed, and 0 satoshis unconfirmed. Subscribe to balance changes To subscribe to balance update notifications, send a `blockchain.address.subscribe` **subscription** to the server with the **address** as the first parameter, then request the updated balance any time the status of the address changes. // The address we want to get balance updates for. const address = 'qr4aadjrpu73d2wxwkxkcrt6gqxgu6a7usxfm96fst'; // Create a callback handler for balance updates. const balanceUpdateHandler = async function(adress) { // Request the balance from the server. const balance = await electrum.request('blockchain.address.get_balance', address); // Print out the updated balance, in satoshis. console.log(`Balance for '${address}' is ${balance.confirmed} satoshis confirmed, and ${balance.unconfirmed} satoshis unconfirmed.`); } // Subscribe to update notifications to the address status from the server. const balance = await electrum.subscribe(balanceUpdateHandler.bind(this, address), 'blockchain.address.subscribe', address); *Example output when sending out all funds in the wallet:* Balance for 'qr4aadjrpu73d2wxwkxkcrt6gqxgu6a7usxfm96fst' is 1165925 satoshis confirmed, and 0 satoshis unconfirmed. Balance for 'qr4aadjrpu73d2wxwkxkcrt6gqxgu6a7usxfm96fst' is 1165925 satoshis confirmed, and -1165925 satoshis unconfirmed. Balance for 'qr4aadjrpu73d2wxwkxkcrt6gqxgu6a7usxfm96fst' is 0 satoshis confirmed, and 0 satoshis unconfirmed.

$3.17

17 comments

Log in to join in Reading is open to everyone. Replying needs an account.