Building a Telegram Bot for DEX: MEV Protection and Gas Optimization

Traders on decentralized exchanges lose profit due to frontrunning and failed transactions. We develop turnkey Telegram bots for DEX: we embed MEV protection and gas optimization so every trade executes at the best price. We reduce trade losses and time spent on manual operations.

Blockchain Development Services

Frequently Asked Questions

Latest works

  • Development of a web application for FEEDME
    Development of a web application for FEEDME
    1376
  • Development of an online store for the company FURNORO
    Development of an online store for the company FURNORO
    1350
  • B2B Advance company logo design
    B2B Advance company logo design
    796
  • Development of a web application for Enviok
    Development of a web application for Enviok
    1088
  • AIDER company logo development
    AIDER company logo development
    1034
  • CRM development for Chasseurs
    CRM development for Chasseurs
    1130

Why a Telegram bot for DEX loses money on MEV and gas

Building a Telegram bot for DEX almost always starts with swap logic and the interface, while the money is lost at a different level — the moment a transaction hits the mempool.

While the user confirms the trade in the chat, the bot sends it to the network, and it becomes visible to search bots that scan the queue and react faster.

Frontrunning in DEX works exactly like this: someone else's transaction gets placed ahead of yours with a higher fee, the price shifts, and you execute at a worse rate.

Sandwich attacks hit even harder: one transaction goes before yours, the second — right after, and the difference ends up with the attacker. For a bot, this means the user sees one price in the chat but actually gets another — and blames the service, not the market.

If the bot doesn't set a reasonable slippage threshold, every volatile pair becomes a source of losses, and when gas spikes sharply, the transaction either hangs in the queue or gets canceled after the fee for the failed attempt has already been charged.

Gas optimization here isn't about saving on fees, but about execution predictability.

The bot must assess network conditions before sending, adjust limits for the specific swap route, and be able to rebuild the transaction if conditions changed between signing and landing in a block.

Without this, the share of failed trades grows, and along with it — user frustration and churn from the bot.

MEV protection is built on several levels: private transaction submission bypassing the public mempool, splitting large orders into parts, slippage limits, and control over the order's lifetime.

Below we break down how this is handled in the bot's architecture and what exactly to check in a ready-made solution.

Bot architecture: how MEV protection and gas savings work

Private transactions instead of the public mempool

The public mempool is the main source of losses during swaps: the order is visible to sandwich bots before inclusion in a block, and they insert themselves on both sides, shifting the execution price.

Sending through a private relay (Flashbots Protect, MEV Blocker and similar) removes the transaction from public view — only the block builder sees it.

The result is measurable: the share of swaps executed worse than the quote drops from tens of percent to single digits, and slippage on large orders is reduced severalfold.

Batching and dynamic fees

Transaction batching combines several operations into a single contract call: instead of three separate swaps — one, with shared gas payment and without intermediate states that the market sees.

The dynamic fee is recalculated before each send based on the current block load, rather than a fixed value — priority is set exactly high enough to land in the nearest block, without overpaying during calm periods.

In practice, this reduces gas consumption by 20–40% on related operations and eliminates stuck transactions.

Choosing the execution mode

Option When it fits Limitations
Public mempool Simple transfers without price sensitivity Open to sandwich attacks, unpredictable slippage
Private relay Swaps and large orders Inclusion delay, dependence on the builder
Batching via contract A series of related operations Requires logic audit, higher entry threshold

The combination of a private relay and batching closes both threats at once: the order is invisible until the block, and the number of network calls is minimal.

Our engineers assemble such a route for a specific DEX and token pair — Flashbots as the transport for private transactions and a proprietary aggregator contract for batching.

Stages of Telegram bot development for DEX: from audit to handover

Developing a Telegram bot for DEX is not writing a script, but an engineering cycle where every decision is validated against historical data and execution simulation.

