← Back to home

AvgInch

1inch Fusion+ on the ICP, bringing the Internet Computer to the best web3 aggregator

Problem Statement

ICP-Fusion: Cross-Chain Atomic SwapsProject OverviewICP-Fusionbrings 1inch Fusion+ to the Internet Computer Protocol (ICP), enabling fully trustless cross-chain atomic swaps between EVM networks and ICP without relying on bridges, wrapped assets, or intermediaries. This revolutionary project implements a complete cross-chain atomic swap infrastructure that allows users to trade any supported token directly between Ethereum Virtual Machine (EVM) compatible networks and the Internet Computer Protocol with cryptographic guarantees.The system establishes a new paradigm for cross-chain transactions by eliminating the need for centralized exchanges, wrapped tokens, bridge protocols, or traditional liquidity pools. Unlike conventional cross-chain solutions that require pre-deposited liquidity in pools or rely on centralized market makers, ICP-Fusion operates on a resolver-based model where any resolver holding the desired tokens can facilitate swaps on-demand.No Liquidity Pools RequiredTraditional cross-chain solutions require massive liquidity pools pre-funded with tokens on both sides of every possible trading pair. ICP-Fusion eliminates this inefficiency through its resolver system:On-Demand Liquidity: Resolvers only need to hold tokens they're willing to trade, not maintain balanced poolsDynamic Market Making: Any entity with tokens can become a resolver and earn fees by facilitating swapsCapital Efficiency: No need to lock tokens in idle liquidity pools waiting for tradesUnlimited Trading Pairs: Any token combination is possible as long as a resolver supports both assetsUniversal Token SupportThe system's architecture supports any token that can be transferred on their respective networks:EVM Tokens: Full support for ETH, ERC-20 tokens, and any custom token implementationsICP Assets: Native ICP, ICRC-1 tokens, and any canister-based token standardsFuture Extensions: Architecture designed to easily add support for new token standardsNo Pre-approval: Tokens don't need to be whitelisted or approved by any central authorityResolver EconomicsResolvers operate as independent market makers with complete autonomy:Custom Pricing: Each resolver sets their own exchange rates and fee structuresRisk Management: Resolvers choose which tokens to support and trading limitsCompetitive Market: Multiple resolvers can compete for the same tradesInstant Settlement: Resolvers receive immediate compensation upon successful swap completionMarket Dynamics and Network EffectsResolver Competition:Rate Competition: Multiple resolvers compete for trades by offering better exchange ratesService Quality: Resolvers compete on speed, reliability, and customer serviceSpecialization: Some resolvers may specialize in specific token pairs or trading volumesGeographic Distribution: Global resolver network provides 24/7 liquidity availabilityNetwork Growth Benefits:Increasing Liquidity: More resolvers mean more available tokens and better pricesMarket Efficiency: Competition drives prices toward fair market valuesInnovation Incentives: Resolvers develop better tools and strategies to competeUser Benefits: Better prices, faster execution, and more token options over timeTrustless Execution ModelThe system ensures complete trustlessness through cryptographic guarantees and smart contract automation:Atomic Guarantees:All-or-Nothing Execution: Either both sides of the trade complete or both revertNo Counterparty Risk: Users never need to trust resolvers with their fundsCryptographic Proof: Mathematical certainty that trades execute as agreedTime-Bounded Safety: Automatic refunds prevent indefinite fund lockingSmart Contract Security:Immutable Logic: Core swap mechanics cannot be changed after deploymentDeterministic Outcomes: Identical inputs always produce identical resultsPublic Verification: All operations can be independently verified on-chainEmergency Safeguards: Built-in recovery mechanisms for edge casesEconomic Model and IncentivesResolver Revenue StreamsTrading Fees:Resolvers earn fees on every successful swap they facilitateCompetitive market allows for dynamic fee structuresVolume-based incentives encourage larger resolversSpread Profits:Resolvers can profit from bid-ask spreads on token exchangesMarket making opportunities across different price sourcesArbitrage profits from cross-chain price differencesService Premiums:Premium pricing for faster execution or rare token pairsSpecialized services for large volume tradesCustom pricing for enterprise clientsUser BenefitsCost Savings:No liquidity pool fees or impermanent lossCompetitive resolver pricing drives down costsDirect peer-to-peer trading without intermediary markupsAccess to Unique Assets:Trade tokens that don't exist in traditional liquidity poolsAccess to newly launched tokens across different chainsAbility to trade any amount without slippage concernsSpeed and Convenience:Near-instant quotes from available resolversNo waiting for liquidity pool rebalancing24/7 availability through global resolver networkProtocol SustainabilityFee Distribution:Protocol fees ensure ongoing development and maintenanceTreasury management for long-term sustainabilityCommunity governance over fee structures and protocol upgradesNetwork Effects:More users attract more resolversMore resolvers provide better service for usersSelf-reinforcing growth cycleScalability and PerformanceMulti-Chain ExpansionHorizontal Scaling:Easy addition of new EVM-compatible chainsModular architecture supports diverse blockchain networksMinimal development effort for new chain integrationPerformance Optimization:Parallel processing of multiple swapsEfficient resolver discovery and matching algorithmsOptimized smart contract gas usageTechnical InnovationNovel Architecture PatternsDeterministic Deployment:Smart contracts with predictable addressesEnables advanced workflow optimizationsReduces complexity in cross-chain coordinationHybrid On-Chain/Off-Chain Model:Critical operations secured by blockchain immutabilityPerformance optimization through off-chain coordinationBest of both worlds approach to scalingSecurity FrameworkCryptographic Guarantees:Mathematical proof of atomic execution across chainsImmutable smart contract logic prevents manipulationTime-locked mechanisms ensure automatic recoveryPublic verification of all operationsRisk Mitigation:Resolver diversification reduces single points of failureAutomated monitoring and alerting systemsEmergency protocols for edge case scenariosComprehensive audit trails for all operationsCurrent Implementation StatusProduction-Ready Features✅Universal Token Support: Any ERC-20 token on EVM side, any ICRC-1 token on ICP side✅Resolver-Based Liquidity: No liquidity pools required, on-demand token availability✅Competitive Market: Multiple resolvers can compete for the same trades✅Dynamic Pricing: Real-time price discovery based on resolver preferences✅Atomic Execution: Cryptographically guaranteed all-or-nothing trade execution✅Multi-Chain Support: Compatible with any EVM network and Internet Computer✅Trustless Operations: No need to trust counterparties or intermediaries✅Emergency Recovery: Time-locked mechanisms prevent permanent fund lossAdvanced Capabilities✅Deterministic Addresses: Escrow contracts with predictable addresses✅Cross-Chain Coordination: Intelligent sequencing and retry logic✅Real-Time Monitoring: Live status tracking and automated error recovery✅Scalable Architecture: Support for unlimited token pairs and trading volumes✅Gas Optimization: Efficient smart contract design minimizes transaction costs✅Developer Tools: Comprehensive APIs and SDKs for integration

