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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
//! Trading against the bonding curve.
//!
//! This module builds **unsigned transactions**. It never sees a private key,
//! never signs and never broadcasts — it hands you an [`UnsignedTransaction`]
//! and you pass that to whatever wallet you already have (`alloy`, `ethers-rs`,
//! a hardware signer, a multisig UI). Signing is the part that needs a crypto
//! stack, and it is not here.
//!
//! ```no_run
//! # async fn demo() -> Result<(), fyuz::Error> {
//! use fyuz::{parse_units, BuyParams, FyuzClient};
//!
//! let client = FyuzClient::new()?;
//! let built = client
//!     .trade()
//!     .build_buy(
//!         &BuyParams::new("0x0000000000000000000000000000000000000001", parse_units("0.5", 18)?)
//!             .slippage_bps(100),
//!     )
//!     .await?;
//!
//! println!("expecting {} tokens", built.quote.amount_out_wei);
//! # Ok(())
//! # }
//! ```
//!
//! Quotes come from the contract, not from arithmetic here: every one is an
//! `eth_call` to `getSwapOutput`. Reimplementing the curve locally would mean a
//! second formula that has to be kept in step with an upgradeable contract, and
//! the day they disagree is the day someone's `min_amount_out` is wrong.
//!
//! Slippage is never chosen for you. [`TradeApi::build_buy`] and
//! [`TradeApi::build_sell`] require either `slippage_bps` or an explicit
//! `limit_wei`; a default here would be a number picked by someone who cannot
//! see the trade.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use tokio::sync::{Mutex, OnceCell};

use crate::abi::{
    address_word, bool_word, decode_bool_at, decode_uint256_at, encode_call, normalize_address,
    uint256_word, SELECTOR_ALLOWANCE, SELECTOR_APPROVE, SELECTOR_BALANCE_OF,
    SELECTOR_GET_FIRST_BUY_FEE, SELECTOR_GET_MAX_SELLABLE_ETH, SELECTOR_GET_SWAP_OUTPUT,
    SELECTOR_PAUSED, SELECTOR_PLATFORM_BUY_FEE_BPS, SELECTOR_SWAP_ETH_FOR_EXACT_TOKENS,
    SELECTOR_SWAP_EXACT_ETH_FOR_TOKENS, SELECTOR_SWAP_EXACT_TOKENS_FOR_ETH,
    SELECTOR_TOKEN_OWNER_FEE_BPS, SELECTOR_TOKEN_POOLS, U256,
};
use crate::addresses::{deployment_for_chain_id, deployment_for_network, Deployment, DEPLOYMENTS};
use crate::models::ChainInfo;
use crate::revert::{graduated_error, revert_error, revert_selector, SELECTOR_ALREADY_LAUNCHED};
use crate::rpc::{CallOutcome, RpcClient, DEFAULT_BLOCK_TAG};
use crate::{Error, FyuzClient};

/// Basis points in 100%.
const BPS_DIVISOR: u32 = 10_000;

/// How long a built transaction stays valid when the caller does not say.
pub const DEFAULT_DEADLINE_SECONDS: u64 = 120;

/// Longest relative deadline this crate will accept, in seconds.
///
/// Not a taste judgement: `now + window` on a `u64` panics in a debug build and
/// wraps in a release one, and `deadline_seconds` is public and takes a `u64`. A
/// year is far past any honest use, so rejecting beyond it costs nobody
/// anything and makes the arithmetic unreachable.
pub const MAX_DEADLINE_SECONDS: u64 = 365 * 24 * 60 * 60;

/// Chain slug used when a call does not name one.
pub const DEFAULT_NETWORK: &str = "bsc";

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

/// A transaction ready to be signed and sent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnsignedTransaction {
    /// EIP-155 chain id. Check it before signing — it is what stops a
    /// BSC-signed transaction replaying elsewhere.
    pub chain_id: i64,
    /// Contract to call.
    pub to: String,
    /// ABI-encoded calldata, `0x`-prefixed.
    pub data: String,
    /// Native value to attach, in wei. Zero for non-payable calls.
    pub value: U256,
    /// Sender, when one was supplied. Gas estimation needs it.
    pub from: Option<String>,
}

/// What a buy will cost and return, priced against current curve state.
#[derive(Debug, Clone)]
pub struct BuyQuote {
    /// Chain slug this was priced on.
    pub network: String,
    /// The token, lower-cased.
    pub token: String,
    /// What goes into the curve.
    pub amount_in_wei: U256,
    /// `getFirstBuyFee(token)`, charged **on top of** `amount_in_wei`.
    pub first_buy_fee_wei: U256,
    /// What `msg.value` must be: `amount_in_wei + first_buy_fee_wei`.
    pub value_wei: U256,
    /// Tokens out at the quoted moment.
    pub amount_out_wei: U256,
    /// Price impact in basis points, as the contract computes it.
    pub price_impact_bps: u64,
}

