# ckBoost for Bitcoin

Welcome to **ckBoost**, a permission‑less liquidity layer that lets anyone receive any **Chain‑Key asset** (ckBTC, ckETH, ckUSDC, and future tokens) on the Internet Computer **before** the corresponding transaction is fully confirmed on its native blockchain.

> **Why it matters:** Native blockchains impose confirmation delays—e.g., \~60 minutes for 6 Bitcoin blocks, \~3 minutes for 12 Ethereum slots—before a Chain‑Key (ck) version can be minted. **ckBoost** eliminates this wait by matching each incoming deposit with **Boosters**: liquidity providers who advance the ck‑version immediately, then redeem the underlying asset once finality is reached.

***

### What Problem Does ckBoost Solve?

| 🐢 Traditional Bridge Flow                                                                                                                                                                                                                 | ⚡️ ckBoost Flow                                                                                                                                                                                                                                                                                                                           |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <p>1. User sends an L1 asset (BTC, ETH, USDC…) to a minting address on the bridge. </p><p></p><p>2. Wait for the required block confirmations (varies by chain). </p><p></p><p>3. Chain‑Key asset is minted and becomes usable on ICP.</p> | <p>1. User sends the asset to a <strong>boost address</strong> generated by ckBoost. </p><p></p><p>2. A Booster detects the deposit and instantly transfers the matching <strong>ckAsset</strong> to the user (minus a fee). </p><p></p><p>3. After confirmations, the Booster claims the underlying L1 funds via ckBoost settlement.</p> |

*Result: users interact with DeFi, games, or payments on ICP in seconds, while Boosters earn fees for providing just‑in‑time liquidity.*


# Protocol Overview

### Core Concepts

ckBoost operates on four fundamental concepts that work together to provide instant Bitcoin liquidity.

#### 1. Boost Requests

A **Boost Request** is created when a user wants to convert Bitcoin to ckBTC instantly.

