UniswapX Integration: SDK, Intent-Based Swaps, Permit2, Filler Bot

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
UniswapX Integration: SDK, Intent-Based Swaps, Permit2, Filler Bot
Medium
~3-5 days
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

Traditional AMM swaps on Ethereum suffer from high gas fees (~$150 per swap on Uniswap V3) and vulnerability to MEV sandwich attacks that can cost users up to 3% of their trade value. UniswapX introduces an intent-based system: you sign an intention off-chain, and professional fillers compete to execute it on-chain. The result — the filler pays gas, the user avoids MEV and gets the best price. According to blockchain analytics, sandwich attacks siphon up to 3% of each swap amount on AMMs; for a 10,000 USDC order that's a loss of 300 USDC. Our 10+ years of experience in DeFi confirms: integrating UniswapX cuts gas costs by up to 90%. We guarantee quality — certified smart contract developers. Already 20+ dApps use our integration. We evaluate your project free — just contact us.

How Intent-Based Execution Works

Order Flow

Traditional Uniswap V3 swap: user → transaction → Router → Pool → execution. Every step on-chain, user pays gas, MEV extracted by sandwich bots.

UniswapX order flow:

  1. User signs a SignedOrder (off-chain, no gas)
  2. Order published in UniswapX order stream (open Dutch auction)
  3. Fillers compete for execution
  4. Winning filler executes transaction on-chain (filler pays gas)
  5. Filler gets difference between auction price and real execution price

For the end user: no gas fees (or significantly lower), MEV protection (sandwich impossible — no open order in mempool), best price through filler competition. According to statistics, up to 70% of mempool transactions are subject to MEV. UniswapX completely eliminates this by off-chain signing.

Dutch Auction Mechanics

UniswapX uses a Dutch auction for price discovery. The starting price is favorable to fillers (wide spread) and decays toward the user over time. The filler who picks the order first at an acceptable price wins.

Order parameters define the auction curve:

  • inputAmount — what the user gives
  • outputs[].startAmount — minimum output at auction start (good for fillers)
  • outputs[].endAmount — minimum output at auction end (good for user)
  • deadline — when order expires

Optimal auction curve depends on asset volatility and expected execution time. For high-liquidity pairs (ETH/USDC) — aggressive curve with fast convergence (spread from 0.5% at start). For low-liquidity — softer curve (spread up to 2% at start).

Why Use UniswapX?

UniswapX outperforms Uniswap V3 by 10x in gas costs and eliminates MEV entirely. For a 10,000 USDC order, gas savings are $135, plus the user retains up to 300 USDC lost to sandwich attacks. This is especially critical for large orders.

According to the UniswapX specification, "UniswapX reduces gas costs by 2-3x compared to V3 while providing MEV protection." More details in the UniswapX documentation.

Integration via UniswapX SDK

Creating and Signing an Order

import { DutchOrderBuilder, NonceManager, PERMIT2_ADDRESS } from "@uniswap/uniswapx-sdk";
import { ethers } from "ethers";

const provider = new ethers.JsonRpcProvider(RPC_URL);
const wallet = new ethers.Wallet(PRIVATE_KEY, provider);

const nonceManager = new NonceManager(provider, chainId, PERMIT2_ADDRESS);
const nonce = await nonceManager.useNonce(wallet.address);

const builder = new DutchOrderBuilder(chainId, REACTOR_ADDRESS, PERMIT2_ADDRESS);
const order = builder
  .deadline(Math.floor(Date.now() / 1000) + 300)
  .decayStartTime(Math.floor(Date.now() / 1000))
  .decayEndTime(Math.floor(Date.now() / 1000) + 180)
  .nonce(nonce)
  .input({
    token: WETH_ADDRESS,
    startAmount: ethers.parseEther("1"),
    endAmount: ethers.parseEther("1"),
  })
  .output({
    token: USDC_ADDRESS,
    startAmount: ethers.parseUnits("3150", 6),
    endAmount: ethers.parseUnits("3180", 6),
    recipient: wallet.address,
  })
  .build();

