A relayer network is a decentralized system of nodes that facilitate secure message passing between different blockchain environments or off-chain services. Unlike centralized message queues, these networks use economic incentives and cryptographic proofs to ensure data availability and delivery guarantees. Key applications include cross-chain bridges (like LayerZero and Axelar), optimistic rollup fraud proofs, and oracle data feeds. The core challenge is creating a trust-minimized system where relayers cannot censor, delay, or tamper with messages without being penalized.

Setting Up a Relayer Network for Secure Message Passing
Setting Up a Relayer Network for Secure Message Passing
A practical guide to building a decentralized message relayer network, covering architecture, implementation, and security considerations for cross-chain and off-chain communication.
The architecture typically involves three components: an on-chain verifier contract, a set of off-chain relayer nodes, and a cryptographic commitment scheme. Messages are posted with a commitment (e.g., a Merkle root) to the source chain. Relayers fetch this data, attest to its validity, and submit it with a proof to the destination. To prevent spam and ensure liveness, relayers often must stake collateral (like in EigenLayer or Across Protocol) which can be slashed for malicious behavior. Networks can be permissioned, permissionless, or use a proof-of-authority model for specific consortia.
To implement a basic relayer, you'll need to interact with smart contracts on both source and destination chains. Below is a simplified TypeScript example using ethers.js that listens for an event and relays a message. This assumes a contract emitting a MessageSent event containing a messageHash.
typescriptimport { ethers } from 'ethers'; import { Relayer } from 'defender-relay-client'; const sourceProvider = new ethers.providers.JsonRpcProvider(SOURCE_RPC); const destProvider = new ethers.providers.JsonRpcProvider(DEST_RPC); const destWallet = new ethers.Wallet(PRIVATE_KEY, destProvider); const sourceContract = new ethers.Contract(SOURCE_ADDRESS, SOURCE_ABI, sourceProvider); const destContract = new ethers.Contract(DEST_ADDRESS, DEST_ABI, destWallet); sourceContract.on('MessageSent', async (messageHash, event) => { try { const tx = await destContract.receiveMessage(messageHash); await tx.wait(); console.log(`Relayed message hash: ${messageHash}`); } catch (error) { console.error('Relay failed:', error); } });
Security is paramount. A naive relayer is a single point of failure. Production systems require decentralization and fault tolerance. Consider using a network like Gelato or OpenZeppelin Defender for automated, managed relaying with built-in redundancy. For censorship resistance, implement a relayer auction or threshold signature scheme (TSS) where multiple nodes must sign off on a message. Always verify message validity on-chain before acting; never trust the relayer's off-chain assertion. Common vulnerabilities include replay attacks, gas price manipulation, and validator set collusion.
When designing your network, key decisions include the data transport layer (P2P vs. hosted), incentive model (fee market vs. fixed reward), and consensus mechanism for attesting to message validity. For high-value transfers, use optimistic verification with a fraud-proof window or zero-knowledge proofs for instant finality. Monitor network health with metrics like latency, delivery success rate, and relayer stake distribution. Open-source stacks like Hyperlane and Wormhole's Guardian network provide reference implementations for building robust, interoperable messaging layers.
Prerequisites and Core Components
Building a secure relayer network requires a foundational understanding of the core components and their interactions. This section outlines the essential prerequisites and the architectural elements you'll need to implement.
Before deploying a relayer network, you must establish the underlying infrastructure. This includes setting up nodes on the source and destination blockchains, which can be full nodes, archive nodes, or light clients depending on your latency and data requirements. You'll need access to RPC endpoints for each chain, such as an Ethereum node via Infura or Alchemy, and a Polygon node. Securely managing private keys for the relayer's funded accounts on each chain is critical, as these accounts will pay for transaction gas. Tools like HashiCorp Vault or cloud-based key management services (KMS) are commonly used for this purpose.
The core component of the system is the relayer service itself, a constantly running process that listens for events. This service is typically built using a framework like the Axelar SDK or Wormhole's Guardian SDK, which abstract much of the cross-chain logic. Your service will subscribe to specific smart contract events on the source chain using a library like ethers.js or web3.py. Upon detecting a valid event (e.g., MessageSent(bytes32 indexed messageId)), it must fetch the calldata, verify its authenticity, and prepare an equivalent transaction for execution on the destination chain.
Message formats and verification are the bedrock of security. You must define a serialization standard for your cross-chain messages. Common approaches include using Protocol Buffers (protobuf) for efficient encoding or a simple ABI-encoded structure. Each message should include a nonce to prevent replay attacks and the source chain ID for context. The relayer must implement a verification step, which often involves checking a cryptographic proof. For optimistic systems, this could be verifying a Merkle proof against a known root. For zk-based bridges like zkBridge, it involves verifying a zero-knowledge validity proof attesting to the source chain's state transition.
To ensure liveness and fault tolerance, a production relayer network requires an oracle or attestation mechanism. For a single relayer, this could be as simple as a health-check dashboard. For a decentralized network, you need a consensus mechanism among multiple relayers. This often involves running a separate consensus client (e.g., a Tendermint-based chain) where relayers run validator nodes. They observe source chain events independently, reach consensus on the validity and ordering of messages, and then collectively sign the payload before it's submitted to the destination chain. This prevents a single point of failure and malicious behavior.
Finally, you need the on-chain components: the smart contracts. On the source chain, you deploy a sender or "mailbox" contract with a function like sendMessage that emits events. On the destination chain, you deploy a receiver contract with a function like receiveMessage that can only be called by your trusted relayer address or a contract that verifies multi-signatures/zero-knowledge proofs. These contracts should include pause mechanisms, upgradeability patterns (using proxies), and rate limits to manage risk. Testing this entire flow on a testnet like Goerli and Mumbai, or using a local Anvil/Hardhat network fork, is a non-negotiable prerequisite before mainnet deployment.
Setting Up a Relayer Network for Secure Message Passing
A practical guide to architecting and deploying a decentralized relayer network for cross-chain communication, focusing on security, redundancy, and economic incentives.
A relayer network is a decentralized set of off-chain nodes responsible for listening to events on a source chain, constructing valid messages, and submitting them with proofs to a destination chain. Unlike a single trusted relayer, a network distributes this responsibility, enhancing censorship resistance and liveness. The core architectural components are: - Watchers that monitor source chain events - Attesters that sign valid message bundles - Executors that submit transactions to the destination chain - An incentive layer that rewards honest behavior and slashes malicious actors. Popular implementations include the design patterns from Axelar and Wormhole.
Security is paramount in relayer design. The network must be resilient to Byzantine failures, where a subset of nodes acts maliciously. This is typically achieved through a threshold signature scheme (TSS). For a message to be considered valid, a super-majority (e.g., 2/3) of relayers in a validator set must cryptographically sign it. The destination chain's verifier contract only accepts messages with these aggregated signatures. This setup ensures no single point of failure; compromising a message requires compromising a majority of the relayer set's private keys, which are often managed using distributed key generation (DKG) protocols.
To deploy a basic relayer, you'll need to run nodes that interact with the smart contracts on both chains. Here's a simplified flow using a hypothetical CrossChainMessaging contract: 1. Listen: Your relayer subscribes to the MessageSent event on the source chain. 2. Fetch Proof: It queries the source chain's RPC for the merkle proof of the event. 3. Attest: The relayer signs the message hash and proof. 4. Submit: It calls executeMessage(message, proof, signature) on the destination contract. In practice, you would use a relayer client library like the Axelar AMPQ relayer or Wormhole Guardian for production.
Economic incentives align relayer behavior with network security. Relay operators stake a bond (in the network's native token) to participate. They earn fees for successfully relaying messages. However, if they sign an invalid message (proven via fraud proof) or are offline during their assigned slot, their stake can be slashed. This Proof-of-Stake model makes attacks economically irrational. Networks like Chainlink's CCIP implement sophisticated risk management networks that continuously monitor for anomalies and can pause operations if a threat is detected, adding another layer of security.
For high-value applications, consider optimistic and ZK-based relay models. An optimistic system (like Nomad's original design) assumes messages are valid unless challenged within a dispute window, favoring cost-efficiency for lower-risk transfers. A ZK-based system (utilizing zk-SNARKs or zk-STARKs) has relayers generate a cryptographic proof that a message is valid, which is then verified on-chain. This offers stronger security guarantees but with higher computational overhead. The choice depends on your security budget and the latency requirements of your application.
Maintaining your network requires monitoring node health, tracking gas prices on destination chains to optimize submission costs, and rotating validator sets periodically. Use off-chain services like Gelato or OpenZeppelin Defender to automate gas-efficient transaction submission. Always conduct audits on your relayer software and the underlying smart contracts. For further reading, study the implementations of Hyperlane's Interchain Security Module and Celer's State Guardian Network.
Messaging Protocol Integration: CCIP vs. Hyperlane
Key architectural and operational differences between two leading cross-chain messaging protocols for building a relayer network.
| Feature / Metric | Chainlink CCIP | Hyperlane |
|---|---|---|
Primary Architecture | Oracle Network with Off-Chain Risk Management Network (RMN) | Modular Permissionless Network with Interchain Security Modules (ISMs) |
Consensus Model | Decentralized Oracle Network (DON) with off-chain consensus | Permissionless validator set with on-chain attestations |
Developer Abstraction | Single smart contract interface (IRouterClient) | Modular APIs for Mailbox, ISMs, and Hook contracts |
Native Gas Payment | ||
Default Finality Speed | 3-5 minutes (varies by chain) | < 5 minutes (optimistic period) |
Supported Chains (Approx.) | 12 | 70 |
Fee Model | Dynamic fee paid in source chain native gas + premium | Gas reimbursement + optional interchain gas payment |
Permissionless Interoperability | ||
Primary Use Case | High-value enterprise DeFi and token transfers | Generalized messaging for dApp composability |
Step 1: Implementing Node Selection and Registration
The foundation of a secure relayer network is a robust, decentralized set of nodes. This step covers the critical processes of selecting qualified participants and establishing their on-chain identity.
A relayer network's security and liveness depend on its node operators. The selection process must balance decentralization with performance requirements. Common criteria include minimum stake (e.g., 10,000 network tokens), proven server uptime (>99%), and a reputation score from services like Chainlink Proof of Reserve or historical on-chain activity. This pre-qualification filters out unreliable participants before they can join the network's registry.
Registration is the on-chain act where a qualified node stakes collateral and becomes an official network participant. A typical registration flow involves a RelayerRegistry.sol smart contract. The node operator calls a function like registerNode(bytes calldata metadataURI, uint256 stakeAmount), which deposits tokens into an escrow contract and emits a NodeRegistered event. The metadataURI often points to an IPFS hash containing the node's public key, endpoint URL, and service specifications.
Here is a simplified Solidity example of a registry's core function:
solidityfunction registerNode(string memory _endpoint, string memory _publicKey) external payable { require(msg.value >= MINIMUM_STAKE, "Insufficient stake"); require(!isRegistered[msg.sender], "Already registered"); nodeStake[msg.sender] = msg.value; nodeEndpoint[msg.sender] = _endpoint; registeredNodes.push(msg.sender); emit NodeRegistered(msg.sender, _endpoint, msg.value); }
This contract tracks the stake, endpoint, and list of all active nodes.
After registration, nodes are typically placed in an active set or a larger validator pool. Networks like Axelar use a proof-of-stake validator set to secure cross-chain messages, while others may use a randomized selection from the pool for each task. The stake acts as slashable collateral; malicious behavior (e.g., signing incorrect states) can lead to a portion of this stake being burned, aligning economic incentives with honest operation.
Effective node selection and registration create a Sybil-resistant foundation. The next step involves defining how these registered nodes listen for messages, achieve consensus on their validity, and execute the actual cross-chain state transitions.
Step 2: Designing the Incentive and Slashing Model
A robust economic model is the foundation of a secure relayer network. This step defines how to reward honest participation and penalize malicious or negligent behavior.
The incentive and slashing model creates the economic game theory that secures your network. The core components are a bonding mechanism, a reward schedule, and a slashing protocol. Relayers must stake a security deposit (bond) to participate. This bond is at risk if they act maliciously or fail their duties. Rewards are distributed for successful message delivery and are typically a function of the message fee and the relayer's stake weight. This aligns the relayer's financial interest with the network's health.
Designing the slashing conditions is critical for security. Common slashing offenses include: - Censorship: Failing to include a valid message in a timely manner. - Data unavailability: Not providing message data when challenged. - Byzantine behavior: Signing conflicting states or messages. The slashing penalty must be severe enough to deter attacks but calibrated to avoid punishing honest mistakes from temporary downtime. For example, a network might slash 5% of a bond for liveness failures and 100% for provable fraud.
Implementation involves writing the slashing logic into your smart contracts. Below is a simplified Solidity example of a slashing function that checks for a double-signing violation, a common byzantine fault.
solidityfunction slashForDoubleSigning( address relayer, bytes32 messageHash1, bytes32 messageHash2, bytes calldata sig1, bytes calldata sig2 ) external { require( recoverSigner(messageHash1, sig1) == relayer && recoverSigner(messageHash2, sig2) == relayer, "Invalid signatures or signer mismatch" ); require( messageHash1 != messageHash2, "Cannot slash for signing same message" ); // Logic to verify these are conflicting messages for the same nonce/chain if (isConflicting(messageHash1, messageHash2)) { uint256 bond = bonds[relayer]; bonds[relayer] = 0; // Transfer slashed funds to treasury or burn them (bool success, ) = treasury.call{value: bond}(""); require(success, "Slash transfer failed"); emit RelayerSlashed(relayer, bond, "DoubleSigning"); } }
The reward mechanism must be sustainable. Avoid inflationary token models that dilute value; instead, fund rewards directly from transaction fees paid by users. Consider a commit-reveal scheme where relayers commit to a message root and later reveal the data, earning rewards only after successful verification. This prevents front-running and ensures payment for actual work done. The exact parameters—bond size, reward percentage, slash severity—should be modeled and tested extensively in a testnet environment before mainnet launch.
Finally, governance plays a role. A decentralized autonomous organization (DAO) should control the ability to adjust slashing parameters or add new fault types via on-chain votes. This allows the network to adapt to new attack vectors discovered post-launch. However, changes to the core economic model should require a high quorum and supermajority to prevent capture. The goal is a self-sustaining system where rational economic actors are incentivized to maintain the network's integrity for long-term profit.
Step 3: Building the Off-Chain Relayer Client
This step details the construction of the off-chain component that listens for events and relays messages between chains.
The off-chain relayer client is a critical service that monitors the source chain for MessageSent events and submits the corresponding proofs to the destination chain. It acts as the active, trusted operator of the bridge. A robust implementation typically uses a TypeScript/Node.js stack with Ethers.js v6 for blockchain interaction and a database like PostgreSQL to track message state and prevent duplicate processing. The core loop involves subscribing to event logs, fetching transaction receipts, and managing nonces for the relayer's own transactions on the destination chain.
Security is paramount in the relayer's design. The client's private key, used to pay gas fees on the destination chain, must be stored securely using environment variables or a cloud KMS. The logic must include idempotency checks to ensure the same message is not relayed twice, which could drain funds. Furthermore, the relayer should implement health checks and alerting (e.g., via PagerDuty or Slack webhooks) to notify operators of halted event streams or failed transactions, ensuring high availability.
Here is a simplified code skeleton for the main relayer service loop:
javascriptimport { ethers } from 'ethers'; import { saveMessage, getMessageStatus } from './db'; async function relayMessage(sourceTxHash, message, proof) { // 1. Check database for existing processing attempt const existing = await getMessageStatus(message.id); if (existing?.status === 'relayed') return; // 2. Prepare the transaction on the destination bridge contract const destBridge = new ethers.Contract(destAddress, abi, relayerWallet); const tx = await destBridge.receiveMessage(message, proof); // 3. Update database with new status and tx hash await saveMessage(message.id, 'relayed', tx.hash); } // 4. Event listener setup on the source chain sourceContract.on('MessageSent', async (messageId, sender, contents) => { // Fetch proof from source chain RPC const proof = await fetchMerkleProof(messageId); await relayMessage(tx.hash, { id: messageId, contents }, proof); });
For production, you must handle gas estimation errors, transaction underpricing, and network congestion. Using a transaction manager like ethers.js's NonceManager and setting appropriate maxFeePerGas and maxPriorityFeePerGas is essential. Consider implementing a retry logic with exponential backoff for failed transactions. The relayer should also be stateless where possible, with all persistent data (message IDs, nonces, status) stored in the external database to allow for horizontal scaling and easy recovery from crashes.
Finally, the relayer's performance can be monitored by tracking key metrics: average relay latency, success/failure rate of transactions, and event processing backlog. Tools like Prometheus and Grafana can visualize this data. Remember, the security of the entire bridge system depends on the reliability and correct operation of this off-chain client; its code should be thoroughly audited and tested in a simulated environment before mainnet deployment.
Common Mistakes and Troubleshooting
Debug common issues when building a secure, cross-chain message passing system. This guide covers configuration errors, gas problems, and security pitfalls.
Relayer transactions fail due to insufficient gas when the execution cost on the destination chain exceeds the gas limit you set. This is common when the target contract's logic is more complex than estimated.
Common causes:
- Dynamic gas consumption: The destination contract uses storage or makes external calls.
- Incorrect estimation: Using a static gas limit instead of simulating the call via
eth_estimateGas. - Message size: Larger payloads (e.g., calldata for contract deployments) cost more.
How to fix:
- Always simulate the transaction on the destination chain using a gas estimation RPC call before submitting.
- Implement a gas buffer (e.g., 20-30%) on top of the estimated amount to account for block-to-block variance.
- For Hyperlane or Axelar, check if your IGasOracle or gas payment configuration is correctly funding the relayer's destination gas.
Essential Resources and Documentation
These resources cover the protocols, architectures, and operational tooling required to set up a relayer network for secure cross-chain message passing. Each card focuses on production-grade systems used by existing protocols.
Operational Security for Relayer Infrastructure
Running a relayer network is an infrastructure problem, not just a protocol problem. Production relayers require hardened operations.
Best practices:
- Isolate signing keys using HSMs or cloud KMS
- Enforce rate limits and packet validation off-chain
- Run geographically distributed nodes
- Monitor reorg depth and finality assumptions per chain
Additional considerations:
- Automate gas rebalancing across chains
- Handle chain halts and client expiration
- Maintain failover RPC endpoints
These practices are shared across IBC, Hyperlane, and Wormhole operators and are necessary to prevent downtime or message censorship.
Looking to build on a specific blockchain?
We build smart contracts, DeFi applications, wallets, tokenization platforms, and blockchain infrastructure across the major ecosystems teams choose today. That includes Ethereum, Arbitrum, Optimism, Polygon, Avalanche, Solana, Sui, Aptos, Hedera, Stellar, and NEAR, with support for additional EVM and non-EVM networks based on your product requirements.
EVM ecosystems
- Ethereum
- Arbitrum
- Optimism
- Polygon
- Avalanche
- Cronos

Non-EVM ecosystems
- Solana
- Sui
- Aptos
- Hedera
- Stellar
- NEAR
Additional ecosystems
- Polkadot
- Cosmos
- TON
- Cardano
- Algorand
- Tempo
Also available for Base, appchains, custom EVM networks, and cross-chain product architecture.
Frequently Asked Questions (FAQ)
Common questions and troubleshooting for developers building and managing secure cross-chain message relayers.
A relayer network is a decentralized set of independent nodes that collectively submit and attest to cross-chain messages, whereas a single relayer is a centralized service operated by one entity. The key difference is fault tolerance and censorship resistance. In a network, messages are considered finalized only after a quorum (e.g., 2/3) of relayers have signed the attestation. This prevents a single point of failure. For example, Axelar and Wormhole use permissioned networks of validators, while LayerZero uses a Decentralized Verification Network (DVN) model. A single relayer is simpler but introduces centralization risk, making it suitable for testnets or low-value transfers where liveness is more critical than censorship resistance.
Conclusion and Next Steps
This guide has covered the core components of building a secure relayer network. The final step is to integrate these pieces into a production-ready system.
You now have the foundational knowledge to deploy a functional relayer network. The key components are: a smart contract for message verification and state management (like Axelar's GeneralMessageReceiver), a relayer backend service that polls for events and submits transactions, and a secure signing mechanism (using a hardware wallet or a service like AWS KMS). The critical security practice is to keep the relayer's private key isolated from the application logic and never hardcoded.
For production deployment, consider these operational steps. First, implement health checks and monitoring for your relayer service using tools like Prometheus and Grafana to track metrics such as transaction success rate and gas costs. Second, set up automated alerting for failed message deliveries or nonce mismatches. Third, establish a key rotation policy for your relayer wallet to limit exposure in case of a compromise. Testing on a testnet like Sepolia or Goerli is essential before mainnet deployment.
To extend your network's capabilities, explore advanced patterns. Batching transactions can reduce gas costs by submitting multiple messages in a single call. Implementing fee abstraction allows the source chain application to pay for gas, improving user experience. For higher security, research multi-signature or threshold signature schemes (TSS) to require multiple approvals before a message is relayed, preventing a single point of failure.
The ecosystem offers robust frameworks to build upon. For EVM chains, consider using the OpenZeppelin Defender relayers for managed security and automation. The Wormhole and Axelar SDKs provide abstracted APIs for cross-chain messaging that can simplify development. For a deeper technical dive, review the Chainlink CCIP architecture whitepaper or the IBC (Inter-Blockchain Communication) protocol specification used by Cosmos.
Your next practical project could be to create a cross-chain governance system where a DAO on Ethereum executes votes on Polygon, or a multi-chain NFT that unlocks features based on state from another chain. Start by forking a template from the Axelar Examples GitHub or the Wormhole Quick Start repository to accelerate development.
Continuous learning is key in this rapidly evolving space. Follow protocol announcements for upgrades like EIP-7715 for relay standards. Participate in developer forums on Discord for LayerZero and Chainlink. Ultimately, a secure relayer network is not a one-time setup but a system that requires ongoing monitoring, updating, and rigorous adherence to the security principles outlined in this guide.
Delivering blockchain solutions for 5+ years.
We have partnered with 50+ leading DeFi protocols, NFT ecosystems, and fintech innovators to build secure, scalable, and capital-efficient blockchain products.
Selected Partners & Clients
“I've been working with Chainscore Labs for last 3+ years, they've consistently delivered with strong ownership across multiple projects. The team is reliable and detail-oriented.”
How to get started?
If you're looking for blockchain integration, ChainScore Labs has 5+ years of experience helping teams build and integrate exchanges, wallets, smart contracts, tokenization solutions, and protocol-connected products, we can help you choose the right path, integrate securely, and get to production faster. Our team consists of experienced blockchain developers and architects who can help you with your blockchain integration needs.
Exploration & Strategy
Define your product goals and choose the right blockchain architecture for your use case.
Architecture & Design
Design the smart contracts, tokenomics, and security parameters of your system.
Development & Integration
Build and integrate with wallets, oracles, and front-end dApps for a seamless experience.
Security & Launch
Comprehensive audits followed by a risk-managed mainnet deployment to protect your users.
Discover our
blockchain development services.
We build production-grade blockchain solutions for top-tier projects across DeFi and Web3.
Need a blockchain engineering team?
Send the project context and we will respond with next steps, scope questions, and a practical path to delivery.


