tycho-ethereum 0.407.2

Ethereum specific implementation of core tycho traits
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
use std::{cmp, sync::Arc};

use alloy::{
    primitives::{Address, Bytes as AlloyBytes, U256},
    rpc::types::{
        state::{AccountOverride, StateOverride},
        TransactionInput, TransactionRequest,
    },
    sol_types::SolCall,
};
use tycho_common::{
    models::{
        blockchain::BlockTag,
        token::{TokenQuality, TransferCost, TransferTax},
    },
    traits::{TokenAnalyzer, TokenOwnerFinding},
    Bytes,
};

use super::{
    arbitrary_recipient,
    bytecode::{analyzeCall, ANALYZER_BYTECODE, FORWARDER_BYTECODE},
    calculate_fee_bps, map_block_tag, ObservedTransfer,
};
use crate::{rpc::EthereumRpcClient, BytesCodec};

/// Gas limit passed to the simulated `eth_call`. Set to the Ethereum block gas limit, which is
/// a safe upper bound for a single token analysis call.
const GAS_LIMIT: u64 = 30_000_000;

/// `TokenAnalyzer` implementation using `eth_call` with bytecode state overrides.
///
/// Injects the Analyzer contract at the token holder's address and the Forwarder contract at the
/// settlement address, then executes the full round-trip transfer simulation in a single
/// `eth_call`. Compatible with any EVM chain that supports `eth_call` state overrides.
pub struct EthCallDetector {
    rpc: EthereumRpcClient,
    finder: Arc<dyn TokenOwnerFinding>,
    settlement_contract: Address,
}

impl EthCallDetector {
    pub fn new(
        rpc: &EthereumRpcClient,
        finder: Arc<dyn TokenOwnerFinding>,
        settlement_contract: Address,
    ) -> Self {
        Self { rpc: rpc.clone(), finder, settlement_contract }
    }
}

#[async_trait::async_trait]
impl TokenAnalyzer for EthCallDetector {
    type Error = String;

    async fn analyze(
        &self,
        token: Bytes,
        block: BlockTag,
    ) -> Result<(TokenQuality, Option<TransferCost>, Option<TransferTax>), String> {
        let (quality, transfer_cost, tax) = self
            .detect_impl(Address::from_bytes(&token), block)
            .await
            .map_err(|e| e.to_string())?;
        tracing::debug!(?token, ?quality, "ethcall detector: determined token quality");
        Ok((
            quality,
            transfer_cost.map(|cost| cost.try_into().unwrap_or(8_000_000)),
            tax.map(|cost| cost.try_into().unwrap_or(10_000)),
        ))
    }
}

