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 Cross-Rollup Atomic Swaps

This guide provides a step-by-step implementation for developers to build atomic swaps between different Layer 2 rollups, ensuring transactions complete fully or not at all.
Chainscore © 2026
introduction
TUTORIAL

Introduction to Cross-Rollup Atomic Swaps

A technical guide to implementing trustless asset exchanges between different rollups using atomic swap protocols.

Cross-rollup atomic swaps enable users to exchange assets between two distinct rollup chains—like Arbitrum and Optimism—without relying on a centralized intermediary or bridge. This is achieved through a cryptographic protocol where both parties commit to a trade, and the assets are either swapped simultaneously or returned to their original owners. The core mechanism relies on Hash Time-Locked Contracts (HTLCs), which use a cryptographic hash and a timelock to enforce the atomicity of the swap, meaning the entire transaction either completes successfully for both sides or fails entirely.

To implement a basic cross-rollup atomic swap, you need smart contracts deployed on both the source and destination rollups. The process begins when the initiator, Alice, creates a secret and computes its hash. She then deploys a locking contract on Rollup A, funding it with her tokens and specifying the hash and a refund timelock (e.g., 24 hours). Bob, upon verifying this contract, deploys a corresponding locking contract on Rollup B with the same hash and a shorter timelock. Once Bob's contract is live and funded, Alice can reveal her secret on Rollup A to claim Bob's tokens, which also exposes the secret to Bob, allowing him to claim Alice's tokens on Rollup B.

The security of this system hinges on the timelocks and the cryptographic hash. The recipient's timelock must be significantly shorter than the initiator's refund timelock. This ensures that if Bob fails to claim the funds on Rollup A after Alice reveals the secret, Alice can still refund her locked tokens on Rollup B after her longer timelock expires. Critical considerations for developers include ensuring both rollups have compatible precompiles for the hash function (like keccak256), accurately estimating network latency for transaction finality, and accounting for potential fee market fluctuations on both L2s.

prerequisites
IMPLEMENTATION GUIDE

Prerequisites and Setup

This guide details the technical prerequisites and initial setup required to implement a secure cross-rollup atomic swap between Ethereum L2s.

To implement cross-rollup atomic swaps, you need a foundational understanding of the involved technologies. You should be proficient with Ethereum smart contract development using Solidity and familiar with the Ethereum Virtual Machine (EVM). A working knowledge of Layer 2 (L2) scaling solutions—specifically Optimistic Rollups like Optimism and Arbitrum, and ZK-Rollups like zkSync Era—is essential, as their unique architectures (e.g., fraud proofs, validity proofs, and finality times) directly impact swap logic. You'll also need Node.js and npm/Yarn installed to manage dependencies and run a local development environment.

The core setup involves initializing a Hardhat or Foundry project. For this guide, we'll use Hardhat. First, create a new project and install the necessary dependencies, including the Hardhat toolbox and the ethers.js library for blockchain interaction. You must also configure the Hardhat network settings to connect to the L2 networks you're targeting, such as Arbitrum Sepolia or Optimism Goerli testnets. This requires adding network configurations to your hardhat.config.js file with the correct RPC URLs and chain IDs. Funding your development wallet with testnet ETH on both chains is a critical step before deployment.

You will need to write and deploy two primary smart contracts: one on each participating rollup chain. These contracts implement the Hash Time-Locked Contract (HTLC) pattern. The contract on the source chain locks the sender's funds with a cryptographic hash, while the contract on the destination chain allows the receiver to claim funds by revealing the preimage. The contracts must be able to verify proofs from each other's chain, which typically requires integrating with each rollup's native cross-chain messaging system, like Arbitrum's ArbSys precompile or Optimism's CrossDomainMessenger.

For local testing, you can use tools like the Hardhat Network to simulate the two L2 environments, but testing the actual cross-chain messaging requires deploying to public testnets. A robust testing suite should verify all swap states: the successful swap where the preimage is revealed in time, the refund scenario where the sender reclaims funds after the timeout, and failure cases like invalid proofs or double-spend attempts. Using a TypeScript or JavaScript script, you will orchestrate the end-to-end swap, simulating the actions of both parties.

Finally, ensure you have access to block explorers for the relevant chains (e.g., Arbiscan, Optimistic Etherscan) to verify contract deployments and transactions. The complete code repository for this guide, including contract examples and deployment scripts, is available on the Chainscore Labs GitHub. With the environment configured and contracts deployed, you can proceed to implement the swap logic detailed in the following sections.

