fyuz-sdk 0.1.1

Async Rust client for the Fyuz public REST API — bonding-curve token market data on BNB Smart Chain.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! The smallest ABI codec that covers this contract, and nothing more.
//!
//! Every argument the Fyuz swap entrypoints take is a static 32-byte word —
//! `address`, `uint256`, `bool` — and so is every value they return. That makes
//! encoding a selector followed by left-padded words, and decoding a walk over
//! fixed offsets. No dynamic types, no head/tail split, no ABI crate.
//!
//! Selectors are **pinned constants**, not computed. Deriving one needs
//! keccak-256, which this crate deliberately does not carry. The values below
//! came from `cast sig` and are asserted against
//! `shared/test-vectors/trade-calldata.json`, so a typo fails the test suite
//! rather than sending a transaction to the wrong function.
//!
//! # Why a hand-rolled [`U256`]
//!
//! `u128` is not enough. An ERC-20 `allowance` is `2^256 - 1` for every wallet
//! that has ever approved unlimited spending — the common case — and a `u128`
//! decoder would fail on the most ordinary value there is. [`U256`] is a
//! big-endian `[u8; 32]` with just the operations this crate performs: parse,
//! format, add/sub, multiply-then-divide by a small factor for slippage, and
//! [`U256::mul_div`] for the one place a full-width `a * b / c` is unavoidable —
//! reproducing the contract's `getAmountIn`, where `virtualEthReserve *
//! amountOut` overflows `uint256` long before the division brings it back.

use std::cmp::Ordering;
use std::fmt;

use crate::Error;

/// `swapExactETHForTokens(address,uint256,uint256,uint256)`
pub const SELECTOR_SWAP_EXACT_ETH_FOR_TOKENS: &str = "0x6bf05b01";
/// `swapETHForExactTokens(address,uint256,uint256,uint256)`
pub const SELECTOR_SWAP_ETH_FOR_EXACT_TOKENS: &str = "0x0541a872";
/// `swapExactTokensForETH(address,uint256,uint256,uint256)`
pub const SELECTOR_SWAP_EXACT_TOKENS_FOR_ETH: &str = "0xeacad12a";
/// `getSwapOutput(address,uint256,bool)`
pub const SELECTOR_GET_SWAP_OUTPUT: &str = "0x908235cc";
/// `getFirstBuyFee(address)`
pub const SELECTOR_GET_FIRST_BUY_FEE: &str = "0xb3cd4902";
/// `getMaxSellableETH(address)`
pub const SELECTOR_GET_MAX_SELLABLE_ETH: &str = "0x82bfb367";
/// `tokenPools(address)`
pub const SELECTOR_TOKEN_POOLS: &str = "0xc3d2c3c1";
/// `approve(address,uint256)`
pub const SELECTOR_APPROVE: &str = "0x095ea7b3";
/// `allowance(address,address)`
pub const SELECTOR_ALLOWANCE: &str = "0xdd62ed3e";
/// `balanceOf(address)`
pub const SELECTOR_BALANCE_OF: &str = "0x70a08231";
/// `PLATFORM_BUY_FEE_BPS()` — public storage with an owner setter
/// (`setPlatformBuyFeeBps`), so it is read rather than assumed.
pub const SELECTOR_PLATFORM_BUY_FEE_BPS: &str = "0x04357acd";
/// `TOKEN_OWNER_FEE_BPS()` — likewise owner-settable.
pub const SELECTOR_TOKEN_OWNER_FEE_BPS: &str = "0xfa3746d8";
/// `paused()`
pub const SELECTOR_PAUSED: &str = "0x5c975abb";

fn invalid(message: impl Into<String>) -> Error {
    Error::InvalidArgument {
        message: message.into(),
    }
}

/// A 256-bit unsigned integer, stored big-endian.
///
/// Only the operations this crate needs are implemented. It is not a
/// general-purpose numeric type and makes no attempt to be one — reach for
/// `primitive-types` or `ruint` if you need arithmetic beyond this.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct U256([u8; 32]);

impl U256 {
    /// Zero.
    pub const ZERO: U256 = U256([0u8; 32]);

