0.1.1 • Published 3 years ago

@xdefi/bitcoin v0.1.1

Weekly downloads
-
License
MIT
Repository
-
Last release
3 years ago

xDeFi bitcoin sdk

Getting started

npm install @xdefi/bitcoin

Initialize

import XDEFIBitcoin from "@xdefi/bitcoin";

let bitcoinClient;
if (window.xfi.bitcoin) {
  bitcoinClient = new XDEFIBitcoin(window.xfi.bitcoin);
}

Get accounts

bitcoinClient.getAccounts()
.then((accounts) => {
  // do something
})
.catch((error) => {
  // do something else
})

Get Unspent UTXOs (Get Balance)

bitcoinClient.getUnspentUTXOs("btcAddress")
.then((utxos) => {
  // do something
})
.catch((error) => {
  // do something else
})

Transfer

bitcoinClient.transfer(
  "btcAddressFrom", // sender
  "btcAddressTo", // recipient
  "1044", // amount in satoshis
  "100" // fee rate
  )
.then((txHash) => {
  // do something
})
.catch((error) => {
  // do something else
})

Sign Bitcoin Transaction

import * as Bitcoin from "bitcoinjs-lib";


const valueOut = 1;
const returnedUTXOS = await bitcoinClient.getUnspentUTXOs("btcAddress")
// generate Pbst for demo
const psbt = new Bitcoin.Psbt({ network: Bitcoin.networks.testnet }); // Network-specific
returnedUTXOS.forEach((UTXO) => {
  let formattedWitnessUtxo = {
    script: Buffer.from(UTXO.witnessUtxo.script),
    value: UTXO.witnessUtxo.value,
  };
  psbt.addInput({
    hash: UTXO.hash,
    index: UTXO.index,
    witnessUtxo: formattedWitnessUtxo,
  });
});
psbt.addOutput({ address: "otherAddress", value: valueOut }); // Add output {address, value}
const hexPbst = psbt.toHex();
console.log("pbsthex", hexPbst)
bitcoinClient.signTransaction("btcAddressFrom", hexPbst)
  .then((resultSignature) => {
    console.log(resultSignature);
    this.resultSignature = resultSignature;
    // TODO: broadcast
  })
  .catch(console.error);

NPM scripts

  • npm t: Run test suite
  • npm start: Run npm run build in watch mode
  • npm run test:watch: Run test suite in interactive watch mode
  • npm run test:prod: Run linting and generate coverage
  • npm run build: Generate bundles and typings, create docs
  • npm run lint: Lints code
  • npm run commit: Commit using conventional commit style (husky will tell you to use it if you haven't :wink:)

Excluding peerDependencies

On library development, one might want to set some peer dependencies, and thus remove those from the final bundle. You can see in Rollup docs how to do that.

Good news: the setup is here for you, you must only include the dependency name in external property within rollup.config.js. For example, if you want to exclude lodash, just write there external: ['lodash'].