diff --git a/src/routes/v3/util.js b/src/routes/v3/util.js index 2f4b1a3..d035b5e 100644 --- a/src/routes/v3/util.js +++ b/src/routes/v3/util.js @@ -199,6 +199,7 @@ class UtilRoute { // Validate input const wif = req.body.wif const toAddr = req.body.toAddr + const balanceOnly = req.body.balanceOnly if (typeof wif !== "string" || wif.length !== 52) { res.status(400) @@ -207,9 +208,12 @@ class UtilRoute { }) } - if (!toAddr || toAddr === "") { - res.status(400) - return res.json({ error: "address can not be empty" }) + if (!balanceOnly) { + // Only throw error if balanceOnly is false or undefined. + if (!toAddr || toAddr === "") { + res.status(400) + return res.json({ error: "address can not be empty" }) + } } wlogger.debug(`Executing util/sweepWif with this address: `, toAddr) @@ -234,6 +238,12 @@ class UtilRoute { return res.json({ error: "No balance found at BCH address." }) } + // Exit if this is a balance-only call. + if (balanceOnly) { + res.status(200) + return res.json(totalBalance) + } + // Get all UTXOs help by the address. const utxos = await _this.blockbook.testableComponents.utxosFromBlockbook( fromAddr diff --git a/test/v3/util.js b/test/v3/util.js index 51d649d..da5a282 100644 --- a/test/v3/util.js +++ b/test/v3/util.js @@ -389,6 +389,34 @@ describe("#Util", () => { assert.equal(result, "test-txid") }) + it("should return balance if balance-only is true", async () => { + // Mock the RPC call for unit tests. + if (process.env.TEST === "unit") { + sandbox + .stub( + utilRouteInst.blockbook.testableComponents, + "balanceFromBlockbook" + ) + .resolves(mockData.mockBalance) + } + + // Mock sendRawTransaction() so that the hex does not actually get broadcast + // to the network. + sandbox + .stub(utilRouteInst.bchjs.RawTransactions, "sendRawTransaction") + .resolves("test-txid") + + req.body = { + wif: "L5GEFg1tETLWBugmhSo9Zc4ms968qVmfmTroDxsJ982AiudAQGyt", + balanceOnly: true + } + + const result = await utilRouteInst.sweepWif(req, res) + // console.log(`result: ${JSON.stringify(result, null, 2)}`) + + assert.isNumber(result) + }) + // Unit tests only if (process.env.TEST === "unit") { it("should generate transaction for valid BCH-only sweep", async () => {