    /// `2^256 - 1`, the unlimited-approval amount.
    pub const MAX: U256 = U256([0xffu8; 32]);

    /// From a small value.
    pub fn from_u64(value: u64) -> Self {
        let mut bytes = [0u8; 32];
        bytes[24..].copy_from_slice(&value.to_be_bytes());
        U256(bytes)
    }

    /// From its big-endian bytes.
    pub fn from_be_bytes(bytes: [u8; 32]) -> Self {
        U256(bytes)
    }

    /// Its big-endian bytes.
    pub fn to_be_bytes(self) -> [u8; 32] {
        self.0
    }

    /// Whether this is zero.
    pub fn is_zero(self) -> bool {
        self.0.iter().all(|&byte| byte == 0)
    }

    /// Parse a base-10 string.
    ///
    /// Rejects anything with a decimal point: a caller passing `"0.5"` means
    /// whole units, not wei, and silently reading that as zero would build a
    /// transaction that buys nothing. Use [`parse_units`] for the conversion.
    pub fn from_dec_str(name: &str, value: &str) -> Result<Self, Error> {
        if value.is_empty() {
            return Err(invalid(format!("{name} must not be empty")));
        }
        if value.contains('.') {
            return Err(invalid(format!(
                "{name} must be a whole amount in wei, got {value:?} — decimal input \
                 looks like whole units, convert it with parse_units first"
            )));
        }

        let mut acc = U256::ZERO;
        for character in value.chars() {
            let digit = character
                .to_digit(10)
                .ok_or_else(|| invalid(format!("{name} must be base-10 digits, got {value:?}")))?;
            acc = acc
                .mul_small(10)
                .and_then(|scaled| scaled.add_small(digit))
                .ok_or_else(|| invalid(format!("{name} exceeds uint256")))?;
        }
        Ok(acc)
    }

    /// Parse one 64-character hex word.
    pub fn from_hex_word(word: &str) -> Result<Self, Error> {
        let trimmed = word.strip_prefix("0x").unwrap_or(word);
        if trimmed.len() != 64 {
            return Err(invalid(format!(
                "expected a 32-byte word, got {} hex characters",
                trimmed.len()
            )));
        }
        let mut bytes = [0u8; 32];
        for (index, byte) in bytes.iter_mut().enumerate() {
            *byte = u8::from_str_radix(&trimmed[index * 2..index * 2 + 2], 16)
                .map_err(|_| invalid(format!("word is not valid hex: {word}")))?;
        }
        Ok(U256(bytes))
    }

    /// Render as one 64-character hex word, ready to concatenate into calldata.
    pub fn to_hex_word(self) -> String {
        self.0.iter().map(|byte| format!("{byte:02x}")).collect()
    }

    /// `self + other`, or `None` on overflow.
    pub fn checked_add(self, other: Self) -> Option<Self> {
        let mut out = [0u8; 32];
        let mut carry = 0u16;
        for index in (0..32).rev() {
            let sum = u16::from(self.0[index]) + u16::from(other.0[index]) + carry;
            out[index] = sum as u8;
            carry = sum >> 8;
        }
        (carry == 0).then_some(U256(out))
    }

    /// `self - other`, or `None` when it would go negative.
    pub fn checked_sub(self, other: Self) -> Option<Self> {
        let mut out = [0u8; 32];
        let mut borrow = 0i16;
        for index in (0..32).rev() {
            let diff = i16::from(self.0[index]) - i16::from(other.0[index]) - borrow;
            if diff < 0 {
                out[index] = (diff + 256) as u8;
                borrow = 1;
            } else {
                out[index] = diff as u8;
                borrow = 0;
            }
        }
        (borrow == 0).then_some(U256(out))
    }

    /// `self * factor`, or `None` on overflow.
    pub fn mul_small(self, factor: u32) -> Option<Self> {
        let mut out = [0u8; 32];
        let mut carry = 0u64;
        for index in (0..32).rev() {
            let product = u64::from(self.0[index]) * u64::from(factor) + carry;
            out[index] = product as u8;
            carry = product >> 8;
        }
        (carry == 0).then_some(U256(out))
    }

