# Booster Package

## Booster Integration Guide

### Table of Contents

1. Introduction
2. Understanding CKBoost
3. Installation
4. Quick Start
5. Core Concepts
6. Step-by-Step Integration
7. API Reference
8. Advanced Usage
9. Best Practices
10. Troubleshooting
11. Sample script

### Introduction

The `@ckboost/booster` package is a TypeScript SDK designed for liquidity providers who want to participate in the CKBoost ecosystem. This package enables you to provide liquidity services that accelerate ckBTC conversion times, earning fees in the process.

#### Who This Guide Is For

* **Liquidity Providers**: Individuals or organizations wanting to provide ckBTC liquidity services
* **DeFi Developers**: Building applications that offer liquidity provision features
* **Financial Services**: Companies looking to offer accelerated Bitcoin conversion services

#### Prerequisites

* Basic understanding of TypeScript/JavaScript
* Familiarity with Internet Computer Protocol (ICP)
* Understanding of Bitcoin and ckBTC concepts
* Node.js 16+ installed

### Understanding CKBoost

#### The Problem

Traditional ckBTC conversion requires waiting for 6 Bitcoin confirmations, which typically takes about 1 hour. This delay creates friction for users who need faster access to their ckBTC.

#### The Solution

CKBoost creates a marketplace where:

1. **Users** submit boost requests when they need faster ckBTC conversion
2. **Liquidity providers** (you) evaluate and accept requests based on risk parameters
3. **Acceleration** reduces conversion time from 1 hour to 7-10 minutes
4. **Fees** are earned by liquidity providers for this service

#### Market Dynamics

```
Traditional Flow:
Bitcoin → [6 confirmations ~1 hour] → ckBTC

CKBoost Flow:
Bitcoin → [Boost Request] → [Liquidity Provider] → [1-2 confirmations ~7-10 minutes] → ckBTC
```

### Installation

#### Package Installation

```bash
npm install @ckboost/booster
```

#### Dependencies

The package automatically includes all necessary dependencies:

* `@dfinity/agent` - ICP communication
* `@dfinity/identity` - Identity management
* `@dfinity/principal` - Principal handling
* `big.js` - Precise decimal calculations

### Quick Start

Here's a minimal example to get you started:

```typescript
import { ckTestBTCBooster } from '@ckboost/booster'

async function startBoosting() {
  // Initialize with your mnemonic
  const booster = new ckTestBTCBooster('your twelve word mnemonic phrase here')
  
  // Connect to the network
  await booster.initialize()
  
  // Register as a booster (one-time setup)
  await booster.registerBoosterAccount()
  
  // Check pending requests
  const requests = await booster.getPendingBoostRequests()
  console.log(`Found ${requests.length} pending requests`)
  
  // Accept the first request (if any)
  if (requests.length > 0) {
    await booster.acceptBoostRequest(requests[0].id)
    console.log('Boost request accepted!')
  }
}

startBoosting().catch(console.error)
```

### Core Concepts

#### Booster Account

A booster account is your registered identity in the CKBoost system:

```typescript
interface BoosterAccount {
  principal: Principal;    // Your unique identifier
  depositAmount: bigint;   // ckTESTBTC locked for boosting
  isActive: boolean;      // Account status
  totalEarned?: bigint;   // Historical earnings
}
```

#### Boost Requests

When users need faster conversion, they create boost requests:

```typescript
interface BoostRequest {
  id: bigint;              // Unique request identifier
  amount: bigint;          // ckBTC amount (in satoshis)
  maxFeePercentage: number; // Maximum fee user will pay
  deadline: bigint;        // When request expires
  userPrincipal: Principal; // Who made the request
}
```

#### Risk Assessment

As a liquidity provider, you should evaluate:

* **Amount size**: Larger amounts = higher risk
* **Fee percentage**: Higher fees = better profit
* **User history**: Repeat users may be lower risk
* **Market conditions**: Bitcoin volatility affects risk

### Step-by-Step Integration

#### Step 1: Setup and Identity

```typescript
import { ckTestBTCBooster, ckTESTBTC_CANISTER_IDS } from '@ckboost/booster'

// Create booster instance
const booster = new ckTestBTCBooster(
  'your twelve word mnemonic phrase here',
  'https://icp0.io' // Optional: custom host
)

// Initialize connection
await booster.initialize()

console.log('Your Principal:', booster.getPrincipal().toString())
console.log('Backend Canister:', ckTESTBTC_CANISTER_IDS.CKBOOST_BACKEND)
```

#### Step 2: Account Registration

