Skip to main content

ccxt_common/
order_router.rs

1// Native Rust — hand-written client for the CCXT order-router service.
2//
3// This is the SIXTH port of a class that is hand-written, not transpiled: the
4// TypeScript reference lives in `ts/src/base/OrderRouter.ts`, and Python, PHP,
5// C# and Go carry line-for-line siblings. They are held together by one shared
6// fixture, `ts/src/test/base/fixtures/orderRouter.json`, which every port runs.
7// A change to any of them that this port does not match fails that fixture, in
8// this language, which is the entire point of writing it out again rather than
9// generating it.
10//
11// Two things about Rust make the port read differently from its siblings while
12// meaning the same thing, and both are load-bearing:
13//
14//   * The other five pass dictionaries of `any`. Here that is `Value`, which is
15//     the same shape (`Value::Dict(Arc<IndexMap<String, Value>>)`) — so the
16//     accessors below are genuine equivalents of `numberAt`/`stringAt`/… and
17//     not a re-design.
18//   * The other five throw. Here the fallible methods return
19//     `Result<_, ExchangeError>`. `ExchangeError::kind` carries the same class
20//     names the other ports throw, so `is("NetworkError")` answers the same
21//     question `isOutcomeUnknownError` asks there.
22
23use std::borrow::Cow;
24use std::collections::BTreeSet;
25use std::sync::Arc;
26
27use crate::error::ExchangeError;
28use crate::value::{HashMap, Value};
29
30/// Result of a fallible router operation. The error's `kind` matches the
31/// exception class the other five ports raise for the same condition.
32pub type RouterResult<T> = std::result::Result<T, ExchangeError>;
33
34fn arguments_required(message: &str) -> ExchangeError {
35    ExchangeError::new("ArgumentsRequired", message)
36}
37
38fn bad_request(message: &str) -> ExchangeError {
39    ExchangeError::new("BadRequest", message)
40}
41
42fn exchange_error(message: &str) -> ExchangeError {
43    ExchangeError::new("ExchangeError", message)
44}
45
46fn insufficient_funds(message: &str) -> ExchangeError {
47    ExchangeError::new("InsufficientFunds", message)
48}
49
50/// NO_CAP is the default: this class does not decide how much of your money you
51/// may trade. `maxNotionalUsd` is an OPT-IN guardrail — set it and it is honoured
52/// exactly, at whatever value you choose; leave it unset and no notional check
53/// runs at all.
54///
55/// It used to be a hard 25 USD ceiling that could be lowered but never raised.
56/// That number came from CLAUDE.md §5.5, which governs THIS REPOSITORY'S live
57/// tests against real exchanges — not the people using the library. A client that
58/// refuses a 30 USD order because its own test suite is cautious is broken as a
59/// product.
60pub const NO_CAP: f64 = 0.0;
61/// Default distance from the expected price at which the limit is placed.
62pub const DEFAULT_SLIPPAGE_BPS: f64 = 25.0;
63/// Default shortfall ratio at which `reconcile_execution_step` halts.
64pub const DEFAULT_RECONCILE_TOLERANCE: f64 = 0.02;
65/// How long `retryFailedSteps` waits before re-placing a step the venue rejected.
66/// A second is the shortest delay that lets a transient cause clear (a rate limit
67/// window, a momentary balance lag) without turning a retry budget into a burst
68/// against a venue that just said no.
69pub const DEFAULT_RETRY_DELAY_MS: f64 = 1000.0;
70/// The float-equality epsilon this class compares with. Not a business
71/// tolerance — that is DEFAULT_RECONCILE_TOLERANCE. This one exists so that
72/// "the fill matches the request" and "the value sits on the precision grid"
73/// survive the last bits of floating-point arithmetic, and it must be the same
74/// number in all six ports or a violation fires in one language and not another.
75pub const TOLERANCE: f64 = 1e-9;
76const DEFAULT_BASE_URL: &str = "https://docs.ccxt.com/router/api";
77
78/// Human-readable text for each safety violation code. Carried in the violation
79/// record itself so a caller logging one does not have to keep its own copy of
80/// this table — and so all six ports emit the same sentence for the same code.
81fn violation_message(code: &str) -> &'static str {
82    match code {
83        "empty_plan" => "the plan contains no steps",
84        "route_unroutable" => "the route carries an unroutableReason and must not be executed",
85        "partial_fill" => "the route does not fill completely at the requested size",
86        "unknown_symbol" => "the symbol is not listed on that venue",
87        "market_mismatch" => "the venue market trades a different pair than the route hop says it does",
88        "invalid_step" => "the step has a non-positive amount or price, or a side that is neither buy nor sell",
89        "amount_below_minimum" => "the amount is below the market minimum",
90        "amount_above_maximum" => "the amount is above the market maximum",
91        "cost_below_minimum" => "the notional is below the market minimum cost",
92        "price_out_of_range" => "the limit price falls outside the market price limits",
93        "notional_unvaluable" => "the step cannot be valued in USD, so the notional cap cannot be enforced",
94        "notional_exceeds_cap" => "the notional exceeds the per-trade USD cap",
95        "amount_precision" => "the amount does not sit on the market amount precision",
96        "price_precision" => "the limit price does not sit on the market price precision",
97        // The TypeScript reads this table with stringAt(.., code, code): an
98        // unknown code falls back to the code itself rather than to empty.
99        other => {
100            // `other` is a &str borrowed from the caller, but this function
101            // returns 'static. Every code the class emits is in the table above,
102            // so the fallback only fires for a code that does not exist yet.
103            let _ = other;
104            "unknown_violation"
105        }
106    }
107}
108const DEFAULT_TIMEOUT_MS: f64 = 30000.0;
109/// The router accepts at most this many balance entries; the rest are dropped
110/// smallest-first and reported.
111const MAX_BALANCE_ENTRIES: usize = 64;
112/// And at most this many characters in the rendered value.
113const MAX_BALANCE_CHARS: usize = 4096;
114
115/// How many executed plan ids the in-process idempotency ledger keeps. 1024 is chosen to
116/// be far more executions than any one process performs in the window where a duplicate is
117/// plausible (a retry loop, an operator re-running a plan, a redelivered message), while
118/// bounding the ledger to a few tens of kilobytes so a router held open for the life of a
119/// daemon cannot grow without limit.
120///
121/// THE TRADEOFF IS REAL AND IS NOT HIDDEN: eviction WEAKENS the guarantee. Once a plan id
122/// has been pushed out by 1024 newer executions, re-executing that plan is no longer
123/// refused in-process — it will be placed again, orders and all. The guard is therefore
124/// "recent duplicates are refused", not "duplicates are impossible". A process that needs
125/// the strong promise across restarts or beyond this window needs the durable ledger the
126/// Known gaps entry calls for; until then, callers whose plans must never re-execute should
127/// key idempotency at the venue themselves (a clientOrderId passed in options.orderParams, on
128/// venues that honour one) rather than rely on this instance's memory.
129pub const MAX_EXECUTED_PLAN_IDS: usize = 1024;
130
131/// The bounded re-execution ledger: a FIFO queue of plan ids plus a set that answers
132/// membership in O(1). Both are private to this type so they can never fall out of step.
133#[derive(Debug)]
134pub struct ExecutedPlanLedger {
135    order: std::collections::VecDeque<String>,
136    seen: std::collections::HashSet<String>,
137}
138
139impl ExecutedPlanLedger {
140    pub fn new() -> Self {
141        ExecutedPlanLedger {
142            order: std::collections::VecDeque::new(),
143            seen: std::collections::HashSet::new(),
144        }
145    }
146
147    /// A hash lookup, not a scan: the ledger is capped but still up to
148    /// MAX_EXECUTED_PLAN_IDS long, and this runs on every live execution.
149    pub fn contains(&self, plan_id: &str) -> bool {
150        self.seen.contains(plan_id)
151    }
152
153    pub fn len(&self) -> usize {
154        self.order.len()
155    }
156
157    pub fn is_empty(&self) -> bool {
158        self.order.is_empty()
159    }
160
161    /// The id at `index` in insertion order, oldest first.
162    pub fn at(&self, index: usize) -> Option<&String> {
163        self.order.get(index)
164    }
165
166    /// Records one plan id, evicting the oldest entry when the cap is reached.
167    pub fn record(&mut self, plan_id: String) {
168        if self.seen.contains(&plan_id) {
169            // Already recorded; re-recording it would move it in the FIFO order and let
170            // a repeatedly re-executed plan keep other ids alive or evict them out of turn.
171            return;
172        }
173        self.seen.insert(plan_id.clone());
174        self.order.push_back(plan_id);
175        while self.order.len() > MAX_EXECUTED_PLAN_IDS {
176            // FIFO: the OLDEST execution is the one whose duplicate is least likely still
177            // in flight. Evicting it drops the refusal for that plan — see the comment on
178            // MAX_EXECUTED_PLAN_IDS; this is a bounded memory promise, not a stronger
179            // idempotency one.
180            if let Some(evicted) = self.order.pop_front() {
181                self.seen.remove(&evicted);
182            }
183        }
184    }
185}
186
187impl Default for ExecutedPlanLedger {
188    fn default() -> Self {
189        Self::new()
190    }
191}
192
193/// Everything one router mutates through `&self`. One owner thread holds all of
194/// it (see `OwnerThread`), so the ledger, the cached balances and the generation
195/// that invalidates them are read and written together and never half-applied.
196#[derive(Default)]
197struct RouterShared {
198    ledger: ExecutedPlanLedger,
199    balances: Option<String>,
200    generation: u64,
201}
202
203
204/// The shape of the `onStep` hook: it is handed one event describing a finished
205/// step and returns `"halt"` to stop the route. SYNCHRONOUS by design — it sits
206/// between orders on the money path, so do no network I/O in it.
207///
208/// WHY THIS IS A FIELD AND NOT AN OPTIONS KEY, unlike the other five ports.
209/// In TypeScript, Python, PHP, C# and Go the hook travels inside `options`,
210/// because in those languages a dictionary value can be a function. Rust's
211/// `options` is a `Value`, and `Value` is a closed, JSON-shaped enum that
212/// derives `Debug`, `Clone` and `PartialEq` and answers `to_json` — none of
213/// which a closure can. Adding a `Value::Fn` variant would mean answering
214/// "what does it mean for two closures to be equal, and how does one
215/// serialise" for every existing Value site in the crate, which is a redesign
216/// of the value model to carry an observability callback. So the callback comes
217/// in through the ONE side channel that can hold it — a field on the router,
218/// set by `set_on_step` — and `call_on_step` still takes `options` so the six
219/// implementations read line for line.
220pub type OnStepHook = Arc<dyn Fn(&Value) -> String + Send + Sync>;
221
222/// A client for the CCXT order-router service.
223pub struct OrderRouter {
224    api_key: String,
225    /// Sent as the `User-Agent` header when non-empty, so the router service can
226    /// attribute traffic to the integration that made it.
227    user_agent: String,
228    base_url: String,
229    timeout_ms: f64,
230    max_notional_usd: f64,
231    /// The only clock this class reads. `None` means the real wall clock; a
232    /// test pins time by setting it. A field rather than an overridable method
233    /// because `OrderRouter` is a concrete struct, not a trait.
234    now_ms_override: Option<f64>,
235    /// The idempotency ledger and the balances cache, both owned by one thread:
236    /// `execute`/`fetch_route` take `&self`, so they hand over a job and wait.
237    shared: crate::value::OwnerThread<RouterShared>,
238    /// The caller's `onStep` hook, or `None`. See `OnStepHook` for why this is a
239    /// field in this port and an options key in the other five. `execute` takes
240    /// `&self`, so this is only ever read, never written, during a run.
241    on_step: Option<OnStepHook>,
242
243    //  The venues this router trades through, held once instead of passed to every call.
244    //  Rust diverges from the other five ports HERE, and for the same reason it diverges
245    //  on the onStep hook: `Value` is a closed enum and cannot carry a `Box<dyn RouterVenue>`,
246    //  so they cannot arrive through the constructor config. The BEHAVIOUR is identical —
247    //  fetch_route filters and funds on them, execute falls back to them — only the
248    //  installation is a setter.
249    venues: std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
250
251    //  Whether this router manages balances at all. TWO decisions used to ride on `venues`:
252    //  where you can trade, and what you hold. The first is a filter - free, and it cannot go
253    //  stale. The second costs an authenticated call per venue and made one bad key enough to
254    //  kill a quote. So the filter is always on and the wallet reads are a mode you ask for.
255    track_balances: bool,
256}
257
258// ---------------------------------------------------------------------------
259// container accessors
260//
261// Every port has these; they exist so the six implementations read line for
262// line, and so a missing key is never a language-specific crash.
263// ---------------------------------------------------------------------------
264
265/// Plain container read: the field if the container is a dict and the field is
266/// present and not null, `None` otherwise. Deliberately NOT `get_value_k`, which
267/// also routes shared-order-book meta keys and live-client lookups — this class
268/// reads inert JSON structures, and picking up those side effects would make the
269/// accessors mean something the other five ports' accessors do not.
270fn field<'a>(container: &'a Value, key: &str) -> Option<&'a Value> {
271    match container.as_map().and_then(|map| map.get(key)) {
272        Some(Value::Null) | None => None,
273        found => found,
274    }
275}
276
277impl OrderRouter {
278    /// The price a step is sent at, derived from `expectedPrice` when the
279    /// caller gave no `limitPrice`. 0 only when the step has neither field.
280    ///
281    /// `build_execution_plan` always sets `limitPrice`, but a HAND-BUILT plan
282    /// need not: the manual documents it as optional, and the "execute your own
283    /// plans" path is the whole point of `execute` taking a plan rather than a
284    /// route. Reading it as 0 made every such plan fail three different ways —
285    /// a blocking `price_out_of_range` from `check_execution_plan_safety`, a
286    /// `rounded_to_zero` before any strategy branch in `place_step`, and a
287    /// buy-side balance requirement of `amount * 0` — so the documented example
288    /// could not place one order. `expectedPrice` is the honest fallback: it is
289    /// what the caller says the step is worth, and it is already guaranteed
290    /// positive by the `invalid_step` guard. A caller wanting a tighter or
291    /// looser bound sets `limitPrice` explicitly.
292    pub fn step_limit_price(&self, step: &Value) -> f64 {
293        let limit_price = self.number_at(step, "limitPrice", 0.0);
294        if limit_price > 0.0 {
295            return limit_price;
296        }
297        self.number_at(step, "expectedPrice", 0.0)
298    }
299
300    /// The step's quote-side value, derived from `amount` and `expectedPrice`
301    /// when absent.
302    ///
303    /// Same reasoning as `step_limit_price`, and the same formula
304    /// `build_execution_plan` uses. Read as 0, a hand-built plan tripped the
305    /// BLOCKING `cost_below_minimum` on every market declaring a minimum cost.
306    pub fn step_notional_quote(&self, step: &Value) -> f64 {
307        let notional_quote = self.number_at(step, "notionalQuote", 0.0);
308        if notional_quote > 0.0 {
309            return notional_quote;
310        }
311        self.number_at(step, "amount", 0.0) * self.number_at(step, "expectedPrice", 0.0)
312    }
313
314    /// Reads a numeric field, with a default for missing, null and unparseable
315    /// values.
316    pub fn number_at(&self, container: &Value, key: &str, default_value: f64) -> f64 {
317        Self::number_of(field(container, key), default_value)
318    }
319
320    fn number_of(value: Option<&Value>, default_value: f64) -> f64 {
321        match value {
322            None | Some(Value::Null) => default_value,
323            // NaN and the infinities are not numbers this class will act on. An
324            // infinite tolerance silently disables the halt verdict and an
325            // infinite rate silently disables the cap, and "the default" is the
326            // only answer six languages can agree on for either.
327            Some(Value::Int(n)) => {
328                let as_float = *n as f64;
329                if Self::is_finite_number(as_float) { as_float } else { default_value }
330            }
331            Some(Value::Float(n)) => {
332                if Self::is_finite_number(*n) { *n } else { default_value }
333            }
334            Some(Value::Str(text)) => Self::parse_number_text(text, default_value),
335            _ => default_value,
336        }
337    }
338
339    /// Reports whether a double is a real number, i.e. neither NaN nor an
340    /// infinity.
341    pub fn is_finite_number(value: f64) -> bool {
342        // DIVERGENCE, and the only one in this method. The other five ports
343        // write `value !== value`, which their comment calls "the one NaN test
344        // that needs no library" — in Rust that is clippy::eq_op, denied by
345        // default, and CI compiles with it fatal. `is_nan()` is the identical
346        // predicate; only the spelling differs.
347        if value.is_nan() {
348            return false;
349        }
350        if value > 1.7976931348623157e308 || value < -1.7976931348623157e308 {
351            return false;
352        }
353        true
354    }
355
356    /// Reads the leading numeric prefix of a string exactly as JavaScript's
357    /// `parseFloat` does, returning the default when there is not one or when
358    /// the result is not finite.
359    pub fn parse_number(&self, text: &str, default_value: f64) -> f64 {
360        Self::parse_number_text(text, default_value)
361    }
362
363    fn parse_number_text(text: &str, default_value: f64) -> f64 {
364        // Hand-rolled rather than delegated to the language's own parser,
365        // because every language's own parser disagrees with the others
366        // somewhere: Python reads '1_000' as 1000 and '1,234.5' not at all, PHP
367        // and Go read '0x10' as 0 only by accident of their regex, C# trims
368        // Unicode whitespace JavaScript does not, and Rust's own `f64::from_str`
369        // accepts "inf"/"NaN" and rejects any trailing text at all. The grammar
370        // below is JavaScript's StrDecimalLiteral prefix over the ASCII
371        // whitespace set, and it is the SAME twenty lines in all six ports.
372        //
373        // Indexed over BYTES, not chars: every character the grammar accepts is
374        // ASCII, and a multi-byte character can only ever end the scan.
375        let bytes = text.as_bytes();
376        let mut cursor = 0usize;
377        while cursor < bytes.len() && Self::is_router_space(bytes[cursor]) {
378            cursor += 1;
379        }
380        let start = cursor;
381        if cursor < bytes.len() && (bytes[cursor] == b'+' || bytes[cursor] == b'-') {
382            cursor += 1;
383        }
384        let mut digits = 0usize;
385        while cursor < bytes.len() && bytes[cursor].is_ascii_digit() {
386            cursor += 1;
387            digits += 1;
388        }
389        if cursor < bytes.len() && bytes[cursor] == b'.' {
390            cursor += 1;
391            while cursor < bytes.len() && bytes[cursor].is_ascii_digit() {
392                cursor += 1;
393                digits += 1;
394            }
395        }
396        if digits == 0 {
397            // 'Infinity', 'inf', 'NaN', '' and '٠١' all land here, in all six.
398            return default_value;
399        }
400        let mut end = cursor;
401        if cursor < bytes.len() && (bytes[cursor] == b'e' || bytes[cursor] == b'E') {
402            let mut exponent = cursor + 1;
403            if exponent < bytes.len() && (bytes[exponent] == b'+' || bytes[exponent] == b'-') {
404                exponent += 1;
405            }
406            let mut exponent_digits = 0usize;
407            while exponent < bytes.len() && bytes[exponent].is_ascii_digit() {
408                exponent += 1;
409                exponent_digits += 1;
410            }
411            if exponent_digits > 0 {
412                // A trailing 'e' with no digits is not part of the number: JS
413                // reads '1e' as 1, and so does every port here.
414                end = exponent;
415            }
416        }
417        let slice = &text[start..end];
418        match slice.parse::<f64>() {
419            // '1e400' overflows to an infinity, which is not a number the cap or
420            // the tolerance may be built out of.
421            Ok(parsed) if Self::is_finite_number(parsed) => parsed,
422            _ => default_value,
423        }
424    }
425
426    /// Reports whether a byte is one of the six ASCII spaces the number grammar
427    /// skips.
428    fn is_router_space(character: u8) -> bool {
429        // Deliberately NOT the language's own is_whitespace: Python, PHP, C#,
430        // Go and Rust each draw the Unicode line in a different place, and a
431        // non-breaking space that parses in one language and not the others is
432        // drift.
433        character == b' '
434            || character == b'\t'
435            || character == b'\n'
436            || character == b'\r'
437            || character == 0x0c
438            || character == 0x0b
439    }
440
441    /// Reads a string field, with a default for missing and null values.
442    pub fn string_at(&self, container: &Value, key: &str, default_value: &str) -> String {
443        match field(container, key) {
444            Some(Value::Str(text)) => text.to_string(),
445            _ => default_value.to_string(),
446        }
447    }
448
449    /// Reads a boolean field, with a default for missing and null values.
450    /// Whether the key holds the boolean `true` and nothing else. A config that
451    /// stringifies its booleans must not silently stop trading, so `"true"` is NOT true here.
452    pub fn is_exactly_true(&self, container: &Value, key: &str) -> bool {
453        matches!(field(container, key), Some(Value::Bool(true)))
454    }
455
456    pub fn bool_at(&self, container: &Value, key: &str, default_value: bool) -> bool {
457        match field(container, key) {
458            Some(Value::Bool(flag)) => *flag,
459            _ => default_value,
460        }
461    }
462
463    /// Reads an array field, returning an empty vector when absent. Never None,
464    /// for the same reason `listAt` never returns undefined.
465    pub fn list_at(&self, container: &Value, key: &str) -> Vec<Value> {
466        match field(container, key) {
467            Some(Value::Arr(items)) => items.as_ref().clone(),
468            _ => Vec::new(),
469        }
470    }
471
472    /// Reads a nested dictionary, returning an empty one when absent.
473    pub fn dict_at(&self, container: &Value, key: &str) -> Value {
474        match field(container, key) {
475            Some(Value::Dict(map)) => Value::Dict(Arc::clone(map)),
476            _ => Value::Map(HashMap::new()),
477        }
478    }
479
480    /// Formats a double as decimal text with no exponent, so that six languages
481    /// produce the same string.
482    pub fn format_number(&self, value: f64) -> RouterResult<String> {
483        // JavaScript prints 1e-7 where Python prints 1e-07 and Go prints 1e-07;
484        // a fixed 12-decimal rendering with the trailing zeros trimmed is the
485        // one spelling all six languages agree on for the magnitudes a balance
486        // or an amount can take.
487        if !Self::is_finite_number(value) {
488            return Ok("0".to_string());
489        }
490        if value.abs() >= 1e18 {
491            // JavaScript's toFixed switches to exponent notation at 1e21 while
492            // the other languages never do. Rather than let one language send a
493            // different string than the others, refuse — loudly, and at a
494            // magnitude no real amount reaches.
495            return Err(bad_request(
496                "OrderRouter: a number this large cannot be rendered identically in all six languages",
497            ));
498        }
499        let mut text = Self::to_fixed_12(value);
500        if text.contains('.') {
501            while text.ends_with('0') {
502                text.pop();
503            }
504            if text.ends_with('.') {
505                text.pop();
506            }
507        }
508        if text.is_empty() || text == "-" || text == "-0" {
509            return Ok("0".to_string());
510        }
511        Ok(text)
512    }
513
514    /// Renders a finite f64 with exactly twelve decimals, from the exact binary
515    /// value and under JavaScript's toFixed tie rule.
516    ///
517    /// The reference is TypeScript, and TypeScript's toFixed is ECMA-262's: the
518    /// sign is stripped BEFORE the digits are chosen, so a tie rounds AWAY FROM
519    /// ZERO on the magnitude and (-0.0001220703125).toFixed(12) is
520    /// -0.000122070313, not -...312. Rust's `{:.12}` rounds half to EVEN and
521    /// would answer ...312, so the balances query string this feeds would differ
522    /// per language on every value landing exactly on a half tick — 2^-13
523    /// included.
524    ///
525    /// `{:.53}` is EXACT for every double whose expansion reaches the twelfth
526    /// decimal: a double is m * 2^-k and its expansion terminates at digit k, so
527    /// k <= 53 (|value| >= 2^-53) renders with no rounding at all, and anything
528    /// smaller is below 1e-16 — its digits 13 and 14 are both 0, so no carry
529    /// from digit 53 can reach the digit this rounds on.
530    fn to_fixed_12(value: f64) -> String {
531        let negative = value < 0.0;
532        // abs() rather than a negation, so a negative zero renders WITHOUT a
533        // sign: the digit walk below assumes every byte it reads is a digit.
534        let magnitude = value.abs();
535        let rendered = format!("{magnitude:.53}");
536        let dot = match rendered.find('.') {
537            Some(index) => index,
538            None => return rendered,
539        };
540        let mut integer_length = dot;
541        let digits: Vec<u8> = rendered
542            .bytes()
543            .filter(|byte| *byte != b'.')
544            .collect();
545        let keep = integer_length + 12;
546        // round half UP on the magnitude, reading the thirteenth decimal exactly
547        let round_up = digits[keep] >= b'5';
548        let mut kept: Vec<u8> = digits[..keep].to_vec();
549        if round_up {
550            let mut carry = 1u8;
551            let mut index = kept.len();
552            while index > 0 && carry == 1 {
553                index -= 1;
554                let digit = kept[index] - b'0' + carry;
555                carry = u8::from(digit >= 10);
556                kept[index] = (digit % 10) + b'0';
557            }
558            if carry == 1 {
559                kept.insert(0, b'1');
560                integer_length += 1;
561            }
562        }
563        let text = String::from_utf8_lossy(&kept).to_string();
564        let sign = if negative { "-" } else { "" };
565        format!("{}{}.{}", sign, &text[..integer_length], &text[integer_length..])
566    }
567}
568
569// ---------------------------------------------------------------------------
570// construction
571// ---------------------------------------------------------------------------
572
573impl OrderRouter {
574    /// Creates a client for the CCXT order-router service.
575    ///
576    /// `config` keys: `apiKey` (optional; the service rate-limits by IP), `baseUrl`, `timeoutMs`,
577    /// `maxNotionalUsd` (an OPT-IN per-trade USD cap, honoured exactly at
578    /// whatever value is given; 0 — the default — means NO CAP, and a negative
579    /// value is refused), `userAgent` (optional `User-Agent` header sent with every
580    /// router request so the service can attribute traffic, e.g.
581    /// `ccxt-mcp/1.2.3 (ccxt 4.5.6)`; empty — the default — keeps reqwest's default).
582    pub fn new(config: &Value) -> RouterResult<Self> {
583        // Constructed through a temporary so the accessors — which are methods,
584        // exactly as in the other five ports — are available while reading the
585        // config that builds the real one.
586        let reader = OrderRouter {
587            api_key: String::new(),
588            user_agent: String::new(),
589            base_url: String::new(),
590            timeout_ms: DEFAULT_TIMEOUT_MS,
591            max_notional_usd: NO_CAP,
592            now_ms_override: None,
593            shared: crate::value::OwnerThread::spawn("ccxt-order-router", RouterShared::default()),
594            on_step: None,
595            venues: std::collections::BTreeMap::new(),
596            track_balances: false,
597        };
598        // The service dropped API keys in favour of per-IP rate limiting, so an empty key is
599        // the normal case and must not error. A key supplied anyway is CARRIED rather than
600        // ignored, so the same client works against both servers.
601        let api_key = reader.string_at(config, "apiKey", "");
602        let user_agent = reader.string_at(config, "userAgent", "");
603        let mut base_url = reader.string_at(config, "baseUrl", DEFAULT_BASE_URL);
604        while base_url.ends_with('/') {
605            base_url.pop();
606        }
607        let timeout_ms = reader.number_at(config, "timeoutMs", DEFAULT_TIMEOUT_MS);
608        let max_notional_usd = reader.number_at(config, "maxNotionalUsd", NO_CAP);
609        if max_notional_usd < 0.0 {
610            // A negative cap is a typo, not a policy, and silently ignoring it
611            // would leave the caller believing a guardrail is in place.
612            return Err(bad_request(
613                "OrderRouter maxNotionalUsd must not be negative; omit it, or pass 0, for no cap",
614            ));
615        }
616        // 0 means NO CAP. Any positive value is honoured exactly — it is not
617        // clamped, because the caller is the one who knows the size of their own
618        // trade.
619        Ok(OrderRouter {
620            api_key,
621            user_agent,
622            base_url,
623            timeout_ms,
624            max_notional_usd,
625            now_ms_override: None,
626            shared: crate::value::OwnerThread::spawn("ccxt-order-router", RouterShared::default()),
627            on_step: None,
628            venues: std::collections::BTreeMap::new(),
629            track_balances: false,
630        })
631    }
632
633    /// Installs the `onStep` hook: called after each step completes and
634    /// reconciles, never mid-order, with one event describing that step. Return
635    /// `"halt"` to stop the route cleanly (`haltReason` becomes
636    /// `halted_by_on_step`); any other value continues. It can only STOP a
637    /// route, never resume one already halted. Do NO network I/O here — it sits
638    /// between orders on the money path. A hook that PANICS is recorded as
639    /// `on_step_hook_failed` and the run continues, because losing the report
640    /// would destroy the only account of orders that are already live.
641    pub fn set_on_step(&mut self, hook: OnStepHook) {
642        self.on_step = Some(hook);
643    }
644
645    /// Installs the venues this router trades through. See the `venues` field for why this
646    /// is a setter in Rust and a constructor key everywhere else.
647    pub fn set_venues(&mut self, venues: std::collections::BTreeMap<String, Box<dyn RouterVenue>>) {
648        self.venues = venues;
649    }
650
651    /// Turns balance tracking on or off. Off (the default), fetch_route never touches a venue
652    /// and stays a single HTTP request; on, it routes on what you can actually fund.
653    pub fn set_track_balances(&mut self, track: bool) {
654        self.track_balances = track;
655        self.invalidate_balances();
656    }
657
658    /// Removes the stored venues, so fetch_route stops filtering and funding on them.
659    pub fn clear_venues(&mut self) {
660        self.venues = std::collections::BTreeMap::new();
661    }
662
663    /// The venues this router holds, empty when none were installed.
664    pub fn venues(&self) -> &std::collections::BTreeMap<String, Box<dyn RouterVenue>> {
665        &self.venues
666    }
667
668    /// Removes the `onStep` hook.
669    pub fn clear_on_step(&mut self) {
670        self.on_step = None;
671    }
672
673    /// Hands one job to the router's owner thread and returns its result.
674    fn shared_op<R, F>(&self, f: F) -> R
675    where R: Send + 'static, F: FnOnce(&mut RouterShared) -> R + Send + 'static {
676        self.shared.run(f)
677    }
678
679    /// Reports whether this instance has executed the given plan id recently enough for
680    /// the bounded ledger to still remember it.
681    pub fn has_executed_plan(&self, plan_id: &str) -> bool {
682        let id = plan_id.to_string();
683        self.shared_op(move |s| s.ledger.contains(&id))
684    }
685
686    /// Records one plan id in the bounded ledger, evicting the oldest entry when full.
687    pub fn record_executed_plan(&self, plan_id: &str) {
688        let id = plan_id.to_string();
689        self.shared_op(move |s| s.ledger.record(id));
690    }
691
692    /// How many plan ids the ledger currently holds, and the id at one position in
693    /// insertion order. Both exist so the self-test can assert the bound and the
694    /// eviction order without reaching through the mutex itself.
695    pub fn executed_plan_count(&self) -> usize {
696        self.shared_op(|s| s.ledger.len())
697    }
698
699    pub fn executed_plan_at(&self, index: usize) -> String {
700        self.shared_op(move |s| match s.ledger.at(index) {
701            Some(entry) => entry.clone(),
702            None => String::new(),
703        })
704    }
705
706    /// Pins the clock, for tests. Production never calls this.
707    pub fn set_now_ms(&mut self, now_ms: f64) {
708        self.now_ms_override = Some(now_ms);
709    }
710
711    /// The only clock this class reads.
712    fn now_ms(&self) -> f64 {
713        match self.now_ms_override {
714            Some(pinned) => pinned,
715            None => std::time::SystemTime::now()
716                .duration_since(std::time::UNIX_EPOCH)
717                .map(|d| d.as_millis() as f64)
718                .unwrap_or(0.0),
719        }
720    }
721
722    /// The per-trade USD notional cap this client will enforce, or `NO_CAP` when
723    /// the caller never asked for one.
724    pub fn max_notional_usd(&self) -> f64 {
725        self.max_notional_usd
726    }
727
728    /// The api key this client carries, empty when it has none. The service is
729    /// public and needs no key; one supplied anyway is sent as `x-api-key`, so a
730    /// deployment fronting the router with its own authentication still works.
731    pub fn api_key(&self) -> &str {
732        &self.api_key
733    }
734
735    /// The User-Agent this client sends, empty when it keeps the http client's default.
736    pub fn user_agent(&self) -> &str {
737        &self.user_agent
738    }
739
740    /// The router base url, with any trailing slashes removed.
741    pub fn base_url(&self) -> &str {
742        &self.base_url
743    }
744
745    /// The configured request timeout, in milliseconds.
746    pub fn timeout_ms(&self) -> f64 {
747        self.timeout_ms
748    }
749}
750
751// ---------------------------------------------------------------------------
752// PURE: build_execution_plan
753// ---------------------------------------------------------------------------
754
755impl OrderRouter {
756    /// Refuses a route whose hops do not connect, or that does not run from the
757    /// asset the caller offered to the asset the caller wanted.
758    ///
759    /// `build_execution_plan` used to copy `from`, `to`, `pair` and `side`
760    /// straight out of the server's JSON, and the safety checks only tested
761    /// internal consistency against whatever market that named — so a
762    /// compromised, or simply buggy, router response could steer real orders
763    /// into any real market and every check would pass it, under the 25 USD cap.
764    pub fn assert_route_chain_is_coherent(&self, route: &Value, hops: &[Value]) -> RouterResult<()> {
765        if hops.is_empty() {
766            return Ok(());
767        }
768        let mut carried = String::new();
769        for (index, hop) in hops.iter().enumerate() {
770            let side = self.string_at(hop, "side", "").to_lowercase();
771            let base_code = self.string_at(hop, "base", "").to_uppercase();
772            let quote = self.string_at(hop, "quote", "").to_uppercase();
773            if base_code.is_empty() || quote.is_empty() || (side != "buy" && side != "sell") {
774                return Err(exchange_error(&format!(
775                    "OrderRouter: hop {index} does not name a market and a side"
776                )));
777            }
778            // A buy spends the quote to acquire the base; a sell is the reverse.
779            let spends = if side == "buy" { quote.clone() } else { base_code.clone() };
780            let produces = if side == "buy" { base_code } else { quote };
781            if index > 0 && spends != carried {
782                // Hop N+1 must spend exactly what hop N produced, or the plan
783                // strands the proceeds of one order and funds the next from a
784                // wallet nobody checked.
785                return Err(exchange_error(&format!(
786                    "OrderRouter: hop {index} spends {spends} but the previous hop produced {carried}"
787                )));
788            }
789            if index == 0 {
790                let requested_from = self.string_at(route, "clientRequestedFrom", "");
791                if !requested_from.is_empty() && spends != requested_from {
792                    return Err(exchange_error(&format!(
793                        "OrderRouter: the route spends {spends}, not the requested {requested_from}"
794                    )));
795                }
796            }
797            carried = produces;
798        }
799        let requested_to = self.string_at(route, "clientRequestedTo", "");
800        if !requested_to.is_empty() && carried != requested_to {
801            return Err(exchange_error(&format!(
802                "OrderRouter: the route produces {carried}, not the requested {requested_to}"
803            )));
804        }
805        Ok(())
806    }
807
808    /// Turns a RouteResult into an ordered list of concrete orders. PURE — no
809    /// I/O, and the same input produces the same output in all six languages.
810    ///
811    /// `options` keys: `slippageBps` (default 25) and `reconcileToleranceRatio`
812    /// (default 0.02).
813    pub fn build_execution_plan(&self, route: &Value, options: &Value) -> RouterResult<Value> {
814        let slippage_bps = self.number_at(options, "slippageBps", DEFAULT_SLIPPAGE_BPS);
815        let tolerance = self.number_at(options, "reconcileToleranceRatio", DEFAULT_RECONCILE_TOLERANCE);
816        let hops = self.list_at(route, "hops");
817        self.assert_route_chain_is_coherent(route, &hops)?;
818        let mut steps: Vec<Value> = Vec::new();
819        let mut step_index = 0i64;
820        for (hop_index, hop) in hops.iter().enumerate() {
821            let symbol = self.string_at(hop, "pair", "");
822            let side = self.string_at(hop, "side", "");
823            let base_code = self.string_at(hop, "base", "");
824            let quote = self.string_at(hop, "quote", "");
825            let legs = self.list_at(hop, "legs");
826            for (leg_index, leg) in legs.iter().enumerate() {
827                // Leg amounts are always in BASE units, on both sides of the
828                // market — see the router's RoutingQuote.filledAmount contract.
829                let amount = self.number_at(leg, "amount", 0.0);
830                let expected_price = self.number_at(leg, "averagePrice", 0.0);
831                let effective_price = self.number_at(leg, "effectivePrice", expected_price);
832                // The limit sits on the side that costs you: above for a buy,
833                // below for a sell.
834                let limit_price = if side == "buy" {
835                    expected_price * (1.0 + slippage_bps / 10000.0)
836                } else {
837                    expected_price * (1.0 - slippage_bps / 10000.0)
838                };
839                let mut step = HashMap::new();
840                step.insert("stepIndex".into(), Value::Float(step_index as f64));
841                step.insert("hopIndex".into(), Value::Float(hop_index as f64));
842                step.insert("legIndex".into(), Value::Float(leg_index as f64));
843                step.insert("exchangeId".into(), Value::Str(self.string_at(leg, "exchangeId", "").into()));
844                step.insert("symbol".into(), Value::Str(symbol.clone().into()));
845                step.insert("side".into(), Value::Str(side.clone().into()));
846                step.insert("base".into(), Value::Str(base_code.clone().into()));
847                step.insert("quote".into(), Value::Str(quote.clone().into()));
848                step.insert("amount".into(), Value::Float(amount));
849                step.insert("expectedPrice".into(), Value::Float(expected_price));
850                step.insert("effectivePrice".into(), Value::Float(effective_price));
851                step.insert("limitPrice".into(), Value::Float(limit_price));
852                step.insert("notionalQuote".into(), Value::Float(amount * expected_price));
853                // The taker fee the ROUTER predicted for this leg, always denominated in
854                // the quote currency (the service's own RouteLeg.feeCost contract). Carried
855                // so step_expected_out can measure the expectation the same way execute
856                // measures the realised amount — see the note there. 0 on a hand-built plan,
857                // which is exactly the old behaviour.
858                step.insert(
859                    "expectedFeeCost".into(),
860                    Value::Float(self.number_at(leg, "feeCost", 0.0)),
861                );
862                // This leg was cut short by the WALLET, not by the book: more was on offer,
863                // the balances just could not pay for it. Size-capped and depth-capped look
864                // identical in the numbers and need different follow-up.
865                step.insert(
866                    "balanceLimited".into(),
867                    Value::Bool(self.bool_at(leg, "balanceLimited", false)),
868                );
869                steps.push(Value::Map(step));
870                step_index += 1;
871            }
872        }
873        let mut plan = HashMap::new();
874        plan.insert("requestId".into(), Value::Str(self.string_at(route, "requestId", "").into()));
875        plan.insert("calculatedAt".into(), Value::Float(self.number_at(route, "calculatedAt", 0.0)));
876        plan.insert("from".into(), Value::Str(self.string_at(route, "from", "").into()));
877        plan.insert("to".into(), Value::Str(self.string_at(route, "to", "").into()));
878        plan.insert("routingStrategy".into(), Value::Str(self.string_at(route, "strategy", "").into()));
879        plan.insert("exactSide".into(), Value::Str(self.string_at(route, "exactSide", "").into()));
880        plan.insert("amountIn".into(), Value::Float(self.number_at(route, "amountIn", 0.0)));
881        plan.insert("amountOut".into(), Value::Float(self.number_at(route, "amountOut", 0.0)));
882        plan.insert("fullyFillable".into(), Value::Bool(self.bool_at(route, "fullyFillable", false)));
883        plan.insert("fillRatio".into(), Value::Float(self.number_at(route, "fillRatio", 0.0)));
884        plan.insert("unroutableReason".into(), Value::Str(self.string_at(route, "unroutableReason", "").into()));
885        // WHICH hop could not be solved. -1 when the route is routable or the server did not
886        // say; 0 is a real answer and must not read as "unknown".
887        plan.insert(
888            "unroutableHopIndex".into(),
889            Value::Float(self.number_at(route, "unroutableHopIndex", -1.0)),
890        );
891        // What the CALLER asked for, stamped by fetch_route — not the server's echo.
892        plan.insert(
893            "requireFullFill".into(),
894            Value::Bool(self.bool_at(route, "clientRequestedRequireFullFill", false)),
895        );
896        plan.insert("hopCount".into(), Value::Float(hops.len() as f64));
897        plan.insert("stepCount".into(), Value::Float(steps.len() as f64));
898        plan.insert("slippageBps".into(), Value::Float(slippage_bps));
899        plan.insert("reconcileToleranceRatio".into(), Value::Float(tolerance));
900        plan.insert("steps".into(), Value::List(steps));
901        Ok(Value::Map(plan))
902    }
903}
904
905// ---------------------------------------------------------------------------
906// the venue abstraction
907// ---------------------------------------------------------------------------
908
909/// What `execute` needs from an exchange, and nothing more.
910///
911/// The other five ports hand `execute` their language's exchange object
912/// directly. Rust cannot: `ExchangeBase`'s methods return `impl Future`, which
913/// is not object-safe, so a `HashMap<String, Box<dyn ExchangeBase>>` — the
914/// shape every other port uses for `venues` — cannot exist. This trait is that
915/// shape, narrowed to the operations the money path actually performs, and it
916/// is what makes the venues map possible here at all.
917///
918/// It also buys something the other ports get for free from dynamic typing: a
919/// test can implement this in twenty lines, so the execute-path invariants are
920/// testable without a live exchange.
921#[async_trait::async_trait]
922pub trait RouterVenue: Send + Sync {
923    /// The venue's ccxt id, e.g. `binance`. Matched against a step's
924    /// `exchangeId`.
925    fn id(&self) -> String;
926
927    /// Snaps an amount to the market's precision, as text — the same contract
928    /// as ccxt's `amountToPrecision`.
929    fn amount_to_precision(&self, symbol: &str, amount: f64) -> String;
930
931    /// Snaps a price to the market's precision, as text.
932    fn price_to_precision(&self, symbol: &str, price: f64) -> String;
933
934    /// Whether this venue accepts an immediate-or-cancel time-in-force on a
935    /// limit order. A venue that does not gets a market order only when the
936    /// caller has explicitly opted in — see `execute`.
937    fn supports_ioc(&self) -> bool;
938
939    /// Places an order. `params` carries the time-in-force and any caller
940    /// extras.
941    async fn create_order(
942        &self,
943        symbol: &str,
944        order_type: &str,
945        side: &str,
946        amount: f64,
947        price: f64,
948        params: &Value,
949    ) -> RouterResult<Value>;
950
951    /// Reads an order back. Used to re-read a venue that answered without a
952    /// `filled`, rather than assuming one.
953    async fn fetch_order(&self, id: &str, symbol: &str) -> RouterResult<Value>;
954
955    /// Cancels an order. Used by the protected-limit path when the poll expires.
956    async fn cancel_order(&self, id: &str, symbol: &str) -> RouterResult<Value>;
957
958    /// Reads the account's holdings, in ccxt's balance shape — `free` and
959    /// `total` maps of currency code to amount. Only `fetch_route_with_balances`
960    /// calls this; a venue used solely with `execute` can return an empty map.
961    async fn fetch_balance(&self) -> RouterResult<Value> {
962        Ok(Value::Map(HashMap::new()))
963    }
964}
965
966// ---------------------------------------------------------------------------
967// PURE: check_execution_plan_safety
968// ---------------------------------------------------------------------------
969
970impl OrderRouter {
971    /// Builds one safety violation record.
972    fn violation(
973        &self,
974        step_index: f64,
975        exchange_id: &str,
976        symbol: &str,
977        code: &str,
978        blocking: bool,
979        actual: f64,
980        limit: f64,
981    ) -> Value {
982        let mut entry = HashMap::new();
983        entry.insert("stepIndex".into(), Value::Float(step_index));
984        entry.insert("exchangeId".into(), Value::Str(exchange_id.to_string().into()));
985        entry.insert("symbol".into(), Value::Str(symbol.to_string().into()));
986        entry.insert("code".into(), Value::Str(code.to_string().into()));
987        entry.insert("blocking".into(), Value::Bool(blocking));
988        entry.insert("actual".into(), Value::Float(actual));
989        entry.insert("limit".into(), Value::Float(limit));
990        entry.insert("message".into(), Value::Str(violation_message(code).to_string().into()));
991        Value::Map(entry)
992    }
993
994    /// Resolves the USD price of a currency, treating USD itself as 1 and
995    /// assuming nothing about anything else.
996    fn usd_rate_for(&self, code: &str, usd_rates: &Value) -> f64 {
997        if code.is_empty() {
998            return 0.0;
999        }
1000        if code == "USD" {
1001            return 1.0;
1002        }
1003        // USDT and USDC are NOT assumed to be one dollar. A stablecoin peg is an
1004        // empirical fact, not a definition, and the caller supplying rates is
1005        // the one who knows today's.
1006        let rate = self.number_at(usd_rates, code, 0.0);
1007        if rate > 0.0 {
1008            return rate;
1009        }
1010        0.0
1011    }
1012
1013    /// The USD value of a step's notional, quote side first and base side as
1014    /// the fallback — `amount * usd(base)` values the same trade.
1015    fn notional_usd(&self, step: &Value, notional_quote: f64, usd_rates: &Value) -> f64 {
1016        let quote = self.string_at(step, "quote", "");
1017        let quote_rate = self.usd_rate_for(&quote, usd_rates);
1018        if quote_rate > 0.0 {
1019            return notional_quote * quote_rate;
1020        }
1021        let base_code = self.string_at(step, "base", "");
1022        let base_rate = self.usd_rate_for(&base_code, usd_rates);
1023        if base_rate > 0.0 {
1024            return self.number_at(step, "amount", 0.0) * base_rate;
1025        }
1026        0.0
1027    }
1028
1029    /// Reports whether a value fails to sit on a market's precision grid.
1030    fn precision_violated(&self, value: f64, precision: f64, mode: &str) -> bool {
1031        if precision <= 0.0 {
1032            // Unknown or unconstrained precision is not a finding.
1033            return false;
1034        }
1035        let rounded = if mode == "decimal_places" {
1036            let factor = 10f64.powf(precision);
1037            (value * factor).round() / factor
1038        } else {
1039            // The rounding mode is irrelevant here: a value exactly halfway
1040            // between two ticks is off-grid whichever neighbour it snaps to, so
1041            // the six languages' differing round() semantics cannot change this
1042            // predicate's answer.
1043            (value / precision).round() * precision
1044        };
1045        let allowed = value.abs() * TOLERANCE + 1e-15;
1046        (rounded - value).abs() > allowed
1047    }
1048
1049    /// Checks a plan against per-venue market rules and the hard per-trade USD
1050    /// notional cap. PURE — no I/O. A step that cannot be valued in USD BLOCKS;
1051    /// it is never skipped, because a cap that silently disappears when a rate
1052    /// is missing is not a cap.
1053    ///
1054    /// `markets` is `markets[exchangeId][symbol]`.
1055    pub fn check_execution_plan_safety(
1056        &self,
1057        plan: &Value,
1058        markets: &Value,
1059        options: &Value,
1060    ) -> Vec<Value> {
1061        let mut violations: Vec<Value> = Vec::new();
1062        // Honoured exactly as given, per call or per client. No clamping: a
1063        // caller trading thousands and a caller trading cents are both using
1064        // this correctly.
1065        let max_notional_usd = self.number_at(options, "maxNotionalUsd", self.max_notional_usd);
1066        let cap_in_force = max_notional_usd > 0.0;
1067        let usd_rates = self.dict_at(options, "usdRates");
1068        let precision_mode = self.string_at(options, "precisionMode", "tick_size");
1069        let steps = self.list_at(plan, "steps");
1070        if steps.is_empty() {
1071            // An empty plan passing an empty violation list would read as "safe".
1072            violations.push(self.violation(-1.0, "", "", "empty_plan", true, 0.0, 0.0));
1073            return violations;
1074        }
1075        let unroutable_reason = self.string_at(plan, "unroutableReason", "");
1076        if !unroutable_reason.is_empty() {
1077            violations.push(self.violation(-1.0, "", "", "route_unroutable", true, 0.0, 0.0));
1078        }
1079        if !self.bool_at(plan, "fullyFillable", false) {
1080            violations.push(self.violation(
1081                // BLOCKING when the caller asked for requireFullFill. That parameter is
1082                // the one route flag that fails OPEN: a partial route in the same breath as
1083                // the flag means the flag did not survive the trip.
1084                -1.0,
1085                "",
1086                "",
1087                "partial_fill",
1088                self.bool_at(plan, "requireFullFill", false),
1089                self.number_at(plan, "fillRatio", 0.0),
1090                1.0,
1091            ));
1092        }
1093        for (i, step) in steps.iter().enumerate() {
1094            let step_index = self.number_at(step, "stepIndex", i as f64);
1095            let exchange_id = self.string_at(step, "exchangeId", "");
1096            let symbol = self.string_at(step, "symbol", "");
1097            let amount = self.number_at(step, "amount", 0.0);
1098            let expected_price = self.number_at(step, "expectedPrice", 0.0);
1099            let limit_price = self.step_limit_price(step);
1100            let notional_quote = self.step_notional_quote(step);
1101            let side = self.string_at(step, "side", "");
1102            if amount <= 0.0 || expected_price <= 0.0 || (side != "buy" && side != "sell") {
1103                violations.push(self.violation(
1104                    step_index, &exchange_id, &symbol, "invalid_step", true, amount, 0.0,
1105                ));
1106                continue;
1107            }
1108            let venue_markets = self.dict_at(markets, &exchange_id);
1109            let market = self.dict_at(&venue_markets, &symbol);
1110            if market.as_map().map(|m| m.is_empty()).unwrap_or(true) {
1111                violations.push(self.violation(
1112                    step_index, &exchange_id, &symbol, "unknown_symbol", true, 0.0, 0.0,
1113                ));
1114                continue;
1115            }
1116            // The same symbol string on a different venue is not necessarily the
1117            // same pair, and the USD valuation below trusts the step's quote
1118            // currency — so disagreement is fatal, not cosmetic.
1119            let market_base = self.string_at(&market, "base", "");
1120            let market_quote = self.string_at(&market, "quote", "");
1121            let step_base = self.string_at(step, "base", "");
1122            let step_quote = self.string_at(step, "quote", "");
1123            let base_disagrees =
1124                !market_base.is_empty() && !step_base.is_empty() && market_base != step_base;
1125            let quote_disagrees =
1126                !market_quote.is_empty() && !step_quote.is_empty() && market_quote != step_quote;
1127            if base_disagrees || quote_disagrees {
1128                violations.push(self.violation(
1129                    step_index, &exchange_id, &symbol, "market_mismatch", true, 0.0, 0.0,
1130                ));
1131                continue;
1132            }
1133            let limits = self.dict_at(&market, "limits");
1134            let amount_limits = self.dict_at(&limits, "amount");
1135            let price_limits = self.dict_at(&limits, "price");
1136            let cost_limits = self.dict_at(&limits, "cost");
1137            let min_amount = self.number_at(&amount_limits, "min", 0.0);
1138            let max_amount = self.number_at(&amount_limits, "max", 0.0);
1139            let min_price = self.number_at(&price_limits, "min", 0.0);
1140            let max_price = self.number_at(&price_limits, "max", 0.0);
1141            let min_cost = self.number_at(&cost_limits, "min", 0.0);
1142            if min_amount > 0.0 && amount < min_amount {
1143                violations.push(self.violation(
1144                    step_index, &exchange_id, &symbol, "amount_below_minimum", true, amount, min_amount,
1145                ));
1146            }
1147            if max_amount > 0.0 && amount > max_amount {
1148                violations.push(self.violation(
1149                    step_index, &exchange_id, &symbol, "amount_above_maximum", true, amount, max_amount,
1150                ));
1151            }
1152            if min_cost > 0.0 && notional_quote < min_cost {
1153                violations.push(self.violation(
1154                    step_index, &exchange_id, &symbol, "cost_below_minimum", true, notional_quote, min_cost,
1155                ));
1156            }
1157            if (min_price > 0.0 && limit_price < min_price)
1158                || (max_price > 0.0 && limit_price > max_price)
1159            {
1160                let bound = if limit_price < min_price { min_price } else { max_price };
1161                violations.push(self.violation(
1162                    step_index, &exchange_id, &symbol, "price_out_of_range", true, limit_price, bound,
1163                ));
1164            }
1165            let precision = self.dict_at(&market, "precision");
1166            let amount_precision = self.number_at(&precision, "amount", 0.0);
1167            let price_precision = self.number_at(&precision, "price", 0.0);
1168            // Precision findings are advisory: execute() snaps through the
1169            // venue's own amountToPrecision/priceToPrecision before sending.
1170            if self.precision_violated(amount, amount_precision, &precision_mode) {
1171                violations.push(self.violation(
1172                    step_index, &exchange_id, &symbol, "amount_precision", false, amount, amount_precision,
1173                ));
1174            }
1175            if self.precision_violated(limit_price, price_precision, &precision_mode) {
1176                violations.push(self.violation(
1177                    step_index, &exchange_id, &symbol, "price_precision", false, limit_price, price_precision,
1178                ));
1179            }
1180            // The notional cap. The worst case is the higher of the expected and
1181            // the limit price, which is the buy side; a sell's limit sits below,
1182            // so its expected price is the one that governs.
1183            let mut worst_price = expected_price;
1184            if limit_price > worst_price {
1185                worst_price = limit_price;
1186            }
1187            if cap_in_force {
1188                // Only when a cap is actually set. With no cap there is nothing
1189                // to enforce, so a missing USD rate is not an error and the
1190                // caller is not made to supply usdRates for a check they did not
1191                // ask for.
1192                let worst_notional = amount * worst_price;
1193                let usd_value = self.notional_usd(step, worst_notional, &usd_rates);
1194                if usd_value <= 0.0 {
1195                    // BLOCKING, and deliberately so. Skipping the cap for a step
1196                    // whose USD value is unknown defeats the cap the caller DID
1197                    // ask for.
1198                    violations.push(self.violation(
1199                        step_index, &exchange_id, &symbol, "notional_unvaluable", true,
1200                        worst_notional, max_notional_usd,
1201                    ));
1202                } else if usd_value > max_notional_usd * (1.0 + TOLERANCE) {
1203                    violations.push(self.violation(
1204                        step_index, &exchange_id, &symbol, "notional_exceeds_cap", true, usd_value,
1205                        max_notional_usd,
1206                    ));
1207                }
1208            }
1209        }
1210        violations
1211    }
1212}
1213
1214// ---------------------------------------------------------------------------
1215// PURE: reconcile_execution_step
1216// ---------------------------------------------------------------------------
1217
1218impl OrderRouter {
1219    /// How much of its output asset a step is expected to produce, gross of
1220    /// fees: base units for a buy, quote units for a sell.
1221    pub fn step_expected_out(&self, step: &Value) -> f64 {
1222        let amount = self.number_at(step, "amount", 0.0);
1223        if self.string_at(step, "side", "") == "buy" {
1224            // A buy produces BASE, and the router's predicted fee is quote-denominated,
1225            // so it does not reduce what this step hands to the next one. A venue that
1226            // charges its buy fee in the base asset really does deliver less, and the
1227            // resize that follows from it is correct.
1228            return amount;
1229        }
1230        // A SELL produces QUOTE, which is the currency the predicted fee is already in.
1231        //
1232        // This subtraction is what stops the fee being counted TWICE. execute reports
1233        // realisedOut net of a fee charged in the asset the step produced, because that
1234        // is what the wallet actually receives. The router, in turn, already sized the
1235        // next hop from its own NET figure: in the shared fixture, hop 0 sells 500 DOGE
1236        // at 0.089 for 44.5 gross, reports amountOut 44.47482324238088 after a
1237        // 0.025176757619121304 USDT fee, and hop 1's amountIn is that net number to the
1238        // last digit. Measuring the expectation gross against a realised amount that is
1239        // net therefore reported a shortfall on a PERFECT fill and shrank the next hop by
1240        // the fee a second time, stranding it in the bridge asset.
1241        //
1242        // Gross stays gross where gross is right: notionalQuote is what the order is
1243        // worth to the venue and is untouched, as is the notional cap built on it.
1244        let gross = amount * self.number_at(step, "expectedPrice", 0.0);
1245        let expected_fee = self.number_at(step, "expectedFeeCost", 0.0);
1246        if expected_fee <= 0.0 || expected_fee >= gross {
1247            // a fee at or above the whole proceeds is not a fee this class will
1248            // subtract: it would report an expectation of zero or less and turn every
1249            // fill into a halt
1250            return gross;
1251        }
1252        gross - expected_fee
1253    }
1254
1255    /// Reports whether a field holds a usable number, as opposed to holding
1256    /// zero or nothing at all.
1257    ///
1258    /// "The venue said zero" and "the venue said nothing" are different facts
1259    /// and used to produce the same number. Reuses `number_of` rather than
1260    /// re-deriving the coercion: "the value is usable" and "the value is
1261    /// present" must never disagree, and two copies of that rule is how they
1262    /// would.
1263    pub fn has_number_at(&self, container: &Value, key: &str) -> bool {
1264        let probe = Self::number_of(field(container, key), f64::NAN);
1265        Self::is_finite_number(probe)
1266    }
1267
1268    /// Compares what a step actually produced against what the route predicted,
1269    /// resizes every downstream hop, and returns the proceed-or-halt verdict.
1270    /// PURE — no I/O.
1271    ///
1272    /// The halt decision lives here rather than in the execution loop because it
1273    /// is a money decision, and six separate loops is six chances to omit it.
1274    pub fn reconcile_execution_step(
1275        &self,
1276        plan: &Value,
1277        step_index: i64,
1278        realised_out: f64,
1279    ) -> RouterResult<Value> {
1280        let steps = self.list_at(plan, "steps");
1281        if step_index < 0 || step_index as usize >= steps.len() {
1282            return Err(bad_request("reconcileExecutionStep: stepIndex is out of range"));
1283        }
1284        let step = &steps[step_index as usize];
1285        let hop_index = self.number_at(step, "hopIndex", 0.0);
1286        let tolerance =
1287            self.number_at(plan, "reconcileToleranceRatio", DEFAULT_RECONCILE_TOLERANCE);
1288        let expected_out = self.step_expected_out(step);
1289        let mut resized: Vec<Value> = Vec::new();
1290        if expected_out <= 0.0 {
1291            let mut verdict = HashMap::new();
1292            verdict.insert("stepIndex".into(), Value::Float(step_index as f64));
1293            verdict.insert("hopIndex".into(), Value::Float(hop_index));
1294            verdict.insert("expectedOut".into(), Value::Float(0.0));
1295            verdict.insert("realisedOut".into(), Value::Float(realised_out));
1296            verdict.insert("shortfall".into(), Value::Float(0.0));
1297            verdict.insert("shortfallRatio".into(), Value::Float(0.0));
1298            verdict.insert("scale".into(), Value::Float(0.0));
1299            verdict.insert("verdict".into(), Value::Str("halt".into()));
1300            verdict.insert("reason".into(), Value::Str("zero_expected_output".into()));
1301            verdict.insert("resizedSteps".into(), Value::List(resized));
1302            return Ok(Value::Map(verdict));
1303        }
1304        let mut shortfall = expected_out - realised_out;
1305        if shortfall < 0.0 {
1306            shortfall = 0.0;
1307        }
1308        let shortfall_ratio = shortfall / expected_out;
1309        // The downstream hops lost `shortfall` out of this hop's whole output,
1310        // not out of this leg's, so the scale is measured against the hop.
1311        let mut hop_expected_out = 0.0f64;
1312        // Shortfall already reported by this hop's OTHER legs. Each leg used to
1313        // compute a scale from the hop total and multiply the downstream amounts
1314        // by it, so a second leg scaled an already-scaled number: 80% and 60%
1315        // fills produced 0.9 x 0.8 = 0.72 of the next hop instead of the true
1316        // 0.70, sizing it for more than the wallet actually received and
1317        // inviting a spurious insufficient-funds halt on exactly the bridged
1318        // routes this class exists for. Reproduced at 144 against a true 140
1319        // before this changed.
1320        let mut prior_shortfall = 0.0f64;
1321        for other in steps.iter() {
1322            if self.number_at(other, "hopIndex", 0.0) == hop_index {
1323                hop_expected_out += self.step_expected_out(other);
1324                if self.number_at(other, "stepIndex", -1.0) != step_index as f64
1325                    && self.has_number_at(other, "realisedOut")
1326                {
1327                    let mut leg_shortfall =
1328                        self.step_expected_out(other) - self.number_at(other, "realisedOut", 0.0);
1329                    if leg_shortfall < 0.0 {
1330                        leg_shortfall = 0.0;
1331                    }
1332                    prior_shortfall += leg_shortfall;
1333                }
1334            }
1335        }
1336        // scale_before is what the downstream amounts have ALREADY been
1337        // multiplied by, so the factor applied here is the increment that takes
1338        // them from that to the hop's true cumulative scale. With one leg per
1339        // hop prior_shortfall is 0, scale_before is 1, and this is
1340        // arithmetically identical to what it replaced.
1341        let mut scale_before = 1.0f64;
1342        let mut scale_after = 1.0f64;
1343        if hop_expected_out > 0.0 {
1344            scale_before = (hop_expected_out - prior_shortfall) / hop_expected_out;
1345            scale_after = (hop_expected_out - prior_shortfall - shortfall) / hop_expected_out;
1346        }
1347        if scale_before <= 0.0 {
1348            // The hop already produced nothing; there is nothing left to scale
1349            // down.
1350            scale_before = 1.0;
1351            scale_after = 0.0;
1352        }
1353        let mut scale = scale_after / scale_before;
1354        if scale > 1.0 {
1355            // Never scale UP. An overfill is good news, but growing a downstream
1356            // order past the size that passed the safety check would place an
1357            // order nobody ever approved.
1358            scale = 1.0;
1359        }
1360        if scale < 0.0 {
1361            scale = 0.0;
1362        }
1363        for (i, other) in steps.iter().enumerate() {
1364            if self.number_at(other, "hopIndex", 0.0) <= hop_index {
1365                continue;
1366            }
1367            let previous_amount = self.number_at(other, "amount", 0.0);
1368            let amount = previous_amount * scale;
1369            let mut entry = HashMap::new();
1370            entry.insert(
1371                "stepIndex".into(),
1372                Value::Float(self.number_at(other, "stepIndex", i as f64)),
1373            );
1374            entry.insert("previousAmount".into(), Value::Float(previous_amount));
1375            entry.insert("amount".into(), Value::Float(amount));
1376            entry.insert(
1377                "notionalQuote".into(),
1378                Value::Float(amount * self.number_at(other, "expectedPrice", 0.0)),
1379            );
1380            resized.push(Value::Map(entry));
1381        }
1382        let mut verdict_text = "proceed";
1383        let mut reason = "within_tolerance";
1384        if realised_out <= 0.0 {
1385            verdict_text = "halt";
1386            reason = "nothing_filled";
1387        } else if shortfall_ratio > tolerance * (1.0 + TOLERANCE) {
1388            verdict_text = "halt";
1389            reason = "shortfall_exceeds_tolerance";
1390        }
1391        let mut verdict = HashMap::new();
1392        verdict.insert("stepIndex".into(), Value::Float(step_index as f64));
1393        verdict.insert("hopIndex".into(), Value::Float(hop_index));
1394        verdict.insert("expectedOut".into(), Value::Float(expected_out));
1395        verdict.insert("realisedOut".into(), Value::Float(realised_out));
1396        verdict.insert("shortfall".into(), Value::Float(shortfall));
1397        verdict.insert("shortfallRatio".into(), Value::Float(shortfall_ratio));
1398        verdict.insert("scale".into(), Value::Float(scale));
1399        verdict.insert("verdict".into(), Value::Str(verdict_text.into()));
1400        verdict.insert("reason".into(), Value::Str(reason.into()));
1401        verdict.insert("resizedSteps".into(), Value::List(resized));
1402        Ok(Value::Map(verdict))
1403    }
1404
1405    /// Writes a reconciliation's downstream resize back into the working steps.
1406    ///
1407    /// Records what this leg actually produced BEFORE resizing anything.
1408    /// `reconcile_execution_step` is pure and cannot remember across calls, so
1409    /// the hop's cumulative shortfall has to live on the steps themselves —
1410    /// this is what stops the next leg of the same hop compounding its scale
1411    /// onto an already-scaled amount.
1412    pub fn apply_resize(&self, steps: &mut [Value], reconciliation: &Value) {
1413        let reconciled_step = self.number_at(reconciliation, "stepIndex", -1.0);
1414        let realised_out = self.number_at(reconciliation, "realisedOut", 0.0);
1415        for step in steps.iter_mut() {
1416            if self.number_at(step, "stepIndex", -1.0) == reconciled_step {
1417                Self::put(step, "realisedOut", Value::Float(realised_out));
1418                break;
1419            }
1420        }
1421        let resized = self.list_at(reconciliation, "resizedSteps");
1422        for entry in &resized {
1423            let target = self.number_at(entry, "stepIndex", -1.0);
1424            let amount = self.number_at(entry, "amount", 0.0);
1425            let notional = self.number_at(entry, "notionalQuote", 0.0);
1426            for step in steps.iter_mut() {
1427                if self.number_at(step, "stepIndex", -1.0) == target {
1428                    Self::put(step, "amount", Value::Float(amount));
1429                    Self::put(step, "notionalQuote", Value::Float(notional));
1430                    break;
1431                }
1432            }
1433        }
1434    }
1435
1436    /// Sets a key on a `Value::Dict` in place, through `Arc::make_mut` so the
1437    /// copy-on-write only deep-copies when the map is actually shared.
1438    ///
1439    /// Public because callers building a route by hand need it too — stamping
1440    /// `clientRequestedFrom`/`clientRequestedTo` onto a route obtained by some
1441    /// route other than `fetch_route`, for one. The other five ports get this
1442    /// for free from assignment into a dictionary.
1443    pub fn set_key(container: &mut Value, key: &str, value: Value) {
1444        Self::put(container, key, value)
1445    }
1446
1447    fn put(container: &mut Value, key: &str, value: Value) {
1448        if let Value::Dict(map) = container {
1449            Arc::make_mut(map).insert(key.to_string(), value);
1450        }
1451    }
1452}
1453
1454// ---------------------------------------------------------------------------
1455// PURE: build_unwind_plan
1456// ---------------------------------------------------------------------------
1457
1458impl OrderRouter {
1459    /// Accumulates a signed amount into the (exchangeId, asset) position list,
1460    /// appending in first-seen order.
1461    ///
1462    /// `produced` is true when this step PRODUCED the asset, which is the only
1463    /// kind of step an unwind can reverse.
1464    fn add_position(
1465        &self,
1466        positions: &mut Vec<Value>,
1467        exchange_id: &str,
1468        asset: &str,
1469        amount: f64,
1470        source: &Value,
1471        produced: bool,
1472    ) {
1473        for position in positions.iter_mut() {
1474            let same_venue = self.string_at(position, "exchangeId", "") == exchange_id;
1475            let same_asset = self.string_at(position, "asset", "") == asset;
1476            if same_venue && same_asset {
1477                let running = self.number_at(position, "amount", 0.0) + amount;
1478                Self::put(position, "amount", Value::Float(running));
1479                let existing = self.dict_at(position, "source");
1480                let empty = existing.as_map().map(|m| m.is_empty()).unwrap_or(true);
1481                if produced && empty {
1482                    Self::put(position, "source", source.clone());
1483                }
1484                return;
1485            }
1486        }
1487        // The source must be the step that PRODUCED the asset, never one that
1488        // consumed it: reversing a step that spent your USDT would sell the
1489        // wrong side of the wrong market. Walking the results backwards, the
1490        // first producing step seen is the last one that ran, which is exactly
1491        // the order an unwind undoes first.
1492        let initial_source =
1493            if produced { source.clone() } else { Value::Map(HashMap::new()) };
1494        let mut entry = HashMap::new();
1495        entry.insert("exchangeId".into(), Value::Str(exchange_id.to_string().into()));
1496        entry.insert("asset".into(), Value::Str(asset.to_string().into()));
1497        entry.insert("amount".into(), Value::Float(amount));
1498        entry.insert("source".into(), initial_source);
1499        positions.push(Value::Map(entry));
1500    }
1501
1502    /// Given a halted execution report, computes the reverse orders that sell
1503    /// each stranded residual back toward the original from-asset, on the venue
1504    /// that actually holds it. PURE — no I/O.
1505    ///
1506    /// NEVER automatic: the result carries `requiresConfirmation` and nothing in
1507    /// this class executes it.
1508    pub fn build_unwind_plan(&self, report: &Value) -> Value {
1509        let from_asset = self.string_at(report, "from", "");
1510        let to_asset = self.string_at(report, "to", "");
1511        let slippage_bps = self.number_at(report, "slippageBps", DEFAULT_SLIPPAGE_BPS);
1512        let results = self.list_at(report, "steps");
1513        // Net position per (exchangeId, asset). Held in a VECTOR rather than a
1514        // map because the output order must be identical in six languages and
1515        // map iteration order is not.
1516        let mut positions: Vec<Value> = Vec::new();
1517        for result in results.iter().rev() {
1518            let exchange_id = self.string_at(result, "exchangeId", "");
1519            let out_asset = self.string_at(result, "outAsset", "");
1520            let out_amount = self.number_at(result, "outAmount", 0.0);
1521            if !out_asset.is_empty() && out_amount > 0.0 {
1522                self.add_position(&mut positions, &exchange_id, &out_asset, out_amount, result, true);
1523            }
1524            let in_asset = self.string_at(result, "inAsset", "");
1525            let in_amount = self.number_at(result, "inAmount", 0.0);
1526            if !in_asset.is_empty() && in_amount > 0.0 {
1527                // What a later hop consumed on this venue is not a residual.
1528                // Netting is per venue: assets sitting on a venue the route
1529                // never spent them on stay stranded, because this class never
1530                // moves funds between venues.
1531                self.add_position(&mut positions, &exchange_id, &in_asset, -in_amount, result, false);
1532            }
1533        }
1534        let mut steps: Vec<Value> = Vec::new();
1535        let mut unresolved: Vec<Value> = Vec::new();
1536        let mut residual_count = 0i64;
1537        for position in &positions {
1538            let asset = self.string_at(position, "asset", "");
1539            let amount = self.number_at(position, "amount", 0.0);
1540            let exchange_id = self.string_at(position, "exchangeId", "");
1541            if amount <= 0.0 {
1542                continue;
1543            }
1544            if asset == from_asset {
1545                // Already home.
1546                continue;
1547            }
1548            residual_count += 1;
1549            let source = self.dict_at(position, "source");
1550            let symbol = self.string_at(&source, "symbol", "");
1551            let source_side = self.string_at(&source, "side", "");
1552            let mut price = self.number_at(&source, "averagePrice", 0.0);
1553            if price <= 0.0 {
1554                price = self.number_at(&source, "expectedPrice", 0.0);
1555            }
1556            if symbol.is_empty() || (source_side != "buy" && source_side != "sell") {
1557                unresolved.push(Self::unresolved_entry(&exchange_id, &asset, amount, "no_source_market"));
1558                continue;
1559            }
1560            if price <= 0.0 {
1561                unresolved.push(Self::unresolved_entry(&exchange_id, &asset, amount, "no_price"));
1562                continue;
1563            }
1564            // Reverse the order that created the residual: a buy left you
1565            // holding base, so sell it back; a sell left you holding quote, so
1566            // buy the base back with it.
1567            //
1568            // The counter asset is whatever the reversed order gives back, which
1569            // is exactly what the original order spent.
1570            let counter_asset = self.string_at(&source, "inAsset", "");
1571            let side;
1572            let unwind_amount;
1573            let market_base;
1574            let market_quote;
1575            if source_side == "buy" {
1576                side = "sell";
1577                market_base = self.string_at(&source, "outAsset", "");
1578                market_quote = self.string_at(&source, "inAsset", "");
1579            } else {
1580                side = "buy";
1581                market_base = self.string_at(&source, "inAsset", "");
1582                market_quote = self.string_at(&source, "outAsset", "");
1583            }
1584            // The limit price comes FIRST, because the buy below is sized on it.
1585            let limit_price = if side == "buy" {
1586                price * (1.0 + slippage_bps / 10000.0)
1587            } else {
1588                price * (1.0 - slippage_bps / 10000.0)
1589            };
1590            if side == "buy" {
1591                // Size the buy on the price it is actually PLACED at, not on the
1592                // expected price. A residual of 44.5 USDT sized at 0.089 is 500
1593                // DOGE, but the order goes out at 0.0892225 and would need 44.61
1594                // USDT to fill - 0.11 more than the venue holds. The venue rejects
1595                // it for insufficient funds, or fills it partially and leaves the
1596                // rest of the stranded money stranded. Dividing by limit_price
1597                // spends at most the residual.
1598                unwind_amount = amount / limit_price;
1599            } else {
1600                unwind_amount = amount;
1601            }
1602            let mut step = HashMap::new();
1603            step.insert("stepIndex".into(), Value::Float(steps.len() as f64));
1604            step.insert("exchangeId".into(), Value::Str(exchange_id.clone().into()));
1605            step.insert("symbol".into(), Value::Str(symbol.into()));
1606            step.insert("side".into(), Value::Str(side.to_string().into()));
1607            // base and quote are carried so that an unwind plan can be fed
1608            // straight back into check_execution_plan_safety: unwinding is
1609            // trading, and it is subject to the same 25 USD cap.
1610            step.insert("base".into(), Value::Str(market_base.into()));
1611            step.insert("quote".into(), Value::Str(market_quote.into()));
1612            step.insert("asset".into(), Value::Str(asset.clone().into()));
1613            step.insert("counterAsset".into(), Value::Str(counter_asset.clone().into()));
1614            step.insert("amount".into(), Value::Float(unwind_amount));
1615            step.insert("expectedPrice".into(), Value::Float(price));
1616            step.insert("limitPrice".into(), Value::Float(limit_price));
1617            // Notional at the price the order is actually placed at: this plan is
1618            // fed back into check_execution_plan_safety, and a cap that was
1619            // checked against the expected price under-counts what the buy above
1620            // really spends.
1621            step.insert(
1622                "notionalQuote".into(),
1623                Value::Float(unwind_amount * limit_price),
1624            );
1625            step.insert("reachesFrom".into(), Value::Bool(counter_asset == from_asset));
1626            step.insert("isDestination".into(), Value::Bool(asset == to_asset));
1627            steps.push(Value::Map(step));
1628        }
1629        let mut plan = HashMap::new();
1630        plan.insert("from".into(), Value::Str(from_asset.into()));
1631        plan.insert("to".into(), Value::Str(to_asset.into()));
1632        plan.insert("halted".into(), Value::Bool(self.bool_at(report, "halted", false)));
1633        plan.insert("haltReason".into(), Value::Str(self.string_at(report, "haltReason", "").into()));
1634        plan.insert("residualCount".into(), Value::Float(residual_count as f64));
1635        plan.insert("requiresConfirmation".into(), Value::Bool(true));
1636        plan.insert("automatic".into(), Value::Bool(false));
1637        plan.insert("steps".into(), Value::List(steps));
1638        plan.insert("unresolved".into(), Value::List(unresolved));
1639        Value::Map(plan)
1640    }
1641
1642    fn unresolved_entry(exchange_id: &str, asset: &str, amount: f64, reason: &str) -> Value {
1643        let mut entry = HashMap::new();
1644        entry.insert("exchangeId".into(), Value::Str(exchange_id.to_string().into()));
1645        entry.insert("asset".into(), Value::Str(asset.to_string().into()));
1646        entry.insert("amount".into(), Value::Float(amount));
1647        entry.insert("reason".into(), Value::Str(reason.to_string().into()));
1648        Value::Map(entry)
1649    }
1650}
1651
1652// ---------------------------------------------------------------------------
1653// I/O: the router HTTP client
1654// ---------------------------------------------------------------------------
1655
1656/// The query keys forwarded to GET /route, in a fixed order so that two ports
1657/// build a byte-identical URL.
1658const ROUTE_QUERY_KEYS: [&str; 14] = [
1659    "amountIn", "amountOut", "strategy", "maxVenues", "bridges", "exchanges", "balances",
1660    "balanceMode", "includeQuotes", "includeFees", "certified", "requireFullFill",
1661    "hopPenaltyBps", "minLegNotional",
1662];
1663
1664impl OrderRouter {
1665    /// Percent-encodes exactly what JavaScript's `encodeURIComponent` leaves
1666    /// alone, so six ports produce the same URL byte for byte.
1667    ///
1668    /// Deliberately not `urlencoding::encode`: that is `application/x-www-form-
1669    /// urlencoded`, which escapes `!`, `'`, `(`, `)`, `*` and renders a space as
1670    /// `+`. `encodeURIComponent` does neither. A route whose bridge list or
1671    /// balances string contains any of those would sign a different URL here
1672    /// than in the other five.
1673    fn encode_uri_component(text: &str) -> String {
1674        let mut out = String::with_capacity(text.len());
1675        for byte in text.as_bytes() {
1676            let c = *byte;
1677            let unreserved = c.is_ascii_alphanumeric()
1678                || matches!(c, b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')');
1679            if unreserved {
1680                out.push(c as char);
1681            } else {
1682                out.push_str(&format!("%{:02X}", c));
1683            }
1684        }
1685        out
1686    }
1687
1688    /// Renders one query parameter's value the way the other five ports do.
1689    fn query_text(&self, value: &Value) -> RouterResult<String> {
1690        Ok(match value {
1691            Value::Bool(flag) => (if *flag { "true" } else { "false" }).to_string(),
1692            Value::Int(n) => self.format_number(*n as f64)?,
1693            Value::Float(n) => self.format_number(*n)?,
1694            Value::Arr(items) => items
1695                .iter()
1696                .map(|item| match item {
1697                    Value::Str(s) => s.to_string(),
1698                    other => format!("{other:?}"),
1699                })
1700                .collect::<Vec<String>>()
1701                .join(","),
1702            Value::Str(s) => s.to_string(),
1703            //  REFUSED rather than debug-formatted. This used to end in `format!("{other:?}")`,
1704            //  which renders a map as Rust's own debug form and ships it: the server then
1705            //  rejects a value naming neither what was sent nor what was wanted. `balances` is
1706            //  the one param with a meaningful map form and it is rendered before it gets here.
1707            other => {
1708                return Err(bad_request(&format!(
1709                    "OrderRouter: a route parameter must be a string, number, boolean or list; got {other:?}"
1710                )))
1711            }
1712        })
1713    }
1714
1715    /// Refuses neither-or-both amounts before a byte reaches the wire.
1716    ///
1717    /// Shared by `fetch_route` and `watch_route` because the service runs ONE parser
1718    /// for both and they must not disagree about what is valid.
1719    pub fn assert_route_amounts(params: &Value, method: &str) -> RouterResult<()> {
1720        let has_amount_in = field(params, "amountIn").is_some();
1721        let has_amount_out = field(params, "amountOut").is_some();
1722        if has_amount_in == has_amount_out {
1723            return Err(bad_request(&format!(
1724                "{method} requires exactly one of amountIn or amountOut"
1725            )));
1726        }
1727        Ok(())
1728    }
1729
1730    /// Builds the wss url for `GET /stream/route`, refusing what the endpoint refuses.
1731    pub fn stream_url(&self, from_asset: &str, to_asset: &str, params: &Value) -> RouterResult<String> {
1732        if from_asset.is_empty() || to_asset.is_empty() {
1733            return Err(arguments_required("watchRoute requires fromAsset and toAsset"));
1734        }
1735        Self::assert_route_amounts(params, "watchRoute")?;
1736        // REFUSED HERE, not by the server closing the socket on us. A stream is held open
1737        // for minutes and carries no channel to update the holdings it was opened with, so
1738        // every frame after the first would price a portfolio the caller may already have
1739        // traded away.
1740        if field(params, "balances").is_some() {
1741            return Err(bad_request(
1742                "OrderRouter: /stream/route does not accept balances — a socket outlives the holdings it was opened with. Use fetch_route",
1743            ));
1744        }
1745        if field(params, "balanceMode").is_some() {
1746            return Err(bad_request(
1747                "OrderRouter: /stream/route does not accept balanceMode, because it does not accept balances. Use fetch_route",
1748            ));
1749        }
1750        // the same venue filter fetch_route applies. A router built with venues can only
1751        // execute on those, so a stream that quoted the rest would hand back routes its own
1752        // executor must refuse. The caller's own exchanges parameter still wins.
1753        let scoped_params: Value;
1754        let params = if !self.venues.is_empty() && field(params, "exchanges").is_none() {
1755            let mut scoped = params.as_map().cloned().unwrap_or_default();
1756            let stored_ids: Vec<String> = self.venues.keys().cloned().collect();
1757            scoped.insert("exchanges".to_string(), Value::from(stored_ids.join(",")));
1758            scoped_params = Value::map(scoped);
1759            &scoped_params
1760        } else {
1761            params
1762        };
1763        // includeQuotes is deliberately NOT defaulted: the service defaults it to false on
1764        // this endpoint and true on the REST one, and the query builder omits what the
1765        // caller did not set.
1766        let mut query = format!(
1767            "from={}&to={}",
1768            Self::encode_uri_component(&from_asset.to_uppercase()),
1769            Self::encode_uri_component(&to_asset.to_uppercase())
1770        );
1771        for key in ROUTE_QUERY_KEYS.iter() {
1772            let value = match field(params, key) {
1773                Some(found) => found,
1774                None => continue,
1775            };
1776            let text = self.query_text(value)?;
1777            query.push('&');
1778            query.push_str(key);
1779            query.push('=');
1780            query.push_str(&Self::encode_uri_component(&text));
1781        }
1782        let base = if let Some(rest) = self.base_url.strip_prefix("https://") {
1783            format!("wss://{rest}")
1784        } else if let Some(rest) = self.base_url.strip_prefix("http://") {
1785            format!("ws://{rest}")
1786        } else {
1787            self.base_url.clone()
1788        };
1789        Ok(format!("{base}/stream/route?{query}"))
1790    }
1791
1792    /// Maps a websocket close code onto the error the same refusal raises over REST.
1793    /// `None` for an ordinary close.
1794    pub fn stream_close_error(&self, code: u16, last_frame: &Value) -> Option<ExchangeError> {
1795        if code == 1008 {
1796            // the service sends ONE json frame carrying the same `error` string the REST
1797            // endpoint would have answered a 400 with — including a bridged exact-out,
1798            // which REST refuses as a 501. Same refusal, same error.
1799            let message = self.string_at(last_frame, "error", "the router rejected the stream request");
1800            return Some(bad_request(&format!("OrderRouter: {message}")));
1801        }
1802        if code == 1013 {
1803            // try again later: the cache was cold when the socket was accepted. A stream
1804            // carries no status codes once open, so this is the only way the service can say
1805            // what a REST 503 says — and it is the same retry, not a fault.
1806            let message = self.string_at(last_frame, "error", "the router cache is cold");
1807            let cold = self.cold_cache_suffix(last_frame);
1808            return Some(ExchangeError::new(
1809                "ExchangeNotAvailable",
1810                format!("OrderRouter: {message}{cold}"),
1811            ));
1812        }
1813        if code == 1000 || code == 1005 || code == 0 {
1814            // a clean close, or one with no code, which is what a caller-requested stop
1815            // looks like from here
1816            return None;
1817        }
1818        Some(ExchangeError::new(
1819            "ExchangeNotAvailable",
1820            format!("OrderRouter: the route stream closed with code {code}"),
1821        ))
1822    }
1823
1824    /// The same route as `fetch_route`, pushed over a websocket whenever any market it
1825    /// depends on moves.
1826    ///
1827    /// BLOCKS until the stream ends: `on_route` is how you read it. Return `"stop"` from the
1828    /// hook to close the socket cleanly; the call then returns the last route it saw. Every
1829    /// frame is stamped with the same client-side keys `fetch_route` stamps, so it can go
1830    /// straight into `build_execution_plan`.
1831    ///
1832    /// `balances` and `balanceMode` are refused — see `stream_url` for why — and
1833    /// `includeQuotes` is left to the endpoint's own default, which is false here.
1834    ///
1835    /// Unlike `execute`'s step hook, this one is a plain parameter rather than something
1836    /// stored on the client: nothing here has to survive in a `Value`, so the closed-enum
1837    /// workaround `set_on_step` needs does not apply.
1838    pub async fn watch_route(
1839        &self,
1840        from_asset: &str,
1841        to_asset: &str,
1842        params: &Value,
1843        on_route: &mut dyn FnMut(&Value) -> String,
1844    ) -> RouterResult<Value> {
1845        use futures::StreamExt;
1846        use tokio_tungstenite::tungstenite::client::IntoClientRequest;
1847        use tokio_tungstenite::tungstenite::Message;
1848
1849        // built BEFORE the socket, so a refusal this client can make itself costs no
1850        // connection
1851        let url = self.stream_url(from_asset, to_asset, params)?;
1852        let mut request = url.as_str().into_client_request().map_err(|e| {
1853            ExchangeError::new("ExchangeNotAvailable", format!("OrderRouter: {e}"))
1854        })?;
1855        {
1856            let headers = request.headers_mut();
1857            // omitted entirely when absent: an empty x-api-key reads as a malformed
1858            // credential to a server that still authenticates, not as an anonymous caller
1859            if !self.api_key.is_empty() {
1860                let key = self.api_key.parse().map_err(|_| {
1861                    bad_request("OrderRouter: the apiKey cannot be sent as a header")
1862                })?;
1863                headers.insert("x-api-key", key);
1864            }
1865            let request_id = self.string_at(params, "requestId", "");
1866            if !request_id.is_empty() && request_id.len() <= 200 {
1867                if let Ok(value) = request_id.parse() {
1868                    headers.insert("x-request-id", value);
1869                }
1870            }
1871            // a userAgent that is not a valid header value is skipped, like x-request-id
1872            if !self.user_agent.is_empty() {
1873                if let Ok(value) = self.user_agent.parse() {
1874                    headers.insert("user-agent", value);
1875                }
1876            }
1877        }
1878        let (socket, _response) = match tokio_tungstenite::connect_async(request).await {
1879            Ok(pair) => pair,
1880            Err(e) => return Err(self.stream_handshake_error(&e.to_string())),
1881        };
1882        let (_write, mut read) = socket.split();
1883        let upper_from = from_asset.to_uppercase();
1884        let upper_to = to_asset.to_uppercase();
1885        let required_full_fill = self.bool_at(params, "requireFullFill", false);
1886        let mut last_frame = Value::Map(HashMap::new());
1887        let mut last_route = Value::Map(HashMap::new());
1888        while let Some(next) = read.next().await {
1889            let message = match next {
1890                Ok(found) => found,
1891                Err(_) => break,
1892            };
1893            match message {
1894                Message::Close(frame) => {
1895                    let code = frame.map(|f| u16::from(f.code)).unwrap_or(0);
1896                    return match self.stream_close_error(code, &last_frame) {
1897                        Some(failure) => Err(failure),
1898                        None => Ok(last_route),
1899                    };
1900                }
1901                Message::Text(text) => {
1902                    let parsed: serde_json::Value = serde_json::from_str(&text)
1903                        .map_err(|_| exchange_error("OrderRouter stream sent a non-JSON frame"))?;
1904                    let mut frame = Value::from_json(&parsed);
1905                    // Held whether or not it looks like a route: a REFUSAL arrives as one
1906                    // ordinary frame and only the close code that follows says it was one.
1907                    last_frame = frame.clone();
1908                    if !self.string_at(&frame, "error", "").is_empty() {
1909                        // not a route — wait for the close code to say which refusal it is
1910                        continue;
1911                    }
1912                    // the same client-side stamps fetch_route applies, for the same reason:
1913                    // every frame is a route build_execution_plan may be handed
1914                    Self::put(&mut frame, "clientRequestedFrom", Value::Str(upper_from.clone().into()));
1915                    Self::put(&mut frame, "clientRequestedTo", Value::Str(upper_to.clone().into()));
1916                    Self::put(
1917                        &mut frame,
1918                        "clientRequestedRequireFullFill",
1919                        Value::Bool(required_full_fill),
1920                    );
1921                    last_route = frame.clone();
1922                    if on_route(&frame) == "stop" {
1923                        return Ok(last_route);
1924                    }
1925                }
1926                _ => {
1927                    // ping/pong/binary: tungstenite answers pings itself, and this endpoint
1928                    // sends nothing binary
1929                }
1930            }
1931        }
1932        // the stream ended without a close frame
1933        match self.stream_close_error(0, &last_frame) {
1934            Some(failure) => Err(failure),
1935            None => Ok(last_route),
1936        }
1937    }
1938
1939    /// Maps a failed websocket upgrade onto the same error the REST path raises for that
1940    /// status. 401, 429 and 503 happen BEFORE the upgrade, so they never arrive as close
1941    /// codes, and the transport reports them only as text.
1942    pub fn stream_handshake_error(&self, message: &str) -> ExchangeError {
1943        if message.contains("401") {
1944            return ExchangeError::new("AuthenticationError", "OrderRouter: unauthorized".to_string());
1945        }
1946        if message.contains("403") {
1947            //  same ipv4-only refusal as the REST path, and the same reason not to call it an
1948            //  authentication failure: this service has no credential to get wrong
1949            return ExchangeError::new("PermissionDenied", "OrderRouter: the router resolved this client to a non-IPv4 address and refused it; reach it over IPv4".to_string());
1950        }
1951        if message.contains("429") {
1952            return ExchangeError::new("RateLimitExceeded", "OrderRouter: rate limit exceeded".to_string());
1953        }
1954        ExchangeError::new("ExchangeNotAvailable", format!("OrderRouter: {message}"))
1955    }
1956
1957    /// Builds the fully-formed `/route` url, including the query string.
1958    ///
1959    /// Split out from `fetch_route` so the URL construction — the part that has
1960    /// to be byte-identical across six languages — is testable without a
1961    /// network.
1962    pub fn build_route_url(
1963        &self,
1964        from_asset: &str,
1965        to_asset: &str,
1966        params: &Value,
1967    ) -> RouterResult<String> {
1968        if from_asset.is_empty() || to_asset.is_empty() {
1969            return Err(arguments_required("fetchRoute requires fromAsset and toAsset"));
1970        }
1971        Self::assert_route_amounts(params, "fetchRoute")?;
1972        let mut query = format!(
1973            "from={}&to={}",
1974            Self::encode_uri_component(&from_asset.to_uppercase()),
1975            Self::encode_uri_component(&to_asset.to_uppercase())
1976        );
1977        for key in ROUTE_QUERY_KEYS.iter() {
1978            let value = match field(params, key) {
1979                Some(found) => found,
1980                None => continue,
1981            };
1982            let text = self.query_text(value)?;
1983            query.push('&');
1984            query.push_str(key);
1985            query.push('=');
1986            query.push_str(&Self::encode_uri_component(&text));
1987        }
1988        Ok(format!("{}/route?{}", self.base_url, query))
1989    }
1990
1991    /// Builds the `POST /route` JSON body — the same fields as the query
1992    /// string, by the same names.
1993    ///
1994    /// HOLDINGS NEVER TRAVEL IN A URL. The service scrubs balances out of its
1995    /// own logs, but a URL does not stay inside that process: the standard
1996    /// deployment puts a reverse proxy in front, and nginx, an ALB and a CDN all
1997    /// log the full request line by default. So do browser history and
1998    /// client-side tracing, and a `Referer` carries it off-origin. None of that
1999    /// is reachable from the router, and no amount of in-process redaction fixes
2000    /// it — the fix is for the wallet not to be in the URL.
2001    pub fn build_route_body(
2002        &self,
2003        from_asset: &str,
2004        to_asset: &str,
2005        params: &Value,
2006    ) -> RouterResult<Value> {
2007        if from_asset.is_empty() || to_asset.is_empty() {
2008            return Err(arguments_required("fetchRoute requires fromAsset and toAsset"));
2009        }
2010        Self::assert_route_amounts(params, "fetchRoute")?;
2011        let mut body = Value::Dict(Arc::new(HashMap::new()));
2012        Self::put(&mut body, "from", Value::Str(from_asset.to_uppercase().into()));
2013        Self::put(&mut body, "to", Value::Str(to_asset.to_uppercase().into()));
2014        for key in ROUTE_QUERY_KEYS.iter() {
2015            let value = match field(params, key) {
2016                Some(found) => found,
2017                None => continue,
2018            };
2019            // numbers and booleans travel as themselves — the body is JSON and
2020            // the service's own schema types amountIn as a number. Everything
2021            // else uses the same text form the query string uses, so one handler
2022            // reads both verbs.
2023            //  balances FIRST, before the number/boolean shortcut: a numeric balances is not
2024            //  a wallet, and letting it through as a JSON number sent it to the server to be
2025            //  refused there.
2026            let encoded = if *key == "balances" {
2027                Value::Str(self.render_balances(value)?.into())
2028            } else {
2029                match value {
2030                    Value::Bool(flag) => Value::Bool(*flag),
2031                    Value::Int(n) => Value::Int(*n),
2032                    Value::Float(n) => Value::Float(*n),
2033                    other => Value::Str(self.query_text(other)?.into()),
2034                }
2035            };
2036            Self::put(&mut body, key, encoded);
2037        }
2038        Ok(body)
2039    }
2040
2041    /// Asks the router how to convert one asset into another, over the venues
2042    /// and bridges it has live books for.
2043    ///
2044    /// An unroutable pair comes back as a RouteResult carrying an
2045    /// `unroutableReason`, NOT as an error: refusing to quote is a deliberate
2046    /// outcome, not a failure.
2047    pub async fn fetch_route(
2048        &self,
2049        from_asset: &str,
2050        to_asset: &str,
2051        params: &Value,
2052    ) -> RouterResult<Value> {
2053        //  THE STORED VENUES ANSWER TWO QUESTIONS HERE, and a caller-supplied value wins both.
2054        //  `exchanges` is cheap and always right: a route naming a venue you hold no keys for
2055        //  is not a route you can take. `balances` reads every venue's wallet, so it happens
2056        //  only when venues were installed and the caller supplied none of their own.
2057        let owned_params;
2058        let params = if self.venues.is_empty() {
2059            params
2060        } else {
2061            let mut map = match params.as_map() {
2062                Some(existing) => existing.clone(),
2063                None => HashMap::new(),
2064            };
2065            if field(params, "exchanges").is_none() {
2066                let ids: Vec<String> = self.venues.keys().cloned().collect();
2067                map.insert("exchanges".into(), Value::Str(ids.join(",").into()));
2068            }
2069            if self.track_balances && field(params, "balances").is_none() {
2070                map.insert("balances".into(), Value::Str(self.load_balances(false).await?.into()));
2071            }
2072            owned_params = Value::Map(map);
2073            &owned_params
2074        };
2075        // A request carrying no holdings still goes as a GET: cacheable,
2076        // linkable, and what every existing caller already uses. One that
2077        // carries them is POSTed — see build_route_body for why.
2078        let sends_balances = field(params, "balances").is_some();
2079        // an audit id the caller chose, so their log and the router's decision log can be
2080        // joined. The service mints one when this is absent, and echoes whichever it used.
2081        let request_id = self.string_at(params, "requestId", "");
2082        let mut route = if sends_balances {
2083            let body = self.build_route_body(from_asset, to_asset, params)?;
2084            self.request(&format!("{}/route", self.base_url), "POST", &body, &request_id).await?
2085        } else {
2086            let url = self.build_route_url(from_asset, to_asset, params)?;
2087            self.request(&url, "GET", &Value::Null, &request_id).await?
2088        };
2089        if sends_balances {
2090            // CHECKED HERE, not only in fetch_route_with_balances. `balances` is a
2091            // documented parameter of this method, and a caller who passes it directly was
2092            // getting no verification at all — the same silent failure, one call lower down.
2093            self.assert_balances_applied(&route, params)?;
2094        }
2095        // What THIS CLIENT asked for, stamped client-side so check_execution_plan_safety can
2096        // tell a flag that was honoured from one that was lost in transit. requireFullFill is
2097        // the one route parameter that fails OPEN.
2098        Self::put(
2099            &mut route,
2100            "clientRequestedRequireFullFill",
2101            Value::Bool(self.bool_at(params, "requireFullFill", false)),
2102        );
2103        // Stamp what THIS CLIENT asked for, client-side, so build_execution_plan
2104        // can check the answer against the question. Everything else in the
2105        // response — from, to, pair, side — is the server's word for it, and the
2106        // plan used to trust all of it: a compromised or simply buggy router
2107        // could name any real market and the safety checks, which only test
2108        // internal consistency against that market, would pass it under the
2109        // 25 USD cap.
2110        Self::put(&mut route, "clientRequestedFrom", Value::Str(from_asset.to_uppercase().into()));
2111        Self::put(&mut route, "clientRequestedTo", Value::Str(to_asset.to_uppercase().into()));
2112        Ok(route)
2113    }
2114
2115    /// Errors unless the router confirmed it read the holdings that were sent.
2116    pub fn assert_balances_applied(&self, route: &Value, params: &Value) -> RouterResult<()> {
2117        if !self.bool_at(params, "requireBalancesApplied", true) {
2118            // the caller opted out, with their eyes open
2119            return Ok(());
2120        }
2121        // /route declares its query without a JSON schema, so a router that predates the
2122        // balances feature IGNORES them and answers byte-identically to one that never
2123        // received any.
2124        if !self.string_at(route, "balancesApplied", "").is_empty() {
2125            return Ok(());
2126        }
2127        // An EMPTY echo is ambiguous on its own: "" is also the honest answer to `balances=`
2128        // meaning "I hold nothing". balanceEntryCount disambiguates by PRESENCE, not by
2129        // value — a current server sends 0, a server that never heard of the feature sends
2130        // nothing at all. This is the case the old check skipped outright.
2131        if self.number_at(route, "balanceEntryCount", -1.0) >= 0.0 {
2132            return Ok(());
2133        }
2134        Err(exchange_error(
2135            "OrderRouter did not echo balancesApplied: the balances were ignored, so this route is not funded-aware",
2136        ))
2137    }
2138
2139    /// Renders a retry interval as a message suffix, empty when the service sent
2140    /// none.
2141    fn retry_suffix(retry_after: &str) -> String {
2142        if retry_after.is_empty() {
2143            return String::new();
2144        }
2145        format!(", retry after {retry_after}s")
2146    }
2147
2148    /// Renders the book counts a `cache_cold` refusal carries, so a caller can
2149    /// log why it was refused.
2150    fn cold_cache_suffix(&self, body: &Value) -> String {
2151        let total = self.number_at(body, "bookCount", 0.0);
2152        if total <= 0.0 {
2153            return String::new();
2154        }
2155        let fresh = self.number_at(body, "freshCount", 0.0);
2156        let needed = self.number_at(body, "minFreshBooksForReady", 0.0);
2157        match (
2158            self.format_number(fresh),
2159            self.format_number(total),
2160            self.format_number(needed),
2161        ) {
2162            (Ok(fresh_text), Ok(total_text), Ok(needed_text)) => {
2163                format!(" ({fresh_text} of {total_text} books fresh, {needed_text} needed)")
2164            }
2165            // a count this class cannot render is a count it will not guess at:
2166            // the suffix is dropped whole rather than reporting a number that
2167            // differs from what the other five ports would print
2168            _ => String::new(),
2169        }
2170    }
2171
2172    /// Performs the authenticated call and maps router status codes onto ccxt
2173    /// error kinds.
2174    pub async fn request(
2175        &self,
2176        url: &str,
2177        method: &str,
2178        request_body: &Value,
2179        request_id: &str,
2180    ) -> RouterResult<Value> {
2181        let client = reqwest::Client::builder()
2182            .timeout(std::time::Duration::from_millis(self.timeout_ms.max(0.0) as u64))
2183            .build()
2184            .map_err(|e| ExchangeError::new("ExchangeNotAvailable", format!("OrderRouter could not build an http client: {e}")))?;
2185        let mut builder = if method == "POST" {
2186            client
2187                .post(url)
2188                .header("Content-Type", "application/json")
2189                .body(request_body.to_json().to_string())
2190        } else {
2191            client.get(url)
2192        };
2193        builder = builder.header("Accept", "application/json");
2194        if !self.api_key.is_empty() {
2195            builder = builder.header("x-api-key", &self.api_key);
2196        }
2197        if !request_id.is_empty() && request_id.len() <= 200 {
2198            // the service caps this at 200 characters and mints its own when absent, so a
2199            // longer one is dropped rather than sent and rejected
2200            builder = builder.header("x-request-id", request_id);
2201        }
2202        if !self.user_agent.is_empty() {
2203            // only when configured: an empty value keeps reqwest's own default rather than
2204            // sending a blank one. (Browsers forbid setting User-Agent, so the TS port silently
2205            // drops it there; no such restriction applies here.)
2206            builder = builder.header("User-Agent", &self.user_agent);
2207        }
2208        let response = builder.send().await;
2209        let response = match response {
2210            Ok(found) => found,
2211            Err(e) => {
2212                if e.is_timeout() {
2213                    return Err(ExchangeError::new(
2214                        "RequestTimeout",
2215                        format!("OrderRouter request timed out after {}ms", self.timeout_ms),
2216                    ));
2217                }
2218                return Err(ExchangeError::new(
2219                    "ExchangeNotAvailable",
2220                    format!("OrderRouter request failed: {e}"),
2221                ));
2222            }
2223        };
2224        let status = response.status().as_u16();
2225        // READ BEFORE THE BODY. On a 429 or a 503 this is the only number that
2226        // says how long to wait, and a caller told "unavailable" with no
2227        // interval retries blind.
2228        //
2229        // The two headers are NOT interchangeable and are kept apart on purpose.
2230        // retry-after answers "how long until this particular refusal clears";
2231        // x-ratelimit-reset answers "how long until the rate-limit window rolls
2232        // over", which is the same question ONLY on a 429. Using the window as a
2233        // fallback for a cold cache would tell a caller to wait a full minute for
2234        // a cache that repopulates in seconds.
2235        let header_text = |name: &str| -> String {
2236            response
2237                .headers()
2238                .get(name)
2239                .and_then(|value| value.to_str().ok())
2240                .unwrap_or("")
2241                .to_string()
2242        };
2243        let retry_after = header_text("retry-after");
2244        let rate_limit_reset = header_text("x-ratelimit-reset");
2245        let text = response.text().await.map_err(|e| {
2246            ExchangeError::new("ExchangeNotAvailable", format!("OrderRouter request failed: {e}"))
2247        })?;
2248        let parsed: serde_json::Value = serde_json::from_str(&text)
2249            .map_err(|_| exchange_error("OrderRouter returned a non-JSON body"))?;
2250        let body = Value::from_json(&parsed);
2251        if (200..300).contains(&status) {
2252            return Ok(body);
2253        }
2254        // 404 and 501 carry a complete RouteResult explaining the refusal —
2255        // `no_market` and `exact_out_multi_hop_unsupported` are routing
2256        // outcomes, and turning them into errors would make the caller parse an
2257        // error string to recover a structure it already has.
2258        if (status == 404 || status == 501) && !self.string_at(&body, "unroutableReason", "").is_empty() {
2259            return Ok(body);
2260        }
2261        let message = self.string_at(&body, "error", &format!("http status {status}"));
2262        if status == 503 {
2263            // /ready answers 503 WITH ITS ANSWER: a Readiness body saying
2264            // not_ready and why. That is the result of the probe, not a failure
2265            // of it — erroring would hide the very counts the caller asked for.
2266            // Distinguished by shape, exactly as 404 and 501 are above.
2267            if !self.string_at(&body, "status", "").is_empty() {
2268                return Ok(body);
2269            }
2270            // Every other 503 is cache_cold: the router is alive but has too few
2271            // fresh books to rank on, typically for a few seconds after a restart
2272            // while the connectors repopulate. It is a RETRY, and the generic
2273            // ExchangeError this used to raise made it indistinguishable from a
2274            // permanent server fault.
2275            let cold = self.cold_cache_suffix(&body);
2276            let retry = Self::retry_suffix(&retry_after);
2277            return Err(ExchangeError::new(
2278                "ExchangeNotAvailable",
2279                format!("OrderRouter: {message}{cold}{retry}"),
2280            ));
2281        }
2282        if status == 429 {
2283            // the window rollover IS the retry interval here, so it stands in when
2284            // the service sent no retry-after
2285            let limit_interval = if retry_after.is_empty() { &rate_limit_reset } else { &retry_after };
2286            let retry = Self::retry_suffix(limit_interval);
2287            return Err(ExchangeError::new(
2288                "RateLimitExceeded",
2289                format!("OrderRouter: {message}{retry}"),
2290            ));
2291        }
2292        if status == 403 {
2293            //  NOT an authentication failure. The service has no API key; its only 403 is the
2294            //  ipv4-only refusal, raised before rate limiting when the resolved client address
2295            //  is not a dotted quad. Calling it an auth error sends the caller looking for a
2296            //  credential that exists for nobody, while the real remedy goes unsaid.
2297            return Err(ExchangeError::new(
2298                "PermissionDenied",
2299                format!("OrderRouter: {message} — the router resolved this client to a non-IPv4 address and refused it; reach it over IPv4"),
2300            ));
2301        }
2302        let kind = match status {
2303            400 => "BadRequest",
2304            401 => "AuthenticationError",
2305            408 | 504 => "RequestTimeout",
2306            _ => "ExchangeError",
2307        };
2308        Err(ExchangeError::new(kind, format!("OrderRouter: {message}")))
2309    }
2310
2311    /// Liveness only — the service answers 200 from the first millisecond of
2312    /// boot, before a single venue has connected. Use `fetch_readiness` to decide
2313    /// whether the router can actually price anything.
2314    pub async fn fetch_health(&self) -> RouterResult<Value> {
2315        self.request(&format!("{}/health", self.base_url), "GET", &Value::Null, "").await
2316    }
2317
2318    /// Whether the router has enough fresh books to rank on, measured with the
2319    /// same staleness cutoff `/route` uses.
2320    ///
2321    /// NOT_READY IS A NORMAL ANSWER: the service replies 503 with the same body
2322    /// it returns on 200, and this method returns it rather than erroring,
2323    /// because a caller asking "are you ready" needs the counts that say why not.
2324    pub async fn fetch_readiness(&self) -> RouterResult<Value> {
2325        self.request(&format!("{}/ready", self.base_url), "GET", &Value::Null, "").await
2326    }
2327
2328    /// Build provenance of the running process. This is what a deploy pipeline
2329    /// asserts against — `/health` answers 200 from the OLD process just as
2330    /// happily when a deploy silently no-ops, and `commit` is the only field that
2331    /// tells the two apart.
2332    pub async fn fetch_version(&self) -> RouterResult<Value> {
2333        self.request(&format!("{}/version", self.base_url), "GET", &Value::Null, "").await
2334    }
2335
2336    /// The unified symbols the router currently holds a cached book for. A pair
2337    /// absent from this list cannot be routed no matter how it is spelled.
2338    pub async fn fetch_symbols(&self) -> RouterResult<Vec<Value>> {
2339        let response = self.request(&format!("{}/symbols", self.base_url), "GET", &Value::Null, "").await?;
2340        Ok(self.list_at(&response, "symbols"))
2341    }
2342
2343    /// Per-venue connection health. A venue can hold an open socket while its
2344    /// subscription is silently dead, so read the per-venue update age and not
2345    /// only the connected flag.
2346    pub async fn fetch_exchanges_status(&self) -> RouterResult<Vec<Value>> {
2347        let response = self
2348            .request(&format!("{}/exchanges/status", self.base_url), "GET", &Value::Null, "")
2349            .await?;
2350        Ok(self.list_at(&response, "exchanges"))
2351    }
2352
2353    /// The router's own cached L2 book for one venue and symbol — the exact depth
2354    /// a route was ranked on, which is what makes a surprising route auditable.
2355    pub async fn fetch_cached_order_book(&self, exchange_id: &str, symbol: &str) -> RouterResult<Value> {
2356        if exchange_id.is_empty() || symbol.is_empty() {
2357            return Err(arguments_required("fetchCachedOrderBook requires an exchangeId and a symbol"));
2358        }
2359        // the symbol carries a slash and travels as ONE path segment, so it is
2360        // encoded rather than interpolated: BTC/USDT unencoded would read as two
2361        // segments and reach a route that does not exist
2362        let url = format!(
2363            "{}/orderbook/{}/{}",
2364            self.base_url,
2365            Self::encode_uri_component(exchange_id),
2366            Self::encode_uri_component(symbol)
2367        );
2368        self.request(&url, "GET", &Value::Null, "").await
2369    }
2370}
2371
2372// ---------------------------------------------------------------------------
2373// IMPURE: execute
2374// ---------------------------------------------------------------------------
2375
2376/// The strategies `execute` accepts. Anything else is refused before a venue is
2377/// touched, rather than silently falling through to a default.
2378//  HOW the orders go out, and nothing else. Whether they go out at all is `dryRun`.
2379const KNOWN_STRATEGIES: [&str; 5] = [
2380    "sequential", "parallel_within_hop", "limit_protected", "best_effort", "atomic_ish",
2381];
2382
2383impl OrderRouter {
2384    /// The stable identity of an execution, used for the re-execution guard.
2385    ///
2386    /// A caller-supplied `idempotencyKey` WINS over the plan's own `requestId`:
2387    /// passing one is a deliberate statement about what this execution is, and it
2388    /// is the only identity a hand-assembled plan can have — `execute` takes any
2389    /// dictionary of the plan shape, not only the output of `build_execution_plan`,
2390    /// and a plan a user built themselves never went through a routing request and
2391    /// so never had a `requestId`. Nothing is invented when both are absent: a
2392    /// generated identity would be either random, which defeats the guard that
2393    /// depends on it, or a fingerprint of the plan's contents, which makes two
2394    /// plans that happen to agree indistinguishable.
2395    pub fn plan_identity(&self, plan: &Value, options: &Value) -> String {
2396        let idempotency_key = self.string_at(options, "idempotencyKey", "");
2397        if !idempotency_key.is_empty() {
2398            return idempotency_key;
2399        }
2400        self.string_at(plan, "requestId", "")
2401    }
2402
2403    /// Counts the distinct hops a step list spans, which is the only authority
2404    /// on whether a plan is multi-hop.
2405    fn hop_count_of(&self, steps: &[Value]) -> usize {
2406        // A vector rather than a set, so the count is the same in six languages
2407        // and does not depend on hash iteration order.
2408        let mut seen: Vec<f64> = Vec::new();
2409        for step in steps {
2410            let hop_index = self.number_at(step, "hopIndex", 0.0);
2411            if !seen.iter().any(|s| *s == hop_index) {
2412                seen.push(hop_index);
2413            }
2414        }
2415        seen.len()
2416    }
2417
2418    /// A deep-enough copy of the plan's steps that resizing them cannot reach
2419    /// back into the caller's plan.
2420    fn clone_steps(&self, plan: &Value) -> Vec<Value> {
2421        let mut copied = Vec::new();
2422        let steps = self.list_at(plan, "steps");
2423        for (i, step) in steps.iter().enumerate() {
2424            // NORMALISE, do not shallow-copy. This used to clone the incoming map field
2425            // for field, which is fine for a plan build_execution_plan produced and wrong
2426            // for every other plan the Manual says execute accepts: a hand-assembled one,
2427            // one that travelled through JSON, or the rebuilt tail of a halted route.
2428            //
2429            // A step carrying no stepIndex then stayed absent, apply_resize reads it as
2430            // -1.0, and reconcile_execution_step only ever names targets >= 0 — so the
2431            // downstream resize matched nothing and silently applied NOTHING. Later hops
2432            // went to the venue at their original unshrunk size, sized for money the
2433            // bridge asset never received, and realisedOut was never written back, so a
2434            // multi-leg hop compounded its scale instead of accumulating the shortfall.
2435            //
2436            // The other five ports have always rebuilt the step here; this is Rust
2437            // catching up to them, field for field.
2438            let mut fresh = HashMap::new();
2439            fresh.insert("stepIndex".into(), Value::Float(self.number_at(step, "stepIndex", i as f64)));
2440            fresh.insert("hopIndex".into(), Value::Float(self.number_at(step, "hopIndex", 0.0)));
2441            fresh.insert("legIndex".into(), Value::Float(self.number_at(step, "legIndex", 0.0)));
2442            fresh.insert("exchangeId".into(), Value::Str(self.string_at(step, "exchangeId", "").into()));
2443            fresh.insert("symbol".into(), Value::Str(self.string_at(step, "symbol", "").into()));
2444            fresh.insert("side".into(), Value::Str(self.string_at(step, "side", "").into()));
2445            fresh.insert("base".into(), Value::Str(self.string_at(step, "base", "").into()));
2446            fresh.insert("quote".into(), Value::Str(self.string_at(step, "quote", "").into()));
2447            fresh.insert("amount".into(), Value::Float(self.number_at(step, "amount", 0.0)));
2448            fresh.insert("expectedPrice".into(), Value::Float(self.number_at(step, "expectedPrice", 0.0)));
2449            fresh.insert("effectivePrice".into(), Value::Float(self.number_at(step, "effectivePrice", 0.0)));
2450            fresh.insert("limitPrice".into(), Value::Float(self.step_limit_price(step)));
2451            fresh.insert("notionalQuote".into(), Value::Float(self.step_notional_quote(step)));
2452            // carried through the clone because execute reconciles against THESE steps,
2453            // not the plan's: without it the fee netting would be measured against a
2454            // gross expectation on every live run
2455            fresh.insert("expectedFeeCost".into(), Value::Float(self.number_at(step, "expectedFeeCost", 0.0)));
2456            copied.push(Value::Map(fresh));
2457        }
2458        copied
2459    }
2460
2461    /// The report skeleton, with one planned result per step.
2462    fn empty_report(
2463        &self,
2464        plan: &Value,
2465        strategy: &str,
2466        dry_run: bool,
2467        steps: &[Value],
2468    ) -> Value {
2469        let mut results = Vec::new();
2470        for step in steps {
2471            let mut result = HashMap::new();
2472            result.insert("stepIndex".into(), Value::Float(self.number_at(step, "stepIndex", -1.0)));
2473            result.insert("hopIndex".into(), Value::Float(self.number_at(step, "hopIndex", 0.0)));
2474            result.insert("legIndex".into(), Value::Float(self.number_at(step, "legIndex", 0.0)));
2475            result.insert("exchangeId".into(), Value::Str(self.string_at(step, "exchangeId", "").into()));
2476            result.insert("symbol".into(), Value::Str(self.string_at(step, "symbol", "").into()));
2477            result.insert("side".into(), Value::Str(self.string_at(step, "side", "").into()));
2478            result.insert("status".into(), Value::Str("planned".into()));
2479            result.insert("requestedAmount".into(), Value::Float(self.number_at(step, "amount", 0.0)));
2480            result.insert("filledAmount".into(), Value::Float(0.0));
2481            result.insert("averagePrice".into(), Value::Float(0.0));
2482            result.insert("cost".into(), Value::Float(0.0));
2483            result.insert("inAsset".into(), Value::Str(Cow::Borrowed("")));
2484            result.insert("inAmount".into(), Value::Float(0.0));
2485            result.insert("outAsset".into(), Value::Str(Cow::Borrowed("")));
2486            result.insert("outAmount".into(), Value::Float(0.0));
2487            result.insert("orderId".into(), Value::Str(Cow::Borrowed("")));
2488            result.insert("clientOrderId".into(), Value::Str(Cow::Borrowed("")));
2489            result.insert("errorCode".into(), Value::Str(Cow::Borrowed("")));
2490            // which retry produced this result; 0 unless retryFailedSteps re-placed it
2491            result.insert("attempt".into(), Value::Float(0.0));
2492            // False until an order is actually dispatched — a failure before
2493            // dispatch cannot have left anything resting on a venue.
2494            result.insert("placementAttempted".into(), Value::Bool(false));
2495            results.push(Value::Map(result));
2496        }
2497        let mut report = HashMap::new();
2498        // A placeholder: execute resolves the real identity from the plan AND the
2499        // options and overwrites it before anything reads this field.
2500        report.insert("planId".into(), Value::Str(Cow::Borrowed("")));
2501        report.insert("strategy".into(), Value::Str(strategy.to_string().into()));
2502        report.insert("dryRun".into(), Value::Bool(dry_run));
2503        report.insert("live".into(), Value::Bool(!dry_run));
2504        report.insert("from".into(), Value::Str(self.string_at(plan, "from", "").into()));
2505        report.insert("to".into(), Value::Str(self.string_at(plan, "to", "").into()));
2506        report.insert("slippageBps".into(), Value::Float(self.number_at(plan, "slippageBps", DEFAULT_SLIPPAGE_BPS)));
2507        report.insert(
2508            "reconcileToleranceRatio".into(),
2509            Value::Float(self.number_at(plan, "reconcileToleranceRatio", DEFAULT_RECONCILE_TOLERANCE)),
2510        );
2511        report.insert("stepCount".into(), Value::Float(steps.len() as f64));
2512        report.insert("wouldPlaceOrders".into(), Value::Float(0.0));
2513        report.insert("ordersPlaced".into(), Value::Float(0.0));
2514        report.insert("halted".into(), Value::Bool(false));
2515        report.insert("haltReason".into(), Value::Str(Cow::Borrowed("")));
2516        report.insert("haltStepIndex".into(), Value::Float(-1.0));
2517        report.insert("filledIn".into(), Value::Float(0.0));
2518        report.insert("filledOut".into(), Value::Float(0.0));
2519        report.insert("steps".into(), Value::List(results));
2520        report.insert("openOrders".into(), Value::List(Vec::new()));
2521        report.insert("errors".into(), Value::List(Vec::new()));
2522        report.insert("reconciliations".into(), Value::List(Vec::new()));
2523        Value::Map(report)
2524    }
2525
2526    /// Appends one entry to a list-valued field of a container.
2527    fn append_to(container: &mut Value, key: &str, entry: Value) {
2528        let mut items = match container.as_map().and_then(|m| m.get(key)) {
2529            Some(Value::Arr(existing)) => existing.as_ref().clone(),
2530            _ => Vec::new(),
2531        };
2532        items.push(entry);
2533        Self::put(container, key, Value::List(items));
2534    }
2535
2536    /// Records an error against the report.
2537    fn record_error(&self, report: &mut Value, step_index: f64, exchange_id: &str, symbol: &str, code: &str) {
2538        let mut entry = HashMap::new();
2539        entry.insert("stepIndex".into(), Value::Float(step_index));
2540        entry.insert("exchangeId".into(), Value::Str(exchange_id.to_string().into()));
2541        entry.insert("symbol".into(), Value::Str(symbol.to_string().into()));
2542        entry.insert("code".into(), Value::Str(code.to_string().into()));
2543        Self::append_to(report, "errors", Value::Map(entry));
2544    }
2545
2546    /// Records an order that may still be resting on a venue.
2547    fn record_open_order(&self, report: &mut Value, exchange_id: &str, symbol: &str, order_id: &str, reason: &str) {
2548        let mut entry = HashMap::new();
2549        entry.insert("exchangeId".into(), Value::Str(exchange_id.to_string().into()));
2550        entry.insert("symbol".into(), Value::Str(symbol.to_string().into()));
2551        entry.insert("orderId".into(), Value::Str(order_id.to_string().into()));
2552        entry.insert("reason".into(), Value::Str(reason.to_string().into()));
2553        Self::append_to(report, "openOrders", Value::Map(entry));
2554    }
2555
2556    /// Records a placement whose outcome is genuinely unknown — the request may
2557    /// or may not have reached the venue, so an order may or may not exist.
2558    fn record_unconfirmed_placement(&self, report: &mut Value, exchange_id: &str, symbol: &str, reason: &str) {
2559        // No order id, because there is none to record: that is the whole
2560        // problem. It goes on openOrders regardless, because the one thing a
2561        // caller must not conclude is that nothing was placed.
2562        self.record_open_order(report, exchange_id, symbol, "", reason);
2563    }
2564
2565    /// Reports whether a thrown error leaves a placement's outcome genuinely
2566    /// unknown.
2567    fn is_outcome_unknown_error(&self, error: &ExchangeError) -> bool {
2568        // Seven names, matched exactly — the same list the other five ports use.
2569        //
2570        // NOT `error.is("NetworkError")`: that walks the hierarchy, and in
2571        // ccxt's tree DDoSProtection, RateLimitExceeded and InvalidNonce are
2572        // all children of NetworkError. Those are the venue ANSWERING — a
2573        // rate-limit rejection is a definite "no order was placed" — so the
2574        // walk reported every throttled request as a possibly-live order,
2575        // halting a route the other five ports complete and sending an
2576        // operator hunting for an order that never existed.
2577        //
2578        // OperationFailed, BadResponse and NullResponse are the other
2579        // direction of the same mistake: the call came back with NO usable
2580        // answer, so an order may well be live. binance maps -1006 — "An
2581        // unexpected response was received from the message bus. Execution
2582        // status unknown." — to OperationFailed on one endpoint and
2583        // BadResponse on another, and both were read as a definite rejection
2584        // and RETRIED under retryFailedSteps.
2585        matches!(
2586            error.kind.as_str(),
2587            "RequestTimeout"
2588                | "ExchangeNotAvailable"
2589                | "NetworkError"
2590                | "OnMaintenance"
2591                | "OperationFailed"
2592                | "BadResponse"
2593                | "NullResponse"
2594        )
2595    }
2596
2597    /// Marks every step from an index onwards as skipped after a halt.
2598    fn mark_remaining_skipped(&self, report: &mut Value, start: usize) {
2599        let mut results = self.list_at(report, "steps");
2600        for result in results.iter_mut().skip(start) {
2601            if self.string_at(result, "status", "") == "planned" {
2602                Self::put(result, "status", Value::Str("skipped".into()));
2603            }
2604        }
2605        Self::put(report, "steps", Value::List(results));
2606    }
2607
2608    /// Totals the report's fills once the loops are done.
2609    fn summarise_report(&self, report: &mut Value, steps: &[Value]) {
2610        let results = self.list_at(report, "steps");
2611        // filledIn is denominated in the route's FROM asset and filledOut in its
2612        // TO asset, which is only true if each is summed over one hop: the first
2613        // and the last. Summing inAmount and outAmount across every step, as
2614        // this port did, adds USDT to BTC to ETH and reports the total as one
2615        // number — meaningless on any route longer than a single hop, and
2616        // meaningless in a way that reads like a figure.
2617        let mut last_hop = 0.0;
2618        for step in steps {
2619            let hop_index = self.number_at(step, "hopIndex", 0.0);
2620            if hop_index > last_hop {
2621                last_hop = hop_index;
2622            }
2623        }
2624        let mut filled_in = 0.0;
2625        let mut filled_out = 0.0;
2626        for result in &results {
2627            let hop_index = self.number_at(result, "hopIndex", 0.0);
2628            if hop_index == 0.0 {
2629                filled_in += self.number_at(result, "inAmount", 0.0);
2630            }
2631            if hop_index == last_hop {
2632                filled_out += self.number_at(result, "outAmount", 0.0);
2633            }
2634        }
2635        // ordersPlaced is NOT recomputed here. It is incremented as each order is
2636        // placed, so it counts an outcome_unknown step too — a status-derived
2637        // recount silently dropped exactly those, which are the placements an
2638        // operator most needs to know about.
2639        Self::put(report, "filledIn", Value::Float(filled_in));
2640        Self::put(report, "filledOut", Value::Float(filled_out));
2641        Self::put(report, "stepCount", Value::Float(steps.len() as f64));
2642    }
2643}
2644
2645impl OrderRouter {
2646    /// Sums the fees an order charged in one asset, ignoring any other currency.
2647    fn order_fee_in_asset(&self, order: &Value, asset: &str) -> f64 {
2648        if asset.is_empty() {
2649            return 0.0;
2650        }
2651        let mut total = 0.0;
2652        // ccxt reports the same cut in up to three places, so this is a strict
2653        // THREE-TIER PRECEDENCE and never a sum across tiers: the `fees` list wins
2654        // outright; if it named no entry in this asset, the single `fee` is read;
2655        // only if that named nothing either are the per-trade fees totalled.
2656        // `saw_in_list` is what makes each tier exclusive of the ones below it —
2657        // safeOrder fills `fee` and `fees` from the same charge, and the per-trade
2658        // fees are usually that same charge again, so adding tiers together would
2659        // double- or triple-count. Within ONE tier every matching entry IS summed.
2660        let fees = self.list_at(order, "fees");
2661        let mut saw_in_list = false;
2662        for entry in &fees {
2663            if self.string_at(entry, "currency", "").to_uppercase() == asset.to_uppercase() {
2664                total += self.number_at(entry, "cost", 0.0);
2665                saw_in_list = true;
2666            }
2667        }
2668        if !saw_in_list {
2669            let single = self.dict_at(order, "fee");
2670            if self.string_at(&single, "currency", "").to_uppercase() == asset.to_uppercase() {
2671                total += self.number_at(&single, "cost", 0.0);
2672                saw_in_list = true;
2673            }
2674        }
2675        if !saw_in_list {
2676            // Last resort: a venue that reports its cut only per trade. The Go
2677            // port has no `fees` list on its typed Order at all, so this
2678            // fallback is what lets all six ports read the same fee off the same
2679            // order — and reading NOTHING here is the dangerous direction, not
2680            // the safe one: an unread fee leaves out_amount GROSS, which sizes
2681            // the next hop on money the venue already took.
2682            let trades = self.list_at(order, "trades");
2683            for trade in &trades {
2684                let trade_fee = self.dict_at(trade, "fee");
2685                if self.string_at(&trade_fee, "currency", "").to_uppercase() == asset.to_uppercase() {
2686                    total += self.number_at(&trade_fee, "cost", 0.0);
2687                }
2688            }
2689        }
2690        if !Self::is_finite_number(total) || total < 0.0 {
2691            return 0.0;
2692        }
2693        total
2694    }
2695
2696    /// One re-read of an order the venue answered incompletely, falling back to
2697    /// what we already had rather than losing the placement record.
2698    async fn refetch_order(
2699        &self,
2700        venue: &dyn RouterVenue,
2701        order_id: &str,
2702        symbol: &str,
2703        fallback: Value,
2704    ) -> Value {
2705        match venue.fetch_order(order_id, symbol).await {
2706            Ok(reread) => reread,
2707            // The caller marks the fill unknown; a failure here must not lose
2708            // the placement record.
2709            Err(_) => fallback,
2710        }
2711    }
2712
2713    /// Re-checks the notional cap immediately before a placement, and does
2714    /// nothing at all when the caller never asked for one.
2715    fn assert_under_cap(
2716        &self,
2717        step: &Value,
2718        amount: f64,
2719        price: f64,
2720        usd_rates: &Value,
2721        options: &Value,
2722    ) -> RouterResult<()> {
2723        let cap = self.number_at(options, "maxNotionalUsd", self.max_notional_usd);
2724        if cap <= 0.0 {
2725            // No cap set, so there is nothing to enforce here.
2726            return Ok(());
2727        }
2728        // A PROBE, not the step: `amount` here is the venue-SNAPPED size actually being
2729        // sent, and the step still carries the unsnapped plan amount. notional_usd's
2730        // base-side fallback values the order off `amount`, so passing the step valued the
2731        // wrong quantity — the other five ports have always built this probe.
2732        let mut probe = HashMap::new();
2733        probe.insert("base".to_string(), Value::Str(self.string_at(step, "base", "").into()));
2734        probe.insert("quote".to_string(), Value::Str(self.string_at(step, "quote", "").into()));
2735        probe.insert("amount".to_string(), Value::Float(amount));
2736        let usd_value = self.notional_usd(&Value::Map(probe), amount * price, usd_rates);
2737        if usd_value <= 0.0 {
2738            return Err(exchange_error(
2739                "OrderRouter: refusing to place an order that cannot be valued in USD",
2740            ));
2741        }
2742        if usd_value > cap * (1.0 + TOLERANCE) {
2743            return Err(exchange_error(
2744                "OrderRouter: refusing to place an order above the per-trade USD notional cap",
2745            ));
2746        }
2747        Ok(())
2748    }
2749
2750    /// Places one order for one step and never returns an error, so that a
2751    /// sibling leg's failure cannot abandon an in-flight order.
2752    async fn place_step(
2753        &self,
2754        step: &Value,
2755        venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
2756        options: &Value,
2757        usd_rates: &Value,
2758        strategy: &str,
2759        report: &mut Value,
2760    ) -> Value {
2761        let step_index = self.number_at(step, "stepIndex", -1.0);
2762        let exchange_id = self.string_at(step, "exchangeId", "");
2763        let symbol = self.string_at(step, "symbol", "");
2764        let side = self.string_at(step, "side", "");
2765        let mut result = HashMap::new();
2766        result.insert("stepIndex".into(), Value::Float(step_index));
2767        // Carried from the step, not derived. Without them every result read as
2768        // hopIndex 0, which is what let summarise_report sum a two-hop route's
2769        // spends together — and it is also how a caller tells which hop a result
2770        // belongs to at all.
2771        result.insert("hopIndex".into(), Value::Float(self.number_at(step, "hopIndex", 0.0)));
2772        result.insert("legIndex".into(), Value::Float(self.number_at(step, "legIndex", 0.0)));
2773        result.insert("exchangeId".into(), Value::Str(exchange_id.clone().into()));
2774        result.insert("symbol".into(), Value::Str(symbol.clone().into()));
2775        result.insert("side".into(), Value::Str(side.clone().into()));
2776        result.insert("status".into(), Value::Str("failed".into()));
2777        result.insert("requestedAmount".into(), Value::Float(self.number_at(step, "amount", 0.0)));
2778        result.insert("filledAmount".into(), Value::Float(0.0));
2779        result.insert("averagePrice".into(), Value::Float(0.0));
2780        result.insert("cost".into(), Value::Float(0.0));
2781        result.insert("inAsset".into(), Value::Str(Cow::Borrowed("")));
2782        result.insert("inAmount".into(), Value::Float(0.0));
2783        result.insert("outAsset".into(), Value::Str(Cow::Borrowed("")));
2784        result.insert("outAmount".into(), Value::Float(0.0));
2785        result.insert("orderId".into(), Value::Str(Cow::Borrowed("")));
2786        result.insert("clientOrderId".into(), Value::Str(Cow::Borrowed("")));
2787        result.insert("errorCode".into(), Value::Str(Cow::Borrowed("")));
2788        result.insert("placementAttempted".into(), Value::Bool(false));
2789        let mut result = Value::Map(result);
2790
2791        let venue = match venues.get(&exchange_id) {
2792            Some(found) => found,
2793            None => {
2794                Self::put(&mut result, "errorCode", Value::Str("venue_missing".into()));
2795                self.record_error(report, step_index, &exchange_id, &symbol, "venue_missing");
2796                return result;
2797            }
2798        };
2799        let amount = self.parse_number(&venue.amount_to_precision(&symbol, self.number_at(step, "amount", 0.0)), 0.0);
2800        let price = self.parse_number(&venue.price_to_precision(&symbol, self.step_limit_price(step)), 0.0);
2801        if !(amount > 0.0) || !(price > 0.0) {
2802            Self::put(&mut result, "errorCode", Value::Str("rounded_to_zero".into()));
2803            self.record_error(report, step_index, &exchange_id, &symbol, "rounded_to_zero");
2804            return result;
2805        }
2806        // CLAUDE.md: compute the notional before EVERY createOrder. The
2807        // plan-level check already ran, but the plan can have been resized by a
2808        // reconciliation since, and the snapped price is not the one that was
2809        // checked.
2810        if let Err(e) = self.assert_under_cap(step, amount, price, usd_rates, options) {
2811            // the exception's own class name, exactly as the other five ports record it.
2812            // A hardcoded "over_cap" was wrong twice over: it did not match the five, and
2813            // it labelled the "cannot be valued in USD" refusal — which is not a cap
2814            // breach at all — as though the notional had exceeded the cap.
2815            Self::put(&mut result, "errorCode", Value::Str(e.kind.clone().into()));
2816            self.record_error(report, step_index, &exchange_id, &symbol, &e.kind);
2817            return result;
2818        }
2819        let order_params = self.dict_at(options, "orderParams");
2820        // No clientOrderId is set here. Whatever the caller put in options.orderParams
2821        // travels as-is, and each exchange's create_order keeps sending whatever
2822        // identifier it generates on its own; the id the venue reports back is
2823        // recorded on the result once the order returns. (An id derived from the
2824        // plan identity used to be forced onto every step, but venues disagree on
2825        // its length and charset, so it was rejected exactly where it mattered.)
2826        // The attempt is still recorded: retryFailedSteps re-places a step the venue
2827        // definitively rejected, and the report should say which try produced the result.
2828        let attempt = self.number_at(step, "attempt", 0.0);
2829        Self::put(&mut result, "attempt", Value::Float(attempt));
2830
2831        // Dispatch. `placementAttempted` is set immediately before the call and
2832        // not a line earlier: everything above this point is a refusal that
2833        // cannot have reached a venue.
2834        let order = if strategy == "limit_protected" {
2835            self.place_protected_limit(
2836                venue.as_ref(), step, &symbol, &side, amount, price, &order_params, options,
2837                report, &mut result,
2838            )
2839            .await
2840        } else {
2841            self.place_immediate_order(
2842                venue.as_ref(), &symbol, &side, amount, price, &order_params, options, &mut result,
2843            )
2844            .await
2845        };
2846        let order = match order {
2847            Ok(placed) => {
2848                Self::put(&mut result, "clientOrderId", Value::Str(self.string_at(&placed, "clientOrderId", "").into()));
2849                placed
2850            }
2851            Err(e) => {
2852                Self::put(&mut result, "errorCode", Value::Str(e.kind.clone().into()));
2853                self.record_error(report, step_index, &exchange_id, &symbol, &e.kind);
2854                // createOrder may already have succeeded: every path between it and the final
2855                // read — a poll that times out, a network drop, a cap re-check — leaves a real
2856                // order on a real venue. Reporting the id is the difference between an operator
2857                // who can go cancel it and one who never learns it exists. (This branch was
2858                // missing from the Rust port: a limit_protected order whose poll threw was
2859                // reported as a plain failure with no id anywhere in the report.)
2860                let known_id = self.string_at(&result, "orderId", "");
2861                if !known_id.is_empty() {
2862                    // "failed" would read as "nothing happened" while openOrders says the
2863                    // opposite, and one report must not carry both readings. Having an id means
2864                    // create_order RETURNED — the venue accepted something — so whatever threw
2865                    // afterwards left a real order behind whose fill is simply unknown to us.
2866                    Self::put(&mut result, "status", Value::Str("outcome_unknown".into()));
2867                    self.record_open_order(report, &exchange_id, &symbol, &known_id, "outcome_unknown");
2868                    return result;
2869                }
2870                if self.bool_at(&result, "placementAttempted", false) && self.is_outcome_unknown_error(&e) {
2871                    // The request may or may not have reached the venue. Halting
2872                    // on an unknown quantity is recoverable; concluding that
2873                    // nothing was placed is not.
2874                    Self::put(&mut result, "status", Value::Str("outcome_unknown".into()));
2875                    self.record_unconfirmed_placement(report, &exchange_id, &symbol, "placement_unconfirmed");
2876                }
2877                return result;
2878            }
2879        };
2880        self.settle_order_into_result(&order, step, &mut result, venue.as_ref(), &symbol, &exchange_id, amount, price, report, strategy).await;
2881        result
2882    }
2883}
2884
2885impl OrderRouter {
2886    /// Places an immediate-or-cancel limit order, or — only with explicit
2887    /// opt-in — a market order on a venue that cannot do IOC.
2888    async fn place_immediate_order(
2889        &self,
2890        venue: &dyn RouterVenue,
2891        symbol: &str,
2892        side: &str,
2893        amount: f64,
2894        price: f64,
2895        order_params: &Value,
2896        options: &Value,
2897        result: &mut Value,
2898    ) -> RouterResult<Value> {
2899        if venue.supports_ioc() {
2900            let mut params = order_params.clone();
2901            Self::put(&mut params, "timeInForce", Value::Str("IOC".into()));
2902            // Set immediately before the call that can leave a real order on a
2903            // real venue, and never reset. Anything that fails before this point
2904            // — a missing venue, a size that rounds to zero, the notional cap, a
2905            // venue that cannot do IOC — dispatched nothing, and recording an
2906            // unconfirmed placement for it would be a false alarm.
2907            Self::put(result, "placementAttempted", Value::Bool(true));
2908            let order = venue.create_order(symbol, "limit", side, amount, price, &params).await?;
2909            Self::put(result, "orderId", Value::Str(self.string_at(&order, "id", "").into()));
2910            return Ok(order);
2911        }
2912        if !self.bool_at(options, "allowMarketOrders", false) {
2913            // A market order is an unbounded price, and switching to one on a
2914            // caller's behalf is exactly the decision they did not delegate.
2915            return Err(ExchangeError::new(
2916                "NotSupported",
2917                "OrderRouter: venue cannot do IOC and allowMarketOrders was not set",
2918            ));
2919        }
2920        // A market order and a notional cap cannot both be honoured. assertUnderCap valued this order
2921        // at the plan's LIMIT price, and the call below sends no price at all: the venue fills wherever
2922        // the book is, which is the one thing the cap exists to bound. Passing the check and then
2923        // removing the price it was computed from is a cap that silently disappears, which by this
2924        // file's own rule is not a cap. So the two options are refused together.
2925        if self.number_at(options, "maxNotionalUsd", self.max_notional_usd) > 0.0 {
2926            return Err(ExchangeError::new("NotSupported", "OrderRouter: allowMarketOrders cannot be honoured under a maxNotionalUsd cap, because a market order has no price to check"));
2927        }
2928        Self::put(result, "placementAttempted", Value::Bool(true));
2929        // Price 0 stands for "no price", which is what a market order carries.
2930        let order = venue.create_order(symbol, "market", side, amount, 0.0, order_params).await?;
2931        Self::put(result, "orderId", Value::Str(self.string_at(&order, "id", "").into()));
2932        Ok(order)
2933    }
2934
2935    /// Rests a limit order, then cancels it on timeout and ALWAYS re-reads it,
2936    /// because a cancel and a fill can cross.
2937    #[allow(clippy::too_many_arguments)]
2938    async fn place_protected_limit(
2939        &self,
2940        venue: &dyn RouterVenue,
2941        step: &Value,
2942        symbol: &str,
2943        side: &str,
2944        amount: f64,
2945        price: f64,
2946        order_params: &Value,
2947        options: &Value,
2948        report: &mut Value,
2949        result: &mut Value,
2950    ) -> RouterResult<Value> {
2951        let timeout_ms = self.number_at(options, "orderTimeoutMs", 20000.0);
2952        let poll_interval_ms = self.number_at(options, "pollIntervalMs", 1000.0);
2953        Self::put(result, "placementAttempted", Value::Bool(true));
2954        let mut order = venue.create_order(symbol, "limit", side, amount, price, order_params).await?;
2955        let order_id = self.string_at(&order, "id", "");
2956        // Before the first poll, the first sleep and the first thing that can go
2957        // wrong: from here on the caller can always name what is resting.
2958        Self::put(result, "orderId", Value::Str(order_id.clone().into()));
2959        let mut waited = 0.0;
2960        while waited < timeout_ms {
2961            let status = self.string_at(&order, "status", "");
2962            if status == "closed" || status == "canceled" {
2963                return Ok(order);
2964            }
2965            tokio::time::sleep(std::time::Duration::from_millis(poll_interval_ms.max(0.0) as u64)).await;
2966            waited += poll_interval_ms;
2967            order = venue.fetch_order(&order_id, symbol).await?;
2968        }
2969        let final_status = self.string_at(&order, "status", "");
2970        if final_status == "closed" || final_status == "canceled" {
2971            // The venue ended it on the last poll — an expiry, a self-trade
2972            // prevention, a post-only rejection of the remainder. Cancelling an
2973            // order the venue already closed throws, and the partial fill this
2974            // order carries is real: dropping it would hide a live position from
2975            // the report AND from the unwind plan built out of it.
2976            return Ok(order);
2977        }
2978        if venue.cancel_order(&order_id, symbol).await.is_err() {
2979            // The order may still be live. Reporting a fill we did not observe
2980            // would be a lie, and continuing to the next hop on top of an
2981            // unknown position is worse.
2982            self.record_open_order(report, &self.string_at(step, "exchangeId", ""), symbol, &order_id, "cancel_failed");
2983            return Err(exchange_error(
2984                "OrderRouter: cancelOrder failed and an order is left OPEN, refusing to proceed",
2985            ));
2986        }
2987        // ALWAYS re-read after a cancel: the cancel and the fill can cross, and
2988        // the observed order is the only authority on what actually happened.
2989        venue.fetch_order(&order_id, symbol).await
2990    }
2991
2992    /// Reads a placed order into the step result: the fill, the direction, the
2993    /// fee netting and the status.
2994    #[allow(clippy::too_many_arguments)]
2995    async fn settle_order_into_result(
2996        &self,
2997        order: &Value,
2998        step: &Value,
2999        result: &mut Value,
3000        venue: &dyn RouterVenue,
3001        symbol: &str,
3002        exchange_id: &str,
3003        amount: f64,
3004        price: f64,
3005        report: &mut Value,
3006        strategy: &str,
3007    ) {
3008        let mut order = order.clone();
3009        // "The venue said zero" and "the venue said nothing" are different facts
3010        // and used to produce the same number. A venue that omits `filled`
3011        // yielded 0, reconciliation read that as nothing_filled and halted the
3012        // route — while a real position sat on a real venue. So presence is
3013        // tested, not the value.
3014        let order_id = self.string_at(result, "orderId", "");
3015        if !self.has_number_at(&order, "filled") && !order_id.is_empty() {
3016            // One re-read, exactly as place_protected_limit already does after
3017            // its poll. The immediate path never did, so it could only ever
3018            // fabricate.
3019            order = self.refetch_order(venue, &order_id, symbol, order.clone()).await;
3020        }
3021        // An order the venue explicitly calls open is RESTING, and on this path
3022        // it must not be: place_immediate_order asked for immediate-or-cancel, so
3023        // a venue that silently dropped the timeInForce param has left a plain
3024        // limit order sitting on the book. Recording it and walking on was not
3025        // enough — the next hop then trades on top of a position that keeps
3026        // growing behind it, is sized from a fill that is already out of date, and
3027        // the leftover order is still live after the route has ended and nobody is
3028        // watching it. So it is cancelled and re-read here, exactly as
3029        // place_protected_limit does on its timeout path.
3030        let mut resting_cancel_failed = false;
3031        if strategy != "limit_protected" && self.string_at(&order, "status", "") == "open" && !order_id.is_empty() {
3032            if venue.cancel_order(&order_id, symbol).await.is_err() {
3033                // The order may still be live and its fill can still move, so
3034                // whatever this step reports below is a snapshot that is already
3035                // stale. The status is downgraded after the amounts are filled in,
3036                // not here: a cost the venue DID report is a fact, and
3037                // build_unwind_plan subtracts it.
3038                resting_cancel_failed = true;
3039            } else {
3040                // ALWAYS re-read after a cancel: the cancel and the fill can
3041                // cross, and the observed order is the only authority on what
3042                // actually happened.
3043                order = self.refetch_order(venue, &order_id, symbol, order.clone()).await;
3044            }
3045        }
3046        let filled_known = self.has_number_at(&order, "filled");
3047        let filled = self.number_at(&order, "filled", 0.0);
3048        let average_known = self.has_number_at(&order, "average") || self.has_number_at(&order, "price");
3049        let mut average = self.number_at(&order, "average", 0.0);
3050        if average <= 0.0 {
3051            average = self.number_at(&order, "price", 0.0);
3052        }
3053        if average <= 0.0 {
3054            average = price;
3055        }
3056        let cost_known = self.has_number_at(&order, "cost");
3057        let mut cost = self.number_at(&order, "cost", 0.0);
3058        if cost <= 0.0 {
3059            cost = filled * average;
3060        }
3061        let side = self.string_at(step, "side", "");
3062        Self::put(result, "filledAmount", Value::Float(filled));
3063        Self::put(result, "averagePrice", Value::Float(average));
3064        Self::put(result, "cost", Value::Float(cost));
3065        // Companion flags, per the file's own "was it known" rule. A false here
3066        // means the number beside it is this class's best guess, not the venue's
3067        // answer. This port omitted all three, so a caller reading a Rust report
3068        // could not tell a venue's figure from a fallback.
3069        Self::put(result, "filledKnown", Value::Bool(filled_known));
3070        Self::put(result, "averageKnown", Value::Bool(average_known));
3071        Self::put(result, "costKnown", Value::Bool(cost_known));
3072        if side == "buy" {
3073            Self::put(result, "inAsset", Value::Str(self.string_at(step, "quote", "").into()));
3074            Self::put(result, "inAmount", Value::Float(cost));
3075            Self::put(result, "outAsset", Value::Str(self.string_at(step, "base", "").into()));
3076            Self::put(result, "outAmount", Value::Float(filled));
3077        } else {
3078            Self::put(result, "inAsset", Value::Str(self.string_at(step, "base", "").into()));
3079            Self::put(result, "inAmount", Value::Float(filled));
3080            Self::put(result, "outAsset", Value::Str(self.string_at(step, "quote", "").into()));
3081            Self::put(result, "outAmount", Value::Float(cost));
3082        }
3083        // Net the taker fee out of what is actually CARRIED FORWARD, when the
3084        // venue charged it in the asset this step produced. filled and cost are
3085        // gross of fees — the manual says so — so a venue taking its cut in the
3086        // acquired asset credits less than `filled`, and sizing the next hop (or
3087        // an unwind) on the gross figure orders more than the wallet holds. Fees
3088        // in any OTHER currency are left alone: they do not reduce what this hop
3089        // hands to the next one.
3090        let out_asset = self.string_at(result, "outAsset", "");
3091        let fee_cost = self.order_fee_in_asset(&order, &out_asset);
3092        Self::put(result, "feeCost", Value::Float(fee_cost));
3093        Self::put(result, "feeCurrency", Value::Str(out_asset.into()));
3094        if fee_cost > 0.0 {
3095            let gross = self.number_at(result, "outAmount", 0.0);
3096            let mut net = gross - fee_cost;
3097            if net < 0.0 {
3098                net = 0.0;
3099            }
3100            Self::put(result, "grossOutAmount", Value::Float(gross));
3101            Self::put(result, "outAmount", Value::Float(net));
3102        }
3103        if !filled_known {
3104            // Refuse to reconcile on a fabricated fill: halting on an unknown
3105            // quantity is recoverable, sizing the next hop from an invented
3106            // number is not.
3107            Self::put(result, "status", Value::Str("outcome_unknown".into()));
3108            self.record_open_order(report, exchange_id, symbol, &self.string_at(result, "orderId", ""), "fill_unconfirmed");
3109            // An order WAS placed, and this is exactly the path where knowing
3110            // that matters most. Counted here, as in the other five ports.
3111            Self::put(report, "ordersPlaced", Value::Float(self.number_at(report, "ordersPlaced", 0.0) + 1.0));
3112            return;
3113        }
3114        // No halt on an unknown PRICE. This port had an extra `price_unconfirmed`
3115        // branch that no other has: a fill whose average or cost the venue did
3116        // not report falls back to the order's `price`, then to the limit price,
3117        // and is flagged above rather than stopping the route. The reference
3118        // halts on an unknown FILL — an invented quantity is what makes the next
3119        // hop unsafe — and reports an estimated price as an estimate.
3120        if filled <= 0.0 {
3121            Self::put(result, "status", Value::Str("unfilled".into()));
3122        } else if filled >= amount * (1.0 - TOLERANCE) {
3123            Self::put(result, "status", Value::Str("filled".into()));
3124        } else {
3125            Self::put(result, "status", Value::Str("partial".into()));
3126        }
3127        if resting_cancel_failed {
3128            // A resting order this class could not cancel is the worst outcome
3129            // there is: it can still fill, in full, after the route has returned.
3130            // Sizing the next hop on the fill recorded above would trade against a
3131            // position that is still moving, so the step is marked unknown and
3132            // execute_sequential stops here.
3133            Self::put(result, "status", Value::Str("outcome_unknown".into()));
3134            self.record_open_order(report, exchange_id, symbol, &self.string_at(result, "orderId", ""), "cancel_failed");
3135        } else if self.string_at(&order, "status", "") == "open" {
3136            // Cancelled — or on the limit_protected path, cancelled by
3137            // place_protected_limit — and the venue STILL calls it open. The order
3138            // is live whatever this class asked for, so the same rule applies:
3139            // report it, and refuse to size anything downstream from a fill that
3140            // can still grow.
3141            Self::put(result, "status", Value::Str("outcome_unknown".into()));
3142            self.record_open_order(report, exchange_id, symbol, &self.string_at(result, "orderId", ""), "still_open");
3143        }
3144        Self::put(report, "ordersPlaced", Value::Float(self.number_at(report, "ordersPlaced", 0.0) + 1.0));
3145    }
3146}
3147
3148
3149impl OrderRouter {
3150    /// Places one step, re-placing it up to `options["retryFailedSteps"]` times
3151    /// when — and ONLY when — the venue definitively rejected it.
3152    async fn place_step_with_retry(
3153        &self,
3154        step: &Value,
3155        venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3156        options: &Value,
3157        usd_rates: &Value,
3158        strategy: &str,
3159        report: &mut Value,
3160    ) -> Value {
3161        let max_retries = self.number_at(options, "retryFailedSteps", 0.0);
3162        let retry_delay_ms = self.number_at(options, "retryDelayMs", DEFAULT_RETRY_DELAY_MS);
3163        let mut attempt = 0.0f64;
3164        loop {
3165            let mut attempted = step.clone();
3166            Self::put(&mut attempted, "attempt", Value::Float(attempt));
3167            let result = self.place_step(&attempted, venues, options, usd_rates, strategy, report).await;
3168            let status = self.string_at(&result, "status", "");
3169            // "failed" is the ONLY retryable outcome, and the distinction is the whole safety
3170            // argument. A failed step was refused by the venue: nothing was placed, so placing
3171            // it again cannot double-fill. An "outcome_unknown" step may ALREADY be a live
3172            // position that simply could not be read back, and re-placing that is precisely the
3173            // double-fill this class exists to prevent. It is never retried, at any setting.
3174            if status != "failed" || attempt >= max_retries {
3175                return result;
3176            }
3177            attempt += 1.0;
3178            if retry_delay_ms > 0.0 {
3179                tokio::time::sleep(std::time::Duration::from_millis(retry_delay_ms.max(0.0) as u64)).await;
3180            }
3181        }
3182    }
3183
3184    /// Hands the caller's `onStep` hook one finished step and returns its
3185    /// verdict, treating any failure of the hook as "no opinion".
3186    ///
3187    /// `options` is taken, and deliberately unused, so that this method reads
3188    /// the same as the other five ports at every call site. In THIS port the
3189    /// hook itself lives on the router (see `OnStepHook`), because `Value`
3190    /// cannot carry a closure.
3191    fn call_on_step(
3192        &self,
3193        options: &Value,
3194        report: &mut Value,
3195        result: &Value,
3196        reconciliation: &Value,
3197        step_index: usize,
3198        steps_total: usize,
3199    ) -> String {
3200        let _ = options;
3201        let hook = match &self.on_step {
3202            Some(found) => Arc::clone(found),
3203            None => return String::new(),
3204        };
3205        let mut event = HashMap::new();
3206        event.insert("planId".to_string(), Value::Str(self.string_at(report, "planId", "").into()));
3207        event.insert("stepIndex".to_string(), Value::Float(step_index as f64));
3208        event.insert("hopIndex".to_string(), Value::Float(self.number_at(result, "hopIndex", 0.0)));
3209        event.insert("legIndex".to_string(), Value::Float(self.number_at(result, "legIndex", 0.0)));
3210        event.insert("exchangeId".to_string(), Value::Str(self.string_at(result, "exchangeId", "").into()));
3211        event.insert("symbol".to_string(), Value::Str(self.string_at(result, "symbol", "").into()));
3212        event.insert("side".to_string(), Value::Str(self.string_at(result, "side", "").into()));
3213        event.insert("status".to_string(), Value::Str(self.string_at(result, "status", "").into()));
3214        event.insert("requestedAmount".to_string(), Value::Float(self.number_at(result, "requestedAmount", 0.0)));
3215        event.insert("filledAmount".to_string(), Value::Float(self.number_at(result, "filledAmount", 0.0)));
3216        event.insert("outAsset".to_string(), Value::Str(self.string_at(result, "outAsset", "").into()));
3217        event.insert("outAmount".to_string(), Value::Float(self.number_at(result, "outAmount", 0.0)));
3218        event.insert("orderId".to_string(), Value::Str(self.string_at(result, "orderId", "").into()));
3219        event.insert("clientOrderId".to_string(), Value::Str(self.string_at(result, "clientOrderId", "").into()));
3220        event.insert("errorCode".to_string(), Value::Str(self.string_at(result, "errorCode", "").into()));
3221        event.insert("attempt".to_string(), Value::Float(self.number_at(result, "attempt", 0.0)));
3222        event.insert("reconciliation".to_string(), reconciliation.clone());
3223        event.insert("ordersPlaced".to_string(), Value::Float(self.number_at(report, "ordersPlaced", 0.0)));
3224        event.insert("halted".to_string(), Value::Bool(self.bool_at(report, "halted", false)));
3225        event.insert("haltReason".to_string(), Value::Str(self.string_at(report, "haltReason", "").into()));
3226        event.insert("stepsTotal".to_string(), Value::Float(steps_total as f64));
3227        event.insert("stepsRemaining".to_string(), Value::Float((steps_total - (step_index + 1)) as f64));
3228        let event = Value::Map(event);
3229        // A hook that PANICS must NOT take the run with it — the Rust form of the try/catch
3230        // the other ports use, and of Go's defer/recover. Everything placed so far is recorded
3231        // in this report, and losing it to a panic raised by observability code would destroy
3232        // the only account of orders that are already live. `catch_unwind` is the right tool
3233        // here and only here: the hook is caller code we make no assumptions about, it is
3234        // handed an owned event and shares no mutable state with the router (hence
3235        // `AssertUnwindSafe`), and the run continues afterwards as if it had no opinion.
3236        // It does NOT contain an abort — a panic=abort profile takes the process down, which
3237        // no language-level construct in any of the six ports can prevent.
3238        let verdict = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| hook(&event)));
3239        match verdict {
3240            Ok(spoken) => {
3241                if spoken == "halt" {
3242                    return "halt".to_string();
3243                }
3244                String::new()
3245            }
3246            Err(_) => {
3247                // Rust panics carry no error TYPE to name, unlike the class name the other
3248                // five ports report, so the code is a fixed "panic".
3249                self.record_error(
3250                    report,
3251                    step_index as f64,
3252                    &self.string_at(result, "exchangeId", ""),
3253                    &self.string_at(result, "symbol", ""),
3254                    "on_step_hook_failed:panic",
3255                );
3256                String::new()
3257            }
3258        }
3259    }
3260}
3261
3262impl OrderRouter {
3263    /// Places one order at a time in plan order, reconciling after each and
3264    /// obeying the halt verdict.
3265    async fn execute_sequential(
3266        &self,
3267        report: &mut Value,
3268        steps: &mut Vec<Value>,
3269        venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3270        options: &Value,
3271        usd_rates: &Value,
3272        strategy: &str,
3273    ) {
3274        for i in 0..steps.len() {
3275            let step = steps[i].clone();
3276            let result = self.place_step_with_retry(&step, venues, options, usd_rates, strategy, report).await;
3277            let mut results = self.list_at(report, "steps");
3278            results[i] = result.clone();
3279            Self::put(report, "steps", Value::List(results));
3280            let status = self.string_at(&result, "status", "");
3281            if status == "failed" || status == "outcome_unknown" {
3282                Self::put(report, "halted", Value::Bool(true));
3283                // An unknown outcome must NOT fall through to reconciliation:
3284                // reconciling reads outAmount, which is 0 because nothing was
3285                // observed, and reports the halt as "nothing_filled" — asserting
3286                // the one thing we do not know.
3287                let reason = if status == "failed" { "order_failed" } else { "outcome_unknown" };
3288                Self::put(report, "haltReason", Value::Str(reason.into()));
3289                Self::put(report, "haltStepIndex", Value::Float(i as f64));
3290                // the hook is told about a halt it did not cause, and cannot undo it
3291                self.call_on_step(options, report, &result, &Value::Map(HashMap::new()), i, steps.len());
3292                self.mark_remaining_skipped(report, i + 1);
3293                return;
3294            }
3295            let mut reconcile_plan = HashMap::new();
3296            reconcile_plan.insert("steps".to_string(), Value::List(steps.clone()));
3297            reconcile_plan.insert(
3298                "reconcileToleranceRatio".to_string(),
3299                Value::Float(self.number_at(report, "reconcileToleranceRatio", DEFAULT_RECONCILE_TOLERANCE)),
3300            );
3301            let reconciliation = match self.reconcile_execution_step(
3302                &Value::Map(reconcile_plan), i as i64, self.number_at(&result, "outAmount", 0.0),
3303            ) {
3304                Ok(verdict) => verdict,
3305                Err(_) => return,
3306            };
3307            Self::append_to(report, "reconciliations", reconciliation.clone());
3308            if strategy != "atomic_ish" {
3309                // atomic_ish is pre-funded end to end, so a hop's shortfall does
3310                // not shrink the next hop's order — the money for it was already
3311                // there before the first order went out.
3312                self.apply_resize(steps, &reconciliation);
3313            }
3314            if self.string_at(&reconciliation, "verdict", "") == "halt" {
3315                Self::put(report, "halted", Value::Bool(true));
3316                Self::put(report, "haltReason", Value::Str(self.string_at(&reconciliation, "reason", "").into()));
3317                Self::put(report, "haltStepIndex", Value::Float(i as f64));
3318                self.call_on_step(options, report, &result, &reconciliation, i, steps.len());
3319                self.mark_remaining_skipped(report, i + 1);
3320                return;
3321            }
3322            // the caller's own verdict, consulted only once the route is otherwise sound. It
3323            // can stop the route; it cannot restart one the reconciliation above already
3324            // stopped.
3325            if self.call_on_step(options, report, &result, &reconciliation, i, steps.len()) == "halt" {
3326                Self::put(report, "halted", Value::Bool(true));
3327                Self::put(report, "haltReason", Value::Str("halted_by_on_step".into()));
3328                Self::put(report, "haltStepIndex", Value::Float(i as f64));
3329                self.mark_remaining_skipped(report, i + 1);
3330                return;
3331            }
3332        }
3333    }
3334
3335    /// Runs the legs of one hop concurrently ACROSS venues and serially WITHIN
3336    /// a venue, and the hops strictly in order.
3337    async fn execute_parallel_within_hop(
3338        &self,
3339        report: &mut Value,
3340        steps: &mut Vec<Value>,
3341        venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3342        options: &Value,
3343        usd_rates: &Value,
3344    ) {
3345        let mut cursor = 0usize;
3346        while cursor < steps.len() {
3347            let hop_index = self.number_at(&steps[cursor], "hopIndex", 0.0);
3348            let mut end = cursor;
3349            while end < steps.len() && self.number_at(&steps[end], "hopIndex", 0.0) == hop_index {
3350                end += 1;
3351            }
3352            // THE CONTRACT: concurrent ACROSS venues, serialised WITHIN a venue.
3353            // It is an ordering guarantee, not a performance promise, which is
3354            // what lets six very different runtimes honour the same words. Two
3355            // legs of one hop that land on the SAME venue must never have two
3356            // orders in flight against that venue's throttle and nonce state.
3357            //
3358            // DIVERGENCE, recorded rather than hidden: TypeScript, Python, C#
3359            // and Go run the venue groups concurrently. This port runs them one
3360            // after another. `place_step` takes `&mut Value` for the report, so
3361            // concurrent groups would need the report behind a lock, and a lock
3362            // around every record_error/record_open_order is a great deal of
3363            // machinery to buy back parallelism the contract does not promise.
3364            // Serialising everything satisfies the ordering guarantee strictly
3365            // more than grouping does — it is what the PHP port does, for the
3366            // same reason — so the report is identical either way.
3367            let mut group_ids: Vec<String> = Vec::new();
3368            for i in cursor..end {
3369                let exchange_id = self.string_at(&steps[i], "exchangeId", "");
3370                if !group_ids.contains(&exchange_id) {
3371                    group_ids.push(exchange_id);
3372                }
3373            }
3374            for group in &group_ids {
3375                for i in cursor..end {
3376                    if self.string_at(&steps[i], "exchangeId", "") != *group {
3377                        continue;
3378                    }
3379                    let step = steps[i].clone();
3380                    let result = self
3381                        .place_step_with_retry(&step, venues, options, usd_rates, "parallel_within_hop", report)
3382                        .await;
3383                    let mut results = self.list_at(report, "steps");
3384                    results[i] = result;
3385                    Self::put(report, "steps", Value::List(results));
3386                }
3387            }
3388            for i in cursor..end {
3389                let results = self.list_at(report, "steps");
3390                let result = results[i].clone();
3391                let status = self.string_at(&result, "status", "");
3392                if status == "failed" || status == "outcome_unknown" {
3393                    Self::put(report, "halted", Value::Bool(true));
3394                    let reason = if status == "failed" { "order_failed" } else { "outcome_unknown" };
3395                    Self::put(report, "haltReason", Value::Str(reason.into()));
3396                    Self::put(report, "haltStepIndex", Value::Float(i as f64));
3397                    self.call_on_step(options, report, &result, &Value::Map(HashMap::new()), i, steps.len());
3398                    self.mark_remaining_skipped(report, end);
3399                    return;
3400                }
3401                let mut reconcile_plan = HashMap::new();
3402                reconcile_plan.insert("steps".to_string(), Value::List(steps.clone()));
3403                reconcile_plan.insert(
3404                    "reconcileToleranceRatio".to_string(),
3405                    Value::Float(self.number_at(report, "reconcileToleranceRatio", DEFAULT_RECONCILE_TOLERANCE)),
3406                );
3407                let reconciliation = match self.reconcile_execution_step(
3408                    &Value::Map(reconcile_plan), i as i64, self.number_at(&result, "outAmount", 0.0),
3409                ) {
3410                    Ok(verdict) => verdict,
3411                    Err(_) => return,
3412                };
3413                Self::append_to(report, "reconciliations", reconciliation.clone());
3414                self.apply_resize(steps, &reconciliation);
3415                if self.string_at(&reconciliation, "verdict", "") == "halt" {
3416                    Self::put(report, "halted", Value::Bool(true));
3417                    Self::put(report, "haltReason", Value::Str(self.string_at(&reconciliation, "reason", "").into()));
3418                    Self::put(report, "haltStepIndex", Value::Float(i as f64));
3419                    self.call_on_step(options, report, &result, &reconciliation, i, steps.len());
3420                    self.mark_remaining_skipped(report, end);
3421                    return;
3422                }
3423                if self.call_on_step(options, report, &result, &reconciliation, i, steps.len()) == "halt" {
3424                    Self::put(report, "halted", Value::Bool(true));
3425                    Self::put(report, "haltReason", Value::Str("halted_by_on_step".into()));
3426                    Self::put(report, "haltStepIndex", Value::Float(i as f64));
3427                    self.mark_remaining_skipped(report, end);
3428                    return;
3429                }
3430            }
3431            cursor = end;
3432        }
3433    }
3434
3435    /// Places what it can and never halts, on a single hop only, up to
3436    /// maxOrders.
3437    async fn execute_best_effort(
3438        &self,
3439        report: &mut Value,
3440        steps: &mut [Value],
3441        venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3442        options: &Value,
3443        usd_rates: &Value,
3444    ) {
3445        let max_orders = self.number_at(options, "maxOrders", 0.0);
3446        let mut placed = 0.0;
3447        for i in 0..steps.len() {
3448            let mut results = self.list_at(report, "steps");
3449            if placed >= max_orders {
3450                Self::put(&mut results[i], "status", Value::Str("skipped".into()));
3451                Self::put(&mut results[i], "errorCode", Value::Str("max_orders_reached".into()));
3452                Self::put(report, "steps", Value::List(results));
3453                continue;
3454            }
3455            let step = steps[i].clone();
3456            let result = self.place_step_with_retry(&step, venues, options, usd_rates, "best_effort", report).await;
3457            let mut results = self.list_at(report, "steps");
3458            results[i] = result.clone();
3459            Self::put(report, "steps", Value::List(results));
3460            placed += 1.0;
3461            // No reconciliation and no halt: that is the whole point of the strategy, and why
3462            // it is refused on anything but a single hop. The hook is still offered every step,
3463            // and stopping early is the one thing it may do here — that is a smaller commitment
3464            // than the strategy's own contract, never a larger one.
3465            if self.call_on_step(options, report, &result, &Value::Map(HashMap::new()), i, steps.len()) == "halt" {
3466                Self::put(report, "halted", Value::Bool(true));
3467                Self::put(report, "haltReason", Value::Str("halted_by_on_step".into()));
3468                Self::put(report, "haltStepIndex", Value::Float(i as f64));
3469                self.mark_remaining_skipped(report, i + 1);
3470                return;
3471            }
3472        }
3473    }
3474
3475    /// Executes a plan against live venues. THE ONLY IMPURE METHOD.
3476    ///
3477    /// `dry_run` is the default, and `options.live != true` forces `dry_run`
3478    /// regardless of the strategy requested, so a call that looks live but
3479    /// forgot the flag places nothing.
3480    ///
3481    /// `plan` is a plan from `build_execution_plan`, OR a caller-assembled plan of
3482    /// the same shape — this method never assumes the plan came from the routing
3483    /// service. `options.idempotencyKey` is the identity of this execution,
3484    /// required when the plan carries no `requestId`; it keys the re-execution
3485    /// guard and overrides the plan's `requestId` when both are given.
3486    /// `options.allowReexecution` must be exactly true to run a plan this instance
3487    /// has already executed live; the DEFAULT is refusal.
3488    ///
3489    /// `options.retryFailedSteps` is how many times to re-place a step the venue
3490    /// DEFINITIVELY REJECTED, default 0. An `outcome_unknown` step is never
3491    /// retried at any setting: it may already be a live position, and re-placing
3492    /// it is the double-fill this class exists to prevent. `options.retryDelayMs`
3493    /// is how long to wait before a retry, default `DEFAULT_RETRY_DELAY_MS` (1000).
3494    ///
3495    /// The third option the other five ports read out of `options` — `onStep` —
3496    /// is set on the router instead, by `set_on_step`; `Value` cannot carry a
3497    /// closure. See `OnStepHook`.
3498    pub async fn execute(
3499        &self,
3500        plan: &Value,
3501        venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3502        options: &Value,
3503    ) -> RouterResult<Value> {
3504        //  the argument wins; the router's own venues are the fallback. Nothing is ever
3505        //  CONSTRUCTED here - this is the money path.
3506        let venues = if venues.is_empty() { &self.venues } else { venues };
3507        //  plan-shaping options cannot be honoured once the plan exists
3508        if !self.list_at(plan, "steps").is_empty() {
3509            self.assert_no_plan_shaping_options(options)?;
3510        }
3511        //  A ROUTE is accepted here as well as a plan. buildExecutionPlan is pure and derives
3512        //  entirely from the route, so requiring the caller to run it first was ceremony: two
3513        //  calls that can only ever happen in that order, with nothing to do in between unless
3514        //  you actually want to inspect the plan. Told apart by shape rather than by a flag - a
3515        //  route carries `hops`, a plan carries `steps`, and nothing carries both.
3516        let built_from_route;
3517        let plan = if self.list_at(plan, "steps").is_empty() && !self.list_at(plan, "hops").is_empty() {
3518            built_from_route = self.build_execution_plan(plan, options)?;
3519            &built_from_route
3520        } else {
3521            plan
3522        };
3523        let requested_strategy = self.string_at(options, "strategy", "sequential");
3524        if !KNOWN_STRATEGIES.contains(&requested_strategy.as_str()) {
3525            return Err(bad_request(&format!(
3526                "OrderRouter: unknown execution strategy {requested_strategy}"
3527            )));
3528        }
3529        //  PLACING IS THE DEFAULT, and ONE knob decides it: `strategy` says only HOW,
3530        //  `dryRun` says only WHETHER. The guardrails that do the work all still run
3531        //  BEFORE anything is sent.
3532        let strategy = requested_strategy.clone();
3533        //  REFUSED, not ignored. `live` was the old knob and it is gone; `live: false` meant
3534        //  "place nothing" and now means nothing at all, so ignoring it silently would send
3535        //  the orders while the caller believed they had opted out.
3536        if field(options, "live").is_some() {
3537            return Err(bad_request(
3538                "OrderRouter: options.live is gone — execute places orders, and a rehearsal is asked for with dryRun. Remove live, or pass dryRun to place nothing",
3539            ));
3540        }
3541        let dry_run = self.is_exactly_true(options, "dryRun");
3542        let mut steps = self.clone_steps(plan);
3543        let mut report = self.empty_report(plan, &strategy, dry_run, &steps);
3544        // Resolved from BOTH the plan and the options, so a hand-assembled plan can
3545        // carry an identity too; reported on every report, rehearsals included.
3546        let plan_id = self.plan_identity(plan, options);
3547        Self::put(&mut report, "planId", Value::Str(plan_id.clone().into()));
3548        // How old the prices in this plan are. ALWAYS reported, even when nothing is enforced: a plan
3549        // is a snapshot of a book, and how stale that snapshot is decides whether any number in it
3550        // means anything. -1 when the route carried no calculatedAt, which is not the same as "fresh"
3551        // and must not read like it. Enforced only if asked for, at whatever value is asked for — the
3552        // same shape as maxNotionalUsd, and for the same reason. But an age that cannot be determined
3553        // BLOCKS under an active limit: a freshness check that silently passes when the timestamp is
3554        // missing is not a freshness check.
3555        let calculated_at = self.number_at(plan, "calculatedAt", 0.0);
3556        let plan_age_ms = if calculated_at > 0.0 { self.now_ms() - calculated_at } else { -1.0 };
3557        Self::put(&mut report, "planAgeMs", Value::Float(plan_age_ms));
3558        let max_plan_age_ms = self.number_at(options, "maxPlanAgeMs", 0.0);
3559        if !dry_run && max_plan_age_ms > 0.0 {
3560            if plan_age_ms < 0.0 {
3561                return Err(exchange_error("OrderRouter: refusing to execute, the plan carries no calculatedAt and maxPlanAgeMs was set"));
3562            }
3563            if plan_age_ms > max_plan_age_ms {
3564                return Err(exchange_error("OrderRouter: refusing to execute a plan older than maxPlanAgeMs, recompute the route"));
3565            }
3566        }
3567        if dry_run {
3568            // Not one call is made against a venue on this path, not even a read.
3569            Self::put(&mut report, "wouldPlaceOrders", Value::Float(steps.len() as f64));
3570            return Ok(report);
3571        }
3572        if venues.is_empty() {
3573            return Err(arguments_required(
3574                "OrderRouter.execute requires a venues dictionary when live",
3575            ));
3576        }
3577        // IDEMPOTENCY, half one: a plan this instance has already run live is
3578        // REFUSED, and refused here — before a single read reaches a venue. The
3579        // ledger is consulted now and written only once the plan is about to be
3580        // dispatched, so a caller error that placed nothing does not burn the plan.
3581        // dry_run never reaches this line and never consumes a plan, because a
3582        // rehearsal places nothing.
3583        if plan_id.is_empty() {
3584            // No identity means no idempotency: the ledger below cannot key on it,
3585            // so a re-run of this plan would be indistinguishable from a first run.
3586            return Err(bad_request("OrderRouter: refusing to execute live without an identity, the plan carries no requestId — pass options.idempotencyKey"));
3587        }
3588        if !self.bool_at(options, "allowReexecution", false) {
3589            let id = plan_id.clone();
3590            if self.shared_op(move |s| s.ledger.contains(&id)) {
3591                return Err(bad_request("OrderRouter: refusing to re-execute a plan this instance already executed, pass allowReexecution to override"));
3592            }
3593        }
3594        // Derived from the steps about to be executed, NEVER read off the plan:
3595        // a plan that travelled through JSON, a persisted step list or a
3596        // hand-rebuilt tail of a halted route can be missing hopCount, and a
3597        // refusal that a missing key switches off is not a refusal.
3598        let hop_count = self.hop_count_of(&steps);
3599        if strategy == "best_effort" {
3600            if hop_count > 1 {
3601                // Best-effort multi-hop is the most reliable way to strand money
3602                // in a bridge asset.
3603                return Err(ExchangeError::new(
3604                    "NotSupported",
3605                    "OrderRouter: best_effort refuses multi-hop routes",
3606                ));
3607            }
3608            if !self.bool_at(options, "acknowledgeDispersion", false) {
3609                return Err(bad_request("OrderRouter: best_effort requires acknowledgeDispersion"));
3610            }
3611            if self.number_at(options, "maxOrders", 0.0) <= 0.0 {
3612                return Err(bad_request("OrderRouter: best_effort requires a positive maxOrders"));
3613            }
3614        }
3615        if strategy == "limit_protected" {
3616            // Refused HERE, before a single order is placed, because the alternative is worse than a
3617            // bad interval: the poll loop advances its clock by this value, so a zero or negative one
3618            // never reaches the timeout. It spins on fetchOrder forever with a real order resting on a
3619            // real venue, and the timeout that exists to cancel that order never arrives.
3620            if self.has_number_at(options, "pollIntervalMs")
3621                && self.number_at(options, "pollIntervalMs", 0.0) <= 0.0
3622            {
3623                return Err(bad_request("OrderRouter: pollIntervalMs must be positive, a resting order is polled on that clock"));
3624            }
3625        }
3626        // Markets are needed for the safety check and for precision snapping.
3627        // The caller supplies them: unlike the other five ports, this one cannot
3628        // call loadMarkets() through the venue trait — adding it there would put
3629        // a method on the trait that only this line uses, and every implementor
3630        // would have to write it.
3631        let markets = self.dict_at(options, "markets");
3632        let usd_rates = self.dict_at(options, "usdRates");
3633        let mut safety_options = HashMap::new();
3634        safety_options.insert("usdRates".to_string(), usd_rates.clone());
3635        safety_options.insert(
3636            "maxNotionalUsd".to_string(),
3637            Value::Float(self.number_at(options, "maxNotionalUsd", self.max_notional_usd)),
3638        );
3639        safety_options.insert(
3640            "precisionMode".to_string(),
3641            Value::Str(self.string_at(options, "precisionMode", "tick_size").into()),
3642        );
3643        let violations = self.check_execution_plan_safety(plan, &markets, &Value::Map(safety_options));
3644        let mut blockers: Vec<String> = Vec::new();
3645        for violation in &violations {
3646            if self.bool_at(violation, "blocking", false) {
3647                blockers.push(self.string_at(violation, "code", ""));
3648            }
3649        }
3650        if !blockers.is_empty() {
3651            // Returned as an error, not reported. A refusal a caller can forget
3652            // to read is not a refusal.
3653            return Err(exchange_error(&format!(
3654                "OrderRouter: refusing to execute, blocking safety violations: {}{}",
3655                blockers.join(", "),
3656                //  notional_unvaluable gets its CAUSE named rather than its symptom: the cap
3657                //  and the rates are one guardrail in two parts, and a caller who set
3658                //  maxNotionalUsd believes they are protected.
3659                if blockers.iter().any(|code| code == "notional_unvaluable")
3660                    && usd_rates.as_map().map(|m| m.is_empty()).unwrap_or(true)
3661                {
3662                    " - maxNotionalUsd is set but options.usdRates is empty, and the cap cannot be evaluated without a USD price for the quote currency"
3663                } else {
3664                    ""
3665                }
3666            )));
3667        }
3668        if strategy == "atomic_ish" {
3669            // The check the strategy is NAMED for. Without it this port accepted
3670            // atomic_ish, skipped the downstream resize that every other strategy
3671            // performs — on the strength of the route being pre-funded end to
3672            // end — and then never established that it was. A short hop would
3673            // have sized the next one off proceeds it did not have.
3674            self.assert_prefunded(&steps, venues).await?;
3675        }
3676        // The ledger is written BEFORE the first order goes out, never after: a run
3677        // that fails half way through has still placed orders, and a guard that only
3678        // recorded completed runs would wave through exactly the retry that
3679        // double-fills.
3680        {
3681            let id = plan_id.clone();
3682            self.shared_op(move |s| s.ledger.record(id));
3683        }
3684        // From here orders go out, so whatever balances were cached are about to be
3685        // wrong. Dropped BEFORE dispatch, for the same reason the ledger is written
3686        // here: a run that fails half way through has still moved money.
3687        self.invalidate_balances();
3688        if strategy == "parallel_within_hop" {
3689            self.execute_parallel_within_hop(&mut report, &mut steps, venues, options, &usd_rates).await;
3690        } else if strategy == "best_effort" {
3691            self.execute_best_effort(&mut report, &mut steps, venues, options, &usd_rates).await;
3692        } else {
3693            // sequential, limit_protected and atomic_ish all walk the plan one
3694            // order at a time; they differ in how a single order is placed and in
3695            // whether they lean on the previous hop's proceeds.
3696            self.execute_sequential(&mut report, &mut steps, venues, options, &usd_rates, &strategy).await;
3697        }
3698        //  and AGAIN on the way out: a quote issued while the orders were in flight
3699        //  repopulates the cache from wallets that had not settled yet.
3700        self.invalidate_balances();
3701        self.summarise_report(&mut report, &steps);
3702        Ok(report)
3703    }
3704}
3705
3706impl OrderRouter {
3707    /// Verifies every step's input is already sitting on its venue, which is what
3708    /// `atomic_ish` actually requires. There is no cross-venue atomicity and there
3709    /// cannot be, so the strategy names its own hedge: pre-fund the whole route,
3710    /// and no hop then depends on the previous one settling.
3711    ///
3712    /// Most routes fail this, and that is the correct outcome.
3713    async fn assert_prefunded(
3714        &self,
3715        steps: &[Value],
3716        venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3717    ) -> RouterResult<()> {
3718        // Built as a Vec, not a map, so the first shortfall reported is the same
3719        // one in all six languages.
3720        let mut required: Vec<(String, String, f64)> = Vec::new();
3721        for step in steps {
3722            let exchange_id = self.string_at(step, "exchangeId", "");
3723            let amount = self.number_at(step, "amount", 0.0);
3724            let (asset, needed) = if self.string_at(step, "side", "") == "buy" {
3725                (self.string_at(step, "quote", ""), amount * self.step_limit_price(step))
3726            } else {
3727                (self.string_at(step, "base", ""), amount)
3728            };
3729            let mut found = false;
3730            for entry in required.iter_mut() {
3731                if entry.0 == exchange_id && entry.1 == asset {
3732                    entry.2 += needed;
3733                    found = true;
3734                    break;
3735                }
3736            }
3737            if !found {
3738                required.push((exchange_id, asset, needed));
3739            }
3740        }
3741        // One fetch_balance per venue, cached: a route with four hops on one
3742        // exchange must not cost four balance calls.
3743        let mut balances: HashMap<String, Value> = HashMap::new();
3744        for (exchange_id, asset, needed) in &required {
3745            if !balances.contains_key(exchange_id) {
3746                let venue = match venues.get(exchange_id) {
3747                    Some(found) => found,
3748                    None => {
3749                        return Err(exchange_error(&format!(
3750                            "OrderRouter: atomic_ish cannot check funding, no venue was passed for {exchange_id}"
3751                        )))
3752                    }
3753                };
3754                balances.insert(exchange_id.clone(), venue.fetch_balance().await?);
3755            }
3756            let balance = balances.get(exchange_id).expect("just inserted");
3757            let free = self.dict_at(balance, "free");
3758            let available = self.number_at(&free, asset, 0.0);
3759            if available < *needed {
3760                return Err(insufficient_funds(&format!(
3761                    "OrderRouter: atomic_ish requires the whole route pre-funded, and {exchange_id} is short of {asset}"
3762                )));
3763            }
3764        }
3765        Ok(())
3766    }
3767
3768    //  NO markets_of HERE, and it is not an omission. The other five ports offer one because
3769    //  their venues expose their markets; `RouterVenue` deliberately does not — it is narrowed
3770    //  to the operations the money path performs — so Rust's execute reads `options.markets`
3771    //  and the caller assembles that dict either way. A helper taking venues would have
3772    //  nothing to read.
3773
3774    /// Refuses plan-shaping options alongside an already-built plan, where they cannot apply.
3775    pub fn assert_no_plan_shaping_options(&self, options: &Value) -> RouterResult<()> {
3776        for key in ["slippageBps", "reconcileToleranceRatio"] {
3777            if field(options, key).is_some() {
3778                return Err(bad_request(&format!(
3779                    "OrderRouter: {key} shapes a plan and this plan is already built, so it cannot be applied - pass it to build_execution_plan, or hand execute the route instead of the plan"
3780                )));
3781            }
3782        }
3783        Ok(())
3784    }
3785
3786    /// Turns whatever a caller wrote for `balances` into the router's wire form: the rendered
3787    /// string itself, a list of entries, a per-venue wallet, or a flat single-venue wallet.
3788    pub fn render_balances(&self, value: &Value) -> RouterResult<String> {
3789        if let Value::Str(text) = value {
3790            return Ok(text.to_string());
3791        }
3792        if let Value::Arr(_) = value {
3793            return self.query_text(value);
3794        }
3795        match value.as_map() {
3796            Some(map) => {
3797                //  Two shapes, told apart by what the values are: a per-venue wallet nests one
3798                //  level, a flat wallet does not. Zero holdings are dropped.
3799                let mut outer_keys: Vec<String> = map.keys().cloned().collect();
3800                outer_keys.sort();
3801                let mut entries: Vec<Value> = Vec::new();
3802                for outer in outer_keys.iter() {
3803                    let inner = map.get(outer);
3804                    let nested = match inner {
3805                        Some(found) => found.as_map(),
3806                        None => None,
3807                    };
3808                    if let Some(wallet) = nested {
3809                        let mut codes: Vec<String> = wallet.keys().cloned().collect();
3810                        codes.sort();
3811                        for code in codes.iter() {
3812                            let amount = self.number_at(inner.unwrap(), code, 0.0);
3813                            if amount > 0.0 {
3814                                let mut entry = HashMap::new();
3815                                entry.insert("exchangeId".to_string(), Value::Str(outer.clone().into()));
3816                                entry.insert("asset".to_string(), Value::Str(code.clone().into()));
3817                                entry.insert("amount".to_string(), Value::Float(amount));
3818                                entries.push(Value::Map(entry));
3819                            }
3820                        }
3821                        continue;
3822                    }
3823                    let amount = self.number_at(value, outer, 0.0);
3824                    if amount > 0.0 {
3825                        //  no venue: a bare ASSET:amount means "wherever you hold it"
3826                        let mut entry = HashMap::new();
3827                        entry.insert("exchangeId".to_string(), Value::Str(Cow::Borrowed("")));
3828                        entry.insert("asset".to_string(), Value::Str(outer.clone().into()));
3829                        entry.insert("amount".to_string(), Value::Float(amount));
3830                        entries.push(Value::Map(entry));
3831                    }
3832                }
3833                self.join_balances(&entries)
3834            }
3835            None => Err(bad_request(
3836                "OrderRouter: balances must be \"[exchangeId.]ASSET:amount\" entries, or a wallet like {\"mexc\": {\"USDT\": 100}} or {\"USDT\": 100}",
3837            )),
3838        }
3839    }
3840
3841    pub(crate) fn join_balances(&self, entries: &[Value]) -> RouterResult<String> {
3842        let mut text = String::new();
3843        for (i, entry) in entries.iter().enumerate() {
3844            if i > 0 {
3845                text.push(',');
3846            }
3847            //  a bare ASSET:amount, with no venue, means "wherever you hold it"
3848            let venue_prefix = self.string_at(entry, "exchangeId", "");
3849            if !venue_prefix.is_empty() {
3850                text.push_str(&venue_prefix);
3851                text.push('.');
3852            }
3853            text.push_str(&self.string_at(entry, "asset", ""));
3854            text.push(':');
3855            text.push_str(&self.format_number(self.number_at(entry, "amount", 0.0))?);
3856        }
3857        Ok(text)
3858    }
3859
3860    /// Reads the live balances of the supplied venues, sends them to the router,
3861    /// and returns a route you can actually fund.
3862    ///
3863    /// The returned route carries two client-side additions: `balancesUsed`,
3864    /// the exact string sent, and `balancesDropped`, everything that did not fit
3865    /// and why.
3866    /// Reads the venues' wallets once and caches the result, so a quote stays a single HTTP
3867    /// request. Called for you by `fetch_route`; call it yourself to prime the cache at
3868    /// start-up, or with `reload` to refresh it.
3869    pub async fn load_balances(&self, reload: bool) -> RouterResult<String> {
3870        if !self.track_balances || self.venues.is_empty() {
3871            //  not this router's job: it was not asked to manage balances
3872            return Ok(String::new());
3873        }
3874        if !reload {
3875            if let Some(cached) = self.shared_op(|s| s.balances.clone()) {
3876                return Ok(cached);
3877            }
3878        }
3879        let generation = self.shared_op(|s| s.generation);
3880        let (balances, _dropped) = self.collect_balances(&self.venues).await?;
3881        //  an invalidation landed while these wallets were being read, which means money
3882        //  moved under this snapshot. It is still the right answer for THIS caller, but it
3883        //  must not become the cache the next quote trusts.
3884        let snapshot = balances.clone();
3885        self.shared_op(move |s| {
3886            if s.generation == generation { s.balances = Some(snapshot); }
3887        });
3888        Ok(balances)
3889    }
3890
3891    /// Drops the cached balances, so the next quote re-reads the wallets.
3892    pub fn invalidate_balances(&self) {
3893        self.shared_op(|s| {
3894            s.generation = s.generation.wrapping_add(1);
3895            s.balances = None;
3896        });
3897    }
3898
3899    /// Reports whether a balances snapshot is currently cached.
3900    pub fn balances_are_loaded(&self) -> bool {
3901        self.shared_op(|s| s.balances.is_some())
3902    }
3903
3904    /// Reads every supplied venue's wallet and renders it as the router's balances string,
3905    /// trimmed to the router's caps. Returns the string and the entries that did not fit.
3906    pub async fn collect_balances(
3907        &self,
3908        venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3909    ) -> RouterResult<(String, Vec<Value>)> {
3910        let mut entries: Vec<Value> = Vec::new();
3911        let mut dropped: Vec<Value> = Vec::new();
3912        // BTreeMap iterates in key order, which is the sort the other five ports
3913        // do explicitly — six languages must build the same string from the same
3914        // wallet.
3915        for (exchange_id, venue) in venues.iter() {
3916            let balance = venue.fetch_balance().await?;
3917            let mut holdings = self.dict_at(&balance, "free");
3918            if holdings.as_map().map(|m| m.is_empty()).unwrap_or(true) {
3919                holdings = self.dict_at(&balance, "total");
3920            }
3921            let mut codes: Vec<String> = match holdings.as_map() {
3922                Some(map) => map.keys().cloned().collect(),
3923                None => Vec::new(),
3924            };
3925            codes.sort();
3926            for code in &codes {
3927                let amount = self.number_at(&holdings, code, 0.0);
3928                if amount <= 0.0 {
3929                    // A zero holding is not information, and it costs one of the
3930                    // router's 64 entries.
3931                    continue;
3932                }
3933                let mut entry = HashMap::new();
3934                entry.insert("exchangeId".to_string(), Value::Str(exchange_id.clone().into()));
3935                entry.insert("asset".to_string(), Value::Str(code.clone().into()));
3936                entry.insert("amount".to_string(), Value::Float(amount));
3937                if amount >= 1e18 {
3938                    // Beyond fixed-point rendering; reported rather than sent,
3939                    // because a silently reshaped amount is worse than a missing
3940                    // one.
3941                    entry.insert("reason".to_string(), Value::Str("amount_out_of_range".to_string().into()));
3942                    dropped.push(Value::Map(entry));
3943                    continue;
3944                }
3945                entries.push(Value::Map(entry));
3946            }
3947        }
3948        // Largest first, so trimming to the router's caps drops the smallest
3949        // holdings. Ties break on exchangeId then asset so six languages produce
3950        // the same list from the same wallet.
3951        entries.sort_by(|a, b| {
3952            let amount_a = self.number_at(a, "amount", 0.0);
3953            let amount_b = self.number_at(b, "amount", 0.0);
3954            if amount_a != amount_b {
3955                // Descending. partial_cmp cannot be None here: number_at only
3956                // ever returns a finite number.
3957                return amount_b.partial_cmp(&amount_a).unwrap_or(std::cmp::Ordering::Equal);
3958            }
3959            let id_a = self.string_at(a, "exchangeId", "");
3960            let id_b = self.string_at(b, "exchangeId", "");
3961            if id_a != id_b {
3962                return id_a.cmp(&id_b);
3963            }
3964            self.string_at(a, "asset", "").cmp(&self.string_at(b, "asset", ""))
3965        });
3966        while entries.len() > MAX_BALANCE_ENTRIES {
3967            let mut removed = entries.pop().expect("entries is non-empty inside this loop");
3968            Self::put(&mut removed, "reason", Value::Str("entry_cap".to_string().into()));
3969            dropped.push(removed);
3970        }
3971        let mut balances = self.join_balances(&entries)?;
3972        while balances.len() > MAX_BALANCE_CHARS && !entries.is_empty() {
3973            let mut removed = entries.pop().expect("entries is non-empty inside this loop");
3974            Self::put(&mut removed, "reason", Value::Str("char_cap".to_string().into()));
3975            dropped.push(removed);
3976            balances = self.join_balances(&entries)?;
3977        }
3978        Ok((balances, dropped))
3979    }
3980
3981    pub async fn fetch_route_with_balances(
3982        &self,
3983        from_asset: &str,
3984        to_asset: &str,
3985        venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3986        params: &Value,
3987    ) -> RouterResult<Value> {
3988        let require_applied = self.bool_at(params, "requireBalancesApplied", true);
3989        let venues = if venues.is_empty() { &self.venues } else { venues };
3990        let (balances, dropped) = self.collect_balances(venues).await?;
3991        let mut route_params = HashMap::new();
3992        if let Some(map) = params.as_map() {
3993            for (key, value) in map.iter() {
3994                route_params.insert(key.clone(), value.clone());
3995            }
3996        }
3997        route_params.insert("balances".to_string(), Value::Str(balances.clone().into()));
3998        let mut route = self.fetch_route(from_asset, to_asset, &Value::Map(route_params)).await?;
3999        if require_applied && !balances.is_empty() && self.string_at(&route, "balancesApplied", "").is_empty() {
4000            // /route declares its query without a JSON schema, so a router that
4001            // predates the balances feature answers byte-identically to one that
4002            // never received it. Executing a plan computed against a portfolio
4003            // the server never saw is the case worth failing on.
4004            return Err(exchange_error(
4005                "OrderRouter did not echo balancesApplied: the balances were ignored, so this route is not funded-aware",
4006            ));
4007        }
4008        Self::put(&mut route, "balancesUsed", Value::Str(balances.into()));
4009        Self::put(&mut route, "balancesDropped", Value::List(dropped));
4010        Ok(route)
4011    }
4012}