impl EthCallDetector {
    pub async fn detect_impl(
        &self,
        token: Address,
        block: BlockTag,
    ) -> Result<(TokenQuality, Option<U256>, Option<U256>), String> {
        let block_tag = map_block_tag(block);

        // Arbitrary amount that is large enough that small relative fees should be
        // visible.
        const MIN_AMOUNT: u64 = 100_000;
        let (holder, amount) = match self
            .finder
            .find_owner(token.to_bytes(), MIN_AMOUNT.into())
            .await
            .map_err(|e| e.to_string())?
        {
            Some((address, balance)) => {
                // Use half the balance to reduce races between find_owner and the eth_call.
                let amount = cmp::max(
                    U256::from_be_bytes::<32>(
                        balance
                            .lpad(32, 0)
                            .as_ref()
                            .try_into()
                            .expect("balance should be 32 bytes"),
                    ) / U256::from(2),
                    U256::from(MIN_AMOUNT),
                );
                tracing::debug!(?token, ?address, ?amount, "ethcall: found token owner");
                (Address::from_bytes(&address), amount)
            }
            None => {
                return Ok((
                    TokenQuality::bad(format!(
                        "Could not find on chain source of the token with at least \
                         {MIN_AMOUNT} balance.",
                    )),
                    None,
                    None,
                ))
            }
        };

        let recipient = arbitrary_recipient();

        let tx = TransactionRequest::default()
            .from(holder)
            .to(holder)
            .input(TransactionInput::both(
                analyzeCall { token, amount, settlement: self.settlement_contract, recipient }
                    .abi_encode()
                    .into(),
            ))
            .gas_limit(GAS_LIMIT);

        let mut overrides = StateOverride::default();
        overrides.insert(
            holder,
            AccountOverride {
                code: Some(AlloyBytes::copy_from_slice(ANALYZER_BYTECODE)),
                ..Default::default()
            },
        );
        overrides.insert(
            self.settlement_contract,
            AccountOverride {
                code: Some(AlloyBytes::copy_from_slice(FORWARDER_BYTECODE)),
                ..Default::default()
            },
        );

        let raw: AlloyBytes = match self
            .rpc
            .eth_call_with_state_overrides(tx, block_tag, overrides)
            .await
        {
            Ok(raw) => raw,
            // A revert is caused by the token itself (e.g. balanceOf reverting), not by the
            // RPC: the injected Analyzer only propagates reverts raised by token calls.
            // Report it as a Bad verdict so callers stop retrying the token indefinitely.
            Err(e) if e.is_execution_reverted() => {
                return Ok((
                    TokenQuality::bad(format!("Token analysis simulation reverted: {e}")),
                    None,
                    None,
                ))
            }
            Err(e) => return Err(format!("eth_call with state overrides failed: {e}")),
        };

        let returns = analyzeCall::abi_decode_returns(raw.as_ref())
            .map_err(|e| format!("Failed to decode Analyzer return value: {e}"))?;

        Self::handle_response(returns, amount, holder)
    }

    fn handle_response(
        r: <analyzeCall as SolCall>::Return,
        amount: U256,
        holder: Address,
    ) -> Result<(TokenQuality, Option<U256>, Option<U256>), String> {
        if !r.transferInOk {
            return Ok((
                TokenQuality::bad(format!(
                    "Transfer of token from on-chain source {holder:#x} into settlement \
                     contract failed",
                )),
                None,
                None,
            ));
        }

        let recipient = arbitrary_recipient();

        if !r.transferOutOk {
            return Ok((
                TokenQuality::bad(format!(
                    "Transfer of token out of settlement contract to arbitrary recipient \
                     {recipient:#x} failed",
                )),
                None,
                None,
            ));
        }

        let gas_per_transfer = (r.gasIn + r.gasOut) / U256::from(2);

        // The Solidity guard ensures balanceAfterIn >= balanceBeforeIn when transferInOk = true,
        // so this subtraction is always safe.
        let middle_amount = r
            .balanceAfterIn
            .checked_sub(r.balanceBeforeIn)
            .ok_or("settlement balance underflow after successful transfer in")?;

        // A U256 overflow in the fee maths is token state (a balance near U256::MAX), not an RPC
        // fault. Both transfers ran, so gas is known; the fee is not.
        let fees = match calculate_fee_bps(
            ObservedTransfer {
                sent: amount,
                balance_before: r.balanceBeforeIn,
                balance_after: r.balanceAfterIn,
            },
            ObservedTransfer {
                sent: middle_amount,
                balance_before: r.recipientBefore,
                balance_after: r.recipientAfter,
            },
        ) {
            Ok(fees) => fees,
            Err(e) => {
                return Ok((
                    TokenQuality::bad(format!("Failed to calculate transfer fee: {e}")),
                    Some(gas_per_transfer),
                    None,
                ))
            }
        };

        // Safe: calculate_fee_bps already checked this sum for overflow.
        let computed_balance_after_in = r.balanceBeforeIn + amount;
        if r.balanceAfterIn != computed_balance_after_in {
            return Ok((
                TokenQuality::bad(format!(
                    "Transferring {amount} into settlement was expected to result in a balance \
                     of {computed_balance_after_in} but got {}. The token likely takes a fee on \
                     transfer.",
                    r.balanceAfterIn,
                )),
                Some(gas_per_transfer),
                Some(fees),
            ));
        }

        if r.balanceAfterOut != r.balanceBeforeIn {
            return Ok((
                TokenQuality::bad(format!(
                    "Transferring {amount} out of settlement was expected to restore the \
                     original balance of {} but got {}.",
                    r.balanceBeforeIn, r.balanceAfterOut,
                )),
                Some(gas_per_transfer),
                Some(fees),
            ));
        }

        // Safe: calculate_fee_bps already checked this sum for overflow.
        let computed_recipient_after = r.recipientBefore + middle_amount;
        if r.recipientAfter != computed_recipient_after {
            return Ok((
                TokenQuality::bad(format!(
                    "Transferring {amount} to arbitrary recipient {recipient:#x} was expected \
                     to result in a balance of {computed_recipient_after} but got {}. The token \
                     likely takes a fee on transfer.",
                    r.recipientAfter,
                )),
                Some(gas_per_transfer),
                Some(fees),
            ));
        }

        if !r.approvalOk {
            return Ok((
                TokenQuality::bad("Approval of U256::MAX failed".to_string()),
                Some(gas_per_transfer),
                Some(fees),
            ));
        }

        Ok((TokenQuality::Good, Some(gas_per_transfer), Some(fees)))
    }
}

