A private relayer network is an infrastructure layer that abstracts gas fee management and transaction submission from end-users. Instead of users signing and paying for transactions directly, they sign meta-transactions (messages authorizing an action) which are then packaged, funded, and submitted by a trusted relayer. This model enables key features like gasless transactions, sponsored operations, and enhanced privacy for dApp users. The network typically consists of a relayer node (the software that processes requests), a signer wallet (which holds the gas funds), and a backend service to manage logic and queueing.
Setting Up a Private Transaction Relayer Network
Setting Up a Private Transaction Relayer Network
A private relayer network allows you to process and submit blockchain transactions on behalf of users without exposing their private keys. This guide covers the core architecture and initial setup.
To begin, you need to set up the core relayer node. A common approach is using the Gelato Relay SDK or OpenZeppelin Defender for managed services, or running a custom node with Ethers.js and a transaction queue like Bull or Redis. The node must listen for user requests via an API, validate the user's signature on the meta-transaction, apply any business logic (e.g., checking a payment), and then wrap the user's intent in a new transaction signed by the relayer's private key. Security at this stage is critical: the relayer must never have access to the user's private key, only the ability to verify their EIP-712 or EIP-2771 signatures.
Next, configure the funding mechanism. The relayer's signer wallet must hold native tokens (like ETH, MATIC, or AVAX) to pay for gas. For production systems, implement a gas tank strategy with automated replenishment using services like Gelato's 1Balance or a custom smart contract that holds funds. You must also decide on a fee model: will transactions be sponsored by the dApp, paid for by the user in ERC-20 tokens, or use a hybrid model? This logic is handled in your backend before the relayer submits the transaction to the public mempool.
Finally, integrate the network with your dApp. Your smart contracts must be compatible with meta-transactions, often by inheriting from OpenZeppelin's MinimalForwarder or implementing EIP-2771 Context. On the frontend, use libraries like ethers.js v6 or web3.js to create the signed meta-transaction payload and send it to your relayer's secure API endpoint. Monitor your network using tools like Tenderly for transaction simulation and Blocknative for mempool visibility to ensure reliability and quickly debug failed transactions.
Prerequisites and System Requirements
Before deploying a private transaction relayer network, you need specific hardware, software, and infrastructure components. This guide outlines the essential requirements for a production-ready setup.
A private transaction relayer network requires a robust infrastructure foundation. The core components include dedicated servers or cloud instances to run the relayer nodes, a private blockchain node (like a Geth or Erigon client for Ethereum), and a secure key management system for signing transactions. You must provision these resources with high availability and redundancy in mind, as network downtime can halt all relayed transactions. For cloud deployments, providers like AWS, Google Cloud, or specialized Web3 infrastructure services (e.g., Alchemy, Infura for node access) are common choices.
The software stack is centered around the relayer software itself. This is typically a custom-built service written in languages like Go, Rust, or TypeScript, which listens for user requests, constructs transactions, signs them with a private key, and broadcasts them to the blockchain. You will need to integrate with a specific EVM-compatible node RPC endpoint and may require additional services for monitoring (Prometheus, Grafana), logging (ELK stack), and secret management (HashiCorp Vault, AWS Secrets Manager). All software should be containerized using Docker for consistent deployment.
Security and operational requirements are non-negotiable. You must establish a secure process for generating and storing the relayer's private keys, often using hardware security modules (HSMs) or cloud KMS solutions. Network security involves configuring firewalls, VPCs, and DDoS protection. Furthermore, you need a plan for gas management, including funding the relayer's wallet with the native chain token (e.g., ETH, MATIC) and implementing logic to handle gas price fluctuations and transaction failures gracefully.
Key Concepts for Relayer Operation
A private relayer network allows you to process transactions off-chain before submitting them to the blockchain. This guide covers the core components and operational considerations.
Relayer Architecture Patterns
Private relayers typically follow one of two patterns: a centralized sequencer model for simplicity or a decentralized p2p network for censorship resistance. Key components include:
- Transaction Pool (Mempool): Manages pending user operations.
- Fee Management: Handles gas estimation and fee payment logic.
- Signer/Submitter: The account that signs and submits the final bundled transaction to the blockchain. Understanding these patterns is the first step in designing your network's fault tolerance and trust model.
Gas Abstraction & Sponsorship
A core feature of relayers is allowing users to pay fees in ERC-20 tokens instead of the native chain currency (e.g., ETH). This requires implementing a paymaster contract. The relayer must:
- Validate paymaster conditions (e.g., user has sufficient USDC).
- Securely handle the sponsorship logic, often reimbursing itself in the same transaction.
- Manage exchange rate oracles if sponsoring with volatile tokens. This is critical for user experience in account abstraction wallets.
Security & Anti-Abuse Mechanisms
Operating a public relayer endpoint requires robust safeguards to prevent economic attacks. Essential mechanisms include:
- Rate Limiting: Per IP or wallet to prevent spam.
- Transaction Simulation: Use tools like Tenderly or
eth_callto simulate every user operation before accepting it. Reject transactions that will revert or drain the paymaster. - Stake Slashing: If using a decentralized network like EigenLayer, define slashing conditions for malicious behavior. Without these, your relayer is vulnerable to denial-of-service and financial loss.
Monitoring & Alerting
Proactive monitoring is non-negotiable for a production relayer. You need visibility into:
- Queue Health: Mempool size and oldest transaction age.
- Success/Failure Rates: Track reverted bundles and investigate causes.
- Gas Price Trends: Monitor base fee spikes to adjust submission strategies.
- Paymaster Balance: Set low-balance alerts for your sponsoring contract. Tools like Prometheus/Grafana for metrics and PagerDuty for alerts are standard in this space.
ERC-4337 Bundler Specifications
The ERC-4337 standard defines the bundler role, which is a specific type of relayer. To be compliant, your implementation must:
- Adhere to the
UserOperationmempool format. - Properly handle the
entryPointcontract flow for verification and execution. - Support alternative mempools like the Pimlico and Alchemy networks for operation sharing. The official ERC-4337 reference bundler in Rust is the canonical implementation to study.
Choosing Your Stack
Your technology choices depend on required throughput and complexity. Common stacks include:
- High-Level SDKs: Use
account-abstractionkits from providers like Biconomy or Stackup for faster deployment. - Custom Node.js/Python: Build using libraries like
userop.jsfor flexibility. - Rust/Go: For maximum performance and reliability, as seen in the reference bundler. Consider whether you need to support multiple chains, as this adds complexity for gas estimation and RPC management.
Setting Up a Private Transaction Relayer Network
A private transaction relayer network allows you to process and forward user operations off-chain, abstracting gas fees and improving UX. This guide covers the core architecture and deployment steps.
A private transaction relayer network is a key infrastructure component for account abstraction and gasless transactions. Its primary function is to receive signed user operations (UserOperations), bundle them, and submit them to a paymaster contract for sponsorship before sending the final bundle to an EntryPoint contract on-chain. This architecture decouples the user from needing native tokens for gas, enabling seamless onboarding. Core components include the relayer server, a bundler service, a paymaster for gas sponsorship, and a mempool for holding pending operations.
To set up a basic relayer, you first need to deploy the necessary smart contracts. The most critical is the EntryPoint contract (v0.6), which is the singleton contract that validates and executes bundles. You'll also need a paymaster contract, which holds funds and implements logic to decide which operations to sponsor. For testing, you can use the verifying paymaster from the account-abstraction samples repository. Deploy these contracts to your target network (e.g., a local Anvil instance or a testnet) using Foundry or Hardhat.
The next step is to configure and run the bundler software. The official reference implementation is the ERC-4337 Bundler, written in Rust. Clone the repository and configure the bundler.config.json file. Key settings include the entry_point address, the beneficiary address (which receives gas refunds), the RPC URL for your Ethereum node, and the chain ID. You must also configure the whitelist or policy to define which paymasters and account factories your bundler will accept operations for. Run the bundler with cargo run to start listening for UserOperations via its JSON-RPC endpoint.
Your application's frontend or SDK must then be configured to send UserOperations to your private relayer network instead of directly to a public RPC. Libraries like UserOperation.js or ZeroDev SDK can help construct these operations. The user signs the operation, which is then sent via eth_sendUserOperation to your bundler's RPC URL. The bundler validates the operation's signature and paymaster data, adds it to its mempool, and eventually creates a bundle to submit on-chain. This setup allows you to offer gas sponsorship, batch transactions, and session keys as features for your users.
For production, security and monitoring are critical. Implement rate limiting and operation validation logic to prevent spam. Monitor your bundler's mempool size and bundle submission success rate. Use a high-availability RPC provider like Alchemy or Infura for reliable node access. Consider running multiple bundler instances behind a load balancer for redundancy. Keep your paymaster contract funded and monitor its balance, as it will pay for all sponsored gas. This private infrastructure gives you full control over the transaction flow and user experience for your application.
Private Mempool Service Comparison
Comparison of major private transaction relaying services based on technical features, costs, and network support.
| Feature / Metric | Flashbots Protect | bloXroute Private Transactions | Eden Network | Titan Builder |
|---|---|---|---|---|
Core Mechanism | MEV-Share order flow auction | Direct private RPC endpoint | Priority block space auction | Exclusive block builder |
Max Priority Fee Supported | ||||
Transaction Revert Protection | ||||
EVM Chain Support | Ethereum, Polygon, Arbitrum | Ethereum, 10+ EVM chains | Ethereum | Ethereum, Arbitrum, Optimism |
Simulation Before Submission | ||||
Typical Cost Premium | 0% (tip to searcher) | $0.10 - $1.00 per tx | 0.1 - 0.5 ETH per block | 10-20% of gas cost |
Submission Latency | < 2 seconds | < 1 second | < 12 seconds | < 500ms |
Open Source Client |
Step 1: Relayer Node Configuration
This guide details the initial setup of a private transaction relayer network, covering environment configuration, node deployment, and essential security practices.
A relayer node is a specialized server that receives, validates, and forwards user-signed transactions to the blockchain. For a private network, you control the infrastructure, which is critical for applications requiring privacy, custom gas policies, or guaranteed transaction ordering. The core components include a secure execution environment, a blockchain client (like Geth or Erigon), and the relayer software itself, which is often built using frameworks like OpenZeppelin Defender or custom Go/Node.js services.
Begin by provisioning a cloud server or dedicated machine. For a production-grade node, we recommend a minimum of 4 vCPUs, 8GB RAM, and a 100GB SSD. Use a hardened Linux distribution (Ubuntu 22.04 LTS is common) and configure a non-root user with sudo privileges. Essential first steps include setting up a firewall (UFW or iptables) to allow only necessary ports (e.g., 8545 for JSON-RPC, 30303 for peer discovery) and installing Docker for containerized deployment, which simplifies dependency management and updates.
Next, configure the blockchain client. For an Ethereum-compatible chain, sync a Geth node in --syncmode snap for faster initial synchronization. The critical configuration is the geth command to start the node with your private network settings: geth --datadir ./chaindata --networkid 12345 --http --http.addr 0.0.0.0 --http.api eth,net,web3 --http.corsdomain "*" --nodiscover. This command initializes a local chain with network ID 12345, enables the HTTP JSON-RPC interface on all addresses, and disables peer discovery to keep the network private.
The relayer application logic is typically a service that listens for incoming transaction requests via an API, wraps them with the necessary gas and network parameters, and submits them using a funded account. A basic Node.js relayer endpoint using Ethers.js might look like this:
javascriptapp.post('/relay', async (req, res) => { const { signedTx } = req.body; const provider = new ethers.providers.JsonRpcProvider('http://localhost:8545'); const txResponse = await provider.sendTransaction(signedTx); res.json({ txHash: txResponse.hash }); });
Secure this endpoint with API keys and rate limiting immediately.
Finally, implement operational safeguards. Use environment variables or a secrets manager for your relayer's private key and API credentials—never hardcode them. Set up Prometheus and Grafana for monitoring node health, including sync status, memory usage, and pending transaction queues. Automate deployment and updates using a CI/CD pipeline. For high availability, consider deploying multiple relayers behind a load balancer, ensuring they share a synchronized mempool or database to prevent transaction duplication or nonce conflicts.
Step 2: RPC Endpoint and Load Balancer Setup
Configure a private RPC endpoint and load balancer to manage traffic, ensure reliability, and provide a single access point for your transaction relayer network.
A private RPC endpoint is the primary interface through which your application or users will submit transactions to your relayer network. Instead of connecting directly to individual node providers, you expose a single URL that acts as a gateway. This endpoint is typically a lightweight web server that authenticates requests, applies any custom logic (like gas policies), and forwards them to the backend infrastructure. Setting this up involves deploying a service, often using frameworks like Express.js for Node.js or a similar web framework, that can handle JSON-RPC requests.
The core component behind this endpoint is the load balancer. Its job is to distribute incoming JSON-RPC requests across your pool of configured node providers (e.g., Alchemy, Infura, QuickNode, or private nodes). This provides critical benefits: high availability (if one provider fails, traffic routes to others), load distribution (preventing overloading a single provider), and performance optimization (routing requests to the fastest or cheapest node). You can implement strategies like round-robin, latency-based routing, or failover logic within your load balancer.
For a basic implementation, you can use a reverse proxy like Nginx or HAProxy. However, for blockchain-specific needs—such as tracking nonces, managing request timeouts, or handling chain reorgs—a custom application load balancer is often necessary. Here's a simplified Node.js example using the express and axios libraries to create a round-robin load balancer across two RPC URLs:
javascriptconst express = require('express'); const axios = require('axios'); const app = express(); app.use(express.json()); const providers = [ 'https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY', 'https://mainnet.infura.io/v3/YOUR_KEY' ]; let currentIndex = 0; app.post('/', async (req, res) => { const targetProvider = providers[currentIndex % providers.length]; currentIndex++; try { const response = await axios.post(targetProvider, req.body); res.json(response.data); } catch (error) { res.status(500).json({ error: 'RPC request failed' }); } }); app.listen(8545, () => console.log('Relayer endpoint on port 8545'));
In production, your load balancer must include robust error handling. This involves catching provider timeouts, parsing error responses (like -32005 rate limit errors), and implementing automatic retries with a different provider. You should also add request logging and metrics collection (using tools like Prometheus) to monitor the health and performance of each backend node. This data is essential for identifying unreliable providers and fine-tuning your routing logic.
Finally, secure your endpoint. At a minimum, use API key authentication to prevent unauthorized public access. For more sensitive operations, consider implementing IP whitelisting or more advanced authentication methods. The configured endpoint URL (e.g., https://rpc.yourdomain.com) is what you will provide to your dApp or backend services, completing the public-facing setup of your relayer network's infrastructure layer.
Step 3: Implementing a Fee Strategy
A sustainable fee model is critical for operating a private transaction relayer network. This step covers designing a strategy that covers operational costs while providing value to users.
The core of your fee strategy is determining the cost basis for relaying a transaction. This includes the gas you pay on the destination chain, any gas spent on optional pre or post-processing logic, and the operational overhead of your relay infrastructure. For a basic setup, your fee can be a simple markup: userFee = estimatedGasCost * gasPrice * (1 + profitMargin). More advanced strategies might implement dynamic pricing based on real-time network congestion using oracles like Chainlink or Pyth for gas price feeds.
You must decide how users will pay these fees. The two primary models are fee abstraction (paying in the source chain's native token) and fee payment in destination gas. Fee abstraction is more user-friendly but requires you to manage cross-chain value flows. A common implementation is to have users sign a message authorizing a fee, which your off-chain relayer submits alongside the main transaction, collecting payment on the source chain via a FeeCollector contract. The EIP-4337 Bundler specification provides a robust reference for this pattern.
For transparency and trust, your fee logic should be verifiable. Consider implementing a commit-reveal scheme or publishing signed fee quotes. Your relayer backend can generate a quote including the fee amount, a nonce, and an expiry timestamp, sign it, and send it to the user's client. The user then submits this signed quote with their transaction request. Your on-chain RelayHub contract can verify the signature and enforce the quoted fee, preventing the relayer from charging more than advertised.
Here is a simplified example of a smart contract function that validates a signed fee quote before executing a relayed call:
solidityfunction relayCall( address target, bytes calldata data, uint256 maxFee, uint256 nonce, uint256 deadline, bytes calldata signature ) external { require(block.timestamp <= deadline, "Quote expired"); require(!usedNonces[nonce], "Nonce already used"); bytes32 messageHash = keccak256(abi.encodePacked(target, data, maxFee, nonce, deadline)); address signer = ECDSA.recover(messageHash, signature); require(signer == trustedRelayer, "Invalid signature"); usedNonces[nonce] = true; // Execute the call and transfer the fee to the relayer (bool success, ) = target.call(data); require(success, "Call failed"); payable(signer).transfer(maxFee); }
Finally, monitor and iterate. Use analytics to track average profit margins, fee payment failure rates, and user adoption. Be prepared to adjust your model based on gas price volatility and competitive pressures. A well-calibrated fee strategy ensures your relayer network remains operationally sustainable without becoming a prohibitive cost for your users, striking a balance between service quality and economic viability.
Step 4: Integration with dApp Frontends
This guide explains how to connect your dApp's frontend to a private transaction relayer network, enabling users to submit gasless or sponsored transactions.
A private relayer network acts as a middleware layer between your dApp's frontend and the blockchain. Instead of users signing and sending transactions directly from their wallets (which requires them to hold native gas tokens), the frontend sends a signed meta-transaction to your relayer endpoint. This meta-transaction contains the user's intent (e.g., swap, mint) and a signature, but lacks gas payment details. Your relayer network is responsible for wrapping this intent in a new transaction, paying for the gas, and broadcasting it to the network. This architecture is fundamental for gasless UX, onboarding, and complex transaction batching.
To integrate, your frontend must be configured to use a custom RPC provider or a dedicated SDK. For networks like Polygon, you might use the @biconomy SDK to create and send userOp objects for Account Abstraction. For EVM chains, you can use the ethers.js JsonRpcProvider pointed to your relayer's API endpoint. The core frontend flow involves: 1) constructing the transaction data with the user's wallet, 2) signing the data (often a EIP-712 structured message), and 3) sending the signed payload via HTTP POST to your relayer's /relay endpoint. The relayer returns a transaction hash once it submits the sponsored tx on-chain.
Here is a simplified code example using ethers.js and a hypothetical relayer API:
javascriptimport { ethers } from 'ethers'; // 1. User signs the meta-transaction data const userSignature = await signer._signTypedData( domain, // EIP-712 domain types, // EIP-712 types payload // The transaction intent ); // 2. Send to private relayer const relayResponse = await fetch('https://relayer.your-dapp.com/relay', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ signature: userSignature, payload: payload, userAddress: signer.address }) }); const { txHash } = await relayResponse.json(); // 3. Monitor the relayed transaction const receipt = await provider.waitForTransaction(txHash);
This pattern decouples signing from submission, which is the key to gasless experiences.
Security is paramount when integrating a relayer. Your frontend must validate the relayer's response and implement error handling for failed transactions. Always use HTTPS for all API calls. The relayer should implement rate limiting, nonce management, and signature verification to prevent replay attacks. For production dApps, consider using established infrastructure like OpenGSN (Gas Station Network), Biconomy, or Stackup which provide battle-tested SDKs and dashboard for managing relay policies, instead of building your own from scratch. These services handle the complexities of gas estimation, nonce conflicts, and transaction queuing.
Finally, monitor the integration's performance. Track metrics like relay latency, transaction success rate, and gas sponsorship costs. Provide clear user feedback in the UI—inform users when a transaction is being relayed and when it's confirmed on-chain. A well-integrated relayer network should be invisible to the end-user, resulting in a seamless Web3 experience where complex blockchain interactions feel as simple as clicking a button on a traditional web application.
Common Issues and Troubleshooting
Resolve frequent challenges when deploying and operating a private transaction relayer network for MEV protection, gas sponsorship, or account abstraction.
A relayer failing to process UserOperations typically stems from configuration or validation errors. Check these common points:
- EntryPoint Mismatch: Ensure your relayer's configured
EntryPointcontract address matches the one your smart accounts use. Mismatches cause silent failures. - Stake Status: If using a paymaster, verify it has sufficient stake deposited in the EntryPoint. An unstaked paymaster will cause operations to be rejected.
- Gas Estimates: The relayer's gas estimation might be incorrect. Use tools like
userop.jsto simulate the operation locally and verify thepreVerificationGas,verificationGasLimit, andcallGasLimitare adequate. - RPC Endpoint: Confirm the relayer's connection to the blockchain RPC is stable and synced. Timeouts or unsynced nodes will prevent operation bundling.
Essential Resources and Documentation
Resources and technical references for building and operating a private transaction relayer network. These cards focus on relayer design, transaction privacy, infrastructure hardening, and production-grade operations.
Frequently Asked Questions
Common technical questions and troubleshooting for developers building and operating private transaction relay networks.
A private transaction relayer network is a decentralized infrastructure of nodes that submit, bundle, and propagate transactions on behalf of users. Unlike public mempools, it keeps transactions off the public network until they are included in a block. This is used for:
- MEV Protection: Prevents front-running and sandwich attacks by hiding transaction intent.
- Transaction Ordering: Allows for fair, first-come-first-served ordering, mitigating negative MEV.
- Guaranteed Inclusion: Relayers can provide a service-level agreement (SLA) for transaction inclusion, often using a commit-reveal scheme.
Protocols like Flashbots SUAVE and bloXroute's private transaction service are prominent examples. A private network is essential for applications like DEX trading, NFT minting, or any on-chain action where timing and price are critical.