@bigmi/core
Version:
TypeScript library for Bitcoin apps.
82 lines • 2.94 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUTXOs = void 0;
const request_js_1 = require("../../errors/request.js");
const utxo_js_1 = require("../../errors/utxo.js");
const url_js_1 = require("../../utils/url.js");
const utils_js_1 = require("./utils.js");
const blockcypherUTXOTransformer = (utxo) => ({
blockHeight: utxo.block_height,
isConfirmed: Boolean(utxo.confirmations),
confirmations: utxo.confirmations,
value: utxo.value,
vout: utxo.tx_output_n,
txId: utxo.tx_hash,
scriptHex: utxo.script,
});
const MAX_API_LIMIT = 2000;
const getUTXOs = async (client, { baseUrl, apiKey }, { address, minValue }) => {
async function* fetchUTXOs() {
let hasMore = true;
let beforeBlock;
while (hasMore) {
const apiUrl = (0, url_js_1.urlWithParams)(`${baseUrl}/addrs/${address}`, {
token: apiKey,
unspentOnly: 'true',
includeScript: 'true',
before: beforeBlock,
limit: MAX_API_LIMIT,
});
const response = (await client.request({
url: apiUrl,
fetchOptions: { method: 'GET' },
}));
if (response.error) {
throw new request_js_1.RpcRequestError({
url: apiUrl,
body: {
method: 'fetchUTXOs',
params: {
address,
minValue,
},
},
error: {
code: (0, utils_js_1.getRpcErrorCode)(response.error),
message: response.error,
},
});
}
if (minValue && minValue > response.final_balance) {
throw new utxo_js_1.InsufficientUTXOBalanceError({
minValue,
address,
balance: response.final_balance,
});
}
if (!response.txrefs || response.txrefs.length === 0) {
hasMore = false;
continue;
}
const { hasMore: apiHasMore } = response;
hasMore = Boolean(apiHasMore);
beforeBlock = response.txrefs[response.txrefs.length - 1].block_height;
yield response.txrefs;
}
}
const utxos = [];
let valueCount = 0;
for await (const batch of fetchUTXOs()) {
const utxoBatch = batch.map(blockcypherUTXOTransformer);
utxos.push(...utxoBatch);
if (minValue) {
valueCount += utxoBatch.reduce((sum, utxo) => sum + utxo.value, 0);
if (valueCount >= minValue) {
break;
}
}
}
return { result: utxos };
};
exports.getUTXOs = getUTXOs;
//# sourceMappingURL=getUTXOs.js.map