{% @mermaid/diagram content="graph LR
A\[User Creates Request] --> B\[Bitcoin Address Generated]
B --> C\[User Sends Bitcoin]
C --> D\[Booster Provides ckBTC]
D --> E\[Request Completed]" %}

**Key Properties:**

* **Amount**: How much Bitcoin (in satoshis) the user wants to convert
* **Fee**: Maximum fee percentage the user is willing to pay
* **Status**: Current state of the request (pending, active, completed, etc.)
* **Subaccount**: Isolated account for this specific request
* **Bitcoin Address**: Unique address where user sends Bitcoin

#### 2. Booster Pools

A **Booster Pool** represents a liquidity provider's available capital for instant transfers.

**Key Properties:**

* **Owner**: The principal who owns this pool
* **Available Amount**: ckBTC currently available for boosting
* **Fee Rate**: The fee this booster charges for providing liquidity
* **Total Boosted**: Historical volume this booster has provided
* **Subaccount**: Isolated account for this booster's funds

#### 3. Liquidity Providers (Boosters)

Boosters are entities that provide instant ckBTC in exchange for future Bitcoin deposits plus fees.

**How Boosters Work:**

1. Deposit ckBTC into their pool
2. Set their fee rate (competitive advantage)
3. Accept boost requests by transferring ckBTC instantly
4. Wait for Bitcoin confirmation and reclaim funds
5. Earn fees for providing the service

#### 4. Users

Users are entities who want instant ckBTC and are willing to pay a fee for speed.

**User Journey:**

1. Create a boost request with desired amount and max fee
2. Receive a unique Bitcoin address
3. Send Bitcoin to that address
4. Receive ckBTC instantly (if booster accepts)
5. Pay agreed fee for the speed

### Economic Model

#### Fee Structure

The protocol uses a **competitive fee marketplace**:

* **Users** set their **maximum fee** they're willing to pay
* **Boosters** set their **minimum fee** they require
* **Market dynamics** determine actual fees through competition

#### Incentive Mechanisms

**For Users:**

* Instant liquidity (15 min vs 2+ hours)
* Predictable fees (set maximum)
* Fallback safety (can claim directly if no booster)

**For Boosters:**

* Earn fees on capital
* Choose risk/reward profile
* Flexible capital deployment
* Automated operations

### Request Lifecycle

#### State Machine

{% @mermaid/diagram content="stateDiagram-v2
\[*] --> pending : registerBoostRequest()
pending --> active : acceptBoostRequest()
pending --> minting : triggerMintingForMyBoostRequest()
active --> boosted : ckBTC transferred to user
boosted --> minting : triggerMintingForBoostReclaim()
minting --> completed : claimMintedFunds()
pending --> cancelled : User cancels
\[*] --> pending : registerBoostRequest()
pending --> active : acceptBoostRequest()
pending --> minting : triggerMintingForMyBoostRequest()
active --> boosted : ckBTC transferred to user
boosted --> minting : triggerMintingForBoostReclaim()
minting --> completed : claimMintedFunds()
pending --> cancelled : User cancels" %}

#### Detailed Flow

**1. Request Creation (`pending`)**

**What happens:**

* Unique request ID generated
* Bitcoin address created for this request
* Request enters `pending` state
* Available for boosters to accept

**2. Booster Acceptance (`active` → `boosted`)**

**What happens:**

* Booster's available balance checked
* ckBTC transferred instantly to user
* Request status → `boosted`
* Booster's available balance reduced
* User receives ckBTC immediately

**3. Bitcoin Monitoring**

**What happens:**

* Booster monitors the Bitcoin address
* When Bitcoin arrives, `receivedBTC` is updated
* Enables fund reclamation process

**4. Fund Reclamation (`boosted` → `completed`)**

**What happens:**

* Bitcoin is converted to ckBTC via ckBTC minter
* ckBTC is transferred back to booster's pool
* Booster's available balance restored + fees earned
* Request status → `completed`

**5. User Fallback (No Booster)**

### Security Model

#### Fund Isolation

Every request and booster pool uses **isolated subaccounts**:

**Benefits:**

* Funds cannot be mixed between different requests
* Clear audit trail for every transaction
* Isolated risk (one request cannot affect another)
* Precise accounting and fee calculations

### Integration Patterns

#### User-Facing Applications (Wallets, dApps)

```typescript
class ckBoostIntegration {
  async createBoostRequest(btcAmount: number, maxFee: number) {
    // 1. Create request
    const request = await this.backend.registerBoostRequest(btcAmount, maxFee);
    
    // 2. Get Bitcoin address
    const address = await this.backend.getBoostRequestBTCAddress(request.id);
    
    // 3. Show QR code to user
    this.showBitcoinAddress(address);
    
    // 4. Monitor status
    this.monitorRequest(request.id);
  }
  
  async monitorRequest(requestId: number) {
    const interval = setInterval(async () => {
      const request = await this.backend.getBoostRequest(requestId);
      
      if ('completed' in request.status) {
        this.notifyUser("ckBTC received!");
        clearInterval(interval);
      }
    }, 30000); // Check every 30 seconds
  }
}
```

#### Liquidity Provider Applications

```typescript
class BoosterBot {
  async managePool() {
    // 1. Register as booster
    await this.backend.registerBoosterPool(this.feeRate);
    
    // 2. Deposit initial capital
    await this.depositToPool(this.initialCapital);
    
    // 3. Monitor and accept requests
    this.startRequestMonitoring();
  }
  
  async startRequestMonitoring() {
    setInterval(async () => {
      const requests = await this.backend.getPendingBoostRequests();
      
      for (const request of requests) {
        if (this.shouldAcceptRequest(request)) {
          await this.backend.acceptBoostRequest(request.id);
        }
      }
    }, 10000); // Check every 10 seconds
  }
}
```

### Performance Characteristics

#### Latency Expectations

| Operation            | Expected Time | Notes                      |
| -------------------- | ------------- | -------------------------- |
| Create Request       | 1-3 seconds   | Single canister call       |
| Accept Request       | 2-5 seconds   | ICRC-1 transfer included   |
| Bitcoin Confirmation | 15-60 minutes | Depends on Bitcoin network |
| Fund Reclamation     | 30-90 seconds | Two-phase process          |

***


# Architecture Deep Dive

### System Overview

ckBoost is designed as a modular, secure, and scalable protocol with clean separation of concerns.

{% @mermaid/diagram content="graph TB
subgraph "Internet Computer"
subgraph "ckBoost Protocol"
A\[Main Canister] --> B\[Ledger Module]
A --> C\[Validation Module]
A --> D\[Booster Account Module]
A --> E\[Minting Operations Module]
A --> F\[Boost Request Module]
A --> G\[State Management]
end

```
    subgraph "External IC Canisters"
        H[ckBTC Ledger]
        I[ckBTC Minter]
    end
end

subgraph "Bitcoin Network"
    J[Bitcoin Addresses]
    K[Bitcoin Transactions]
end

A --> H
A --> I
I --> J
K --> I
```

" %}

### Canister Architecture

#### Core Modules

**1. Main Canister (`main.mo`)**

**Purpose**: Orchestration layer and public API **Responsibilities**:

* Expose public functions defined in Candid interface
* Coordinate between modules
* Handle authentication and authorization
* Manage system state

**2. State Management (`state.mo`)**

**Purpose**: Centralized state storage with persistence **Responsibilities**:

* Store all boost requests
* Store all booster accounts
* Provide atomic updates
* Handle canister upgrades

**3. Ledger Operations (`ledger.mo`)**

**Purpose**: All ICRC-1 token operations **Responsibilities**:

* Handle ckBTC transfers
* Manage transaction fees
* Account balance queries
* Error handling and logging

**4. Validation Module (`validation.mo`)**

**Purpose**: Input validation and business rules **Responsibilities**:

* Validate amounts and fees
* Check business logic constraints
* Sanitize inputs

**5. Booster Account Management (`booster_account.mo`)**

**Purpose**: Liquidity provider operations **Responsibilities**:

* Register new boosters
* Manage deposits and withdrawals
* Track available balances
* Handle pool operations

**6. Minting Operations (`minting_operations.mo`)**

**Purpose**: Complex ckBTC minting workflows **Responsibilities**:

* Two-phase minting processes
* Cross-canister call management
* Error recovery and retry logic
* Fund reclamation flows

### Data Architecture

#### Type System

```motoko
// Core types with clear relationships
type BoostRequest = {
  id: Nat;
  owner: Principal;
  amount: Nat;                    // Amount in satoshis
  maxFeePercentage: Float;        // Maximum fee user will pay
  receivedBTC: Nat;               // Actually received Bitcoin
  btcAddress: ?Text;              // Generated Bitcoin address
  subaccount: Blob;               // Isolated subaccount
  status: BoostStatus;            // Current state
  matchedBooster: ?Principal;     // Which booster accepted
  createdAt: Int;                 // Timestamp
  updatedAt: Int;                 // Last modification
};

type BoosterAccount = {
  owner: Principal;
  feePercentage: Float;           // Fee this booster charges
  subaccount: Blob;               // Booster's isolated subaccount
  availableBalance: Nat;          // Available for new boosts
  totalDeposited: Nat;            // Lifetime deposits
  totalWithdrawn: Nat;            // Lifetime withdrawals
  totalBoosted: Nat;              // Volume provided
  totalFeesEarned: Nat;           // Fees earned
  createdAt: Int;
  updatedAt: Int;
};
```

#### State Transitions

{% @mermaid/diagram content="stateDiagram-v2
\[\*] --> pending : registerBoostRequest()

```
pending --> active : acceptBoostRequest()
pending --> minting : triggerMintingForMyBoostRequest()
pending --> cancelled : User cancels

active --> boosted : ckBTC transferred

boosted --> minting : triggerMintingForBoostReclaim()

minting --> completed : claimMintedFunds() / claimMintedCKBTC()

cancelled --> [*]
completed --> [*]" %}
```

### Security Architecture

#### Trust Boundaries

{% @mermaid/diagram content="graph TB
subgraph "Trusted Zone (ckBoost Canister)"
A\[Main Logic]
B\[State Storage]
C\[Subaccount Management]
end

```
subgraph "External Trust (IC System Canisters)"
    D[ckBTC Ledger]
    E[ckBTC Minter]
end

subgraph "Untrusted Zone"
    F[User Inputs]
    G[Bitcoin Network]
    H[External Calls]
end

F --> A
A --> D
A --> E
G --> E
H --> A" %}
```

#### Fund Isolation Strategy

Every operation uses isolated subaccounts to prevent fund mixing:

**Security Benefits:**

* Request funds cannot be mixed with other requests
* Booster funds cannot be mixed with user funds
* Clear audit trail for every satoshi
* Isolated failure domains

***

**Next**: API Reference →


# User Flow

### Complete User Journey

This diagram shows the entire user flow from creating a boost request to receiving ckBTC, including all actors and timeframes.

{% @mermaid/diagram content="sequenceDiagram
participant U as User
participant P as ckBoost Protocol
participant B as Booster
participant BN as Bitcoin Network
participant M as ckBTC Minter

```
Note over U,M: Happy Path: Booster Available

%% Phase 1: Request Creation
U->>P: registerBoostRequest(0.01 BTC, 2% max fee)
P->>P: Generate unique subaccount
P->>M: Create Bitcoin address for subaccount
M-->>P: Bitcoin address (bc1q...)
P-->>U: Request created + Bitcoin address

%% Phase 2: Market Discovery
P->>B: Broadcast pending request
B->>B: Evaluate request (profit, risk, liquidity)
B->>P: acceptBoostRequest(requestId)
P->>P: Verify booster balance
P->>U: Transfer ckBTC instantly (0.98 ckBTC)
P-->>U: ✅ ckBTC received!

%% Phase 3: User sends Bitcoin
U->>BN: Send 0.01 BTC to address
BN->>BN: Transaction propagates
Note over BN: ~10-60 minutes for confirmations

%% Phase 4: Bitcoin confirmation & reclamation
BN->>M: Bitcoin confirmations (6/6)
M->>P: Notify of confirmed deposit
B->>P: triggerMintingForBoostReclaim(requestId)
P->>M: update_balance(subaccount)
M->>P: Mint ckBTC from Bitcoin
B->>P: reclaimMintedFunds(requestId)
P->>B: Transfer 0.01 ckBTC + 0.002 fee to booster
P->>P: Mark request as completed

Note over U,M: Fallback Path: No Booster Available 

%% Alternative flow when no booster
U->>P: registerBoostRequest(0.01 BTC, 2% max fee)
P->>P: Generate subaccount + Bitcoin address
P-->>U: Request created, waiting for booster...
Note over P: no booster accepts
U->>P: triggerMintingForMyBoostRequest(requestId)
P->>P: Switch to direct minting mode

U->>BN: Send 0.01 BTC to address
BN->>BN: Transaction confirms
BN->>M: Bitcoin deposit confirmed
M->>P: Notify of deposit
P->>M: update_balance(subaccount)
M->>P: Mint ckBTC from Bitcoin
U->>P: claimMintedCKBTC(requestId)
P->>U: Transfer 0.01 ckBTC directly
P-->>U: ✅ ckBTC received!
```

" %}

### Step-by-Step User Experience

#### Phase 1: Request Creation

**What the user does:**

1. **Decides amount and fee**: User wants to convert 0.01 BTC and is willing to pay up to 2% fee for instant service
2. **Creates boost request**: Calls `registerBoostRequest(1000000, 2.0)` via wallet or dApp
3. **Receives Bitcoin address**: Gets a unique address like `bc1q7x8k2...` where they need to send Bitcoin

**What happens behind the scenes:**

* Protocol generates a unique subaccount for this request
* Bitcoin address is created specifically for this request (fund isolation)
* Request enters `pending` status and becomes visible to boosters
* Unique request ID is assigned for tracking

#### Phase 2: Market Discovery (0-5 minutes)

**Two possible paths from here:**

**Path A: Booster Available (Happy Path)**

**What happens:**

1. **Booster monitoring**: Active boosters continuously scan pending requests
2. **Request evaluation**: Booster evaluates:
   * **Profitability**: X% fee on 0.01 BTC
   * **Risk assessment**: Amount size, user history, current market conditions
   * **Available liquidity**: Does booster have 0.01 ckBTC available?
3. **Instant acceptance**: If profitable and low-risk, booster accepts within seconds
4. **Immediate ckBTC transfer**: User receives 0.98 ckBTC (0.01 BTC minus \~2% fee) instantly

**Path B: No Booster Available (Fallback                                                                                                )**

**What happens:**

1. **Waiting period**: Request sits in `pending` status
2. **User decision**: After some time, user can trigger direct minting
3. **Fallback activation**: User calls `triggerMintingForMyBoostRequest()`
   1. **Direct processing**: Protocol handles minting directly without booster2 wj

#### Phase 3: Bitcoin Transaction (User action required)

**What the user does:**

1. **Send Bitcoin**: User sends exactly 0.01 BTC to the provided address
   * Can use any Bitcoin wallet
   * Must send the exact amount requested
   * Should use appropriate fee for timely confirmation

**What happens behind the scenes:**

* Bitcoin transaction broadcasts to the network
* Transaction appears in mempool (unconfirmed)
* ckBTC minter begins monitoring this specific address
* Protocol tracks the incoming transaction

**Timeline**: Immediate broadcast, 10-60 minutes for confirmations

#### Phase 4A: Instant Liquidity (Booster Path)

**What the user experiences:**

1. **Immediate notification**: "ckBTC received! Transaction complete."
2. **Balance update**: Wallet shows new ckBTC balance
3. **Ready to use**: Can immediately use ckBTC in DeFi, transfers, etc.

**What happens behind the scenes:**

1. **ICRC-1 transfer**: Booster's ckBTC is transferred to user's principal
2. **Booster balance**: Booster's available balance decreases
3. **Status update**: Request status changes to `boosted`
4. **Fee calculation**: User pays agreed fee (e.g., 1.5% actual vs 2% max)

#### Phase 4B: Direct Minting (Fallback Path)

**What the user experiences:**

1. **Minting notification**: "Bitcoin received, minting ckBTC..."
2. **Progress updates**: Regular status updates during minting process
3. **Completion**: "ckBTC minted and transferred!"

**What happens behind the scenes:**

1. **Bitcoin confirmation**: Wait for sufficient Bitcoin confirmations (usually 6)
2. **Minter interaction**: Protocol calls ckBTC minter to convert BTC to ckBTC
3. **Direct transfer**: Minted ckBTC goes directly to user (no booster involved)
4. **No additional fees**: User only pays standard ckBTC minting fees

#### Phase 5: Fund Reclamation (Background - Booster Path Only)

**What happens (user doesn't see this):**

1. **Bitcoin monitoring**: Protocol monitors for Bitcoin deposit confirmation
2. **Minting trigger**: Once Bitcoin arrives, booster can trigger fund reclamation
3. **Two-phase process**:
   * **Phase 1**: Call ckBTC minter to mint ckBTC from deposited Bitcoin
   * **Phase 2**: Transfer minted ckBTC back to booster's pool
4. **Profit realization**: Booster receives original amount + earned fees
5. **Pool replenishment**: Booster's available balance is restored + profit


# API Reference

Complete reference for all ckBoost Protocol functions based on the Candid interface.

### Type Definitions

#### Basic Types

| Type            | Description                                   |
| --------------- | --------------------------------------------- |
| `BoostId`       | `nat` - Unique identifier for boost requests  |
| `BoosterPoolId` | `nat` - Unique identifier for booster pools   |
| `Subaccount`    | `blob` - ICRC-1 subaccount for fund isolation |
| `Amount`        | `nat` - Amount in satoshis                    |
| `Timestamp`     | `int` - Unix timestamp in nanoseconds         |
| `Fee`           | `float64` - Fee percentage (0.1 to 10.0)      |

#### Status Types

```candid
type BoostStatus = variant {
  pending;     // Waiting for booster acceptance
  active;      // Booster matched, waiting for Bitcoin
  completed;   // Transaction completed successfully
  cancelled;   // Request cancelled
  boosted;     // ckBTC provided, waiting for reclamation
  minting;     // Minting process in progress
};
```

#### Record Types

```candid
type BoostRequest = record {
  id: BoostId;
  owner: principal;
  amount: Amount;
  fee: Fee;
  receivedBTC: Amount;
  btcAddress: opt text;
  subaccount: Subaccount;
  status: BoostStatus;
  matchedBoosterPool: opt BoosterPoolId;
  createdAt: Timestamp;
  updatedAt: Timestamp;
};

type BoosterPool = record {
  id: BoosterPoolId;
  owner: principal;
  fee: Fee;
  subaccount: Subaccount;
  availableAmount: Amount;
  totalBoosted: Amount;
  createdAt: Timestamp;
  updatedAt: Timestamp;
};
```

#### Result Types

```candid
type BoostRequestResult = variant { ok: BoostRequest; err: text };
type BoosterPoolResult = variant { ok: BoosterPool; err: text };
type TextResult = variant { ok: text; err: text };
```

### Helper Functions

Utility functions for conversions and system information.

| Function               | Parameters | Returns        | Description                       |
| ---------------------- | ---------- | -------------- | --------------------------------- |
| `ckBTCToSatoshis`      | `float64`  | `nat`          | Converts ckBTC amount to satoshis |
| `satoshisToCkBTC`      | `nat`      | `float64`      | Converts satoshis to ckBTC amount |
| `getCanisterPrincipal` | none       | `text` (query) | Gets the canister's principal ID  |
| `getDirectBTCAddress`  | none       | `text`         | Gets the main Bitcoin address     |

#### System Functions

| Function | Parameters | Returns        | Description                |
| -------- | ---------- | -------------- | -------------------------- |
| `greet`  | `text`     | `text` (query) | Basic greeting function    |
| `whoami` | none       | `text`         | Returns caller's principal |

### Boost Request Operations

Functions for creating, managing, and querying boost requests.

#### Request Lifecycle

| Function                    | Parameters          | Returns              | Purpose                           |
| --------------------------- | ------------------- | -------------------- | --------------------------------- |
| `registerBoostRequest`      | `Amount`, `Fee`     | `BoostRequestResult` | Create new boost request          |
| `updateReceivedBTC`         | `BoostId`, `Amount` | `BoostRequestResult` | Update Bitcoin deposit amount     |
| `getBoostRequestBTCAddress` | `BoostId`           | `TextResult`         | Get Bitcoin address for request   |
| `checkBTCDeposit`           | `BoostId`           | `BoostRequestResult` | Check and update Bitcoin deposits |

#### Request Queries

| Function               | Parameters  | Returns                    | Purpose                    |
| ---------------------- | ----------- | -------------------------- | -------------------------- |
| `getBoostRequest`      | `BoostId`   | `opt BoostRequest` (query) | Get specific request by ID |
| `getUserBoostRequests` | `principal` | `vec BoostRequest` (query) | Get all requests for user  |
| `getAllBoostRequests`  | none        | `vec BoostRequest` (query) | Get all requests in system |

#### Function Details

**`registerBoostRequest(Amount, Fee) -> BoostRequestResult`**

Creates a new boost request for instant ckBTC conversion.

* **Amount**: Satoshis to convert (minimum: 10,000)
* **Fee**: Maximum fee percentage (0.1 - 10.0)
* **Errors**: Invalid amount, invalid fee, address generation failure

**`updateReceivedBTC(BoostId, Amount) -> BoostRequestResult`**

Updates the Bitcoin amount received for a request.

* **BoostId**: Target request identifier
* **Amount**: Bitcoin amount received in satoshis
* **Errors**: Request not found, invalid status, invalid amount

**`getBoostRequestBTCAddress(BoostId) -> TextResult`**

Retrieves the unique Bitcoin address for a boost request.

* **BoostId**: Target request identifier
* **Returns**: Bitcoin address string
* **Errors**: Request not found, address not generated

**`checkBTCDeposit(BoostId) -> BoostRequestResult`**

Monitors and updates Bitcoin deposits for a request.

* **BoostId**: Target request identifier
* **Returns**: Updated request with current Bitcoin balance
* **Errors**: Request not found, monitoring failure

### Booster Pool Operations

Functions for liquidity providers to manage their capital pools.

#### Pool Management

| Function              | Parameters | Returns             | Purpose                 |
| --------------------- | ---------- | ------------------- | ----------------------- |
| `registerBoosterPool` | `Fee`      | `BoosterPoolResult` | Create new booster pool |

#### Pool Queries

| Function              | Parameters      | Returns                   | Purpose                 |
| --------------------- | --------------- | ------------------------- | ----------------------- |
| `getBoosterPool`      | `BoosterPoolId` | `opt BoosterPool` (query) | Get specific pool by ID |
| `getUserBoosterPools` | `principal`     | `vec BoosterPool` (query) | Get all pools for user  |
| `getAllBoosterPools`  | none            | `vec BoosterPool` (query) | Get all pools in system |

#### Function Details

**`registerBoosterPool(Fee) -> BoosterPoolResult`**

Creates a new liquidity pool for providing instant ckBTC.

* **Fee**: Fee percentage charged (0.1 - 10.0)
* **Errors**: User already has pool, invalid fee percentage

### Advanced Operations

Core protocol operations for boosters and users.

#### Booster Operations

| Function                        | Parameters            | Returns                | Purpose                        |
| ------------------------------- | --------------------- | ---------------------- | ------------------------------ |
| `acceptBoostRequest`            | `BoostId`             | `text`                 | Accept a pending boost request |
| `registerBoosterAccount`        | `Fee`                 | `BoosterAccountResult` | Create booster account         |
| `updateBoosterDeposit`          | `principal`, `Amount` | `BoosterAccountResult` | Add liquidity to account       |
| `withdrawBoosterFunds`          | `Amount`              | `text`                 | Remove liquidity from account  |
| `triggerMintingForBoostReclaim` | `BoostId`             | `text`                 | Start fund reclamation process |
| `reclaimMintedFunds`            | `BoostId`             | `text`                 | Complete fund reclamation      |

#### User Fallback Operations

<table><thead><tr><th width="308.6484375">Function</th><th>Parameters</th><th width="91.45703125">Returns</th><th>Purpose</th></tr></thead><tbody><tr><td><code>triggerMintingForMyBoostRequest</code></td><td><code>BoostId</code></td><td><code>text</code></td><td>Start direct minting (no booster)</td></tr><tr><td><code>claimMintedCKBTC</code></td><td><code>BoostId</code></td><td><code>text</code></td><td>Complete direct minting</td></tr></tbody></table>

#### Additional Query Functions

<table><thead><tr><th width="184.14453125">Function</th><th>Parameters</th><th>Returns</th><th>Purpose</th></tr></thead><tbody><tr><td><code>getBoosterAccount</code></td><td><code>principal</code></td><td><code>opt BoosterAccount</code> (query)</td><td>Get booster account by principal</td></tr><tr><td><code>getAllBoosterAccounts</code></td><td>none</td><td><code>vec BoosterAccount</code> (query)</td><td>Get all booster accounts</td></tr><tr><td><code>getPendingBoostRequests</code></td><td>none</td><td><code>vec BoostRequest</code> (query)</td><td>Get all pending requests</td></tr><tr><td><code>getBoostedRequests</code></td><td>none</td><td><code>vec BoostRequest</code> (query)</td><td>Get all boosted requests</td></tr><tr><td><code>getMintingRequests</code></td><td>none</td><td><code>vec BoostRequest</code> (query)</td><td>Get all minting requests</td></tr></tbody></table>


# Faucet

<figure><img src="https://2801405176-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUSJarEbyoQmHpvKQvoDw%2Fuploads%2FaV7jzV5vFNKBkaLq4jvL%2Fimage.png?alt=media&amp;token=7d3c14b3-cfde-4ab4-ad2d-fd87b467ac8c" alt=""><figcaption></figcaption></figure>

Need some play-money to experiment with **ckBoost** and other BTC-related dApps on the Internet Computer? Our [Faucet](https://testnet-faucet.ckboost.com/) hands out both sides of the bridge:

* **Testnet4 BTC** – Bitcoin running on the “Testnet4” network, perfect for trial deposits without risking real coins.
* [**ckTESTBTC**](https://dashboard.internetcomputer.org/testbtc) – The testnet version of ckBTC, minted on ICP, usable in local canister environments and staging dApps.

### How to get Testnet4 BTC&#x20;

1. Navigate to <https://testnet-faucet.ckboost.com/>&#x20;

<figure><img src="https://2801405176-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUSJarEbyoQmHpvKQvoDw%2Fuploads%2F0spTSnNCnBgMB4EN7Z1G%2Fimage.png?alt=media&amp;token=74d0b87f-b2d8-4dd9-8805-34e2f9fc8fbe" alt=""><figcaption></figcaption></figure>

2. Click on 'Get ckTESTBTC'&#x20;

<figure><img src="https://2801405176-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUSJarEbyoQmHpvKQvoDw%2Fuploads%2FfQkHyxmnTBUr1tPxBCDt%2Fimage.png?alt=media&amp;token=fca9e730-ea47-41be-8019-32b8eb3a781e" alt=""><figcaption></figcaption></figure>

3. Enter your wallet's Principal ID and click 'Request Funds'&#x20;
4. Wait for success message to appear

<figure><img src="https://2801405176-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUSJarEbyoQmHpvKQvoDw%2Fuploads%2FfRKSa9y7PaBRqb5RtDix%2Fimage.png?alt=media&amp;token=d37ca69e-36a5-4d5a-8a9b-adb403111498" alt=""><figcaption></figcaption></figure>

5. Make sure your wallet is tracking ckTESTBTC. If it's not - you can add ckTESTBTC to your wallet by specifying ledger canister ID to tracked token list. Here's example for Plug wallet:&#x20;

<figure><img src="https://2801405176-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUSJarEbyoQmHpvKQvoDw%2Fuploads%2FD29OMIDEU0MG0jUdAvGL%2Fimage.png?alt=media&amp;token=76451aeb-9cc2-46e3-b5f5-5b7f858c79be" alt=""><figcaption></figcaption></figure>

* Click 'Manage' in the end of the list;&#x20;
* Add custom token icon in the top right corner&#x20;

<figure><img src="https://2801405176-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUSJarEbyoQmHpvKQvoDw%2Fuploads%2FtNhM42QMMho6mmuexbli%2Fimage.png?alt=media&amp;token=2be27a55-f468-4145-a02a-41559b988295" alt=""><figcaption></figcaption></figure>

* In the Custom Token drawer, enter following values:

  * Canister ID: **mc6ru-gyaaa-aaaar-qaaaq-cai**
  * Token Standard: ICRC-1

  <figure><img src="https://2801405176-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUSJarEbyoQmHpvKQvoDw%2Fuploads%2FZpOTzBQ1gJPWv9jYtYYt%2Fimage.png?alt=media&amp;token=bf927599-3ce4-4ba0-96a6-465472a822e5" alt=""><figcaption></figcaption></figure>
* Chain Key Testnet Bitcoin (ckTESTBTC) will appear in the token list. Have fun&#x20;

  <figure><img src="https://2801405176-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUSJarEbyoQmHpvKQvoDw%2Fuploads%2Fc5tCYUcwyRXNscSfWoKp%2Fimage.png?alt=media&amp;token=d3fb259a-4ee3-467d-a2d1-183e99db8246" alt=""><figcaption></figcaption></figure>


# 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! 🚀*


# Client Package

## @ckboost/client SDK

### Overview

The `@ckboost/client` SDK provides a simple, type-safe way to integrate CKBoost acceleration services into your dApp. CKBoost reduces ckBTC conversion times from 1 hour (6 confirmations) to 7-10 minutes (1-2 confirmations) through a network of liquidity providers. We are planning to expend ckBoost and support other chain-key tokens (ckETH, in the future ckSOL, etc)&#x20;

#### Key Features

* 🚀 **Fast Integration**: Simple API with just two main functions
* 📝 **TypeScript First**: Full type safety and excellent developer experience
* ⚡ **Real-time Monitoring**: Track boost request status changes
* 🔒 **Secure**: Built on Internet Computer Protocol (ICP)
* 🎯 **dApp Ready**: Designed specifically for frontend integration

### Installation

```bash
npm install @ckboost/client
```

```bash
yarn add @ckboost/client
```

```bash
pnpm add @ckboost/client
```

### Quick Start

```typescript
import { ckTESTBTCClient, BoostStatus } from '@ckboost/client';

// Initialize client
const client = new ckTESTBTCClient({
  host: 'https://icp-api.io',
  timeout: 30000
});

// Create a boost request
const result = await client.generateDepositAddress({
  amount: '0.01',              // 0.01 ckTESTBTC
  maxFeePercentage: 1.5        // 1.5% maximum fee
});

if (result.success) {
  const { requestId, address, explorerUrl } = result.data;
  
  // Show deposit address to user
  console.log(`Send Bitcoin to: ${address}`);
  console.log(`Track at: ${explorerUrl}`);
  
  // Monitor status
  const statusResult = await client.getBoostRequest(requestId);
  if (statusResult.success) {
    console.log(`Status: ${statusResult.data.status}`);
  }
}
```

### API Reference

#### Client Initialization

**`ckTESTBTCClient`**

Creates a new client instance for ckTESTBTC (Bitcoin testnet).

```typescript
import { ckTESTBTCClient } from '@ckboost/client';

const client = new ckTESTBTCClient(config?: ClientConfig);
```

**Parameters:**

| Parameter | Type           | Default | Description                   |
| --------- | -------------- | ------- | ----------------------------- |
| `config`  | `ClientConfig` | `{}`    | Optional client configuration |

**ClientConfig:**

```typescript
interface ClientConfig {
  host?: string;     // ICP host URL (default: 'https://icp-api.io')
  timeout?: number;  // Request timeout in ms (default: 30000)
}
```

#### Core Methods

**`generateDepositAddress()`**

Creates a new boost request and returns deposit information.

```typescript
async generateDepositAddress(
  params: DepositAddressParams
): Promise<ApiResponse<DepositInfo>>
```

**Parameters:**

```typescript
interface DepositAddressParams {
  amount: string;                    // Amount in ckTESTBTC (e.g., "0.01")
  maxFeePercentage: number;          // Maximum fee as percentage (e.g., 1.5)
  confirmationsRequired?: number;    // Override default confirmations
  preferredBooster?: string;         // Specific booster principal ID
}
```

**Returns:**

```typescript
interface DepositInfo {
  requestId: string;           // Unique request identifier
  address: string;             // Bitcoin deposit address
  amount: string;              // Amount in ckTESTBTC
  amountRaw: string;           // Amount in satoshis
  maxFeePercentage: number;    // Maximum fee percentage
  explorerUrl: string;         // Block explorer URL
}
```

**`getBoostRequest()`**

Retrieves detailed information about a specific boost request.

```typescript
async getBoostRequest(
  requestId: string
): Promise<ApiResponse<BoostRequest>>
```

**Parameters:**

| Parameter   | Type     | Description                   |
| ----------- | -------- | ----------------------------- |
| `requestId` | `string` | The unique request identifier |

**Returns:**

```typescript
interface BoostRequest {
  id: string;                    // Request ID
  status: BoostStatus;           // Current status
  amount: string;                // Requested amount in ckTESTBTC
  receivedAmount: string;        // Amount received so far
  maxFeePercentage: number;      // Maximum fee percentage
  confirmationsRequired: number;  // Required confirmations
  depositAddress?: string;       // Bitcoin deposit address
  booster?: string;             // Assigned booster principal
  createdAt: number;            // Creation timestamp (ms)
  updatedAt: number;            // Last update timestamp (ms)
}
```

**`getPendingBoostRequests()`**

Retrieves all pending boost requests.

```typescript
async getPendingBoostRequests(): Promise<ApiResponse<BoostRequest[]>>
```

#### Utility Methods

**`getTokenConfig()`**

Returns the current token configuration.

```typescript
getTokenConfig(): TokenConfig
```

**Returns:**

```typescript
interface TokenConfig {
  token: SupportedToken;         // Token type
  minimumAmount: string;         // Minimum boost amount
  maximumAmount: string;         // Maximum boost amount
  standardFee: string;           // Standard fee amount
  confirmationsRequired: number; // Default confirmations
  decimals: number;             // Token decimals (8 for Bitcoin)
  isTestnet: boolean;           // Whether this is testnet
  blockExplorerUrl: string;     // Block explorer base URL
}
```

**`rawToTokenAmount()`**

Converts raw amount (satoshis) to token amount (ckTESTBTC).

```typescript
rawToTokenAmount(rawAmount: string | bigint): string
```

**`tokenToRawAmount()`**

Converts token amount (ckTESTBTC) to raw amount (satoshis).

```typescript
tokenToRawAmount(tokenAmount: string): string
```

### Types Reference

#### Enums

**`BoostStatus`**

```typescript
enum BoostStatus {
  PENDING = 'pending',       // Waiting for Bitcoin deposit
  ACTIVE = 'active',         // Processing the boost
  COMPLETED = 'completed',   // ckTESTBTC delivered
  CANCELLED = 'cancelled'    // Request cancelled
}
```

**`SupportedToken`**

```typescript
enum SupportedToken {
  CK_TEST_BTC = 'ckTESTBTC'
}
```

**`CKBoostErrorType`**

```typescript
enum CKBoostErrorType {
  INVALID_AMOUNT = 'INVALID_AMOUNT',
  NETWORK_ERROR = 'NETWORK_ERROR',
  REQUEST_NOT_FOUND = 'REQUEST_NOT_FOUND',
  CANISTER_ERROR = 'CANISTER_ERROR',
  VALIDATION_ERROR = 'VALIDATION_ERROR',
  UNKNOWN_ERROR = 'UNKNOWN_ERROR'
}
```

#### Response Types

**`ApiResponse<T>`**

All API methods return this discriminated union type:

```typescript
type ApiResponse<T> = 
  | { success: true; data: T; }
  | { success: false; error: CKBoostError; };

interface CKBoostError {
  type: CKBoostErrorType;
  message: string;
  details?: any;
}
```

### Examples

#### Basic Integration

```typescript
import { ckTESTBTCClient, BoostStatus } from '@ckboost/client';

class BitcoinAccelerator {
  private client = new ckTESTBTCClient();

  async createBoost(amount: string, maxFee: number) {
    const result = await this.client.generateDepositAddress({
      amount,
      maxFeePercentage: maxFee
    });

    if (result.success) {
      return {
        success: true,
        depositAddress: result.data.address,
        requestId: result.data.requestId,
        explorerUrl: result.data.explorerUrl
      };
    } else {
      return {
        success: false,
        error: result.error.message
      };
    }
  }

  async checkStatus(requestId: string) {
    const result = await this.client.getBoostRequest(requestId);
    
    if (result.success) {
      const request = result.data;
      return {
        status: request.status,
        progress: {
          requested: request.amount,
          received: request.receivedAmount,
          percentage: (parseFloat(request.receivedAmount) / parseFloat(request.amount)) * 100
        },
        isComplete: request.status === BoostStatus.COMPLETED
      };
    }
    
    return { error: result.error.message };
  }
}
```

#### React Hook Integration

```typescript
import { useState, useEffect } from 'react';
import { ckTESTBTCClient, BoostRequest, BoostStatus } from '@ckboost/client';

export function useBoostRequest(requestId?: string) {
  const [request, setRequest] = useState<BoostRequest | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const client = new ckTESTBTCClient();

  useEffect(() => {
    if (!requestId) return;

    const pollStatus = async () => {
      setLoading(true);
      setError(null);

      try {
        const result = await client.getBoostRequest(requestId);
        
        if (result.success) {
          setRequest(result.data);
        } else {
          setError(result.error.message);
        }
      } catch (err) {
        setError('Failed to fetch boost request');
      } finally {
        setLoading(false);
      }
    };

    pollStatus();
    
    // Poll every 10 seconds until complete
    const interval = setInterval(() => {
      if (request?.status !== BoostStatus.COMPLETED && 
          request?.status !== BoostStatus.CANCELLED) {
        pollStatus();
      }
    }, 10000);

    return () => clearInterval(interval);
  }, [requestId, request?.status]);

  return { request, loading, error };
}
```

#### Complete dApp Integration

```typescript
import { ckTESTBTCClient, BoostStatus } from '@ckboost/client';

class CKBoostService {
  private client: ckTESTBTCClient;
  private activeRequests = new Map<string, NodeJS.Timeout>();

  constructor() {
    this.client = new ckTESTBTCClient({
      host: 'https://icp-api.io',
      timeout: 30000
    });
  }

  async createBoostRequest(amount: string, maxFeePercentage: number) {
    // Validate amount first
    const config = this.client.getTokenConfig();
    const amountNum = parseFloat(amount);
    const minAmount = parseFloat(config.minimumAmount);
    const maxAmount = parseFloat(config.maximumAmount);

    if (amountNum < minAmount || amountNum > maxAmount) {
      return {
        success: false,
        error: `Amount must be between ${minAmount} and ${maxAmount} ckTESTBTC`
      };
    }

    const result = await this.client.generateDepositAddress({
      amount,
      maxFeePercentage
    });

    if (result.success) {
      // Start monitoring this request
      this.startMonitoring(result.data.requestId);
      
      return {
        success: true,
        data: result.data
      };
    }

    return {
      success: false,
      error: result.error.message
    };
  }

  private startMonitoring(requestId: string, onUpdate?: (request: BoostRequest) => void) {
    // Clear existing timeout for this request
    if (this.activeRequests.has(requestId)) {
      clearTimeout(this.activeRequests.get(requestId)!);
    }

    const poll = async () => {
      const result = await this.client.getBoostRequest(requestId);
      
      if (result.success) {
        const request = result.data;
        
        // Notify about update
        if (onUpdate) {
          onUpdate(request);
        }

        // Continue polling if not in final state
        if (request.status !== BoostStatus.COMPLETED && 
            request.status !== BoostStatus.CANCELLED) {
          const timeout = setTimeout(poll, 10000); // Poll every 10 seconds
          this.activeRequests.set(requestId, timeout);
        } else {
          this.activeRequests.delete(requestId);
        }
      }
    };

    // Start immediate poll
    poll();
  }

  stopMonitoring(requestId: string) {
    if (this.activeRequests.has(requestId)) {
      clearTimeout(this.activeRequests.get(requestId)!);
      this.activeRequests.delete(requestId);
    }
  }

  destroy() {
    // Clean up all active monitoring
    this.activeRequests.forEach(timeout => clearTimeout(timeout));
    this.activeRequests.clear();
  }
}
```

### Error Handling

#### Error Types

The SDK provides specific error types to help you handle different scenarios:

```typescript
import { CKBoostErrorType } from '@ckboost/client';

async function handleBoostRequest() {
  const result = await client.generateDepositAddress({
    amount: '0.01',
    maxFeePercentage: 1.5
  });

  if (!result.success) {
    switch (result.error.type) {
      case CKBoostErrorType.INVALID_AMOUNT:
        // Show amount validation error to user
        alert('Please enter a valid amount between the minimum and maximum limits');
        break;
        
      case CKBoostErrorType.NETWORK_ERROR:
        // Show network error and retry option
        alert('Network error. Please check your connection and try again');
        break;
        
      case CKBoostErrorType.CANISTER_ERROR:
        // Backend service error
        alert('Service temporarily unavailable. Please try again later');
        break;
        
      default:
        // Generic error handling
        alert(`Error: ${result.error.message}`);
    }
  }
}
```

#### Best Practices

1. **Always check the `success` property** before accessing `data`
2. **Provide user-friendly error messages** based on error types
3. **Implement retry logic** for network errors
4. **Validate amounts** before making requests
5. **Monitor request status** until completion

### Configuration

#### Canister IDs

The SDK includes the required canister IDs:

```typescript
import { ckTESTBTC_CANISTER_IDS } from '@ckboost/client';

console.log('Backend Canister:', ckTESTBTC_CANISTER_IDS.CKBOOST_BACKEND);
console.log('Ledger Canister:', ckTESTBTC_CANISTER_IDS.CKTESTBTC_LEDGER);
```

#### Network Configuration

For production applications, use the default configuration:

```typescript
const client = new ckTESTBTCClient({
  host: 'https://icp-api.io',  // Production ICP host
  timeout: 30000               // 30 second timeout
});
```

For development, you might want to use a local replica:

```typescript
const client = new ckTESTBTCClient({
  host: 'http://localhost:4943',  // Local dfx replica
  timeout: 10000                  // Shorter timeout for local testing
});
```

### Monitoring and Real-time Updates

#### Polling Strategy

For production applications, implement efficient polling:

```typescript
class BoostMonitor {
  private intervals = new Map<string, NodeJS.Timeout>();

  startMonitoring(requestId: string, callback: (request: BoostRequest) => void) {
    let attempts = 0;
    const maxAttempts = 360; // Monitor for 1 hour max (10s intervals)
    
    const poll = async () => {
      attempts++;
      
      const result = await client.getBoostRequest(requestId);
      if (result.success) {
        const request = result.data;
        callback(request);
        
        // Stop if complete or max attempts reached
        if (request.status === BoostStatus.COMPLETED || 
            request.status === BoostStatus.CANCELLED ||
            attempts >= maxAttempts) {
          this.stopMonitoring(requestId);
          return;
        }
      }
      
      // Continue polling with exponential backoff
      const delay = Math.min(10000 + (attempts * 1000), 30000);
      const timeout = setTimeout(poll, delay);
      this.intervals.set(requestId, timeout);
    };
    
    poll();
  }
  
  stopMonitoring(requestId: string) {
    const interval = this.intervals.get(requestId);
    if (interval) {
      clearTimeout(interval);
      this.intervals.delete(requestId);
    }
  }
}
```

#### WebSocket Alternative

For real-time updates, consider implementing WebSocket connections to the backend canister (when available) instead of polling.

### Troubleshooting

#### Common Issues

**Import Errors**

```typescript
// ❌ Don't do this
import CKBoostClient from '@ckboost/client';

// ✅ Do this
import { ckTESTBTCClient } from '@ckboost/client';
```

**Type Errors**

Make sure you have TypeScript configured properly:

```json
// tsconfig.json
{
  "compilerOptions": {
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  }
}
```

**Network Errors**

If you're getting network errors:

1. Check your internet connection
2. Verify the ICP host URL is correct
3. Ensure the canister IDs are valid
4. Try increasing the timeout value

### Support

* **Documentation**: [docs.ckboost.com](https://docs.ckboost.com)
* **GitHub**: [github.com/ckboost/ckboost-packages](https://github.com/ckboost/ckboost-packages)
* **Issues**: Report bugs and feature requests on GitHub


