project screenshot 1
project screenshot 2
project screenshot 3

LockedIn

Secure, atomic cross-chain swaps between evm and non evm chains, but easier.

LockedIn

Created At

Unite Defi

Project Description

ChainCrossing is a cutting-edge decentralized application (dApp) designed to facilitate secure and seamless value transfer between the Bitcoin and Ethereum blockchains. It addresses the fundamental challenge of blockchain interoperability, allowing users to move assets like native Bitcoin (BTC) to the Ethereum ecosystem (represented as Wrapped Bitcoin, WBTC, or other ERC-20 tokens) and vice-versa, without relying on centralized intermediaries.

The Problem: Bitcoin and Ethereum are distinct blockchain networks, each with its own architecture, consensus mechanism, and token standards. This inherent separation means that assets on one chain cannot natively exist or be directly transacted on the other. Traditional bridging solutions often involve trusted third parties, introducing points of centralization and potential security risks.

Our Solution: Hashed Time-Lock Contracts (HTLCs) ChainCrossing leverages the power of Hashed Time-Lock Contracts (HTLCs) as its core mechanism. HTLCs are cryptographic primitives that enable atomic swaps, guaranteeing that either both sides of a cross-chain transaction are successfully completed, or neither is. This eliminates counterparty risk and ensures that funds are never lost in transit.

How it Works (Simplified HTLC Flow):

  1. Initiation: A user wishing to swap, for example, Ethereum's native currency (ETH) for Bitcoin (BTC), initiates a swap on the Ethereum side. They lock their ETH in a smart contract, providing a cryptographic hash of a secret "preimage" and a time limit (timelock).
  2. Counterparty Action: An off-chain "resolver" (a participant in the 1inch Fusion network) observes this locked transaction. The resolver then locks the equivalent amount of BTC on the Bitcoin blockchain, using the same cryptographic hash and a slightly shorter timelock.
  3. Redemption: To claim the BTC, the original user must reveal the secret preimage on the Bitcoin blockchain. This revelation makes the preimage publicly available.
  4. Completion: The resolver, seeing the preimage revealed on the Bitcoin chain, can then use it to claim the locked ETH on the Ethereum smart contract.

The timelocks ensure that if either party fails to complete their side of the swap within the specified time, the funds are automatically returned to their original owners, preventing any loss of assets.

Key Components:

  • BitcoinBridge.sol Smart Contract (Ethereum):

    • Deployed on the Ethereum blockchain, this Solidity smart contract is the heart of ChainCrossing.
    • It implements the HTLC logic, managing the locking and releasing of ERC-20 tokens (like WBTC or ETH) based on the cryptographic proofs (hashes and preimages) and time constraints.
    • Functions like initiate, redeem, and refund govern the lifecycle of each cross-chain swap, ensuring trustless execution.
    • It emits events (Initiated, Redeemed, Refunded) that the frontend monitors for real-time status updates.
  • Frontend Application (Next.js/React/TypeScript):

    • A user-friendly web interface built with Next.js and React, providing an intuitive experience for initiating cross-chain swaps.
    • Utilizes ethers.js to connect directly to the user's Web3 wallet (e.g., MetaMask), allowing them to securely interact with the BitcoinBridge.sol smart contract.
    • Features include:
      • Token Selection: Users can select the source and destination tokens for their swap.
      • Amount Input: Users specify the amount they wish to swap.
      • User-Defined Timelock: Users can set a custom timelock for their swap, offering flexibility while adhering to minimum security requirements.
      • Live Transaction Monitoring: A dedicated component listens for smart contract events, providing real-time updates on the status of the swap (pending, redeemed, refunded), enhancing transparency and user confidence.
    • The UI is styled with Tailwind CSS for a modern and responsive design.
  • Off-chain Resolver/Relayer (Future/Conceptual):

    • While the current implementation focuses on the core HTLC contract and frontend, a complete solution for the 1inch Fusion hackathon would involve an off-chain resolver service.
    • This service would monitor the Ethereum chain for new HTLC initiations, execute the corresponding locking transactions on the Bitcoin network, and then claim the funds on Ethereum once the Bitcoin side is confirmed.

Significance and Future: ChainCrossing represents a significant step towards a more interconnected blockchain ecosystem. By enabling trustless, atomic swaps between Bitcoin and Ethereum, it unlocks new possibilities for Bitcoin holders to participate in Ethereum's vibrant DeFi landscape. The project is specifically tailored to meet the requirements of the 1inch Fusion hackathon, demonstrating the practical application of HTLCs for secure cross-chain value transfer. Future enhancements will include full integration with the 1inch Fusion API for optimized quotes and order management, as well as a robust off-chain resolver implementation.

How it's Made

The ChainCrossing project is engineered to provide a robust and transparent solution for cross-chain asset transfers, specifically focusing on the Bitcoin and Ethereum networks. Its construction leverages a modern web development stack combined with battle-tested blockchain development tools and cryptographic primitives.