/// What a sell will return, priced against current curve state.
#[derive(Debug, Clone)]
pub struct SellQuote {
    /// Chain slug this was priced on.
    pub network: String,
    /// The token, lower-cased.
    pub token: String,
    /// Tokens going in.
    pub amount_in_wei: U256,
    /// Native currency out, net of the platform and token-owner fees, which the
    /// contract takes off the output rather than the input.
    pub amount_out_wei: U256,
    /// Price impact in basis points.
    pub price_impact_bps: u64,
}

/// A built buy with the quote it was priced from.
#[derive(Debug, Clone)]
pub struct BuiltBuy {
    /// Ready to sign and send.
    pub transaction: UnsignedTransaction,
    /// The pricing it was built against.
    pub quote: BuyQuote,
    /// The `minAmountOut` (or `maxAmountIn`) actually encoded.
    pub limit_wei: U256,
    /// Unix second after which the contract rejects the swap.
    pub deadline: u64,
}

/// A built sell with the quote it was priced from.
#[derive(Debug, Clone)]
pub struct BuiltSell {
    /// Ready to sign and send.
    pub transaction: UnsignedTransaction,
    /// The pricing it was built against.
    pub quote: SellQuote,
    /// The `minAmountOut` actually encoded.
    pub limit_wei: U256,
    /// Unix second after which the contract rejects the swap.
    pub deadline: u64,
}

/// Slippage and deadline configuration, shared by every build.
#[derive(Debug, Clone, Default)]
struct Limits {
    slippage_bps: Option<u32>,
    limit_wei: Option<U256>,
    deadline: Option<u64>,
    deadline_seconds: Option<u64>,
    from: Option<String>,
}

macro_rules! limit_builders {
    () => {
        /// Tolerance in basis points — `100` is 1%. Mutually exclusive with
        /// [`limit_wei`](Self::limit_wei).
        pub fn slippage_bps(mut self, bps: u32) -> Self {
            self.limits.slippage_bps = Some(bps);
            self
        }

        /// Set `minAmountOut`/`maxAmountIn` exactly, bypassing the tolerance.
        pub fn limit_wei(mut self, limit: U256) -> Self {
            self.limits.limit_wei = Some(limit);
            self
        }

        /// Absolute deadline, unix seconds. Wins over
        /// [`deadline_seconds`](Self::deadline_seconds).
        pub fn deadline(mut self, unix_seconds: u64) -> Self {
            self.limits.deadline = Some(unix_seconds);
            self
        }

        /// Relative deadline in seconds from now. Defaults to 120.
        pub fn deadline_seconds(mut self, seconds: u64) -> Self {
            self.limits.deadline_seconds = Some(seconds);
            self
        }

        /// Sender address, copied onto the transaction.
        pub fn from(mut self, address: impl Into<String>) -> Self {
            self.limits.from = Some(address.into());
            self
        }

        /// Chain slug. Defaults to `"bsc"`.
        pub fn network(mut self, network: impl Into<String>) -> Self {
            self.network = network.into();
            self
        }
    };
}

/// Spend an exact amount of native currency on a token.
#[derive(Debug, Clone)]
pub struct BuyParams {
    token: String,
    amount_wei: U256,
    network: String,
    limits: Limits,
}

impl BuyParams {
    /// The token to buy, and the native currency to spend (excluding the
    /// first-buy fee, which the SDK adds to `value` for you).
    pub fn new(token: impl Into<String>, amount_wei: U256) -> Self {
        Self {
            token: token.into(),
            amount_wei,
            network: DEFAULT_NETWORK.to_string(),
            limits: Limits::default(),
        }
    }

    limit_builders!();
}

/// Buy an exact number of tokens, capping the spend.
#[derive(Debug, Clone)]
pub struct BuyExactTokensParams {
    token: String,
    amount_out_wei: U256,
    network: String,
    limits: Limits,
}

impl BuyExactTokensParams {
    /// The token, and the exact number of tokens wanted.
    pub fn new(token: impl Into<String>, amount_out_wei: U256) -> Self {
        Self {
            token: token.into(),
            amount_out_wei,
            network: DEFAULT_NETWORK.to_string(),
            limits: Limits::default(),
        }
    }

    limit_builders!();
}

/// Sell tokens for native currency.
#[derive(Debug, Clone)]
pub struct SellParams {
    token: String,
    amount_wei: U256,
    network: String,
    limits: Limits,
}

impl SellParams {
    /// The token, and how much of it to sell.
    pub fn new(token: impl Into<String>, amount_wei: U256) -> Self {
        Self {
            token: token.into(),
            amount_wei,
            network: DEFAULT_NETWORK.to_string(),
            limits: Limits::default(),
        }
    }

    limit_builders!();
}

