Bigmi 最佳实践指南
本指南介绍使用 Bigmi 构建健壮、高性能且安全的 Bitcoin 应用的最佳实践,这些实践基于实际代码库中的模式。客户端配置
带回退(Fallback)的传输配置
始终使用多个提供商以提高可靠性:import { createClient, fallback, blockchair, ankr, mempool, bitcoin } from '@bigmi/core'
const client = createClient({
chain: bitcoin,
transport: fallback([
blockchair(),
ankr({ apiKey: 'YOUR_API_KEY' }),
mempool(),
], {
rank: true, // Auto-optimize provider selection
retryCount: 3, // Retry failed requests
retryDelay: 1000, // Delay between retries
})
})
超时与重试策略
为每个操作配置合适的超时:const client = createClient({
transport: http('https://api.provider.com', {
timeout: 30_000, // 30 seconds for most operations
retryCount: 3,
retryDelay: 1000 // 1 second delay between retries
})
})
const client = createClient({
chain: bitcoin,
transport: fallback([
blockchair({
timeout: 10_000, // 10 seconds for fast provider
retryCount: 2,
}),
ankr({
apiKey: 'YOUR_API_KEY',
timeout: 20_000, // 20 seconds for reliable provider
retryCount: 3,
}),
mempool({
timeout: 30_000, // 30 seconds for slower provider
retryCount: 1,
}),
], {
rank: true,
retryCount: 3,
retryDelay: 1000,
})
})
缓存策略
配置合适的缓存时间:const client = createClient({
cacheTime: 4_000, // Cache responses for 4 seconds
pollingInterval: 4_000, // Poll for updates every 4 seconds
})
使用 withRetry 的重试逻辑
使用 Bigmi 内置的重试工具:import { withRetry, TimeoutError } from '@bigmi/core'
const result = await withRetry(
() => riskyOperation(),
{
delay: 1000, // 1 second delay between retries
retryCount: 3,
shouldRetry: ({ error }) => {
// Don't retry user errors or permanent failures
return !(error instanceof UserRejectedRequestError)
}
}
)
交易管理
UTXO 选择最佳实践
高效地过滤和选择 UTXO:import { getUTXOs, getBalance } from '@bigmi/core'
// Check balance first
const balance = await getBalance(client, { address })
if (balance < requiredAmount + estimatedFee) {
throw new Error('Insufficient balance')
}
// Get UTXOs with filtering
const utxos = await getUTXOs(client, {
address,
minValue: requiredAmount + estimatedFee
})
// Select optimal UTXOs (largest-first strategy)
const selectedUTXOs = utxos
.sort((a, b) => b.value - a.value)
.reduce((acc, utxo) => {
if (acc.totalValue < requiredAmount + estimatedFee) {
acc.utxos.push(utxo)
acc.totalValue += utxo.value
}
return acc
}, { utxos: [], totalValue: 0 })
费用估算策略
使用来自多个来源的动态费用估算:import { getBlockStats, getBlockCount } from '@bigmi/core'
async function estimateFee(client, priority = 'standard') {
const blockHeight = await getBlockCount(client)
const blockStats = await getBlockStats(client, {
blockNumber: blockHeight,
stats: ['avgfeerate', 'minfeerate']
})
const feeRates = {
economy: blockStats.minfeerate || 1,
standard: blockStats.avgfeerate || 5,
priority: (blockStats.avgfeerate || 5) * 2
}
return feeRates[priority]
}
RBF(Replace-By-Fee)实现
始终启用 RBF 并处理替换:import { waitForTransaction, sendUTXOTransaction } from '@bigmi/core'
// Enable RBF when creating transaction
psbt.setInputSequence(0, 0xfffffffd) // RBF-enabled
// Monitor for replacements
const receipt = await waitForTransaction(client, {
txId,
txHex,
confirmations: 1,
timeout: 300_000, // 5 minutes
onReplaced: ({ reason, transaction }) => {
console.log(`Transaction replaced: ${reason}`)
// Update UI with new transaction
updateTransactionStatus(transaction)
}
})
地址校验
在使用前始终校验地址:import { getAddressChainId } from '@bigmi/core'
function validateAddress(address, expectedChainId = ChainId.BITCOIN_MAINNET) {
try {
const addressChainId = getAddressChainId(address)
if (addressChainId !== expectedChainId) {
throw new Error(`Address is for ${addressChainId}, expected ${expectedChainId}`)
}
return true
} catch (error) {
throw new Error(`Invalid Bitcoin address: ${error.message}`)
}
}
钱包集成
多钱包支持
配置多个连接器以获得更广泛的兼容性:import { createConfig } from '@bigmi/client'
import { bitcoin, http } from '@bigmi/core'
import { phantom, xverse, unisat, binance } from '@bigmi/client'
const config = createConfig({
chains: [bitcoin],
connectors: [
phantom(),
xverse(),
unisat(),
binance({ shimDisconnect: true }), // Handle disconnect issues
],
transports: {
[bitcoin.id]: http('https://api.provider.com')
}
})
连接错误处理
优雅地处理钱包特定的错误:import { useConnect } from '@bigmi/react'
import {
ProviderNotFoundError,
UserRejectedRequestError,
} from '@bigmi/client'
function WalletConnector() {
const { connect, connectors, isPending, error } = useConnect()
const handleConnect = async (connector) => {
try {
await connect({ connector })
} catch (error) {
if (error instanceof ProviderNotFoundError) {
alert(`Please install ${connector.name} wallet extension`)
} else if (error instanceof UserRejectedRequestError) {
console.log('User rejected connection')
} else {
console.error('Connection failed:', error)
}
}
}
return (
<div>
{connectors.map((connector) => (
<button
key={connector.id}
onClick={() => handleConnect(connector)}
disabled={isPending}
>
Connect {connector.name}
</button>
))}
{error && <p>Error: {error.message}</p>}
</div>
)
}
生产环境部署
环境配置
为开发和生产环境使用不同的配置:const config = createConfig({
chains: [process.env.NODE_ENV === 'production' ? bitcoin : testnet],
connectors: [phantom(), xverse()],
transports: {
[bitcoin.id]: fallback([
// Use paid providers in production for reliability
ankr({ apiKey: process.env.ANKR_API_KEY }),
blockchair(),
mempool(),
http('private_rpc_url')
]),
[testnet.id]: fallback([
// update the base URL for this transport, as it defaults to a mainnet URL
mempool({baseUrl: 'https://mempool.space/testnet/api'}),
])
}
})
监控与日志
实现适当的错误跟踪:import { BaseError } from '@bigmi/core'
function logError(error, context) {
if (error instanceof BaseError) {
console.error('Bigmi Error:', {
name: error.name,
message: error.message,
details: error.details,
context
})
} else {
console.error('Unknown Error:', error, context)
}
// Send to error tracking service in production
if (process.env.NODE_ENV === 'production') {
errorTracker.captureException(error, { extra: context })
}
}
小结
遵循这些最佳实践将帮助你使用 Bigmi 构建健壮、高性能且安全的 Bitcoin 应用:- 始终使用回退提供商 以提高可靠性
- 优雅地处理错误,使用特定的错误类型
- 实现适当的重试逻辑,采用指数退避
- 校验所有输入,包括地址和交易
- 使用高效的状态管理 以最小化重新渲染
- 为不同操作配置合适的超时
- 启用 RBF 并处理交易替换
- 支持多个钱包 以获得更好的用户覆盖
- 使用 Bigmi 的内置工具,例如
withRetry,以提高可靠性

