UNPKG

meta-contract-debug

Version:

Meta Contract SDK

94 lines (93 loc) 2.94 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SizeTransaction = void 0; function getVariableSize(n) { if (n < 0xfd) { return 1; } else if (n < 0x10000) { return 2 + 1; } else if (n < 0x100000000) { return 3 + 1; } else if (n < 0x10000000000000000) { return 4 + 1; } } var OutputType; (function (OutputType) { OutputType[OutputType["P2PKH"] = 0] = "P2PKH"; OutputType[OutputType["OP_RETURN"] = 1] = "OP_RETURN"; OutputType[OutputType["OTHER"] = 2] = "OTHER"; })(OutputType || (OutputType = {})); var InputType; (function (InputType) { InputType[InputType["P2PKH"] = 0] = "P2PKH"; InputType[InputType["OTHER"] = 1] = "OTHER"; })(InputType || (InputType = {})); class SizeTransaction { constructor(feeRate, dustCalculator) { this.inputs = []; this.outputs = []; this.feeRate = feeRate; this.dustCalculator = dustCalculator; } addInput(unlockingScriptSize, satothis) { this.inputs.push({ size: unlockingScriptSize, type: InputType.OTHER, satothis, }); } addP2PKHInput() { this.inputs.push({ size: 107, type: InputType.P2PKH }); } addOutput(lockingScriptSize) { this.outputs.push({ size: lockingScriptSize, type: OutputType.OTHER }); } addOpReturnOutput(lockingScriptSize) { this.outputs.push({ size: lockingScriptSize, type: OutputType.OP_RETURN }); } addP2PKHOutput() { this.outputs.push({ size: 25, type: OutputType.P2PKH }); } getSize() { let sizeSum = 0; sizeSum += 4; //nVersionSize sizeSum += 1; //vinNum(vins should not more than 255) this.inputs.forEach((input) => { sizeSum += 32; //txid sizeSum += 4; //outputINex sizeSum += getVariableSize(input.size); //unlocking script length sizeSum += input.size; //unlocking script sizeSum += 4; //nSequence }); sizeSum += 1; //voutNum this.outputs.forEach((output) => { sizeSum += 8; // satothis sizeSum += getVariableSize(output.size); //locking script length sizeSum += output.size; //locking script }); sizeSum += 4; //nLockTime return sizeSum; } getFee() { let fee = 0; fee += Math.ceil(this.getSize() * this.feeRate); this.inputs.forEach((input) => { if (input.type == InputType.OTHER) { fee -= input.satothis; } }); this.outputs.forEach((output) => { if (output.type == OutputType.OTHER) { fee += this.dustCalculator.getDustThreshold(output.size); } }); if (fee < 0) return 0; return Math.ceil(fee); } } exports.SizeTransaction = SizeTransaction;