/// Builds unsigned bonding-curve transactions. Reach it through
/// [`FyuzClient::trade`].
#[derive(Debug)]
pub struct TradeApi<'a> {
    client: &'a FyuzClient,
}

impl<'a> TradeApi<'a> {
    pub(crate) fn new(client: &'a FyuzClient) -> Self {
        Self { client }
    }

    // ---------------------------------------------------------- chain setup

    /// Chain metadata from `GET /config`: contract address, chain id, RPC.
    ///
    /// Fetched once and memoised — it changes about as often as a redeploy.
    ///
    /// `contract_address` comes back normalised, and is `Some` or this call
    /// failed. Where `/config` is silent — it has no `contractAddress` for the
    /// chain, or does not serve the chain at all, which is the case for BSC
    /// testnet — [`addresses`](crate::addresses) fills the gap so the build path
    /// still has 20 verified bytes to encode.
    pub async fn chain(&self, network: &str) -> Result<ChainInfo, Error> {
        // A chain the API is known not to serve is answered from the book
        // without asking it. That is not just a saved round trip: it is what
        // makes testnet and fork work against a local node with the Fyuz API
        // unreachable, which is the situation most integration tests run in.
        if let Some(deployment) = deployment_for_network(network) {
            if deployment.api_network.is_none() {
                return Ok(chain_from(deployment));
            }
        }

        let chains = self
            .client
            .trade_state()
            .chains
            .get_or_try_init(|| async { Ok::<_, Error>(self.client.get_config().await?.chains) })
            .await?;

        for chain in chains {
            if chain.network.as_deref() != Some(network) && chain.chain_id.to_string() != network {
                continue;
            }

            let mut chain = chain.clone();
            // The one address in this crate that never went through
            // `normalize_address`: it arrives from the network, and from here it
            // flows into `transaction.to` and into two `approve`/`allowance`
            // spender words. A malformed one has to fail here, not silently
            // become a shifted argument list.
            chain.contract_address = match chain.contract_address.as_deref() {
                Some(address) => Some(normalize_address("contractAddress", address)?),
                None => deployment_for_chain_id(chain.chain_id).map(|d| d.fyuz.to_string()),
            };
            if chain.contract_address.is_none() {
                return Err(invalid(format!(
                    "the API did not publish a contract address for {network:?} and this SDK \
                     has none on file for chain id {}, so no transaction can be built",
                    chain.chain_id
                )));
            }
            return Ok(chain);
        }

        if let Some(deployment) = deployment_for_network(network) {
            return Ok(chain_from(deployment));
        }

        let known: Vec<String> = chains
            .iter()
            .map(|c| c.network.clone().unwrap_or_else(|| c.chain_id.to_string()))
            .chain(DEPLOYMENTS.iter().map(|d| d.network.to_string()))
            .collect();
        Err(invalid(format!(
            "unknown network {network:?}; the API serves: {}",
            known.join(", ")
        )))
    }

    /// A chain reduced to what building a transaction needs, with the launchpad
    /// address as a plain `String`.
    ///
    /// Exists so no call site has to write `unwrap_or_default()` on the
    /// contract address — which turned "the API sent nothing" into the empty
    /// string, and then into calldata addressed to nowhere.
    async fn resolve(&self, network: &str) -> Result<Resolved, Error> {
        let chain = self.chain(network).await?;
        let contract = chain
            .contract_address
            .ok_or_else(|| invalid(format!("no contract address is known for {network:?}")))?;
        Ok(Resolved {
            chain_id: chain.chain_id,
            contract,
            rpc_url: chain.rpc_url,
        })
    }

    /// The JSON-RPC client for a chain, from the override or `/config`.
    async fn rpc(&self, network: &str) -> Result<Arc<RpcClient>, Error> {
        {
            let cache = self.client.trade_state().rpcs.lock().await;
            if let Some(existing) = cache.get(network) {
                return Ok(Arc::clone(existing));
            }
        }

        let chain = self.resolve(network).await?;
        let url = self
            .client
            .rpc_url()
            .map(str::to_string)
            .or_else(|| chain.rpc_url.clone())
            .ok_or_else(|| {
                invalid(format!(
                    "no RPC endpoint for {network:?}: the API published none, and none was \
                     configured with FyuzClientBuilder::rpc_url"
                ))
            })?;

        // The `reqwest::Client` is the one the builder configured: it carries the
        // crate's User-Agent, any header the caller attached for an authenticated
        // node, and — the part that matters under load — a single connection pool
        // shared with every other chain rather than one per chain.
        let client = Arc::new(
            RpcClient::with_http(url, self.client.rpc_http().clone())
                .block(self.client.rpc_block().unwrap_or(DEFAULT_BLOCK_TAG)),
        );

        let mut cache = self.client.trade_state().rpcs.lock().await;
        Ok(Arc::clone(
            cache.entry(network.to_string()).or_insert(client),
        ))
    }

