Catalog npm
Back to packageRELEASE DETAILS

1.0.8

npm

@0xbridge/bitcoin-vault

Bitcoin-psbt implementation TypeScript library supporting ESM and CJS.

bitcoinjscjsesmlibrarytypescript
Published10 Jan 2025
Direct dependencies13
Transitive dependenciesNot calculated

README

Current package documentation

@0xbridge/bitcoin-vault

@0xbridge/bitcoin-vault is a powerful TypeScript library for creating and signing Bitcoin PSBT transactions, working with Taproot scripts (such as multisig and timelock), and fetching UTXOs via public APIs. It is optimized for Testnet but can be configured for Mainnet or custom networks.


Features

  • PSBT Construction: Effortlessly build and sign Bitcoin transactions.
  • Taproot Utilities: Support for creating advanced Taproot scripts for multisig and timelock paths.
  • UTXO Fetching: Retrieve unspent outputs with automatic fallback using Blockstream or Mempool APIs.
  • Fee Estimation: Fetch recommended sat/vB fee rates from public endpoints.
  • OP_RETURN Metadata :Insert optional metadata into the transaction’s outputs using OP_RETURN scripts.
  • TypeScript Support: Comprehensive type definitions for safer and easier development.

Project Structure

.
├── src/                # Source code
│   ├── constants.ts    # API endpoints, OP_RETURN messages, and common constants
│   ├── transaction.ts  # Core class for creating and signing PSBTs
│   ├── taproot.ts      # Utilities for building Taproot scripts (multisig, timelock, etc.)
│   ├── utils.ts        # Helper functions like fetchFeeRate, fetchUtxos, and selectUtxos
│   ├── types.ts        # Type definitions for UTXOs, configurations, and more
│   └── index.ts        # Main entry point exporting core modules
│
├── package.json        # Project metadata and dependencies
├── tsconfig.*.json     # TypeScript configurations for different builds
├── README.md           # Documentation (this file)

Note: The dist/ folder is auto-generated after running the build script (npm run build).


Installation

Install the library using your preferred package manager:

npm install @0xbridge/bitcoin-vault

or

yarn add @0xbridge/bitcoin-vault

Usage

Below are examples demonstrating common use cases.

1. Create and Sign a PSBT

import { TransactionService } from '@0xbridge/bitcoin-vault';

// Variables (example values)
const userAddress = 'tb1qsomeTestnetAddr...';
const userWif = 'cYourPrivateKey...';
const lockingAddress = 'tb1qLockingAddress...';
const lockingAmount = 10_000; // Satoshis
const oxbridgeAmount = 5_000; // Satoshis

const txService = new TransactionService();

(async () => {
  try {
    // define metadata to embed in OP_RETURN
    const metadataParams = {
      receiverAddress: '0xSomeReceiverOnAnotherChain',
      lockedAmount: 1000,
      chainId: 5,            
      baseTokenAmount: 99999,
    };

    // Fee rate can be omitted to automatically fetch a recommended rate
    const feeRate = 5; // sat/vB

    const { txid, rawTxHex } = await txService.createAndSignTransaction(
      userAddress,
      userWif,
      lockingAddress,
      lockingAmount,
      oxbridgeAmount,
      metadataParams,
      feeRate
    );

    console.log('Transaction broadcast successfully!');
    console.log('TXID:', txid);
    console.log('Raw Transaction Hex:', rawTxHex);
  } catch (err) {
    console.error('Error creating or signing transaction:', err);
  }
})();

2. Create an Unsigned PSBT

import { TransactionService } from '@0xbridge/bitcoin-vault';

const userAddress = 'tb1qsomeTestnetAddr...';
const lockingAddress = 'tb1qLockingAddress...';
const lockingAmount = 10_000; // Satoshis
const oxbridgeAmount = 5_000; // Satoshis

(async () => {
  try {
    const txService = new TransactionService();
    const { psbtBase64 } = await txService.createUnsignedTransaction(
      userAddress,
      Buffer.from('...someUserPubKey...'), // The user's public key
      lockingAddress,
      lockingAmount,
      oxbridgeAmount,
      {
        receiverAddress: '0xSomeReceiverOnAnotherChain',
        lockedAmount: 1000,
        chainId: 5,
        baseTokenAmount: 99999,
      }
      // feeRate: 5 (Optional)
    );

    console.log('Unsigned PSBT (Base64):', psbtBase64);

    // Later, you or another party can sign the PSBT:
  } catch (err) {
    console.error('Error creating an unsigned transaction:', err);
  }
})();

3. Create a Taproot Script (Multisig + Timelock)

import {
  createTaprootScriptWithMultisigAndTimelock,
  createTaprootOutput,
  generateRandomKeyPair
} from '@0xbridge/bitcoin-vault';
import * as bitcoin from 'bitcoinjs-lib';

// Create dummy key pairs for the user and AVS (vault) signers
const userKeyPair = generateRandomKeyPair();
const avsKeyPair = generateRandomKeyPair();

// Choose a locktime (block height or timestamp)
const locktime = 500_000;

const tapVault = createTaprootScriptWithMultisigAndTimelock(
  userKeyPair.publicKey,
  avsKeyPair.publicKey,
  locktime
);

// Build a Taproot output (address) using the userKeyPair as the internal key
const taprootOutput = createTaprootOutput(
  userKeyPair.publicKey,
  tapVault,
  bitcoin.networks.testnet
);