```typescript
// Check if already registered
let account = await booster.getBoosterAccount()

if (!account) {
  console.log('Registering as booster...')
  
  try {
    await booster.registerBoosterAccount()
    account = await booster.getBoosterAccount()
    console.log('Registration successful!')
  } catch (error) {
    console.error('Registration failed:', error)
    return
  }
}

console.log('Booster account:', account)
```

#### Step 3: Liquidity Management

```typescript
// Check your ckTESTBTC balance
const balance = await booster.getBalance()
console.log('Available balance:', booster.formatBTC(balance), 'ckTESTBTC')

// Define how much to deposit (example: 0.01 ckTESTBTC)
const depositAmount = booster.parseBTC('0.01')

// Approve the backend to spend your tokens
await booster.approve(
  ckTESTBTC_CANISTER_IDS.CKBOOST_BACKEND, 
  depositAmount
)

// Update your booster deposit
await booster.updateBoosterDeposit(depositAmount)

console.log('Liquidity deposited successfully!')
```

#### Step 4: Request Monitoring

```typescript
async function monitorRequests() {
  try {
    const requests = await booster.getPendingBoostRequests()
    
    console.log(`Found ${requests.length} pending requests`)
    
    for (const request of requests) {
      console.log({
        id: request.id,
        amount: booster.formatBTC(request.amount),
        maxFee: request.maxFeePercentage,
        user: request.userPrincipal.toString()
      })
    }
    
    return requests
  } catch (error) {
    console.error('Failed to fetch requests:', error)
    return []
  }
}
```

#### Step 5: Request Evaluation and Acceptance

```typescript
function evaluateRequest(request: BoostRequest): boolean {
  // Convert amount to BTC for easier analysis
  const amountBTC = parseFloat(booster.formatBTC(request.amount))
  const feePercentage = request.maxFeePercentage
  
  // Define your risk parameters
  const maxAmountBTC = 0.1;      // Maximum 0.1 ckTESTBTC
  const minFeePercentage = 0.5;  // Minimum 0.5% fee
  
  // Basic risk assessment
  if (amountBTC > maxAmountBTC) {
    console.log(`Request ${request.id}: Amount too large (${amountBTC} BTC)`)
    return false
  }
  
  if (feePercentage < minFeePercentage) {
    console.log(`Request ${request.id}: Fee too low (${feePercentage}%)`)
    return false
  }
  
  console.log(`Request ${request.id}: Meets criteria - accepting`)
  return true
}

async function processRequests() {
  const requests = await monitorRequests()
  
  for (const request of requests) {
    if (evaluateRequest(request)) {
      try {
        await booster.acceptBoostRequest(request.id)
        console.log(`✅ Accepted request ${request.id}`)
        
        // Calculate expected earnings
        const feeAmount = request.amount * BigInt(request.maxFeePercentage) / BigInt(100)
        console.log(`Expected fee: ${booster.formatBTC(feeAmount)} ckTESTBTC`)
        
      } catch (error) {
        console.error(`❌ Failed to accept request ${request.id}:`, error)
      }
    }
  }
}
```

### API Reference

#### Constructor

```typescript
new ckTestBTCBooster(mnemonics: string, host?: string)
```

Creates a new booster instance.

**Parameters:**

* `mnemonics` - Your 12-word recovery phrase
* `host` - ICP network host (optional, defaults to mainnet)

#### Initialization Methods

**`initialize()`**

```typescript
await booster.initialize(): Promise<void>
```

Initializes the connection to ICP and sets up the actor. Must be called before other methods.

#### Account Management

**`registerBoosterAccount()`**

```typescript
await booster.registerBoosterAccount(): Promise<any>
```

Registers your account as a liquidity provider. Only needs to be called once.

**`getBoosterAccount()`**

```typescript
await booster.getBoosterAccount(): Promise<BoosterAccount | null>
```

Retrieves your booster account information.

**`updateBoosterDeposit(amount)`**

```typescript
await booster.updateBoosterDeposit(amount: bigint): Promise<any>
```

Updates the amount of ckTESTBTC you have available for boosting.

#### Boost Operations

**`getPendingBoostRequests()`**

```typescript
await booster.getPendingBoostRequests(): Promise<BoostRequest[]>
```

Retrieves all pending boost requests from users.

**`acceptBoostRequest(requestId)`**

```typescript
await booster.acceptBoostRequest(requestId: bigint): Promise<any>
```

Accepts a specific boost request.

#### Token Operations

**`getBalance()`**

```typescript
await booster.getBalance(): Promise<bigint>
```

Gets your ckTESTBTC balance in satoshis.

**`transfer(to, amount)`**

```typescript
await booster.transfer(to: string, amount: bigint): Promise<any>
```