key-concepts-text
CORE CONCEPTS: HTLCS AND ATOMICITY

How to Implement Cross-Rollup Atomic Swaps

A technical guide to building trustless asset exchanges between different rollups using Hashed Timelock Contracts (HTLCs).

A cross-rollup atomic swap is a trustless protocol that allows two parties on different rollup chains to exchange assets without a centralized intermediary. The core mechanism ensuring security is the Hashed Timelock Contract (HTLC), a conditional smart contract that enforces atomicity: either the entire swap completes successfully, or all funds are returned to their original owners. This prevents one party from receiving an asset without sending their counterpart, a fundamental challenge in decentralized cross-chain coordination. Atomic swaps are essential for creating a composable, multi-rollup ecosystem.

The swap protocol relies on a cryptographic hash and a timelock. Party A initiates the swap by locking funds in an HTLC on Rollup A, using a secret preimage they generate. This creates a hash commitment H = hash(secret). Party B can see this hash and, if they agree to the terms, locks their funds in a corresponding HTLC on Rollup B, using the same hash H. The timelock (T) is a critical parameter that defines a deadline by which the swap must be completed, after which locked funds become refundable.

Execution follows a two-step claim process. First, Party B, who now possesses the hash H but not the secret, cannot claim Party A's funds. To claim them, Party B must first learn the secret. They do this by completing their side of the deal: they claim Party A's funds on Rollup A by submitting the secret, which is revealed on-chain in the process. Once Party B reveals the secret to claim the first asset, Party A (or anyone observing) can use that now-public secret to claim the counterpart asset locked on Rollup B before the timelock T expires. This sequence ensures the swap is atomic.

Implementing this requires smart contracts on both rollups. Below is a simplified HTLC interface in Solidity for an ERC-20 token swap. The core functions are lock, claim, and refund.

solidity
interface IHTLC {
    function lock(
        bytes32 hash,
        address token,
        uint256 amount,
        address recipient,
        uint256 timelock
    ) external payable;
    function claim(bytes32 secret) external;
    function refund(bytes32 hash) external;
}

The lock function creates the conditional payment. The claim function requires the preimage secret that hashes to the original hash. The refund function allows the original locker to reclaim their assets after the timelock expires if the claim hasn't occurred.

Key design considerations include timelock synchronization and cross-chain communication. The timelock on the second rollup (Rollup B) must be significantly shorter than the first (Rollup A) to ensure Party A has a sufficient window to claim after Party B reveals the secret. Furthermore, the protocol depends on one chain learning about on-chain events from the other. While a simple implementation might rely on users manually submitting proofs, advanced systems integrate with cross-rollup messaging protocols like LayerZero or Hyperlane to automate event relaying and proof verification, moving towards a seamless user experience.

Practical challenges remain, primarily around liquidity fragmentation and rollup bridge trust. While HTLCs remove the need to trust a counterparty, users must still trust the security of the underlying rollups and their bridges for fund deposition. For widespread adoption, liquidity pools utilizing HTLCs, similar to atomic swap DEXs like Comit Network, may emerge. Developers should audit timelock logic thoroughly and consider using established libraries like OpenZeppelin's TimelockController for inspiration. Testing with rollup development frameworks like Foundry's forge against local Anvil or Rollup devnets is crucial before deployment.

system-components
CROSS-ROLLUP ATOMIC SWAPS

System Architecture Components

Atomic swaps enable trustless asset exchange between different rollups. This requires specific components to coordinate, verify, and finalize transactions across chains.

02

Verification & State Proofs

Proving the state of one rollup to another is critical for swap verification.

  • Optimistic Rollups: Rely on fraud proofs and a challenge period (e.g., 7 days for Arbitrum), making fast atomic swaps complex.
  • ZK-Rollups: Use validity proofs (ZK-SNARKs/STARKs) for instant, cryptographic verification. A ZK proof can attest that an HTLC was correctly created on the source chain.
  • Shared Sequencers: Emerging solutions like Espresso or Astria provide a unified sequencing layer, offering native cross-rollup transaction ordering and proof availability.
03

Relayer Networks

Off-chain services that monitor chains and submit transactions to fulfill swap conditions.

  • Responsibilities: Watch for HTLC locks, submit preimage-reveal transactions, and handle gas fees on the destination chain.
  • Decentralization: Networks like Across use a decentralized set of relayers with bonded stakes to prevent censorship.
  • Fee Economics: Relayers are incentivized via fees and must manage gas price arbitrage between L2s.
  • Vulnerability: The system's liveness depends on at least one honest, well-funded relayer.
