All files / lib/dlc TxBuilder.ts

92.52% Statements 99/107
67.74% Branches 21/31
100% Functions 26/26
94.95% Lines 94/99

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 3251x               1x           1x   1x     1x   1x   1x 1x       1x 1x       1x   10x 10x                                                                     10x 11x       10x       10x                           10x 10x     10x     10x       10x 10x 10x   10x   10x 10x       10x   10x 10x 11x 11x   11x             10x 11x     10x                     10x 12x     10x 12x     10x 12x     10x   7x         10x         10x 9x     10x 19x             10x 11x     10x 11x       10x 11x 11x 11x     10x 11x           11x             11x               10x   10x     10x 2x                 8x 1x             7x 7x 8x                   7x 4x             7x 3x             8x   7x 15x     7x         10x 12x   10x 1x 2x   1x               10x 7x   10x 1x 1x   1x                 2x 2x 3x   2x                  
import {
  LockTime,
  OutPoint,
  Script,
  Tx,
  TxBuilder,
  Value,
} from '@node-dlc/bitcoin';
import {
  DlcAcceptWithoutSigs,
  DlcOffer,
  FundingInput,
  MessageType,
} from '@node-dlc/messaging';
import Decimal from 'decimal.js';
 
import { DualFundingTxFinalizer } from './TxFinalizer';
 
// Dust limit matching C++ implementation (1000 satoshis)
export const DUST_LIMIT = BigInt(1000);
 
export class DlcTxBuilder {
  constructor(
    readonly dlcOffer: DlcOffer,
    readonly dlcAccept: DlcAcceptWithoutSigs,
  ) {}
 
  public buildFundingTransaction(): Tx {
    const txBuilder = new BatchDlcTxBuilder([this.dlcOffer], [this.dlcAccept]);
    return txBuilder.buildFundingTransaction();
  }
}
 
export class BatchDlcTxBuilder {
  constructor(
    readonly dlcOffers: DlcOffer[],
    readonly dlcAccepts: DlcAcceptWithoutSigs[],
  ) {}
 
  /**
   * Calculates the maximum collateral that can be used given a set of funding inputs
   * for exact-amount DLC scenarios (no change outputs).
   *
   * @param fundingInputs The inputs to be used for funding
   * @param feeRatePerVb Fee rate in satoshis per virtual byte
   * @param numContracts Number of DLC contracts being created (default: 1)
   * @returns Maximum collateral amount in satoshis
   *
   * @example
   * ```typescript
   * // Calculate max collateral for DLC splicing scenario
   * const dlcFundingInput = getDlcFundingInput(); // 970,332 sats
   * const additionalInput = getAdditionalInput(); // 100,000 sats
   * const inputs = [dlcFundingInput, additionalInput];
   *
   * const maxCollateral = BatchDlcTxBuilder.calculateMaxCollateral(
   *   inputs,
   *   BigInt(1), // 1 sat/vB fee rate
   *   1 // Single DLC contract
   * );
   *
   * // Use maxCollateral in DLC offer to ensure exact amount with no change
   * const dlcOffer = createDlcOffer(contractInfo, maxCollateral, ...);
   * ```
   */
  public static calculateMaxCollateral(
    fundingInputs: FundingInput[],
    feeRatePerVb: bigint,
    numContracts = 1,
  ): bigint {
    // Calculate total input value
    const totalInputValue = fundingInputs.reduce((total, input) => {
      return total + input.prevTx.outputs[input.prevTxVout].value.sats;
    }, BigInt(0));
 
    // Create a temporary finalizer to calculate fees
    const fakeSPK = Buffer.from(
      '0014663117d27e78eb432505180654e603acb30e8a4a',
      'hex',
    );
    const finalizer = new DualFundingTxFinalizer(
      fundingInputs,
      fakeSPK,
      fakeSPK,
      [], // No accepter inputs for single-funded scenario
      fakeSPK,
      fakeSPK,
      feeRatePerVb,
      numContracts,
    );
 
    // For exact-amount scenarios, we need to account for:
    // 1. Future fees (for CET/refund transactions)
    // 2. Funding transaction fees
    const futureFee = finalizer.offerFutureFee;
    const fundingFee = finalizer.offerFundingFee;
 
    // Maximum collateral is input value minus all fees
    const maxCollateral = totalInputValue - futureFee - fundingFee;
 
    // Ensure we don't return negative values
    return maxCollateral > BigInt(0) ? maxCollateral : BigInt(0);
  }
 