Transfers ckTESTBTC to another account.

**`approve(spender, amount)`**

```typescript
await booster.approve(spender: string, amount: bigint): Promise<any>
```

Approves another account to spend your ckTESTBTC.

#### Utility Methods

**`formatBTC(satoshis)`**

```typescript
booster.formatBTC(satoshis: bigint): string
```

Converts satoshis to BTC decimal format.

**`parseBTC(btc)`**

```typescript
booster.parseBTC(btc: string): bigint
```

Converts BTC decimal string to satoshis.

**`getPrincipal()`**

```typescript
booster.getPrincipal(): Principal
```

Returns your principal identifier.

### Advanced Usage

#### Automated Booster Bot

```typescript
class BoosterBot {
  private booster: ckTestBTCBooster
  private isRunning = false
  private config = {
    maxAmountBTC: 0.1,
    minFeePercentage: 0.5,
    checkIntervalMs: 30000, // 30 seconds
  }

  constructor(mnemonics: string) {
    this.booster = new ckTestBTCBooster(mnemonics)
  }

  async start() {
    await this.booster.initialize()
    
    // Ensure we're registered
    const account = await this.booster.getBoosterAccount()
    if (!account) {
      await this.booster.registerBoosterAccount()
    }

    this.isRunning = true
    this.runLoop()
  }

  private async runLoop() {
    while (this.isRunning) {
      try {
        await this.processRequests()
      } catch (error) {
        console.error('Bot error:', error)
      }
      
      // Wait before next check
      await new Promise(resolve => 
        setTimeout(resolve, this.config.checkIntervalMs)
      )
    }
  }

  private async processRequests() {
    const requests = await this.booster.getPendingBoostRequests()
    
    for (const request of requests) {
      if (this.shouldAcceptRequest(request)) {
        await this.booster.acceptBoostRequest(request.id)
        console.log(`🤖 Bot accepted request ${request.id}`)
      }
    }
  }

  private shouldAcceptRequest(request: BoostRequest): boolean {
    const amountBTC = parseFloat(this.booster.formatBTC(request.amount))
    
    return (
      amountBTC <= this.config.maxAmountBTC &&
      request.maxFeePercentage >= this.config.minFeePercentage
    )
  }

  stop() {
    this.isRunning = false
  }
}

// Usage
const bot = new BoosterBot('your mnemonic here')
await bot.start()
```

#### Risk Scoring System

```typescript
interface RiskMetrics {
  amountScore: number      // 0-100 (higher = riskier)
  feeScore: number        // 0-100 (higher = better)
  userScore: number       // 0-100 (higher = more trustworthy)
  timeScore: number       // 0-100 (higher = more urgent)
}

class RiskAnalyzer {
  calculateRisk(request: BoostRequest): RiskMetrics {
    const amountBTC = parseFloat(
      this.booster.formatBTC(request.amount)
    )
    
    // Amount risk (higher amounts = higher risk)
    const amountScore = Math.min(amountBTC * 1000, 100)
    
    // Fee attractiveness (higher fees = better)
    const feeScore = Math.min(request.maxFeePercentage * 50, 100)
    
    // User trustworthiness (would need historical data)
    const userScore = 50 // Default neutral score
    
    // Time urgency (closer to deadline = higher score)
    const timeScore = this.calculateTimeUrgency(request.deadline)
    
    return { amountScore, feeScore, userScore, timeScore }
  }
  
  shouldAccept(request: BoostRequest): boolean {
    const metrics = this.calculateRisk(request)
    
    // Combined score weighted by importance
    const combinedScore = (
      metrics.feeScore * 0.4 +
      metrics.userScore * 0.3 +
      metrics.timeScore * 0.2 -
      metrics.amountScore * 0.1
    )
    
    // Accept if score is above threshold
    return combinedScore > 60
  }
}
```

### Best Practices

#### Security

1. **Secure Mnemonic Storage**

```typescript
// ❌ Don't hardcode mnemonics
const booster = new ckTestBTCBooster('word1 word2 word3...')

// ✅ Use environment variables
const booster = new ckTestBTCBooster(process.env.BOOSTER_MNEMONIC!)
```

2. **Error Handling**

```typescript
// ✅ Always wrap in try-catch
try {
  await booster.acceptBoostRequest(requestId)
} catch (error) {
  if (error.message.includes('insufficient funds')) {
    console.log('Need more liquidity')
  } else {
    console.error('Unexpected error:', error)
  }
}
```

#### Performance

1. **Batch Operations**

