> For the complete documentation index, see [llms.txt](https://docs.bitsafe.finance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.bitsafe.finance/developers/integration-guides.md).

# Integration Guides

> ⚠️ **API Disclaimer:** CBTC APIs are subject to change. Label all examples with the SDK version and DAR version they were tested against.

***

## Overview

This page provides integration patterns for common CBTC use cases. Each pattern includes architecture notes, key considerations, and pointers to relevant code. For API details, see the [API Reference](https://docs.bitsafe.finance/developers/cbtc-api-reference). For authentication setup, see the [Authentication Guide](https://docs.bitsafe.finance/developers/cbtc-authentication).

***

## Integration Pattern 1: DeFi Protocol

**Use case:** Build a DEX, lending platform, or liquidity pool using CBTC as collateral.

### Architecture

1. Your protocol runs on a Canton participant node with CBTC DAR files installed
2. Users deposit CBTC into your protocol's Canton party via a `Transfer` choice
3. Your protocol logic (Daml contracts) manages positions, collateral, and settlement
4. Users withdraw CBTC back to their own party when exiting

### Key Considerations

* **UTXO management:** Each transfer creates UTXOs. Keep below 10 per party. Use `cbtc-lib` consolidation functions.
* **Instrument ID:** Fetch dynamically - see [Instrument ID Management](https://docs.bitsafe.finance/developers/instrument-id-management)
* **Privacy:** Canton transactions are private by default. Only parties to a contract see its details. This eliminates MEV.
* **Transfer costs:** \~$3-5 per CBTC transfer on Canton currently. Factor this into your protocol economics.

### Example Partners

* **Bron** - BTC-CBTC and CC-CBTC swapping on Canton
* **Elk Capital Markets / Triangle** - OTC and app-based CBTC trading
* **Silvana** - DEX/trading venue on Canton *(coming soon)*

***

## Integration Pattern 2: Wallet or Custody Solution

**Use case:** Support CBTC in an institutional-grade wallet or custody platform.

### Architecture

1. Wallet connects to a Canton participant via the Ledger API
2. Authentication via OIDC (Keycloak supported, Auth0 community example available)
3. CBTC balances queried via `state-queries` endpoint
4. Transfers executed via `Transfer` choice on CBTC token contracts

### Supported Wallets (Current Ecosystem)

* **Loop Wallet** - Canton-native wallet with CBTC support
* **Console / Zoro Wallet** - Canton wallet with API access
* **Bron Wallet** - Multi-party wallet with testnet support
* **WalletConnect** - For dApp-to-wallet connections

### Key Considerations

* **External signing:** Available for integration with custody providers (DFNS, Fordefi, Ledger)
* **Party creation at scale:** If creating 10+ parties, use the Ledger API directly rather than wallet UI - see [Canton docs](https://docs.digitalasset.com/build/3.4/tutorials/json-api/canton_and_the_json_ledger_api_ts.html#allocating-a-party)
* **CORS:** If your wallet makes browser-based API calls, configure CORS on your ingress

***

## Integration Pattern 3: Trading System

**Use case:** Build spot trading, perpetual contracts, options, or structured products with CBTC.

### Why Canton for Trading

* **No public mempool** - positions are not visible to other participants, eliminating front-running and sandwich attacks (MEV)
* **Private transactions** - only parties to a trade see the details
* **Audit-ready** - Canton's privacy model supports selective disclosure for compliance

### Architecture

1. Trading engine runs as Daml contracts on Canton
2. CBTC used as settlement or collateral asset
3. Counterparty discovery and matching handled by your protocol
4. Settlement is atomic - either both sides complete or neither does

### Example: Options on CBTC

CBTC holders can write covered CALL options, earning premium income while maintaining BTC exposure. Settlement uses Canton's atomic dual-token transfer - the buyer receives the underlying asset while the seller receives payment, atomically.

### DvP Settlement Using Allocations

For atomic delivery-versus-payment, `cbtc-lib` provides the `cbtc::allocation` module, which implements the Canton Token Standard allocation lifecycle. This is the mechanism behind the atomic settlement described above.

**How it differs from a standard transfer.** The two-phase `transfer` / `accept` flow described in the [Quick Start](https://docs.bitsafe.finance/developers/cbtc-quick-start) is **free-of-payment (FOP)**: the sender offers CBTC, the receiver accepts, and nothing is exchanged in return. There is no linkage to a second leg. An **allocation** instead locks CBTC into one leg of a multi-leg settlement that a third party settles atomically, so the CBTC only moves if the other leg moves too.

|                        | FOP transfer (`cbtc::transfer` + `cbtc::accept`) | DvP allocation (`cbtc::allocation`)                   |
| ---------------------- | ------------------------------------------------ | ----------------------------------------------------- |
| **Parties**            | Sender, receiver                                 | Sender, receiver, **settlement executor** (the venue) |
| **Settled by**         | The receiver, by accepting                       | The executor, across all legs at once                 |
| **Atomicity**          | Single leg only                                  | All legs settle together or none do                   |
| **Sender can reclaim** | Cancel the offer (`cbtc::cancel_offers`)         | Withdraw the allocation before settlement             |
| **Deadlines**          | `execute_before`                                 | `allocate_before`, then `settle_before`               |

**Lifecycle.** The sender locks their leg, then the executor settles:

1. **Allocate** - the leg sender calls `cbtc::allocation::allocate`, which exercises `AllocationFactory_Allocate` and locks the sender's holdings. If no input holdings are specified, the library auto-selects them.
2. **Execute** - the settlement executor calls `cbtc::allocation::execute_transfer` (`Allocation_ExecuteTransfer`). A coordinating app normally settles every leg together in a single transaction; the library exposes the single-leg choice for that purpose.
3. **Or unwind** - the sender can call `cbtc::allocation::withdraw` (`Allocation_Withdraw`) to reclaim locked holdings before settlement, and `cbtc::allocation::cancel` (`Allocation_Cancel`) releases them back to the sender.

**Timing.** An allocation must be funded before `allocate_before` and settled before `settle_before`, which must be the later of the two.

Allocating CBTC into a settlement leg:

```rust
use cbtc::allocation;

let allocation_spec = common::allocation::AllocationSpecification {
 settlement: common::allocation::SettlementInfo {
 executor: executor_party_id.clone(), // the venue settling the legs
 settlement_ref: common::allocation::Reference {
 id: settlement_ref_id.clone(),
 cid: None,
 },
 requested_at: now.to_rfc3339(),
 allocate_before: (now + chrono::Duration::hours(24)).to_rfc3339(),
 settle_before: (now + chrono::Duration::hours(48)).to_rfc3339(),
 meta: common::allocation::Metadata::default(),
 },
 transfer_leg_id: "leg0".to_string(),
 transfer_leg: common::allocation::TransferLeg {
 sender: sender_party_id.clone(),
 receiver: receiver_party_id.clone(),
 amount: cbtc::DamlDecimal::parse("0.1")?,
 instrument_id: common::transfer::InstrumentId {
 admin: decentralized_party_id.clone(),
 id: "CBTC".to_string(),
 },
 meta: common::allocation::Metadata::default(),
 },
};

allocation::allocate(allocation::Params {
 allocation: allocation_spec,
 requested_at: now.to_rfc3339(),
 input_holding_cids: Vec::new(), // empty = library auto-selects the sender's holdings
 ledger_host: ledger_host.clone(),
 access_token: access_token.clone(),
 registry_url: registry_url.clone(),
 decentralized_party_id: decentralized_party_id.clone(),
}).await?;
```

Reclaiming an allocation before settlement:

```rust
use cbtc::allocation;

allocation::withdraw(allocation::ActionParams {
 allocation_contract_id: allocation_cid.clone(),
 actor_party: sender_party_id.clone(),
 ledger_host: ledger_host.clone(),
 access_token: access_token.clone(),
 registry_url: registry_url.clone(),
 decentralized_party_id: decentralized_party_id.clone(),
}).await?;
```

> 💡 **No Minter credential needed.** Allocations move existing CBTC rather than creating or destroying it, so they do not require the Minter credential that minting and burning do.

A complete runnable example is in the library: [`examples/allocate_cbtc.rs`](https://github.com/DLC-link/cbtc-lib/blob/v0.6.4/examples/allocate_cbtc.rs). For the underlying standard, see the [Canton Token Standard allocation docs](https://docs.dev.sync.global/app_dev/token_standard/index.html).

***

## Integration Pattern 4: Minting Integration

**Use case:** Offer CBTC minting as a service to your users.

### Three Options

| Option                           | Description                                               | Effort                    |
| -------------------------------- | --------------------------------------------------------- | ------------------------- |
| **1. Direct API**                | Install CBTC DAR, call Canton APIs to mint/redeem         | Low - a few hours         |
| **2. Self-hosted UI**            | Install DAR + BitSafe minting UI locally                  | Medium - more maintenance |
| **3. Hosted UI** *(coming soon)* | Use BitSafe's centrally hosted UI against your validator. | TBD                       |

For Option 1, see the [Minting and Burning Guide](https://docs.bitsafe.finance/developers/cbtc-minting-and-burning) and [API Reference](https://docs.bitsafe.finance/developers/cbtc-api-reference).

For Options 2 and 3, contact BitSafe for setup details.

***

## Getting Started

1. **Install the SDK and DAR files** - see [SDK Setup and Installation](https://docs.bitsafe.finance/developers/sdk-setup-and-installation) for `cbtc-lib`, `canton-lib`, DAR upload, and environment configuration
2. **Set up testnet first** - see [Testnet Guide](https://docs.bitsafe.finance/developers/cbtc-testnet-guide)
3. **Mint your first CBTC** - see [Quick Start](https://docs.bitsafe.finance/developers/cbtc-quick-start)
4. **Review examples** - [GitHub examples](https://github.com/DLC-link/cbtc-lib/tree/main/examples) **Need help?** Reach out via <support@bitsafe.finance>

***


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.bitsafe.finance/developers/integration-guides.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