  public buildFundingTransaction(): Tx {
    const tx = new TxBuilder();
    tx.version = 2;
    tx.locktime = LockTime.zero();
 
    Iif (this.dlcOffers.length !== this.dlcAccepts.length)
      throw Error('DlcOffers and DlcAccepts must be the same length');
    Iif (this.dlcOffers.length === 0) throw Error('DlcOffers must not be empty');
    Iif (this.dlcAccepts.length === 0)
      throw Error('DlcAccepts must not be empty');
 
    // Ensure all DLC offers and accepts have the same funding inputs
    this.ensureSameFundingInputs();
 
    const multisigScripts: Script[] = [];
    for (let i = 0; i < this.dlcOffers.length; i++) {
      const offer = this.dlcOffers[i];
      const accept = this.dlcAccepts[i];
 
      multisigScripts.push(
        Buffer.compare(offer.fundingPubkey, accept.fundingPubkey) === -1
          ? Script.p2msLock(2, offer.fundingPubkey, accept.fundingPubkey)
          : Script.p2msLock(2, accept.fundingPubkey, offer.fundingPubkey),
      );
    }
 
    const witScripts = multisigScripts.map((multisigScript) =>
      Script.p2wshLock(multisigScript),
    );
 
    const finalizer = new DualFundingTxFinalizer(
      this.dlcOffers[0].fundingInputs,
      this.dlcOffers[0].payoutSpk,
      this.dlcOffers[0].changeSpk,
      this.dlcAccepts[0].fundingInputs,
      this.dlcAccepts[0].payoutSpk,
      this.dlcAccepts[0].changeSpk,
      this.dlcOffers[0].feeRatePerVb,
      this.dlcOffers.length,
    );
 
    this.dlcOffers[0].fundingInputs.forEach((input) => {
      Iif (input.type !== MessageType.FundingInput)
        throw new Error('Input is not a funding input');
    });
    const offerFundingInputs: FundingInput[] = this.dlcOffers[0].fundingInputs.map(
      (input) => input as FundingInput,
    );
 
    const offerTotalFunding = offerFundingInputs.reduce((total, input) => {
      return total + input.prevTx.outputs[input.prevTxVout].value.sats;
    }, BigInt(0));
 
    const acceptTotalFunding = this.dlcAccepts[0].fundingInputs.reduce(
      (total, input) => {
        return total + input.prevTx.outputs[input.prevTxVout].value.sats;
      },
      BigInt(0),
    );
 
    const fundingInputs: FundingInput[] = [
      ...offerFundingInputs,
      ...this.dlcAccepts[0].fundingInputs,
    ];
 
    fundingInputs.sort(
      (a, b) => Number(a.inputSerialId) - Number(b.inputSerialId),
    );
 
    fundingInputs.forEach((input) => {
      tx.addInput(
        OutPoint.fromString(
          `${input.prevTx.txId.toString()}:${input.prevTxVout}`,
        ),
      );
    });
 
    const offerInput = this.dlcOffers.reduce(
      (total, offer) => total + offer.offerCollateral,
      BigInt(0),
    );
    const acceptInput = this.dlcAccepts.reduce(
      (total, accept) => total + accept.acceptCollateral,
      BigInt(0),
    );
 
    const totalInputs = this.dlcOffers.map((offer, i) => {
      const offerInput = offer.offerCollateral;
      const acceptInput = this.dlcAccepts[i].acceptCollateral;
      return offerInput + acceptInput;
    });
 
    const fundingValues = totalInputs.map((totalInput) => {
      const offerFutureFeePerOffer = new Decimal(
        finalizer.offerFutureFee.toString(),
      )
        .div(this.dlcOffers.length)
        .ceil()
        .toNumber();
      const acceptFutureFeePerAccept = new Decimal(
        finalizer.acceptFutureFee.toString(),
      )
        .div(this.dlcAccepts.length)
        .ceil()
        .toNumber();
 
      return (
        totalInput +
        Value.fromSats(offerFutureFeePerOffer).sats +
        Value.fromSats(acceptFutureFeePerAccept).sats
      );
    });
 
    const offerChangeValue =
      offerTotalFunding - offerInput - finalizer.offerFees;
    const acceptChangeValue =
      acceptTotalFunding - acceptInput - finalizer.acceptFees;
 
    // Validate that we have sufficient funds
    if (offerChangeValue < BigInt(0)) {
      throw new Error(
        `Insufficient funds for offerer: need ${
          offerInput + finalizer.offerFees
        } sats, have ${offerTotalFunding} sats`,
      );
    }
 
    // In single-funded DLCs, if accepter has no inputs, they don't pay fees
    // This matches the C++ layer behavior where parties with no inputs have zero fees
    if (acceptChangeValue < BigInt(0) && acceptTotalFunding > BigInt(0)) {
      throw new Error(
        `Insufficient funds for accepter: need ${
          acceptInput + finalizer.acceptFees
        } sats, have ${acceptTotalFunding} sats`,
      );
    }
 
    const outputs: Output[] = [];
    witScripts.forEach((witScript, i) => {
      outputs.push({
        value: Value.fromSats(Number(fundingValues[i])),
        script: witScript,
        serialId: this.dlcOffers[i].fundOutputSerialId,
      });
    });
 
    // Dust filtering: Only create change outputs if they're above dust threshold
    // This matches the C++ implementation and enables "exact amount" DLC scenarios
    // where all input value goes into the DLC funding output with no change
    if (offerChangeValue >= DUST_LIMIT) {
      outputs.push({
        value: Value.fromSats(Number(offerChangeValue)),
        script: Script.p2wpkhLock(this.dlcOffers[0].changeSpk.slice(2)),
        serialId: this.dlcOffers[0].changeSerialId,
      });
    }
 
    if (acceptChangeValue >= DUST_LIMIT) {
      outputs.push({
        value: Value.fromSats(Number(acceptChangeValue)),
        script: Script.p2wpkhLock(this.dlcAccepts[0].changeSpk.slice(2)),
        serialId: this.dlcAccepts[0].changeSerialId,
      });
    }
 
    outputs.sort((a, b) => Number(a.serialId) - Number(b.serialId));
 
    outputs.forEach((output) => {
      tx.addOutput(output.value, output.script);
    });
 
    return tx.toTx();
  }
 