#[cfg(test)]
mod tests {
    use std::{collections::HashMap, str::FromStr, sync::Arc};

    use alloy::primitives::{address, Address};
    use tycho_common::models::token::{TokenOwnerStore, TokenQuality};

    use super::*;
    use crate::test_fixtures::{TestFixture, TEST_BLOCK_NUMBER, TOKEN_HOLDERS, USDC_STR, WETH_STR};

    const COWSWAP_SETTLEMENT: Address = address!("c9f2e6ea1637E499406986ac50ddC92401ce1f58");

    // Return value builder for unit tests — all fields default to zero / true.
    fn good_return(amount: U256) -> <analyzeCall as SolCall>::Return {
        type R = <analyzeCall as SolCall>::Return;
        R {
            transferInOk: true,
            transferOutOk: true,
            approvalOk: true,
            balanceBeforeIn: U256::ZERO,
            balanceAfterIn: amount,
            balanceAfterOut: U256::ZERO,
            recipientBefore: U256::ZERO,
            recipientAfter: amount,
            gasIn: U256::from(30_000_u64),
            gasOut: U256::from(25_000_u64),
        }
    }

    #[test]
    fn handle_response_good_token() {
        let amount = U256::from(1_000_000_u64);
        let result = EthCallDetector::handle_response(good_return(amount), amount, Address::ZERO);
        let (quality, gas, tax) = result.unwrap();
        assert_eq!(quality, TokenQuality::Good);
        assert_eq!(gas, Some(U256::from(27_500_u64))); // (30_000 + 25_000) / 2
        assert_eq!(tax, Some(U256::ZERO));
    }

    #[test]
    fn handle_response_transfer_in_failed() {
        let amount = U256::from(1_000_000_u64);
        let mut r = good_return(amount);
        r.transferInOk = false;
        let (quality, gas, tax) =
            EthCallDetector::handle_response(r, amount, Address::ZERO).unwrap();
        assert!(matches!(quality, TokenQuality::Bad { .. }));
        assert!(gas.is_none());
        assert!(tax.is_none());
    }

    #[test]
    fn handle_response_transfer_out_failed() {
        let amount = U256::from(1_000_000_u64);
        let mut r = good_return(amount);
        r.transferOutOk = false;
        let (quality, gas, tax) =
            EthCallDetector::handle_response(r, amount, Address::ZERO).unwrap();
        assert!(matches!(quality, TokenQuality::Bad { .. }));
        assert!(gas.is_none());
        assert!(tax.is_none());
    }

    #[test]
    fn handle_response_approval_failed() {
        let amount = U256::from(1_000_000_u64);
        let mut r = good_return(amount);
        r.approvalOk = false;
        let (quality, gas, tax) =
            EthCallDetector::handle_response(r, amount, Address::ZERO).unwrap();
        assert!(matches!(quality, TokenQuality::Bad { .. }));
        assert!(gas.is_some());
        assert!(tax.is_some());
    }

