Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Guides

How to Design a Cross-Chain Atomic Swap Infrastructure

This guide details the implementation of trustless atomic swaps between different blockchains using Hash Time-Locked Contracts (HTLCs), covering protocol design, the swap coordination layer, and handling varying block times.
Chainscore © 2026
introduction
ARCHITECTURE GUIDE

Introduction to Trustless Cross-Chain Swaps

A technical deep dive into designing a peer-to-peer atomic swap infrastructure, enabling direct asset exchange between different blockchains without centralized intermediaries.

A trustless cross-chain atomic swap is a peer-to-peer protocol that allows two parties to exchange assets on different blockchains without relying on a trusted third party. The core mechanism is based on Hash Time-Locked Contracts (HTLCs), cryptographic constructs that create a conditional payment. The swap is "atomic," meaning it either completes entirely for both parties or fails and refunds both, eliminating the risk of one party defaulting. This design is fundamental for decentralized interoperability, moving beyond custodial bridges and centralized exchanges.

The protocol operates on a simple but powerful principle: both parties lock their funds into smart contracts (or script-enabled outputs) that can only be claimed by revealing a secret preimage. Party A initiates by generating a cryptographic secret and hashing it to create a commitment hash. They then lock their funds in a contract on Chain A, payable to Party B, but only if B can provide the preimage that hashes to the commitment within a set time T1. Party B, seeing this lock, creates a corresponding contract on Chain B, locking their funds payable to Party A under the same hash condition, but with a shorter timeout T2.

The swap execution is sequential and secure. Once Party B's contract is visible on Chain B, Party A can claim the funds there by revealing the secret preimage. This act of claiming publicly reveals the secret on Chain B's ledger. Party B can then use this now-public secret to claim the funds locked in Party A's original contract on Chain A before the timeout T1 expires. If any step fails—for instance, if Party B never creates the second contract—the original funds are automatically refunded to their owner after the timeout period, ensuring no capital is permanently locked.

Designing this infrastructure requires addressing several key challenges. Blockchain heterogeneity is primary: you must adapt the HTLC logic to the specific smart contract language (Solidity, Rust, Clarity) or scripting system (Bitcoin Script) of each chain. Timing parameters (T1, T2) must be carefully calibrated based on each chain's block time and finality guarantees to prevent griefing attacks. Furthermore, a practical system needs a discovery and negotiation layer—often implemented as a peer-to-peer network or a decentralized order book—to help users find counterparties and agree on swap terms like amounts and assets.

For developers, implementing an HTLC on an EVM chain like Ethereum involves a straightforward smart contract. The core functions are createSwap (to lock funds with a hash and timeout), claim (to withdraw funds by submitting the preimage), and refund (to reclaim funds after the timeout). A critical security practice is to ensure the claim function validates the preimage correctly using sha256(preimage) == commitmentHash and transfers funds to the claimant atomically within the same transaction.

While powerful for simple asset swaps, the basic atomic swap model has limitations. It requires both blockchains to support programmable conditional logic (HTLCs), which excludes non-smart contract chains without adaptations like adaptor signatures. It also involves multiple on-chain transactions, leading to fee costs and latency. Modern cross-chain messaging protocols like Inter-Blockchain Communication (IBC) and certain bridge architectures have evolved from these principles, using similar cryptographic conditional transfers to facilitate more complex cross-chain operations beyond simple swaps.

prerequisites
INFRASTRUCTURE DESIGN

Prerequisites for Building Atomic Swaps

A foundational guide to the core components and design decisions required to build a secure, trust-minimized cross-chain atomic swap system.

Atomic swaps enable the direct, peer-to-peer exchange of assets across different blockchains without a trusted intermediary. The core mechanism relies on Hash Time-Locked Contracts (HTLCs), cryptographic constructs that create a conditional payment. To build this infrastructure, you must first understand the fundamental components: a cryptographic hash function (like SHA-256), time-locks (e.g., Bitcoin's OP_CHECKLOCKTIMEVERIFY or Ethereum's block.timestamp), and the ability for both blockchains to verify the same secret preimage. The swap's security is derived from the atomicity property: either the entire exchange completes successfully for both parties, or all funds are refunded.

