The short version
Ongoing since 2018. It started as a question about bonding curves and now includes prediction-market venues.
Every AMM in the survey turned out to be one pattern: a pool state, a conservation function that fixes a scalar of that state, and three mechanisms. Providing and withdrawing liquidity move the invariant and leave the price alone. A swap leaves the invariant alone and moves the price. Pick the function and you have picked the slippage, the divergence loss and most of the attack surface, before anyone writes a line of Solidity.
- Framework. State space, mechanisms, conservation function, configuration space. The same objects for a bonding curve, a two-asset pool, a weighted pool and a multi-asset pool.
- Worked example. A constant-product pool specified end to end: four state layers, three mechanisms, each with the invariant it preserves.
- Many assets in one pool. The multidimensional case: one pool holding a portfolio, a reference unit whose supply is elastic, two separate conservation laws, and a role and mechanism taxonomy around them.
- The comparison. The survey: the major protocols side by side on conservation function, spot rate, slippage and divergence loss, plus a taxonomy of what goes wrong.
- A build. A constant-product venue for outcome tokens of a prediction market, to show two price processes on one set of balances.
Arc
How the work developed
Each step used the previous one as its vocabulary.
- 2018 to 2020. Configuration spaces.What does a bonding curve guarantee regardless of how anyone behaves? The answer is the reachable subset of the state space once an invariant is enforced on every transition. Published at IEEE ICBC 2020.
- 2020. Games as estimators.The same system read as a sensor: trades are noisy samples of private valuations and the spot price is the estimate. Published at MARBLE 2020.
- 2021 to 2023. Many assets in one pool.A design engagement for a pool holding a whole portfolio: research on mechanics and formulas, a generalised invariant, then a simulation model and its metrics. The client's own team built the contracts.
- 2021 to 2023. The survey.One state-space framework applied to Uniswap, Balancer, Curve and DODO, with a security and privacy taxonomy. Preprint from March 2021, published in ACM Computing Surveys in 2023, with 477 citations at the time of writing. The engagement's questions informed the paper.
- 2021 to 2024. Teaching.A summer-school course on engineering and simulating a multi-asset pool (August to October 2021), and AMM and market-design teaching at the Token Engineering Academy and WU Vienna. The constant-product specification below was written as the worked example.
- 2025 to now. AMMs for claims.A constant-product venue for prediction-market outcome tokens, and the open question of how a curve and a scoring rule price the same claim.
Framework
One model for every AMM
State, transitions, one invariant. Everything else is a choice made inside it.
The pool as a state machine
The state of a pool is a tuple
where is the reserve of token , its spot price, the invariant, and the fixed hyperparameters: fees, weights, amplification. A user action is a transition
Two rules hold for every design compared: the prices in a pool stay constant under pure liquidity provision and withdrawal, and the invariant stays constant under pure swaps. A protocol is a particular choice of conservation function
inside that one structure. That is what makes protocols comparable at all: they share the model and differ in one function and a few parameters.
Conservation and configuration space
A conservation function encodes a property as a scalar. Enforce it on every mechanism,
and every reachable state lies in a restricted set, the configuration space
Any property true throughout that set is true for every possible sequence of agent actions, with no assumption about what agents want. Choosing an invariant is therefore a dimensionality reduction: the reachable state space collapses onto a lower-dimensional manifold on which the designer's guarantee holds by construction.
The same idea as an estimator
In the companion paper the system is read as a sensor. Agents act on private valuations, the actions leave traces in the state, and the mechanism turns the traces into an estimate of something no single agent reports, most simply a price:
For a bonding curve with invariant the spot price is the estimator and each trade's realised price is a noisy sample. The curve guarantees that a realised price above the spot always calls for bonding and below it always for burning, so the estimate and its samples cannot disagree in sign. That is the basis for a bound on the estimation error and for treating a pool's price tracking as a control problem. The same reading applies to any invariant, though the error bound in the paper is stated for the bonding curve.
Worked example
A constant-product AMM, specified in full
The framework applied to the one AMM every reader already knows, so no argument about the mechanism gets in the way of the argument about the method.
Why specify something this well understood
A specification is not documentation of code that exists. It sits between a design intention and an implementation, and it either makes the system's properties checkable or it does not. The structure below is the one I use on systems that do not yet exist: decompose the state, map the mechanisms over it, derive each transition and state its invariants explicitly. It was written as the worked example for the Token Engineering Academy fundamentals programme.
Four state layers, kept separate on purpose
The separation is the load-bearing decision. Collapse these and you lose the ability to say which agent knows what.
Global state. The information required to maintain an active pool: quantities and of each asset, and the supply of tokens representing rights to pool liquidity, all over .
Stateful parameters and metrics. Parameters carry units, which is where most informal specifications go wrong: gas amount in , gas price in , and swap fee as a rate. Metrics are derived, not stored:
is the market price of asset 2 in the numeraire and the invariant the pool quantities always adhere to.
Local state, and the inside and outside distinction. What an address holds: , , . Local state also carries each agent's private price beliefs , tagged as inside or outside information. Without belief there is no way to say why anyone trades. A pool with no belief heterogeneity has no order flow, and a specification that cannot represent the reason for a transaction cannot be simulated against one.
Exogenous state. Not part of the system, but intrinsic to any dynamic model of it: assumed global prices in ETH and in USD. Naming these as exogenous is what stops a model from quietly assuming its own price process.
Add liquidity: preserves price
Takes and returns the that must accompany it so the price is unchanged:
The invariant moves, and that is the point:
Shares are issued on the linear proportion of the contribution, which keeps ownership claims consistent across deposits:
Resolving the global state:
Locally and , subject to and . Preconditions belong in the specification, not in the implementation's error handling.
Withdraw liquidity: also preserves price
Burning returns a pro-rata share of both reserves:
Price is held constant and falls. Add and withdraw are the two mechanisms that move the invariant without moving the price.
Swap: preserves the invariant, moves the price
The constant product is what is held fixed here:
Which fixes the output for a given input:
And the price resolves to a new value:
The whole design in one line. Liquidity operations hold price and move ; trades hold and move price. Slippage, divergence loss and capital efficiency all follow from that split.
Roles drive mechanisms
A state machine with no actors is not a model of anything. The specification closes by assigning mechanisms to roles: an operational trader swapping in and out, an arbitrage trader closing the gap between and the exogenous , and liquidity providers adding and withdrawing. Once roles are attached the specification is executable, because each role has a feasible action set over the state, which is exactly what a simulation is written against.
- Properties become checkable. "Price is preserved" is a claim you can test, not a sentence in a blog post.
- Preconditions surface early. Balance constraints appear in the specification rather than as a revert message.
- Simulation is a translation, not a redesign. The state decomposition maps directly onto a cadCAD model.
- Disagreement gets localised. Arguments become arguments about a named mechanism's invariant, a much shorter conversation.
Generalising
From two assets to one pool of many
The multidimensional case. The model stays the same, the state grows to a vector, and new questions appear that a pair never raises.
The design question
In a pair-based world every new asset needs a new pool, and liquidity is split across them. The design studied here puts a whole portfolio of assets into one pool. A reference asset always accounts for half of the value of the pool, and the supply of that reference asset is elastic: it is minted to match the value of incoming assets and burned when value leaves. Liquidity providers hold shares per asset, and a trade redistributes those shares, because it changes the risk each provider carries.
The aims were low slippage and high capital efficiency. The price is that listing, delisting and pricing a new asset become mechanisms the protocol has to specify, not events that happen to an unrelated pool.
State, and what can be done to it
The state splits into an agent level and a system level. For agent it is the vector of holdings and shares . The protocol can act as an agent and hold assets itself. The system level is the pool and the other subsystems taken together:
with the reserves, the supply of the reference asset minted into the pool, the price vector in that reference asset and the number of distinct assets in the pool right now. That last variable is new: the dimension of the state itself changes when an asset is added.
Agents choose from a small admissible action set: deposit, disburse, provide liquidity, withdraw liquidity, trade, and a set of stakes for governance, for security and for keeping the chain-level resource the pool depends on. The protocol has its own actions, triggered by the users': evaluate (set the price of a newly arriving asset and extend the state by one dimension), withdraw and save, withdraw and sell, fund, distribute, allocate, match, trade and distribute, and trade and rebalance.
- Evaluate. A new asset has no price in the pool. The protocol sets one, and the reserve vector and price vector each grow by one entry.
- Withdraw and save, or sell. When a provider withdraws an asset that governance wants to hold, it moves to the treasury and any residual is sold. When it is an asset the protocol has no interest in, the withdrawal simply completes as a sale.
- Match. When two trades offset each other, they settle between the two users, and the pool is not touched.
- Trade and rebalance. After a trade, shares are redistributed among providers to account for the shift in exposure to the portfolio.
Two conservation laws, not one
With dynamic supply a single invariant is not enough. The design uses two. The trade law holds the value of the portfolio fixed under every user trade. It is a weighted geometric mean with the reference asset at weight one half and the other assets sharing the other half, and with the reference side equal to the sum of the others:
The liquidity law says the value carried into the next state after any liquidity provision, withdrawal or new listing equals the value that was there before:
Together they carve a configuration space out of a state space whose dimension grows with the number of assets. The trade law is Balancer's weighted invariant with a particular weight structure. What is new is the second law and the elastic supply that lets it hold.
Mechanisms in sequence
The mechanisms form a taxonomy by the order in which they fire, in four steps:
- Sequence 0, user actions. The user submits a proposal: provide liquidity, trade, or take part in governance. Each carries its own parameters.
- Sequence 1, protocol selection. The protocol picks the mechanism from the proposal: add new, add existing or withdraw for liquidity; buy or sell for trades; and two special cases, evaluating a new asset and matching offsetting trades.
- Sequence 2, calculation. The protocol computes what the state change implies.
- Sequence 3, settlement. Mint or burn, distribute assets and shares, or rebalance share holdings among providers.
Alongside the pool there are subsystems that must stay balanced against it: assets staked for governance, assets staked for security, assets held to keep the chain-level resource the pool runs on, and a treasury. Too much value in the pool and too little staked for security gives a working exchange whose transactions cannot be secured. The size of the flows between these holdings is a parameter in their own right.
Roles
The role taxonomy has three classes and five levels. A role is described by type, level, description, action space, transitions to other roles and targets.
| Class | What the roles do |
|---|---|
| Governance roles | Control over parts of the system: keeping the technical functions running and the political and economic balances in place. |
| Internal roles | The main users of what the protocol offers: liquidity providers and traders. |
| Interface roles | Roles that connect the system to other protocols or move value in and out of it. |
| Level | Meaning |
|---|---|
| Level 0 | Entities that exist: an address, the basic identity. |
| Level 1 | Entities that hold assets. |
| Level 2 | Entities that transfer: they act on the protocol. |
| Level 3 | Entities that earn: paid for work done or services provided. |
| Level 4 | Entities that spend: they put value in to secure the system or to pay for incentives. |
Roles can mutate. An address that merely exists becomes a holder, then a trader, then a provider who earns, then a staker who spends. The map of roles, transitions, votes and value flows is the other half of the specification: it says who can do what to the state.
The research direction
The research proposal behind the generalisation had three aims: bring methods from Hamiltonian and Lagrangian mechanics into the design of the pool, derive a representation of an AMM that does not fix the invariant in advance, and define performance indicators that let designs be compared on risk, trade-offs and benefits. The motivation is that invariants are conserved quantities, the natural object of statistical physics and thermodynamics, so the analytical treatment of deviations from an invariant, and of fluctuating outside variables such as external prices, is available.
It was planned in three phases: assess existing documentation and unify concepts, introduce the general formalism, define stability criteria and metrics. The stated minimum outcome was numerical evidence that an analytical solution is infeasible, which would still justify tuning fees and weights numerically instead of by simulation alone.
In practice the focus moved with the work. It began with AMM mechanics and formulas, went on to generalising the invariant to higher dimensions, and then, once the simulation model took over, returned to the underlying metrics, benchmarked against loss-versus-rebalancing, FLARE and how others had treated them. The invariant generalisation was quick and mattered less once the model could answer questions directly.
Modelling and simulation
The specification was translated into a cadCAD model: partial state update blocks for the mechanisms, system parameters and states from the state decomposition, and scenario suites run against it. The outputs were the system metrics that matter to operators and liquidity providers, slippage and divergence loss first, and the comparison of mechanism variants and implementation architectures before committing to one. The production contracts were written by the client's own team.
Comparison
What the market built: the survey
The framework applied to the four most representative protocols of the time, with derivations in an appendix so they can be checked.
What the paper does
By 2021 AMM-based exchanges were routing tens of billions of dollars without an order book, each with its own whitepaper, its own notation and its own claims about slippage and risk, and no common frame to check them against each other. The survey does five things: it builds one state-space framework for every AMM design, derives and compares the conservation function, slippage and divergence loss of the major protocols, places AMM exchanges within the broader taxonomy of DeFi, builds a taxonomy of the security and privacy attacks they face, and reviews the related literature in both DeFi and conventional market microstructure to identify future research.
Conservation functions side by side
The simplest case is constant product:
Uniswap V3 concentrates liquidity: providers choose a price range, and the curve is the same product shifted by virtual reserves with range parameter :
Balancer generalises to a weighted geometric mean over two or more assets, with a spot rate set by weights and reserves:
Curve blends constant sum and constant product with an amplification parameter , which keeps assets with the same peg near 1:1 and still absorbs imbalance:
DODO breaks the pattern. Price is not derived only from reserves: it takes an external market price and lets arbitrage pull the pool back to it, a proactive market maker that gives up simplicity to largely remove divergence loss at equilibrium.
| Protocol | Invariant shape | Distinguishing move |
|---|---|---|
| Uniswap V2 | constant product | the baseline every other design is read against |
| Uniswap V3 | constant product, concentrated | providers choose a price range instead of the full curve |
| Balancer | weighted geometric mean | more than two assets, arbitrary weights |
| Curve | constant-sum and constant-product blend | low slippage for pegged assets |
| DODO | external-price anchored | arbitrage restores equilibrium, cutting divergence loss |
Two implicit costs every AMM imposes
Trading against a curve instead of an order book has two native costs, and the survey defines both without reference to any one protocol. The spot exchange rate is read off the invariant,
Slippage is the gap between that pre-trade rate and the realised rate of an actual trade:
It approaches zero for small trades and grows with trade size relative to pool depth, which is also what makes sandwich attacks profitable. Divergence loss, the paper's term in place of the more common but misleading "impermanent loss", is what a provider gives up by holding assets inside a pool instead of outside once prices move:
For constant-product pools this has a closed form in the price ratio :
The paper works out the equivalent for every other protocol in the comparison and shows that low slippage and low divergence loss trade off: an AMM that is cheap for traders is, structurally, more expensive for the providers who fund it.
A taxonomy of what goes wrong
The security and privacy half of the paper is organised by the layer an attack targets.
- Infrastructure layer. Timestamp and transaction-order manipulation by miners or validators, and generic threats such as denial of service and majority attacks that degrade a venue indirectly.
- Middleware layer. Smart-contract vulnerabilities, reentrancy chief among them.
- Application layer. Attacks specific to how AMMs price: oracle manipulation with flash loans, rug pulls, front-running, back-running, the sandwich that combines both, and vampire attacks that drain a protocol's liquidity by out-incentivising it.
On privacy it covers transaction inspection, identity tracing and behavioural inference on a fully transparent ledger, and the mitigations proposed: zero-knowledge proofs, multi-party computation and encrypted mempools. It also notes the real tension with the market supervision regulators expect.
Open problems the survey named
- Price manipulation. Once an attacker moves the price, they can in principle drain the pool. This needs joint work from computer science, economics and finance.
- Privacy at AMM speed. General privacy techniques exist but cost the real-time efficiency an AMM depends on, and privacy-preserving chains are often incompatible with AMM protocols.
- Speed and scalability. Confirmation delay ranges from seconds to hours and throughput is bounded by the underlying chain, an order of magnitude behind centralised venues even with layer-2 designs.
- Limited trading functionality. Compared with an order book, what a trader can express against a curve is narrow.
- System, protocol and governance design. The remaining avenues the paper lists.
Synthesis
The design space, as dimensions
What the framework, the engagement and the survey say a designer is actually choosing between.
| Dimension | Options seen | What it decides |
|---|---|---|
| Invariant shape | Product, weighted product, constant-sum blend, or anchored to an outside price. | Sets slippage for the trader and divergence loss for the liquidity provider. The two trade off. |
| Number of assets in one pool | Two assets, a handful with weights, or one pool holding every listed asset. | Decides how much liquidity is shared, and what a new listing or a delisting does to everyone already inside. |
| Where liquidity sits on the curve | Spread over the whole curve, or concentrated in a chosen price range. | Capital efficiency against the risk of being out of range and earning nothing. |
| Source of price | Reserves only, or reserves plus an external reference. | An outside anchor can remove divergence loss at equilibrium, and brings oracle risk with it. |
| Share accounting | One pool token for the pair, one share class per asset, or shares that are redistributed after trades. | Who owns what after a trade, and who carries the exposure the trade created. |
| Supply of the reference unit | Fixed, or elastic: minted when value enters, burned when it leaves. | Lets one side of a pool stay a constant fraction of pool value as assets come and go. |
| Fee and weight dynamics | Static parameters, or parameters that move with state. | The knob that can be tuned for a target behaviour once the invariant is fixed. |
| Matching | Every trade hits the pool, or offsetting trades are netted first. | Pool depth is spent only on the net flow. |
The conservation function fixes the first row, and almost every later argument is about the others. A specification is the document that says which option was taken on each row, and what the system guarantees as a result.
Built
An AMM for prediction-market claims
The smallest honest instance of the theory, and a way to see two pricing rules disagree.
Why a second venue
The ERC-20 prediction market mints portable Yes and No tokens. The DEX is the first place those tokens can go: a Uniswap-V2-style constant-product venue whose pools hold two tokens and price them against each other on a curve. It knows nothing about logarithmic scoring rules or event outcomes. Pools can hold the Yes and No tokens of the same event, and optionally the market's collateral token.
That makes the following visible: secondary trading, liquidity provision, and how prices and price finding differ between venues when the underlying mechanisms differ. It is an optional surface. You can buy Yes on the primary market, never open the DEX and still settle at resolution.
Architecture
- Factory. The registry and gate for creating pools. Creation needs a dedicated role, and swapping does not.
- Pair. One pool: holds the two reserves, enforces , and issues its own liquidity-provider token.
- Router. The entry point traders and providers approve. It routes swaps and liquidity changes into the right pair.
It runs on test networks next to the primary market, with the same token notation in both interfaces, at dex.tokenengineeringlabs.com. Full notes are in the ERC-20 CFMM DEX write-up.
Where this goes next
- Price discovery between a scoring-rule market and a curve on the same outcome tokens: when they agree, when they diverge, and who closes the gap.
- Metrics for comparing designs on one footing, in particular loss-versus-rebalancing next to divergence loss, so a design change can be judged before it ships.
- Invariants for claims with a bounded, terminal payoff, where the usual price process assumptions do not hold.
- Keeping the specification and the simulation as one artefact, so a change to the mechanism is a change to the model.
References
- Jiahua Xu, Krzysztof Paruch, Simon Cousaert, Yebo Feng. SoK: Decentralized Exchanges (DEX) with Automated Market Maker (AMM) Protocols, ACM Computing Surveys 55(11), 2023. arXiv:2103.12732.
- Michael Zargham, Jamsheed Shorish, Krzysztof Paruch. From Curved Bonding to Configuration Spaces, IEEE ICBC 2020. Write-up: on this site.
- Michael Zargham, Krzysztof Paruch, Jamsheed Shorish. Economic Games as Estimators, MARBLE 2020. Write-up: on this site.
- Uniswap V2 whitepaper: uniswap.org/whitepaper.pdf.
- Related write-ups: ERC-20 CFMM DEX, the survey in short.