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 System for Atomic Cross-Border Swaps

Build a system that guarantees atomicity for cross-border asset swaps across different blockchains. This guide covers protocol design, smart contract implementation, and security considerations.
Chainscore © 2026
introduction
ARCHITECTURE GUIDE

How to Design a System for Atomic Cross-Border Swaps

This guide explains the core architectural principles and smart contract logic required to build a secure, non-custodial system for swapping assets across different blockchain networks without counterparty risk.

An atomic cross-border swap enables two parties to exchange assets on different blockchains, such as swapping ETH on Ethereum for SOL on Solana, in a single, trust-minimized transaction. The core guarantee is atomicity: the swap either completes successfully for both parties, or the entire transaction is reverted, leaving no participant with a partial outcome. This eliminates the significant counterparty risk inherent in manual, time-delayed OTC trades. The system's design relies on cryptographic hash-locks and time-locks to coordinate the conditional transfer of assets across independent ledgers.

The most common implementation pattern is the Hash Time-Locked Contract (HTLC). The protocol flow begins when Party A, the initiator, generates a secret random number and computes its cryptographic hash. Party A deploys a smart contract on Chain A, locking their funds with two conditions: the funds can be claimed by anyone who reveals the secret pre-image of the hash, or refunded back to Party A after a specified time-lock expires. Party A then sends the hash (but not the secret) to Party B. Upon receiving the hash, Party B can verify the locked contract on Chain A and then deploy a corresponding HTLC on Chain B, locking their counterpart asset with the same hash and a shorter time-lock.

To execute the swap, Party A must first reveal the secret to claim the funds locked in Party B's contract on Chain B. This action publicly exposes the secret on Chain B's ledger. Party B (or any observer) can then take this revealed secret and use it to claim the original funds locked in the contract on Chain A. The carefully sequenced time-locks are critical: the lock on Chain B must expire before the lock on Chain A. This ensures that if Party B fails to claim the funds on Chain A after learning the secret, Party A can still safely refund their own assets once their longer-duration time-lock elapses.

Designing the smart contracts requires careful attention to security parameters. The time-lock durations must account for the maximum network latency and block time variability between the two chains. A lock duration that is too short risks stranding funds if a chain is congested, while one that is too long increases capital inefficiency. The secret generation must use a cryptographically secure random function, and the hash function (typically SHA-256) must be preimage-resistant. Contracts must also include clear functions for claim(bytes32 secret) and refund(), with access controls ensuring only the rightful parties can trigger them.

Beyond basic HTLCs, modern designs integrate with bridges and liquidity networks to improve user experience. Instead of requiring a direct counterparty, a user can swap with a liquidity pool managed by a bridge protocol like Chainlink CCIP or Across. In this model, the user's HTLC interacts with a bridge router contract, which uses locked liquidity on the destination chain to fulfill the swap instantly. The bridge then assumes the role of the counterparty and handles the cross-chain settlement. This abstracts away the need for peer discovery and negotiation, creating a seamless cross-chain DEX experience.

When implementing your system, audit all edge cases: failed transactions, expired locks, and blockchain reorganizations. Use established libraries like OpenZeppelin for secure contract patterns and consider gas optimization for claim and refund functions. Testing must be done on testnets for all involved chains (e.g., Sepolia, Solana Devnet) using tools like Hardhat or Foundry. A well-designed atomic swap system provides a fundamental, trustless primitive for cross-chain interoperability, forming the backbone for more complex DeFi applications.

prerequisites
SYSTEM DESIGN

Prerequisites and System Requirements

Before building an atomic cross-border swap system, you must establish a robust technical foundation. This guide outlines the essential components, tools, and infrastructure required to design a secure and efficient protocol.

An atomic cross-border swap system requires a trust-minimized architecture that guarantees the atomicity of asset transfers across distinct blockchain networks. The core prerequisite is a deep understanding of Hash Time-Locked Contracts (HTLCs). HTLCs are the fundamental cryptographic primitive that enables conditional payments. They use a hash lock, requiring the presentation of a secret preimage to claim funds, and a time lock, which refunds the sender if the swap isn't completed within a deadline. You must be proficient in writing and deploying HTLCs on your target chains, typically using Solidity for EVM networks or Rust for Solana and Cosmos SDK chains.