    #[test]
    fn handle_response_fee_on_transfer_inbound() {
        // Token takes 1% fee: 1_000_000 sent, only 990_000 received.
        let amount = U256::from(1_000_000_u64);
        let received = U256::from(990_000_u64);
        let mut r = good_return(amount);
        r.balanceAfterIn = received;
        r.recipientAfter = received; // recipient gets what settlement received
        let (quality, gas, tax) =
            EthCallDetector::handle_response(r, amount, Address::ZERO).unwrap();
        assert!(matches!(quality, TokenQuality::Bad { .. }));
        assert!(gas.is_some());
        // Fee should be ~100 bps (1%)
        assert_eq!(tax, Some(U256::from(100_u64)));
    }

    #[test]
    fn handle_response_fee_on_transfer_with_settlement_balance() {
        // Settlement already holds 50_000 when the 1% fee token credits it with 990_000.
        let amount = U256::from(1_000_000_u64);
        let mut r = good_return(amount);
        r.balanceBeforeIn = U256::from(50_000_u64);
        r.balanceAfterIn = U256::from(1_040_000_u64);
        r.balanceAfterOut = U256::from(50_000_u64);
        r.recipientAfter = U256::from(990_000_u64);
        let (quality, gas, tax) =
            EthCallDetector::handle_response(r, amount, Address::ZERO).unwrap();
        assert!(matches!(quality, TokenQuality::Bad { .. }));
        assert!(gas.is_some());
        assert_eq!(tax, Some(U256::from(100_u64)));
    }

    #[test]
    fn handle_response_fee_overflow_is_bad() {
        let amount = U256::from(1_000_000_u64);
        let mut r = good_return(amount);
        r.balanceBeforeIn = U256::MAX;
        r.balanceAfterIn = U256::MAX;
        let (quality, gas, tax) = EthCallDetector::handle_response(r, amount, Address::ZERO)
            .expect("a balance near U256::MAX must yield a Bad verdict, not an error");
        assert!(matches!(quality, TokenQuality::Bad { .. }));
        assert_eq!(gas, Some(U256::from(27_500_u64)));
        assert!(tax.is_none());
    }

    #[test]
    fn handle_response_credits_more_than_sent_is_bad() {
        let amount = U256::from(1_000_000_u64);
        let mut r = good_return(amount);
        r.balanceAfterIn = amount + U256::from(1_u64);
        r.recipientAfter = amount + U256::from(1_u64);
        let (quality, gas, tax) =
            EthCallDetector::handle_response(r, amount, Address::ZERO).unwrap();
        assert!(matches!(quality, TokenQuality::Bad { .. }));
        assert_eq!(gas, Some(U256::from(27_500_u64)));
        assert_eq!(tax, Some(U256::ZERO));
    }

    impl TestFixture {
        pub(crate) fn create_ethcall_detector(&self) -> EthCallDetector {
            let rpc = self.create_rpc_client(false);
            let finder = TokenOwnerStore::new(TOKEN_HOLDERS.clone());
            EthCallDetector::new(&rpc, Arc::new(finder), COWSWAP_SETTLEMENT)
        }
    }

    #[tokio::test]
    async fn detect_impl_maps_execution_revert_to_bad() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("POST", "/")
            .match_body(mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","id":0,"error":{"code":3,"message":"execution reverted","data":"0x"}}"#,
            )
            .expect(1)
            .create_async()
            .await;

        let rpc = EthereumRpcClient::new(&server.url()).expect("mock rpc client");
        let token = Bytes::from_str("e172e9b6cfbeeb5593bdce3f077356fdb33af904").unwrap();
        let holder = Bytes::from_str("000000000004444c5dc75cb358380d2e3de08a90").unwrap();
        let finder = TokenOwnerStore::new(HashMap::from([(
            token.clone(),
            (holder, U256::from(1_000_000_u64).to_bytes()),
        )]));
        let detector = EthCallDetector::new(&rpc, Arc::new(finder), COWSWAP_SETTLEMENT);

        let (quality, gas, tax) = detector
            .analyze(token, BlockTag::Latest)
            .await
            .expect("a reverting simulation must yield a Bad verdict, not an error");

