The closed-form optimal split across fee-adjusted constant-product venues
How should an order be split across constant-product pools?
A derivation a reader can redo on paper: why splitting an order is a concave program, why venues enter in descending order of fee-adjusted spot price, the explicit closed form for the legs, and an honest separation of prior art from ours — the shipped solver does not use it.
BlazePhoenix Engineering · article updated 2026-08-13 · site dataset through 2026-11-30 · 12 min · written from the deployed bytecode
At a glance
Level
Advanced
Formal name
Spot-Order Admission
Reading time
12 min
Sections
10
Sources cited
2
Updated
2026-08-13
By Mitra (@Sigmacrit) — anonymous developer of the BlazePhoenix protocol. The code is the résumé.
Abstract in 15 languages · resumo · resumen · 摘要 · 要旨 · ملخص
English — Splitting an order across fee-adjusted constant-product venues is a strictly concave program, so there is exactly one optimum: venues enter the route in descending order of fee-adjusted spot price and the legs have an explicit closed form a reader can redo on paper. The convex framing is Angeris–Chitra–Evans–Boyd prior art; the specialisation is presented as a corollary — and stated plainly, the shipped solver allocates by depth in a single pass and does not use it.
Português — Dividir uma ordem por venues de produto constante ajustadas à fee é um programa estritamente côncavo, logo há exatamente um ótimo: as venues entram na rota por ordem decrescente de preço spot ajustado à fee e as pernas têm forma fechada explícita que um leitor pode refazer no papel. O enquadramento convexo é arte prévia de Angeris–Chitra–Evans–Boyd; a especialização é apresentada como corolário — e dito com clareza, o solver em produção aloca por profundidade numa única passagem e não a usa.
Español — Dividir una orden entre venues de producto constante ajustadas por comisión es un programa estrictamente cóncavo, así que hay exactamente un óptimo: las venues entran en la ruta en orden descendente de precio spot ajustado por comisión y los tramos tienen una forma cerrada explícita que un lector puede rehacer en papel. El marco convexo es arte previo de Angeris–Chitra–Evans–Boyd; la especialización se presenta como corolario — y dicho claramente, el solver desplegado asigna por profundidad en una sola pasada y no la usa.
Français — Diviser un ordre entre venues à produit constant ajustées des frais est un programme strictement concave, donc il existe exactement un optimum : les venues entrent dans la route par ordre décroissant de prix spot ajusté des frais et les segments ont une forme close explicite qu'un lecteur peut refaire sur papier. Le cadre convexe est l'art antérieur d'Angeris–Chitra–Evans–Boyd ; la spécialisation est présentée comme un corollaire — et dit sans détour, le solveur livré alloue par profondeur en une seule passe et ne l'utilise pas.
Deutsch — Eine Order über gebührenadjustierte Constant-Product-Venues zu splitten ist ein strikt konkaves Programm, also gibt es genau ein Optimum: Venues treten in absteigender Reihenfolge des gebührenadjustierten Spotpreises in die Route ein, und die Legs haben eine explizite geschlossene Form, die ein Leser auf Papier nachrechnen kann. Der konvexe Rahmen ist Prior Art von Angeris–Chitra–Evans–Boyd; die Spezialisierung wird als Korollar präsentiert — und klar gesagt: Der ausgelieferte Solver allokiert in einem Durchgang nach Tiefe und nutzt sie nicht.
Русский — Разделение ордера между площадками постоянного произведения с поправкой на комиссию — строго вогнутая программа, так что оптимум ровно один: площадки входят в маршрут по убыванию спот-цены с поправкой на комиссию, а плечи имеют явную замкнутую форму, которую читатель может пересчитать на бумаге. Выпуклая постановка — prior art Ангериса–Читры–Эванса–Бойда; специализация подана как следствие — и сказано прямо: поставленный солвер распределяет по глубине за один проход и её не использует.
Türkçe — Bir emri ücrete-göre-düzeltilmiş sabit-çarpım mekânlarına bölmek kesin içbükey bir programdır, yani tam olarak tek optimum vardır: mekânlar rotaya ücrete-göre-düzeltilmiş spot fiyatın azalan sırasıyla girer ve bacakların, okurun kâğıt üzerinde yineleyebileceği açık bir kapalı formu vardır. Dışbükey çerçeve Angeris–Chitra–Evans–Boyd'un önceki çalışmasıdır; özelleştirme bir sonuç olarak sunulur — ve açıkça söylenir: yayındaki çözücü tek geçişte derinliğe göre tahsis eder ve bunu kullanmaz.
العربية — تقسيم أمر بين منصات الجداء الثابت المعدّلة بالرسوم برنامجٌ مقعّر تماماً، فثمة أمثل واحد بالضبط: تدخل المنصات المسار بترتيب تنازلي للسعر الفوري المعدّل بالرسوم، وللسيقان صيغة مغلقة صريحة يستطيع القارئ إعادتها على الورق. الإطار المحدّب فنٌّ سابق لأنجيريس–تشيترا–إيفانز–بويد؛ والتخصيص مقدَّم كنتيجة — ويقال بوضوح: المحلّل المنشور يخصّص حسب العمق في مرور واحد ولا يستخدمها.
हिन्दी — फ़ीस-समायोजित स्थिर-गुणनफल venues में ऑर्डर बाँटना एक सख़्ती से अवतल प्रोग्राम है, इसलिए ठीक एक ही इष्टतम है: venues रूट में फ़ीस-समायोजित स्पॉट-मूल्य के घटते क्रम में प्रवेश करती हैं और लेगों का स्पष्ट बंद-रूप है जिसे पाठक काग़ज़ पर दोहरा सकता है। उत्तल ढाँचा Angeris–Chitra–Evans–Boyd की पूर्व-कला है; विशेषीकरण उपप्रमेय के रूप में प्रस्तुत है — और साफ़ कहा गया है कि शिप हुआ सॉल्वर एक ही पास में गहराई के अनुपात से आवंटित करता है और इसका उपयोग नहीं करता।
한국어 — 수수료 조정된 상수곱 장소들에 주문을 분할하는 문제는 순凹 계획이라 최적해가 정확히 하나입니다. 장소들은 수수료 조정 현물가의 내림차순으로 경로에 들어오고, 각 레그에는 독자가 종이 위에서 다시 풀 수 있는 명시적 닫힌 형식이 있습니다. 볼록 최적화 틀은 Angeris–Chitra–Evans–Boyd의 선행 연구이고, 이 특수화는 따름정리로 제시됩니다 — 그리고 분명히 말하자면, 배포된 솔버는 한 번의 패스로 깊이에 비례해 배분하며 이것을 사용하지 않습니다.
Bahasa Indonesia — Membagi pesanan ke venue produk-konstan yang disesuaikan fee adalah program cekung ketat, jadi ada tepat satu optimum: venue masuk ke rute dalam urutan menurun harga spot yang disesuaikan fee dan kaki-kakinya punya bentuk tertutup eksplisit yang bisa dikerjakan ulang pembaca di atas kertas. Kerangka cembungnya adalah karya terdahulu Angeris–Chitra–Evans–Boyd; spesialisasinya disajikan sebagai korolari — dan dikatakan terang-terangan, solver yang dirilis mengalokasikan menurut kedalaman dalam satu lintasan dan tidak memakainya.
বাংলা — ফি-সমন্বিত স্থির-গুণফল ভেনুতে অর্ডার ভাগ করা একটি কঠোরভাবে অবতল প্রোগ্রাম, তাই অপ্টিমাম ঠিক একটিই: ভেনুগুলো ফি-সমন্বিত স্পট দামের অবরোহী ক্রমে রুটে ঢোকে এবং লেগগুলোর একটি স্পষ্ট বদ্ধ রূপ আছে যা পাঠক কাগজে আবার করতে পারেন। উত্তল কাঠামোটি Angeris–Chitra–Evans–Boyd-এর পূর্বকর্ম; বিশেষায়নটি উপপাদ্যের ফল হিসেবে উপস্থাপিত — আর স্পষ্ট বলা: শিপ করা সলভার এক পাসে গভীরতা অনুযায়ী বরাদ্দ করে এবং এটি ব্যবহার করে না।
Filipino — Ang paghahati ng order sa mga fee-adjusted na constant-product na venue ay mahigpit na concave na programa, kaya iisa lang ang optimum: pumapasok ang mga venue sa ruta ayon sa pababang ayos ng fee-adjusted na spot price at ang mga leg ay may tahasang closed form na maaaring ulitin ng mambabasa sa papel. Ang convex na balangkas ay naunang gawa nina Angeris–Chitra–Evans–Boyd; ang espesyalisasyon ay inilalahad bilang corollary — at sinasabi nang tuwiran, ang naipadalang solver ay naglalaan ayon sa lalim sa iisang pasada at hindi ito ginagamit.
A router earns its existence in one inequality: splitting an order across several pools can return more than sending it to the best single pool. Everything else — discovery, filtering, floors — is machinery around that inequality. This article works out by how much, where the split point is, which pools deserve a leg at all, and when an extra leg stops paying for itself. It is arithmetic you can redo with a calculator, and the worked example below is included precisely so that you will.
One thing has to be said before the mathematics rather than after it: this derivation is not a description of the deployed solver. The shipped solver allocates in proportion to each venue's depth, in a single pass, and quotes the venues once their shares are already fixed. The closed form is what would replace that allocation, and it has not been wired in. Publishing the derivation while implying it is running would be the exact failure this protocol was built to avoid.
What is prior art here, and what is not
The framing belongs to other people. Angeris, Chitra, Evans and Boyd established that routing an order across constant-function market makers is a convex program, and that its optimality condition is the equalisation of marginal prices across the venues that receive flow; a dual-decomposition algorithm for the same problem appears in Diamandis, Angeris, Evans and Chitra. The water-filling reading of that condition is published language, not a metaphor we invented. The two sections that follow are therefore a restatement, included because a paper that hides its foundations is harder to check.
What we have not found attributed to anyone is the specialisation: an explicit closed form for the fee-adjusted constant-product case, and the observation that venues enter the route in descending order of fee-adjusted spot price. The published treatments reach for a convex solver or a one-dimensional search instead. We present it as a corollary and an implementation result — the arithmetic a contract can afford — and not as a theorem. If it turns out to be written down somewhere we did not look, nothing in the implementation changes and this paragraph is what gets corrected.
Setup, and the two derivatives that decide everything
Consider n constant-product pools trading the same pair. Pool i holds reserves x_i of the input token and y_i of the output token, and charges a fee written as the retention factor gamma_i = 1 - f_i, so a thirty-basis-point fee is gamma_i = 0.997. Sending delta_i into pool i returns the constant-product rule with the fee taken on the way in. We split a total order Delta into legs with sum delta_i = Delta and delta_i >= 0, and maximise total output.
Differentiating once and twice is the whole structural argument. The first derivative is strictly positive and the second strictly negative, so each leg is strictly increasing and strictly concave, and the objective is strictly concave on a convex feasible set. That is worth stating plainly because it is what makes the rest cheap: there is exactly one optimum, any stationary point is it, and no search over local maxima is required.
Attaching a multiplier lambda to the budget constraint, the Karush-Kuhn-Tucker conditions say: every pool that receives a leg must return the same amount for the next marginal unit, and every pool that receives nothing must be worse than that common rate even at its very first unit. If two used pools disagreed on the marginal return, moving one unit from the worse to the better would increase the total — so at the optimum they cannot disagree.
The identity at the end of the code block above is what turns that condition into something a contract can evaluate. The marginal return at zero input is exactly the fee-adjusted spot price gamma_i * y_i / x_i, which is read straight from reserves: no oracle, no simulation, no trial swap. Pools therefore enter the route in descending order of that quantity, and admission ends at the first pool whose implied leg would be non-positive. Sorting dominates, so the whole selection is O(n log n).
The equimarginal condition. Used venues equalise marginal return; unused venues are worse than that rate at their very first unit.
Closed form for the legs
Solving the stationarity condition for the leg, and then summing over the active set to impose the budget, determines the multiplier in closed form. Two sums over the active set, one division, and one square root per pool. No iteration and no binary search over the split point — which is the entire reason this is publishable as an implementation result rather than as a restatement.
For two pools the substitution can be carried out by hand, giving the form that is easiest to sanity-check. Two checks come free. If the pools are identical then A_1 = A_2 and x_1 = x_2, and the expression collapses to Delta/2 — half each, as it must. And if it returns a value outside [0, Delta], the constraint binds and the whole order goes to the single better pool, which is the same statement as the admission test.
Two pools on the same pair, both at a spot price of one, one four times deeper than the other, both charging thirty basis points, and an order of Delta = 100. The shallow pool holds 1,000 and 1,000; the deep pool holds 4,000 and 4,000; gamma = 0.997 for both.
Then sqrt(A_1) = 998.50 and sqrt(A_2) = 3993.99, and the two-pool formula gives delta_1* = 20.0 — the order splits in the ratio of the pools' depth, 1:4, which is the answer intuition would guess and a useful confirmation that the algebra is sound. Sending the whole order into the shallow pool returns 90.661; the whole order into the deep pool returns 97.276; the 20/80 split returns 97.746.
The split beats the best single pool by 0.470 output tokens, or 47 basis points of the order. That number is the router's entire economic claim on this trade. Every cost the router imposes — the protocol fee of 28 bps, the cost of an extra leg — is spent out of it, and a router that reports the split output while charging for the extra leg is quoting a number the user never receives.
pool x_i y_i gamma
shallow 1000 1000 0.997
deep 4000 4000 0.997 order D = 100
sqrt(A_1) = 998.50 sqrt(A_2) = 3993.99 d_1* = 20.0
all 100 -> shallow 90.661
all 100 -> deep 97.276
split 20 / 80 97.746 <- +0.470 (47 bps of the order)
Two properties of the curve that matter more than the optimum
Plot total output against the amount routed to the shallow pool and two things appear that the table cannot show. The curve is flat near its peak: being a few units away from the optimal split costs almost nothing, which is why a cheap approximation is defensible where an exact solver is not — and it is the honest defence of the proportional allocation the solver actually ships. And it falls off a cliff on the right, because routing the whole order into the shallow pool is the one genuinely bad decision available.
The practical reading is deflationary about our own derivation. A router that merely avoids the right-hand end has captured most of the value; the closed form is what captures the rest. The gap between proportional-to-depth and equimarginal allocation is real — proportional allocation equalises share of capital, optimality requires equalising marginal return, and the two coincide only when the venues have identical curves and identical fees — but it is bounded by the flatness, not large in the typical case.
When an extra leg stops paying, and why the gate is a heuristic
Each additional leg costs gas. Writing g for the marginal gas of one more leg and p for the gas price expressed in the output token, the (k+1)-th pool should be admitted only when the incremental gain in output exceeds g*p. In the example above, a second leg is worth taking only while gas costs less than 0.470 output tokens; above that, the deep pool alone is the better route including the fee the user actually pays.
Two qualifications belong in the same paragraph as the gate. First, a fixed cost per leg breaks convexity: everything above holds for a given set of venues, and choosing the set when each carries a fixed charge is a mixed-integer problem. Applying the gate greedily down the admission order is exact only if the incremental gains are decreasing in k, which is what makes a single crossing point exist; where that fails, the gate is a heuristic — a good and cheap one, but it should be named as such rather than dressed as an optimum. Second, the comparison is only as honest as p. Turning gas into output-token units requires a price, and a protocol that refuses oracles does not have one lying around; the deployed router applies the gate with a fixed bound rather than a measured cost, and that is a weaker thing than the inequality suggests.
This article publishes no gas figure, and that is deliberate rather than coy. A gas number carries an implied promise of reproducibility, and one stated without a named chain, a pinned block, a declared build profile and warm and cold cases reported separately is not evidence.
The one allocation step that has a proof rather than a rationale
If a venue cannot honour the share it was allocated, the solver reduces the input and promises exactly the clamped output. That is safe for a reason that follows from the shape of every constant-function curve: output is a concave function of input passing through the origin, and any such function satisfies f(lambda*s) >= lambda*f(s) for lambda in [0,1]. Cutting the input by a factor while promising the proportionally reduced output therefore promises no more than the venue will actually deliver. The inequality runs in the safe direction by construction, not by tuning — which is a stronger statement than any threshold, because it does not depend on the threshold being right.
What this derivation does not cover
The derivation assumes each venue is a constant-product curve, that reserves do not move between quote and execution, and that the legs are independent — no two touching the same pool or the same token in a longer path. Concentrated liquidity is piecewise constant-product, so the same water-filling applies inside a tick range, but A_i changes when a leg crosses a tick and the closed form must be applied per range. Stableswap and weighted pools have a different leg function and therefore a different derivative, though the equimarginal condition itself holds for any concave leg and is the part worth carrying into those cases.
Multi-hop routing is not a split at all: it is a composition, where one leg's output is the next leg's input, and the concavity of a composition needs its own argument before any of this transfers. That argument, what survives it and what does not, is a separate article.
Do not trust this page — reproduce it
Every claim above is checkable against the chain. Start here:
redo the example yourself — python3 -c "g=0.997; f=lambda x,y,d: y*g*d/(x+g*d); print(f(1000,1000,100), f(4000,4000,100), f(1000,1000,20)+f(4000,4000,80))" should print 90.661…, 97.276…, 97.746…
Cite this article
Licensed CC BY-NC-ND 4.0: quote and cite it with attribution and a link. Commercial use and derivative versions need written permission from BlazePhoenix; translations are made by BlazePhoenix. Copy a ready-made citation:
BlazePhoenix (2026). The closed-form optimal split across fee-adjusted constant-product venues. BlazePhoenix Engineering. https://blazephoenix.xyz/learn/closed-form-optimal-split/
@misc{blazephoenix_closed_form_optimal_split,
title = {The closed-form optimal split across fee-adjusted constant-product venues},
author = {BlazePhoenix},
year = {2026},
url = {https://blazephoenix.xyz/learn/closed-form-optimal-split/},
note = {Accessed: reproduce the claim with the command above}
}
Writing an answer, a wiki entry or a paper? The claim above is reproducible against the chain before you quote it — which is the only sound basis for citing a technical source at all.
Contracts are verified on every chain we deploy to — addresses in the protocol manifest. Deeper formal treatment: the whitepaper (PDF). Sources cited: Angeris, Chitra, Evans, Boyd — Optimal routing for constant function market makers · Diamandis, Angeris, Evans, Chitra — An efficient algorithm for optimal routing through constant function market makers