TON DEX Bot Development for StonFi and DeDust

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
TON DEX Bot Development for StonFi and DeDust
Complex
~1-2 weeks
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    957
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

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:

  1. User wallet → Jetton Wallet: transfer with forward payload
  2. Jetton Wallet → Router: transfer_notification
  3. Router → Pool: swap
  4. Pool → Jetton Wallet (output token): internal_transfer
  5. 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&lt_={}&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.

DeFi Protocol Development

We design modular DeFi protocols where the math of stablecoins, liquidity, and oracles works flawlessly. Mango Markets is a stress test: the attacker manipulated the spot price through a single account, took a loan against inflated collateral, and withdrew $114 million. The oracle took the price from a single source without TWAP. Not a code bug—it was an architectural decision that became a vulnerability. Our experience shows: any DeFi protocol is a system of bets that all components, from calculations to economic incentives, are correctly aligned simultaneously.

We don't write code under the 'if it works, don't touch it' mindset. We model stress scenarios: cascading liquidations, depegs, flash loans. Only then do we build events that won't break the protocol.

Why are oracles a critical component of DeFi?

Most major DeFi hacks started with oracle manipulation. Let's break down the three layers we use in every project.

Spot price as oracle—not an option. Uniswap v2 spot price can be shifted by a flash loan in one transaction. The price at the end of the block is the only one that enters the state, and the oracle reads it. Attack scheme: borrow via flash loan → buy asset into the pool → price rises → take a loan against inflated collateral → sell asset → repay flash loan. One transaction.

TWAP as protection. Uniswap v3 observe() averages the price over a period (30 minutes). Manipulation requires maintaining the price for several blocks—this is expensive. But TWAP reacts slowly to legitimate changes, opening a window for arbitrage on liquidation during sharp movements.

Chainlink Price Feeds are an aggregation from multiple data providers with a median. Standard for lending. Problem: heartbeat 1–24 hours and deviation threshold 0.5%. If the price doesn't move, the feed may not update for a day. In volatile markets—lag.

Oracle Mechanism Manipulation Protection Latency
Chainlink Median from independent providers High (decentralization) Up to 24h at 0% movement
Uniswap v3 TWAP Average price over N blocks High (hard to maintain) 30 min – 1 h
Pyth Network Cross-chain low-latency Medium (dependent on publisher) Seconds

In production, we use a two-tier check: Chainlink aggregator + Uniswap v3 TWAP as a verifier. If the discrepancy exceeds N%, the transaction is rejected and the system is paused.

How to protect a DeFi protocol from flash loan attacks?

Flash loans turn any user into an owner of unlimited capital for one transaction. Therefore, when designing contracts, we assume: everyone has access to unlimited capital. This completely changes the threat model.

Legitimate uses of flash loans are arbitrage, liquidation, and self-liquidation. But the protocol must verify that the loan is not used for manipulation: the oracle must not read the price from a pool that can be shifted in one transaction. We add checks on block.timestamp and minimum liquidity depth.

Key Components of DeFi Architecture

Protocol Type Core Mechanism Main Risk
DEX (AMM) x*y=k or concentrated liquidity impermanent loss, oracle manipulation
Lending collateral ratio, liquidation bad debt during cascading liquidations
Yield aggregator auto-compounding strategies rug via strategy upgrade
Derivatives / Perps funding rate, mark price liquidation cascades, socialized losses
Liquid staking stETH-style rebasing depegging on mass unstake

AMM: From x*y=k to Concentrated Liquidity

Uniswap v2 uses x * y = k. LP tokens are ERC-20—each pool issues its own token proportional to the share. Problem: liquidity is spread across the entire curve, most of it unused.

Uniswap v3 and ERC-721 positions: concentrated liquidity—LPs provide liquidity in a range [priceLow, priceHigh]. Capital efficiency up to 4000x for stable pairs. But ERC-721 breaks vault strategies built for ERC-20. Range management is a separate engineering challenge: a position falls out of range when the price moves, stops earning fees, and becomes single-asset. Protocols like Arrakis Finance automatically rebalance. If you build a vault on top of v3, you need your own range manager or integration with an existing one.

Slippage in v3 is calculated via sqrtPriceX96—96-bit fixed-point math. Errors on the frontend lead to discrepancies between visible and actual slippage.

Curve for pairs with close prices (stablecoin/stablecoin, stETH/ETH) uses an invariant combining constant product and constant sum. Lower slippage within the peg range. Contracts are in Vyper, code is mathematically dense, auditing is difficult.

Lending Protocols: Collateral, Liquidation, Bad Debt

LTV defines the maximum loan against collateral. Liquidation threshold is the level for liquidation. The difference is the buffer for the liquidator. Typical example: LTV 75%, liquidation threshold 80%, bonus 5%. If the price drops 20%+, the position is open for liquidation.

Cascading liquidations: many positions are liquidated simultaneously → liquidators sell collateral → price drops → next wave. LUNA/UST 2022 is a classic cascade.

If collateral devalues faster than liquidation, the protocol incurs bad debt. Aave uses a Safety Module (staked AAVE), Compound uses reserves. Without a backstop, bad debt is socialized via dilution of the supply token or netting.

Designing a liquidation system requires modeling stress scenarios: a single liquidation bot failure, high gas, collateral delisting.

Yield Farming and Incentive Mechanics

Liquidity mining distributes governance tokens to LP providers. Problem: mercenary capital—farmers come, sell tokens, leave. TVL is illusory.

Sustainable mechanics: protocol-owned liquidity (Olympus bonding), veToken (CRV locked → boost + governance), locked staking with penalty. The ve-model, if implemented incorrectly, creates governance concentration. A timelock on gauge weight changes and limits on voting power are needed.

What Our DeFi Protocol Development Includes

  • Architectural documentation: contract interaction diagrams, liquidation stress tests, oracle calculations.
  • Implementation in Solidity 0.8.x with OpenZeppelin 5.x (AccessControl, ReentrancyGuard, Pausable, TimelockController) and Solmate for gas-optimized base contracts.
  • Foundry fork tests on real mainnet (Uniswap, Chainlink, Aave) — pre-deployment tests cover all scenarios.
  • Audit: at least two independent auditors for TVL over $1M. Code4rena or Sherlock for bug bounty.
  • Deployment with Gnosis Safe 3/5 multisig + timelock 48–72 hours.
  • Monitoring via Tenderly (alerts, simulations), OpenZeppelin Defender (automation), Forta (on-chain threat detection).
  • Post-launch support: updates, patches, upgrades via proxy.

Our Expertise and Experience

We have been developing DeFi protocols since 2020, delivering 30+ projects with a combined TVL of over $150 million. Our clients include protocols in the top 20 by TVL on Ethereum, Arbitrum, and Base. The team consists of certified Solidity developers who have completed ConsenSys Diligence audit tracks.

DeFi basic principles that we apply in practice.

Timelines

  • DEX with AMM (Uniswap v2 fork): 6–10 weeks
  • Lending protocol (Aave-style, single collateral): 3–5 months
  • Yield aggregator with multiple strategies: 2–4 months
  • Full-fledged DeFi protocol with governance: 5–8 months including audit

Cost is calculated individually—contact us for a project estimate.

Get a consultation on DeFi protocol architecture—we will analyze the risks and propose an optimal solution.