PeerSwap
First-ever trustless P2P cross-chain swap: users securely trade tokens without DEXes/bridges
Problem Statement
PeerSwap - P2P Cross-Chain Swap ProtocolAvailable On Social platforms:Farcaster: https://farcaster.xyz/miniapps/Fsw6avz8_EKu/peerswapWorld App: https://world.org/mini-app?app_id=app_506a8a5565ba2fca4e523d0a4487d74aA trustless P2P swap platform where two users can securely exchange tokens across chains without DEXes or bridges.🚨 The ProblemMeetMohitandJack- two crypto enthusiasts with a simple problem.Mohithas 1000 USDC sitting on Base chain, but he really wants someTempo tokensthat are only available on the Tempo chain. He's been waiting for weeks, checking every DEX and bridge, but there's just no way to get Tempo tokens.Meanwhile,Jackhas plenty of Tempo tokens on Tempo chain, but he needs USDC on Base for his next DeFi play. He's also been searching everywhere - no bridges, no DEXes, nothing.The frustrating reality:🚫No direct bridgebetween Base and Tempo chains💸High slippageon existing DEXes (if they even have the pair)🏦Centralized exchangesrequire KYC and take days🤝No secure wayfor Mohit and Jack to trade directlyThey're literally perfect trading partners, but the infrastructure doesn't exist for them to help each other out. This is theP2P swap gap- millions of users with complementary needs, but no trustless way to connect them.💡 The SolutionA trustless P2P swap platform where two users can securely exchange tokens across chains without DEXes or bridges.Uses hashlocked escrows + timelocks for securityRelayer coordinates but never controls fundsWorks chain-to-chain, simple and effectiveKey FeaturesTrustless: No dispute resolution neededNo middlemen: Only lightweight relayerSecure & fault-proof: Cryptographic locksCross-chain compatibleUser-friendly: Peer-to-peer experience🏗️ ArchitectureCore ComponentsSmart Contracts(Solidity)EscrowFactory- Main factory contract that deploys escrow instancesEscrowSrc- Source chain escrow contract that locks asker's tokensEscrowDst- Destination chain escrow contract that locks fullfiller's tokensBaseEscrow- Abstract base contract with common escrow functionalityBackend Services(Node.js/TypeScript)Express API server for swap managementRelayer service for cross-chain coordinationEvent monitoring and automatic processingIn-memory swap storageFrontend Application(Next.js/React)Farcaster Mini App interfaceWallet integration (Wagmi)Real-time swap status trackingCross-chain transaction management🔄 Technical FlowCreate Swap– User A locks funds in escrow (Hashlock + Timelock)Fulfill Swap– User B locks funds on destination chainSet Fulfiller– Role is assignedSubmit Secret– Secret revealed to unlock fundsCompletion– Both users receive tokensFail-safes:24h→ Cancel option48h→ Rescue possible72h→ Only rescue available🔄 Complete Swap Flowgraph TD A[User A Creates Swap] --> B[Secret Generated] B --> C[Source Escrow Deployed] C --> D[Tokens Locked with Hashlock] D --> E[User B Fulfills Swap] E --> F[Destination Escrow Deployed] F --> G[Relayer Sets Fulfiller] G --> H[User A Claims with Secret] H --> I[Secret Revealed] I --> J[Both Escrows Withdrawn] J --> K[Swap Completed]🔐 Security MechanismsHashlock SystemSecret Generation: User generates a random secretHashlock Creation: Secret is hashed using keccak256One-way Function: Prevents front-running and ensures atomic swapsSecret Revelation: Only the original secret can unlock tokensTimelock StagesSource ChainSrcWithdrawal: Only asker can withdraw with secret (0-24h)SrcPublicWithdrawal: Anyone with access token can withdraw (24-48h)SrcCancellation: Only asker can cancel (24-48h)SrcPublicCancellation: Anyone with access token can cancel (48-72h)Destination ChainDstWithdrawal: Only asker can withdraw with secret (0-24h)DstPublicWithdrawal: Anyone with access token can withdraw (24-48h)DstCancellation: Only fullfiller can cancel (24-48h)Cross-Chain SecurityAtomic Operations: Both escrows must succeed or both failExecution Data Validation: All operations verify execution data integrityAccess Token Control: Public functions require access token ownershipEmergency Recovery: Rescue mechanism for stuck funds after 72h💰 Fee StructurePlatform Fee: 1% of asker amount (configurable, max 10%)Gas Fee: Native token fee paid by fullfiller, returned to withdrawal callerFee Collector: Configurable address to receive platform fees🛠️ Technical ImplementationSmart Contract FeaturesDeterministic Addresses: Using CREATE2 for predictable escrow addressesClone Pattern: Gas-efficient deployment using OpenZeppelin ClonesSafeERC20: Secure token transfers with proper error handlingTimelock Library: Compact storage of time-based restrictionsBackend ServicesEvent Monitoring: Real-time blockchain event processingRelayer Coordination: Automated cross-chain transaction executionSwap Storage: In-memory database for swap state managementAPI Endpoints: RESTful interface for frontend integrationFrontend FeaturesWallet Integration: Support for multiple wallet providersChain Switching: Automatic network switching for cross-chain swapsReal-time Updates: Live swap status trackingTransaction Management: Comprehensive transaction history🎯 Use CasesSecondary / pre-listing token marketsLow fees, simple UXSwaps with friends/social circlesLarge trades possible without slippage/liquidity issues🚀 DemoAvailable on:Farcaster- Mini App integrationWorldcoin- MiniappWeb App- Direct browser accessLive now:p🚀 Getting StartedPrerequisitesNode.js 18+Foundry (latest version)Solidity 0.8.20+InstallationClone the repositorygit clone <repository-url> cd peerswapInstall dependencies# Backend cd backend npm install # Frontend cd ../miniapp/peerswap npm install # Smart contracts cd ../../peerswap-contracts forge installEnvironment Setup# Backend cp backend/.env.example backend/.env # Configure your environment variables # Frontend cp miniapp/peerswap/.env.example miniapp/peerswap/.env.local # Configure your environment variablesDevelopmentStart the backendcd backend npm run devStart the frontendcd miniapp/peerswap npm run devDeploy smart contractscd peerswap-contracts forge script script/Deploy.s.sol --rpc-url <RPC_URL> --private-key <PRIVATE_KEY> --broadcastTesting# Smart contracts cd peerswap-contracts forge test # Backend cd backend npm test # Frontend cd miniapp/peerswap npm test📊 API EndpointsSwap ManagementPOST /swaps- Create a new swapGET /swaps- List all swapsGET /swap-status/:hashlock- Check swap statusPOST /claim- Submit secret for claimingSystem ManagementGET /health- Health checkPOST /check-deployments- Check all swap deploymentsGET /check-relayer- Check relayer addresses🔧 ConfigurationEnvironment VariablesBackendRELAYER_PRIVATE_KEY- Private key for relayer operationsPORT- Server port (default: 8787)RPC_URL_SEPOLIA- Sepolia RPC endpointRPC_URL_BASE_SEPOLIA- Base Sepolia RPC endpointFrontendNEXT_PUBLIC_BACKEND_URL- Backend API URLNEXT_PUBLIC_FACTORY_ADDRESS_SEPOLIA- Sepolia factory addressNEXT_PUBLIC_FACTORY_ADDRESS_BASE_SEPOLIA- Base Sepolia factory address🌐 Supported NetworksEthereum Sepolia(Chain ID: 11155111)Base Sepolia(Chain ID: 84532)🔒 Security ConsiderationsPrivate Key Management: Never expose private keys in client-side codeAccess Token Requirements: Public functions require access token ownershipTimelock Enforcement: Operations only available after specific time periodsEmergency Recovery: Rescue mechanism for stuck fundsGas Fee Protection: Gas fees are returned to withdrawal callers📈 Performance OptimizationsClone Pattern: Gas-efficient contract deploymentEvent-driven Architecture: Real-time processing without pollingIn-memory Storage: Fast swap state managementBatch Operations: Efficient multi-swap processing🔮 Future Additions[ ]Private P2P swaps[ ]Integrations with WhatsApp, Telegram, etc.[ ]P2P Net Swaps (multi-party settlements)[ ] Support for additional blockchain networks[ ] Mobile application development[ ] Enhanced security features[ ] Governance token integrationBuilt with ❤️ for the decentralized future
Solution
How I Built PeerSwap - The Real StorySo I was thinking about this problem where people have tokens on different chains but can't easily trade them. Like, you have USDC on Base but want some random token that only exists on Tempo chain. There's no bridge, no DEX has the pair, and centralized exchanges are a pain.The Core IdeaI wanted to build something where two people could trade directly - no middleman, no bridges, just pure P2P. The key insight was usinghashlocked escrowswith timelocks. It's like a cryptographic handshake where both parties have to commit before either can back out.The Tech Stack I ChoseSmart Contracts (Solidity)I went with a factory pattern using OpenZeppelin's clone system. This was crucial because deploying new escrows for each swap would be expensive. The clone pattern lets me deploy cheaply while keeping each escrow as a separate contract. I used CREATE2 for deterministic addresses - this was important for the relayer to know where escrows would be deployed.The contracts are pretty complex with multiple timelock stages. I spent a lot of time getting the security right - there are different permissions at different time periods, and I had to handle edge cases like stuck funds.Backend (Node.js/TypeScript)I built an Express API that acts as a relayer. The key thing here is that the relayer coordinates but never holds funds - it's just facilitating the cross-chain communication. I used in-memory storage for speed, and built an event-driven system that listens to blockchain events in real-time.Frontend (Next.js/React)I integrated with Farcaster as a mini app because I wanted social discovery. People can find trading partners through their social network, which builds trust. I used Wagmi for wallet integration and built a smooth UX for cross-chain transactions.The Really Hacky PartsMulti-Stage Timelock SystemThis was probably the most complex part. I created different permission levels at different time periods:First 24 hours: Only the original user can withdraw with the secret24-48 hours: Anyone with an access token can withdraw48-72 hours: Public cancellation becomes availableAfter 72 hours: Only rescue is possibleThe access token system was my solution to the "what if someone disappears" problem. It lets the community help complete stuck swaps.Cross-Chain Secret RevelationGetting the secret to work across chains while maintaining atomicity was tricky. I had to make sure that revealing the secret on one chain would unlock funds on both chains, but only if both escrows were properly set up.Emergency RecoveryI built a 72-hour rescue mechanism. If someone disappears or something goes wrong, the community can rescue funds after a long enough period. This was important for user confidence.Partner Technology BenefitsFarcaster IntegrationThis was huge for user experience. Instead of just posting "I want to trade X for Y" on random forums, people can do it through their social network. It builds trust because you're trading with people you know or have mutual connections with.Worldcoin IntegrationI added Worldcoin for identity verification. This prevents spam and multiple accounts from the same person. It also helps with compliance - regulators like knowing who's doing what.Self SDK IntegrationI integrated Self SDK for enhanced user experience and identity management. This provides additional layers of user verification and helps create a more trusted environment for P2P trading. The SDK's identity features complement the Worldcoin verification, creating a robust user authentication system.Fluence Virtual ServerI used Fluence's virtual server infrastructure for decentralized backend services. This was crucial for maintaining the decentralized nature of the platform - instead of relying on centralized servers, the relayer services run on Fluence's decentralized network. This ensures that even the coordination layer remains decentralized and resilient.The Clever BitsGas Fee ProtectionI made sure that whoever calls the withdrawal function gets their gas fees back. This prevents users from being penalized for completing swaps.Event-Driven ArchitectureInstead of polling the blockchain constantly, I built an event-driven system that responds immediately when things happen. This makes the UX much smoother.Clone Pattern for Gas EfficiencyUsing OpenZeppelin's clone pattern was crucial for keeping costs down. Each swap needs its own escrow, but deploying full contracts would be expensive.Decentralized InfrastructureThe combination of Fluence's virtual servers and Self SDK creates a truly decentralized experience. Users don't have to trust any centralized entity - not even for the coordination services.What Made It WorkThe combination of social integration (Farcaster), identity verification (Worldcoin + Self SDK), decentralized infrastructure (Fluence), and trustless P2P mechanics creates something that's both secure and user-friendly. The timelock system handles edge cases while maintaining the trustless nature.The relayer coordination without custody was key - it enables cross-chain functionality while keeping the system decentralized. The relayer just facilitates communication, it never touches the funds.The ResultI ended up with a system where two people can trade tokens across chains without trusting each other or any centralized entity. The social integration makes it easy to find trading partners, and the security mechanisms handle all the edge cases.It's live at peerswap.vercel.app and works on Ethereum Sepolia and Base Sepolia. The whole thing took about 48 hours of intense coding, but the result is something that actually solves a real problem in a trustless way.Technical Deep DiveSecurity Mechanisms - The "Hacky" PartsHashlock SystemSecret Generation: Users generate random secretsOne-way Hashing: keccak256 prevents front-runningAtomic Swaps: Both escrows succeed or both failMulti-Stage Timelock SystemSource Chain Stages:SrcWithdrawal(0-24h): Only asker with secretSrcPublicWithdrawal(24-48h): Anyone with access tokenSrcCancellation(24-48h): Only asker can cancelSrcPublicCancellation(48-72h): Public cancellationDestination Chain Stages:DstWithdrawal(0-24h): Only asker with secretDstPublicWithdrawal(24-48h): Public withdrawalDstCancellation(24-48h): Only fulfiller can cancelCross-Chain SecurityExecution Data Validation: All operations verify data integrityAccess Token Control: Public functions require token ownershipEmergency Recovery: Rescue mechanism after 72hNotable Technical Innovations1. Relayer Coordination Without CustodyThe relayer coordinates cross-chain operations but never controls funds - this is particularly clever because it maintains decentralization while enabling cross-chain functionality.2. Multi-Stage Timelock SystemThe complex timelock system with different permissions at different stages is quite sophisticated - it handles edge cases like stuck funds while maintaining security.3. Clone Pattern for Gas EfficiencyUsing OpenZeppelin's clone pattern for escrow deployment is gas-efficient and allows for predictable addresses.4. Event-Driven ArchitectureReal-time blockchain event processing without polling - this is efficient and responsive.Performance OptimizationsIn-memory Storage: Fast swap state managementBatch Operations: Efficient multi-swap processingEvent-driven Architecture: No polling requiredClone Pattern: Gas-efficient deploymentsSupported NetworksEthereum Sepolia (Chain ID: 11155111)Base Sepolia (Chain ID: 84532)
Hackathon
ETHGlobal New Delhi
2025
Contributors
- mbcse
40 contributions