project screenshot 1
project screenshot 2
project screenshot 3
project screenshot 4

Quantum Swap

QuantumSwap: Trustless ETH-BTC atomic swaps using HTLCs, no intermediaries, no custody, pure DeFi.

Quantum Swap

Created At

Unite Defi

Project Description

QuantumSwap: Trustless Cross-Chain Atomic Swaps

What is QuantumSwap?

QuantumSwap is a complete implementation of trustless atomic swaps between Ethereum and Bitcoin using Hash Time-Locked Contracts (HTLCs). Built for ETHGlobal, it enables users to exchange cryptocurrencies across different blockchains without requiring any trusted intermediaries, custodians, or centralized exchanges.

Core Technology: HTLCs (Hash Time-Locked Contracts)

How HTLCs Work:

  1. Secret Generation: A random 32-byte secret is generated by one party
  2. Hash Creation: The secret is hashed using SHA-256 to create a "hashlock"
  3. Fund Locking: Both parties lock their funds in smart contracts/scripts with the same hashlock
  4. Atomic Exchange: When either party reveals the secret, both can claim their funds simultaneously
  5. Time-Limited Refunds: If no one reveals the secret within the timelock period, funds are automatically refunded

Security Guarantees:

  • Atomicity: Either both parties get their funds or neither does
  • Trustlessness: No trusted third party required
  • Non-custodial: Users maintain control of their private keys throughout
  • Time-bounded: Automatic refunds prevent funds from being stuck indefinitely

Project Architecture:

  1. Smart Contracts (Ethereum):
  • ETHHTLC.sol: Core HTLC contract for locking ETH
  • FusionHTLC.sol: Advanced contract supporting order matching and partial fills
  • Events: Emits Locked, Redeemed, and Refunded events for monitoring
  1. Bitcoin Scripts (UTXO Chains):
  • P2SH Scripts: Pay-to-Script-Hash addresses for BTC/LTC/DOGE/BCH
  • OP_SHA256: For hashlock verification
  • OP_CLTV: For timelock enforcement
  • OP_CHECKSIG: For signature verification
  1. Relayer Service:
  • Cross-Chain Monitoring: Watches both Ethereum and Bitcoin networks
  • Automated Execution: Detects events and triggers corresponding actions
  • Secret Extraction: Extracts secrets from one chain to complete swaps on the other
  • Status Tracking: Maintains real-time swap status and transaction logs
  1. Web Frontend:
  • React + Vite: Modern, responsive user interface
  • MetaMask Integration: For Ethereum wallet connection
  • Unisat/Hiro/Xverse Support: For Bitcoin wallet connections
  • Live Exchange Rates: Real-time price feeds from multiple sources
  • Dual Input Fields: Users can specify both send and receive amounts
  • Real-Time Monitoring: Live status updates and transaction tracking
  1. CLI Tools:
  • Order Management: Create, list, and match Fusion+ orders
  • Direct HTLC Operations: Lock, redeem, and refund operations
  • Status Monitoring: Track swap progress and transaction status
  • Partial Fill Support: Handle large orders with multiple counterparties

Key Features:

Trustless Operation:

  • No custodians or intermediaries
  • All operations are on-chain and verifiable
  • Cryptographic proofs ensure atomicity
  • Time-locked refunds prevent fund loss

Multi-Chain Support:

  • Ethereum: Smart contract-based HTLCs
  • Bitcoin: Native script-based HTLCs
  • Litecoin: Compatible with Bitcoin scripts
  • Dogecoin: Compatible with Bitcoin scripts
  • Bitcoin Cash: Compatible with Bitcoin scripts

Advanced Features:

  • Fusion+ Protocol: Order matching and partial fills
  • Live Exchange Rates: Real-time price feeds with fallback sources
  • Automated Relayer: 24/7 cross-chain monitoring and execution
  • Production Ready: SSL, monitoring, logging, and error handling

User Experience:

  • Intuitive Interface: Clear, step-by-step swap process
  • Real-Time Updates: Live status and transaction monitoring
  • Wallet Integration: Seamless connection to popular wallets
  • Mobile Responsive: Works on desktop and mobile devices

Technical Implementation:

Frontend (React + TypeScript):

  • State Management: React hooks for local state
  • Wallet Integration: Web3 providers for Ethereum and Bitcoin
  • Exchange Rate API: Multiple sources with fallback mechanisms
  • Real-Time Updates: WebSocket/polling for status updates