    /// An `eth_call` against the launchpad on `network`.
    async fn call_contract(&self, network: &str, data: &str) -> Result<CallOutcome, Error> {
        let chain = self.resolve(network).await?;
        let rpc = self.rpc(network).await?;
        rpc.call(&chain.contract, data, None).await
    }

    // ---------------------------------------------------------------- reads

    /// Whether the token has left the bonding curve.
    ///
    /// Reads `tokenPools(token).launched` — the contract's own flag, not the
    /// indexer's view of it, so it cannot lag behind a graduation that happened
    /// seconds ago.
    pub async fn is_graduated(&self, network: &str, token: &str) -> Result<bool, Error> {
        Ok(self.pool_state(network, token).await?.launched)
    }

    /// `tokenPools(token)`, reduced to what pricing an exact-tokens buy needs.
    ///
    /// The real `token_reserve` is the ceiling on what one buy can be handed;
    /// the virtual pair is the constant product the curve is priced on. The
    /// remaining struct members — the real eth reserve, the token and owner
    /// addresses, the pool type — are not decoded, because nothing here reads
    /// them and the REST API serves them anyway.
    async fn pool_state(&self, network: &str, token: &str) -> Result<PoolState, Error> {
        let token = normalize_address("token", token)?;
        let data = encode_call(SELECTOR_TOKEN_POOLS, &[address_word(&token)?]);

        match self.call_contract(network, &data).await? {
            // (uint256 ethReserve, uint256 tokenReserve, uint256 virtualEthReserve,
            //  uint256 virtualTokenReserve, address token, address owner,
            //  uint8 poolType, bool launched) — Fyuz.sol PoolInfo, in order.
            CallOutcome::Ok(result) => Ok(PoolState {
                token_reserve: decode_uint256_at(&result, 1)?,
                virtual_eth_reserve: decode_uint256_at(&result, 2)?,
                virtual_token_reserve: decode_uint256_at(&result, 3)?,
                launched: decode_bool_at(&result, 7)?,
            }),
            CallOutcome::Reverted(revert) => {
                Err(revert_error(&revert, &format!("tokenPools({token})")))
            }
        }
    }

    /// Whether the launchpad has trading paused.
    ///
    /// Not called automatically before a quote: that would double the RPC cost
    /// of every quote to check a flag that is almost never set, and a paused
    /// contract already surfaces as a typed [`RevertKind::Paused`](crate::RevertKind)
    /// when the swap is simulated. Call it when you want the reason *before*
    /// asking someone to sign, rather than after their transaction reverted.
    pub async fn is_paused(&self, network: &str) -> Result<bool, Error> {
        let data = encode_call(SELECTOR_PAUSED, &[]);

        match self.call_contract(network, &data).await? {
            CallOutcome::Ok(result) => decode_bool_at(&result, 0),
            CallOutcome::Reverted(revert) => Err(revert_error(&revert, "paused()")),
        }
    }

    /// `getFirstBuyFee(token)` in wei — the surcharge on a token's first buy.
    pub async fn first_buy_fee(&self, network: &str, token: &str) -> Result<U256, Error> {
        let token = normalize_address("token", token)?;
        let data = encode_call(SELECTOR_GET_FIRST_BUY_FEE, &[address_word(&token)?]);

        match self.call_contract(network, &data).await? {
            CallOutcome::Ok(result) => decode_uint256_at(&result, 0),
            CallOutcome::Reverted(revert) => {
                Err(revert_error(&revert, &format!("getFirstBuyFee({token})")))
            }
        }
    }

    /// `getMaxSellableETH(token)` — the ceiling one sell may extract.
    pub async fn max_sellable_wei(&self, network: &str, token: &str) -> Result<U256, Error> {
        let token = normalize_address("token", token)?;
        let data = encode_call(SELECTOR_GET_MAX_SELLABLE_ETH, &[address_word(&token)?]);

        match self.call_contract(network, &data).await? {
            CallOutcome::Ok(result) => decode_uint256_at(&result, 0),
            CallOutcome::Reverted(revert) => Err(revert_error(
                &revert,
                &format!("getMaxSellableETH({token})"),
            )),
        }
    }

    /// ERC-20 `allowance(owner, contract)` — how much the curve may pull.
    pub async fn allowance(&self, network: &str, token: &str, owner: &str) -> Result<U256, Error> {
        let token = normalize_address("token", token)?;
        let owner = normalize_address("owner", owner)?;
        let chain = self.resolve(network).await?;
        let rpc = self.rpc(network).await?;

        let data = encode_call(
            SELECTOR_ALLOWANCE,
            &[address_word(&owner)?, address_word(&chain.contract)?],
        );
        let result = rpc
            .call_or_error(&token, &data, &format!("allowance({owner})"))
            .await?;
        decode_uint256_at(&result, 0)
    }

