How to Build an AMM in 2026: Lessons from Curve

Curve started as a StableSwap whitepaper, authored by Michael Egorov, a NuCypher founder with a physicist background. The innovative StableSwap formula unified the constant sum and constant product mechanics to reduce the slippage risk for pegged assets (stablecoins). The idea behind it was specific: existing AMMs were built for assets with considerable price volatility, but the growing share of on-chain volume was stablecoin-to-stablecoin. Since stablecoins are assets pegged to stable off-chain currencies at 1:1, the general-purpose curve usage for their traffic left enormous value untapped.
The new model worked out, with Curve growing to the deepest stablecoin venue in DeFi within 18 months of its launch in January 2020. While Curve is not the leading DEX today, its underlying logic and trajectory of development are sound working templates for DeFi projects. Those interested in how to build an AMM DEX should derive three vital learning lessons from the Curve project:
- Starting from the asset class, not the codebase.
- Separating the curve from the incentives.
- Early transfer to permissionless pool deployments.
This guide from 4IRE experts walks you through the nuances of AMM development as a design process and covers all practicalities, from math and architecture to tokenomics, security, and liquidity growth.
Curve at a Glance
So, why is Curve a suitable blueprint for present-day DEX builders? Here are a few facts that will help trace Curve’s setup and business approach.
- The Curve DEX launched in January 2020. The CRV token was issued in August 2020, and the veCRV lock model has become a working mechanism for turning emissions into a governance market.
- In 2021, the company issued CryptoSwap (Curve v2) to expand the StableSwap mechanism to volatile cryptocurrencies without manual range management (unlike Uniswap v3).
- crvUSD with a LLAMMA mechanism was launched in 2023, equipped with a stepwise transfer of staked assets into stablecoins within the stipulated price range instead of rigid one-point liquidation.
- Curve’s TVL as of September 2026 equals around $1.32 billion.
- The protocol works on 31 blockchains.
- Week 32 in 2026 witnessed a peak of weekly trading volume of $704 million, with $215,000 in fees and $1.44 billion TVL.
- Stablecoin price slippage on Curve is under 0.05%, with the constant gain difference becoming visible in deals exceeding $100,000.
- Saddle Finance completed Curve fork development and launched a StableSwap-based project with a 0.02% fee compared to Curve’s 0.04%, but its TVL has failed to surpass $20-50 million.
- The CRV token is trading slightly above $0.37 in September 2026, more than 90% below its all-time high at $12.16, proving that a successful protocol doesn’t guarantee the token’s success.
What Is Needed to Launch an AMM? Cost Breakdown
AMM production seems overwhelming at first, but understanding its underlying architecture makes the project more manageable. At a minimum, your AMM inventory should cover:
- Core pool contracts are your pricing engine, holding assets, tracking pool share ownership, and determining each trade’s costs. Here, you will need the invariant, swap logic, liquidity addition and removal functionality, and fee accounting.
- A factory for pool deployment. It can be permissionless or permissioned based on your project needs. Without it, your development team will face a huge scaling bottleneck of manual deployment of every new trading pair.
- A router enables asset swaps through intermediate pools without manual intervention. Most pairs have no direct pools, and routers help users find and execute multi-stage exchanges.
- Oracles supply manipulation-resistant price feeds. You will need internal price EMAs at minimum and external feeds if you rely on data from them.
- Incentive infrastructure is the machinery that decides which pools get fee rewards and routes revenue back to asset holders. Its inventory includes gauges, emission schedules, and fee distribution for projects running their own tokens.
- Governance inventory covers voting functionality, timelocks, and an emergency pause path to prevent attacks and asset leakage.
- Off-chain tools, like indexer/subgraph, API, front-end, analytics, monitoring, and an alert system, make pools discoverable and tradable in real time.
- Security is the backbone of a DeFi project’s vitality; you will need separate security layers for internal and external reviews, testing of fuzzing and invariants, an incident runbook, and a bug bounty for continuous improvements.
- Liquidity. Even with all elements discussed above present in your project, it won’t be a success if it can’t attract the actual money to pools.
With this inventory in your project development roadmap, you can count on $150,000 to $400,000 for engineering and allocate an additional $60,000 to $150,000 to security. These are all pre-launch expenditures, with liquidity acquisition often exceeding the development budget. A huge mistake is to plan the engineering stage carefully and improvise in security and liquidity aspects, which reveals backwards thinking in DeFi design.
Why the x·y=k Logic Doesn’t Work with Stablecoins
The constant product formula never runs out, giving some projects real market leverage (e.g., Uniswap’s ability to operate without oracles, market makers, and permissions). When one side of the pool is drained, the asset’s price on the other side of the pool rises infinitely. Unbalanced pools quote prices for any trade size with zero external input, but the cost of this viability is price slippage. Look at the math breakdown below to understand its implications.