```typescript
// ✅ Process multiple requests efficiently
const requests = await booster.getPendingBoostRequests()
const acceptableRequests = requests.filter(shouldAcceptRequest)

// Process in parallel (with rate limiting)
const results = await Promise.allSettled(
  acceptableRequests.map(req => 
    booster.acceptBoostRequest(req.id)
  )
)
```

2. **Caching**

```typescript
// ✅ Cache account info to reduce calls
class CachedBooster {
  private accountCache: BoosterAccount | null = null
  private cacheExpiry = 0

  async getBoosterAccount(): Promise<BoosterAccount | null> {
    if (this.accountCache && Date.now() < this.cacheExpiry) {
      return this.accountCache
    }
    
    this.accountCache = await this.booster.getBoosterAccount()
    this.cacheExpiry = Date.now() + 60000 // 1 minute cache
    
    return this.accountCache
  }
}
```

#### Monitoring

1. **Logging**

```typescript
// ✅ Structured logging
import winston from 'winston'

const logger = winston.createLogger({
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'booster.log' })
  ]
})

logger.info('Request accepted', {
  requestId: request.id,
  amount: booster.formatBTC(request.amount),
  fee: request.maxFeePercentage,
  timestamp: new Date().toISOString()
})
```

2. **Metrics**

```typescript
// ✅ Track performance metrics
class BoosterMetrics {
  private stats = {
    requestsProcessed: 0,
    requestsAccepted: 0,
    totalFeesEarned: BigInt(0),
    averageProcessingTime: 0
  }
  
  recordAcceptance(request: BoostRequest, processingTime: number) {
    this.stats.requestsProcessed++
    this.stats.requestsAccepted++
    this.stats.totalFeesEarned += 
      request.amount * BigInt(request.maxFeePercentage) / BigInt(100)
    
    // Update rolling average
    this.stats.averageProcessingTime = 
      (this.stats.averageProcessingTime + processingTime) / 2
  }
}
```

### Troubleshooting

#### Common Issues

**"Cannot find module" Error**

```bash
Error: Cannot find module '@ckboost/booster'
```

**Solution:**

```bash
npm install @ckboost/booster
# or if using yarn
yarn add @ckboost/booster
```

**Identity/Authentication Errors**

```bash
Error: Failed to authenticate with agent
```

**Solutions:**

1. Verify your mnemonic phrase is correct
2. Check network connectivity
3. Ensure proper host configuration

```typescript
// Try with explicit host
const booster = new ckTestBTCBooster(
  mnemonics, 
  'https://icp0.io'
)
```

**Insufficient Funds**

```bash
Error: Insufficient funds for operation
```

**Solutions:**

1. Check your ckTESTBTC balance
2. Ensure you have approved enough tokens
3. Verify your deposit amount

```typescript
// Check balances
const balance = await booster.getBalance()
console.log('Balance:', booster.formatBTC(balance))

// Check account deposit
const account = await booster.getBoosterAccount()
console.log('Deposited:', booster.formatBTC(account.depositAmount))
```

**Request Already Accepted**

```bash
Error: Boost request has already been accepted
```

This is normal - another booster accepted the request first. Your system should handle this gracefully:

```typescript
try {
  await booster.acceptBoostRequest(requestId)
} catch (error) {
  if (error.message.includes('already accepted')) {
    console.log('Request was accepted by another booster')
  } else {
    throw error
  }
}
```

#### Debug Mode

Enable detailed logging for troubleshooting:

```typescript
// Add debug logging
const originalConsoleLog = console.log
console.log = (...args) => {
  originalConsoleLog(new Date().toISOString(), ...args)
}

// Enable agent debugging (if available)
const booster = new ckTestBTCBooster(mnemonics, 'https://icp0.io')
await booster.initialize()

// Log all operations
console.log('Booster initialized successfully')
```

#### Performance Issues

If operations are slow:

1. **Check Network Latency**

```typescript
const start = Date.now()
await booster.getPendingBoostRequests()
console.log(`Request took ${Date.now() - start}ms`)
```

2. **Optimize Polling Frequency**

```typescript
// Don't poll too frequently
const POLL_INTERVAL = 30000 // 30 seconds minimum
```

3. **Use Connection Pooling**

```typescript
// Reuse the same booster instance
const globalBooster = new ckTestBTCBooster(mnemonics)
await globalBooster.initialize()

// Use this instance throughout your application
export { globalBooster as booster }
```

***

### Source code and sample

ckBoost packages are completely open-source and can be found on Github: <https://github.com/ckboost/ckboost-packages>

Sample application source, using @ckboost/booster package can be found here:&#x20;

<https://github.com/ckboost/ckboost-packages/tree/main/sample>

***

*Happy boosting! 🚀*