Your system's design must account for chain-specific requirements. For Ethereum and other EVM chains, you'll need a development environment like Hardhat or Foundry, and familiarity with ERC-20 token standards. For non-EVM chains like Solana, Cosmos, or Bitcoin (using scripts), you must understand their unique smart contract or scripting paradigms. A critical requirement is access to reliable RPC endpoints for each supported network to monitor blockchain state and submit transactions. Services like Alchemy, Infura, or chain-specific providers are essential for mainnet deployment.

The operational backbone is an off-chain relayer or watchtower service. This is a server-side component that monitors the blockchain for HTLC events, broadcasts transactions, and shares cryptographic secrets between parties. You can build this in any language (Node.js, Go, Python), but it must securely manage private keys for fee payment and integrate with multiple blockchain clients. The relayer's design must prioritize liveness; if it goes offline during a swap, funds could be locked indefinitely. Implementing automatic retry logic and failover mechanisms is a key system requirement.

Security and testing are non-negotiable prerequisites. You must conduct extensive integration testing across forked mainnet environments to simulate real-world conditions. Use tools like Ganache for EVM chains or local validators for others. A comprehensive test suite should cover all failure modes: - Secret revelation before deadline - Refund after timeout - Partial fulfillment attempts - Network congestion scenarios. Formal verification of HTLC logic, using tools like Certora or Scribble, is highly recommended for production systems to eliminate costly bugs.

Finally, consider the user experience and fee model. Your system must calculate and communicate network gas costs accurately for both sides of the swap, which can be highly volatile. You'll need to integrate oracles or gas estimation APIs. For cross-border fiat integrations, compliance with local regulations (like Travel Rule) may require implementing identity verification layers. The architecture should be modular, allowing you to plug in different liquidity sources, such as direct peer-to-peer pools or decentralized exchanges, to source the destination asset.

core-mechanism-text
TUTORIAL

Core Mechanism: Hash Time-Locked Contracts (HTLCs)

A technical guide to implementing atomic cross-chain swaps using the foundational HTLC pattern, with practical Solidity examples.

A Hash Time-Locked Contract (HTLC) is a conditional smart contract that enables trust-minimized atomic swaps between two parties across potentially untrusted chains. It uses two cryptographic primitives: a hashlock and a timelock. The hashlock requires the presentation of a secret preimage to unlock funds, while the timelock ensures funds can be refunded to the original owner if the swap is not completed within a specified period. This mechanism ensures the swap is atomic—it either completes entirely for both parties or fails entirely, preventing one party from stealing funds.

Designing a system for a cross-border (cross-chain) swap begins with the setup phase. Party A, wanting to swap Token X on Chain A for Token Y on Chain B, deploys an HTLC on Chain A. They lock their tokens with two conditions: the contract can be claimed by anyone who provides the correct preimage R that hashes to a publicly known hash H = hash(R), or refunded back to Party A after a timelock T1 expires. The hash H is the crucial link between the two chains. Party B must verify this contract deployment before proceeding.

On the destination chain, Party B must now deploy a corresponding HTLC. They lock their Token Y in a contract on Chain B with the same hashlock H. The claim condition is identical: provide preimage R. However, the refund timelock T2 on this second contract must be significantly shorter than T1 on the first chain (e.g., 24 hours vs. 48 hours). This asymmetry is critical. It ensures Party B has a sufficient time window to claim the funds on Chain A after learning R, while Party A has a subsequent safety window to refund their own funds if Party B never claims.

The atomic execution is triggered when Party B, upon seeing Party A's locked funds, reveals the secret preimage R to claim Token X from the HTLC on Chain A. This action publicly exposes R on Chain A's blockchain. Party A (or any observer) can then take this now-public R and use it to claim Token Y from the HTLC on Chain B before the shorter timelock T2 expires. The swap completes without either party having to trust the other, relying only on the deterministic execution of the two smart contracts. If Party B never claims the first contract, both parties can refund their funds after their respective timelocks pass.

