Telegram bot for swaps: where swaps break
A swap in a Telegram bot looks simple: the user selects a pair, confirms — and receives the asset. In reality, the trade goes through several independent states, and at each one it can be lost.
The most common failure is price slippage: between the quote display and confirmation, pool reserves change, and in thin pairs a large order moves the price more than the user is willing to accept.
The second failure point is a stuck operation. The transaction is signed and sent to the network, but the fee turned out to be below market, there is no confirmation, and the bot has already shown the “processing” status.
The user sees a debit, the balance is unchanged, and they go to support: formally the funds are not lost, but the trade did not occur.
The third and most expensive scenario is a route break halfway. A crypto swap in a bot rarely goes in one leg: the route is assembled through two or three pools, sometimes with an intermediate asset.
If the first leg is executed and the second fails, funds are stuck in the intermediate token, and this has to be sorted out manually.
For the client this is not an abstraction: failed swaps mean abandoned carts, first-line support flow, and bot reputation restored over months. We break down how these scenarios are closed at the mechanics level: slippage control, timeouts and cancellation, route atomicity.
Implementation effect: swap speed, failures, downtime
Swap speed
The bottleneck is not the network itself, but the chain “quote → confirmation → signature → sending”. We keep pre-warmed connections to nodes and request quotes in parallel, so the bot in Telegram responds in 1–2 seconds where a manual route took 10–15. The user does not leave to wait in another chat, and the displayed price matches the executed one.
Share of failed swaps
Failures are caused by price slippage, insufficient funds for the fee, and confirmation timeout. Retry with route recalculation, balance check before sending, and a fee buffer turn the share of failed swaps from tens of percent to single digits. Each trade retains a hash and a clear status — resolution of a disputed case takes minutes.
Payout automation
The payout queue, operation idempotency, and automatic fee selection remove manual labor: withdrawal batches go out without an operator, and a stuck transaction is picked up by a retry without creating a duplicate. Night and peak windows are covered by the same code as daytime.
Service downtime
Downtime during peak hours is usually tied to a single node and quote source limits. Node redundancy, multiple price sources, and degradation instead of failure keep the service online: some routes disconnect, the swap continues. Updates roll out node by node — the bot does not go offline.
Swap execution options: comparison of approaches
The execution scheme determines where the bot gets the rate, how it builds swap routing, and what it does when a source is unavailable. We fix the option at the design stage — the logic of confirmations, key storage requirements, and system behavior on failure depend on it.
| Option | When suitable | Limitations |
|---|---|---|
| Direct pool | One or two pairs with sufficient depth, large orders, minimum external dependencies | Rate moves noticeably under slippage; on rare pairs liquidity is thin, a large order itself moves the price |
| Liquidity aggregator | Many pairs, best rate needed without an own set of sources | Dependency on external service: response delays, request limits, part of the route opaque |
| Own router | Frequent pairs, need control over the swap path and commission retention | More expensive to support: reserve rebalancing, constant source health monitoring, harder to test |
| Custodial scheme | Deposit and withdrawal off-chain, simple interface for a novice | Funds in operator accounts — stricter key requirements, some operations manual, regulatory restrictions added |
In practice, one option is rarely taken in pure form. More often we assemble a hybrid: a liquidity aggregator as the base rate source, an own router on pairs with constant flow, and a custodial scheme as a reserve for large orders.
Such a combination gives predictable execution and a clear scenario when the source responds with an error: the route rebuilds and the swap goes through the reserve channel without user involvement.
How implementation goes: stages of engineering work
The audit starts not with code, but with how assets actually move between wallets, exchanges, and networks. At this step we fix places where a transaction can get stuck and agree on acceptance criteria: what share of operations passes on the first attempt and in what time.
- Infrastructure audit. We check access to network nodes, key storage, provider limits, and logs of past failures. Output — a list of bottlenecks that cannot be closed by code alone.
- Asset flow scheme. We break down how the token leaves the user, which pools it passes through, and where it returns. The scheme shows where the signature remains with the user and where the service controls it.
- Route setup. We determine quote sources, pool priority, slippage threshold, and behavior on price divergence. The route switches itself, without manual intervention at the trade moment.
- Bot logic assembly. Dialogue, trade confirmation, statuses, notifications, retries on network error. Each scenario is built so that the user at any moment sees where the funds are.
- Test environment. We run routes on the test network, then within restricted limits. We look not only at successful trades, but also failures, timeouts, repeated signatures.
- Handover to operation. We provide configurations, the scheme, monitoring instructions, and the rollback procedure. Separately we show how to change routes and limits without code edits.
Implementation artifacts: configurations, schemes, regulations
The handover package is not a folder with a presentation, but a working set in your repository: with change history, edit rights, and the ability to bring up the environment from scratch without our help. Each artifact covers its own layer — settings, routes, access, operation.
- Bot configuration. A settings file with a list of supported networks and tokens, operation size limits, slippage thresholds, and confirmation waiting timeouts — changed by editing values, without rebuilding the image.
- Route scheme. A diagram of the order path from a command in chat to transaction signature: which liquidity sources are queried, in what order, where the reserve route turns on if the primary fails.
- Key access policy. Where signing keys are stored, who receives them and by what procedure, how operator and administrator roles are separated, how rotation and access revocation are configured.
- Deployment scheme. Separation of test and production environments, a list of environment variables, rollback points to the previous build, and the procedure for returning to it.
- Maintenance regulations. A checklist of regular checks: native token balance for fees, order queue depth, node lag behind the network, review of rejected transactions.
- Logging and alerts. Which events are written, with what detail, which thresholds raise a notification to the on-call.
- Acceptance scenarios. A set of checks with expected result: successful swap, insufficient liquidity, confirmation timeout, repeated sending.
The kit is handed over with edit rights and without vendor lock-in: an engineer on your team deploys the bot according to these documents and then maintains it independently.
Case: how the share of successful swaps grew
The bot initially went for quotes to a single liquidity source. On thin pairs, depth was insufficient, and the swap dropped off after user confirmation, while the same “failed to execute swap” appeared in chat.
Each such case engineers reviewed manually: compared transaction hashes, pool state, and token allowance for spending.
First, price retrieval was moved to the 1inch aggregator — it assembles the route through several pools itself and splits a large volume into parts.
Before sending, the bot re-requests the quote and recalculates the minimum amount to receive, while balance and token allowance are checked in advance, before signature — the user sees the reason, not an abstract error.
Response was addressed separately: heavy network requests were moved to background tasks, so the bot reacts to a command immediately, not after receiving a price. Result across three metrics:
| Metric | Before | After |
|---|---|---|
| Share of successful swaps | 78% | 97% |
| Bot response time | 9 s | 2 s |
| Manual reviews per day | 40+ | single cases |
To keep the result from rolling back, alerts were set on the failure share, every route step is written to the log, and scenarios with insufficient liquidity are covered by automated tests. Support switched from resolving stuck transactions to product questions.
How does a direct swap differ from routing through an aggregator?
A direct swap is one trade with one liquidity pool: the bot sends a transaction, and the contract exchanges token A for token B at the current reserve ratio.
An aggregator works differently: first it builds a route, splitting the amount between several pools and venues, sometimes as a chain A → B → C, and only then assembles one transaction from it.
The difference is primarily visible in the execution price. A direct swap gives the ratio lying in the pool, and on a large amount it sags proportionally to the share you take from the reserve.
An aggregator sums liquidity from several sources, so the final price on medium and large volume is usually better — but the aggregator’s own fee and the fees of each pool in the route are added to it.
Swap speed and resilience are structured differently. A direct swap is predictable: one call, clear network fee spend, minimum places where the trade can fail.
A route through an aggregator is longer, and the more hops it has, the higher the chance that by the time it is included in a block some pools have already changed and the transaction fails due to exceeded slippage — especially on thin liquidity of an illiquid token.
Therefore, in the bot we do not fix one method forever, but set a rule for a specific flow: up to a certain threshold and in a liquid pair, a direct swap goes; above the threshold or with shallow pool depth — routing through an aggregator with an allowed slippage limit and a re-check of the output amount.
If the route cannot be assembled, the logic falls back to a direct swap or reduces volume, and the user sees not an error, but an executed swap.
Key security, limits, and fault tolerance
The most frequent technical doubt about a swap bot is not the interface, but who can dispose of funds and what happens when an external service fails. Below — specifically on each point: key storage, swap limits, fault tolerance.
Where are keys stored and who has access to them?
Keys are not stored in the bot database and are not written to logs. Signing happens in an isolated signer service: the key is decrypted in memory only during transaction assembly and does not leave it.
Every access is recorded in the journal — you can see who requested a signature and for which trade. In a non-custodial scheme, the key remains with the owner; the bot only initiates the swap.
How do swap limits work and what happens when they are exceeded?
Limits are set at three levels: per trade, per user daily turnover, and a general safeguard across all operations. When exceeded, the operation is not silently rejected — it goes to manual confirmation with administrator notification. Thresholds are changed by configuration, without rebuild or service downtime.
What if an external service — pool, network node, exchange — is unavailable?
The trade is maintained by a state journal, so failure at any step does not lose data. The bot retries the request with increasing delay and before retry verifies state by operation identifier — a duplicate transaction will not be sent.
If the service is silent longer than the configured threshold, the trade is marked as requiring attention, funds remain in a known state, and the administrator receives a notification. After recovery, processing continues from the same point.
Let's discuss the task: send a description of the swap flow
To come back with an estimate for bot development, rather than general words, we need your view of the swap itself. Below — what usually closes most questions; if something is not there yet, it is enough to describe in words how it works now.
- Description of the swap flow: which network and token the user comes from, which they leave to, where the bot gets liquidity and along which route it conducts the trade.
- Quote rules: how the rate is calculated, what price tolerance we allow, what we show on sharp market movement.
- Failure behavior: what we do if the swap did not go through or went through partially — who sees the status, what the user receives, how we roll back the operation.
- Bot interface: set of commands and buttons, work in DM or group, whether roles and admin panel are needed.
- Wallet connection: which ones should be supported and whether the user signs the operation on their side.
- Protection requirements: operation limits, anti-fraud, action log, access separation.
- What already exists: current code, schemes, logs, test environment — you tell us what we reuse.
Describe the task in free form, attach the flow scheme if you have one — we will discuss it specifically. The bot development estimate is built from the swap flow description: the more accurately it is stated, the fewer clarifications and reworks at the start. We will come back with a work plan, stage composition, and timelines.