Backend (Node.js + TypeScript):

  • Ethereum Integration: ethers.js for smart contract interaction
  • Bitcoin Integration: bitcoinjs-lib for script building and signing
  • Database: JSON-based logging for swap status tracking
  • API Server: REST endpoints for order management

Smart Contracts (Solidity):

  • Gas Optimization: Minimal gas footprint for cost efficiency
  • Security: Reentrancy protection and input validation
  • Events: Comprehensive event logging for monitoring
  • Upgradeability: Modular design for future enhancements

Bitcoin Scripts:

  • P2SH Addresses: Standard Bitcoin address format
  • Script Validation: Proper signature and hash verification
  • Timelock Support: CLTV for absolute time-based locking
  • Change Addresses: Proper UTXO management

Security Considerations:

Cryptographic Security:

  • Random Secret Generation: Cryptographically secure random number generation
  • Hash Function: SHA-256 for hashlock creation
  • Digital Signatures: ECDSA for transaction signing
  • Private Key Management: No private keys stored on servers

Smart Contract Security:

  • Input Validation: All inputs validated with zod schemas
  • Reentrancy Protection: Guards against reentrancy attacks
  • Access Control: Only authorized parties can execute functions
  • Event Logging: Comprehensive audit trail

Network Security:

  • HTTPS: SSL/TLS encryption for all communications
  • CORS: Proper cross-origin resource sharing configuration
  • Rate Limiting: Protection against abuse and spam
  • Error Handling: Graceful degradation and error recovery

Use Cases:

Individual Users:

  • Cross-Chain Trading: Exchange ETH for BTC without centralized exchanges
  • Privacy: No KYC requirements or identity verification
  • Control: Maintain full control of private keys throughout the process
  • Cost Efficiency: Lower fees compared to traditional exchanges

DeFi Protocols:

  • Liquidity Provision: Provide liquidity for cross-chain swaps
  • Arbitrage: Exploit price differences across chains
  • Portfolio Management: Rebalance holdings across multiple chains
  • Yield Farming: Earn rewards by participating in swap protocols

Institutional Users:

  • OTC Trading: Large volume trades without market impact
  • Risk Management: Hedge positions across multiple chains
  • Compliance: Transparent, auditable transaction history
  • Automation: Programmatic execution of cross-chain trades

Development and Deployment:

Local Development:

  • pnpm: Package manager for dependency management
  • TypeScript: Type-safe development across all modules
  • ESLint + Prettier: Code quality and formatting
  • Jest: Unit and integration testing

Production Deployment:

  • EC2 Instance: AWS cloud hosting
  • Nginx: Reverse proxy and SSL termination
  • Systemd: Service management for frontend and relayer
  • Let's Encrypt: Automated SSL certificate management
  • Monitoring: Log aggregation and error tracking

Environment Configuration:

  • Environment Variables: Secure configuration management
  • Network Selection: Support for testnet and mainnet
  • Contract Addresses: Configurable contract deployments
  • RPC Endpoints: Multiple RPC providers for reliability

Future Enhancements:

Planned Features:

  • Additional Chains: Support for more blockchain networks
  • Advanced Order Types: Limit orders, stop-loss, etc.
  • Liquidity Pools: Automated market making
  • Mobile App: Native iOS and Android applications
  • API Access: Public API for third-party integrations

Technical Improvements:

  • Layer 2 Integration: Support for Lightning Network and rollups
  • Cross-Chain Bridges: Integration with existing bridge protocols
  • MEV Protection: Protection against front-running and sandwich attacks
  • Gas Optimization: Further improvements to transaction costs

Conclusion:

QuantumSwap represents a complete, production-ready implementation of trustless atomic swaps, demonstrating how blockchain technology can enable truly decentralized cross-chain trading. By eliminating the need for trusted intermediaries while maintaining security and usability, it provides a foundation for the future of decentralized finance where users have full control over their assets and trading activities.

The project showcases advanced blockchain development techniques, including smart contract design, Bitcoin script programming, cross-chain communication, and modern web development practices, serving as both a practical tool for users and a reference implementation for developers looking to build similar systems.

How it's Made

How it's made:

QuantumSwap was built as a comprehensive full-stack application combining smart contracts, Bitcoin scripts, cross-chain communication, and modern web technologies. Here's the technical deep dive:

Smart Contract Architecture: The Ethereum side uses two main contracts: ETHHTLC.sol for basic atomic swaps and FusionHTLC.sol for advanced order matching. The contracts implement the core HTLC logic with lock(), redeem(), and refund() functions. A particularly hacky but effective approach was using keccak256 hashing of random data to generate unique order IDs, ensuring no collisions while maintaining gas efficiency. The contracts emit comprehensive events (Locked, Redeemed, Refunded) that the relayer service monitors for cross-chain coordination.

Bitcoin Script Implementation: The Bitcoin side required custom P2SH scripts using bitcoinjs-lib. The most challenging part was implementing the HTLC script with OP_SHA256, OP_CLTV, and OP_CHECKSIG operations. We had to manually construct the redeem script and serialize it properly for P2SH addresses. The hacky part here was using a custom script builder that generates both the redeem path (with secret) and refund path (with timelock) in a single script, allowing for atomic execution.

Cross-Chain Relayer Service: The relayer is a Node.js service that monitors both Ethereum and Bitcoin networks simultaneously. It uses ethers.js for Ethereum interaction and electrum-client for Bitcoin. The most complex part was implementing the secret extraction mechanism - when a redeem event is detected on one chain, the relayer extracts the secret and automatically triggers the corresponding redemption on the other chain. This required careful event parsing and transaction construction.

Frontend Development: Built with React + TypeScript + Vite for optimal development experience. The frontend integrates multiple wallet providers: MetaMask for Ethereum and Unisat/Hiro/Xverse for Bitcoin. A particularly hacky solution was implementing a dual input system where users can specify both send and receive amounts, with real-time calculation based on live exchange rates. The exchange rate system uses multiple API sources (CoinGecko, Binance) with fallback mechanisms to ensure reliability.

1inch Fusion+ Integration: The project integrates with 1inch Fusion+ protocol for advanced order matching and partial fills. This integration allows users to create orders that can be matched by multiple counterparties, enabling better liquidity and more efficient trading. The Fusion+ integration required implementing order creation, matching, and execution logic that works seamlessly with our HTLC system. The most complex part was ensuring that Fusion+ orders maintain the same security guarantees as direct HTLC swaps while providing additional flexibility.

Real-Time Exchange Rates: Implemented a sophisticated exchange rate system that fetches from multiple sources with automatic fallback. The hacky part was using a combination of CoinGecko's free API and Binance's public endpoints, with local caching and rate limiting to avoid API restrictions. When all external APIs fail, it falls back to estimated rates to maintain functionality.

Wallet Integration: The most challenging part was integrating multiple Bitcoin wallet providers (Unisat, Hiro, Xverse) with different APIs. We implemented a provider detection system that checks for wallet availability and provides a unified interface. The hacky solution was using window object detection and dynamic API calls based on which wallet is available.

Production Deployment: Deployed on AWS EC2 with Nginx reverse proxy and Let's Encrypt SSL. The deployment process involved creating systemd services for both frontend and relayer, with proper environment variable management. A particularly hacky but effective approach was using npx for service execution to avoid path issues with globally installed packages.

Database and State Management: Instead of a traditional database, we implemented a JSON-based logging system for swap status tracking. This was a deliberate choice for simplicity and transparency - all swap data is stored in human-readable JSON files. The hacky part was implementing file-based locking to prevent race conditions when multiple processes access the same log files.

CLI Tools: Built comprehensive CLI tools using TypeScript and Commander.js. The tools can create orders, monitor status, and execute HTLC operations directly. The most complex part was implementing partial fill support for large orders, which required careful UTXO management and change address handling.

Security Implementation: Implemented comprehensive input validation using Zod schemas throughout the application. The most critical security feature is the cryptographic secret generation using window.crypto.getRandomValues() for true randomness. Private keys are never stored on servers - all signing happens in user wallets.

Cross-Chain Communication: The most technically challenging part was implementing reliable cross-chain communication. The relayer service polls both networks every 5 seconds, parsing events and transaction data. When it detects a redeem event on one chain, it extracts the secret and constructs the corresponding transaction for the other chain. This required deep understanding of both Ethereum and Bitcoin transaction formats.

Error Handling and Monitoring: Implemented comprehensive error handling with graceful degradation. The system continues to function even if external APIs fail or networks are congested. Real-time status updates are provided through polling mechanisms, with proper error states and user feedback.

The entire system is designed to be stateless and fault-tolerant, with each component able to recover from failures independently. The most hacky but effective approach was using a combination of file-based logging, in-memory caching, and real-time polling to maintain system reliability without complex infrastructure requirements.

background image mobile

Join the mailing list

Get the latest news and updates