05

Interoperability Protocols

Frameworks that standardize cross-chain communication for swaps.

  • IBC (Inter-Blockchain Communication): Used in Cosmos, defines packet structure, ordering, and proof verification. Adapting IBC to Ethereum rollups is an active area of research.
  • Chain-Agnostic Standards: CCIP (Chainlink) and LayerZero provide generalized messaging layers that can be used to trigger HTLC logic on destination chains.
  • Atomicity Guarantee: These protocols provide the transport layer, but the swap logic (HTLC) must be implemented in the connected smart contracts.
06

Implementation Checklist

Key steps to build a cross-rollup atomic swap.

  1. Design Contracts: Deploy interoperable HTLC contracts on both source and destination rollups.
  2. Choose Proof System: Determine if you'll use native verification (ZK) or a fraud-proof window.
  3. Integrate a Relayer: Use an existing network or build a simple watcher service.
  4. Handle Gas: Ensure the relayer or user can pay fees on the target chain, possibly via meta-transactions.
  5. Test Thoroughly: Simulate mainnet conditions, including chain reorgs and gas spikes. Example: A swap from Arbitrum to zkSync Era requires managing the 7-day challenge period on Arbitrum.
step-1-htlc-contract
CORE CONTRACT

Step 1: Write the HTLC Smart Contract

The foundation of a cross-rollup atomic swap is a Hashed Timelock Contract (HTLC). This smart contract acts as a secure, conditional escrow that enforces the swap's rules on both chains.

An HTLC is a specialized smart contract that holds funds until one of two conditions is met. The first condition is the presentation of a cryptographic secret, known as a preimage, that matches a publicly committed hash. The second is the expiration of a predefined time lock. In a cross-rollup swap, identical HTLCs are deployed on both the source and destination rollups (e.g., Arbitrum and Optimism). The contract on the source chain locks the initiator's funds, while the contract on the destination chain locks the counterparty's funds, with both contracts using the same hash and timelock parameters.

The contract logic is straightforward but must be secure. Key functions include lock, which allows a user to deposit funds by specifying the hash H and the beneficiary address. The withdraw function lets the beneficiary claim the funds by providing the correct preimage R that hashes to H. Finally, the refund function allows the original depositor to reclaim their funds after the timelock period has expired, but only if the funds haven't already been withdrawn. This creates the "atomic" property: either the swap completes successfully when the secret is revealed, or both parties get their money back.

Here is a simplified Solidity example for an HTLC on an EVM-compatible rollup:

solidity
contract HTLC {
    address public sender;
    address public recipient;
    bytes32 public hashLock;
    uint public timelock;
    uint public balance;
    bool public withdrawn;
    bool public refunded;

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

    function withdraw(bytes32 _secret) external {
        require(!withdrawn && !refunded, "Funds already claimed");
        require(sha256(abi.encodePacked(_secret)) == hashLock, "Invalid secret");
        require(msg.sender == recipient, "Not recipient");
        withdrawn = true;
        payable(recipient).transfer(balance);
    }

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

Critical security considerations for the contract include using a strong hash function like keccak256 or sha256, ensuring the timelock duration is sufficient for the cross-chain message relay, and preventing reentrancy attacks. The timelock on the second rollup must be significantly longer than the timelock on the first to account for potential delays in proving the secret's revelation across the bridge. A common pattern is to set the destination chain's timelock to be at least 4-6 hours longer than the source chain's to create a safe buffer.

Once this contract is written and audited, the next step is deployment. You will need to deploy an identical instance on both participating rollups. The contract addresses, the agreed-upon hash H, the asset amounts, and the two timelock values (T1 for Chain A, T2 for Chain B where T2 > T1) become the core parameters that both parties must agree upon and verify before any funds are locked, setting the stage for the swap execution.

step-2-relayer-service
IMPLEMENTATION

Build the Relayer Service

This section details how to construct the off-chain relayer service that coordinates the atomic swap, ensuring both transactions are submitted to their respective rollups.

The relayer service is the off-chain coordinator for an atomic swap. Its primary function is to monitor the state of the swap on both rollups and submit the second transaction only after confirming the first is finalized. You can implement this as a simple Node.js script, a long-running process, or a serverless function. The service needs access to RPC endpoints for both the source and destination rollups (e.g., an Optimism Sepolia RPC and an Arbitrum Sepolia RPC) and must hold the private key for the relayer wallet that will submit the completeSwap transaction.

The core logic follows a state machine. First, after the user initiates the swap with initiateSwap on Rollup A, the relayer listens for the SwapInitiated event. Upon detecting it, the relayer extracts the secretHash and timelock from the event logs. It then continuously polls the contract on Rollup A, calling a view function to check if the preimage (the secret) has been revealed. The relayer must wait for finality on Rollup A, which could mean waiting for a certain number of L2 block confirmations or for the state root to be posted to L1, depending on the rollup architecture.

Once the preimage is confirmed on Rollup A, the relayer uses it to call completeSwap on the contract on Rollup B. This involves signing and broadcasting a transaction to the destination rollup's RPC. The service must handle transaction lifecycle events: monitoring for inclusion, confirmation, and potential reverts. Error handling is critical; the service should implement retry logic for RPC errors and have a fallback mechanism to manually submit the completion transaction if the primary relayer fails, ensuring the user's funds are not permanently locked.

For production, consider these enhancements: Private Key Management: Use a secure secret manager (e.g., AWS Secrets Manager, GCP Secret Manager) instead of environment variables. High Availability: Deploy multiple relayers behind a load balancer or use a distributed lock (e.g., with Redis) to prevent duplicate transaction submission. Monitoring and Logging: Integrate with logging services (Datadog, Grafana) and set up alerts for failed transactions or stalled swap states. The OpenZeppelin Defender Sentinels platform is a managed alternative for automating these types of cross-chain transactions.

IMPLEMENTATION COMPARISON

Messaging Protocols for Cross-Rollup Communication

Comparison of the primary protocols used to pass messages and state proofs between rollups for atomic swap execution.

Protocol FeatureArbitrum Nitro (BOLD)Optimism (Cross-Chain Messaging)zkSync Era (L1→L2 Messaging)StarkNet (L1<>L2 Messaging)

Native Bridge Messaging

Gasless Relayer for L2→L1

Via Paymaster

Average Finality Time (L2→L1)

~1 week (Dispute Period)

~20 minutes

~1 hour

~3-4 hours

Average Finality Time (L1→L2)

< 10 min

< 10 min

< 10 min

< 10 min

Cost per Message (Est. Mainnet Gas)

$5-15

$3-8

$2-7

$8-20

Supports Custom Data Payloads

Requires Trusted Relayer for Speed

Formal Verification of Bridge Contracts

step-3-frontend-integration
IMPLEMENTATION

Step 3: Integrate with a Frontend

This guide walks through building a web interface to interact with a cross-rollup atomic swap smart contract, using a React application with ethers.js and the Wagmi library.

To begin, set up a new React project and install the necessary dependencies. You will need a library for wallet connection and blockchain interaction. We recommend using Wagmi and viem for a modern, type-safe experience. Install them with npm install wagmi viem @tanstack/react-query. Configure your app's provider by wrapping it with WagmiConfig, specifying the chains (e.g., Arbitrum, Optimism) and a wallet connector like MetaMask. This setup abstracts away low-level RPC calls and manages connection state.

The core logic involves interacting with the atomic swap contract deployed in the previous step. You will need its Application Binary Interface (ABI) and address on both the source and destination rollups. Create a custom hook using Wagmi's useContractWrite and useContractRead to call functions like initiateSwap, completeSwap, and checkSwapStatus. For example, to initiate a swap, you would prepare a transaction that calls initiateSwap(recipientAddress, secretHash, timeout), funded with the token amount to be swapped.

A critical component is the secret generation and revelation flow. The frontend must: 1) Generate a cryptographically random secret and its SHA-256 hash client-side (using crypto.subtle). 2) Send the hash to initiate the swap. 3) Reveal the secret to complete the counterparty's swap. Store the secret securely in the application's state (e.g., using useState or a context) and never log it. The UI should guide the user through these steps sequentially, displaying transaction statuses and countdown timers for the swap's timeout period.

Handling cross-chain interactions requires listening for events on both networks. Use Wagmi's useContractEvent hook to listen for the SwapInitiated event on the source chain. Upon detection, your UI should update to show the swap as 'Pending' on the destination chain. You must then prompt the user to switch their wallet network (using switchChain from Wagmi) to the destination rollup to complete their side of the swap. Error handling is essential here—catch and display common issues like insufficient funds, wrong network, or transaction reverts.

Finally, consider user experience and security best practices. Implement clear UI states: 'Connect Wallet', 'Select Tokens', 'Approve Spending', 'Initiate Swap', 'Wait for Counterparty', 'Complete Swap'. Use the useWaitForTransaction hook to show confirmations. For production, you should integrate a block explorer API (like Arbiscan or Optimistic Etherscan) to generate links for users to verify transactions. Always inform users that they must stay on the page until both sides are complete, as losing the secret means losing funds.

