Quantum Swap
QuantumSwap: Trustless ETH-BTC atomic swaps using HTLCs, no intermediaries, no custody, pure DeFi.
Problem Statement
QuantumSwap: Trustless Cross-Chain Atomic SwapsWhat 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:Secret Generation: A random 32-byte secret is generated by one partyHash Creation: The secret is hashed using SHA-256 to create a "hashlock"Fund Locking: Both parties lock their funds in smart contracts/scripts with the same hashlockAtomic Exchange: When either party reveals the secret, both can claim their funds simultaneouslyTime-Limited Refunds: If no one reveals the secret within the timelock period, funds are automatically refundedSecurity Guarantees:Atomicity: Either both parties get their funds or neither doesTrustlessness: No trusted third party requiredNon-custodial: Users maintain control of their private keys throughoutTime-bounded: Automatic refunds prevent funds from being stuck indefinitelyProject Architecture:Smart Contracts (Ethereum):ETHHTLC.sol: Core HTLC contract for locking ETHFusionHTLC.sol: Advanced contract supporting order matching and partial fillsEvents: Emits Locked, Redeemed, and Refunded events for monitoringBitcoin Scripts (UTXO Chains):P2SH Scripts: Pay-to-Script-Hash addresses for BTC/LTC/DOGE/BCHOP_SHA256: For hashlock verificationOP_CLTV: For timelock enforcementOP_CHECKSIG: For signature verificationRelayer Service:Cross-Chain Monitoring: Watches both Ethereum and Bitcoin networksAutomated Execution: Detects events and triggers corresponding actionsSecret Extraction: Extracts secrets from one chain to complete swaps on the otherStatus Tracking: Maintains real-time swap status and transaction logsWeb Frontend:React + Vite: Modern, responsive user interfaceMetaMask Integration: For Ethereum wallet connectionUnisat/Hiro/Xverse Support: For Bitcoin wallet connectionsLive Exchange Rates: Real-time price feeds from multiple sourcesDual Input Fields: Users can specify both send and receive amountsReal-Time Monitoring: Live status updates and transaction trackingCLI Tools:Order Management: Create, list, and match Fusion+ ordersDirect HTLC Operations: Lock, redeem, and refund operationsStatus Monitoring: Track swap progress and transaction statusPartial Fill Support: Handle large orders with multiple counterpartiesKey Features:Trustless Operation:No custodians or intermediariesAll operations are on-chain and verifiableCryptographic proofs ensure atomicityTime-locked refunds prevent fund lossMulti-Chain Support:Ethereum: Smart contract-based HTLCsBitcoin: Native script-based HTLCsLitecoin: Compatible with Bitcoin scriptsDogecoin: Compatible with Bitcoin scriptsBitcoin Cash: Compatible with Bitcoin scriptsAdvanced Features:Fusion+ Protocol: Order matching and partial fillsLive Exchange Rates: Real-time price feeds with fallback sourcesAutomated Relayer: 24/7 cross-chain monitoring and executionProduction Ready: SSL, monitoring, logging, and error handlingUser Experience:Intuitive Interface: Clear, step-by-step swap processReal-Time Updates: Live status and transaction monitoringWallet Integration: Seamless connection to popular walletsMobile Responsive: Works on desktop and mobile devicesTechnical Implementation:Frontend (React + TypeScript):State Management: React hooks for local stateWallet Integration: Web3 providers for Ethereum and BitcoinExchange Rate API: Multiple sources with fallback mechanismsReal-Time Updates: WebSocket/polling for status updatesBackend (Node.js + TypeScript):Ethereum Integration: ethers.js for smart contract interactionBitcoin Integration: bitcoinjs-lib for script building and signingDatabase: JSON-based logging for swap status trackingAPI Server: REST endpoints for order managementSmart Contracts (Solidity):Gas Optimization: Minimal gas footprint for cost efficiencySecurity: Reentrancy protection and input validationEvents: Comprehensive event logging for monitoringUpgradeability: Modular design for future enhancementsBitcoin Scripts:P2SH Addresses: Standard Bitcoin address formatScript Validation: Proper signature and hash verificationTimelock Support: CLTV for absolute time-based lockingChange Addresses: Proper UTXO managementSecurity Considerations:Cryptographic Security:Random Secret Generation: Cryptographically secure random number generationHash Function: SHA-256 for hashlock creationDigital Signatures: ECDSA for transaction signingPrivate Key Management: No private keys stored on serversSmart Contract Security:Input Validation: All inputs validated with zod schemasReentrancy Protection: Guards against reentrancy attacksAccess Control: Only authorized parties can execute functionsEvent Logging: Comprehensive audit trailNetwork Security:HTTPS: SSL/TLS encryption for all communicationsCORS: Proper cross-origin resource sharing configurationRate Limiting: Protection against abuse and spamError Handling: Graceful degradation and error recoveryUse Cases:Individual Users:Cross-Chain Trading: Exchange ETH for BTC without centralized exchangesPrivacy: No KYC requirements or identity verificationControl: Maintain full control of private keys throughout the processCost Efficiency: Lower fees compared to traditional exchangesDeFi Protocols:Liquidity Provision: Provide liquidity for cross-chain swapsArbitrage: Exploit price differences across chainsPortfolio Management: Rebalance holdings across multiple chainsYield Farming: Earn rewards by participating in swap protocolsInstitutional Users:OTC Trading: Large volume trades without market impactRisk Management: Hedge positions across multiple chainsCompliance: Transparent, auditable transaction historyAutomation: Programmatic execution of cross-chain tradesDevelopment and Deployment:Local Development:pnpm: Package manager for dependency managementTypeScript: Type-safe development across all modulesESLint + Prettier: Code quality and formattingJest: Unit and integration testingProduction Deployment:EC2 Instance: AWS cloud hostingNginx: Reverse proxy and SSL terminationSystemd: Service management for frontend and relayerLet's Encrypt: Automated SSL certificate managementMonitoring: Log aggregation and error trackingEnvironment Configuration:Environment Variables: Secure configuration managementNetwork Selection: Support for testnet and mainnetContract Addresses: Configurable contract deploymentsRPC Endpoints: Multiple RPC providers for reliabilityFuture Enhancements:Planned Features:Additional Chains: Support for more blockchain networksAdvanced Order Types: Limit orders, stop-loss, etc.Liquidity Pools: Automated market makingMobile App: Native iOS and Android applicationsAPI Access: Public API for third-party integrationsTechnical Improvements:Layer 2 Integration: Support for Lightning Network and rollupsCross-Chain Bridges: Integration with existing bridge protocolsMEV Protection: Protection against front-running and sandwich attacksGas Optimization: Further improvements to transaction costsConclusion: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.
Solution
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.
Hackathon
ETHGlobal Unite
2025
Contributors
- virajbhartiya
63 contributions