STON.fi SDK Integration: Where the Swap Breaks and Why
Integrating the STON.fi SDK looks straightforward: read the pool reserve, assemble the message, send it to the blockchain. Everything breaks on timing — between reading the quote and executing the transaction, the pool state has time to change.
If the minimum output is not recalculated before sending, the transaction fails the check: no trade, the fee is charged, and the logs show swap errors in the bot that are easy to blame on the network or the node.
The second gap is the race for pool state. Multiple bot instances, parallel requests, and manual operations from the wallet read the same reserve but apply it to different points in time.
While one trade is being confirmed, the second is built from outdated data — and price slippage grows not because of market volatility but because the bot is operating from an outdated picture.
The third area is trade confirmation delay. Related messages are not executed instantly, and until the final status the bot does not know whether the trade went through, was rejected by the output limit, or is stuck in an intermediate state.
Without parsing these transitions, the bot either duplicates attempts or considers the trade closed ahead of time — and the reliability of a trading bot rests precisely on handling these states.
All three areas are connected: an error in quotes intensifies the race, and the race masquerades as slow confirmation. We break down how each of them is closed in code.
What Changes After Directly Connecting the Bot to the Exchange
While the bot accesses the exchange through an intermediary — an aggregator, an external service, or manual confirmation — every trade goes through extra steps. Each step adds latency and its own point of failure.
In a volatile market, the quote moves during that time, and the order is executed at a price that no one accounted for in the logic.
Direct connection to STON.fi removes intermediaries: the bot itself reads the pool state, forms and signs the transaction.
The trade chain is reduced to “read — calculate — send,” so execution speed stops depending on someone else’s service and becomes as predictable as the network itself.
Depth-of-book control comes from the same data source. Pool reserves are visible before the order is sent, so slippage is calculated in advance, and a large order is split into parts according to a given threshold.
The engineering result: the trade does not “eat” more from the bottom than the strategy rules allow.
Bot resilience under load rests on the request queue, retries on network failure, and idempotent sending — a retry does not create a second trade.
At the same time, a whole class of failures related to losing an intermediary’s response is removed: state is always taken from the chain, not from someone else’s cache. Next we break down how this is assembled into a working loop.
Connection Options: In-House Service, Aggregator, Proxy Layer
Choice of connection method determines who is responsible for the swap route and what happens when some pools become unavailable.
Integrating STON.fi through a ready-made set of libraries is the obvious path, but not the only one: three schemes fit the task, and each moves complexity to its own place.
| Option | When it fits | Limitations |
|---|---|---|
| Direct work with contracts | You need full control over the swap route, your own retry rules, and a minimal number of intermediaries in the chain | You track exchange interface and pool state changes yourself: a change on the contract side breaks the bot before our response to it |
| Liquidity aggregator | Best price across multiple pools matters, and swap logic is not your competitive part | The route is chosen by someone else’s logic, part of the fee goes to the intermediary, and pool composition and routing rules change without warning |
| Proxy layer for requests | You need to shield the bot from direct network calls, smooth request frequency, and keep a quote buffer | Adds latency and another point of failure: while the proxy is unavailable, the bot loses connection to the exchange and runs on outdated data |
Limitations do not disappear when changing the option — they move to another layer.
That is why working configurations are almost always hybrid: direct work with contracts on critical operations, a proxy for reading and monitoring, an aggregator as a fallback route when a pool is thin.
How Implementation Goes: From Logic Audit to Launch
We start not with code, but with analyzing how the bot makes decisions. A trading logic audit for STON.fi SDK integration shows where price and volume calculation diverges from actual execution on the exchange, and sets the list of what we rewrite.
- Trading logic audit. We analyze entry and exit rules, volume calculation, network fee and slippage accounting. The output is a map of the bot’s decisions and a list of places that contradict the exchange’s real behavior.
- Exchange interaction scheme. We fix which requests are sent, which confirmations we wait for, what we do on partial execution and a rejected transaction. We agree on the scheme before code — edits at this step are the cheapest.
- Key storage. Keys do not end up in code, configs, or logs: we move signing into a separate process, restrict access by roles, and allow withdrawals only with manual confirmation.
- Configuration and assembly. Separate environments, request-rate limits, retries on failures, and a detailed trade log — incident analysis takes minutes, not hours.
- Trade verification. A run on real trades with a small volume: we compare expected price and volume with actual. We separately test connection loss and bot restart at the moment of an open position.
- Solution handover. We hand over access, documentation on the exchange scheme, logs, and instructions for typical failures — your team supports the bot independently.
After the sixth stage, you have a working integration, a described exchange scheme, and logs, not a set of edits without documentation.
What the Team Keeps: Configurations, Schemes, Regulations
An integration can be considered handed over only when the client can launch, modify, and repair it without us.
Therefore acceptance includes not just one working bot, but a package of artifacts for the specific task — STON.fi SDK integration with a trading bot: configurations, schemes, access policies, and regulations by which an on-duty engineer acts independently.
- Bot configuration. Parameters are moved out of code: pair list, trigger thresholds, trade volume limits, network node addresses, and backup quote sources. Values change without rebuilding, with correctness checks at startup.
- Integration schemes. Flow diagrams: the price retrieval path, the order of signing and sending a transaction, behavior when a liquidity pool fails, and retry.
- Access policies. Roles and permissions, separation of signing keys and read keys, volume limits, a list of allowed addresses, and a separate circuit for manually stopping the bot.
- Support regulations. What to monitor, which notifications are critical, how to update the configuration, where rollback points are, and how to return to the previous working state.
- Documentation. Description of environment variables, local launch instructions, deployment procedure, glossary, and an error code table with explanations.
- Set of checks. Failure scenarios: insufficient liquidity, outdated quote, connection loss to a node, repeated transaction sending.
- Secrets management. Where keys are stored, how they are rotated, who owns them, and what happens when the responsible person changes.
We hand everything over in the client’s repository with owner rights. Support can be left to us or handled in-house — the regulations are designed for an engineer who did not participate in development.
Case: Bot on the Exchange, How Failures and Trade Delays Were Eliminated
The client came with a trading bot on a decentralized exchange in the TON network. Signals worked, but execution let them down: the price the bot calculated from the last read pool state was already outdated by the time the order was sent.
Some trades were rejected due to slippage, and mismatched executions were analyzed manually from exports.
The analysis showed two causes. Requests to STON.fi went sequentially, each next one waited for the previous response, so the queue accumulated latency, and the pool state was read less often than it changed.
We rewrote the execution loop: instead of periodic polling — subscription to pool events, instead of single orders — a queue with a shared time to live, instead of manual reconciliation — automatic matching of the trade with actual execution and retry on price rejection.
Metrics Before and After
| Parameter | Before | After |
|---|---|---|
| Share of unsuccessful trades | every fifth | a few percent |
| Bot response time | tens of seconds | 1–2 seconds |
| Quote-to-execution divergence | regular | within the specified deviation |
| Trade reconciliation | manual exports once a day | automatic, only exceptions analyzed |
Resilience rests not on one parameter but on the combination: a time boundary cuts off obviously outdated trades, retry triggers only when the price boundary is exceeded, and the reconciliation log shows where expectation and fact diverged. The loop transfers to other pairs and bots — thresholds change, the logic remains.
How Does Working Through the SDK Differ from Calls Through an Aggregator?
Direct work through the STON.fi SDK gives control over every trade: the bot itself reads pool state, calculates the route, sets the minimum output and transaction time to live. Slippage stops being a surprise, and behavior during a sharp price move becomes predictable.
The price for this is support on your side. Pool addresses change, for a non-standard pair the swap chain has to be built manually, and an error in calculation results in a rejected transaction and a lost network fee. The more pairs the bot serves, the more logic lives inside it.
An aggregator works differently: an external service itself searches pools, stitches a route from several swaps, and returns ready-made trade parameters.
Less code, wider pair coverage, but dependency appears — response latency, request-rate limits, someone else’s behavior under load, and no guarantee that the route will remain the best by execution time.
An aggregator is justified when liquidity is spread across many small pools or pairs change from trade to trade. If the bot works with two or three main pairs, direct contract calls are both faster and more resilient.
In practice, a hybrid scheme is chosen: key pairs via direct SDK calls, rare routes via an aggregator, but with reserve and limit checks on our side. The main flow does not depend on someone else’s service, and the long tail of pairs is covered without in-house routing.
Technical Doubts Worth Resolving Before Start
Some questions come up already at the estimation stage — before the first line of code. It is better to resolve them immediately so as not to build incorrect assumptions into the plan.
Below are four stories that we most often go through before starting work on STON.fi SDK integration.
How are the bot wallet’s keys stored?
The private key does not end up in the repository or configs — only in a secret store, from which the signing process reads it.
The bot works with a separate wallet and a balance limit: even in case of compromise, the volume of losses is limited rather than equal to the entire turnover.
Access to the secret is granted by roles, the key is rotated according to regulations, and the signing history remains in the log.
Can several exchanges be connected at the same time?
Yes, and usually that is worth doing. A routing layer is placed above the pools: before a trade, quotes are compared, and the order goes where price and depth are better taking into account the transfer fee.
If one venue is unavailable or gives slippage above the threshold, the logic switches to the second without bot downtime.
What happens when the exchange updates contracts?
Pool addresses and call formats change, and hardcoded values turn into failures. Therefore we keep addresses and parameters in a single registry rather than scattering them across code, and periodically verify it against public network data. Before rollout we run swap scenarios on a test loop — the update arrives without stopping the bot.
How to work around exchange request limits?
Limits are counted by request frequency, so quotes are cached for a short period, and identical requests are combined into a batch. The queue to the external service is rate-limited, and on failures there are retries with increasing delay.
Urgent operations (signing and sending a trade) go through a separate channel and do not compete with background polling.
Let’s Discuss the Task: What Is Needed for a Work Plan and Estimate
To return with an implementation plan and an estimate rather than general wording, we need a set of inputs about your bot and scenarios for working with STON.fi.
The more specific the inputs, the more accurate the scope of work and order of stages — from testnet checks to production launch. Below is what we usually request in the first conversation.
- Bot scenarios: market swaps, limit orders, adding and withdrawing liquidity, transfers — what is needed at the start and what goes to the second priority.
- Wallet access model: a non-custodial scheme with user-side signing or a service wallet; where keys are stored and who is responsible for their rotation.
- Pairs and tokens: asset list, priority pools, acceptable slippage, and minimum trade size.
- Limits and protection: maximum operation amount, number of requests per minute, stop rules on anomalies, and behavior when a network node is unavailable.
- Interface and notifications: where the bot lives, what user roles exist, which events go to chat and which are written only to the log.
- Environments and access: testnet, access to nodes, repository with the build, a stand for load testing.
- Reporting: which metrics matter — share of successful trades, transaction confirmation time, number of failures and reasons.
Based on this data, we fix the scope of work, break it into stages, and give timelines for each. Describe the task — we will return with an implementation plan and an estimate.