  private ensureSameFundingInputs(): void {
    // Check for offers
    const referenceOfferInputs = this.dlcOffers[0].fundingInputs.map((input) =>
      input.serialize().toString('hex'),
    );
    for (let i = 1; i < this.dlcOffers.length; i++) {
      const currentInputs = this.dlcOffers[i].fundingInputs.map((input) =>
        input.serialize().toString('hex'),
      );
      Iif (!this.arraysEqual(referenceOfferInputs, currentInputs)) {
        throw new Error(
          `Funding inputs for offer ${i} do not match the first offer's funding inputs.`,
        );
      }
    }
 
    // Check for accepts
    const referenceAcceptInputs = this.dlcAccepts[0].fundingInputs.map(
      (input) => input.serialize().toString('hex'),
    );
    for (let i = 1; i < this.dlcAccepts.length; i++) {
      const currentInputs = this.dlcAccepts[i].fundingInputs.map((input) =>
        input.serialize().toString('hex'),
      );
      Iif (!this.arraysEqual(referenceAcceptInputs, currentInputs)) {
        throw new Error(
          `Funding inputs for accept ${i} do not match the first accept's funding inputs.`,
        );
      }
    }
  }
 
  private arraysEqual(arr1: string[], arr2: string[]): boolean {
    Iif (arr1.length !== arr2.length) return false;
    for (let i = 0; i < arr1.length; i++) {
      Iif (arr1[i] !== arr2[i]) return false;
    }
    return true;
  }
}
 
interface Output {
  value: Value;
  script: Script;
  serialId: bigint;
}