Core Technologies & How They Piece Together

  1. Smart Contract Layer (Solidity & Hardhat)
  • Solidity: The core logic for the cross-chain swaps is encapsulated within the BitcoinBridge.sol smart contract, written in Solidity. This contract is responsible for managing the Hashed Time-Lock Contracts (HTLCs), which are the cryptographic backbone ensuring the atomic (all-or-nothing) nature of the swaps.
  • Hardhat: This is our chosen Ethereum development environment. Hardhat was instrumental in:
    • Compilation: It compiles the Solidity code into bytecode and ABI (Application Binary Interface), which the frontend uses to interact with the contract. The compilation process involved careful debugging to align Solidity versions (^0.8.20) and correctly resolve OpenZeppelin import paths.
    • Local Development Network: Hardhat provides a local Ethereum network for rapid testing and iteration without deploying to a public testnet.
    • Deployment Scripts: Although not yet fully implemented, Hardhat will be used to write scripts for deploying the BitcoinBridge.sol contract to public testnets (like Sepolia) and eventually mainnet.
  • OpenZeppelin Contracts: We heavily rely on OpenZeppelin's battle-tested smart contract libraries, including ReentrancyGuard (to prevent re-entrant attacks, a common vulnerability in DeFi) and Ownable (for basic access control, allowing only the contract owner to perform certain administrative functions). These libraries significantly enhance the security and reliability of our contract by providing audited and widely used implementations of common patterns.
  1. Frontend Application (Next.js, React, TypeScript, Zustand, Ethers.js, Tailwind CSS)
  • Next.js & React: The user interface is built using Next.js, a React framework. This provides benefits like server-side rendering (SSR) for improved performance and SEO, file-system based routing, and an optimized development experience. React's component-based architecture allows for modular and reusable UI elements.
  • TypeScript: The entire frontend codebase is written in TypeScript. This provides static type checking, which significantly reduces runtime errors, improves code readability, and enhances developer productivity, especially in a complex domain like Web3 development where data structures (like contract ABIs) are critical.
  • Zustand (State Management): For managing global application state, particularly the user's wallet connection and network information, we utilize Zustand. Its lightweight and unopinionated nature, combined with its immer middleware for immutable state updates and persist middleware for local storage, makes it ideal for handling the dynamic and persistent aspects of wallet state.
  • Ethers.js: This is the primary library for interacting with the Ethereum blockchain from the frontend. Ethers.js is used to:
    • Connect to Wallets: It connects to the user's browser-injected Ethereum provider (e.g., MetaMask) to get their account address and network details.
    • Contract Interaction: It creates instances of our BitcoinBridge smart contract using its address and ABI, allowing the frontend to call contract functions (initiate) and send transactions.
    • Event Listening: Crucially, Ethers.js enables the frontend to listen for real-time events emitted by the BitcoinBridge contract (Initiated, Redeemed, Refunded). This powers the live transaction monitoring feature.
  • Tailwind CSS: The styling of the application is handled by Tailwind CSS. Its utility-first approach allows for rapid UI development and ensures a consistent design system without writing custom CSS.

How Components Integrate

  1. Wallet Connection: The useWalletStore (Zustand) manages the connection to the user's Web3 wallet via ethers.js. When a user connects, the ethers.BrowserProvider instance is stored, making it accessible throughout the application.
  2. Form Logic (useBridgeFormState.ts): This custom React hook encapsulates the complex logic for the bridge form. It manages input states (from/to tokens, amounts, timelock, resolver), handles form validation, and orchestrates the interaction with the smart contract. It retrieves the ethers.BrowserProvider from the useWalletStore to sign and send transactions.
  3. Smart Contract Interaction (handleInitiateSwap): When the user initiates a swap, the handleInitiateSwap function (within useBridgeFormState) uses the ethers.js Contract instance to call the initiate function on the deployed BitcoinBridge.sol contract. It passes the unique swap ID, resolver address, a generated hash (from a secret preimage), and the user-defined timelock, along with the ETH amount.
  4. Live Transaction Monitoring (TransactionMonitor.tsx): This dedicated component subscribes to the Initiated, Redeemed, and Refunded events emitted by the BitcoinBridge contract. When an event related to the user's htlcId is detected, the UI updates in real-time, providing transparency on the swap's progress.

Notable Aspects & "Hacky" Details

  • Transition to HTLCs: A significant undertaking was refactoring the existing BitcoinBridge.sol from a validator-based model to a trustless HTLC system. This involved removing substantial legacy code and introducing the new HTLC struct and its associated initiate, redeem, and refund functions, while maintaining the contract's core purpose.
  • Manual Hardhat Setup: Due to the non-interactive nature of the development environment, the Hardhat project setup (creating hardhat.config.ts and directory structure) was performed manually, followed by iterative debugging of compilation errors related to OpenZeppelin import paths and Solidity version compatibility.
  • Placeholder for 1inch Fusion API: While the smart contract and frontend are ready for HTLCs, the full integration with the 1inch Fusion API for quote fetching and order creation is a planned next step. Currently, the handleInitiateSwap function generates a placeholder hash and ID.
  • Off-Chain Resolver (Conceptual): The project's current scope focuses on the on-chain Ethereum component and the user-facing frontend. A complete cross-chain solution, especially for the hackathon, would necessitate an off-chain "resolver" service that monitors the Ethereum chain, performs the corresponding Bitcoin HTLC, and then calls the redeem function on the Ethereum side. This is a critical piece for the full bidirectional swap functionality.
  • User-Controlled Timelock: A key feature is allowing users to set their own timelock. While this offers flexibility, it requires careful validation (e.g., enforcing a minimum timelock) to ensure the resolver has sufficient time to complete their part of the atomic swap, preventing potential griefing attacks.

In summary, ChainCrossing is a robust, modular, and transparent cross-chain bridging solution built on secure smart contract principles and a modern, user-centric frontend. Its design prioritizes trustlessness and real-time feedback, setting a strong foundation for future expansion and integration within the broader DeFi ecosystem.

background image mobile

Join the mailing list

Get the latest news and updates