In the context of stablecoin usage in pools, the x · y = k formula charges every trade a premium for the stablecoin’s insurance from depegging. The same problem is observed in correlated pairs of stETH/ETH, WBTC/cbBTC, EUR-stables, etc. – in other words, the assets that drift predictably.
StableSwap Invariant
StableSwap was developed as a technical solution that interpolates between two invariants. The constant sum (Σxᵢ = D in the formula below) ensures a perfect 1:1 pricing balance with zero slippage but is devoid of protection for the pool. In other words, a single trade can drain one side of the pool entirely. The constant product (Πxᵢ = (D/n)ⁿ) is unbounded but expensive near the peg.
Egorov combined these two mechanisms using an amplification coefficient A:
A · nⁿ · Σxᵢ + D = A · D · nⁿ + D^(n+1) / (nⁿ · Πxᵢ)
In this formula, n is the number of assets, xᵢ are the balances, and D is the invariant, equaling a perfectly balanced pool’s total value.
Special attention should be given to an elegant solution that Egorov termed the leverage term, χ = A · Πxᵢ / (D/n)ⁿ. When the pool is balanced, the constant product is at a maximum, and χ is large, making the curve almost flat. This way, trades execute at almost 1:1 under these conditions. When the pool gets skewed, the constant product collapses, and χ shrinks to zero, with the invariant degenerating into constant product. This mechanism is responsible for the pool’s automated self-protection, which activates only when it is needed.
Egorov didn’t develop any separate solution for D or the output amount, with both computed using Newton’s method on-chain. For this reason, Curve’s core pools are built on Vyper with hand-tuned loops, minimizing gas fees for swaps that may otherwise run high with iterative solvers.
This way, Egorov’s main innovation is the A coefficient. Higher A means a flatter curve and tighter pricing near the peg, reducing its cushioning effect under the conditions of depegging, letting LPs absorb the imbalance faster. Lower A creates higher trading costs on every swap but lets LPs exit the imbalanced pool with less financial loss. Two important A implementation nuances for developers are as follows:
- A should be ramped instead of instant activation. This arrangement lets the parameter move linearly across time without altering D and compromising risk-free arbitrage.
- Storage conventions should be chosen between direct storage and A · n^(n-1).
StableSwap vs CryptoSwap: Decision-Making Framework
With the StableSwap invariant explained in the previous section, it’s now time to look into its widespread alternative: CryptoSwap. StableSwap, which works well with two pegged assets in a pool and concentrates liquidity around a fixed point (1:1 exchange), doesn’t work in volatile asset-stablecoin pools (e.g., ETH/USDC).
CryptoSwap solved the problem by adding a self-re-pegging, internal price scale to StableSwap’s concentration principle. Under CryptoSwap, the pool maintains an exponential moving average (EMA) of its own trade prices, periodically shifting the liquidity concentration point towards it. This way, the pool rebalances its own price range, much like in Uniswap v3, with no outside risk management.
The main implication of repegging is that someone has to bear its cost after the algorithm’s occasional price shift. The move results in a loss against the invariant, which Curve handles by tracking the accumulated profit and permitting price adjustments only after the trading fee covers the cost in full. Without proper control of this condition, the pool may start leaking LPs’ profits for the sake of keeping the price stable.
CryptoSwap also introduces a dynamic fee, which is minimal at the balance point and rises as the pool skews. Following this logic, trades considerably outside the balance point are more expensive to complete, incentivizing traders to maintain balance.
Choosing between CryptoSwap and StableSwap is scenario-specific. Here are the main decision-making parameters:
- StableSwap suits projects working with assets with a hard peg or known, slowly drifting ratios. These include fiat stablecoins, wrapped BTC, and yield-bearing stables.
- CryptoSwap suits pools with floating ratios. Some examples are governance tokens against ETH, ETH-stablecoin pools, and multi-asset baskets.
Neither suits projects with low trading volumes because pools with less than $1,000,000 of monthly volume will deliver no profits, with audit costs and parameter risk coverage eating all the money. For these cases, a classical constant-product pool is a safe, transparent, and tried-and-tested option. Use the table below as a decision-making framework.
| Asset Pair Type | Suitable Formula | Protocol Example |
|---|---|---|
| Stablecoin-to-stablecoin | StableSwap | Curve |
| Wrapped-asset-to-base-asset | StableSwap | Curve, Saddle |
| Volatile pair | Constant Product | Uniswap v2 |
| Volatile with concentration | Concentrated Liquidity | Uniswap v3 |
| Volatile without manual range management | CryptoSwap | Curve v2 |
| Weighted pool | Weighted pool | Balancer |
Protocol Architecture
Curve’s on-chain architecture is worth copying almost entirely because it has accounted for almost every problem a DEX can face.

