Your team deployed a constant product pool with x*y=k mechanics. Everything worked on testnet. On mainnet, three days after launch, a sandwich bot extracted $180k from the pool — entry price 12% above the real price, exit price 11% below. No slippage control at the contract level, only frontend validation. This is a typical story: developers copy AMM mechanics without understanding how Ethereum's MEV infrastructure operates. Contact us to avoid such losses — we specialize in pool protection.
Problems with AMM Contracts at Deployment
Impermanent Loss as an Architectural Decision, Not a Bug
IL is not a bug but a mathematical consequence of rebalancing. Protocols that fail to explain the real math to LP providers lose liquidity: people see 40% APY, withdraw after a month, and don't understand why they are in the red in USD terms. The contract's job is to provide accurate data on the position: current value, accumulated fees, estimated IL.
In Uniswap v3, this is complicated by concentrated liquidity: a position is active only within the range [tickLower, tickUpper]. When the price exits the range, the position stops earning fees and fully converts to one token. An LP provider without monitoring can hold a dead position for weeks.
Price Manipulation via Flash Loans in Single-Source Oracles
An AMM pool that itself serves as a price oracle is an attack vector. A flash loan, a single swap transaction — spot price in the pool shifts by 10x. If your lending protocol reads the price from this pool, it issues loans against manipulated collateral. This happened to Mango Markets (loss of $114M). Solution: TWAP via Uniswap v3 oracle — IUniswapV3Pool.observe() with a minimum observation window of 30 minutes. Or Chainlink as an external oracle with a circuit breaker: if spot and Chainlink diverge by more than 5%, the transaction reverts.
Reentrancy in Callback Mechanics
Uniswap v2/v3 uses a callback pattern: uniswapV2Call and uniswapV3SwapCallback. If your pool implements similar mechanics and does not put nonReentrant on the function that invokes the callback — classic vector. In practice, we encountered a pool contract with a swap function that updated reserve0 and reserve1 after calling _callback. Reentrancy allowed getting tokens twice on one input. ReentrancyGuard is needed on swap, addLiquidity, removeLiquidity — all three.
Why a TWAP Oracle Is Mandatory for a Pool
Without TWAP, the pool is vulnerable to flash loan attacks. By using a short observation window, we smooth out manipulations. In high-TVL projects, we add a fallback to Chainlink to increase reliability.
How to Reduce Impermanent Loss Risk for LPs
We embed real-time impermanent loss calculation in the contract and provide data via view functions. In concentrated pools, we add automatic position rebalancing through keeper bots to avoid prolonged stays outside the range. This reduces losses for LP providers.
How We Build Liquidity Pools
Architectural Decisions
For most tasks, there's no need to write an AMM from scratch. Uniswap v2/v3, Balancer, Curve protocols are battle-tested code with billions in TVL. The task is to choose the right mechanics for the tokenomics:
| Mechanics |
Suitable for |
Example |
| x*y=k (Uniswap v2) |
General case, two tokens |
Any ERC-20 pair |
| Concentrated liquidity (Uniswap v3) |
Stablecoins, correlated assets |
USDC/USDT, ETH/stETH |
| StableSwap (Curve) |
Stablecoins with minimal slippage |
3pool, FRAX |
| Weighted pools (Balancer) |
2-8 tokens with custom weights |
80/20 WETH/TOKEN |
| CPMM with custom fees |
Protocol pools with fee-sharing |
Custom DEX |
If the task is a custom pool for a specific protocol, we base it on Uniswap v4 Hooks (if the chain supports it) or Balancer v2 Vault architecture, where a shared vault holds tokens and pools only contain logic.
LP Tokens and Position Accounting
The ERC-20 standard for LP tokens in Uniswap v2 is the simplest case. Share in pool = lpBalance / lpTotalSupply. Problem: with many LP providers, each transfer of LP tokens changes relative shares without notifying other participants. For Uniswap v3-style positions, we use NFT (ERC-721) — each position is unique by ticks and size. This complicates integration but provides accurate accounting. Fees accumulate via feeGrowthInside0LastX128 — requires unchecked arithmetic with explicit comments.
MEV Protection at the Contract Level
- Use commit-reveal for large swaps: user publishes a hash, then after N blocks the actual transaction. Bots don't know parameters in advance.
- Use dynamic fees: fee increases during high volatility (detected via deviation from TWAP). Implemented via Uniswap v4 Hook or custom fee tier.
- Recommend private mempool (Flashbots Protect, MEV Blocker) — infrastructural solution, we warn the client before deployment.
What's Included in Liquidity Pool Development
| Stage |
Duration |
Result |
| Specification |
2-3 days |
Document with pool mechanics, tokenomics, fee structure, roles |
| Development |
1-6 weeks |
Contracts in Solidity 0.8.x with Foundry, fuzz tests |
| Fork testing |
3-5 days |
Tests on mainnet fork with real prices |
| Audit |
1-2 weeks |
Internal Slither + optional external |
| Deployment |
1-2 days |
Forge script, verification, multisig, timelock |
Additional: frontend integration (ethers.js, wagmi), position monitoring, client team training.
Our Experience Metrics
Total TVL of developed pools exceeds $100M. 5+ years in DeFi, 30+ smart contract projects. We work with certified auditors from Code4rena and Sherlock. In one project, contract optimization reduced gas costs by 40%, saving the client $50k per year.
Development Process
Specification (2-3 days). Define pool mechanics, LP token tokenomics, fee structure, roles (owner, fee collector, pause guardian). Draw state diagram: all pool state transitions, including emergency pause.
Development (1-2 weeks). Contracts in Solidity 0.8.x with Foundry. Fuzz tests on invariants: reserve0 * reserve1 >= k never violated, sum of all LP shares equals totalSupply, fees do not exceed swap volume.
Fork testing. Tests on mainnet/Arbitrum fork — real prices, real tokens, real MEV bots in mempool. Use vm.createFork in Foundry.
Internal audit + Slither. At least a week before deployment. For TVL >$500k, we recommend external audit (Code4rena, Sherlock, Spearbit).
Deployment. forge script with verification, Gnosis Safe multisig on owner functions, timelock on fee parameter changes (minimum 48 hours).
Timeline Estimates
Basic x*y=k pool with ERC-20 LP tokens — from 2 weeks with tests. Concentrated liquidity pool (Uniswap v3 style) — from 6 weeks. Custom mechanics with multiple tokens, external oracle integration, and fee-sharing — 2-3 months. Audit timeline not included.
Get a consultation on pool architecture selection — contact us for a free assessment of your project.
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.