0.1.1 • Published 12 months ago

@bithive/select-utxo v0.1.1

Weekly downloads
-
License
-
Repository
-
Last release
12 months ago

Select UTXO

A tool for UTXO selection

Install

pnpm add @bithive/select-utxo

Usage

import { selectUtxo } from '@bithive/select-utxo';
import * as bitcoin from 'bitcoinjs-lib';

// Testnet
const network = bitcoin.networks.testnet;

// Sender address and script
const senderAddress = 'tb1qf...devcu'; // Native Segwit address
const senderScript = bitcoin.address.toOutputScript(senderAddress, network);

// Sent value
const sentValue = 3500;

// Fee of sent BTC transaction
const sentFeeRate = 5;

// Receiver address and script
const receiverAddress = 'tb1qz...vgncd'; // Native Segwit address
const receiverScript = bitcoin.address.toOutputScript(receiverAddress, network);

// UTXOs owned by sender
const utxos = [
  {
    hash: Buffer.from(
      '0000000000000000000000000000000000000000000000000000000000000001',
      'hex',
    ),
    index: 1,
    witnessUtxo: { // Native Segwit UTXO
      value: 1234,
      script: senderScript,
    },
    value: 1234,
    script: senderScript,
  },
  {
    hash: Buffer.from(
      '0000000000000000000000000000000000000000000000000000000000000002',
      'hex',
    ),
    index: 2,
    value: 2345,
    witnessUtxo: { // Native Segwit UTXO
      value: 2345,
      script: senderScript,
    },
    script: senderScript,
  },
  {
    hash: Buffer.from(
      '0000000000000000000000000000000000000000000000000000000000000003',
      'hex',
    ),
    index: 3,
    witnessUtxo: { // Native Segwit UTXO
      value: 3456,
      script: senderScript,
    },
    value: 3456,
    script: senderScript,
  },
  {
    hash: Buffer.from(
      '0000000000000000000000000000000000000000000000000000000000000004',
      'hex',
    ),
    index: 4,
    witnessUtxo: { // Native Segwit UTXO
      value: 4567,
      script: senderScript,
    },
    value: 4567,
    script: senderScript,
  },
];

// TXOs to send BTC to receiver
const txos = [
  {
    value: sentValue,
    script: receiverScript,
  },
];

// Select UTXO
const result = selectUtxo({
  utxos,
  txos,
  // feeLimit: 1000, // Specify `feeLimit` here if needed
  feeRate: sentFeeRate,
  changeScript: senderScript,
  // strategy: 'Greedy', // Specify `strategy` here if needed
});

console.log(result);

// Build PSBT with selection result
const psbt = new bitcoin.Psbt({ network })
  .addInputs(result.utxos)
  .addOutputs(result.txos);

console.log(psbt);

Strategies

StrategyDescription
SequentialSelect UTXOs in the given order
GreedySelect UTXOs with the SMALLEST count. The relative order between UTXOs will be preserved
MaximalSelect UTXOs with the LARGEST count. The relative order between UTXOs will be preserved
0.1.1

12 months ago

0.1.0

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago

0.0.1-alpha.3

1 year ago

0.0.1-alpha.2

1 year ago

0.0.1-alpha.1

1 year ago