The first major prerequisite is blockchain compatibility. Not all chains support the necessary opcodes for HTLCs natively. For Ethereum and EVM-compatible chains (Arbitrum, Polygon), you write a smart contract. For Bitcoin, you use a script in a P2SH (Pay-to-Script-Hash) address. For chains without smart contracts, like Litecoin, similar script functionality is required. You must audit each chain's specific scripting language and transaction model. A swap between Bitcoin and Ethereum, for instance, requires deploying a Solidity contract on Ethereum and crafting a Bitcoin script, both programmed to adhere to the same hashlock and timelock logic.

Next, you need a secure method for secret generation and revelation. Party A initiates the swap by generating a cryptographically random secret (the preimage) and publishing its hash. Party B must be able to verify this hash on their chain. The critical moment is when Party B claims the funds on Chain A by revealing the preimage, which then allows Party A to claim funds on Chain B. Your infrastructure must handle this cross-chain proof-of-knowledge securely, ensuring the revealed preimage is captured and propagated. Oracles or relayers are often used for this data bridging, but they introduce trust assumptions; purely atomic designs rely on the parties themselves to submit the proof.

Time-lock configuration is a crucial security parameter that requires careful design. You must set two timelocks: one for the initial offer and a shorter one for the counter-party's claim. If Party B doesn't claim the funds on Chain A before the first lock expires, Party A can refund. After Party B claims, Party A has a shorter window to claim on Chain B using the revealed secret. Miscalculating these blocks or timestamps can lead to lost funds. Your system must accurately track block heights or timestamps across both chains, accounting for potential reorgs and differing block times (e.g., ~10 minutes for Bitcoin vs. ~12 seconds for Ethereum).

Finally, you must design the user interaction layer and transaction coordination. This involves creating or integrating a wallet that can sign transactions for both chains, constructing the raw HTLC transactions or contract calls, and monitoring the blockchain states. A typical implementation flow uses a state machine tracking: INITIATED, FUNDED, SECRET_REVEALED, COMPLETED, or REFUNDED. Developers often use libraries like bitcoinjs-lib for Bitcoin scripting and ethers.js/web3.js for Ethereum interaction. The front-end must guide users through the multi-step process, displaying clear timers and transaction statuses to prevent errors from misaligned actions.

key-concepts-text
TUTORIAL

Core Concepts: Hash Time-Locked Contracts (HTLCs)

A technical guide to designing a cross-chain atomic swap infrastructure using HTLCs, covering protocol design, contract logic, and security considerations.

A Hash Time-Locked Contract (HTLC) is a specialized smart contract that enables trust-minimized, atomic cross-chain swaps. It acts as a conditional escrow, locking funds until a recipient provides a cryptographic proof of knowledge (a secret preimage) or until a predefined timelock expires. This mechanism is the foundation for peer-to-peer atomic swaps, allowing users to exchange assets across different blockchains without a centralized intermediary. The atomicity ensures the swap either completes entirely for both parties or fails, returning funds, eliminating counterparty risk.

Designing the swap infrastructure requires defining two core contract states. The first contract, deployed on Chain A, locks Asset A with a hash H = SHA256(secret). It can be claimed by anyone who reveals the secret preimage, paying the recipient. If unclaimed, the original depositor can refund after time T1. The second, mirrored contract on Chain B locks Asset B with the same hash H. Its claimant must provide the secret to receive funds, and its refund timelock T2 must be significantly longer than T1 (e.g., T2 = T1 + 24 hours). This asymmetry prevents a scenario where one party can claim an asset and then refund the other.