An error in slippage calculation or order routing costs the user money on every trade, so we start with an audit, not with code.

  1. Audit of the DEX and current trades. We capture the actual picture: which pools and pairs are involved, how gas is distributed across transaction types, where losses occur due to slippage and sandwich attacks. The output is a map of bottlenecks with numbers: the share of failed transactions, average gas overpayment, liquidity depth for target pairs.
  2. Designing the bot's architecture. We define the architecture: how the bot receives quotes, where it stores position state, how signal logic and execution are separated. We lock in the modes — manual trade confirmation or automatic entry by strategy, limits on position size and the number of simultaneous orders.
  3. Setting up MEV protection. We design submission through private transaction delivery channels, configure slippage tolerance and frontrunning protection, and add retries for rejected orders. We verify that the bot does not expose its intent to the public mempool ahead of time.
  4. Testing trading strategies. We run the logic on historical data and in simulation mode on live quotes without real funds. We look not only at profitability but also at behavior during drawdown: how the bot behaves during a sharp price move and thin liquidity.
  5. Deploying the bot. We deploy on the client's infrastructure or in an isolated environment, connect monitoring and alerts, and restrict access by roles. For the first period we operate in observation mode with manual confirmation of large trades.
  6. Handover of the solution. We hand over the source code, configurations, routing schemes, and strategy documentation. We conduct a walkthrough with the client's team: how to change parameters, how to read logs, what to do if the delivery channel fails.
  7. Post-launch support. We adjust gas and protection parameters based on the actual metrics of the first weeks, and update the logic when changes occur in DEX pools and contracts.

Describe your task — we will come back with an estimate and a plan for each stage.

How does a private mempool differ from a public one, and which should you choose?

A public mempool is a shared buffer of unconfirmed transactions that all network participants can see.

As soon as a bot sends a swap there, the trade becomes available for analysis: sandwich bots scan the stream, find your order, insert a buy before it and a sell after it, pocketing the price difference as your slippage.

For a DEX bot that executes trades on a signal, this means every large market-limit order turns into a target — you get a worse execution price than you expected and pay for someone else's arbitrage.

A private mempool works differently: the transaction goes directly to miners or validators through a closed channel, bypassing the public stream. Sandwich bots simply don't see it until it's included in a block, so frontrunning and backrunning are technically impossible.

This is the key transaction protection when a trade is sensitive to execution order: large swaps, arbitrage bundles, liquidations.

The limitation is that a private channel doesn't guarantee inclusion — if the fee is below market, the transaction may not make it into a block, and you'll have to resubmit it manually.

A public mempool isn't "bad," though — it offers predictability and full control over the fee.

If a bot trades small volumes, where the potential slippage from a sandwich is lower than the premium for a private channel, or if the strategy itself relies on competitive submission, the public route is more profitable.

A sound gas strategy matters more here than the channel: dynamic fee calculation based on current block load, a priority markup for a specific trade type, replacing a stuck transaction with the same nonce at a higher rate.

Choosing a strategy isn't "private versus public" — it's routing by trade type. Within a single bot, it makes sense to keep both channels: order-sensitive orders go through the private one, routine ones go through the public one with an adaptive fee.

We build in a switch at the trade configuration level so the route can be changed without rewriting the logic.

Case study: how a bot reduced losses from MEV and failed transactions

The client was a trading team working with liquid pairs across several DEXs.

The complaint was specific: some trades were consistently executed worse than expected, and the cause was not visible in the logs — the transaction went through, but at a price noticeably worse than the quote at the moment of signing.

The investigation revealed a classic sandwich: an attacking bot saw the trade in the mempool, inserted its own orders before and after, and pocketed the difference. Plus a second problem — failures from hitting the gas limit during spikes in activity.

We rebuilt the execution logic: the order no longer goes into the public mempool, but is submitted through a private delivery channel, where it is invisible until it is included in a block.

The gas limit is calculated not from the latest block, but from a rolling window with headroom for spikes, and the swap route is rebuilt around the actual depth of the pools rather than the nominal one. Below is what changed in the numbers.