    /// `self + digit`, or `None` on overflow.
    fn add_small(self, digit: u32) -> Option<Self> {
        self.checked_add(U256::from_u64(u64::from(digit)))
    }

    /// `floor(self * factor / divisor)`, or `None` when there is no answer to
    /// give: a zero `divisor`, or a quotient past `2^256 - 1`.
    ///
    /// The intermediate product is held at full width, in 512 bits, which is the
    /// whole point of the function. The contract's `getAmountIn` computes
    /// `virtualEthReserve * amountOut / (virtualTokenReserve - amountOut)`, and
    /// on a live curve that numerator is around `2^150` — an
    /// [`mul_small`](Self::mul_small)-then-divide would report overflow on a
    /// trade the contract prices without blinking, and a caller who worked around
    /// that by dividing first would be off by the remainder on every buy.
    ///
    /// ```
    /// # use fyuz::U256;
    /// // Neither operand fits an intermediate uint256 on its own …
    /// let big = U256::from_dec_str("a", "340282366920938463463374607431768211456").unwrap();
    /// // … but 2^128 * 2^128 / 2^128 does.
    /// assert_eq!(big.mul_div(big, big).unwrap(), big);
    /// assert_eq!(U256::from_u64(7).mul_div(U256::from_u64(3), U256::from_u64(2)).unwrap(),
    ///            U256::from_u64(10), "floor(21/2)");
    /// assert!(U256::from_u64(1).mul_div(U256::from_u64(1), U256::ZERO).is_none());
    /// ```
    pub fn mul_div(self, factor: Self, divisor: Self) -> Option<Self> {
        if divisor.is_zero() {
            return None;
        }

        // Schoolbook, byte by byte, into twice the width. `product[i + j + 1]`
        // is where a byte pair lands; the carry out of each pass lands one place
        // to its left, which no later pass has written yet.
        let mut product = [0u8; 64];
        for i in (0..32).rev() {
            let mut carry = 0u32;
            for j in (0..32).rev() {
                let at = i + j + 1;
                let sum =
                    u32::from(product[at]) + u32::from(self.0[i]) * u32::from(factor.0[j]) + carry;
                product[at] = sum as u8;
                carry = sum >> 8;
            }
            product[i] = carry as u8;
        }

        // Binary long division: walk the product from its top bit, shifting each
        // one into a running remainder and subtracting the divisor whenever it
        // fits. 512 passes over 32 bytes, which is nothing next to the RPC round
        // trip that produced the operands.
        let mut quotient = [0u8; 64];
        let mut remainder = [0u8; 32];
        for bit in 0..512 {
            let mut carry = (product[bit / 8] >> (7 - bit % 8)) & 1;
            for byte in remainder.iter_mut().rev() {
                let shifted = (u16::from(*byte) << 1) | u16::from(carry);
                *byte = shifted as u8;
                carry = (shifted >> 8) as u8;
            }

            // `carry` is the 257th bit of the shifted remainder. Set, it is
            // already past any 256-bit divisor, and the subtraction below is
            // still exact: the remainder before the shift was under the divisor,
            // so twice it plus a bit is under twice the divisor, and the true
            // difference therefore lands back inside 256 bits.
            if carry == 1 || U256(remainder) >= divisor {
                remainder = U256(remainder).wrapping_sub(divisor).0;
                quotient[bit / 8] |= 1 << (7 - bit % 8);
            }
        }

        if quotient[..32].iter().any(|&byte| byte != 0) {
            return None;
        }
        let mut out = [0u8; 32];
        out.copy_from_slice(&quotient[32..]);
        Some(U256(out))
    }

    /// `self - other` modulo `2^256`. Private: every caller in this crate wants
    /// [`checked_sub`](Self::checked_sub), except the one place inside
    /// [`mul_div`](Self::mul_div) that has already proved the result is positive.
    fn wrapping_sub(self, other: Self) -> Self {
        let mut out = [0u8; 32];
        let mut borrow = 0i16;
        for index in (0..32).rev() {
            let diff = i16::from(self.0[index]) - i16::from(other.0[index]) - borrow;
            if diff < 0 {
                out[index] = (diff + 256) as u8;
                borrow = 1;
            } else {
                out[index] = diff as u8;
                borrow = 0;
            }
        }
        U256(out)
    }