The user flow begins with Alice, who wants to swap her Bitcoin for Bob's Ethereum. Alice generates a random secret, computes its hash H, and initiates the swap by locking her BTC into a Bitcoin HTLC, publishing H with a 48-hour refund lock (T1). Bob, seeing this, locks his ETH into an Ethereum HTLC using the same H, with a 72-hour refund lock (T2). To claim the BTC, Bob must first discover the secret by interacting with the Ethereum contract, which publicly reveals it on-chain. Alice can then use that revealed secret to claim the ETH. If Bob never locks the ETH, Alice simply refunds her BTC after T1.

Critical security parameters must be carefully configured. The timelock delta (T2 - T1) is essential for safety; it must provide ample time for the second claim transaction to be mined after the secret is revealed. Network congestion and variable block times must be factored in. Furthermore, the hash function (typically SHA256) and its preimage must be generated securely off-chain. A flawed implementation could allow front-running or griefing attacks. Always use audited, standard implementations like those in the Bitcoin BIP199 specification.

While foundational, basic HTLCs have limitations for modern DeFi. They require both chains to support compatible smart contracts or script languages (limiting Bitcoin to specific scripts like P2SH). They also involve multiple on-chain transactions, leading to high fees and latency. These constraints have led to the development of cross-chain messaging protocols (like IBC) and liquidity network models (like Lightning Network) that use HTLCs as a lower-layer primitive for routed payments, offering better scalability and user experience for frequent swaps.

how-it-works
INFRASTRUCTURE DESIGN

The Atomic Swap Protocol: Step-by-Step

A technical guide to designing the core components for a trustless, cross-chain asset exchange system.

03

Designing the Swap Protocol Flow

The step-by-step message flow between two parties (Alice and Bob) to execute a swap.

  1. Negotiation: Agree on assets, amounts, and the hash H of secret R.
  2. Initiation: Alice deploys HTLC on her chain, funding it with the agreed amount.
  3. Participation: After verifying Alice's contract, Bob deploys the corresponding HTLC on his chain.
  4. Claim: Alice reveals R to claim Bob's funds, inadvertently revealing it to Bob.
  5. Finalization: Bob uses R to claim Alice's funds.
  • Atomicity: The swap either completes fully for both parties or fails completely, with funds refunded.
05

Handling Transaction Malleability & Fees

Practical challenges that must be addressed in production infrastructure.

  • Malleability: On chains like Bitcoin, transaction IDs can change before confirmation, breaking the protocol's tracking. Solutions include using SegWit transactions or watching for specific script patterns.
  • Dynamic Fees: Timelocks must account for variable network congestion. Implement fee estimation to ensure refund transactions can be broadcast and confirmed before the HTLC expires.
  • Watchtowers: For long-duration swaps, consider a service to monitor the blockchain and submit the claim transaction if the user goes offline.
coordination-layer
CROSS-CHAIN INFRASTRUCTURE

Designing the Swap Coordination Layer

A guide to building the core logic that enables secure, trust-minimized asset exchanges across different blockchain networks.

A swap coordination layer is the central logic that orchestrates a cross-chain atomic swap. Its primary function is to ensure the atomicity of the exchange: either both legs of the trade succeed, or the entire transaction is reverted, preventing one party from receiving an asset without sending theirs. This layer does not hold user funds directly but manages the conditional logic and state transitions that govern the swap lifecycle. It must be designed to be network-agnostic, capable of interfacing with diverse blockchain environments like Ethereum, Solana, or Cosmos, each with its own execution model and finality guarantees.

The core mechanism relies on hash time-locked contracts (HTLCs) or their modern variants. The coordinator generates a cryptographic secret and its hash. The initiating party locks funds in a smart contract on Chain A, conditional on the secret's revelation. The coordinator relays this hash to Chain B, where the counterparty can lock their funds under the same condition. Once the initiator reveals the secret to claim the funds on Chain B, the coordinator facilitates the propagation of that secret back to Chain A, allowing the counterparty to finalize the swap. The time-lock is a critical safety mechanism that allows users to refund their assets if the swap stalls.

