From d2f701bb46f3e8a9111468c5a153b860918fbc1f Mon Sep 17 00:00:00 2001 From: Corey Phillips Date: Wed, 17 Aug 2022 21:10:55 -0400 Subject: [PATCH] fix(subscribe): Subscribe Address Fix Updated subscribe address method in index.js. Added onAddressReceive to client.js. --- helpers/clients.js | 5 +++++ helpers/index.js | 14 ++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/helpers/clients.js b/helpers/clients.js index 98e3fea..e1026ee 100644 --- a/helpers/clients.js +++ b/helpers/clients.js @@ -26,6 +26,11 @@ class Clients { bitcoinTestnet: false, bitcoinRegtest: false }; + this.onAddressReceive = { + bitcoin: undefined, + bitcoinTestnet: undefined, + bitcoinRegtest: undefined + } } updateNetwork(network) { diff --git a/helpers/index.js b/helpers/index.js index 1ebffda..d478380 100644 --- a/helpers/index.js +++ b/helpers/index.js @@ -320,13 +320,19 @@ const subscribeHeader = async ({ id = "subscribeHeader", network = "", onReceive } }; -const subscribeAddress = async ({ id = Math.random(), scriptHash = "", network = "bitcoin", onReceive = (data) => console.log(data) } = {}) => { +const subscribeAddress = async ({ id = Math.random(), scriptHash = "", network = "bitcoin", onReceive = undefined } = {}) => { try { if (clients.mainClient[network] === false) await connectToRandomPeer(network, clients.peers[network]); - if (clients.subscribedAddresses[network].length < 1) { - const res = await promiseTimeout(10000, clients.mainClient[network].subscribe.on('blockchain.scripthash.subscribe', (onReceive))); - if (res.error) return { ...res, id, method: "subscribeAddress" }; + + // Set onAddressReceive if wasn't previously. + if (onReceive && !clients.onAddressReceive[network]) { + clients.onAddressReceive[network] = onReceive; + const res = await promiseTimeout(10000, clients.mainClient[network].subscribe.on('blockchain.scripthash.subscribe', clients.onAddressReceive[network])); + if (res.error) { + return { ...res, id, method: "subscribeAddress" }; + } } + //Ensure this address is not already subscribed if (clients.subscribedAddresses[network].includes(scriptHash)) return { id, error: false, method: "subscribeAddress", data: "Already Subscribed." }; const response = await promiseTimeout(10000, clients.mainClient[network].blockchainScripthash_subscribe(scriptHash));