# @bigmi/core 中文文档

规范地址：https://npmcn.com/package/%40bigmi/core/

版本：0\.9\.3
npm 元数据更新时间：2026-10-06T15:15:55.852Z
中文译文更新时间：2026-11-08T02:06:22.981Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40bigmi/core
原文对照：https://npmcn.com/package/%40bigmi/core/?lang=original
项目主页：https://github.com/lifinance/bigmi
源码仓库：https://github.com/lifinance/bigmi

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：1 MB，826 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：6 个
- peer 依赖：bs58 ^6\.0\.0
- 首次发布：2024-10-15T16:25:53.027Z
- 最新版本发布：2026-10-06T15:15:55.410Z
- 近 30 天下载量：240215（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：58（近 12 个月 19 个）

## 中文简介

Bitcoin apps 的 TypeScript 库.

## 安装

```sh
npm install @bigmi/core
```

也可以使用：`pnpm add @bigmi/core`、`yarn add @bigmi/core`、`bun add @bigmi/core`

## README

# 毕克米

**TypeScript库和Bitcoin应用软件的活性原始.**

[![license](https://img.shields.io/github/license/lifinance/bigmi)](https://npmcn.com/LICENSE.md) [![npm latest package](https://img.shields.io/npm/v/@bigmi/core/latest.svg)](https://www.npmjs.com/package/@bigmi/core) [![npm downloads](https://img.shields.io/npm/dm/@bigmi/core.svg)](https://www.npmjs.com/package/@bigmi/core)

**毕克米** (减: _比特币会成功_)是一个TypeScript库,为建设比特币应用程序提供活性原始. Bigmi通过提供:

-   引文摘自 [比特币 JSON-RPC API](https://developer.bitcoin.org/reference/rpc/)
-   用于互动的一等API [比特币](https://bitcoin.design/) 网络,包括发送交易和与 [替换-By-Fee(RBF)](https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki) 支助
-   流行比特币钱包扩展名的连接器
-   类型脚本支持

Bigmi提供与Bitcoin互动所需的工具.

### 软件包

Bigmi被模块化成数个包,每个包适合不同的用例:

-   [@ bigmi/ 核心](https://www.npmjs.com/package/@bigmi/core) - 节点或客户端应用的动作、运输、公用事业和其他核心原始产品.
-   [@ bigmi/ 反应](https://www.npmjs.com/package/@bigmi/react) - Hooks,提供商,以及其他用于反应应用的实用原始.
-   [@ bigmi/ 客户端](https://www.npmjs.com/package/@bigmi/client) - 钱包连接器和其他工具,用比特币应用程序连接钱包扩展.

## 安装

```sh
pnpm add @bigmi/react
```

```sh
pnpm add @bigmi/core
```

```sh
pnpm add @bigmi/client
```

## 开始

### 节点.js

如何用 Node.js 在后端设置 Bigmi :

```typescript
// main.ts
import {
  createClient,
  bitcoin,
  blockchair,
  sendUTXOTransaction,
  waitForTransaction,
  getBalance,
} from '@bigmi/core'

// Create a client for Bitcoin mainnet
const publicClient = createClient({
  chain: bitcoin,
  rpcSchema: rpcSchema<UTXOSchema>(),
  transport: fallback([
    blockchair(),
    ankr({apiKey: 'YOUR_ANKR_API_KEY'}),
    blockcypher(),
    mempool(),
  ]),
})

// Define the Bitcoin address you're working with
const address = 'BITCOIN_ADDRESS';

// Fetch the balance of the address
const balance = await getBalance(publicClient, { address });
console.log(`Balance for ${address}:`, balance);

// Fetch the current block count (height)
const blockCount = await getBlockCount(publicClient);
console.log('Current block count:', blockCount);

// Prepare the transaction hex (as a string)
const txHex = 'TRANSACTION_HEX';

// Send the transaction to the network
const txId = await sendUTXOTransaction(publicClient, { hex: txHex });
console.log('Transaction sent with ID:', txId);

// Wait for the transaction to be confirmed
const transaction = await waitForTransaction(publicClient, {
  txId,
  txHex,
  senderAddress: address,
  onReplaced: (response) => {
    console.log('Transaction replaced due to:', response.reason);
  },
});

console.log('Transaction confirmed:', transaction);
 
```

### 反应

简单的 bigmi 设置, 带有反应应用程序 :

```typescript
// App.tsx

import { bitcoin, http, createClient } from '@bigmi/core'
import { BigmiProvider, createConfig } from '@bigmi/react'
import { binance, xverse } from '@bigmi/client'

// Create bigmi config object
const config = createConfig({
    chains: [bitcoin],
    connectors: [binance(), xverse()],
    client: ({ chain }) => createClient({ chain, transport: http() }),
    ssr: true // If using Next.js or SSR
})


function App() {
  return (
    // Wrap your application with the necessary providers:
    <BigmiProvider config={config}>
      <YourApp />
    </BigmiProvider>
  )
}
```

```typescript
// YourApp.tsx

// Import the hooks from bigmi/react library
import { useAccount, useBalance, useConnect } from '@bigmi/react'

const { address, isConnected } = useAccount()
const { balance } = useBalance()
const { connect } = useConnect()

function YourApp() {
  return (
    <div>
      {isConnected ? (
        <p>Connected: {address}: {balance}BTC</p>
      ) : (
        <button onClick={connect}>Connect Wallet</button>
      )}
    </div>
  )
}
```

## 创建比特币交易

虽然Bigmi在块链数据检索和交易广播方面表现优异,但它并不包括交易创建功能. 对于生成有效的交易十六进制,我们建议使用 **比特币js-lib** (Bigmi已经依赖它).

### 基本交易创建

以下是如何使用比特币-lib与比特克米创建比特币交易:

```typescript
import * as bitcoin from 'bitcoinjs-lib';
import { 
  createClient, 
  getUTXOs, 
  sendUTXOTransaction, 
  waitForTransaction,
  getBlockStats,
  getBlockCount
} from '@bigmi/core';

async function createAndSendTransaction(
  client: Client,
  fromAddress: string,
  toAddress: string,
  amount: number, // in satoshis
  privateKey: Buffer
) {
  // 1. Get UTXOs for the address using Bigmi
  const utxos = await getUTXOs(client, { address: fromAddress });
  
  // 2. Create a new transaction using bitcoinjs-lib
  const psbt = new bitcoin.Psbt();
  
  // 3. Add inputs from UTXOs
  let inputValue = 0;
  const estimatedFee = 1000; // You should calculate this properly
  
  for (const utxo of utxos) {
    psbt.addInput({
      hash: utxo.txId,
      index: utxo.vout,
      witnessUtxo: {
        script: Buffer.from(utxo.scriptHex, 'hex'),
        value: utxo.value,
      },
    });
    inputValue += utxo.value;
    if (inputValue >= amount + estimatedFee) break;
  }
  
  // 4. Add recipient output
  psbt.addOutput({
    address: toAddress,
    value: amount,
  });
  
  // 5. Add change output if needed
  const change = inputValue - amount - estimatedFee;
  if (change > 546) { // Dust threshold
    psbt.addOutput({
      address: fromAddress,
      value: change,
    });
  }
  
  // 6. Sign the transaction
  const keyPair = bitcoin.ECPair.fromPrivateKey(privateKey);
  psbt.signAllInputs(keyPair);
  psbt.finalizeAllInputs();
  
  // 7. Get the raw transaction hex
  const rawTx = psbt.extractTransaction().toHex();
  
  // 8. Broadcast using Bigmi
  const txId = await sendUTXOTransaction(client, { hex: rawTx });
  
  // 9. Wait for confirmation using Bigmi
  const confirmedTx = await waitForTransaction(client, {
    txId,
    txHex: rawTx,
    senderAddress: fromAddress,
    confirmations: 1,
  });
  
  return confirmedTx;
}
```

### 收费估计

适当的费用估计对于确认交易至关重要:

```typescript
async function estimateFee(
  client: Client,
  numInputs: number,
  numOutputs: number
): Promise<number> {
  // Get recent block stats for fee estimation
  const blockHeight = await getBlockCount(client);
  const blockStats = await getBlockStats(client, {
    blockNumber: blockHeight,
    stats: ['avgfeerate']
  });
  
  // Estimate transaction size
  // P2WPKH: ~68 bytes per input, ~31 bytes per output, ~10 bytes overhead
  const estimatedSize = (numInputs * 68) + (numOutputs * 31) + 10;
  
  // Calculate fee (satoshis per byte * size)
  const feeRate = blockStats.avgfeerate || 1; // fallback to 1 sat/byte
  return Math.ceil(feeRate * estimatedSize);
}
```

### 处理错误的完整示例

```typescript
import * as bitcoin from 'bitcoinjs-lib';
import { createClient, getBalance, getUTXOs, sendUTXOTransaction, waitForTransaction } from '@bigmi/core';

async function safeSendBitcoin(
  client: Client,
  fromAddress: string,
  toAddress: string,
  amount: number,
  privateKey: Buffer
) {
  try {
    // Check balance
    const balance = await getBalance(client, { address: fromAddress });
    if (balance < amount + 1000) {
      throw new Error('Insufficient balance');
    }
    
    // Get UTXOs
    const utxos = await getUTXOs(client, {
      address: fromAddress,
      minValue: amount + 1000,
    });
    
    if (utxos.length === 0) {
      throw new Error('No UTXOs available');
    }
    
    // Create transaction
    const psbt = new bitcoin.Psbt();
    
    let totalInput = 0;
    for (const utxo of utxos) {
      psbt.addInput({
        hash: utxo.txId,
        index: utxo.vout,
        witnessUtxo: {
          script: Buffer.from(utxo.scriptHex, 'hex'),
          value: utxo.value,
        },
      });
      totalInput += utxo.value;
    }
    
    // Add outputs
    psbt.addOutput({
      address: toAddress,
      value: amount,
    });
    
    // Calculate fee and change
    const fee = await estimateFee(client, utxos.length, 2);
    const change = totalInput - amount - fee;
    
    if (change < 0) {
      throw new Error('Insufficient funds for fee');
    }
    
    if (change > 546) { // Dust threshold
      psbt.addOutput({
        address: fromAddress,
        value: change,
      });
    }
    
    // Sign and finalize
    const keyPair = bitcoin.ECPair.fromPrivateKey(privateKey);
    psbt.signAllInputs(keyPair);
    psbt.finalizeAllInputs();
    
    // Get transaction hex
    const txHex = psbt.extractTransaction().toHex();
    
    // Broadcast with Bigmi
    const txId = await sendUTXOTransaction(client, { hex: txHex });
    
    // Wait for confirmation
    const confirmed = await waitForTransaction(client, {
      txId,
      txHex,
      senderAddress: fromAddress,
      confirmations: 1,
    });
    
    return {
      txId,
      fee,
      confirmed,
    };
    
  } catch (error) {
    console.error('Transaction failed:', error);
    throw error;
  }
}
```

### 使用不同的地址类型

```typescript
import { getAddressInfo } from '@bigmi/core';

function createInputForUTXO(utxo: UTXO, addressInfo: AddressInfo) {
  const input: any = {
    hash: utxo.txId,
    index: utxo.vout,
  };
  
  switch (addressInfo.type) {
    case 'p2wpkh':
    case 'p2wsh':
      // Witness UTXOs for SegWit
      input.witnessUtxo = {
        script: Buffer.from(utxo.scriptHex, 'hex'),
        value: utxo.value,
      };
      break;
    case 'p2pkh':
    case 'p2sh':
      // Need full transaction for legacy
      input.nonWitnessUtxo = Buffer.from(fullTransactionHex, 'hex');
      break;
  }
  
  return input;
}
```

### RBF (替换- By- Fee) 支持

创建与 RBF 的交易, 以进行费用折叠 :

```typescript
const psbt = new bitcoin.Psbt();

// Add inputs with RBF sequence
for (const utxo of utxos) {
  psbt.addInput({
    hash: utxo.txId,
    index: utxo.vout,
    sequence: 0xfffffffd, // RBF enabled
    witnessUtxo: {
      script: Buffer.from(utxo.scriptHex, 'hex'),
      value: utxo.value,
    },
  });
}
```

### 替代图书馆

当我们推荐比特币,你也可以使用:

-   **@ scure/btc- signer** - 经审计的现代比特币交易库
-   **位点- lib** - 比特币的替代品
-   **贝币** - 全面执行比特币

### 安保最佳做法

1.  **永远不要暴露私钥** 在客户端代码中
2.  **使用硬件钱包** 用于生产用途
3.  **验证所有输入** 在创建交易前
4.  **测试网** 主网部署前
5.  **执行适当的错误处理** 所有边框

## 实例

-   [见Node.js实例](https://npmcn.com/package/%40bigmi/core/docs/core/examples.md)
-   [见反应示例](https://npmcn.com/package/%40bigmi/core/docs/react/examples.md)

你可以探索 [LI.FI 部件](https://github.com/lifinance/widget) 财务报告和审定财务报表 [L.FI 隐蔽](https://github.com/lifinance/sdk) 详细生产实例.

## 文档

-   [更多地了解配置](https://npmcn.com/package/%40bigmi/core/docs/core/config.md)
    
-   [见核心文档](https://npmcn.com/package/%40bigmi/core/docs/core/index.md)
    
-   [参见客户端 Docs](https://npmcn.com/package/%40bigmi/core/docs/client/index.md)
    
-   [见反应文件](https://npmcn.com/package/%40bigmi/core/docs/react/index.md)
    
-   [要为您的钱包添加支持吗 ?](https://npmcn.com/package/%40bigmi/core/docs/client/connectors.md)
    

## 支助

若遇到问题或有问题,请开题.

## 捐款

我们欢迎社区的贡献!

## 更改日志

这个 [更改日志](https://npmcn.com/CHANGELOG.md) 定期更新,以反映每个新版中的变化.

## 许可证

本项目的许可条件如下: [MIT 许可证](https://npmcn.com/LICENSE.md)。 。 。 .

## 承认

比克米受到 [微调](https://github.com/wevm) 堆栈。 我们赞赏开放源码社区对推动区块链发展的贡献.

## 常见问题

### @bigmi/core 是什么？

Bitcoin apps 的 TypeScript 库\.

### 如何安装 @bigmi/core？

在项目目录运行 npm install @bigmi/core，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：bs58（^6\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @bigmi/core 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @bigmi/core 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @bigmi/core 可以商用吗？

@bigmi/core 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @bigmi/core 的下载量有多少？

根据 npm 官方下载统计，@bigmi/core 在 2026/10/08 – 2026/11/06 这 30 天内被下载 240,215 次，日均约 8,007 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @bigmi/core 还在维护吗？

最新版本 0\.9\.3 发布于 2026/10/06（1 个月前）；至今共发布 58 个版本，其中过去 12 个月发布了 19 个；首次发布于 2024/10/16。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

