Wrap/Unwrap BTC

Convert BTC to frBTC for use in Alkanes DeFi

frBTC (Fractional BTC) is a synthetic representation of Bitcoin on the Alkanes protocol. This tutorial covers how to wrap BTC to frBTC and unwrap frBTC back to BTC.

Overview

The frBTC contract at [32, 0] allows users to:

Wrap BTC- Send BTC to the signer address to mint frBTC
Unwrap frBTC- Burn frBTC to receive BTC at a specified address
Query Signer- Get the current signer public key
Premium Fee- Small fee deducted on wrap (configurable)

How Wrapping Works

The wrapping process verifies Bitcoin transactions on-chain:

1.User sends BTC to the signer's p2tr address
2.User calls wrap (opcode 77) on frBTC contract
3.Contract verifies BTC was sent to signer
4.Contract mints equivalent frBTC (minus premium)
5.frBTC is sent to the caller

How Unwrapping Works

The unwrap process creates payment records for the signer:

1.User calls unwrap (opcode 78) with frBTC
2.Contract burns the frBTC
3.Contract creates payment record for the signer
4.Signer processes payment and sends BTC
5.Payment is marked complete

Wrapping BTC

Use the alkanes-cli wrap-btc command:

# Wrap 1 BTC (100,000,000 satoshis) to frBTC
alkanes-cli -p regtest \
  --wallet-file ~/.alkanes/wallet.json \
  --passphrase "your-passphrase" \
  alkanes wrap-btc \
  100000000 \
  --to p2tr:0 \
  --from p2tr:0 \
  --mine \
  --change p2tr:0 \
  -y

# The wrap-btc command:
# 1. Creates a transaction sending BTC to the frBTC signer
# 2. Includes a protostone calling wrap (opcode 77) on [32, 0]
# 3. Mines the transaction (regtest only)
# 4. Returns frBTC to your address

# Check your frBTC balance
alkanes-cli -p regtest \
  --wallet-file ~/.alkanes/wallet.json \
  --passphrase "your-passphrase" \
  alkanes getbalance

Unwrapping frBTC

Call the unwrap opcode on the frBTC contract:

# Unwrap frBTC to BTC
# Opcode 78 = Unwrap
# Args: vout (output index), amount_requested

alkanes-cli -p regtest \
  --wallet-file ~/.alkanes/wallet.json \
  --passphrase "your-passphrase" \
  alkanes execute "[32,0,78,0,50000000]:v0:v0" \
  --inputs "32:0:50000000" \
  --from p2tr:0 \
  --fee-rate 1 \
  --mine \
  -y

# Parameters:
# - 32,0: frBTC contract at [32, 0]
# - 78: Unwrap opcode
# - 0: vout (output index in tx for signer)
# - 50000000: Amount to unwrap (0.5 BTC in satoshis)
# --inputs 32:0:50000000: Send 50M frBTC to the contract

# The unwrap creates a payment record. The actual BTC
# is sent by the signer in a separate transaction.

Query Commands

Check frBTC state and balances:

# Get frBTC total supply (opcode 105)
alkanes-cli -p regtest alkanes simulate "32:0:105"

# Get signer public key (opcode 103)
alkanes-cli -p regtest alkanes simulate "32:0:103"

# Get current premium (opcode 104)
alkanes-cli -p regtest alkanes simulate "32:0:104"

# Get pending payments (opcode 101)
alkanes-cli -p regtest alkanes simulate "32:0:101"

# Get token name (opcode 99)
alkanes-cli -p regtest alkanes simulate "32:0:99"

# Get token symbol (opcode 100)
alkanes-cli -p regtest alkanes simulate "32:0:100"

Premium Fee

The frBTC contract charges a small premium on wraps. The premium is measured in parts per 100,000,000 (satoshis per BTC).

// Premium calculation in fr-btc contract
fn exchange(&self, context: &Context) -> Result<AlkaneTransfer> {
    // Get BTC amount sent to signer
    let payout = self.compute_output(&tx);

    // Apply premium (default: 100,000 = 0.1%)
    let premium = self.premium();
    let adjusted_payout = if premium > 0 && payout > 0 {
        // Fee = payout * premium / 100_000_000
        let fee = (payout * premium) / 100_000_000;
        payout.saturating_sub(fee)
    } else {
        payout
    };

    // Mint frBTC with adjusted amount
    self.mint(&context, adjusted_payout)
}

// Example: 1 BTC with 0.1% premium
// payout = 100,000,000 sats
// premium = 100,000 (0.1%)
// fee = 100,000,000 * 100,000 / 100,000,000 = 100,000 sats
// adjusted_payout = 99,900,000 sats of frBTC

Storage Layout

PathDescription
/signerSigner public key (x-only, 32 bytes)
/premiumPremium fee in parts per 100M
/totalsupplyTotal frBTC supply
/seen/{txid}Processed transaction IDs
/payments/byheight/{h}Pending payment records

frBTC Opcodes

OpcodeNameDescription
0InitializeSet up the contract with auth token
1SetSignerUpdate the signer pubkey (owner only)
4SetPremiumUpdate the premium fee (owner only)
77WrapMint frBTC for BTC sent to signer
78UnwrapBurn frBTC and create payment record
99GetNameReturn 'frBTC'
100GetSymbolReturn 'frBTC'
101GetPendingPaymentsGet all pending payment records
103GetSignerReturn signer pubkey
104GetPremiumReturn current premium
105GetTotalSupplyReturn total supply

