Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions examples/swap-board-ml-btc/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Database
DATABASE_URL="file:./dev.db"

# Mintlayer Network (testnet or mainnet)
NEXT_PUBLIC_MINTLAYER_NETWORK="testnet"
50 changes: 50 additions & 0 deletions examples/swap-board-ml-btc/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local
.env

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts

# database
prisma/dev.db
prisma/dev.db-journal

# IDE
.vscode/
.idea/
*.swp
*.swo

# OS
Thumbs.db
135 changes: 135 additions & 0 deletions examples/swap-board-ml-btc/BTC_INTEGRATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# BTC Integration for Mintlayer P2P Swap Board

This document describes the Bitcoin (BTC) integration added to the swap board, enabling atomic swaps between Mintlayer tokens and native Bitcoin.

## Overview

The BTC integration allows users to:
- Create offers involving BTC (BTC → ML tokens or ML tokens → BTC)
- Accept BTC offers by providing BTC credentials
- Create BTC HTLCs for atomic swaps
- Claim and refund BTC HTLCs
- Track BTC transactions on blockchain explorers

## Architecture

### Wallet-Centric Design
- **Web App**: Builds requests and manages UI/coordination
- **Wallet Extension**: Handles all BTC cryptographic operations
- **No Private Keys**: Web app never handles BTC private keys

### Key Components

#### 1. Database Schema (`prisma/schema.prisma`)
**Offer Model Additions:**
- `creatorBTCAddress`: Creator's BTC address
- `creatorBTCPublicKey`: Creator's BTC public key for HTLC creation

**Swap Model Additions:**
- `takerBTCAddress`: Taker's BTC address
- `takerBTCPublicKey`: Taker's BTC public key for HTLC creation
- `btcHtlcAddress`: Generated BTC HTLC contract address
- `btcRedeemScript`: BTC HTLC redeem script
- `btcHtlcTxId`: BTC HTLC funding transaction ID
- `btcHtlcTxHex`: BTC HTLC signed transaction hex
- `btcClaimTxId`: BTC claim transaction ID
- `btcClaimTxHex`: BTC claim signed transaction hex
- `btcRefundTxId`: BTC refund transaction ID
- `btcRefundTxHex`: BTC refund signed transaction hex

#### 2. Type Definitions (`src/types/`)
- `btc-wallet.ts`: Wallet interface definitions
- `swap.ts`: Updated with BTC fields and new status types

#### 3. BTC Utilities (`src/lib/btc-request-builder.ts`)
- Amount conversion (BTC ↔ satoshis)
- Address and public key validation
- HTLC request builders
- Explorer URL generators

#### 4. API Endpoints
- **POST /api/offers**: Validates BTC credentials for BTC offers
- **POST /api/swaps**: Handles BTC credentials during offer acceptance
- **POST /api/swaps/[id]**: Updates swaps with BTC transaction data

#### 5. Frontend Components
- **Create Offer**: Requests BTC credentials when BTC is involved
- **Offers List**: Handles BTC credential exchange during acceptance
- **Swap Detail**: Full BTC HTLC management interface

## Swap Flow

### ML → BTC Swap
1. **Creator creates offer**: Provides BTC address + public key
2. **Taker accepts**: Provides their BTC address + public key
3. **Creator creates ML HTLC**: Standard Mintlayer HTLC
4. **Taker creates BTC HTLC**: Using creator's public key as recipient
5. **Creator claims BTC**: Uses secret to spend BTC HTLC
6. **Taker claims ML**: Uses revealed secret to claim ML HTLC

### BTC → ML Swap
1. **Creator creates offer**: Provides BTC address + public key
2. **Taker accepts**: Provides their BTC address + public key
3. **Creator creates BTC HTLC**: Using taker's public key as recipient
4. **Taker creates ML HTLC**: Standard Mintlayer HTLC
5. **Taker claims BTC**: Uses secret to spend BTC HTLC
6. **Creator claims ML**: Uses revealed secret to claim ML HTLC

## Status Tracking

New swap statuses:
- `btc_htlc_created`: BTC HTLC has been created
- `both_htlcs_created`: Both ML and BTC HTLCs exist
- `btc_refunded`: BTC side was refunded

## Security Considerations

### Public Key Exchange
- Public keys are required for HTLC script generation
- Keys are stored in database (consider privacy implications)
- Keys are visible to counterparty (required for HTLC creation)

### Timelock Coordination
- BTC timelock should be shorter than ML timelock
- Ensures proper claim ordering for security

### Atomic Guarantees
- Same secret hash used for both chains
- Standard HTLC atomic swap properties maintained
- Manual refund available after timelock expiry

## Testing

Run the integration test:
```bash
node test-btc-integration.js
```

## Development Status

