Booster Package
Booster Integration Guide
Table of Contents
Introduction
Understanding CKBoost
Installation
Quick Start
Core Concepts
Step-by-Step Integration
API Reference
Advanced Usage
Best Practices
Troubleshooting
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:
Users submit boost requests when they need faster ckBTC conversion
Liquidity providers (you) evaluate and accept requests based on risk parameters
Acceleration reduces conversion time from 1 hour to 7-10 minutes
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
npm install @ckboost/booster
Dependencies
The package automatically includes all necessary dependencies:
@dfinity/agent
- ICP communication@dfinity/identity
- Identity management@dfinity/principal
- Principal handlingbig.js
- Precise decimal calculations
Quick Start
Here's a minimal example to get you started:
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:
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:
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
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
// 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
// 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
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
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
new ckTestBTCBooster(mnemonics: string, host?: string)
Creates a new booster instance.
Parameters:
mnemonics
- Your 12-word recovery phrasehost
- ICP network host (optional, defaults to mainnet)
Initialization Methods
initialize()
await booster.initialize(): Promise<void>
Initializes the connection to ICP and sets up the actor. Must be called before other methods.
Account Management
registerBoosterAccount()
await booster.registerBoosterAccount(): Promise<any>
Registers your account as a liquidity provider. Only needs to be called once.
getBoosterAccount()
await booster.getBoosterAccount(): Promise<BoosterAccount | null>
Retrieves your booster account information.
updateBoosterDeposit(amount)
await booster.updateBoosterDeposit(amount: bigint): Promise<any>
Updates the amount of ckTESTBTC you have available for boosting.
Boost Operations
getPendingBoostRequests()
await booster.getPendingBoostRequests(): Promise<BoostRequest[]>
Retrieves all pending boost requests from users.
acceptBoostRequest(requestId)
await booster.acceptBoostRequest(requestId: bigint): Promise<any>
Accepts a specific boost request.
Token Operations
getBalance()
await booster.getBalance(): Promise<bigint>
Gets your ckTESTBTC balance in satoshis.
transfer(to, amount)
await booster.transfer(to: string, amount: bigint): Promise<any>
Transfers ckTESTBTC to another account.
approve(spender, amount)
await booster.approve(spender: string, amount: bigint): Promise<any>
Approves another account to spend your ckTESTBTC.
Utility Methods
formatBTC(satoshis)
booster.formatBTC(satoshis: bigint): string
Converts satoshis to BTC decimal format.
parseBTC(btc)
booster.parseBTC(btc: string): bigint
Converts BTC decimal string to satoshis.
getPrincipal()
booster.getPrincipal(): Principal
Returns your principal identifier.
Advanced Usage
Automated Booster Bot
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
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
Secure Mnemonic Storage
// ❌ Don't hardcode mnemonics
const booster = new ckTestBTCBooster('word1 word2 word3...')
// ✅ Use environment variables
const booster = new ckTestBTCBooster(process.env.BOOSTER_MNEMONIC!)
Error Handling
// ✅ 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
Batch Operations
// ✅ 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)
)
)
Caching
// ✅ 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
Logging
// ✅ 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()
})
Metrics
// ✅ 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
Error: Cannot find module '@ckboost/booster'
Solution:
npm install @ckboost/booster
# or if using yarn
yarn add @ckboost/booster
Identity/Authentication Errors
Error: Failed to authenticate with agent
Solutions:
Verify your mnemonic phrase is correct
Check network connectivity
Ensure proper host configuration
// Try with explicit host
const booster = new ckTestBTCBooster(
mnemonics,
'https://icp0.io'
)
Insufficient Funds
Error: Insufficient funds for operation
Solutions:
Check your ckTESTBTC balance
Ensure you have approved enough tokens
Verify your deposit amount
// 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
Error: Boost request has already been accepted
This is normal - another booster accepted the request first. Your system should handle this gracefully:
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:
// 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:
Check Network Latency
const start = Date.now()
await booster.getPendingBoostRequests()
console.log(`Request took ${Date.now() - start}ms`)
Optimize Polling Frequency
// Don't poll too frequently
const POLL_INTERVAL = 30000 // 30 seconds minimum
Use Connection Pooling
// 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:
https://github.com/ckboost/ckboost-packages/tree/main/sample
Happy boosting! 🚀
Last updated