Here is a simplified Solidity skeleton for an HTLC. Note that in production, you must add access controls, better randomness for the secret, and rigorous testing.

solidity
contract SimpleHTLC {
    address public sender;
    address public recipient;
    bytes32 public hashlock;
    uint public timelock;
    bool public fundsClaimed;
    bool public fundsRefunded;

    constructor(address _recipient, bytes32 _hashlock, uint _timelock) payable {
        sender = msg.sender;
        recipient = _recipient;
        hashlock = _hashlock;
        timelock = block.timestamp + _timelock;
    }

    function claim(bytes32 _preimage) external {
        require(!fundsClaimed && !fundsRefunded, "Funds already claimed/refunded");
        require(sha256(abi.encodePacked(_preimage)) == hashlock, "Incorrect preimage");
        fundsClaimed = true;
        payable(recipient).transfer(address(this).balance);
    }

    function refund() external {
        require(msg.sender == sender, "Only sender can refund");
        require(!fundsClaimed && !fundsRefunded, "Funds already claimed/refunded");
        require(block.timestamp >= timelock, "Timelock not expired");
        fundsRefunded = true;
        payable(sender).transfer(address(this).balance);
    }
}

While foundational, basic HTLCs have limitations for modern DeFi. They require both chains to support compatible smart contracts and the same hash function (typically SHA-256). They also introduce capital inefficiency as funds are locked for the duration of the timelocks. Furthermore, they are susceptible to griefing attacks where a malicious party can lock funds without intending to complete the swap, forcing the counterparty's capital to be stuck. Modern cross-chain protocols like Chainlink CCIP or LayerZero often use more advanced designs with relayers and optimistic verification to overcome these hurdles, but the HTLC remains the essential conceptual model for atomicity.

system-components
ARCHITECTURE

Key System Components

Building a secure atomic swap system requires specific cryptographic and smart contract components. This guide covers the core building blocks.

protocol-flow
SYSTEM DESIGN

Step-by-Step Swap Protocol Flow

This guide details the architectural components and message flow required to build a secure, atomic cross-chain swap system, using a Hashed Timelock Contract (HTLC) as the core primitive.

An atomic cross-chain swap allows two parties to exchange assets on different blockchains without a trusted intermediary. The core mechanism ensuring security is the Hashed Timelock Contract (HTLC), a conditional payment smart contract. The swap's atomicity is guaranteed: either the entire exchange completes successfully, or all funds are refunded to their original owners. This is achieved through two cryptographic primitives: a secret preimage (R) and its cryptographic hash (H = hash(R)). The party initiating the swap (Alice) creates the secret and shares only its hash, H, which becomes the lock condition for both chains.

The protocol begins with initiation and lock creation. Alice, wanting to swap her ETH on Ethereum for Bob's BTC on Bitcoin, deploys an HTLC on the Ethereum network. This contract locks her ETH, specifying that it can be claimed by anyone who can provide the secret preimage, R, that hashes to the public hash H. The contract also includes a timelock (e.g., 24 hours), after which Alice can refund her ETH if the swap isn't completed. Alice then communicates the hash H and the Ethereum contract address to Bob via an off-chain channel.

Upon receiving the hash H, Bob verifies the locked funds on Ethereum. Convinced, he creates a corresponding HTLC on the Bitcoin network, locking his BTC with the same hash H and a shorter timelock (e.g., 12 hours). This shorter deadline is critical; it ensures Bob has enough time to claim the ETH after he learns the secret but before Alice can refund her funds. Bob informs Alice of the Bitcoin contract address. This establishes the two interdependent, hash-locked contracts that form the swap's backbone.

The execution phase is triggered by Alice claiming the BTC. To do this, she must first submit the secret R to the Bitcoin HTLC, which validates that hash(R) equals H. This transaction, which is public on the Bitcoin blockchain, reveals the secret R to the network. By claiming the BTC, Alice inadvertently publishes R, allowing anyone (including Bob) to see it. Bob now monitors the Bitcoin blockchain, extracts the revealed secret R from Alice's claim transaction, and uses it to unlock and claim the ETH from the Ethereum HTLC before Alice's longer timelock expires.