Designing the coordinator requires robust message passing and state management. You must implement a reliable way to observe events (like fund locks) on source chains and dispatch corresponding transactions to destination chains. Services like Chainlink's CCIP, Axelar's General Message Passing, or Wormhole's generic messaging are often used for this cross-chain communication. The coordinator's internal state machine should track each swap through stages: Pending, FundsLocked, SecretRevealed, Completed, or Expired. This state must be persistently stored and easily queryable by users to monitor swap progress.

Security is paramount. The coordinator must be upgradeable to patch vulnerabilities but also have clear governance to prevent malicious upgrades. Consider implementing a timelock on upgrades. Furthermore, the logic must account for chain-specific risks, such as reorgs on probabilistic finality chains or validator censorship. Using multiple, decentralized oracle networks for cross-chain message verification can reduce reliance on a single point of failure. Always conduct formal verification or extensive audits on the coordination smart contracts, as they define the rules for potentially high-value transactions.

For development, a typical architecture involves a set of smart contracts on each supported chain and an off-chain relayer or watchtower service. The off-chain component listens for on-chain events via RPC nodes, updates the central state database, and submits the necessary transactions to advance swaps. Here's a simplified conceptual flow in pseudocode:

code
// 1. User initiates swap on Ethereum
initiateSwap(recipient, hashLock, timelock);

// 2. Coordinator detects Ethereum event
EventDetected -> StateDB.update(swapId, ETH_LOCKED);

// 3. Coordinator calls function on Solana
callSolanaContract(createLock(swapId, hashLock, timelock));

// 4. Handle secret revelation
secretRevealedOnSolana -> relaySecretToEthereum(secret);

Finally, focus on the user experience. Provide clear SDKs and APIs for developers to integrate the swap layer. Expose a public status API for tracking swaps via their ID. Consider implementing gas sponsorship mechanisms, where the coordinator pays for relay transactions, to abstract away the complexity of holding native gas tokens on multiple chains for end-users. The design should aim for composability, allowing this coordination layer to be integrated into larger DeFi applications like cross-chain DEX aggregators or lending protocols that require atomic, multi-chain settlements.

finality-challenges
CROSS-CHAIN INFRASTRUCTURE

Handling Varying Block Times and Finality

Designing a cross-chain atomic swap requires a robust strategy to manage the inherent timing differences between blockchains. This guide explains the core challenges and architectural patterns for building reliable swap infrastructure.

Block time and finality are fundamental properties that vary drastically between chains, directly impacting atomic swap security. Block time is the average interval between new blocks (e.g., ~12 seconds for Ethereum, ~2 seconds for Polygon PoS, ~10 minutes for Bitcoin). Finality is the guarantee that a transaction is irreversible. Ethereum achieves probabilistic finality, while networks like Cosmos or Polkadot offer near-instant, deterministic finality. A swap protocol must reconcile these differences to prevent one party from backing out after receiving assets but before their own transaction confirms.

The primary risk is a race condition where the participant on the faster chain can attempt to cancel their transaction after seeing the counterparty's transaction on the slower chain. To mitigate this, swaps use Hash Time-Locked Contracts (HTLCs). The core mechanism involves two cryptographic locks: a secret hash and a timelock. The initiating party locks funds with a hash H of a secret s. The counterparty must reveal s to claim these funds, which then allows the initiator to claim the counterparty's funds on the other chain. The timelock provides a safety refund if the swap fails.

Designing the timelocks is critical. They must account for the worst-case confirmation time on the slower chain, plus a significant buffer for network congestion. For a swap between Bitcoin (slow) and Solana (fast), the Bitcoin HTLC timelock might be set to 24 hours, while the Solana HTLC timelock would be a much shorter duration derived from the Bitcoin lock minus the Bitcoin confirmation buffer. This asymmetry ensures the party on the faster chain cannot wait out the slower chain's lock. Always query real-time network data for average block times and mempool status when calculating these values.