- Pools. These are self-contained contracts with two or more assets, implementing the invariant. They represent the core functionality of an AMM project, with all other system parts serving as wrappers around it.
- Metapools. These pair new assets against the LP token of an existing base pool. As a result, the new asset immediately has depth against three stablecoins instead of one, and the base pool is immune to dilution by an untested asset. In case the new asset depegs, the damage of this event is limited to the metapool only, without destabilizing the base pool.
- Factory. This mechanism deploys pools using a vetted implementation contract on a permissionless basis. It operates using cheap, modernized EIP-5202 blueprints. Its strategic value lies in reducing the development team’s gatekeeping burden. Anyone can list a new pair, and the market decides whether it’s livable.
- Router. Routers find suitable exchange pools in the market to help a user exchange any asset into any target asset, even if no direct A-to-B pool exists. It unifies several swaps into a single transaction for user convenience.
- Registry. Records are kept on-chain so that integrators don’t need to maintain an off-chain list of pools. Curve is not the best UI example for registry, as its records grew organically and are quite messy today. Improve that aspect to build for usability.
- Gauges, GaugeController, Minter, fee distributor. This is a vital incentive layer that manages the distribution of emissions to pools, admin fee allocation, and rewards to LPs.
AMM Tokenomics and Governance
At the heart of Curve’s tokenomics is the veCRV model, with a max supply of CRV around 3.03 billion. The majority of tokens are distributed among LPs via emissions, with an annual 16% decline rate. Yet, Curve has come to be known and widely cited not for the emission schedule but for its unique token lock model.
Vote-Escrow
CRV owners lock their tokens for a period from 1 week to 4 years, receiving veCRV in exchange. The formula looks as follows:
1 CRV locked for 4 years = 1 veCRV
1 CRV locked for 1 year = 0.25 veCRV, and so on.
The user’s veCRV balance declines over time, reaching zero by the moment the lock-up period ends. veCRV is non-transferable. These tokens give owners the following perks in the ecosystem:
- The right to vote on governance issues, including parameters, new pools, and treasury.
- Gauge weight votes: the power to direct CRV emissions to specific pools.
- A boost in the holder’s LP rewards up to 2.5x.
- A share of trading fees.
The logic behind this mechanism is straightforward: the longer LPs stake their CRV, the greater governance weight and financial gain they get. An interesting side effect of this model was the onset of “Curve Wars” in 2022, with Convex, Yearn, and StakeDAO combining their CRV holdings, locking them permanently, and trading their voting power to third-party protocols wanting to attract Curve’s liquidity.
How to Attract Liquidity? The Core Business Problem
Saddle Finance’s example given above shows that technology, no matter how flawless it is, doesn’t work without liquidity. Take this as fact: smart contracts are the easiest part. With so many open-source implementation use cases and a good dev team, no AMM fails because of technical flaws or an inability to implement Newton’s method.
Projects fail because nobody deposits money in them. That’s why you should take liquidity seriously from day one of your AMM project’s development. Liquidity is a two-sided dilemma:
- Traders don’t come to pools without depth.
- LPs don’t deposit money without volume because they see thin revenue from fees and high risks of impermanent loss.
Neither side moves first voluntarily, so your project has to incentivize one of them to be the first. Five realistic options to consider are:
- Token emissions. This method is fast and effective, but with dilutive effects. The worst scenario you can hit is mercenary capital, which happens if the lion’s share of your project’s TVL is emission-driven.
- Protocol-owned liquidity. Using this model, you can buy or bond your own float to prevent its departure from the project. It is slower and more capital-intensive to execute, but it keeps the money on the platform, making it work.
- Vote incentives. In many cases, this is the most correct answer to the liquidity question. Paying veCRV holders to point emissions at your pool is more cost-effective per dollar of liquidity than issuing your own token. Besides, this option comes with zero smart contract risk for your project.
- Market maker agreements. This model presupposes using loans plus options for specific assets, which is a widely recognized professional standard in DeFi. It is more predictable than other options, but the cost is also high.
- Real yield. The most durable of all, generous yield sharing is the greatest incentive for LPs to leave their assets on your platform.
The project’s TVL is a good number to monitor, but it’s not the only metric indicative of the project’s liquidity health. Divide your trading volume by TVL, and you will see how much of the capital is really working. The exercise will also show the revenue per dollar from your incentives. For comparison: a $20,000,000 pool that turns over every day is much better from the liquidity viewpoint than a $200,000,000 pool turning over only once a week.
The sobering note is that liquidity acquisition is expensive and unavoidable. Statistics show that DeFi projects spend more on liquidity acquisition in year one post-launch than they did on the DEX’s full engineering work and security audits combined. So, set aside a minimum of $300,000 for liquidity incentives to give your platform a smooth head start.
Security: Not a Place to Cut Corners
The second reason for most projects’ failure is inadequate attention to security issues. In this regard, Curve also offers a rich learning experience.
In July 2023, several Curve pools were drained, with the project and its customers losing around $70 million. The reentrancy lock failure in specific versions of the Vyper compiler made the leakage possible, even from a platform with thoroughly audited and correct code. The lesson for everyone to learn is that not only architecture but the toolchain can become attack objects and require thorough security controls.
Recurring attack vectors in AMMs like Curve include:
- Read-only reentrancy. This exploit is the costliest to the system and specific to the Curve architecture. If the pool’s price is read mid-update during liquidity removal with a native-token callback, the system may return a wrong value. Hackers repeatedly took advantage of this weakness to drain money from Curve integrators. This way, dForce lost $3.6 million in February 2023, and Conic Finance lost $3.3 million in July 2023.
- Price oracle manipulation. If the market for some assets is thin, spot prices can be subject to manipulation within a block. Mango Markets lost $110 million in October 2022 on MNGO price manipulation.
- Donation and first-depositor attacks. Direct transfers to pools that are not meant for the volume and types of such transactions can distort share pricing considerably, affecting other markets. Hundred Finance lost around $7.4 million in April 2023 after the attacker’s donation of 200 WBTC into a forgotten, empty market, causing rapid inflation in the exchange rate and rapid drainage of lending pools that followed.
- Precision and rounding. Small rounding errors in iterative solvers, differing token decimals and repeated division leak value, and attackers can compound that leakage to undermine the system’s invariant math. An attack of this type drained roughly $128 million from Balancer v2 across over six chains.
- Non-standard tokens. Invariant assumptions may also fail as a result of fee-on-transfer attacks, rebasing, and multi-entrypoint token attacks. Balancer lost $500,000 in June 2020 as a result of such an attack.
- Parameter and admin risk. Internal failures or interception of admin access can also cause severe problems. These include an unramped A change, a compromised multisig, or a missing timelock. A notorious case is the loss of $53 million by Radiant Capital in October 2024 because of malware infiltration of three developers’ machines.
By taking a look at this spectrum of security risks your active AMM faces every day, you should consider security broader than regular audits. An ideal safety net should also incorporate internal reviews in the development process, coupled with property-based fuzzing and invariant testing. Two audits from licensed firms specializing in AMM security are a must pre-launch. The project should also undergo formal verification of the core invariant math and rigorous adversarial testing on testnet.
The project’s launch marks the beginning of a new security cycle, with a guarded launch with deposit caps and permanent bug bounty measures. Live monitoring and an on-call incident runbook help projects keep security commitments on top of the priority lists.
With the cost of an AMM smart contract exploit currently standing at $1.9 million, you can’t skip security measures and audits as an avoidable expenditure. Adding reputational damage to the loss, you can easily see how a single drained pool can send your whole platform to oblivion. This is where we at 4IRE dedicate most of our time in DEX development projects, and this is what we suggest worrying about first of all.
AMM Development Timing and Budget: A Realistic View
Let’s be honest about the AMM smart contract development cost and consider three realistic scenarios with a cost breakdown.