### ✅ Completed
- Database schema with BTC fields
- Type definitions and interfaces
- BTC utility functions
- API endpoint updates
- Frontend BTC integration
- Status tracking and UI
- BTC wallet method implementations
- BTC HTLC script generation
- BTC transaction building and signing
- BTC network integration
- Secret extraction from BTC claims

### 🧪 Testing Needed
- End-to-end BTC swap testing
- Error handling and edge cases
- Network compatibility (testnet/mainnet)
- Performance optimization

## Support

For questions about the BTC integration:
- Check the test file for usage examples
- Review the utility functions in `btc-request-builder.ts`
- Examine the swap detail page for UI implementation
- Test with the provided mock data structures
156 changes: 156 additions & 0 deletions examples/swap-board-ml-btc/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
# Mintlayer P2P Swap Board

A minimal peer-to-peer token swap board for Mintlayer tokens using HTLC (Hash Time Locked Contracts) atomic swaps.

## Features

- **Create Swap Offers**: Post your intent to swap one Mintlayer token for another
- **Browse & Accept Offers**: View available offers and accept the ones that interest you
- **Atomic Swaps**: Secure token exchanges using HTLC contracts via mintlayer-connect-sdk
- **Status Tracking**: Real-time monitoring of swap progress with clear status indicators
- **Wallet Integration**: Connect with Mojito wallet for seamless transactions

## Tech Stack

- **Frontend**: Next.js 14 (App Router) + React + Tailwind CSS
- **Backend**: Next.js API routes
- **Database**: SQLite with Prisma ORM
- **Blockchain**: Mintlayer Connect SDK for HTLC operations
- **Package Manager**: pnpm (workspace integration)

## Getting Started

### Prerequisites

- Node.js 18+
- pnpm
- Mojito wallet extension

### Installation

1. Install dependencies:
```bash
cd examples/swap-board-ml-ml
pnpm install
```

2. Set up the database:
```bash
pnpm db:generate
pnpm db:push
```

3. Copy environment variables:
```bash
cp .env.example .env.local
```

4. Start the development server:
```bash
pnpm dev
```

5. Open [http://localhost:3000](http://localhost:3000) in your browser

## Usage

### Creating an Offer

1. Navigate to `/create`
2. Connect your Mojito wallet
3. Fill in the swap details:
- Token to give (Token ID)
- Amount to give
- Token to receive (Token ID)
- Amount to receive
- Optional contact information
4. Submit the offer

### Accepting an Offer

1. Browse offers at `/offers`
2. Connect your wallet
3. Click "Accept Offer" on any available offer
4. You'll be redirected to the swap progress page

### Monitoring Swaps

1. Visit `/swap/[id]` to track swap progress
2. The page shows:
- Current swap status
- Progress steps
- Next actions required
- HTLC details when available

## Swap Process

1. **Offer Created**: User posts swap intention
2. **Offer Accepted**: Another user accepts the offer
3. **HTLC Creation**: Creator creates initial HTLC with secret hash
4. **Counterparty HTLC**: Taker creates matching HTLC
5. **Token Claiming**: Both parties reveal secrets to claim tokens
6. **Completion**: Swap finalized or manually refunded after timelock expires

## Database Schema

### Offer Model
- Stores swap offers with token details and creator information
- Tracks offer status (open, taken, completed, cancelled)

### Swap Model
- Manages active swaps linked to offers
- Stores HTLC secrets, transaction hashes, and status updates
- Tracks swap progress from pending to completion

## API Endpoints

- `GET/POST /api/offers` - List and create swap offers
- `POST /api/swaps` - Accept an offer (creates new swap)
- `GET/POST /api/swaps/[id]` - Get and update swap status

## Development

### Database Operations

```bash
# Generate Prisma client
pnpm db:generate

# Push schema changes
pnpm db:push

# Open database browser
pnpm db:studio
```

### Building

```bash
# Build for production
pnpm build

# Start production server
pnpm start
```

## Security Considerations

- HTLC contracts provide atomic swap guarantees
- Timelock mechanisms prevent indefinite locks - users must manually refund after expiry
- No private keys are stored in the database
- All transactions require wallet confirmation

## Contributing

This is a minimal example implementation. For production use, consider:

- Enhanced error handling and validation
- Comprehensive testing suite
- Rate limiting and spam protection
- Advanced UI/UX improvements
- Mobile responsiveness optimization
- Real-time notifications

## License

This project is part of the Mintlayer Connect SDK examples.
16 changes: 16 additions & 0 deletions examples/swap-board-ml-btc/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
webpack: (config) => {
config.experiments = {
...config.experiments,
asyncWebAssembly: true,
};
return config;
},
// Disable static generation for pages that might use browser APIs
experimental: {
missingSuspenseWithCSRBailout: false,
}
}

module.exports = nextConfig
Loading