The system's security hinges on the timelock asymmetry and the public revelation of the secret. If Bob never creates the Bitcoin HTLC, Alice simply refunds her ETH after her timelock expires. If Alice never claims the BTC, Bob refunds his BTC after his shorter timelock. The only successful path requires both parties to act: Alice must reveal R to get BTC, which then enables Bob to get ETH. This design eliminates counterparty risk without requiring trust. For a practical implementation, review the OpenZeppelin library's HashTimelock contract or the Interledger Protocol's conditional payment specs.

When designing such a system, key considerations include chain-specific constraints (Bitcoin script vs. Ethereum EVM), accurate timelock calculations accounting for block time variance, and robust oracle or relay services for each party to verify the state of the foreign chain. Modern cross-chain messaging protocols like Axelar's General Message Passing or LayerZero can abstract away much of this verification complexity, but the fundamental atomic swap pattern using hash-and-timelock conditions remains a foundational concept for trust-minimized interoperability.

CROSS-CHAIN SWAP ARCHITECTURE

Smart Contract Implementation Examples

Cross-Chain Messaging Integration

Modern atomic swap systems often integrate with cross-chain messaging protocols like Axelar, LayerZero, or Wormhole to coordinate swaps across heterogeneous chains.

Contract Architecture:

  • Swap Initiator Contract: Deployed on the source chain (e.g., Ethereum). Locks user's USDC and sends a message via the bridge.
  • Message Bridge Adapter: Handles the cross-chain call, often using a Generic Message Passing (GMP) pattern.
  • Swap Fulfiller Contract: Deployed on the destination chain (e.g., Avalanche). Upon verifying the bridge message, it releases the equivalent amount of bridged USDC.e to the user.

Key Code Snippet (Initiator):

solidity
// Example using Axelar GMP
function initiateSwap(
    string calldata destinationChain,
    string calldata destinationAddress,
    uint256 amount,
    bytes32 secretHash
) external payable {
    IERC20(usdc).transferFrom(msg.sender, address(this), amount);
    
    bytes memory payload = abi.encode(
        msg.sender,
        amount,
        secretHash
    );
    
    // Pay gas for execution on destination chain
    iaxelarGasService.payNativeGasForContractCall{value: msg.value}(
        address(this),
        destinationChain,
        destinationAddress,
        payload,
        msg.sender
    );
    
    // Send the cross-chain message
    iaxelarGateway.callContract(destinationChain, destinationAddress, payload);
}

The atomicity is enforced by the bridge's guaranteed message delivery or revert semantics.

relayer-watchtower
IMPLEMENTING RELAY AND WATCHTOWER SERVICES

How to Design a System for Atomic Cross-Border Swaps

This guide explains the architectural design for a secure, trust-minimized system that facilitates atomic cross-chain swaps using relayers and watchtowers to ensure transaction finality and protect user funds.

An atomic cross-chain swap is a protocol that allows two parties to exchange assets on different blockchains without a trusted intermediary. The core mechanism is the Hash Time-Locked Contract (HTLC), which uses a cryptographic secret to lock funds. The swap succeeds only if both parties reveal the secret within a predefined time window, making the exchange atomic: it either completes for both parties or fails for both. This prevents one party from taking the asset without fulfilling their side of the deal. Designing a robust system around this primitive requires components to broadcast transactions and monitor for failures.

The Relayer Service is a critical off-chain component responsible for broadcasting signed transactions to their respective blockchains. In a typical flow, User A signs a transaction locking funds in an HTLC on Chain A and sends it to the relayer. The relayer submits this transaction, pays the gas fee, and broadcasts the resulting contract address to User B. Once User B locks their funds on Chain B, the relayer facilitates the secret revelation by submitting the final claim transactions. To be non-custodial, relayers should never hold user private keys; they only broadcast user-signed payloads. Services like Gelato Network or OpenZeppelin Defender can be used to build or augment this functionality.