CROSS-ROLLUP ATOMIC SWAPS

Frequently Asked Questions

Common developer questions and troubleshooting for implementing trustless asset exchanges across different rollup ecosystems.

A cross-rollup atomic swap is a trustless protocol that enables two parties to exchange assets across different rollup chains without a centralized intermediary. It works by using hash timelock contracts (HTLCs) deployed on both rollups.

Core Mechanism:

  1. Commit Phase: Party A locks Asset X on Rollup A into an HTLC, generating a cryptographic secret hash.
  2. Reveal Phase: Party B, seeing the hash, locks Asset Y on Rollup B into a corresponding HTLC.
  3. Claim Phase: Party A reveals the secret to claim Asset Y on Rollup B. This action reveals the secret to Party B, who can then use it to claim Asset X on Rollup A.

The swap is atomic: either both parties get the desired assets, or the transaction times out and funds are refunded. This eliminates counterparty risk and does not require a bridging liquidity pool.

CROSS-ROLLUP ATOMIC SWAPS

Troubleshooting Common Issues

Implementing atomic swaps between different rollups presents unique challenges. This guide addresses common developer errors, security pitfalls, and integration issues.

A revert in a cross-rollup atomic swap is often due to a state mismatch or deadline expiration. The most common causes are:

  • Insufficient Time Locks: The timelock on the initiating chain is too short for the counterparty to complete their action on the destination chain. Increase the lock duration to account for slower block times or congestion.
  • Hashlock Mismatch: The hashlock (the hash of the secret preimage) must be identical in both smart contracts. Verify the hash is computed off-chain using the same algorithm (e.g., keccak256) and passed correctly in the constructor or initiation function.
  • Incorrect Recipient: The msg.sender or specified recipient address in the redeem function does not match the intended beneficiary on the counterparty chain.

Debugging Steps:

  1. Emit events with the calculated hashlocks and timestamps on both chains.
  2. Use a block explorer to verify the exact calldata sent.
  3. Simulate the full swap sequence in a local forked environment using tools like Foundry's forge test.
conclusion
IMPLEMENTATION SUMMARY

Conclusion and Next Steps

You have now explored the core mechanisms for implementing trust-minimized cross-rollup atomic swaps, a critical primitive for a multi-chain future.

Building a production-ready cross-rollup atomic swap requires moving beyond the conceptual HTLC and AtomicSwap contracts. Key next steps include implementing robust relayer services to broadcast transactions and proofs, integrating with oracles like Chainlink or Pyth for secure timestamp verification, and adding comprehensive error handling for scenarios like partial fills or network congestion. Your contracts should emit detailed events for off-chain indexers and include administrative functions for pausing swaps in case of a critical vulnerability.

For developers, the immediate path forward is to test your implementation rigorously. Deploy your contracts to testnets like Sepolia or Holesky and use frameworks like Foundry or Hardhat to simulate adversarial conditions—front-running, griefing attacks, and rollup sequencer downtime. Tools like Tenderly or OpenZeppelin Defender can help monitor contract health. Consider contributing to or forking established codebases like the Connext Amarok protocol or Across Protocol's bridge architecture, which have battle-tested cross-chain messaging layers.

The architectural choice between a centralized relayer and a decentralized verifier network has significant implications. A centralized relayer is simpler to launch but introduces a liveness dependency. A decentralized network, potentially using a proof-of-stake model for relayers, enhances censorship resistance but adds complexity. Evaluate this trade-off based on your application's security requirements and the value of assets being swapped. Protocols like Synapse Protocol employ a hybrid model for inspiration.

Looking ahead, the evolution of shared sequencing (e.g., Espresso, Astria) and native interoperability protocols (e.g., Polymer, Hyperlane) will fundamentally change the cross-rollup landscape. These infrastructures aim to provide secure, low-latency messaging as a base layer, potentially rendering custom bridging logic obsolete. Your implementation should be modular, allowing the message-passing layer to be upgraded as these new standards mature. Stay engaged with rollup team roadmaps and interoperability working groups.

To continue your learning, dive into the documentation for specific ZK-proof systems like Circom and Halo2, which are essential for building light clients. Explore formal verification tools such as Certora or K-framework to mathematically prove the safety of your swap logic. The goal is not just a working swap, but a verifiably secure one that users can trust with significant assets in a permissionless environment.

How to Implement Cross-Rollup Atomic Swaps | ChainScore Guides