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 Implement Atomic Swaps for Instant Cross-Border Settlements

This guide provides a technical implementation walkthrough for Hashed Timelock Contracts (HTLCs) to enable trustless, peer-to-peer currency exchange across borders. It covers the swap lifecycle, time lock parameter selection, liquidity provider roles, and integration with wallet software.
Chainscore © 2026
introduction
CROSS-CHAIN FINANCE

Introduction to Atomic Swaps for Settlements

Atomic swaps enable direct, trustless asset exchange between different blockchains, offering a foundational mechanism for instant cross-border settlements without intermediaries.

An atomic swap is a peer-to-peer cryptocurrency exchange executed via a smart contract that ensures the trade either completes entirely or fails without any funds being lost. This is achieved using Hash Time-Locked Contracts (HTLCs), which act as cryptographic escrow. The core principle is simple: two parties lock their respective assets into contracts on two separate blockchains (e.g., Bitcoin and Ethereum). The swap is "atomic" because the release of both assets is a single, indivisible event—it happens for both parties simultaneously or not at all. This eliminates counterparty risk and the need for a trusted third-party custodian, which is a significant advantage over traditional centralized exchanges for settlement.

The technical mechanism relies on two key components: a secret and its hash. Party A initiates the swap by locking funds in an HTLC on Chain A, specifying that the funds can be claimed by anyone who can reveal the preimage (the original data) that produces a specific cryptographic hash. Party B, seeing this contract, locks their funds in a corresponding HTLC on Chain B, using the same hash. Once Party A claims the funds on Chain B by revealing the secret, Party B can use that revealed secret to claim the funds on Chain A. If either party fails to act within a predefined time window, the contracts automatically refund the locked assets to their original owners, ensuring safety.

For developers, implementing a basic atomic swap involves writing HTLC logic on both involved chains. Below is a simplified example of an HTLC contract in Solidity for an Ethereum-based swap. The contract locks Ether until the correct secret is provided or a timeout expires.