The Watchtower Service acts as a security monitor to protect users if a counterparty disappears or a relayer fails. Its primary job is to watch for specific on-chain states and trigger fallback actions. For an HTLC, the watchtower constantly scans for two critical events: a successful secret revelation on one chain, or the approach of the HTLC's expiry time. If a secret is revealed on Chain B, the watchtower must immediately submit a transaction with that secret to claim User A's funds on Chain A before the timer expires. Conversely, if the timer is close to expiring and no one has claimed, the watchtower should submit the refund transaction to return funds to the original owner.

System design must account for liveness assumptions and fee management. Relay services require a sustainable economic model, often involving a small fee taken from the swapped amount or a separate fee payment in a native token. Watchtowers, which provide a safety net, may operate on a subscription or staking model. Both services must be highly available and deployed across multiple nodes to avoid single points of failure. Using decentralized oracle networks or validator sets for watchtower logic can increase censorship resistance. The architecture should also include a state synchronizer to keep all components aware of the current swap status across chains.

Implementing these services involves listening to blockchain events. For Ethereum Virtual Machine (EVM) chains, you would use libraries like ethers.js or viem to listen for HTLCCreated, HTLCClaimed, and HTLCRefunded events. The watchtower logic can be implemented as a Node.js or Python service using these libraries, with a database like PostgreSQL to track active swaps and their timers. For production reliability, consider using a transaction manager like Web3.js's NonceManager or a dedicated service to handle transaction queuing, gas price estimation, and resubmission on failure.

IMPLEMENTATION APPROACHES

Atomic Swap Protocol Comparison

Comparison of core technical approaches for implementing trustless cross-chain asset swaps.

Protocol FeatureHash Time-Locked Contracts (HTLCs)Adaptor SignaturesDiscreet Log Contracts (DLCs)

Underlying Primitive

Hashlock + Timelock

Schnorr/Taproot Signature

Schnorr Signatures + Oracles

Blockchain Support

Any with smart contracts or script

Primarily Bitcoin (Taproot)

Bitcoin (with external data)

On-Chain Footprint

Multiple transactions (setup, claim, refund)

Single cooperative settlement transaction

Single settlement transaction

Privacy Level

Low (hash preimage reveals on-chain)

High (cooperative settlement is indistinguishable)

Medium (oracle attestation is public)

Time Sensitivity

High (strict refund timelocks required)

None (no built-in expiration)

Configurable (bound to oracle event)

Typical Use Case

Simple peer-to-peer asset swap

Payment channels, CoinSwap

Complex derivatives, cross-chain swaps

Trust Assumption

Cryptographic only (counterparty liveness)

Cryptographic only

Cryptographic + Oracle honesty

Transaction Fee Cost

High (multiple on-chain actions)

Low (single on-chain settlement)

Medium (setup + settlement)

security-considerations
ATOMIC SWAP DESIGN

Critical Security Considerations and Risks

Designing a system for atomic cross-border swaps requires rigorous security architecture. These cards detail the core risks and mitigation strategies for developers.

01

Preventing Front-Running and MEV

Atomic swaps are vulnerable to Maximal Extractable Value (MEV) bots that can front-run transactions. Mitigation strategies include:

  • Using commit-reveal schemes to hide transaction details until execution.
  • Implementing fair ordering protocols or leveraging private mempools like Flashbots.
  • Designing swap logic that minimizes predictable profit opportunities for searchers. Failure to address this can lead to significant user loss, as seen in early DEX arbitrage.
02

Handling Blockchain Reorganizations

A chain reorg can invalidate a transaction considered final, breaking atomicity. Your design must account for this by:

  • Setting appropriate confirmation block depths for each chain (e.g., 6+ for Bitcoin, 15+ for Ethereum).
  • Implementing a watchtower or monitoring service to detect reorgs and trigger fallback logic.
  • Using time-locked refunds (HTLCs) that are long enough to survive a deep reorg event. Ignoring reorg risk is a common cause of fund loss in cross-chain systems.
03

Secure Hash Time-Locked Contract (HTLC) Design

