@ordinalsbot/bitcoin-fee-estimator
Version:
A library for calculating Bitcoin transaction fees
47 lines (46 loc) • 2.24 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTxOverhead = getTxOverhead;
exports.estimateTxVBytesSimple = estimateTxVBytesSimple;
exports.estimateTxFee = estimateTxFee;
const types_1 = require("../types");
const varuint_bitcoin_1 = require("varuint-bitcoin");
const common_1 = require("../common");
function getTxOverhead(inputScripts, outputCount) {
const inputCount = inputScripts.length;
const hasWitnessInputs = inputScripts.some((type) => [
types_1.ScriptType.P2WPKH,
types_1.ScriptType.P2WSH,
types_1.ScriptType.P2TR,
types_1.ScriptType.P2SH_P2WPKH,
types_1.ScriptType.P2SH_P2WSH,
].includes(type));
const baseSize = 4 + // nVersion
(0, varuint_bitcoin_1.encodingLength)(inputCount) + // input count (varint)
(0, varuint_bitcoin_1.encodingLength)(outputCount) + // output count (varint)
4; // nLockTime
const segwitMarkerAndFlag = hasWitnessInputs ? 0.5 : 0;
return baseSize + segwitMarkerAndFlag;
}
function estimateTxVBytesSimple(inputScript = [types_1.ScriptType.P2TR], outputScript = [types_1.ScriptType.P2TR], opReturnData = null) {
const overhead = getTxOverhead(inputScript, outputScript.length);
let totalInput = 0;
for (const script of inputScript) {
totalInput += (0, common_1.estimateInputSize)(script);
}
const outputSize = outputScript.reduce((total, scriptType) => total + (0, common_1.getOutputSize)(scriptType), 0);
let opReturnSize = 0;
if (opReturnData !== null) {
const dataBuffer = typeof opReturnData === "string"
? Buffer.from(opReturnData, "utf8")
: opReturnData;
opReturnSize =
8 + 1 + (0, varuint_bitcoin_1.encodingLength)(dataBuffer.length) + dataBuffer.length; // (8)value + 1(OP_RETURN) + (N)length Bytes + (M)Data
}
const vBytes = Math.ceil(overhead + totalInput + outputSize + opReturnSize);
return vBytes;
}
function estimateTxFee(inputScript = [types_1.ScriptType.P2TR], outputScript = [types_1.ScriptType.P2TR], feeRate, opReturnData = null) {
const vBytes = estimateTxVBytesSimple(inputScript, outputScript, opReturnData);
return Math.ceil(vBytes * feeRate);
}