    /// `(self / divisor, self % divisor)`. Panics only on a zero divisor, which
    /// is never reachable from this crate's call sites.
    pub fn div_rem_small(self, divisor: u32) -> (Self, u32) {
        assert!(divisor != 0, "division by zero");
        let mut out = [0u8; 32];
        let mut remainder = 0u64;
        for (slot, &byte) in out.iter_mut().zip(self.0.iter()) {
            let current = (remainder << 8) | u64::from(byte);
            *slot = (current / u64::from(divisor)) as u8;
            remainder = current % u64::from(divisor);
        }
        (U256(out), remainder as u32)
    }
}

impl fmt::Display for U256 {
    /// Base-10, exactly. This is the representation to log and to hand onward.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_zero() {
            return f.write_str("0");
        }
        let mut digits = Vec::new();
        let mut value = *self;
        while !value.is_zero() {
            let (quotient, remainder) = value.div_rem_small(10);
            digits.push(b'0' + remainder as u8);
            value = quotient;
        }
        digits.reverse();
        f.write_str(&String::from_utf8(digits).expect("ascii digits"))
    }
}

impl PartialOrd for U256 {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for U256 {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.cmp(&other.0)
    }
}

/// Validate an EVM address and return it lower-cased.
///
/// EIP-55 checksums are accepted but not verified: confirming one needs
/// keccak-256, and the encoded word is identical either way. What is checked is
/// the part that can actually corrupt a transaction — that the value is 20 hex
/// bytes and not, say, a token symbol or a truncated paste.
pub fn normalize_address(name: &str, value: &str) -> Result<String, Error> {
    let body = value.strip_prefix("0x").ok_or_else(|| {
        invalid(format!(
            "{name} must be a 0x-prefixed 20-byte address, got {value:?}"
        ))
    })?;
    if body.len() != 40 || !body.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(invalid(format!(
            "{name} must be a 0x-prefixed 20-byte address, got {value:?}"
        )));
    }
    Ok(value.to_ascii_lowercase())
}

/// Whole units to the smallest unit — `"0.5"` BNB to `500000000000000000` wei.
///
/// String in, [`U256`] out, with no float anywhere in between: `0.1 * 1e18` in
/// `f64` gives `100000000000000000` on a good day and `99999999999999998` on a
/// bad one.
pub fn parse_units(value: &str, decimals: u32) -> Result<U256, Error> {
    let (whole, fraction) = match value.split_once('.') {
        Some((whole, fraction)) => (whole, fraction),
        None => (value, ""),
    };
    if fraction.len() > decimals as usize {
        return Err(invalid(format!(
            "amount {value:?} has {} decimal places, more than the {decimals} this token \
             carries — the extra digits would be silently truncated",
            fraction.len()
        )));
    }
    if !whole.chars().all(|c| c.is_ascii_digit())
        || !fraction.chars().all(|c| c.is_ascii_digit())
        || (whole.is_empty() && fraction.is_empty())
    {
        return Err(invalid(format!(
            "amount must be a non-negative decimal string, got {value:?}"
        )));
    }

    let padded = format!(
        "{}{}{}",
        if whole.is_empty() { "0" } else { whole },
        fraction,
        "0".repeat(decimals as usize - fraction.len())
    );
    U256::from_dec_str("amount", &padded)
}

/// The smallest unit back to whole units, exactly. Inverse of [`parse_units`].
pub fn format_units(value: U256, decimals: u32) -> String {
    // Done on the decimal digits rather than by dividing: the split point is
    // just a string offset once the value is base-10, and that avoids a second
    // big-integer division path to get wrong.
    let digits = value.to_string();
    let decimals = decimals as usize;

    let (whole, fraction) = if digits.len() > decimals {
        digits.split_at(digits.len() - decimals)
    } else {
        ("0", digits.as_str())
    };

    let padded = format!(
        "{}{}",
        "0".repeat(decimals.saturating_sub(fraction.len())),
        fraction
    );
    let trimmed = padded.trim_end_matches('0');

    if trimmed.is_empty() {
        whole.to_string()
    } else {
        format!("{whole}.{trimmed}")
    }
}

