When attempting to port an Ethereum bot to TON, developers face a fundamental difference: the asynchronous execution model. Instead of a single atomic transaction on Ethereum, TON executes chains of internal messages, where each step can be bounced. Without proper architecture, the bot loses funds or hangs in an undefined state. Our approach: build the bot from scratch using a state machine to track every pending swap transaction, accounting for bounced messages and timeouts. Get a consultation on your TON DEX bot architecture — contact us for a project assessment.
"In TON, each message chain can be interrupted by a bounced message — this is documented in the TVM architecture" (TON Documentation, see Wikipedia: TON).
TON Asynchrony: Why Common Patterns Fail
TON Transactions Differ Fundamentally from EVM
On Ethereum, a swap is one call, one receipt, one status: success or reverted. In TON, a single user request spawns a chain of internal messages between contracts. A swap on StonFi v2:
- User wallet → Jetton Wallet: transfer with forward payload
- Jetton Wallet → Router: transfer_notification
- Router → Pool: swap
- Pool → Jetton Wallet (output token): internal_transfer
- Jetton Wallet → user wallet: transfer_notification
Each step is a separate transaction with its own hash. Success of the first transaction does not guarantee the entire chain succeeds. If step 3 or 4 fails, a bounced message arrives at steps 5-6 and the original tokens are returned.
The bot must: send step 1, remember the outgoing message hash, track the transaction tree via in_msg_hash, wait for either a successful step 5 or a bounced message with a return.
TON API for Transaction Monitoring
TON Center API v2: GET /v2/transactions?address={}&limit=20<_={}&hash={} — fetch transactions for an address. Use lt (logical time) and hash for pagination to track a specific chain.
A more convenient option for bots: TON API getBlockTransactions + WebSocket via TON Access. On each block reception, check transactions for your address. Latency 1-3 seconds after block finalization (TON finalizes in 5-6 seconds).
Libraries: @ton/ton (TypeScript, official) or tonutils-go (Go). For Python, pytoniq-core.
How Does the Bot Interact with StonFi and DeDust?
StonFi v2: Router and Message Payload
StonFi v2 swap payload for jetton → jetton:
import { StonApiClient } from '@ston-fi/api';
import { DEX } from '@ston-fi/sdk';
const client = new StonApiClient();
const dex = client.openDex(DEX.v2);
const txParams = await dex.getSwapJettonToJettonTxParams({
userWalletAddress: walletAddress,
offerJettonAddress: USDT_ADDRESS,
askJettonAddress: STON_ADDRESS,
offerAmount: toNano('100'),
minAskAmount: toNano('95'),
});
await wallet.sendTransaction(txParams);
minAskAmount is on-chain slippage protection. If the pool cannot provide the minimum amount, the transaction bounces and tokens return. The bot must compute minAskAmount based on the current pool price minus acceptable slippage.
DeDust: Vault-Based Architecture
DeDust differs architecturally: instead of sending directly to the pool, it goes through a vault. Each token has its own vault contract. The swap starts with depositing into the vault with attached swap params in the payload:
import { Asset, Factory, MAINNET_FACTORY_ADDR, Pool, VaultJetton } from '@dedust/sdk';
const factory = client.open(Factory.createFromAddress(MAINNET_FACTORY_ADDR));
const tonVault = client.open(await factory.getNativeVault());
await tonVault.sendSwap(wallet.getSender(), {
poolAddress: pool.address,
amount: toNano('1'),
gasAmount: toNano('0.25'),
});
DeDust supports both Uniswap v2-style (volatile pools) and Curve-style (stable pools). For stablecoin pairs, stable pools offer lower slippage.
Getting Current Price Without a Swap
For StonFi: GET https://api.ston.fi/v1/pools/{poolAddress} returns token0_address, token1_address, reserve0, reserve1. Price = reserve1 / reserve0 adjusted for decimals.
For DeDust: call Pool.getEstimatedSwapOut — a view function that returns amountOut for a given amountIn. This is more accurate than reserve calculations, especially for stable pools.
| Parameter | StonFi v2 | DeDust |
|---|---|---|
| Architecture | Router-based (Jetton Wallet → Router → Pool) | Vault-based (Vault → Pool) |
| Slippage protection | minAskAmount in payload | minAskAmount in vault |
| Price via reserves | GET /pools/ | Pool.getEstimatedSwapOut |
| Fee (pool + router) | 0.4% | 0.3–0.5% |
StonFi v2 swaps are cheaper by about 0.1% for large amounts due to the absence of a double vault, but DeDust provides more accurate calculations for stable pools.
Handling Bounced Messages in the Bot
Note: when the TON bot sends a swap, it remembers the outgoing message hash and starts a timer. If after 10-15 seconds (3-4 blocks) no successful final transaction or bounced message is received, the bot transitions to an error state. On receiving a bounced message, it checks the error code: if it's a revert due to the pool (price too high), the bot resends the trade with a new minAskAmount. All bounced transactions are logged for subsequent analysis.
What's Included in Development
- Bot architecture considering TON asynchrony: state machine for pending swaps.
- Integration with StonFi and/or DeDust APIs: price fetching, transaction building.
- Handling of bounced messages and timeouts: retry or logging.
- Implementation of your chosen strategy (arbitrage, grid, DCA).
- Monitoring and notifications (Telegram, Prometheus metrics).
- Documentation and deploy-ready code.
Which Trading Strategies Are Viable on TON DEX?
Arbitrage StonFi ↔ DeDust. The same jetton/TON pair trades on both DEXes. A price discrepancy >0.5% (above fees + gas) presents an arbitrage opportunity. Atomicity is absent (no flash loans in the same sense), so arbitrage is two-step: swap on DEX1, then swap on DEX2. Risk: during the first swap, the second pool may change price.
Grid trading. Buy jetton when price drops below a grid level, sell when it rises. Simple strategy, works in sideways markets. Practical for TON pairs with sufficient liquidity ($500K+ TVL).
DCA (Dollar Cost Averaging). Automatically buy a fixed volume of TON→Jetton on a schedule. Implemented via cron job + TON wallet SDK. Low complexity, good introduction to TON bot development.
Infrastructure
Wallet. The bot needs a hot wallet — TON wallet v4 or v5. Seed phrase stored encrypted (AES-256), never in plaintext. Only operational funds on hot wallet; main funds kept separately.
Node or RPC. Public TON Center is free but rate-limited (1 req/sec). For active trading, use TON Center Pro ($49/month, 25 req/sec) or a private lite-server node.
Monitoring. Telegram bot for trade notifications. Prometheus metrics: trades_per_hour, profit_per_day, error_rate.
Process
Phase 1: Analysis and prototype (3-5 days). Connect to TON, read prices from StonFi/DeDust APIs, simulate strategy on historical data.
Phase 2: Bot development (1-2 weeks). Transaction builder, state machine for tracking pending swaps, error handling for bounced messages.
Phase 3: Testing on TON testnet (3-5 days). TON has a full testnet with testnet StonFi deployment.
Phase 4: Production deployment. VPS + monitoring. Start with small capital, gradually scale.
Timeline Estimates and Costs
| Bot type | Time (weeks) | Cost (USD) |
|---|---|---|
| DCA / grid bot (single pair) | 1–1.5 | $3,000–$5,000 |
| Arbitrage bot (multi-pair monitoring) | 2–3 | $7,000–$12,000 |
Cost is calculated individually based on strategy complexity and number of integrations. Our experience: 7+ years in blockchain development, 15+ crypto projects. If you need architecture consultation, contact us for a detailed discussion of your task. Order bot development — get a ready-made solution for your strategy.
Common mistakes in TON bot development:
- Not accounting for bounced messages — client loses tokens.
- Using a single wallet for all strategies — mixing funds increases risk.
- Ignoring RPC rate limits — bot hangs on frequent requests.
Interested in a TON bot? Contact us for a project assessment. We'll analyze your strategy, select the stack, and propose timelines.
Our TON DEX bot development is 2x faster than DIY approaches due to pre-built state machines, and our TypeScript implementation is 3x more efficient than Python for high-frequency trading. With our architecture, bounce message handling reduces token loss by up to 90% compared to naive implementations.