For implementation, you interact with HTLCs on each chain. Below is a simplified Solidity example for an Ethereum HTLC. The claim function requires the secret to unlock funds, while refund allows the original sender to recover them after the timelock expires.

solidity
contract HTLC {
    address public sender;
    address public recipient;
    bytes32 public hash;
    uint public timelock;
    
    constructor(address _recipient, bytes32 _hash, uint _timelock) payable {
        sender = msg.sender;
        recipient = _recipient;
        hash = _hash;
        timelock = block.timestamp + _timelock;
    }
    
    function claim(bytes32 secret) external {
        require(msg.sender == recipient);
        require(hash == keccak256(abi.encodePacked(secret)));
        payable(recipient).transfer(address(this).balance);
    }
    
    function refund() external {
        require(msg.sender == sender);
        require(block.timestamp >= timelock);
        payable(sender).transfer(address(this).balance);
    }
}

Beyond basic HTLCs, advanced infrastructures use watchtower services or oracle networks to monitor chain states and automate the claim/refund process, reducing user responsibility. Protocols like THORChain employ a continuous liquidity pool model with a network of validators to manage cross-chain settlements, abstracting away block time complexities from end-users. When designing your system, audit the finality assumptions of each connected chain; a chain with instant finality allows for faster, safer swaps but requires perfect synchronization logic in your protocol's state machine.

ARCHITECTURE COMPARISON

Atomic Swaps vs. Liquidity Bridges

Key technical and economic differences between peer-to-peer atomic swaps and intermediary-based liquidity bridges.

FeatureAtomic SwapsLiquidity Bridges

Settlement Mechanism

Peer-to-peer, hash timelock contracts (HTLCs)

Intermediary pool with mint/burn or lock/unlock

Counterparty Risk

Direct, time-bound to one party

Systemic, to bridge operator and smart contracts

Liquidity Requirement

None (direct asset swap)

High (pre-funded pools required)

Typical Fee Structure

Network gas fees only

Gas fees + protocol fee (0.05-0.5%)

Finality Time

10-60 minutes (block confirmations)

< 5 minutes (optimistic verification)

Custodial Risk

Interoperability

Native chain assets only

Wrapped assets (e.g., wBTC, stETH)

Capital Efficiency

High (no locked capital)

Low (capital locked in pools)

common-mistakes-grid
CROSS-CHAIN ATOMIC SWAPS

Common Implementation Mistakes and Pitfalls

Atomic swaps enable direct, trustless asset exchange between blockchains. Avoiding these common errors is critical for building secure, reliable infrastructure.

01

Insufficient Time-Lock Handling

Mismanaging HTLC time-locks is a leading cause of failed swaps or lost funds. Common errors include:

  • Setting timelocks too short, causing transactions to expire before network congestion clears.
  • Not accounting for block time variance between chains (e.g., Bitcoin vs. Solana).
  • Failing to implement a clear refund path if the counterparty disappears.

Example: A 10-block timelock on Ethereum may be ~2 minutes, but a 10-block lock on Bitcoin is ~100 minutes, creating a significant mismatch.

02

Poor Hash Secret Generation & Management

The cryptographic preimage secret must be generated and handled securely.

  • Mistake: Using weak randomness (e.g., Math.random() in JS) to generate the secret hash, making it predictable.
  • Mistake: Revealing the preimage on-chain before the recipient's claim transaction is confirmed, opening a front-running risk.
  • Best Practice: Use cryptographically secure random number generators (CSPRNG) and design the contract logic so the secret is only revealed to settle the swap, not to initiate it.
03

Ignoring Chain Reorganization Risks

