Developing a Split-Routing System for Price Optimization

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
Developing a Split-Routing System for Price Optimization
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
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • 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

Note: When executing a large order through a single DEX, price slippage is guaranteed to be 3–8% — even on Uniswap v3 with concentrated liquidity. On illiquid pairs, price impact eats even more. We develop split-routing systems — not a marketing gimmick, but a mathematically precise order splitting among multiple liquidity sources. Split-routing takes into account the liquidity curves of each pool and finds the optimal distribution, minimizing the total price shift. According to Uniswap v3 Whitepaper, concentrated liquidity allows increased depth in a narrow range, but a large order still causes slippage. Our approach solves this by distributing the flow among Uniswap, Curve, Balancer, and other protocols. Contact us for a preliminary liquidity analysis — we will evaluate your project and offer a turnkey architecture.

Why naive splitting doesn't work

An intuitive approach — a 50/50 split between Uniswap and Curve — gives a suboptimal result. The optimal distribution is nonlinear and depends on the current state of pools, liquidity depth in specific ticks (for Uniswap v3), and the slope of the bonding curve (for Curve StableSwap). The problem is compounded by the fact that pool states change between route computation and transaction execution.

How MEV bots attack split-routing

Split-routing systems are attacked on two levels. First, the classic sandwich attack: an MEV bot sees a large swap in the mempool, places a buy before it and a sell after, using Flashbots bundles or a private mempool. The second level is subtler: the route is computed off-chain based on pool states at block N, but executed at block N+2. Over two blocks, liquidity in the active Uniswap v3 tick may have shifted, making the optimal route suboptimal.

In practice, this means the routing algorithm must incorporate a tolerance for state changes and recalculate if the actual output deviates from expected. 1inch implements this via partial fills with minReturn; we implement a similar mechanism in our on-chain executor.

The problem of atomicity in multi-step routes

Splitting across multiple transactions is not splitting — it's sequential swaps. Atomic execution requires an aggregator contract that performs all route parts in a single call via multicall or custom routing logic. If an intermediate step reverts, the entire bundle rolls back. This requires careful gas handling: each additional hop costs 30–80k gas depending on the protocol.

What is split-routing and why it's needed

Split-routing is not just order fragmentation, but mathematically optimal distribution across pools. It reduces price impact by 3-5x compared to a direct swap on large orders. The savings on a trade often exceed the additional gas costs.

How we build split-routing

Route optimization algorithm

The core is an off-chain optimizer that solves the problem of minimizing total price impact. For each DEX, we obtain a "volume → execution price" curve:

  • Uniswap v2/v3, PancakeSwap: via quoter contract or simulation via eth_call with a forked state
  • Curve: analytical StableSwap/Cryptoswap formula
  • Balancer: WeightedPool or StablePool formula via querySwap
  • DODO: PMM (Proactive Market Maker) — nonlinear curve with oracle parameters

The optimizer splits the order into N parts and iterates over the distribution, minimizing total output. We use gradient descent with numerical differentiation — analytical derivatives for Uniswap v3 with ticks are nontrivial due to discreteness. The algorithm converges in 50–200 iterations, achieving <100ms on a typical server.

On-chain executor

The aggregator contract receives an encoded route from the off-chain optimizer: an array of (address pool, bytes calldata swapData, uint256 portion). The executor iterates over the array, calling each pool with the calculated share of the input token. It verifies actualOutput >= minOutput via require, otherwise reverts.

struct SwapStep {
    address pool;
    address tokenIn;
    address tokenOut;
    uint256 amountIn;
    bytes data; // ABI-encoded call to pool
}

For Uniswap v3, data contains encoded exactInputSingle with parameters. For Curve — exchange with i, j, dx. A unified interface via adapters for each protocol.

MEV protection

Integration with Flashbots Protect RPC as an option for large orders — the transaction goes directly to the builder, bypassing the public mempool. For EVM-compatible L2s (Arbitrum, Optimism), MEV risk is lower due to centralized sequencers, but MEV bots are already appearing on Base and zkSync.

Slippage tolerance is set dynamically: for high-volatility pairs (alts) — 0.5–1%, for stablecoins on Curve — 0.05–0.1%.

What's included

  • Documentation: architecture description, API specification, configuration parameters.
  • Source code: off-chain optimizer (TypeScript/Python) and smart contracts with tests.
  • Integration: deployment setup, front-end connection, team training.
  • Support: 2 weeks of post-launch monitoring and fixes.

Everything is delivered turnkey: you get a ready-made aggregator adapted to your tokens and chains. Contact us to evaluate your project and propose an architecture.

Process

  1. Liquidity analysis (3–5 days). Profile pools on target chains: liquidity depth, typical volumes, tick distribution for v3. Determine which DEXs to integrate.
  2. Optimizer development (1–2 weeks). Off-chain service in TypeScript/Python. Test on historical data via The Graph — how much the optimal route outperforms a direct swap in output price.
  3. Smart contract executor (1 week). Develop and test with Foundry fork tests on mainnet. Check all edge cases: zero output, revert in intermediate pool, reentrancy via callback.
  4. Integration and deployment. API for front-end, parameter documentation, deploy to testnet → mainnet via Gnosis Safe multisig.

Estimated timelines

Basic system with 3–5 DEXs on one chain — 3–4 weeks. Multichain aggregator with cross-L2 routing via bridge — from 2 months. Timelines depend on the number of protocols integrated and real-time route update requirements.

Typical pitfalls in development

Common issues

Stale quotes in production. The algorithm computes the route based on block N state, but the transaction is mined at N+3. The pool has shifted. Solution: on-chain minimum output verification and fairly conservative slippage tolerance.

Gas for multicall exceeds savings from better price. On Ethereum mainnet with high gas (>50 gwei), splitting into 5 hops adds 200–400k gas. For small orders, this is more expensive than the price impact of a direct swap. The optimizer must account for gas cost as part of the objective function.

Curve pool imbalance after a large swap. After executing our portion of the route through Curve, the pool may become significantly imbalanced, and the next hop gets a worse price than the optimizer assumed. For sequential hops within a single transaction, this is critical — we need state simulation after each step.

Comparison: split-routing vs direct swap

Feature Direct swap on one DEX Split-routing (3+ DEX)
MEV risk High Reduced (partial private txs)
Gas (Ethereum) ~100k gas 300–500k gas
Available protocols One 3–5 or more

Note: As shown, split-routing wins in execution price by 2-4x, although it requires more gas. This is an ideal trade-off for large orders.

Uniswap v3 WhitepaperCurve Finance Documentation

Our engineers have over 5 years of experience in DeFi, with 30+ successful projects. We guarantee transparent code with a full suite of tests. Order a preliminary liquidity analysis — we will select the optimal set of DEXs for your tokens.

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.