Skip to content

Commit fc88018

Browse files
authored
feat: add example for atomic swap with btc (#25)
* make a copy of swap board * add support for btc * fix build * fix btc request * cleanup readme with completed tasks
1 parent 7b390ea commit fc88018

26 files changed

+3754
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Database
2+
DATABASE_URL="file:./dev.db"
3+
4+
# Mintlayer Network (testnet or mainnet)
5+
NEXT_PUBLIC_MINTLAYER_NETWORK="testnet"

examples/swap-board-ml-btc/.gitignore

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
# dependencies
4+
/node_modules
5+
/.pnp
6+
.pnp.js
7+
.yarn/install-state.gz
8+
9+
# testing
10+
/coverage
11+
12+
# next.js
13+
/.next/
14+
/out/
15+
16+
# production
17+
/build
18+
19+
# misc
20+
.DS_Store
21+
*.pem
22+
23+
# debug
24+
npm-debug.log*
25+
yarn-debug.log*
26+
yarn-error.log*
27+
28+
# local env files
29+
.env*.local
30+
.env
31+
32+
# vercel
33+
.vercel
34+
35+
# typescript
36+
*.tsbuildinfo
37+
next-env.d.ts
38+
39+
# database
40+
prisma/dev.db
41+
prisma/dev.db-journal
42+
43+
# IDE
44+
.vscode/
45+
.idea/
46+
*.swp
47+
*.swo
48+
49+
# OS
50+
Thumbs.db
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
# BTC Integration for Mintlayer P2P Swap Board
2+
3+
This document describes the Bitcoin (BTC) integration added to the swap board, enabling atomic swaps between Mintlayer tokens and native Bitcoin.
4+
5+
## Overview
6+
7+
The BTC integration allows users to:
8+
- Create offers involving BTC (BTC → ML tokens or ML tokens → BTC)
9+
- Accept BTC offers by providing BTC credentials
10+
- Create BTC HTLCs for atomic swaps
11+
- Claim and refund BTC HTLCs
12+
- Track BTC transactions on blockchain explorers
13+
14+
## Architecture
15+
16+
### Wallet-Centric Design
17+
- **Web App**: Builds requests and manages UI/coordination
18+
- **Wallet Extension**: Handles all BTC cryptographic operations
19+
- **No Private Keys**: Web app never handles BTC private keys
20+
21+
### Key Components
22+
23+
#### 1. Database Schema (`prisma/schema.prisma`)
24+
**Offer Model Additions:**
25+
- `creatorBTCAddress`: Creator's BTC address
26+
- `creatorBTCPublicKey`: Creator's BTC public key for HTLC creation
27+
28+
**Swap Model Additions:**
29+
- `takerBTCAddress`: Taker's BTC address
30+
- `takerBTCPublicKey`: Taker's BTC public key for HTLC creation
31+
- `btcHtlcAddress`: Generated BTC HTLC contract address
32+
- `btcRedeemScript`: BTC HTLC redeem script
33+
- `btcHtlcTxId`: BTC HTLC funding transaction ID
34+
- `btcHtlcTxHex`: BTC HTLC signed transaction hex
35+
- `btcClaimTxId`: BTC claim transaction ID
36+
- `btcClaimTxHex`: BTC claim signed transaction hex
37+
- `btcRefundTxId`: BTC refund transaction ID
38+
- `btcRefundTxHex`: BTC refund signed transaction hex
39+
40+
#### 2. Type Definitions (`src/types/`)
41+
- `btc-wallet.ts`: Wallet interface definitions
42+
- `swap.ts`: Updated with BTC fields and new status types
43+
44+
#### 3. BTC Utilities (`src/lib/btc-request-builder.ts`)
45+
- Amount conversion (BTC ↔ satoshis)
46+
- Address and public key validation
47+
- HTLC request builders
48+
- Explorer URL generators
49+
50+
#### 4. API Endpoints
51+
- **POST /api/offers**: Validates BTC credentials for BTC offers
52+
- **POST /api/swaps**: Handles BTC credentials during offer acceptance
53+
- **POST /api/swaps/[id]**: Updates swaps with BTC transaction data
54+
55+
#### 5. Frontend Components
56+
- **Create Offer**: Requests BTC credentials when BTC is involved
57+
- **Offers List**: Handles BTC credential exchange during acceptance
58+
- **Swap Detail**: Full BTC HTLC management interface
59+
60+
## Swap Flow
61+
62+
### ML → BTC Swap
63+
1. **Creator creates offer**: Provides BTC address + public key
64+
2. **Taker accepts**: Provides their BTC address + public key
65+
3. **Creator creates ML HTLC**: Standard Mintlayer HTLC
66+
4. **Taker creates BTC HTLC**: Using creator's public key as recipient
67+
5. **Creator claims BTC**: Uses secret to spend BTC HTLC
68+
6. **Taker claims ML**: Uses revealed secret to claim ML HTLC
69+
70+
### BTC → ML Swap
71+
1. **Creator creates offer**: Provides BTC address + public key
72+
2. **Taker accepts**: Provides their BTC address + public key
73+
3. **Creator creates BTC HTLC**: Using taker's public key as recipient
74+
4. **Taker creates ML HTLC**: Standard Mintlayer HTLC
75+
5. **Taker claims BTC**: Uses secret to spend BTC HTLC
76+
6. **Creator claims ML**: Uses revealed secret to claim ML HTLC
77+
78+
## Status Tracking
79+
80+
New swap statuses:
81+
- `btc_htlc_created`: BTC HTLC has been created
82+
- `both_htlcs_created`: Both ML and BTC HTLCs exist
83+
- `btc_refunded`: BTC side was refunded
84+
85+
## Security Considerations
86+
87+
### Public Key Exchange
88+
- Public keys are required for HTLC script generation
89+
- Keys are stored in database (consider privacy implications)
90+
- Keys are visible to counterparty (required for HTLC creation)
91+
92+
### Timelock Coordination
93+
- BTC timelock should be shorter than ML timelock
94+
- Ensures proper claim ordering for security
95+
96+
### Atomic Guarantees
97+
- Same secret hash used for both chains
98+
- Standard HTLC atomic swap properties maintained
99+
- Manual refund available after timelock expiry
100+
101+
## Testing
102+
103+
Run the integration test:
104+
```bash
105+
node test-btc-integration.js
106+
```
107+
108+
## Development Status
109+
110+
### ✅ Completed
111+
- Database schema with BTC fields
112+
- Type definitions and interfaces
113+
- BTC utility functions
114+
- API endpoint updates
115+
- Frontend BTC integration
116+
- Status tracking and UI
117+
- BTC wallet method implementations
118+
- BTC HTLC script generation
119+
- BTC transaction building and signing
120+
- BTC network integration
121+
- Secret extraction from BTC claims
122+
123+
### 🧪 Testing Needed
124+
- End-to-end BTC swap testing
125+
- Error handling and edge cases
126+
- Network compatibility (testnet/mainnet)
127+
- Performance optimization
128+
129+
## Support
130+
131+
For questions about the BTC integration:
132+
- Check the test file for usage examples
133+
- Review the utility functions in `btc-request-builder.ts`
134+
- Examine the swap detail page for UI implementation
135+
- Test with the provided mock data structures

examples/swap-board-ml-btc/README.md

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
# Mintlayer P2P Swap Board
2+
3+
A minimal peer-to-peer token swap board for Mintlayer tokens using HTLC (Hash Time Locked Contracts) atomic swaps.
4+
5+
## Features
6+
7+
- **Create Swap Offers**: Post your intent to swap one Mintlayer token for another
8+
- **Browse & Accept Offers**: View available offers and accept the ones that interest you
9+
- **Atomic Swaps**: Secure token exchanges using HTLC contracts via mintlayer-connect-sdk
10+
- **Status Tracking**: Real-time monitoring of swap progress with clear status indicators
11+
- **Wallet Integration**: Connect with Mojito wallet for seamless transactions
12+
13+
## Tech Stack
14+
15+
- **Frontend**: Next.js 14 (App Router) + React + Tailwind CSS
16+
- **Backend**: Next.js API routes
17+
- **Database**: SQLite with Prisma ORM
18+
- **Blockchain**: Mintlayer Connect SDK for HTLC operations
19+
- **Package Manager**: pnpm (workspace integration)
20+
21+
## Getting Started
22+
23+
### Prerequisites
24+
25+
- Node.js 18+
26+
- pnpm
27+
- Mojito wallet extension
28+
29+
### Installation
30+
31+
1. Install dependencies:
32+
```bash
33+
cd examples/swap-board-ml-ml
34+
pnpm install
35+
```
36+
37+
2. Set up the database:
38+
```bash
39+
pnpm db:generate
40+
pnpm db:push
41+
```
42+
43+
3. Copy environment variables:
44+
```bash
45+
cp .env.example .env.local
46+
```
47+
48+
4. Start the development server:
49+
```bash
50+
pnpm dev
51+
```
52+
53+
5. Open [http://localhost:3000](http://localhost:3000) in your browser
54+
55+
## Usage
56+
57+
### Creating an Offer
58+
59+
1. Navigate to `/create`
60+
2. Connect your Mojito wallet
61+
3. Fill in the swap details:
62+
- Token to give (Token ID)
63+
- Amount to give
64+
- Token to receive (Token ID)
65+
- Amount to receive
66+
- Optional contact information
67+
4. Submit the offer
68+
69+
### Accepting an Offer
70+
71+
1. Browse offers at `/offers`
72+
2. Connect your wallet
73+
3. Click "Accept Offer" on any available offer
74+
4. You'll be redirected to the swap progress page
75+
76+
### Monitoring Swaps
77+
78+
1. Visit `/swap/[id]` to track swap progress
79+
2. The page shows:
80+
- Current swap status
81+
- Progress steps
82+
- Next actions required
83+
- HTLC details when available
84+
85+
## Swap Process
86+
87+
1. **Offer Created**: User posts swap intention
88+
2. **Offer Accepted**: Another user accepts the offer
89+
3. **HTLC Creation**: Creator creates initial HTLC with secret hash
90+
4. **Counterparty HTLC**: Taker creates matching HTLC
91+
5. **Token Claiming**: Both parties reveal secrets to claim tokens
92+
6. **Completion**: Swap finalized or manually refunded after timelock expires
93+
94+
## Database Schema
95+
96+
### Offer Model
97+
- Stores swap offers with token details and creator information
98+
- Tracks offer status (open, taken, completed, cancelled)
99+
100+
### Swap Model
101+
- Manages active swaps linked to offers
102+
- Stores HTLC secrets, transaction hashes, and status updates
103+
- Tracks swap progress from pending to completion
104+
105+
## API Endpoints
106+
107+
- `GET/POST /api/offers` - List and create swap offers
108+
- `POST /api/swaps` - Accept an offer (creates new swap)
109+
- `GET/POST /api/swaps/[id]` - Get and update swap status
110+
111+
## Development
112+
113+
### Database Operations
114+
115+
```bash
116+
# Generate Prisma client
117+
pnpm db:generate
118+
119+
# Push schema changes
120+
pnpm db:push
121+
122+
# Open database browser
123+
pnpm db:studio
124+
```
125+
126+
### Building
127+
128+
```bash
129+
# Build for production
130+
pnpm build
131+
132+
# Start production server
133+
pnpm start
134+
```
135+
136+
## Security Considerations
137+
138+
- HTLC contracts provide atomic swap guarantees
139+
- Timelock mechanisms prevent indefinite locks - users must manually refund after expiry
140+
- No private keys are stored in the database
141+
- All transactions require wallet confirmation
142+
143+
## Contributing
144+
145+
This is a minimal example implementation. For production use, consider:
146+
147+
- Enhanced error handling and validation
148+
- Comprehensive testing suite
149+
- Rate limiting and spam protection
150+
- Advanced UI/UX improvements
151+
- Mobile responsiveness optimization
152+
- Real-time notifications
153+
154+
## License
155+
156+
This project is part of the Mintlayer Connect SDK examples.
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/** @type {import('next').NextConfig} */
2+
const nextConfig = {
3+
webpack: (config) => {
4+
config.experiments = {
5+
...config.experiments,
6+
asyncWebAssembly: true,
7+
};
8+
return config;
9+
},
10+
// Disable static generation for pages that might use browser APIs
11+
experimental: {
12+
missingSuspenseWithCSRBailout: false,
13+
}
14+
}
15+
16+
module.exports = nextConfig

0 commit comments

Comments
 (0)