frBTC Contract Structure

Key components of the frBTC contract:

// Simplified frBTC contract structure
use alkanes_runtime::{
    declare_alkane, message::MessageDispatch,
    runtime::AlkaneResponder, storage::StoragePointer,
    auth::AuthenticatedResponder,
};
use alkanes_std_factory_support::MintableToken;

#[derive(Default)]
pub struct SyntheticBitcoin(());

impl AlkaneResponder for SyntheticBitcoin {}
impl AuthenticatedResponder for SyntheticBitcoin {}
impl MintableToken for SyntheticBitcoin {}

#[derive(MessageDispatch)]
enum SyntheticBitcoinMessage {
    #[opcode(0)]
    Initialize,

    #[opcode(1)]
    SetSigner { vout: u128 },

    #[opcode(4)]
    SetPremium { premium: u128 },

    #[opcode(77)]
    Wrap,

    #[opcode(78)]
    Unwrap { vout: u128, amount_requested: u128 },

    #[opcode(99)]
    #[returns(String)]
    GetName,

    #[opcode(103)]
    #[returns(Vec<u8>)]
    GetSigner,

    #[opcode(105)]
    #[returns(u128)]
    GetTotalSupply,
}

impl SyntheticBitcoin {
    // Wrap: verify BTC tx and mint frBTC
    fn wrap(&self) -> Result<CallResponse> {
        let context = self.context()?;
        let tx = self.transaction_object()?;

        // Prevent replay
        self.observe_transaction(&tx)?;

        // Calculate BTC sent to signer
        let payout = self.compute_output(&tx);

        // Apply premium fee
        let premium = self.premium();
        let fee = (payout * premium) / 100_000_000;
        let adjusted = payout.saturating_sub(fee);

        // Mint frBTC
        let mut response = CallResponse::forward(&context.incoming_alkanes);
        response.alkanes.0.push(self.mint(&context, adjusted)?);
        Ok(response)
    }

    // Unwrap: burn frBTC and create payment record
    fn unwrap(&self, vout: u128, amount: u128) -> Result<CallResponse> {
        let context = self.context()?;

        // Only EOA can unwrap
        if context.caller != AlkaneId::default() {
            return Err(anyhow!("must be called by EOA"));
        }

        // Get frBTC sent and calculate burn amount
        let frbtc_sent = self.burn_input(&context)?;
        let actual_burn = min(amount, frbtc_sent);

        // Create payment record for signer
        self.burn(&context, vout as usize, actual_burn)?;

        // Decrease supply
        self.decrease_total_supply(actual_burn)?;

        // Return leftover frBTC
        let refund = frbtc_sent - actual_burn;
        let mut response = CallResponse::default();
        if refund > 0 {
            response.alkanes.0.push(AlkaneTransfer {
                id: context.myself,
                value: refund,
            });
        }
        Ok(response)
    }
}

declare_alkane! {
    impl AlkaneResponder for SyntheticBitcoin {
        type Message = SyntheticBitcoinMessage;
    }
}

Security Considerations

frBTC is backed 1:1 by BTC held by the signer
Transaction replay is prevented by tracking seen txids
Only EOA (not contracts) can call unwrap
Unwrap creates payment records, actual BTC is sent off-chain
Premium fee can be adjusted by owner with auth token

TypeScript Integration

Use the TS SDK to interact with frBTC:

import { AlkanesProvider } from '@alkanes/ts-sdk';

// Initialize provider
const provider = new AlkanesProvider({
  network: 'mainnet',  // or 'regtest' for local development
  rpcUrl: 'https://mainnet.subfrost.io/v4/jsonrpc',
});
await provider.initialize();

// Load wallet from mnemonic (for transactions)
provider.walletLoadMnemonic('your twelve word mnemonic...');
const addresses = provider.walletGetAddresses('p2tr', 0, 1);
const walletAddress = addresses[0].address;

// Wrap BTC to frBTC using the typed method
const wrapResult = await provider.frbtcWrapTyped({
  amount: BigInt(100000000),  // 1 BTC in satoshis
  toAddress: walletAddress,
  fromAddress: walletAddress,
  feeRate: 1,
  traceEnabled: true,
  mineEnabled: true,  // Auto-mine on regtest
  autoConfirm: true,
});
console.log('Wrap TXID:', wrapResult.reveal_txid);

// Get frBTC balance for an address
const balances = await provider.alkanes.getBalance(walletAddress);
const frbtc = balances.find(b =>
  b.alkane_id?.block === 32 && b.alkane_id?.tx === 0
);
console.log('frBTC balance:', frbtc?.balance);

// Get frBTC total supply using simulate
const result = await provider.metashrew.view(
  'simulate',
  '0x2096ce382a0602000665653001', // [32,0,105] encoded
  'latest'
);
// Parse result as u128 little-endian

// Query signer address
const signerResult = await provider.metashrew.view(
  'simulate',
  '0x2096ce382a0602006765673001', // [32,0,103] encoded
  'latest'
);