/* The balance example takes an address and calculates the balance currently stored in it. * * To do this we first list all the transactions that actually pay to the address * we want. These get reported on onAddressUsedInOutput() * But some of those may be spent already, so we check the UTXO (unspent output database) * which reports back to onUtxoLookup(). If the amount is still unspent we actually fetch * the transaction in order to find out what the amount is that is stored in the address. * * Notice that there are multiple ways of fetching the balance, this is probably not the * most correct one. */ if (process.argv.length <= 2) { console.log("Fetch balance of address\nUsage node balance.js [address]"); process.exit(); } const FloweeServices = require('../'); var Flowee = new FloweeServices(); function checkSaldo(address) { console.log("CheckSaldo " + address); // search request passes an object literal var promise = Flowee.search({ jobs: [ { // Get all transactions based on the following address value: address, type: Flowee.Job.LookupByAddress, } ], onAddressUsedInOutput: function(blockHeight, offsetInBlock, outIndex) { // The search for address returns all the outputs that pays into that address. // Each result results in one call to this function. // Fetch the UTXO status of this item. // Transactions that are already spent don't have to be fetched. this.addJob({ type: Flowee.Job.FetchUTXOUnspent, value: blockHeight, value2: offsetInBlock, value3: outIndex, }); }, onUtxoLookup: function(entry) { this.outputs++; if (entry.unspent) { this.unspent++; // Lets fetch that TX so we know how much money went into the address. this.addJob({ type: Flowee.Job.FetchTx, value: entry.blockHeight, value2: entry.offsetInBlock, outIndex: entry.outIndex, // this one is not needed for the job, but we reuse this in the onTxAdded method txFilter: [ // in this demo we only want the output address. // The advantage is that the hub won't send us anything else, severely pushing down bandwidth need Flowee.IncludeOutputAmounts ] }); } }, total: 0, outputs: 0, unspent: 0, onTxAdded: function(transaction) { // For the amount we only care about the output that pays us, and // in the onAddressUsedInOutput we stored the outIndex in the job. // so we can use that to only parse the output that pays the searched-for address. var jobId = transaction.jobId; var job = this.jobs[jobId]; this.total += transaction.outputs[job.outIndex].amount; } }); return promise; } Flowee.connect().then(async function() { try { for (arg in process.argv) { if (arg > 1) { // nodejs, skip first two args. let result = await checkSaldo(process.argv[arg]); console.log("Address balance fetched: " + process.argv[arg]); if (result.total != 0 || result.outputs != 0) { console.log(" UTXOs: " + result.unspent + "/" + result.outputs); console.log(" Balance: " + result.total / 100000000); } else { console.log(" empty"); } } } } catch (error) { console.log("Error detected: " + error); } process.exit(); })