The HTLC is the standard primitive. Critical implementation details include:

  • Generating cryptographically secure preimages using keccak256 or sha256.
  • Calculating precise timelock durations based on block times and network congestion.
  • Ensuring the contract correctly validates the preimage and refunds expired locks. A single bug, like the one exploited in the 2020 THORChain hack, can drain all locked funds.
04

Oracle and Pricing Risks

Swaps involving stablecoins or priced assets require an oracle for exchange rates. This introduces centralization and manipulation risk.

  • Use decentralized oracles like Chainlink with multiple data feeds.
  • Implement circuit breakers and maximum price slippage limits.
  • Consider designs that use the native assets of each chain (e.g., BTC for ETH) to avoid oracle dependency entirely, as in pure atomic swaps.
05

Liquidity Provider and Counterparty Risk

In systems with liquidity pools (not peer-to-peer), users trust the pool's solvency. Key risks are:

  • Impermanent Loss for LPs, which affects long-term liquidity.
  • Smart Contract Risk of the pool itself (e.g., bugs in the bonding curve).
  • Bridge Risk if the system uses wrapped assets (e.g., WBTC). Mitigate by auditing pool contracts and preferring native asset swaps where possible.
06

Network Congestion and Gas Management

A swap can fail if one leg runs out of gas or times out due to congestion, potentially leaving funds locked.

  • Implement dynamic gas estimation using recent block data.
  • Design gas sponsorship mechanisms so one party can pay for the other's transaction if needed.
  • Set conservative timelocks that account for potential network downtime, like Ethereum's 2020 Infura outage.
ATOMIC SWAPS

Frequently Asked Questions

Common technical questions and solutions for developers building systems for atomic cross-border swaps.

Atomicity is enforced through Hash Time-Locked Contracts (HTLCs). This cryptographic protocol ensures a swap either completes entirely for both parties or fails completely, with funds returned. The mechanism works in two phases:

  1. Locking Phase: Party A locks funds in a smart contract or script, secured by a cryptographic hash of a secret preimage. They send the resulting hash to Party B.
  2. Claiming Phase: Party B uses the hash to lock their funds in a reciprocal contract on their chain. To claim Party A's funds, Party B must reveal the secret preimage. This revelation automatically allows Party A to claim Party B's funds.

If the secret is not revealed before a predefined timeout, all locked funds are refunded to their original owners. This eliminates counterparty risk, as no participant can receive assets without the other also receiving theirs.

conclusion
SYSTEM DESIGN SUMMARY

Conclusion and Next Steps

This guide has outlined the core components and security considerations for building a system that facilitates atomic cross-border swaps. The next step is to implement and test these concepts.

Designing a system for atomic cross-border swaps requires integrating several critical components: a secure custody layer for holding assets, a cross-chain messaging protocol like Axelar or Wormhole for communication, and a verification and execution engine powered by smart contracts. The atomicity guarantee, ensuring both sides of the trade succeed or fail together, is typically enforced using a commit-reveal scheme or Hash Time-Locked Contracts (HTLCs). This architecture must be resilient to chain reorganizations, message delivery failures, and oracle manipulation.

For developers ready to build, the next steps are practical. First, select and integrate a production-ready cross-chain messaging protocol. For Ethereum-to-Avalanche swaps, you might use the Axelar Gateway contracts. Second, implement the atomic swap logic in Solidity for EVM chains or Rust for Solana, using libraries like OpenZeppelin for secure patterns. A basic HTLC in Solidity would involve functions for lock(bytes32 hash, uint256 expiration), claim(bytes32 secret), and refund(). Thorough unit and fork testing with tools like Foundry or Hardhat is non-negotiable.

Finally, consider the operational and long-term evolution of your system. You will need a robust monitoring dashboard to track swap statuses, liquidity balances across chains, and message bridge health. Plan for protocol upgrades using proxy patterns or governance modules. As the cross-chain ecosystem evolves, stay informed about new standards like the Inter-Blockchain Communication (IBC) protocol for Cosmos-based chains or Chainlink's CCIP. The ultimate goal is a system that is not only functionally correct but also maintainable, upgradeable, and transparent to its users.

How to Design a System for Atomic Cross-Border Swaps | ChainScore Guides