Solution

TECHNOLOGY STACKEVM Smart Contracts (Solidity + Hardhat)Factory pattern with CREATE2 for deterministic addressesOpenZeppelin contracts for securityPacked structs and immutable variables for gas optimizationTime-locked escrows with public withdrawal fallbacksICP Canister Backend (Rust)Internet Computer CDK for canister developmentDirect ICP ledger integration without wrapper tokensPersistent storage across canister upgradesPrincipal-based auth with public withdrawal supportResolver Service (Node.js + Express)Ethers.js for EVM, @dfinity/agent for ICP integration90-second timing buffers for ICP operations (learned through testing)Smart withdrawal sequencing (EVM first, then ICP)Exponential backoff retry logic up to 3.5 minutesFrontend (React + TypeScript + Vite)Tailwind CSS for stylingDirect contract interaction without external APIsReal-time status tracking and wallet integrationIMPLEMENTING 1INCH FUSION+ FOR CROSS-CHAINWe attempted to implement the 1inch Fusion+ protocol for cross-chain scenarios, which required completely reimagining the architecture:Fusion+ Core Concepts We Implemented:Resolver-based liquidity eliminating the need for poolsCompetitive market dynamics between multiple resolversOn-demand liquidity provision from resolver holdingsDynamic pricing based on resolver preferencesCross-Chain Adaptations We Built:Cryptographic hashlock coordination across different consensus systemsTime-synchronized operations between EVM and ICP networksDeterministic address calculation across heterogeneous chainsAtomic execution guarantees without trusted intermediariesSMART CONTRACT ARCHITECTUREEVM Factory Pattern: contract ICPEscrowFactory { function createEscrow(bytes32 salt) external returns (address) { return Clones.cloneDeterministic(implementation, salt); } }Salt generation ensures both chains calculate identical escrow addresses: bytes32 salt = keccak256(abi.encodePacked(orderHash, maker, taker, token, amount));ICP Canister Structure:Escrow state management with persistent storageDirect ledger integration for ICP transfersTime-based authorization with nanosecond precisionPublic withdrawal mechanisms for emergency recoveryRESOLVER COORDINATION ENGINEThe resolver service handles complex cross-chain timing coordination: async function scheduleWithdrawal(orderData) { // Wait for both escrows to be properly funded await waitForEscrowFunding(orderData);// Add timing buffer for ICP consensus await new Promise(resolve => setTimeout(resolve, 90000)); // Execute withdrawal with smart sequencing return executeWithdrawal(orderData);Key optimizations:EVM operations first, then ICP (discovered through testing)Exponential backoff for failed operationsConnection pooling for blockchain RPC callsParallel status checking across chainsTECHNICAL CHALLENGES SOLVEDCross-Chain Timing Synchronization:ICP consensus requires 3x longer than EVM (90+ second buffers)Implemented intelligent retry logic with exponential backoffState synchronization across different finality modelsDecimal Conversion Precision:ETH uses 18 decimals (wei), ICP uses 8 decimals (e8s)Solution:BigInt(etherAmount) / BigInt(10**10)Prevents precision loss in large transactionsDeterministic Address Generation:Both chains must calculate identical escrow addressesUsed keccak256 hash of order parameters as CREATE2 saltEnables pre-calculation of addresses before deploymentICP Authorization Architecture:Implemented dual authorization systemPrivate operations use caller() for authenticationPublic operations available after timelock expirationEmergency recovery through community-accessible methodsHACKY STUFFGas-Optimized Timelock Packing: We pack 4 timelock values into a single uint256 storage slot: function packTimelocks(uint256 w, uint256 p, uint256 c, uint256 d) returns (uint256) { return (d << 192) | (c << 128) | (p << 64) | w; } This saves ~75% gas costs compared to separate storage slots.Cross-Chain State Machine: Built a custom state machine for tracking escrow lifecycle:PENDING → FUNDED → WITHDRAWING → COMPLETEDEach state has specific timelock requirementsAutomatic transitions based on blockchain eventsDEVELOPMENT WORKFLOW OPTIMIZATIONSRapid Testing Setup:30-second withdrawal windows for fast iteration60-second public withdrawal timeouts90-second resolver buffers with 3 retry attemptsComplete end-to-end test cycle in under 5 minutesContract Deployment Pipeline:Deploy ICP canister with dfx deployDeploy EVM contracts to Base Sepolia testnetUpdate resolver config with deployed addressesRun integration tests across all components (More info in the repo I swear)PERFORMANCE OPTIMIZATIONS AND SECURITY EVM Optimizations:Immutable variables for deployment-time constantsPacked structs to minimize storage operationsCREATE2 deterministic deploymentICP Optimizations:Batch canister calls to reduce round tripsPersistent storage for critical state across upgradesDirect ledger integration avoiding wrapper overheadQuery vs update call optimizationSecurity Model:SHA256 hashlocks for maximum cross-chain compatibilityTime-bounded execution preventing indefinite fund locksImmutable core logic in deployed smart contractsIndependent verification on both blockchain networksMathematical proof of atomic executionLESSONS LEARNED DURING HACKATHON Timing is Everything: ICP consensus mechanisms require significantly longer buffers than EVM. What works instantly on Ethereum can take 90+ seconds on ICP due to subnet consensus requirements.Cross-Chain Testing Complexity: Integration testing across two different blockchain environments with different development tools, deployment processes, and debugging methods requires patience and sophisticated tooling.Resolver Economics Balance: Need sufficient resolvers for competitive pricing but enough volume per resolver to make participation profitable. Too few resolvers = poor prices; too many = insufficient volume.User Experience Challenges: Explaining atomic swaps to users is difficult. The concept of "either both sides execute or both revert" requires careful UX design and clear status communication.CURRENT LIMITATIONS AND FUTURE WORK Known Issues:Occasional "Unauthorized" errors in ICP public withdrawals (timing-related)Gas costs could be optimized further with advanced assembly techniquesFrontend error handling could provide better user feedbackResolver discovery mechanism could be more sophisticated

Hackathon

ETHGlobal Unite

2025

Prizes

  • 🏆

    Extend Fusion+ to ICP1st place

    1inch

Contributors