    /// ERC-20 `balanceOf(owner)`, in the token's smallest unit.
    pub async fn balance_of(&self, network: &str, token: &str, owner: &str) -> Result<U256, Error> {
        let token = normalize_address("token", token)?;
        let owner = normalize_address("owner", owner)?;
        let rpc = self.rpc(network).await?;

        let data = encode_call(SELECTOR_BALANCE_OF, &[address_word(&owner)?]);
        let result = rpc
            .call_or_error(&token, &data, &format!("balanceOf({owner})"))
            .await?;
        decode_uint256_at(&result, 0)
    }

    // --------------------------------------------------------------- quotes

    /// `getSwapOutput`, with the graduated revert promoted to a typed error.
    async fn swap_output(
        &self,
        network: &str,
        token: &str,
        amount_in: U256,
        is_eth_input: bool,
    ) -> Result<(U256, u64), Error> {
        let data = encode_call(
            SELECTOR_GET_SWAP_OUTPUT,
            &[
                address_word(token)?,
                uint256_word(amount_in),
                bool_word(is_eth_input),
            ],
        );

        match self.call_contract(network, &data).await? {
            CallOutcome::Ok(result) => {
                let amount_out = decode_uint256_at(&result, 0)?;
                let impact = decode_uint256_at(&result, 1)?;
                let impact = impact.to_string().parse::<u64>().unwrap_or(u64::MAX);
                Ok((amount_out, impact))
            }
            CallOutcome::Reverted(revert) => {
                if revert_selector(&revert).as_deref() == Some(SELECTOR_ALREADY_LAUNCHED) {
                    return Err(graduated_error(token, None));
                }
                Err(revert_error(&revert, &format!("getSwapOutput({token})")))
            }
        }
    }

    /// `PLATFORM_BUY_FEE_BPS() + TOKEN_OWNER_FEE_BPS()` — the gross-up the
    /// contract applies to the input side of a buy.
    ///
    /// Read, never assumed, and read again on every quote rather than memoised.
    /// Both are plain storage with owner setters (`setPlatformBuyFeeBps`,
    /// `setTokenOwnerFeeBps`), and a hardcoded or cached figure that is too low
    /// produces a `maxAmountIn` under the real cost — which the contract rejects
    /// with `MaxInputExceeded`, and which the caller would then retry against
    /// the same stale number forever.
    async fn buy_fee_bps(&self, network: &str) -> Result<U256, Error> {
        let mut total = U256::ZERO;
        for (selector, name) in [
            (SELECTOR_PLATFORM_BUY_FEE_BPS, "PLATFORM_BUY_FEE_BPS()"),
            (SELECTOR_TOKEN_OWNER_FEE_BPS, "TOKEN_OWNER_FEE_BPS()"),
        ] {
            let part = match self.call_contract(network, selector).await? {
                CallOutcome::Ok(result) => decode_uint256_at(&result, 0)?,
                CallOutcome::Reverted(revert) => return Err(revert_error(&revert, name)),
            };
            total = total
                .checked_add(part)
                .ok_or_else(|| invalid("the contract's buy fees do not fit in a uint256"))?;
        }

        if total >= U256::from_u64(u64::from(BPS_DIVISOR)) {
            return Err(invalid(format!(
                "the contract reports a combined buy fee of {total} bps, which is 100% or more — \
                 refusing to price a buy against it"
            )));
        }
        Ok(total)
    }

    /// Price a buy: tokens out for a given amount of native currency in.
    ///
    /// Returns an error satisfying [`Error::is_graduated`] when the curve is closed.
    pub async fn quote_buy(
        &self,
        network: &str,
        token: &str,
        amount_wei: U256,
    ) -> Result<BuyQuote, Error> {
        let token = normalize_address("token", token)?;
        if amount_wei.is_zero() {
            return Err(invalid("amount_wei must be greater than zero"));
        }

        let (amount_out, price_impact_bps) =
            self.swap_output(network, &token, amount_wei, true).await?;
        let fee = self.first_buy_fee(network, &token).await?;
        let value = amount_wei
            .checked_add(fee)
            .ok_or_else(|| invalid("amount plus first-buy fee exceeds uint256"))?;

        Ok(BuyQuote {
            network: network.to_string(),
            token,
            amount_in_wei: amount_wei,
            first_buy_fee_wei: fee,
            value_wei: value,
            amount_out_wei: amount_out,
            price_impact_bps,
        })
    }

    /// Price a sell: native currency out for a given amount of tokens in.
    pub async fn quote_sell(
        &self,
        network: &str,
        token: &str,
        amount_wei: U256,
    ) -> Result<SellQuote, Error> {
        let token = normalize_address("token", token)?;
        if amount_wei.is_zero() {
            return Err(invalid("amount_wei must be greater than zero"));
        }

        let (amount_out, price_impact_bps) =
            self.swap_output(network, &token, amount_wei, false).await?;

        Ok(SellQuote {
            network: network.to_string(),
            token,
            amount_in_wei: amount_wei,
            amount_out_wei: amount_out,
            price_impact_bps,
        })
    }