/// An `address` as one 64-character word: 12 zero bytes then the 20 address bytes.
///
/// Fallible on purpose. Left-padding whatever it is handed would turn a 21-byte
/// value into a 65-character "word", shifting every argument after it by half a
/// byte — calldata that still decodes, against a completely different set of
/// arguments. Every address this crate encodes therefore goes through
/// [`normalize_address`] here, whether it came from the caller or from
/// `GET /config`.
pub fn address_word(address: &str) -> Result<String, Error> {
    let normalized = normalize_address("address", address)?;
    Ok(format!("{:0>64}", &normalized[2..]))
}

/// A `uint256` as one 64-character word.
pub fn uint256_word(value: U256) -> String {
    value.to_hex_word()
}

/// A `bool` as one 64-character word.
pub fn bool_word(value: bool) -> String {
    U256::from_u64(u64::from(value)).to_hex_word()
}

/// Selector plus words, as `0x`-prefixed calldata.
pub fn encode_call(selector: &str, words: &[String]) -> String {
    let mut out = String::from(selector);
    for word in words {
        out.push_str(word);
    }
    out
}

/// Strip `0x` and reject anything that is not whole bytes of hex.
fn hex_body(data: &str) -> Result<&str, Error> {
    let body = data.strip_prefix("0x").unwrap_or(data);
    if body.len() % 2 != 0 || !body.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(invalid(format!("expected hex data, got {data:?}")));
    }
    Ok(body)
}

/// Read the `index`-th 32-byte word of a return payload as a `uint256`.
///
/// Errors on a short payload rather than yielding zero. A truncated response and
/// a genuine zero are very different answers to "how many tokens do I get", and
/// only one of them should let a transaction get built.
pub fn decode_uint256_at(data: &str, index: usize) -> Result<U256, Error> {
    let body = hex_body(data)?;
    let start = index * 64;
    if body.len() < start + 64 {
        return Err(invalid(format!(
            "response has {} words, expected at least {}",
            body.len() / 64,
            index + 1
        )));
    }
    U256::from_hex_word(&body[start..start + 64])
}

/// Read the `index`-th word as a `bool`. Any non-zero word is `true`.
pub fn decode_bool_at(data: &str, index: usize) -> Result<bool, Error> {
    Ok(!decode_uint256_at(data, index)?.is_zero())
}