- Deployment on the existing infrastructure. Use Curve’s permissionless factory and set parameters for your asset. Dedicate money and effort to liquidity acquisition. The time-to-market is roughly 2-6 weeks, with $15,000 to $60,000 as your development budget without incentives.
- Forking and modification. Use proven contracts and introduce real changes to them to make it customized: a new invariant term, a different fee model, custom hooks. Keep in mind that every modification invalidates the contract’s original audit results, so reserve time and budget for re-auditing the AMM before launch. The timeline is 3-5 months, with a realistic budget of $120,000 to $250,000. An audit will take an additional $40,000 to $90,000, depending on the scale of changes. Front-end development and the platform’s indexing, with a subsequent analysis of these efforts, may take $50,000 more.
- Brand-new AMM. In this scenario, you build a completely new invariant with novel architecture. This project typically takes 5-8 months, with the full breakdown of work stages presented below.
| Phase | Duration |
|---|---|
| Economic modeling and simulation | 4-6 weeks |
| Core contract development | 8-12 weeks |
| Peripheral contracts | 4-6 weeks |
| Internal review, fuzzing, invariant tests | 3-4 weeks |
| External audits | 6-10 weeks |
| Remediation and re-review | 2-4 weeks |
| Front-end, subgraph, analytics | Parallel, 8-12 weeks |
| Testnet and guarded launch | 3-4 weeks |
Again, don’t forget about the added cost of liquidity incentives that development teams rarely budget for at the project planning stage. Here, your ambition is the only criterion. Ongoing security expenditures are also vital, with bug bounties and monitoring being an integral part of the platform’s protection.
Conclusion
This guide explains the nuances of the exchange curve’s math using the example of Curve’s formulas. Don’t forget that the curve’s choice is an economic decision disguised as a technical one. To choose correctly, match it to your assets (stablecoins, volatile crypto, small-volume markets). Focus most of your attention on the security surface and dedicate enough creativity and effort to bring liquidity in the door. These are the core priorities businesses overlook and that we at 4IRE are ready to handle for you.
FAQ
It depends on the problem you’re trying to solve. If you need to bootstrap liquidity that can’t be attracted otherwise, a token is a solution. But running your own token comes with added risks, such as securities exposure, permanent sell pressure, and governance issues.
L2 is cheaper to deploy and trade on, but liquidity, integrations, and credibility are better on mainnet. The latter is more suitable for stablecoins, which thrive on depth rather than the cost-effectiveness of the chosen infrastructure.
Simulation pre-launch is vital. Take historical data for your assets, including the worst scenarios you faced in depegging, and model several LP outcomes for a range of A values based on your realistic trading volume.
Regulatory issues are jurisdiction-dependent. You should comply with MiCA in the EU and track the evolving regulatory stance in the US market, currently governed by the GENIUS Act. Take into account the growing interest of FATF in DeFi, which suggests a further increase in scrutiny.
Build Your AMM With 4IRE
Our blockchain engineers take a DEX from the curve to the launch: invariant design and simulation, core contracts, the factory, router and incentive layer, and the fuzzing, invariant testing and audit preparation that keep a live pool solvent. Schedule a free consultation.