    // --------------------------------------------------------------- builds

    /// Spend an exact amount of native currency on a token.
    ///
    /// `transaction.value` already includes the first-buy fee; sending only the
    /// amount reverts with `InsufficientEthValue`. Excess is refunded on-chain.
    pub async fn build_buy(&self, params: &BuyParams) -> Result<BuiltBuy, Error> {
        let quote = self
            .quote_buy(&params.network, &params.token, params.amount_wei)
            .await?;
        let chain = self.resolve(&params.network).await?;

        let limit = apply_limit(
            &params.limits,
            quote.amount_out_wei,
            false,
            "min_amount_out",
        )?;
        let deadline = resolve_deadline(&params.limits)?;

        Ok(BuiltBuy {
            transaction: UnsignedTransaction {
                chain_id: chain.chain_id,
                to: chain.contract,
                data: encode_call(
                    SELECTOR_SWAP_EXACT_ETH_FOR_TOKENS,
                    &[
                        address_word(&quote.token)?,
                        uint256_word(quote.amount_in_wei),
                        uint256_word(limit),
                        uint256_word(U256::from_u64(deadline)),
                    ],
                ),
                value: quote.value_wei,
                from: optional_address(params.limits.from.as_deref())?,
            },
            quote,
            limit_wei: limit,
            deadline,
        })
    }

    /// Buy an exact number of tokens, capping what you spend.
    ///
    /// Slippage runs the other way here: the limit is a `maxAmountIn`, so
    /// `slippage_bps` widens the cap rather than lowering a floor.
    ///
    /// # Why this one does its own arithmetic
    ///
    /// Every other quote in this module is an `eth_call`, for the reason in the
    /// module note. This one cannot be. `getSwapOutput` answers "what do I get
    /// for X" in both directions and the contract publishes no view at all for
    /// "what does Y cost" — `getAmountIn` is internal. Pricing the buy off
    /// `getSwapOutput(wanted, is_eth_input = false)` is not an approximation of
    /// the right answer, it is the wrong side of the curve: it divides by
    /// `virtual_token + wanted` where the buy divides by `virtual_token -
    /// wanted`, and it subtracts the sell fees where the buy adds the buy fees.
    /// A `maxAmountIn` derived that way is under the real cost and the swap
    /// reverts with `MaxInputExceeded`, after the caller has paid the gas.
    ///
    /// Searching the forward direction for the inverse — which this used to do —
    /// gets the side right and the number wrong: a bisection stops inside a
    /// tolerance band, so it returns a cost above the contract's own to the tune
    /// of that band, and spends dozens of `eth_call`s doing it. So this mirrors
    /// `Fyuz.getAmountIn` exactly instead, including its `+1` and its fee
    /// gross-up, over reserves and fee rates read from the same contract. The
    /// inputs are still the chain's; only the multiply is local.
    pub async fn build_buy_exact_tokens(
        &self,
        params: &BuyExactTokensParams,
    ) -> Result<BuiltBuy, Error> {
        let token = normalize_address("token", &params.token)?;
        if params.amount_out_wei.is_zero() {
            return Err(invalid("amount_out_wei must be greater than zero"));
        }

        let pool = self.pool_state(&params.network, &token).await?;
        if pool.launched {
            return Err(graduated_error(&token, None));
        }
        if pool.virtual_token_reserve.is_zero() {
            // `tokenPools` is a mapping, so an unknown token reads back as all
            // zeros rather than reverting. Saying that outright beats "the curve
            // cannot deliver N tokens, its reserve is 0", which reads like a
            // curve that has been bought out.
            return Err(invalid(format!(
                "no bonding curve exists for {token} on {:?} — check the token address and \
                 the network",
                params.network
            )));
        }
        let fee_bps = self.buy_fee_bps(&params.network).await?;

        // The contract clamps the request to what the curve still holds *before*
        // it prices anything (`_swapETHForExactTokens`), so price what will
        // actually be filled. Pricing the full request would quote a number the
        // swap never uses.
        let deliverable = if params.amount_out_wei > pool.token_reserve {
            pool.token_reserve
        } else {
            params.amount_out_wei
        };
        let cost = buy_cost_wei(&pool, deliverable, fee_bps)?;

        let limit = apply_limit(&params.limits, cost, true, "max_amount_in")?;
        let fee = self.first_buy_fee(&params.network, &token).await?;
        let chain = self.resolve(&params.network).await?;
        let deadline = resolve_deadline(&params.limits)?;
        // swapETHForExactTokens wants msg.value >= maxAmountIn + firstBuyFee and
        // refunds whatever the swap did not need, so the ceiling is what has to
        // be funded, not the quote.
        let value = limit
            .checked_add(fee)
            .ok_or_else(|| invalid("max input plus first-buy fee exceeds uint256"))?;

        // `checkPriceImpact` measures the output against the virtual token
        // reserve, which is the same ratio `getSwapOutput` reports for a buy.
        let impact = deliverable
            .mul_div(
                U256::from_u64(u64::from(BPS_DIVISOR)),
                pool.virtual_token_reserve,
            )
            .ok_or_else(|| invalid("this token's price impact does not fit in a uint256"))?;

        Ok(BuiltBuy {
            transaction: UnsignedTransaction {
                chain_id: chain.chain_id,
                to: chain.contract,
                data: encode_call(
                    SELECTOR_SWAP_ETH_FOR_EXACT_TOKENS,
                    &[
                        address_word(&token)?,
                        uint256_word(params.amount_out_wei),
                        uint256_word(limit),
                        uint256_word(U256::from_u64(deadline)),
                    ],
                ),
                value,
                from: optional_address(params.limits.from.as_deref())?,
            },
            quote: BuyQuote {
                network: params.network.clone(),
                token,
                amount_in_wei: cost,
                first_buy_fee_wei: fee,
                value_wei: value,
                amount_out_wei: deliverable,
                price_impact_bps: impact.to_string().parse::<u64>().unwrap_or(u64::MAX),
            },
            limit_wei: limit,
            deadline,
        })
    }

