Estimate a fill from depth
Price an order from bid/ask depth, including the bin it ends in
The depth in Retrieve pool bid and ask and Retrieve pool batch bid and ask lets you size an order yourself, without a request per amount. Each level is one bin, with the cumulative input and output to walk through its end; see Depth levels for the fields.
Find best route uses bid/ask depth to plan the trade and prices shortlisted paths with the swap engine when it has the underlying pool snapshots. Its quoted amounts can differ from an estimate built from the same depth table.
Walking the depth
Pick the side from the direction: bids to sell token0, asks to buy token0. Then walk its levels in order, turning the cumulative columns into per-bin amounts:
// Exact input: X is what you pay. Returns what you receive.
remaining = X; received = 0; crossedZero = false
prevIn = 0; prevOut = 0
for level in side:
if level.cumulativeInputVolume <= prevIn: continue // adds no input: skip
binIn = level.cumulativeInputVolume - prevIn
binOut = level.cumulativeVolume - prevOut
prevIn = level.cumulativeInputVolume; prevOut = level.cumulativeVolume
if remaining < binIn: // the order ends in this bin
if binOut == 0 or crossedZero: return received
return received + fillInside(level.price, binIn, binOut, remaining)
received += binOut
remaining -= binIn
if remaining == 0: return received
if binOut == 0: crossedZero = true
// out of levels: the order is larger than this side's depthfillInside prices the part of the bin the order ends in. The simplest choice is the bin's proportional share, floor(binOut × remaining / binIn). To account for the price curve, use Estimate a fill inside a bin.
For exact output (X is what you receive), swap the roles: pay each whole bin's binIn while remaining >= binOut, and price the bin the order ends in with payInside(level.price, binIn, binOut, remaining). Its proportional share is ceil(binIn × remaining / binOut). For an estimate that uses the price curve, see Estimate a fill inside a bin.
An increase in input still costs that input when output rounds to zero. For an exact-input stop after crossing such a bin, use the last completed level's output. For exact output, pay the full input of any crossed zero-output bins while output is still needed. If the target ends partway through a later bin, use that bin's cumulative input as the upper estimate.
Use BigInt throughout and multiply before dividing: the proportional products can exceed 2^128.
The average fill price is received / X (exact input) or X / paid (exact output), in raw units. The proportional share is an estimate. Before rounding, the start of a bin fills better than its average (see How the price moves inside a bin), so it can understate an order that ends inside a bin by up to half of that bin's remaining width. That matters only on pools with wide bins. A small order in a 6.25% bin fills about 3% better; in a 0.01% bin, less than 0.005% better.
Example: selling 5 WETH (X = 5000000000000000000) into the bids of the example response, a WETH/USDC pool (WETH has 18 decimals, USDC 6):
"bids": [
{ "binIdx": -1, "price": "49937913286041055521250", "cumulativeVolume": "7430706558", "cumulativeInputVolume": "2744786401520641763" },
{ "binIdx": -2, "price": "49932918995283375647711", "cumulativeVolume": "21731301391", "cumulativeInputVolume": "8027598362225637937" }
]- 1.The first bin takes all
2744786401520641763of its input and returns7430706558USDC. - 2.The remaining
2255213598479358237ends inside the second bin. That bin has5282811960704996174input and14300594833output, so its proportional share returnsfloor(14300594833 × 2255213598479358237 / 5282811960704996174) = 6104872967. - 3.The proportional estimate totals
13535579525(13,535.58 USDC), an average of 2,707.12 USDC per WETH. The price-curve estimate returns13535754492.
How the price moves inside a bin
Depth gives cumulative amounts at bin boundaries. Inside a bin, the pool moves its price in a straight line with the output the bin pays, from the bin's opening price to its closing price. So the bin's average price, binIn / binOut, sits exactly halfway between the two, and an order that stops partway through pays only the bin's earlier, better prices.
binIn and binOut are the bin's full size: what crossing all of it costs and pays out. The input r or output o still to fill when the order reaches the bin is how far into it the order gets.
For example, take an ask bin that pays out 100 for 100, with a closing price of 1.1. Its average price is 1.0, so it opens at 0.9. Buying the first 50 costs 47.5, the average of 0.9 and 1.0 times 50, not the proportional 50.
Depth carries only the closing price, so the calculation below first estimates the opening price from it, then prices the part of the bin the order takes along that line.
Estimate a fill inside a bin
For an estimate inside the bin where the order ends, use the calculation below as fillInside and payInside. Every bin before it is crossed whole. The price and amounts in the depth table are rounded. It also omits how much of the current bin was already traded, which the pool uses to calculate partial sells.
A partial-fill estimate can differ from the amount Find best route computes with the pool snapshot. Use slippage protection when submitting a trade.
It takes the bin's binIn, binOut and closing price from the walk, the input r still to fill (exact input) or the output o still to receive (exact output), and dec0/dec1, the token0Decimals/token1Decimals from /metadata. The products exceed 2^512, so use arbitrary-precision integers.
The whole calculation, as pseudo-code. Each step is explained below, with its formula.
// The bin's curvature: what all of binOut would cost at the closing price, minus binIn. asks: closeIn = floor(binOut × price × 10^dec1 / (2^64 × 10^dec0)) bids: closeIn = floor(binOut × 2^64 × 10^dec0 / (price × 10^dec1)) E = closeIn − binIn // E <= 0, E > binIn on asks, or E >= binIn on bids: use the proportional share. // The bin's lowest price, which sizes the margin for the pool's price rounding. low = asks: floor(price × (binIn − E) / (binIn + E)); bids: price margin(a) = ceil(2 × a / low) + 1 // What the pool charges for output o of this bin. askIn(o) = ceil(o × ((binIn − E) × binOut + E × o) / binOut²) bidIn(o) = ceil(o × (binIn − E) × ((binIn + E) × binOut − E × o) / (binOut × ((binIn + E) × binOut − 2 × E × o))) // Exact input, asks: solve (binIn − E)·x + E·x² = r with 64 fractional bits, root rounded up. S = 2^64 × (binIn − E) out = floor(2^64 × 2 × r × binOut / (S + ceilSqrt(S² + 2^128 × 4 × E × r))) // Exact input, bids: fill at the opening price, then correct once, as the pool does. g = min(floor(binOut × r / (binIn − E)), binOut) out = bidIn(g) <= r ? g : floor(g × r / bidIn(g)) fillInside(r) = clamp(out − margin(out), floor(binOut × r / binIn), binOut) // Exact output: askIn on asks, bidIn on bids. payInside(o) = min(in(o) + margin(in(o)), ceil(binIn × o / binOut))
Below, $$I$$ is binIn, $$O$$ is binOut, $$p$$ is price, and $$d\_0$$, $$d\_1$$ are dec0, dec1. Every $$\lfloor\cdot\rfloor$$ and $$\lceil\cdot\rceil$$ is integer division rounded down or up, and $$\lceil\sqrt{\cdot},\rceil$$ is the integer square root rounded up.
1. The bin's curvature. $$\mathrm{closeIn}$$ is what the whole bin would cost if every unit were charged the closing price, and $$E$$ is how much more that is than what the bin really costs:
$$ \mathrm{closeIn} = \begin{cases} \left\lfloor \dfrac{O \cdot p \cdot 10^{d\_1}}{2^{64} \cdot 10^{d\_0}} \right\rfloor & \text{asks} \\\[2ex] \left\lfloor \dfrac{O \cdot 2^{64} \cdot 10^{d\_0}}{p \cdot 10^{d\_1}} \right\rfloor & \text{bids} \end{cases} \qquad\qquad E = \mathrm{closeIn} - I $$
The 2^64 and decimals only convert the level's fixed-point price into raw token units. Per unit of output, the bin then costs $$(I + E)/O$$ at its close, $$I/O$$ on average and $$(I - E)/O$$ at its open: $$E$$ is how far the closing cost sits above the average, and the opening cost sits the same distance below it. When $$E = 0$$ the price is flat and the proportional share is exact. In the 100-for-100 bin above, $$\mathrm{closeIn} = 110$$ and $$E = 10$$.
If $$E \le 0$$, $$E > I$$ on asks, or $$E \ge I$$ on bids, the depth doesn't describe a straight-line bin, so use the proportional share instead.
2. The safety margin. The pool rounds each price inside a bin to a whole unit of its 64-bit fixed-point grid, so its result can differ from these formulas by a few units. The estimate leaves a margin for those rounding steps. A grid step matters most where the price is lowest, so the margin is sized at the bin's lowest price, $$p\_{\text{low}}$$: the opening price on asks, where the price rises through the bin, and the closing price on bids, where it falls:
$$ p\_{\text{low}} = \begin{cases} \left\lfloor \dfrac{p,(I - E)}{I + E} \right\rfloor & \text{asks} \\\[2ex] p & \text{bids} \end{cases} \qquad\qquad \mathrm{margin}(a) = \left\lceil \frac{2a}{p\_{\text{low}}} \right\rceil + 1 $$
$$a$$ is the result the margin applies to, the output for exact input or the input for exact output. The margin covers two grid steps of it, plus one unit for rounding the amount itself. At ordinary prices that's 2 units; it grows only on tokens priced at a tiny fraction of the other.
3. What the pool charges for output $$o$$ of this bin: $$o$$ times the average of the bin's opening cost and its cost at $$o$$, rounded up. On asks the cost per unit rises in a straight line. On bids the pool's price, output per input, falls in a straight line, so the cost per unit curves and the formula is longer:
$$ \mathrm{askIn}(o) = \left\lceil \frac{o,\big((I - E),O + E,o\big)}{O^2} \right\rceil $$
$$ \mathrm{bidIn}(o) = \left\lceil \frac{o,(I - E),\big((I + E),O - E,o\big)}{O,\big((I + E),O - 2E,o\big)} \right\rceil $$
Both are 0 at $$o = 0$$, $$I$$ for the whole bin and the proportional share when $$E = 0$$.
4. Exact input. Here the order fixes what you pay and the formula finds what you receive, which runs step 3 backwards. On asks, solve $$(I - E),x + E,x^2 = r$$ with 64 fractional bits, rounding the root up:
$$ S = 2^{64},(I - E) \qquad\qquad \mathrm{out} = \left\lfloor \frac{2^{65}, r, O}{S + \left\lceil \sqrt{S^2 + 2^{130}, E, r},\right\rceil} \right\rfloor $$
On bids, fill at the opening price, then correct once, as the pool does:
$$ g = \min!\left( \left\lfloor \frac{O, r}{I - E} \right\rfloor,\ O \right) \qquad\qquad \mathrm{out} = \begin{cases} g & \text{if } \mathrm{bidIn}(g) \le r \\\[1ex] \left\lfloor \dfrac{g, r}{\mathrm{bidIn}(g)} \right\rfloor & \text{otherwise} \end{cases} $$
Then take off the margin, and keep the result between the proportional share and the whole bin:
$$ \mathrm{fillInside}(r) = \min!\left( \max!\left( \mathrm{out} - \mathrm{margin}(\mathrm{out}),\ \left\lfloor \frac{O, r}{I} \right\rfloor \right),\ O \right) $$
5. Exact output. Here the order fixes what you receive, so step 3 prices it directly. With $$\mathrm{in} = \mathrm{askIn}$$ on asks and $$\mathrm{bidIn}$$ on bids, add the margin, and never ask more than the proportional share:
$$ \mathrm{payInside}(o) = \min!\left( \mathrm{in}(o) + \mathrm{margin}\big(\mathrm{in}(o)\big),\ \left\lceil \frac{I, o}{O} \right\rceil \right) $$
In the WETH example, the second bin gives closeIn = 5283076140833714739, so E = 264180128718565 and $$p\_{\text{low}}$$ is the level's price. Then g = 6105178272, and bidIn(g) = 2255261744665388318 is more than r, so out = floor(g × r / bidIn(g)) = 6105047936. The margin is 2, so the bin returns 6105047934 instead of 6104872967. In total you receive 13535754492 (13,535.75 USDC).
Before you execute
Depth is a snapshot for estimation, and the pool moves with every trade and price update. Never execute an amount estimated from depth with zero slippage. For an exact amount, quote with MetricOmmSwapQuoter before executing.
Last updated 29 days ago
Relatick