        assert!(matches!(quality, TokenQuality::Bad { .. }));
        assert!(gas.is_none());
        assert!(tax.is_none());
        mock.assert_async().await;
    }

    #[tokio::test]
    #[ignore = "require RPC connection"]
    async fn test_detect_impl_usdc() {
        let fixture = TestFixture::new();
        let detector = fixture.create_ethcall_detector();
        let usdc = Address::from_str(USDC_STR).unwrap();

        let (quality, gas, tax) = detector
            .detect_impl(usdc, BlockTag::Number(TEST_BLOCK_NUMBER))
            .await
            .expect("detect_impl failed");

        assert_eq!(quality, TokenQuality::Good);
        assert!(gas.is_some_and(|g| g > U256::ZERO));
        assert_eq!(tax, Some(U256::ZERO));
    }

    #[tokio::test]
    #[ignore = "require RPC connection"]
    async fn test_detect_impl_weth() {
        let fixture = TestFixture::new();
        let detector = fixture.create_ethcall_detector();
        let weth = Address::from_str(WETH_STR).unwrap();

        let (quality, gas, tax) = detector
            .detect_impl(weth, BlockTag::Number(TEST_BLOCK_NUMBER))
            .await
            .expect("detect_impl failed");

        assert_eq!(quality, TokenQuality::Good);
        assert!(gas.is_some_and(|g| g > U256::ZERO));
        assert_eq!(tax, Some(U256::ZERO));
    }

    mod arbitrum {
        use super::*;
        use crate::test_fixtures::{ARB_ARB_STR, ARB_TOKEN_HOLDERS, ARB_USDC_STR, ARB_WETH_STR};

        const ARB_COWSWAP_SETTLEMENT: Address =
            address!("9008D19f58AAbD9eD0D60971565AA8510560ab41");

        impl TestFixture {
            pub(crate) fn create_arb_ethcall_detector(&self) -> EthCallDetector {
                let rpc = self.create_rpc_client(false);
                let finder = TokenOwnerStore::new(ARB_TOKEN_HOLDERS.clone());
                EthCallDetector::new(&rpc, Arc::new(finder), ARB_COWSWAP_SETTLEMENT)
            }
        }

        #[tokio::test]
        #[ignore = "require ARB_RPC_URL"]
        async fn arb_usdc() {
            let fixture = TestFixture::new_arbitrum();
            let detector = fixture.create_arb_ethcall_detector();
            let token = Address::from_str(ARB_USDC_STR).unwrap();
            let (quality, gas, _tax) = detector
                .detect_impl(token, BlockTag::Latest)
                .await
                .expect("detect_impl failed");
            assert_eq!(quality, TokenQuality::Good, "Arbitrum USDC should be Good");
            assert!(gas.is_some_and(|g| g > U256::ZERO));
        }

        #[tokio::test]
        #[ignore = "require ARB_RPC_URL"]
        async fn arb_weth() {
            let fixture = TestFixture::new_arbitrum();
            let detector = fixture.create_arb_ethcall_detector();
            let token = Address::from_str(ARB_WETH_STR).unwrap();
            let (quality, gas, _tax) = detector
                .detect_impl(token, BlockTag::Latest)
                .await
                .expect("detect_impl failed");
            assert_eq!(quality, TokenQuality::Good, "Arbitrum WETH should be Good");
            assert!(gas.is_some_and(|g| g > U256::ZERO));
        }

        #[tokio::test]
        #[ignore = "require ARB_RPC_URL"]
        async fn arb_arb_token() {
            let fixture = TestFixture::new_arbitrum();
            let detector = fixture.create_arb_ethcall_detector();
            let token = Address::from_str(ARB_ARB_STR).unwrap();
            let (quality, gas, _tax) = detector
                .detect_impl(token, BlockTag::Latest)
                .await
                .expect("detect_impl failed");
            assert_eq!(quality, TokenQuality::Good, "ARB token should be Good");
            assert!(gas.is_some_and(|g| g > U256::ZERO));
        }
    }
}