console.log('Generated Taproot Address:', taprootOutput.taprootAddress);
console.log('Taproot Output Script (hex):', taprootOutput.output?.toString('hex'));

4. Fetch UTXOs and Fee Rates

import { fetchUtxos, fetchFeeRate, selectUtxos } from '@0xbridge/bitcoin-vault';

const apiConfig = {
  primary: 'https://blockstream.info/testnet/api',
  fallback: 'https://mempool.space/testnet/api',
};

(async () => {
  try {
    // Fetch unspent outputs for a given address
    const utxos = await fetchUtxos(apiConfig, 'tb1qsomeTestnetAddr...');
    console.log('Fetched UTXOs:', utxos);

    // Fetch recommended fee rate (sat/vB)
    const feeRate = await fetchFeeRate(apiConfig);
    console.log('Recommended fee rate:', feeRate);

    // Select UTXOs that sum up to at least `needed` satoshis
    const needed = 20_000; // Satoshis
    const { chosenUtxos, totalAmount } = selectUtxos(utxos, needed);
    console.log('Selected UTXOs:', chosenUtxos);
    console.log('Total Amount Found:', totalAmount);
  } catch (err) {
    console.error('Error fetching UTXOs or fee rate:', err);
  }
})();

5. Broadcasting Transactions

Once a PSBT is finalized (signed and finalizeAllInputs() called), you can broadcast with the built-in method:

import { TransactionService } from '@0xbridge/bitcoin-vault';

const txid = await txService.broadcastTransaction(txHex);

console.log('Broadcasted TxID:', txid);

Additional Information

  • TypeScript Support: Fully typed definitions for all library functions.
  • Networking: Configurable API endpoints for UTXO fetching and fee estimation.
  • Fallbacks: Automatically switches to a fallback API if the primary endpoint fails.

Downloads & popularity

Awaiting observations

No metric observations yet

Download counts and popularity will appear here as the collector receives them.

Declared dependencies 13

Native requirements
13 direct targetsNot calculated transitive count
Package / targetRequirementRelationship
axios
Environment
{
  "local_name": "axios",
  "alias": false,
  "peer_metadata": null
}
^1.7.9runtime
bip32
Environment
{
  "local_name": "bip32",
  "alias": false,
  "peer_metadata": null
}
^5.0.0-rc.0runtime
bip39
Environment
{
  "local_name": "bip39",
  "alias": false,
  "peer_metadata": null
}
^3.1.0runtime
ecpair
Environment
{
  "local_name": "ecpair",
  "alias": false,
  "peer_metadata": null
}
^3.0.0-rc.0runtime
bitcoinjs-lib
Environment
{
  "local_name": "bitcoinjs-lib",
  "alias": false,
  "peer_metadata": null
}
^6.1.7runtime
tiny-secp256k1
Environment
{
  "local_name": "tiny-secp256k1",
  "alias": false,
  "peer_metadata": null
}
^2.2.3runtime
@bitcoinerlab/secp256k1
Environment
{
  "local_name": "@bitcoinerlab/secp256k1",
  "alias": false,
  "peer_metadata": null
}
^1.2.0runtime
jest
Environment
{
  "local_name": "jest",
  "alias": false,
  "peer_metadata": null
}
^29.7.0development
rimraf
Environment
{
  "local_name": "rimraf",
  "alias": false,
  "peer_metadata": null
}
^6.0.1development
ts-jest
Environment
{
  "local_name": "ts-jest",
  "alias": false,
  "peer_metadata": null
}
^29.2.5development
ts-node
Environment
{
  "local_name": "ts-node",
  "alias": false,
  "peer_metadata": null
}
^10.9.2development
@types/jest
Environment
{
  "local_name": "@types/jest",
  "alias": false,
  "peer_metadata": null
}
^29.5.14development
@types/node
Environment
{
  "local_name": "@types/node",
  "alias": false,
  "peer_metadata": null
}
^22.10.2development

Distribution files

1 collected
Distribution 1

Source distribution

Source file
Checksums from source
{
  "shasum": "66297c93038b76931fb9b451acb5d08170e6316e",
  "tarball": "https://registry.npmjs.org/@0xbridge/bitcoin-vault/-/bitcoin-vault-1.0.8.tgz",
  "fileCount": 20,
  "integrity": "sha512-qjIgQvEl5jr+xNFV8aI+UlrgzZhVBr6wOOWgY2+hoj17ZtlebHWsRrQ+gBoNq6IgYyQCI0kk2ZWJs7+WljdPFA==",
  "signatures": [
    {
      "sig": "MEQCIDjhz/h5QHbJegRfXnYg14kfRQP4sgsk2PeuIMirjo0cAiBsiKL2rEefKAbWSdQcd2170s3D2C7SQokzM8I9DYQiQg==",
      "keyid": "SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"
    }
  ],
  "unpackedSize": 64026
}

Repository

PENDING
0xbridge/bitcoin-vault

Shared repository data · GitHub

License detected in repository
Not collected

Metadata history

Meaningful changes
Current collected state Current

Observed since 20 Oct, 22:44 UTC

No superseded metadata states collected. Unchanged observations do not create new revisions.

Record identity

package_version:9cb1b96d30599d1ff0f032f7c04bbcc1cfb108bcc4ce044554ba866a99732bcf

Other collected versions

1.1.420 Feb1.1.317 Jan1.1.217 Jan1.1.017 Jan1.0.913 Jan1.0.710 JanView all collected versions →