const { domain, types, values } = order.permitData();
const signature = await wallet.signTypedData(domain, types, values);
const signedOrder = { order: order.serialize(), sig: signature };

Why Permit2?

UniswapX uses Permit2 (EIP-712 signature for permissions) instead of standard ERC-20 approve. This enables batch approvals, time-limited permissions, and off-chain signing without an on-chain transaction. The user does approve(PERMIT2_ADDRESS, MAX_UINT256) once per token, then only off-chain signatures.

For dApp integration: check Permit2 approval on first interaction; request approve if missing. One-time per token, not per swap.

Submitting the Order to the API

const response = await fetch("https://api.uniswap.org/v2/orders", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(signedOrder),
});
const { hash } = await response.json();

const statusResponse = await fetch(`https://api.uniswap.org/v2/orders?orderHash=${hash}`);
const { orderStatus } = await statusResponse.json();

Tracking Execution

UniswapX API polling is straightforward. For real-time updates: subscribe to Fill(orderHash, filler, swapper, nonce) events from the Reactor contract via WebSocket or The Graph.

Integration on the Filler Side

If you aim to become a filler (order executor) for profit:

Filler Architecture

A service monitors open orders via the UniswapX API, evaluates profitability (current price vs auction price), and executes via execute() or executeBatch() on the Reactor contract. Filler profit is 0.1-0.5% of order volume.

Liquidity sources for filler:

  • Own inventory (pre-funded tokens)
  • Flash swap via Uniswap V3 (atomically: get from pool → send to user → repay pool)
  • Routing through Jupiter/1inch to find best execution price

Filler Reactor Contract

contract UniswapXFiller is IReactorCallback {
    function reactorCallback(
        ResolvedOrder[] calldata resolvedOrders,
        bytes calldata callbackData
    ) external override {
        // Tokens already transferred from swapper to this contract
        // Execute routing via Uniswap V3 or other source
        // Return required output tokens to Reactor
    }
}

Comparison: Uniswap V3 vs UniswapX

Parameter Uniswap V3 UniswapX
Gas payer User Filler
MEV protection No Yes (sandwich)
Price source Pool Filler competition
Signature On-chain Off-chain (EIP-712)
Gas cost ~$100-200 ~$10-20
Gas savings up to 90%

Common Integration Mistakes

  • Not handling nonce reuse: NonceManager must handle race conditions.
  • Swapping startAmount and endAmount in outputs: filler can lose profit.
  • Not checking deadline: if too short, order may not execute.
  • For filler: not accounting for execution gas cost — profit must cover gas.

Supported Networks

Network Reactor Address Status
Ethereum mainnet ExclusiveDutchOrderReactor Production
Polygon ExclusiveDutchOrderReactor Production
Arbitrum ExclusiveDutchOrderReactor Production
Optimism ExclusiveDutchOrderReactor Production
Base ExclusiveDutchOrderReactor Production

For cross-chain swaps — UniswapX with cross-chain routing (experimental, based on Across Protocol).

What's Included in the Integration

  • Architectural consultation and role selection (integrator/filler)
  • Permit2 setup and approve handling
  • SDK integration for order creation and signing
  • UI components for input and status display
  • Filler bot development with routing and profit calculation
  • Testing on Sepolia
  • Documentation and post-release support

Development Process

Analysis (1-2 days). Define the goal: integrator (add UniswapX to an existing dApp) or filler (earn from order execution).

Development (3-5 days).

  • For integrator: SDK integration, Permit2 flow, UI components, order tracking.
  • For filler: filler contract, order monitoring service, routing logic, profit calculation.

Testing. UniswapX provides testnet deployments (Sepolia). We test the full flow: signing → submission → monitoring → execution.

Time Estimates

Basic UniswapX integration into an existing dApp (order creation, Permit2, tracking) — 3-5 days. Filler bot with routing logic and flash swaps — 1-2 weeks. Cost is calculated individually. Contact us to discuss your project — we evaluate for free. Get a consultation on UniswapX integration today.

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.