> ## Documentation Index
> Fetch the complete documentation index at: https://docs.li.fi/llms.txt
> Use this file to discover all available pages before exploring further.

# Best Practices

> Best practices for building Bitcoin applications with Bigmi.

# Bigmi Best Practices Guide

This guide covers best practices for building robust, performant, and secure Bitcoin applications with Bigmi, based on patterns from the actual codebase.

## Client Configuration

### Transport Configuration with Fallbacks

**Always use multiple providers for reliability:**

```typescript theme={"system"}
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
  })
})
```

### Timeout and Retry Strategy

**Configure appropriate timeouts per operation:**

```typescript theme={"system"}
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
  })
})
```

**Use fallback with timeout config for individual transports:**

```typescript theme={"system"}
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,
  })
})
```

### Caching Strategy

**Configure appropriate cache times:**

```typescript theme={"system"}
const client = createClient({
  cacheTime: 4_000,        // Cache responses for 4 seconds
  pollingInterval: 4_000,  // Poll for updates every 4 seconds
})
```

### Retry Logic with withRetry

**Use Bigmi's built-in retry utility:**

```typescript theme={"system"}
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)
    }
  }
)
```

## Transaction Management

### UTXO Selection Best Practices

**Filter and select UTXOs efficiently:**

```typescript theme={"system"}
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 })
```

### Fee Estimation Strategy

**Use dynamic fee estimation with multiple sources:**

```typescript theme={"system"}
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) Implementation

**Always enable RBF and handle replacements:**

```typescript theme={"system"}
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)
  }
})
```

### Address Validation

**Always validate addresses before use:**

```typescript theme={"system"}
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}`)
  }
}
```

## Wallet Integration

### Multi-Wallet Support

**Configure multiple connectors for broader compatibility:**

```typescript theme={"system"}
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')
  }
})
```

### Connection Error Handling

**Handle wallet-specific errors gracefully:**

```typescript theme={"system"}
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>
  )
}
```

## Production Deployment

### Environment Configuration

**Use different configurations for development and production:**

```typescript theme={"system"}
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'}),
    ])

  }
})
```

### Monitoring and Logging

**Implement proper error tracking:**

```typescript theme={"system"}
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 })
  }
}
```

## Summary

Following these best practices will help you build robust, performant, and secure Bitcoin applications with Bigmi:

* **Always use fallback providers** for reliability
* **Handle errors gracefully** with specific error types
* **Implement proper retry logic** with exponential backoff
* **Validate all inputs** including addresses and transactions
* **Use efficient state management** to minimize re-renders
* **Configure appropriate timeouts** for different operations
* **Enable RBF** and handle transaction replacements
* **Support multiple wallets** for better user coverage
* **Use Bigmi's built-in utilities** like `withRetry` for reliability
