electrumCoin.js

var globalVar = require("global");
var libraries = globalVar.libraries;
var Electrum = require("./Electrum.js");
/** @classdesc A class that provides some basic methods for electrum-compatible coins.  E.g. new xxx.BCH(privateKey);
* @class 
* @extends Coin
* @hideconstructor 
*/

class ElectrumCoin extends Coin {
// eventually, would like to error handle inside these to automatically pick a new electrum server
	// MORE ENDPOINTS: https://github.com/you21979/node-electrum-client/blob/master/lib/electrum_client.js
	// -->> seems like there's a typo in blockchainBlock_headers call
	constructor(coin,config){
		super.constructor(coin,config);
		this.coin=coin;
		this.desc = this.coin=="btc" ? "bitcoin" : (this.coin=="bch" ? "bitcoin-cash" : (()=>{throw 'Expected btc or bch for electrum coin'})());
		if(this.coin=="btc")this.electrum=new Electrum(config.electrumConfig || {"coin":"btc","defaultServer":{'elec.luggs.co':{ 's':'443'}}}); 
		else if(this.coin=="bch")this.electrum=new Electrum(config.electrumConfig || {"coin":"bch"})
	}
	/** 
	* Get get all unspent coin UTXOs for this coin (non-SLP). Only for UTXO-like coins.
	* @param {string} Address A cryptocurrency address
	*/
	async getUTXOs(address){return await this.electrum.methods.blockchainAddress_listunspent(address);}

	async _coin(){
		// would connect to websockets here
		this.electrum.connect();
	}
	async _getBalance(address){return await this.electrum.methods.blockchainAddress_getBalance(address);};
	
	async _getTransaction(hash){return await this.electrum.methods.blockchainTransaction_get(hash,false);}
	
	async _getTransactionHistory(address){ return await this.electrum.methods.blockchainAddress_getHistory(address);}

	async _sendTransaction(hash){
		return new Promise(function(resolve,reject){
			this.electrum.methods.blockchainTransaction_broadcast(hash).then(function(value){
				console.log("here is value",value);
				resolve(value);

			}).catch(function(err){		
				console.log("Here is err",err);
				reject(err);
			});
		});
	}

	async _getFee (numBlocks){ return await this.electrum.methods.blockchainEstimateFee(numBlocks || 6)};

	async _getLatestBlock(){
		// really weird that electrum doesn't let you do this in an api call
		var url = "https://api.blockchair.com/"+this.desc+"/blocks?limit=10";
		return new Promise((resolve, reject)=>{
			libraries.request.get(url,function(err,res,body){
				console.log(err,body);
				try{body=JSON.parse(body)}catch(err){};
		
				var blocks = body.data;
				var key ="6";
				var block = {"hash":blocks[key].hash,"number":blocks[key].number};
				resolve(block);
			});
		});
	}

}
module.exports = ElectrumCoin;