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