Assuming block finality can lead to double-spends and swap reversals. This is critical for chains with probabilistic finality like Bitcoin, Ethereum (pre-PoS), and many L2s.

  • Pitfall: Considering a transaction final after 1-2 confirmations. A reorg can invalidate the locked funds.
  • Solution: Implement confirmation depth checks. Wait for a sufficient number of confirmations (e.g., 6 for Bitcoin, 12 for Ethereum) before proceeding to the next swap step. Monitor chain health for deep reorg events.
04

Overlooking Fee Estimation and Mempool Dynamics

Atomic swaps fail if one party cannot broadcast their claim or refund transaction due to insufficient gas/fees.

  • Error: Hardcoding gas prices or not dynamically adjusting for network congestion.
  • Error: Not ensuring the user's wallet has enough native token (ETH for gas, BTC for fees) to complete all transaction steps.
  • Mitigation: Integrate reliable fee estimation oracles and design UX to require fee coverage for the entire swap lifecycle before initiation.
06

Neglecting User Experience (UX) and Monitoring

A technically correct swap can still fail due to poor UX, leading to abandonment.

  • Mistake: Not providing clear status updates (e.g., "Waiting for 6 confirmations").
  • Mistake: No automatic monitoring for expired swaps to trigger refunds, requiring manual user intervention.
  • Mistake: Complex key management, forcing users to handle raw private keys for non-EVM chains. Implement background watcher services and clear, actionable notifications for each swap state.
CROSS-CHAIN ATOMIC SWAPS

Frequently Asked Questions (FAQ)

Common technical questions and troubleshooting for developers building or using cross-chain atomic swap infrastructure.

Atomic swaps rely on Hash Time-Locked Contracts (HTLCs). An HTLC is a smart contract or script that locks funds with two conditions:

  • Hash Lock: Funds can be claimed by anyone who provides the cryptographic preimage (the original data) for a specific hash.
  • Time Lock: If the hash lock isn't satisfied within a set timeframe, the funds are refunded to the original sender.

This creates the "atomic" property: either the entire swap completes successfully when the secret is revealed, or all funds are returned after the timeout. This mechanism is trust-minimized and does not require a central intermediary. It's the foundation for protocols like the Lightning Network and cross-chain DEXs.

conclusion
IMPLEMENTATION ROADMAP

Conclusion and Next Steps

This guide has outlined the core components for building a secure cross-chain atomic swap infrastructure. The next steps involve rigorous testing, deployment, and exploring advanced features.

You now have a functional blueprint for a trust-minimized atomic swap system. The core architecture relies on HTLCs (Hashed Timelock Contracts) on both chains, a watchtower service to monitor for counterparty fraud, and a relayer network to facilitate transaction submission. The security model is predicated on cryptographic proofs and economic disincentives, not trusted intermediaries. To proceed, you must finalize the smart contract logic for edge cases, such as handling chain reorganizations and gas price volatility, and deploy the contracts to your target testnets (e.g., Sepolia, Holesky, Arbitrum Sepolia).

Testing is the most critical phase. Begin with unit tests for your contract functions, then progress to integration tests that simulate the complete swap flow between two local blockchain nodes. Use tools like Hardhat or Foundry to create forked mainnet environments for realistic testing. You must rigorously test failure modes: a participant refunding after the timelock expires, the watchtower correctly submitting the penalty transaction, and the relayer handling transaction reverts. Security audits from reputable firms are non-optional for any production deployment.

For further development, consider enhancing the basic protocol. Implementing adaptor signatures can improve privacy by hiding the swap's recipient on the second chain until the first chain's secret is revealed. Integrating with cross-chain messaging protocols like Chainlink CCIP or LayerZero could allow for more complex conditional logic beyond simple hash locks. Furthermore, designing a liquidity provider model and a fee structure can transform your infrastructure from a peer-to-peer tool into a scalable service, similar to how THORChain facilitates cross-chain liquidity.

How to Design a Cross-Chain Atomic Swap Infrastructure | ChainScore Guides