/// Read the `index`-th word as an `address`, lower-cased.
pub fn decode_address_at(data: &str, index: usize) -> Result<String, Error> {
    let word = decode_uint256_at(data, index)?.to_hex_word();
    Ok(format!("0x{}", &word[24..]))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `2^256 - 1` written out, so a quotient that does not fit can be spotted
    /// by the reference implementation without asking [`U256`] anything.
    const UINT256_MAX: &str =
        "115792089237316195423570985008687907853269984665640564039457584007913129639935";

    /// The values every triple below is drawn from: the boundaries a byte-wise
    /// implementation gets wrong (`255`/`256`, `2^64`, `2^128`), zero and one,
    /// the widest possible operand, and the three live curve numbers whose
    /// product is what [`U256::mul_div`] exists for.
    const SPREAD: [&str; 11] = [
        "0",
        "1",
        "2",
        "255",
        "256",
        "18446744073709551616",
        "340282366920938463463374607431768211455",
        "8337685194944913640",
        "1061715547304072332277807447",
        "1000000000000000000000000",
        UINT256_MAX,
    ];

    fn u256(value: &str) -> U256 {
        U256::from_dec_str("value", value).expect("a uint256 in range")
    }

    // ---------------------------------------------------------- the reference
    //
    // Base-10 schoolbook on digit vectors, least significant first. It shares no
    // line of code with `mul_div` — not the radix, not the division algorithm —
    // so the two agreeing is evidence rather than the same bug twice.

    fn digits(value: &str) -> Vec<u8> {
        value.bytes().rev().map(|byte| byte - b'0').collect()
    }

    fn text(mut value: Vec<u8>) -> String {
        while value.len() > 1 && value.last() == Some(&0) {
            value.pop();
        }
        value.iter().rev().map(|d| char::from(b'0' + d)).collect()
    }

    fn multiply(left: &[u8], right: &[u8]) -> Vec<u8> {
        let mut out = vec![0u8; left.len() + right.len() + 1];
        for (i, &x) in left.iter().enumerate() {
            let mut carry = 0u32;
            for (j, &y) in right.iter().enumerate() {
                let sum = u32::from(out[i + j]) + u32::from(x) * u32::from(y) + carry;
                out[i + j] = (sum % 10) as u8;
                carry = sum / 10;
            }
            let mut at = i + right.len();
            while carry > 0 {
                let sum = u32::from(out[at]) + carry;
                out[at] = (sum % 10) as u8;
                carry = sum / 10;
                at += 1;
            }
        }
        out
    }

    fn compare(left: &[u8], right: &[u8]) -> Ordering {
        let (left, right) = (trimmed(left), trimmed(right));
        left.len()
            .cmp(&right.len())
            .then_with(|| left.iter().rev().cmp(right.iter().rev()))
    }

    fn trimmed(value: &[u8]) -> &[u8] {
        let mut end = value.len();
        while end > 1 && value[end - 1] == 0 {
            end -= 1;
        }
        &value[..end]
    }

    fn subtract(left: &[u8], right: &[u8]) -> Vec<u8> {
        let mut out = left.to_vec();
        let mut borrow = 0i16;
        for (index, slot) in out.iter_mut().enumerate() {
            let take = i16::from(*right.get(index).unwrap_or(&0)) + borrow;
            let digit = i16::from(*slot) - take;
            if digit < 0 {
                *slot = (digit + 10) as u8;
                borrow = 1;
            } else {
                *slot = digit as u8;
                borrow = 0;
            }
        }
        assert_eq!(borrow, 0, "the reference never subtracts past zero");
        out
    }

    /// `floor(left / right)` by long division, one decimal digit at a time.
    fn divide(left: &[u8], right: &[u8]) -> Vec<u8> {
        let mut quotient = vec![0u8; left.len()];
        let mut remainder: Vec<u8> = vec![0];
        for index in (0..left.len()).rev() {
            remainder.insert(0, left[index]);
            let mut digit = 0u8;
            while compare(&remainder, right) != Ordering::Less {
                remainder = subtract(&remainder, right);
                digit += 1;
            }
            quotient[index] = digit;
        }
        quotient
    }

    /// `floor(a * b / c)` as decimal text, or `None` when `c` is zero.
    fn reference_mul_div(a: &str, b: &str, c: &str) -> Option<String> {
        if c.bytes().all(|byte| byte == b'0') {
            return None;
        }
        Some(text(divide(&multiply(&digits(a), &digits(b)), &digits(c))))
    }

    // ------------------------------------------------------------- the checks

    #[test]
    fn the_reference_divides_the_way_the_evm_does() {
        // The reference is only worth comparing against if it is right, and it
        // is 60 lines of hand-rolled base-10. These are the answers by eye.
        assert_eq!(reference_mul_div("7", "3", "2").as_deref(), Some("10"));
        assert_eq!(reference_mul_div("1", "1", "2").as_deref(), Some("0"));
        assert_eq!(reference_mul_div("0", "5", "7").as_deref(), Some("0"));
        assert_eq!(
            reference_mul_div("255", "256", "1").as_deref(),
            Some("65280")
        );
        assert_eq!(reference_mul_div("5", "5", "0"), None);
    }

    #[test]
    fn mul_div_agrees_with_a_slow_reference_across_the_spread() {
        for a in SPREAD {
            for b in SPREAD {
                for c in SPREAD {
                    let expected = reference_mul_div(a, b, c);
                    let actual = u256(a).mul_div(u256(b), u256(c));

                    match (&expected, actual) {
                        // A quotient past uint256 has no representation, so the
                        // only honest answer is None — never a truncated word.
                        (Some(quotient), _) if quotient.len() > UINT256_MAX.len() => {
                            assert!(actual.is_none(), "{a} * {b} / {c} = {quotient} overflows");
                        }
                        (Some(quotient), Some(got)) => {
                            assert_eq!(&got.to_string(), quotient, "{a} * {b} / {c}");
                        }
                        (Some(quotient), None) => {
                            assert!(
                                compare(&digits(quotient), &digits(UINT256_MAX))
                                    == Ordering::Greater,
                                "{a} * {b} / {c} = {quotient} fits and should not be refused"
                            );
                        }
                        (None, got) => assert_eq!(got, None, "a zero divisor has no answer"),
                    }
                }
            }
        }
    }

    #[test]
    fn mul_div_refuses_a_zero_divisor_rather_than_panicking() {
        // `div_rem_small` asserts, because nothing can reach it with a zero.
        // This one is reachable: the divisor is `virtualTokenReserve -
        // amountOut`, straight off a curve the SDK does not control.
        assert_eq!(U256::MAX.mul_div(U256::MAX, U256::ZERO), None);
        assert_eq!(U256::ZERO.mul_div(U256::ZERO, U256::ZERO), None);
    }

    #[test]
    fn mul_div_carries_a_product_that_does_not_fit_in_a_uint256() {
        // The case the old bisection existed to avoid. `2^255 * 2^255` needs 510
        // bits; dividing by `2^254` brings it back to `2^256`, which does not
        // fit, and by `2^255` to `2^255`, which does.
        let two_255 =
            u256("57896044618658097711785492504343953926634992332820282019728792003956564819968");
        assert_eq!(two_255.mul_div(two_255, two_255), Some(two_255));
        assert!(
            two_255.mul_div(two_255, U256::from_u64(2)).is_none(),
            "2^509 does not fit"
        );
        // And the exact boundary: MAX * MAX / MAX is MAX, one wei of divisor
        // less is not representable.
        assert_eq!(U256::MAX.mul_div(U256::MAX, U256::MAX), Some(U256::MAX));
        assert_eq!(
            U256::MAX.mul_div(U256::MAX, U256::MAX.checked_sub(U256::from_u64(1)).unwrap()),
            None
        );
    }

    #[test]
    fn mul_div_handles_zero_and_one_without_a_special_case() {
        assert_eq!(
            U256::ZERO.mul_div(U256::MAX, U256::from_u64(1)),
            Some(U256::ZERO)
        );
        assert_eq!(
            U256::MAX.mul_div(U256::from_u64(1), U256::from_u64(1)),
            Some(U256::MAX)
        );
        assert_eq!(
            U256::from_u64(1).mul_div(U256::from_u64(1), U256::MAX),
            Some(U256::ZERO),
            "flooring, not rounding"
        );
    }

    #[test]
    fn mul_div_reproduces_the_contracts_get_amount_in_on_a_live_curve() {
        // The reserves the fork carried when this was verified against the chain
        // by bisecting eth_call: 8911076867959950 wei succeeds for a million
        // tokens and one wei less reverts. This is the pre-fee half of that
        // number, which is where the full-width product is needed — the
        // numerator alone is about 2^153.
        let virtual_eth = u256("8832685194944913640");
        let virtual_token = u256("1002215046118283895434733086");
        let wanted = u256("1000000000000000000000000");

        let before_fee = virtual_eth
            .mul_div(wanted, virtual_token.checked_sub(wanted).unwrap())
            .expect("the quotient is small")
            .checked_add(U256::from_u64(1))
            .expect("the contract's +1");
        assert_eq!(before_fee.to_string(), "8821966099280351");

        let cost = before_fee
            .mul_div(U256::from_u64(10_000), U256::from_u64(10_000 - 100))
            .expect("the gross-up");
        assert_eq!(cost.to_string(), "8911076867959950");
    }
}