solidity
contract HTLC {
    address public sender;
    address public recipient;
    bytes32 public hashLock;
    uint public timelock;
    bool public fundsClaimed = false;

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

    function claim(bytes32 _secret) external {
        require(msg.sender == recipient, "Not recipient");
        require(sha256(abi.encodePacked(_secret)) == hashLock, "Invalid secret");
        fundsClaimed = true;
        payable(recipient).transfer(address(this).balance);
    }

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

The counterparty would deploy a similar contract on another blockchain (like Bitcoin using its scripting language) with the same hashLock.

For cross-border settlements, atomic swaps offer distinct advantages: instant finality upon secret revelation, reduced costs by cutting out intermediary fees, and enhanced privacy as trades aren't recorded on a central order book. However, practical challenges remain. They require both blockchains to support compatible hash functions and timelock capabilities, which isn't universal. Liquidity can be fragmented compared to centralized venues, and the user experience is more complex, requiring direct coordination between parties. Projects like Komodo and AtomicDEX have built interfaces to abstract this complexity, offering non-custodial swap services.

The future of atomic swaps is evolving with new protocols. Inter-Blockchain Communication (IBC) on Cosmos enables fast finality swaps between IBC-enabled chains. Cross-chain messaging protocols like LayerZero and Wormhole can be used to orchestrate more complex conditional swaps across ecosystems. For enterprise settlements, combining atomic swaps with oracle-verified real-world data (like proof of payment) could trigger releases, creating a robust framework for trustless international trade. While not a panacea, atomic swaps provide a critical, decentralized primitive for building the infrastructure of peer-to-peer global finance.

prerequisites
PREREQUISITES AND SETUP

How to Implement Atomic Swaps for Instant Cross-Border Settlements

This guide details the technical prerequisites and initial setup required to build a secure, non-custodial atomic swap system for cross-border payments, focusing on the Bitcoin and Ethereum blockchains.

An atomic swap is a peer-to-peer, trustless exchange of cryptocurrencies across different blockchains. For cross-border settlements, this eliminates intermediaries, reduces counterparty risk, and enables near-instant finality. The core mechanism is a Hash Time-Locked Contract (HTLC), which uses a cryptographic hash and time constraints to ensure the swap either completes for both parties or refunds their assets. You will need a development environment with Node.js (v18+), npm or yarn, and a basic understanding of Bitcoin Script and Ethereum smart contracts.

You must set up access to blockchain networks. For testing, use the Bitcoin Testnet and an Ethereum Sepolia testnet RPC endpoint from providers like Alchemy or Infura. Fund your test wallets with tBTC and Sepolia ETH using faucets. Essential libraries include bitcoinjs-lib for constructing Bitcoin transactions and ethers.js v6 or web3.js for interacting with Ethereum. For a streamlined experience, consider the Cross-Chain Atomic Swap Toolkit by Comit Network, which provides pre-audited contract templates and utilities.

The swap logic is enforced by two synchronized HTLCs. On Ethereum, you deploy a smart contract. On Bitcoin, you create a P2SH (Pay-to-Script-Hash) address. Both lock funds with the same secret hash (the SHA-256 hash of a preimage) and a timelock. The initiating party (Alice) reveals the preimage to claim Bob's funds, which automatically reveals it to Bob, allowing him to claim Alice's funds. If the timelock expires, funds are refunded. This sequence guarantees atomicity: the swap is all-or-nothing.

Start by generating the secret and its hash. In Node.js: const crypto = require('crypto'); const secret = crypto.randomBytes(32); const hash = crypto.createHash('sha256').update(secret).digest('hex');. This hash is public and used in both contracts. The secret (preimage) is kept private by Alice until she claims Bob's funds. The timelock must be longer on the chain where the swap is initiated to prevent one party from claiming their side and then running out the clock on the other chain.

For the Ethereum contract, import and deploy an HTLC template. Key parameters are the recipient address, hashlock (the bytes32 hash), and timelock (a future block number). The contract holds the offered ERC-20 tokens or native ETH. On Bitcoin, you construct a redeem script using OP codes for hashlock and timelock checks, then derive the P2SH address. The funds are sent to this address. Both parties must verify the contract details—hashlock, amounts, and timelocks—match before locking any funds.

To execute, Bob locks his Bitcoin first. Alice verifies the lock, then locks her Ethereum funds. Alice then claims the Bitcoin by revealing the secret in the unlocking transaction. Bob watches the Bitcoin blockchain, extracts the revealed secret, and uses it to claim the Ethereum funds. Monitor transactions using block explorers and your node RPC. For production, implement robust error handling, monitor for mempool congestion affecting timelocks, and consider using Submarine Sends or Lightning Network for faster Bitcoin settlement layers.

key-concepts-text
CORE CONCEPTS

How to Implement Atomic Swaps for Instant Cross-Border Settlements

Atomic swaps use Hash Time-Locked Contracts (HTLCs) to enable trustless, peer-to-peer cryptocurrency exchanges across different blockchains without intermediaries.

An atomic swap is a peer-to-peer exchange of cryptocurrencies between two parties on potentially different blockchains. The swap is "atomic" because it either completes entirely or fails entirely, preventing one party from receiving an asset without sending theirs. This is achieved using a Hash Time-Locked Contract (HTLC), a type of smart contract that uses a cryptographic hash and a timelock to enforce the swap's conditions. The core components are a secret preimage (a random number), its hash digest (e.g., SHA-256), and a timelock that refunds the initiator if the swap isn't completed.

The swap lifecycle follows a specific sequence. First, Party A generates a secret preimage R and calculates its hash H = hash(R). Party A then locks funds into an HTLC on Chain 1, specifying that anyone who can reveal the preimage R that produces hash H can claim the funds before the timelock T1 expires. Party B, upon verifying this contract, locks their funds into a corresponding HTLC on Chain 2, using the same hash H but with a shorter timelock T2 (where T2 < T1). This time differential is critical for security.

To claim the funds, Party B must first discover the secret R. They do this by claiming Party A's funds on Chain 1, which requires broadcasting R on-chain, thereby revealing it. Party A can then use this publicly revealed R to claim Party B's funds on Chain 2 before timelock T2 expires. If Party B fails to act, Party A can refund their locked funds after T1. This interlocking mechanism ensures the swap is trustless; neither party can cheat without forfeiting their own funds or allowing the other to claim a refund.

Implementing an HTLC requires writing smart contract logic for locking, claiming, and refunding. Below is a simplified Solidity example for an HTLC on an EVM-compatible chain like Ethereum:

solidity
contract HTLC {
    address public sender;
    address public recipient;
    bytes32 public hashLock;
    uint public timelock;
    bool public fundsClaimed = false;
    bool public fundsRefunded = false;

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

    function claim(bytes32 _secret) external {
        require(msg.sender == recipient, "Not recipient");
        require(keccak256(abi.encodePacked(_secret)) == hashLock, "Invalid secret");
        require(block.timestamp < timelock, "Timelock expired");
        require(!fundsClaimed, "Already claimed");
        fundsClaimed = true;
        payable(recipient).transfer(address(this).balance);
    }

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

For cross-border settlements, atomic swaps eliminate intermediaries like banks or centralized exchanges, reducing fees and settlement times from days to minutes. Key considerations include chain compatibility (both chains must support programmable smart contracts like HTLCs), liquidity (finding a counterparty with matching assets and amounts), and network latency (ensuring transactions confirm before timelocks expire). Projects like Komodo and Lightning Network have pioneered atomic swap implementations, demonstrating their viability for Bitcoin, Litecoin, and Ethereum-based asset swaps.

While powerful, atomic swaps have limitations. They are not suitable for swapping between a smart contract chain and a non-smart contract chain (e.g., direct Bitcoin to Monero). The user experience can be complex, requiring manual coordination and on-chain transactions. Furthermore, the public revelation of the secret preimage on the first chain has privacy implications. For developers, thorough testing of timelock logic and edge cases is essential to prevent fund loss. Despite these challenges, HTLC-based atomic swaps remain a foundational primitive for decentralized cross-chain value transfer.

parameter-selection
CRITICAL PARAMETER SELECTION

How to Implement Atomic Swaps for Instant Cross-Border Settlements

Atomic swaps enable direct, trustless asset exchange across blockchains. This guide explains how to configure the two most critical parameters—timelocks and fees—to ensure secure and timely settlements for cross-border payments.

An atomic swap is a peer-to-peer smart contract protocol that allows two parties to exchange cryptocurrencies from different blockchains without a centralized intermediary. For cross-border settlements, this eliminates counterparty risk and reduces costs. The swap's atomicity is guaranteed by Hash Time-Locked Contracts (HTLCs), which use a cryptographic hash and two timelocks to create a conditional exchange. If one party fails to act within the specified time, the entire transaction is refunded, making the process fail-safe. This mechanism is ideal for settling international invoices or remittances directly between businesses or individuals.

The timelock is the most critical security parameter. It defines the window of time a party has to complete their side of the swap after the secret is revealed. For a cross-chain swap between Alice (on Bitcoin) and Bob (on Litecoin), you need two timelocks: one on each chain. The first layer timelock on the initiating chain (e.g., Bitcoin) must be significantly longer than the second layer timelock on the counter-party's chain. A common practice is to set the second-layer timelock (e.g., 24 hours) and then set the first-layer timelock to that value plus several block confirmations (e.g., 24h + 100 blocks). This prevents a scenario where one party can claim their asset on one chain and then deliberately let the other chain's contract expire.

Setting appropriate transaction fees is equally vital for timely settlement. You must ensure the fees attached to the HTLC transactions are high enough to be mined before the timelocks expire, especially during periods of network congestion. For Bitcoin and Ethereum, using fee estimation APIs (like estimatesmartfee or EIP-1559 feeHistory) is essential. In code, you dynamically calculate this. Furthermore, the refund transaction, which is claimable if the swap fails, must also have a sufficiently high fee to be viable days later. Underestimating fees can result in stuck transactions and locked capital, defeating the purpose of an "instant" settlement.

Here is a simplified Python example using the bitcoinlib and web3.py libraries to demonstrate parameter calculation for a BTC-ETH swap. This snippet outlines how to set the timelocks and calculate current network fees.

python
import time
from web3 import Web3
# Assume connections to BTC and ETH nodes are established

# Set base timelock (e.g., 24 hours in seconds)
base_timelock = 24 * 3600

# Calculate first layer (BTC) timelock: base + buffer for BTC block confirmations
btc_block_time = 600  # seconds
confirmation_buffer = 10  # blocks
btc_timelock = base_timelock + (btc_block_time * confirmation_buffer)

# Second layer (ETH) timelock is the base
eth_timelock = base_timelock

# Fetch current fee rates
btc_fee_per_byte = btc_node.estimatesmartfee(6)['feerate']  # feerate in BTC/kB
eth_gas_price = w3.eth.gas_price  # in wei

print(f"BTC Timelock: {btc_timelock} sec, Fee rate: {btc_fee_per_byte} BTC/kB")
print(f"ETH Timelock: {eth_timelock} sec, Gas price: {eth_gas_price} wei")

For production use, integrate with specialized libraries like Komodo's AtomicDEX API or Boltz Exchange for a more robust implementation. These platforms handle the complexity of constructing, broadcasting, and monitoring the HTLCs across chains. When planning a settlement, always conduct a test swap on testnets (like Bitcoin Testnet and Sepolia) to verify your parameter logic. Monitor real-time network statistics from sources like mempool.space for Bitcoin or etherscan.io/gastracker for Ethereum to adjust fees immediately before initiating the mainnet swap. The goal is to balance security (long enough timelocks) with practicality (swift settlement and competitive fees).

The primary risks in parameter selection are timelock asymmetry and fee underestimation. Asymmetric timelocks can enable a griefing attack where a malicious party locks funds without intending to swap. Always use a reputable, open-source atomic swap protocol that has undergone audits. Furthermore, while atomic swaps provide censorship-resistant settlement, they currently lack native fiat on/off ramps and may face liquidity constraints for large amounts. For recurring business settlements, building a relationship with a liquidity provider or using a non-custodial DEX aggregator that supports cross-chain swaps can streamline the process.

SECURITY PARAMETERS

Recommended Timelock Durations by Network

Suggested HTLC timelock windows for atomic swaps based on average block times and finality.

NetworkAvg. Block TimeRecommended HTLC TimelockSecurity Notes

Bitcoin

~10 minutes

24-48 hours

High security, slow finality

Ethereum

~12 seconds

2-6 hours

Post-merge PoS finality

Polygon PoS

~2 seconds

1-3 hours

Checkpoint finality to Ethereum

Arbitrum One

< 1 second

30-90 minutes

Optimistic rollup challenge period

Solana

~400ms

15-60 minutes

Fast probabilistic finality

Avalanche C-Chain

~2 seconds

1-2 hours

Subnet finality in <3 sec

Cosmos Hub

~6 seconds

2-4 hours

Tendermint BFT finality

liquidity-provider-role
IMPLEMENTING ATOMIC SWAPS

The Liquidity Provider's Role and Infrastructure

Atomic swaps enable trustless, peer-to-peer cross-chain asset exchange. This guide covers the core infrastructure and technical steps for developers to implement them.

05

Liquidity Provision and Market Making

As a liquidity provider, you can run automated systems to facilitate swaps. This involves:

  • Pricing Engine: Setting exchange rates based on oracle feeds or DEX prices.
  • Watchtower Service: Monitoring multiple blockchains for HTLC setup and claim transactions.
  • Risk Management: Managing capital allocation and exposure across different chains and assets.

Running a profitable node requires balancing capital efficiency (minimizing locked, idle funds) with uptime to capture fees. Automated market maker (AMM) models are now being adapted for cross-chain atomic swaps.

06

Security Considerations and Auditing

Atomic swap implementations carry specific risks:

  • Timing Attacks: If block times differ significantly, one party may have a refund advantage.
  • Malleability: On Bitcoin, transaction malleability could invalidate a swap (mitigated by SegWit).
  • Fee Market Volatility: High network congestion can prevent timely claim or refund transactions.
  • Oracle Reliability: Pricing engines dependent on external data are attack vectors.

Best Practice: Conduct formal verification or professional audits of your HTLC contracts. Use established libraries and avoid custom cryptographic implementations.

wallet-integration
TUTORIAL

Integrating Swaps into Wallet Software

This guide explains how to implement atomic swaps for instant, trustless cross-border settlements directly within a cryptocurrency wallet.

Atomic swaps enable the direct exchange of cryptocurrencies between two parties on different blockchains without a centralized intermediary. The process is secured by Hash Time-Locked Contracts (HTLCs), which use cryptographic hashes and time constraints to ensure the swap either completes successfully for both parties or funds are returned. This makes atomic swaps ideal for cross-border settlements, as they eliminate counterparty risk, reduce fees, and can settle in minutes rather than days. For wallet integration, this means building a system that can generate, verify, and execute these contracts.

To implement a swap, your wallet software must handle two primary phases: the setup and the execution. First, the initiating party (Alice) creates a secret and generates its cryptographic hash. She then deploys an HTLC on her blockchain (e.g., Bitcoin), locking her funds with a condition: the recipient must reveal the secret to claim them. The hash of this secret is shared. The counterparty (Bob) uses this hash to create a corresponding HTLC on his chain (e.g., Litecoin). Once both contracts are locked, the secret is revealed to claim Bob's funds, which then allows Alice to claim hers using the same secret.

From a developer's perspective, integration involves several key components. Your wallet needs a cross-chain communication layer to share contract details and proofs. You must also integrate with the specific scripting languages of each blockchain, such as Bitcoin Script for BTC-based swaps or Solidity for Ethereum-based swaps using wrapped assets. Libraries like Komodo's AtomicDEX API or the Boltz Exchange SDK can abstract much of this complexity. Critical logic includes monitoring for HTLC deployments on both chains, managing secret generation and revelation, and handling refund transactions if a swap expires.

Security considerations are paramount. Your implementation must securely generate and store the pre-image secret; exposure before the swap compromises the entire process. The wallet must also rigorously validate all conditions of the counterparty's HTLC before locking funds. Transaction fee estimation is crucial, as insufficient fees can cause transactions to stall, potentially leading to expired contracts and forced refunds. Always use well-audited, open-source libraries for cryptographic operations and contract templates to minimize risk.

For a practical example, here is a simplified flow using pseudo-code for a Bitcoin-to-Litecoin swap initiated from your wallet:

python
# 1. Generate secret and hash
secret = generate_random_secret()
hash_lock = sha256(secret)

# 2. Create & broadcast Bitcoin HTLC
btc_htlc_tx = create_htlc(receiver_address, hash_lock, expiry_blocks)
broadcast_transaction(btc_htlc_tx, bitcoin_network)

# 3. Share hash_lock with counterparty
counterparty.build_ltc_htlc(hash_lock)

# 4. Monitor for LTC HTLC, then reveal secret to claim LTC
if ltc_htlc_confirmed:
    claim_ltc(secret)
    # 5. Counterparty uses revealed secret to claim BTC

This highlights the interactive, event-driven nature of the protocol that your wallet's backend must orchestrate.

Looking forward, integrating with cross-chain messaging protocols like IBC (Inter-Blockchain Communication) or LayerZero can facilitate swaps across a wider array of networks. The ultimate goal for wallet software is to provide a seamless user experience where a cross-border payment is as simple as selecting an asset and a destination, with the atomic swap executed automatically in the background. By implementing this technology, wallets move beyond simple storage to become active gateways for decentralized, global value transfer.

DEVELOPER TROUBLESHOOTING

Atomic Swap Implementation FAQ

Common technical questions and solutions for developers implementing atomic swaps for cross-border settlements, covering protocols, security, and integration challenges.

The fundamental primitive is the Hash Time-Locked Contract (HTLC). An HTLC uses two conditions to lock funds:

  • Hash Lock: Funds are locked with a cryptographic hash (e.g., sha256(preimage)). To claim them, the counterparty must reveal the original preimage.
  • Time Lock: A refund path is secured by a CLTV (CheckLockTimeVerify) or CSV (CheckSequenceVerify) clause. If the swap isn't completed within a set block height or time, the original sender can reclaim their funds.

This creates the "atomic" property: either both parties successfully exchange assets using the revealed preimage, or both transactions time out and funds are returned. This mechanism is protocol-agnostic and forms the basis for swaps between Bitcoin Script, Ethereum smart contracts, and other chains.

conclusion
IMPLEMENTATION SUMMARY

Conclusion and Next Steps

Atomic swaps provide a trustless, peer-to-peer mechanism for cross-border settlements, eliminating intermediaries and counterparty risk. This guide has covered the core concepts and a practical implementation path.

Successfully implementing atomic swaps for instant settlements requires a robust technical foundation. You must ensure your system handles hash time-locked contracts (HTLCs) correctly, manages on-chain transaction fees, and provides a reliable user interface for secret exchange. The primary challenges are coordinating the time locks across different blockchains and ensuring participants are online to complete the swap within the specified windows. Testing on testnets like Sepolia, Goerli, or Polygon Mumbai is non-negotiable before any mainnet deployment.

For further development, consider integrating with cross-chain messaging protocols like LayerZero or Axelar to facilitate the initial swap negotiation and status updates off-chain. This can improve the user experience by making the process feel instantaneous. Additionally, explore liquidity pool models where users can swap with a pool's reserves instead of waiting for a direct counterparty, though this introduces different trust assumptions. Always audit your smart contract code; platforms like Certik and OpenZeppelin provide tools and services for this critical step.

The next practical step is to build upon the basic HTLC example. Implement a frontend dApp that guides users through generating secrets, creating contracts, and revealing the preimage. Use libraries like ethers.js or viem for Ethereum-compatible chains and their equivalents for others like bitcoinjs-lib. For production, you'll need to run or connect to reliable blockchain nodes and potentially implement a watchtower service to monitor for expired contracts and automate refunds, protecting users who go offline.

Atomic swaps are a powerful primitive for decentralized finance (DeFi) and cross-border commerce. They enable direct currency exchange between parties in different jurisdictions without FX intermediaries. As blockchain interoperability improves with technologies like inter-blockchain communication (IBC) and more standardized token bridges, the utility and speed of atomic swaps will only increase. Start with simple asset pairs and gradually expand your protocol's supported networks and currencies based on user demand and liquidity availability.

How to Implement Atomic Swaps for Cross-Border Settlements | ChainScore Guides