What we changed in the execution mechanics

  • Private transaction delivery. The order goes directly to a validator, bypassing the public pool. The sandwich attack loses its entry point: the attacker has nothing to intercept.
  • Dynamic gas limit. The threshold is recalculated from network load history rather than taken as fixed. Failures from insufficient gas are gone as a category.
  • Route rebuild before signing. The bot checks pool depth at the moment of submission and changes the swap path if slippage goes beyond the tolerance.
  • Slippage protection at the order level. If the price moves beyond the boundary, the trade is not signed at all, instead of being executed at a bad price.
Option When it fits Limitations
Public mempool with a high gas limit Large pairs with dense liquidity The trade is visible to attackers, the sandwich remains
Private delivery channel Pairs with noticeable slippage Requires support on the node side
Batching orders Many small trades in a row Latency to execution grows

Metrics before and after

Worth mentioning separately is the fallback: if the private channel is unavailable, the bot reverts to public submission with a raised gas limit — the trade does not hang, but is executed, albeit with less protection. The switching logic is described in the configuration and can be changed without a rebuild.

Flashbots Protect — the private delivery mechanism on which protection against mempool interception is built.

Compatibility, migration, and rollback: technical concerns

Building a DEX Telegram bot almost never starts from scratch: the client already has wallets, nodes, a liquidity pool, and familiar entry points.

That is why the first question on a call is not "which stack," but "what exactly will have to be touched in a running system." Below are the things that most often come up during the technical review stage.

What if the bot is not compatible with our wallet? DEX compatibility is built on connection standards: the bot works with public network nodes and signs transactions through the same mechanism as your wallet.

If the wallet supports connecting to external services, no separate integration is needed — the bot sees the same balances and pools.

Bot migration without downtime. We move the logic and state to new infrastructure in parallel with the running version: traffic is switched over after verification, and the old environment remains a hot standby until stability is confirmed. The user does not notice the switch, and order and subscription history is preserved.

Transaction rollback. A confirmed transaction on the blockchain cannot be canceled — that is a property of the network, not the bot.

Therefore, protection is built before sending: simulation on the current pool state, slippage checks, a gas limit, and cancellation if the price moves beyond the boundary. If the transaction fails, the funds remain with the user, and only the network fee is charged.

How are access and security structured?

Private keys are not stored on the bot server: signing happens on the user's side or in an isolated module with restricted access. Access to the admin panel is role-based, and actions involving the movement of funds are logged with attribution to a specific operator.

The client receives:

  • a diagram of how the bot interacts with nodes, wallets, and pools;
  • network and exchange connection configurations with parameter descriptions;
  • a policy for gas limits and protection against unfavorable execution;
  • a migration and traffic-switching procedure without downtime;
  • an access matrix and a key storage model;
  • an operations log and an incident investigation guide.

Describe your current setup — wallets, exchanges, infrastructure — and we will come back with an estimate and a work plan for compatibility, migration, and rollback.

Timeline for Developing and Deploying a Telegram Bot for DEX

Timelines depend not on the volume of code, but on the number of external integrations: the more quote sources, routers, and networks, the longer the validation stage on real flows.

Below is an approximate duration by stage for a bot that calculates the trade route, assesses sandwich attack risk, and sets gas parameters. Stage boundaries overlap: design begins before the audit closes, and testing runs in parallel with configuration.

Implementation Stages and Approximate Timelines

Configuration takes the longest: this is where it becomes clear how many routes are actually available and how gas behaves under peak load.

Testing can send the task back a step — if the failure rate is higher than expected, we change the risk assessment logic rather than fudging the metric.

Can timelines be shortened? Yes, if the first release is narrowed to one network and one router — the rest is added in iterations without rewriting the core. What if we already have a bot?

The audit takes less time, but design is still needed: old gas and protection settings are usually incompatible with the new routing scheme.