    /// Sell tokens for native currency.
    ///
    /// The contract pulls the tokens with `transferFrom`, so an ERC-20 approval
    /// must already be in place — check [`TradeApi::allowance`] and send
    /// [`TradeApi::build_approve`] first, or the swap reverts inside the token.
    pub async fn build_sell(&self, params: &SellParams) -> Result<BuiltSell, Error> {
        let quote = self
            .quote_sell(&params.network, &params.token, params.amount_wei)
            .await?;
        let chain = self.resolve(&params.network).await?;

        let limit = apply_limit(
            &params.limits,
            quote.amount_out_wei,
            false,
            "min_amount_out",
        )?;
        let deadline = resolve_deadline(&params.limits)?;

        Ok(BuiltSell {
            transaction: UnsignedTransaction {
                chain_id: chain.chain_id,
                to: chain.contract,
                data: encode_call(
                    SELECTOR_SWAP_EXACT_TOKENS_FOR_ETH,
                    &[
                        address_word(&quote.token)?,
                        uint256_word(quote.amount_in_wei),
                        uint256_word(limit),
                        uint256_word(U256::from_u64(deadline)),
                    ],
                ),
                value: U256::ZERO,
                from: optional_address(params.limits.from.as_deref())?,
            },
            quote,
            limit_wei: limit,
            deadline,
        })
    }

    /// ERC-20 `approve`, letting the curve pull tokens for a sell.
    ///
    /// Pass [`U256::MAX`] to approve once and forever — it saves a transaction
    /// per sell, at the cost of a standing allowance against an upgradeable
    /// contract.
    pub async fn build_approve(
        &self,
        network: &str,
        token: &str,
        amount_wei: U256,
    ) -> Result<UnsignedTransaction, Error> {
        let token = normalize_address("token", token)?;
        let chain = self.resolve(network).await?;

        Ok(UnsignedTransaction {
            chain_id: chain.chain_id,
            to: token,
            data: encode_call(
                SELECTOR_APPROVE,
                &[address_word(&chain.contract)?, uint256_word(amount_wei)],
            ),
            value: U256::ZERO,
            from: None,
        })
    }
}

/// The part of `tokenPools(token)` an exact-tokens buy is priced against.
#[derive(Debug, Clone)]
struct PoolState {
    /// The real token balance the curve still holds — the ceiling on one buy.
    token_reserve: U256,
    /// `x` in `x * y = k`.
    virtual_eth_reserve: U256,
    /// `y` in `x * y = k`.
    virtual_token_reserve: U256,
    /// The graduation flag: once true every swap entrypoint reverts.
    launched: bool,
}

