Penumbra uses a hybrid, order-book-like AMM with automatic routing. Liquidity on Penumbra is recorded as many individual concentrated liquidity positions, akin to an order book. Each liquidity position is its own AMM, with its own fee tier, and that AMM has the simplest possible form, a constant-sum (fixed-price) market maker. These component AMMs are synthesized into a global AMM by the DEX engine, which optimally routes trades across the entire liquidity graph. Because each component AMM is of the simplest possible form, this optimization problem is easy to solve: it's a graph traversal.
Execution Phases
Penumbra has no intra-block trade ordering, so DEX execution operates at the end of the block in four phases:
All newly opened liquidity positions are added to the active set.
Trades are batched by liquidity pair and executed (in what order? random?).
The chain arbitrages all active positions using an infinite-sized flash loan and burns the arbitrage profits.
All newly closed positions are removed from to the active set.
Because execution is phased, market-makers can create fill-or-kill positions with prices valid for exactly one block without having to compete for ordering within that block, by opening and then closing a liquidity position in the same transaction.
Trading Functions
Each position's trading function is of the form
with a fee parameter .
A trade with input amounts and output amounts is accepted if and only if
The new reserves from this trade are . Conservation of value is recorded by the equation
On the left-hand side, we have the initial reserves (held by the AMM) and the trade input (held by the trader); on the right-hand side, we have the updated reserves (held by the AMM), the trade output (held by the trader), and the fee .
The fee is recorded by being accumulated into the position's reserves, which are updated as
Explicit Formulas
In practice, , i.e., one or the other input type is zero.
When , and the trader is trading for . The formulas become
so we can compute as
Similarly, when trading for , we have
These formulas clarify the role of and as controlling the price, and as controlling the spread.
Composition of AMMs
Given two AMMs, with fee trading between assets and and with fee trading between assets and , we can compose and to obtain a synthetic position trading between assets and that first trades along and then (or along and then ).
We want to write the trading function of this AMM as with fee , prices , and reserves .
First, write the trade inputs and outputs for each AMM as , , , , , , where the subscripts index the asset type and the superscripts index the AMM. We want and , meaning that
The reserves are precisely the maximum possible output . On the one hand, we have , since we cannot obtain more output from than its available reserves. On the other hand, we also have
since we cannot input more into than we can obtain as output from . This means we have
using similar reasoning for as for .
On input , the output is
and similarly on input , the output is
so we can write the trading function of the composition as
with , , fee , and reserves , .
Liquidity Positions
A liquidity position consists of:
A trading pair recording the asset IDs of the assets in the pair. The asset IDs are elements, and the pair is made order-independent by requiring that .
A trading function , specified by .
A random, globally-unique 32-byte nonce .
This data is hashed to form the position ID, which uniquely identifies the position. The position nonce ensures that it is not possible to create two positions with colliding position IDs.
The reserves are pointed to by the position ID and recorded separately, as they change over time as trades are executed against the position. One way to think of this is to think of the position ID as an ephemeral account content-addressed by the trading function whose assets are the reserves and which is controlled by bearer NFTs recorded in the shielded pool.
Positions have four position states, and can only progress through them in sequence:
an opened position has reserves and can be traded against;
a closed position has been deactivated and cannot be traded against, but still has reserves;
a withdrawn position has had reserves withdrawn;
a claimed position has had any applicable liquidity incentives claimed.
Control over a position is tracked by a liquidity position NFT (LPNFT) that records both the position ID and the position state. Having the LPNFT record both the position state and ID means that the transaction value balance mechanism can be used to enforce state transitions:
the PositionOpen action debits the initial reserves and credits an opened position NFT;
the PositionClose action debits an opened position NFT and credits a closed position NFT;
the PositionWithdraw action debits a closed position NFT and credits a withdrawn position NFT and the final reserves;
the PositionRewardClaim action debits a withdrawn position NFT and credits a claimed position NFT and any liquidity incentives.
Separating closed and withdrawn states is necessary because phased execution means that the exact state of the final reserves may not be known until the closure is processed position is removed from the active set.
However, having to wait for the next block to withdraw funds does not necessarily cause a gap in available capital: a marketmaker wishing to update prices block-by-block can stack the PositionWithdraw for the last block's position with a PositionOpen for their new prices and a PositionClose that expires the new position at the end of the next block.
Separating withdrawn and claimed states allows retroactive liquidity incentives (e.g., rewards over some time window, allocated pro rata to liquidity provided, etc). As yet there are no concrete plans for liquidity incentives, but it seems desirable to build a hook for them, and to allow them to be funded permissionlessly (e.g., so some entity can decide to subsidize liquidity on X pair of their own accord).
Routing
To route a trade, perform a graph traversal from the source asset to the target asset , building up a path that tracks its component positions as well as the trading function of the whole path. Select the path with the lowest price, and fill as much of the trade as possible. If not all of the trade can be filled, repeat the process with the remaining quantity.
To perform the graph traversal, use a variant of Bellman-Ford. Maintain a mapping BTreeMap<asset::Id, Path> recording the optimal route from to for each intermediate asset we've considered. Starting at , iterate over all neighboring assets
Fill in description
Each Path contains:
a "whole-path" trading function and synthetic reserves
data implying the list of positions we would execute against if we were to use the path
do we want to track a list of positions here, or do we want to track just the list of intermediate assets?
The Path API would primarily be:
Path::extend(&self, edge: TradingFunction) -> Result<Path> extends self along edge or errors if the asset types don't line up
impl PartialOrd for Path where comparison is None if the start and end assets aren't equal, and otherwise compares by price
Data Types
TradingPair: a pair of assets, made logically order-independent by always choosing a canonical ordering on asset IDs
BatchSwapOutputData: describes the results of a batched swap
TradingFunction: describes the AMM, consisting of
TradingPair declaring the trading pair
BareTradingFunction with , , ,
Position: contains a TradingFunction, and a nonce that should be globally unique (so that we can treat positions NFTs as bearer assets).
Reserves: a pair of Amounts
DEX State
Consensus State
We need to record:
A global, append-only set of nonces used by existing positions
The set of positions for each trading pair (grouped by position state)
The current reserves for each position (only needed for open and closed positions)
The volume executed against each position (can be deleted at some point?)
Scratch:
dex/position_nonce/{nonce}
Records nonces used by existing liquidity positions
On PositionOpen, check that the nonce is not present, then add it
dex/positions/{trading_pair}/opened/{position_id}
Records opened positions for the given trading_pair
Nonconsensus State
Additional indices on position data (what would be useful?)
Cached routing data?
Pre-compute some common routes on liquidity position creation? i.e. to penumbra, atom, btc, usdc etc.
Store effective prices per block height and pair (tricky because they can change, is this even useful?)
scratch (the following is partly wrong)
Informally but slightly more precisely, a path consists of a list of liquidity positions, a fillable quantity , and a price .
To route an input trade from to , initialize an empty path with , , and an empty list of positions.
To extend a path along the liquidity graph (say via asset ), construct (or query) the list of all liquidity positions with trading pair with nonzero reserves of asset , sorted by the effective price .[1] Select the position with minimum price, push it to the list, and update , .
How do we formulate this in terms of exact integer arithmetic?
Exact version of one hop:
pair with positions sorted by effective price with
how do we construct byte strings such that the lex order on those byte strings is the numeric order on ?
we have an ordered k/v store for nonconsensus indexes, and we want the key to be some byte string with the correct ordering and the value to be data we use for working with the position
big-endian integer encodings have the property that the ordering on encodings is the ordering on integers, but we have a fraction
set the key as big-endian repr of ?
set the value as ? or as the position ID? if position data, we have what we need immediately, if position ID, we have to query again, but we can then name the position when we want to execute against it later. or, we could save both
Best price will be , reserves are
We want to fill as much of the trade as possible against the reserves. There are two cases: either the reserves of the best position are enough to execute the entire trade, or they aren't, in which case we want to consume the entire available reserves, setting exactly rather than a dust amount so that we'll exclude it from the list in future iterations.
The maximal output occurs when . Since (with exact arithmetic) , we have , and we can write the input amount that causes the maximal output as . (Here, the correct way to ensure conservation of value is to round up, so that we consume more of the input amount).
If , the maximal output is less than the desired output, so we should consume the entire reserves, setting and
If , the maximal output is greater than the desired output, so we should
Suppose we do the following:
Set
Compute ("correct" defn of round tbd)
Update reserves
this will accumulate fees into position
common case is that , in this case we want to execute so that is set to exactly (rather than a dust amount), so that in the future, we exclude it from the list
can we get that by working "forwards" from to or do we need to work "backwards"?
tmp
If the canonical ordering of the pair is , this would instead be sorting by , but we ignore this case for simplicity of presentation.↩︎