{"id":17436220,"url":"https://github.com/lifinance/bigmi","last_synced_at":"2025-10-07T11:39:15.967Z","repository":{"id":257827449,"uuid":"873099111","full_name":"lifinance/bigmi","owner":"lifinance","description":"TypeScript library focused on providing reactive primitives for Bitcoin apps.","archived":false,"fork":false,"pushed_at":"2025-02-17T17:33:18.000Z","size":663,"stargazers_count":50,"open_issues_count":5,"forks_count":4,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-29T04:04:12.040Z","etag":null,"topics":["bitcoin","bitcoinjs","btc","dapp","hooks","react","typescript","utxo","web3"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lifinance.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-10-15T15:43:58.000Z","updated_at":"2025-03-21T16:55:10.000Z","dependencies_parsed_at":"2024-12-13T15:48:18.087Z","dependency_job_id":"7d282fbf-015e-442d-919d-18e14fb35090","html_url":"https://github.com/lifinance/bigmi","commit_stats":{"total_commits":8,"total_committers":2,"mean_commits":4.0,"dds":0.375,"last_synced_commit":"35d56b0b9a5a878ccf62a712ce67537a6be0135d"},"previous_names":["lifinance/bigmi"],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lifinance%2Fbigmi","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lifinance%2Fbigmi/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lifinance%2Fbigmi/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lifinance%2Fbigmi/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lifinance","download_url":"https://codeload.github.com/lifinance/bigmi/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247289409,"owners_count":20914464,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bitcoin","bitcoinjs","btc","dapp","hooks","react","typescript","utxo","web3"],"created_at":"2024-10-17T10:06:57.374Z","updated_at":"2025-10-07T11:39:15.944Z","avatar_url":"https://github.com/lifinance.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n\n\u003ch1 align=\"center\"\u003eBigmi\u003c/h1\u003e\n\u003cp align=\"center\"\u003e\u003cstrong\u003eTypeScript library and reactive primitives for Bitcoin apps.\u003c/strong\u003e\u003c/p\u003e\n\n[![license](https://img.shields.io/github/license/lifinance/bigmi)](/LICENSE.md)\n[![npm latest package](https://img.shields.io/npm/v/@bigmi/core/latest.svg)](https://www.npmjs.com/package/@bigmi/core)\n[![npm downloads](https://img.shields.io/npm/dm/@bigmi/core.svg)](https://www.npmjs.com/package/@bigmi/core)\n\n\u003c/div\u003e\n\n**Bigmi** (short for *Bitcoin Is Gonna Make It*) is a TypeScript library that provides reactive primitives for building Bitcoin applications. Bigmi simplifies Bitcoin app development by offering:\n\n- Abstractions over the [Bitcoin JSON-RPC API](https://developer.bitcoin.org/reference/rpc/)\n- First-class APIs for interacting with the [Bitcoin](https://bitcoin.design/) network, including sending transactions and tracking with [Replace-By-Fee (RBF)](https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki) support\n- Connectors for popular Bitcoin wallet extensions\n- TypeScript support\n  \nWhether you're building a Node.js application or a client-side app, Bigmi provides the tools you need to interact with the Bitcoin.\n\n### Packages\n\nBigmi is modularized into several packages, each suited to different use cases:\n\n- [@bigmi/core](https://www.npmjs.com/package/@bigmi/core) - Actions, transports, utilities, and other core primitives for Node.js or client-side applications.\n- [@bigmi/react](https://www.npmjs.com/package/@bigmi/react) - Hooks, providers, and other useful primitives for React applications.\n- [@bigmi/client](https://www.npmjs.com/package/@bigmi/client) - Wallet connectors and other tools to connect wallet extensions with Bitcoin applications.\n\n## Installation\n\n```sh\npnpm add @bigmi/react\n```\n\n```sh\npnpm add @bigmi/core\n```\n\n```sh\npnpm add @bigmi/client\n```\n\n## Getting Started\n\n### Node.js\n\nHow to setup Bigmi on the backend with Node.js:\n\n```typescript\n// main.ts\nimport {\n  createClient,\n  bitcoin,\n  blockchair,\n  sendUTXOTransaction,\n  waitForTransaction,\n  getBalance,\n} from '@bigmi/core'\n\n// Create a client for Bitcoin mainnet\nconst publicClient = createClient({\n  chain: bitcoin,\n  rpcSchema: rpcSchema\u003cUTXOSchema\u003e(),\n  transport: fallback([\n    blockchair(),\n    ankr({apiKey: 'YOUR_ANKR_API_KEY'}),\n    blockcypher(),\n    mempool(),\n  ]),\n})\n\n// Define the Bitcoin address you're working with\nconst address = 'BITCOIN_ADDRESS';\n\n// Fetch the balance of the address\nconst balance = await getBalance(publicClient, { address });\nconsole.log(`Balance for ${address}:`, balance);\n\n// Fetch the current block count (height)\nconst blockCount = await getBlockCount(publicClient);\nconsole.log('Current block count:', blockCount);\n\n// Prepare the transaction hex (as a string)\nconst txHex = 'TRANSACTION_HEX';\n\n// Send the transaction to the network\nconst txId = await sendUTXOTransaction(publicClient, { hex: txHex });\nconsole.log('Transaction sent with ID:', txId);\n\n// Wait for the transaction to be confirmed\nconst transaction = await waitForTransaction(publicClient, {\n  txId,\n  txHex,\n  senderAddress: address,\n  onReplaced: (response) =\u003e {\n    console.log('Transaction replaced due to:', response.reason);\n  },\n});\n\nconsole.log('Transaction confirmed:', transaction);\n \n```\n\n### React\n\nSimple bigmi setup with a react app:\n\n```typescript\n// App.tsx\n\nimport { bitcoin, http, createClient } from '@bigmi/core'\nimport { BigmiProvider, createConfig } from '@bigmi/react'\nimport { binance, xverse, phantom } from '@bigmi/client'\n\n// Create bigmi config object\nconst config = createConfig({\n    chains: [bitcoin],\n    connectors: [binance(), xverse(), phantom()],\n    client: ({ chain }) =\u003e createClient({ chain, transport: http() }),\n    ssr: true // If using Next.js or SSR\n})\n\n\nfunction App() {\n  return (\n    // Wrap your application with the necessary providers:\n    \u003cBigmiProvider config={config}\u003e\n      \u003cYourApp /\u003e\n    \u003c/BigmiProvider\u003e\n  )\n}\n```\n\n```typescript\n// YourApp.tsx\n\n// Import the hooks from bigmi/react library\nimport { useAccount, useBalance, useConnect } from '@bigmi/react'\n\nconst { address, isConnected } = useAccount()\nconst { balance } = useBalance()\nconst { connect } = useConnect()\n\nfunction YourApp() {\n  return (\n    \u003cdiv\u003e\n      {isConnected ? (\n        \u003cp\u003eConnected: {address}: {balance}BTC\u003c/p\u003e\n      ) : (\n        \u003cbutton onClick={connect}\u003eConnect Wallet\u003c/button\u003e\n      )}\n    \u003c/div\u003e\n  )\n}\n```\n\n## Creating Bitcoin Transactions\n\nWhile Bigmi excels at blockchain data retrieval and transaction broadcasting, it doesn't include transaction creation functions. For generating valid transaction hex, we recommend using **bitcoinjs-lib** (which Bigmi already depends on).\n\n### Basic Transaction Creation\n\nHere's how to create a Bitcoin transaction using bitcoinjs-lib with Bigmi:\n\n```typescript\nimport * as bitcoin from 'bitcoinjs-lib';\nimport { \n  createClient, \n  getUTXOs, \n  sendUTXOTransaction, \n  waitForTransaction,\n  getBlockStats,\n  getBlockCount\n} from '@bigmi/core';\n\nasync function createAndSendTransaction(\n  client: Client,\n  fromAddress: string,\n  toAddress: string,\n  amount: number, // in satoshis\n  privateKey: Buffer\n) {\n  // 1. Get UTXOs for the address using Bigmi\n  const utxos = await getUTXOs(client, { address: fromAddress });\n  \n  // 2. Create a new transaction using bitcoinjs-lib\n  const psbt = new bitcoin.Psbt();\n  \n  // 3. Add inputs from UTXOs\n  let inputValue = 0;\n  const estimatedFee = 1000; // You should calculate this properly\n  \n  for (const utxo of utxos) {\n    psbt.addInput({\n      hash: utxo.txId,\n      index: utxo.vout,\n      witnessUtxo: {\n        script: Buffer.from(utxo.scriptHex, 'hex'),\n        value: utxo.value,\n      },\n    });\n    inputValue += utxo.value;\n    if (inputValue \u003e= amount + estimatedFee) break;\n  }\n  \n  // 4. Add recipient output\n  psbt.addOutput({\n    address: toAddress,\n    value: amount,\n  });\n  \n  // 5. Add change output if needed\n  const change = inputValue - amount - estimatedFee;\n  if (change \u003e 546) { // Dust threshold\n    psbt.addOutput({\n      address: fromAddress,\n      value: change,\n    });\n  }\n  \n  // 6. Sign the transaction\n  const keyPair = bitcoin.ECPair.fromPrivateKey(privateKey);\n  psbt.signAllInputs(keyPair);\n  psbt.finalizeAllInputs();\n  \n  // 7. Get the raw transaction hex\n  const rawTx = psbt.extractTransaction().toHex();\n  \n  // 8. Broadcast using Bigmi\n  const txId = await sendUTXOTransaction(client, { hex: rawTx });\n  \n  // 9. Wait for confirmation using Bigmi\n  const confirmedTx = await waitForTransaction(client, {\n    txId,\n    txHex: rawTx,\n    senderAddress: fromAddress,\n    confirmations: 1,\n  });\n  \n  return confirmedTx;\n}\n```\n\n### Fee Estimation\n\nProper fee estimation is crucial for transaction confirmation:\n\n```typescript\nasync function estimateFee(\n  client: Client,\n  numInputs: number,\n  numOutputs: number\n): Promise\u003cnumber\u003e {\n  // Get recent block stats for fee estimation\n  const blockHeight = await getBlockCount(client);\n  const blockStats = await getBlockStats(client, {\n    blockNumber: blockHeight,\n    stats: ['avgfeerate']\n  });\n  \n  // Estimate transaction size\n  // P2WPKH: ~68 bytes per input, ~31 bytes per output, ~10 bytes overhead\n  const estimatedSize = (numInputs * 68) + (numOutputs * 31) + 10;\n  \n  // Calculate fee (satoshis per byte * size)\n  const feeRate = blockStats.avgfeerate || 1; // fallback to 1 sat/byte\n  return Math.ceil(feeRate * estimatedSize);\n}\n```\n\n### Complete Example with Error Handling\n\n```typescript\nimport * as bitcoin from 'bitcoinjs-lib';\nimport { createClient, getBalance, getUTXOs, sendUTXOTransaction, waitForTransaction } from '@bigmi/core';\n\nasync function safeSendBitcoin(\n  client: Client,\n  fromAddress: string,\n  toAddress: string,\n  amount: number,\n  privateKey: Buffer\n) {\n  try {\n    // Check balance\n    const balance = await getBalance(client, { address: fromAddress });\n    if (balance \u003c amount + 1000) {\n      throw new Error('Insufficient balance');\n    }\n    \n    // Get UTXOs\n    const utxos = await getUTXOs(client, {\n      address: fromAddress,\n      minValue: amount + 1000,\n    });\n    \n    if (utxos.length === 0) {\n      throw new Error('No UTXOs available');\n    }\n    \n    // Create transaction\n    const psbt = new bitcoin.Psbt();\n    \n    let totalInput = 0;\n    for (const utxo of utxos) {\n      psbt.addInput({\n        hash: utxo.txId,\n        index: utxo.vout,\n        witnessUtxo: {\n          script: Buffer.from(utxo.scriptHex, 'hex'),\n          value: utxo.value,\n        },\n      });\n      totalInput += utxo.value;\n    }\n    \n    // Add outputs\n    psbt.addOutput({\n      address: toAddress,\n      value: amount,\n    });\n    \n    // Calculate fee and change\n    const fee = await estimateFee(client, utxos.length, 2);\n    const change = totalInput - amount - fee;\n    \n    if (change \u003c 0) {\n      throw new Error('Insufficient funds for fee');\n    }\n    \n    if (change \u003e 546) { // Dust threshold\n      psbt.addOutput({\n        address: fromAddress,\n        value: change,\n      });\n    }\n    \n    // Sign and finalize\n    const keyPair = bitcoin.ECPair.fromPrivateKey(privateKey);\n    psbt.signAllInputs(keyPair);\n    psbt.finalizeAllInputs();\n    \n    // Get transaction hex\n    const txHex = psbt.extractTransaction().toHex();\n    \n    // Broadcast with Bigmi\n    const txId = await sendUTXOTransaction(client, { hex: txHex });\n    \n    // Wait for confirmation\n    const confirmed = await waitForTransaction(client, {\n      txId,\n      txHex,\n      senderAddress: fromAddress,\n      confirmations: 1,\n    });\n    \n    return {\n      txId,\n      fee,\n      confirmed,\n    };\n    \n  } catch (error) {\n    console.error('Transaction failed:', error);\n    throw error;\n  }\n}\n```\n\n### Working with Different Address Types\n\n```typescript\nimport { getAddressInfo } from '@bigmi/core';\n\nfunction createInputForUTXO(utxo: UTXO, addressInfo: AddressInfo) {\n  const input: any = {\n    hash: utxo.txId,\n    index: utxo.vout,\n  };\n  \n  switch (addressInfo.type) {\n    case 'p2wpkh':\n    case 'p2wsh':\n      // Witness UTXOs for SegWit\n      input.witnessUtxo = {\n        script: Buffer.from(utxo.scriptHex, 'hex'),\n        value: utxo.value,\n      };\n      break;\n    case 'p2pkh':\n    case 'p2sh':\n      // Need full transaction for legacy\n      input.nonWitnessUtxo = Buffer.from(fullTransactionHex, 'hex');\n      break;\n  }\n  \n  return input;\n}\n```\n\n### RBF (Replace-By-Fee) Support\n\nCreate transactions with RBF enabled for fee bumping:\n\n```typescript\nconst psbt = new bitcoin.Psbt();\n\n// Add inputs with RBF sequence\nfor (const utxo of utxos) {\n  psbt.addInput({\n    hash: utxo.txId,\n    index: utxo.vout,\n    sequence: 0xfffffffd, // RBF enabled\n    witnessUtxo: {\n      script: Buffer.from(utxo.scriptHex, 'hex'),\n      value: utxo.value,\n    },\n  });\n}\n```\n\n### Alternative Libraries\n\nWhile we recommend bitcoinjs-lib, you can also use:\n- **@scure/btc-signer** - Modern, audited Bitcoin transaction library\n- **bitcore-lib** - Alternative to bitcoinjs-lib\n- **bcoin** - Full Bitcoin implementation\n\n### Security Best Practices\n\n1. **Never expose private keys** in client-side code\n2. **Use hardware wallets** for production applications\n3. **Validate all inputs** before creating transactions\n4. **Test on testnet** before mainnet deployment\n5. **Implement proper error handling** for all edge cases\n\n## Examples\n\n- [See Node.js examples](./docs/core/examples.md)\n- [See React examples](./docs/react/examples.md)\n\nYou can explore the [LI.FI Widget](https://github.com/lifinance/widget) and [LI.FI SDK](https://github.com/lifinance/sdk) for detailed production examples.\n\n## Documentation\n\n- [Learn more about Configuration](./docs/core/config.md)\n- [See Core Docs](./docs/core/index.md)\n- [See Client Docs](./docs/client/index.md)\n- [See React Docs](./docs/react/index.md)\n\n- [Want to add support for your wallet?](./docs/client/connectors.md)\n\n## Support\n\nIf you encounter any issues or have questions, please open an issue.\n\n## Contributing\n\nWe welcome contributions from the community!\n\n## Changelog\n\nThe [changelog](/CHANGELOG.md) is regularly updated to reflect what's changed in each new release.\n\n## License\n\nThis project is licensed under the terms of the [MIT License](/LICENSE.md).\n\n## Acknowledgments\n\nBigmi is inspired by the [wevm](https://github.com/wevm) stack. We appreciate the open-source community's contributions to advancing blockchain development.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flifinance%2Fbigmi","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flifinance%2Fbigmi","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flifinance%2Fbigmi/lists"}