/// What `swapETHForExactTokens` will charge for `amount_out` tokens.
///
/// `Fyuz.getAmountIn(amountOut, virtualEthReserve, virtualTokenReserve,
/// PLATFORM_BUY_FEE_BPS + TOKEN_OWNER_FEE_BPS)`, to the wei — including the `+1`
/// the contract adds after its floor division, which is what stops a rounded-down
/// input landing one token short of what was asked for.
fn buy_cost_wei(pool: &PoolState, amount_out: U256, fee_bps: U256) -> Result<U256, Error> {
    if amount_out.is_zero() || amount_out >= pool.virtual_token_reserve {
        // getAmountIn's own InvalidOutput guard: at or beyond the virtual
        // reserve the denominator is zero or negative and the curve can never
        // deliver, however much is offered for it.
        return Err(invalid(format!(
            "the curve cannot deliver {amount_out} tokens: its virtual token reserve is only {}",
            pool.virtual_token_reserve
        )));
    }
    if pool.virtual_eth_reserve.is_zero() {
        return Err(invalid(
            "the curve for this token holds no virtual reserve, so it cannot be priced",
        ));
    }

    let denominator = pool
        .virtual_token_reserve
        .checked_sub(amount_out)
        .expect("amount_out is below the virtual token reserve");
    let before_fee = pool
        .virtual_eth_reserve
        .mul_div(amount_out, denominator)
        .and_then(|floor| floor.checked_add(U256::from_u64(1)))
        .ok_or_else(|| invalid("pricing this many tokens overflowed uint256"))?;

    let divisor = U256::from_u64(u64::from(BPS_DIVISOR));
    let net = divisor
        .checked_sub(fee_bps)
        .filter(|net| !net.is_zero())
        .ok_or_else(|| {
            invalid(format!(
                "a buy fee of {fee_bps} bps leaves nothing to price"
            ))
        })?;
    before_fee
        .mul_div(divisor, net)
        .ok_or_else(|| invalid("grossing this trade up by the buy fee overflowed uint256"))
}

/// A chain with its launchpad address already validated.
#[derive(Debug, Clone)]
struct Resolved {
    chain_id: i64,
    contract: String,
    rpc_url: Option<String>,
}

/// A [`ChainInfo`] built from the compile-time address book.
///
/// Only the fields the trading layer reads are populated. The rest stay `None`
/// rather than being invented: this is a deployment record, not a copy of what
/// `/config` would have said, and a caller reading `target_market_cap` off it
/// should get "unknown" rather than a number from a stale constant.
fn chain_from(deployment: &Deployment) -> ChainInfo {
    ChainInfo {
        name: deployment.name.to_string(),
        chain_id: deployment.chain_id,
        network: Some(deployment.network.to_string()),
        contract_address: Some(deployment.fyuz.to_string()),
        rpc_url: Some(deployment.rpc_url.to_string()),
        currency: Some(deployment.currency.to_string()),
        explorer_url: Some(deployment.explorer_url.to_string()),
        ..ChainInfo::default()
    }
}

/// Per-client trading state: the memoised `/config` and the RPC clients.
#[derive(Debug, Default)]
pub(crate) struct TradeState {
    pub(crate) chains: OnceCell<Vec<ChainInfo>>,
    pub(crate) rpcs: Mutex<HashMap<String, Arc<RpcClient>>>,
}

/// Turn a quote plus a tolerance into the limit that goes on-chain.
///
/// `up` is which way the tolerance moves the number: `false` for a
/// `minAmountOut` floor, `true` for a `maxAmountIn` ceiling.
fn apply_limit(limits: &Limits, quoted: U256, up: bool, field: &str) -> Result<U256, Error> {
    if limits.limit_wei.is_some() && limits.slippage_bps.is_some() {
        return Err(invalid("pass either slippage_bps or limit_wei, not both"));
    }
    if let Some(limit) = limits.limit_wei {
        return Ok(limit);
    }

    let Some(bps) = limits.slippage_bps else {
        return Err(invalid(format!(
            "slippage protection is required: set slippage_bps (100 = 1%) or limit_wei to \
             choose {field} yourself. There is no default, because the right tolerance \
             depends on the trade and getting it wrong costs you money"
        )));
    };
    if bps >= BPS_DIVISOR {
        return Err(invalid(format!(
            "slippage_bps must be below 10000, got {bps}"
        )));
    }

    let factor = if up {
        BPS_DIVISOR + bps
    } else {
        BPS_DIVISOR - bps
    };
    let scaled = quoted
        .mul_small(factor)
        .ok_or_else(|| invalid("applying slippage overflowed uint256"))?;
    Ok(scaled.div_rem_small(BPS_DIVISOR).0)
}

/// Absolute deadline in unix seconds, from whichever form the caller used.
fn resolve_deadline(limits: &Limits) -> Result<u64, Error> {
    if let Some(deadline) = limits.deadline {
        if deadline == 0 {
            return Err(invalid("deadline must be a positive unix timestamp"));
        }
        return Ok(deadline);
    }
    let window = limits.deadline_seconds.unwrap_or(DEFAULT_DEADLINE_SECONDS);
    if window == 0 {
        return Err(invalid("deadline_seconds must be positive"));
    }
    if window > MAX_DEADLINE_SECONDS {
        return Err(invalid(format!(
            "deadline_seconds must be at most {MAX_DEADLINE_SECONDS} (one year), got {window}"
        )));
    }
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or(Duration::ZERO)
        .as_secs();
    // Bounded above, so this cannot wrap — saturating anyway costs nothing and
    // means a clock that has run away does not decide whether this panics.
    Ok(now.saturating_add(window))
}

fn optional_address(value: Option<&str>) -> Result<Option<String>, Error> {
    value.map(|v| normalize_address("from", v)).transpose()
}