clear-signing 0.1.0

ERC-7730 v2 clear signing library: decodes and formats Ethereum calldata and EIP-712 typed data for human-readable display.
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
//! Integration tests using real Aave v2/v3 registry descriptors.

use clear_signing::decoder::parse_signature;
use clear_signing::resolver::ResolvedDescriptor;
use clear_signing::token::{
    CompositeDataProvider, StaticTokenSource, TokenMeta, WellKnownTokenSource,
};
use clear_signing::types::descriptor::Descriptor;
use clear_signing::{format_calldata, DisplayEntry, DisplayModel, TransactionContext};

fn load_descriptor(fixture: &str) -> Descriptor {
    let path = format!("{}/tests/fixtures/{fixture}", env!("CARGO_MANIFEST_DIR"));
    let json = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {path}: {e}"));
    Descriptor::from_json(&json).unwrap_or_else(|e| panic!("parse {path}: {e}"))
}

fn build_calldata(selector: &[u8; 4], args: &[Vec<u8>]) -> Vec<u8> {
    let mut data = Vec::with_capacity(4 + args.len() * 32);
    data.extend_from_slice(selector);
    for arg in args {
        data.extend_from_slice(arg);
    }
    data
}

fn address_word(hex_addr: &str) -> Vec<u8> {
    let hex_str = hex_addr
        .strip_prefix("0x")
        .or_else(|| hex_addr.strip_prefix("0X"))
        .unwrap_or(hex_addr);
    let addr_bytes = hex::decode(hex_str).expect("valid hex address");
    let mut word = vec![0u8; 12];
    word.extend_from_slice(&addr_bytes);
    assert_eq!(word.len(), 32);
    word
}

fn uint_word(val: u128) -> Vec<u8> {
    let mut word = vec![0u8; 16];
    word.extend_from_slice(&val.to_be_bytes());
    assert_eq!(word.len(), 32);
    word
}

fn max_uint256_word() -> Vec<u8> {
    vec![0xff; 32]
}

fn aave_token_source() -> CompositeDataProvider {
    let mut custom = StaticTokenSource::new();
    // Aave uses these token addresses in tests
    custom.insert(
        1,
        "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
        TokenMeta {
            symbol: "USDC".to_string(),
            decimals: 6,
            name: "USD Coin".to_string(),
        },
    );
    custom.insert(
        1,
        "0x6b175474e89094c44da98b954eedeac495271d0f",
        TokenMeta {
            symbol: "DAI".to_string(),
            decimals: 18,
            name: "Dai Stablecoin".to_string(),
        },
    );
    custom.insert(
        1,
        "0xdac17f958d2ee523a2206206994597c13d831ec7",
        TokenMeta {
            symbol: "USDT".to_string(),
            decimals: 6,
            name: "Tether USD".to_string(),
        },
    );
    custom.insert(
        8453,
        "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
        TokenMeta {
            symbol: "USDC".to_string(),
            decimals: 6,
            name: "USD Coin".to_string(),
        },
    );
    CompositeDataProvider::new(vec![
        Box::new(custom),
        Box::new(WellKnownTokenSource::new()),
    ])
}

fn wrap_rd(descriptor: Descriptor, chain_id: u64, address: &str) -> Vec<ResolvedDescriptor> {
    vec![ResolvedDescriptor {
        descriptor,
        chain_id,
        address: address.to_lowercase(),
    }]
}

fn get_entry_value(model: &DisplayModel, label: &str) -> String {
    for entry in &model.entries {
        match entry {
            DisplayEntry::Item(item) if item.label == label => return item.value.clone(),
            _ => {}
        }
    }
    panic!("no entry with label '{label}' found in {:?}", model.entries);
}

// --- LPv3 Tests ---

#[tokio::test]
async fn aave_supply_usdc_mainnet() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let sig = parse_signature("supply(address,uint256,address,uint16)").unwrap();
    let tokens = aave_token_source();

    let usdc_addr = "a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48";
    let on_behalf = "1111111111111111111111111111111111111111";

    let calldata = build_calldata(
        &sig.selector,
        &[
            address_word(usdc_addr),
            uint_word(1_000_000_000), // 1000 USDC (6 decimals)
            address_word(on_behalf),
            uint_word(0), // referralCode
        ],
    );

    let to = "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: None,
        from: None,
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Supply");
    assert_eq!(get_entry_value(&result, "Amount to supply"), "1000 USDC");
}

#[tokio::test]
async fn aave_supply_usdc_base() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let sig = parse_signature("supply(address,uint256,address,uint16)").unwrap();
    let tokens = aave_token_source();

    let usdc_base = "833589fcd6edb6e08f4c7c32d4f71b54bda02913";
    let on_behalf = "2222222222222222222222222222222222222222";

    let calldata = build_calldata(
        &sig.selector,
        &[
            address_word(usdc_base),
            uint_word(500_000_000), // 500 USDC
            address_word(on_behalf),
            uint_word(0),
        ],
    );

    let to = "0xA238Dd80C259a72e81d7e4664a9801593F98d1c5";
    let descriptors = wrap_rd(descriptor, 8453, to);
    let tx = TransactionContext {
        chain_id: 8453,
        to,
        calldata: &calldata,
        value: None,
        from: None,
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Supply");
    assert_eq!(get_entry_value(&result, "Amount to supply"), "500 USDC");
}

#[tokio::test]
async fn aave_repay_all_dai() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let sig = parse_signature("repay(address,uint256,uint256,address)").unwrap();
    let tokens = aave_token_source();

    let dai_addr = "6b175474e89094c44da98b954eedeac495271d0f";
    let on_behalf = "3333333333333333333333333333333333333333";

    let calldata = build_calldata(
        &sig.selector,
        &[
            address_word(dai_addr),
            max_uint256_word(), // max uint256 = "All"
            uint_word(2),       // variable rate
            address_word(on_behalf),
        ],
    );

    let to = "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: None,
        from: None,
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Repay loan");
    assert_eq!(get_entry_value(&result, "Amount to repay"), "All DAI");
    assert_eq!(get_entry_value(&result, "Interest rate mode"), "variable");
}

#[tokio::test]
async fn aave_withdraw_max() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let sig = parse_signature("withdraw(address,uint256,address)").unwrap();
    let tokens = aave_token_source();

    let usdc_addr = "a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48";
    let to_addr = "4444444444444444444444444444444444444444";

    let calldata = build_calldata(
        &sig.selector,
        &[
            address_word(usdc_addr),
            max_uint256_word(), // max = "Max"
            address_word(to_addr),
        ],
    );

    let to = "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: None,
        from: None,
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Withdraw");
    assert_eq!(get_entry_value(&result, "Amount to withdraw"), "Max USDC");
}

#[tokio::test]
async fn aave_borrow_variable() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let sig = parse_signature("borrow(address,uint256,uint256,uint16,address)").unwrap();
    let tokens = aave_token_source();

    let usdt_addr = "dac17f958d2ee523a2206206994597c13d831ec7";
    let on_behalf = "5555555555555555555555555555555555555555";

    let calldata = build_calldata(
        &sig.selector,
        &[
            address_word(usdt_addr),
            uint_word(5_000_000), // 5 USDT
            uint_word(2),         // variable rate
            uint_word(0),         // referralCode
            address_word(on_behalf),
        ],
    );

    let to = "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: None,
        from: None,
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Borrow");
    assert_eq!(get_entry_value(&result, "Amount to borrow"), "5 USDT");
    assert_eq!(get_entry_value(&result, "Interest Rate mode"), "variable");
}

#[tokio::test]
async fn aave_set_collateral() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let sig = parse_signature("setUserUseReserveAsCollateral(address,bool)").unwrap();
    let tokens = aave_token_source();

    let usdc_addr = "a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48";

    let calldata = build_calldata(
        &sig.selector,
        &[
            address_word(usdc_addr),
            uint_word(1), // true
        ],
    );

    let to = "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: None,
        from: None,
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Manage collateral");
    assert_eq!(get_entry_value(&result, "Enable use as collateral"), "true");
}

// --- LPv2 Tests ---

#[tokio::test]
async fn aave_deposit_usdc_mainnet() {
    let descriptor = load_descriptor("aave-lpv2.json");
    let sig = parse_signature("deposit(address,uint256,address,uint16)").unwrap();
    let tokens = aave_token_source();

    let usdc_addr = "a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48";
    let on_behalf = "1111111111111111111111111111111111111111";

    let calldata = build_calldata(
        &sig.selector,
        &[
            address_word(usdc_addr),
            uint_word(1_000_000_000), // 1000 USDC
            address_word(on_behalf),
            uint_word(0),
        ],
    );

    let to = "0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: None,
        from: None,
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Supply");
    assert_eq!(get_entry_value(&result, "Amount to supply"), "1000 USDC");
}

// --- WrappedTokenGatewayV3 Tests ---

#[tokio::test]
async fn gateway_deposit_eth() {
    let descriptor = load_descriptor("aave-gateway.json");
    let sig = parse_signature("depositETH(address,address,uint16)").unwrap();
    let tokens = aave_token_source();

    let pool_addr = "87870bca3f3fd6335c3f4ce8392d69350b4fa4e2";
    let on_behalf = "6666666666666666666666666666666666666666";

    let calldata = build_calldata(
        &sig.selector,
        &[
            address_word(pool_addr),
            address_word(on_behalf),
            uint_word(0),
        ],
    );

    // 1 ETH = 10^18 wei
    let value = uint_word(1_000_000_000_000_000_000);

    let to = "0xd01607c3C5eCABa394D8be377a08590149325722";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: Some(&value),
        from: None,
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Supply");
    // @.value should be formatted as native currency (ETH with 18 decimals)
    let amount = get_entry_value(&result, "Amount to supply");
    assert_eq!(amount, "1 ETH");
}

#[tokio::test]
async fn gateway_borrow_eth_with_from() {
    let descriptor = load_descriptor("aave-gateway.json");
    let sig = parse_signature("borrowETH(address,uint256,uint16)").unwrap();
    let tokens = aave_token_source();

    let pool_addr = "87870bca3f3fd6335c3f4ce8392d69350b4fa4e2";

    let calldata = build_calldata(
        &sig.selector,
        &[
            address_word(pool_addr),
            uint_word(500_000_000_000_000_000), // 0.5 ETH
            uint_word(0),
        ],
    );

    let from_addr = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

    let to = "0xd01607c3C5eCABa394D8be377a08590149325722";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: None,
        from: Some(from_addr),
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Borrow");
    // @.from should be resolved (EIP-55 checksummed)
    let debtor = get_entry_value(&result, "Debtor");
    assert!(
        debtor.to_lowercase().contains("aaaaaa"),
        "debtor should contain the from address: {debtor}"
    );
}

/// Real wallet request: depositETH with value=0x5af3107a4000 (0.0001 ETH) on mainnet.
/// Verifies @.value with format "amount" renders native currency (decimals + symbol).
#[tokio::test]
async fn real_wallet_supply_eth_mainnet() {
    let descriptor = load_descriptor("aave-gateway.json");
    let tokens = aave_token_source();

    // depositETH(address,address,uint16) calldata from real wallet
    let calldata = hex::decode(
        "474cf53d\
         00000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e2\
         000000000000000000000000bf01daf454dce008d3e2bfd47d5e186f71477253\
         0000000000000000000000000000000000000000000000000000000000000000",
    )
    .unwrap();

    // value = 0x5af3107a4000 = 100000000000000 wei = 0.0001 ETH
    let value_bytes =
        hex::decode("00000000000000000000000000000000000000000000000000005af3107a4000").unwrap();

    let to = "0xd01607c3C5eCABa394D8be377a08590149325722";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: Some(&value_bytes),
        from: Some("0xbf01daf454dce008d3e2bfd47d5e186f71477253"),
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Supply");
    assert_eq!(get_entry_value(&result, "Amount to supply"), "0.0001 ETH");

    // Interpolated intent should show "0.0001 ETH", not raw wei
    let interp = result.interpolated_intent.as_deref().unwrap();
    assert!(
        interp.contains("0.0001 ETH"),
        "interpolated intent should contain '0.0001 ETH': {interp}"
    );
    assert!(
        !interp.contains("100000000000000"),
        "interpolated intent should NOT contain raw wei: {interp}"
    );
}

#[tokio::test]
async fn aave_interpolated_intent() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let sig = parse_signature("supply(address,uint256,address,uint16)").unwrap();
    let tokens = aave_token_source();

    let usdc_addr = "a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48";
    let on_behalf = "1111111111111111111111111111111111111111";

    let calldata = build_calldata(
        &sig.selector,
        &[
            address_word(usdc_addr),
            uint_word(1_000_000_000), // 1000 USDC
            address_word(on_behalf),
            uint_word(0),
        ],
    );

    let to = "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: None,
        from: None,
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    // interpolatedIntent: "Supply {amount} for {onBehalfOf}"
    let intent = result.interpolated_intent.as_deref().unwrap();
    assert!(
        intent.contains("1000 USDC"),
        "interpolated intent should contain formatted amount: {intent}"
    );
    assert!(
        intent.contains("1111111111"),
        "interpolated intent should contain the address: {intent}"
    );
}

// --- Graceful Degradation Test ---

#[tokio::test]
async fn graceful_fallback_unknown_selector() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let tokens = aave_token_source();

    // Unknown function selector
    let calldata = hex::decode(
        "deadbeef000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000003e8",
    )
    .unwrap();

    let to = "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: None,
        from: None,
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert!(result.intent.contains("0xdeadbeef"));
    assert_eq!(
        result.fallback_reason(),
        Some(&clear_signing::FallbackReason::FormatNotFound)
    );
    assert!(
        result.diagnostics().iter().any(|diagnostic| diagnostic
            .message
            .contains("no descriptor format matched selector")),
        "expected format-not-found diagnostic"
    );
}

// --- L2 encoded withdraw(bytes32) on Optimism ---
// Real wallet data: Aave V3 Pool on Optimism uses L2-encoded functions
// where params are packed into a single bytes32 instead of separate args.
// The descriptor only has withdraw(address,uint256,address) (selector 0x69328dec),
// so the L2 variant withdraw(bytes32) (selector 0x8e19899e) falls back to raw preview.
#[tokio::test]
async fn aave_withdraw_bytes32_optimism_graceful_fallback() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let tokens = aave_token_source();

    // Exact calldata from wallet: withdraw(bytes32) on Optimism chain 10
    let calldata =
        hex::decode("8e19899e0000000000000000000000000000ffffffffffffffffffffffffffffffff0005")
            .unwrap();

    let to = "0x794a61358d6845594f94dc1db02a252b5b4814ad";
    let descriptors = wrap_rd(descriptor, 10, to);
    let tx = TransactionContext {
        chain_id: 10,
        to,
        calldata: &calldata,
        value: Some(&[0x00]),
        from: Some("0xbf01daf454dce008d3e2bfd47d5e186f71477253"),
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    // No format key matches selector 0x8e19899e, so we get graceful fallback
    assert!(
        result.intent.contains("0x8e19899e"),
        "should fall back to unknown function: {}",
        result.intent
    );
    assert_eq!(
        result.fallback_reason(),
        Some(&clear_signing::FallbackReason::FormatNotFound)
    );
    assert!(
        result.diagnostics().iter().any(|diagnostic| diagnostic
            .message
            .contains("no descriptor format matched selector")),
        "expected format-not-found diagnostic"
    );
    // The single bytes32 arg should appear as a raw param
    assert_eq!(result.entries.len(), 1);
}

// --- Real Wallet Request: Withdraw USDC on Mainnet ---

/// Exact eth_sendTransaction from a real wallet session:
/// to=0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2 (Aave LPv3, chain 1)
/// data=0x69328dec... (withdraw(address,uint256,address))
/// from=0xbf01daf454dce008d3e2bfd47d5e186f71477253
/// value=0x0
#[tokio::test]
async fn real_wallet_withdraw_usdc_mainnet() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let tokens = aave_token_source();

    let calldata = hex::decode(
        "69328dec\
         000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\
         ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\
         000000000000000000000000bf01daf454dce008d3e2bfd47d5e186f71477253",
    )
    .unwrap();

    let to = "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: Some(&[0x00]),
        from: Some("0xbf01daf454dce008d3e2bfd47d5e186f71477253"),
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Withdraw");
    assert_eq!(get_entry_value(&result, "Amount to withdraw"), "Max USDC");
    // Recipient should be the from address
    let to_value = get_entry_value(&result, "To recipient");
    assert!(
        to_value
            .to_lowercase()
            .contains("bf01daf454dce008d3e2bfd47d5e186f71477253"),
        "recipient should be the from address: {to_value}"
    );
    // Interpolated intent should use threshold/message formatting
    let interp = result.interpolated_intent.as_deref().unwrap();
    assert!(
        interp.contains("Max USDC"),
        "interpolated intent should contain 'Max USDC': {interp}"
    );
    assert!(
        interp.to_lowercase().contains("bf01daf454dce"),
        "interpolated intent should contain recipient: {interp}"
    );
}

/// Exact eth_sendTransaction: withdraw 0.1 USDC (100000 raw, 6 decimals) on mainnet.
/// Verifies interpolated intent renders formatted token amount, not raw integer.
#[tokio::test]
async fn real_wallet_withdraw_0_1_usdc_mainnet() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let tokens = aave_token_source();

    let calldata = hex::decode(
        "69328dec\
         000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\
         00000000000000000000000000000000000000000000000000000000000186a0\
         000000000000000000000000bf01daf454dce008d3e2bfd47d5e186f71477253",
    )
    .unwrap();

    let to = "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: Some(&[0x00]),
        from: Some("0xbf01daf454dce008d3e2bfd47d5e186f71477253"),
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Withdraw");
    assert_eq!(get_entry_value(&result, "Amount to withdraw"), "0.1 USDC");

    // Interpolated intent must show "0.1 USDC", not raw "100000"
    let interp = result.interpolated_intent.as_deref().unwrap();
    assert!(
        interp.contains("0.1 USDC"),
        "interpolated intent should contain '0.1 USDC': {interp}"
    );
    assert!(
        !interp.contains("100000"),
        "interpolated intent should NOT contain raw '100000': {interp}"
    );
}

// --- Real Transaction Tests (from Etherscan mainnet, generate-tests skill) ---

/// Real tx 0xae03ca4d: borrow 100 USDT variable rate on mainnet.
/// Verifies enum interpolation renders "variable" not raw "2" in interpolated intent.
#[tokio::test]
async fn real_tx_borrow_usdt_enum_interpolation() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let tokens = aave_token_source();

    let calldata = hex::decode(
        "a415bcad\
         000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec7\
         0000000000000000000000000000000000000000000000000000000005f5e100\
         0000000000000000000000000000000000000000000000000000000000000002\
         0000000000000000000000000000000000000000000000000000000000000000\
         000000000000000000000000694278718ecb91113a4c6141cc579dc105187a8a",
    )
    .unwrap();

    let to = "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: None,
        from: Some("0x694278718ecb91113a4c6141cc579dc105187a8a"),
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Borrow");
    assert_eq!(get_entry_value(&result, "Amount to borrow"), "100 USDT");
    assert_eq!(get_entry_value(&result, "Interest Rate mode"), "variable");

    let interp = result.interpolated_intent.as_deref().unwrap();
    assert!(
        interp.contains("100 USDT"),
        "interpolated intent should contain '100 USDT': {interp}"
    );
    assert!(
        interp.contains("variable"),
        "interpolated intent should contain 'variable' (not raw '2'): {interp}"
    );
    assert!(
        !interp.contains("with 2 rate"),
        "interpolated intent should NOT contain raw enum value 'with 2 rate': {interp}"
    );
}

/// Real tx 0x6a49bcf0: repay 99.348201 USDC variable rate on mainnet.
/// Verifies enum + tokenAmount interpolation together.
#[tokio::test]
async fn real_tx_repay_usdc_enum_interpolation() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let tokens = aave_token_source();

    let calldata = hex::decode(
        "573ade81\
         000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\
         0000000000000000000000000000000000000000000000000000000005ebeee9\
         0000000000000000000000000000000000000000000000000000000000000002\
         000000000000000000000000ad8c1b5b4d5dfe7fbe508ba57b1e05b33391f94a",
    )
    .unwrap();

    let to = "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: None,
        from: Some("0xad8c1b5b4d5dfe7fbe508ba57b1e05b33391f94a"),
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Repay loan");
    assert_eq!(
        get_entry_value(&result, "Amount to repay"),
        "99.348201 USDC"
    );
    assert_eq!(get_entry_value(&result, "Interest rate mode"), "variable");

    let interp = result.interpolated_intent.as_deref().unwrap();
    assert!(
        interp.contains("99.348201 USDC"),
        "interpolated intent should contain formatted amount: {interp}"
    );
    assert!(
        interp.contains("variable"),
        "interpolated intent should resolve enum to 'variable': {interp}"
    );
}

/// Real tx 0x9acfc63d: repay All USDT variable rate on mainnet.
/// Verifies threshold/message + enum interpolation together.
#[tokio::test]
async fn real_tx_repay_all_usdt_enum_interpolation() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let tokens = aave_token_source();

    let calldata = hex::decode(
        "573ade81\
         000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec7\
         ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\
         0000000000000000000000000000000000000000000000000000000000000002\
         0000000000000000000000000b5a6a15b975fd35f0b301748c8dabd35b50d8c5",
    )
    .unwrap();

    let to = "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: None,
        from: Some("0x0b5a6a15b975fd35f0b301748c8dabd35b50d8c5"),
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Repay loan");
    assert_eq!(get_entry_value(&result, "Amount to repay"), "All USDT");
    assert_eq!(get_entry_value(&result, "Interest rate mode"), "variable");

    let interp = result.interpolated_intent.as_deref().unwrap();
    assert!(
        interp.contains("All USDT"),
        "interpolated intent should contain threshold message: {interp}"
    );
    assert!(
        interp.contains("variable"),
        "interpolated intent should resolve enum to 'variable': {interp}"
    );
    assert!(
        !interp.contains("with 2"),
        "interpolated intent should NOT contain raw '2': {interp}"
    );
}

/// Real tx 0x3b5748a6: withdraw Max WETH on mainnet.
/// Verifies threshold/message interpolation with a token not in default well-known set.
#[tokio::test]
async fn real_tx_withdraw_max_weth() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let mut custom = StaticTokenSource::new();
    custom.insert(
        1,
        "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
        TokenMeta {
            symbol: "WETH".to_string(),
            decimals: 18,
            name: "Wrapped Ether".to_string(),
        },
    );
    let tokens = CompositeDataProvider::new(vec![
        Box::new(custom),
        Box::new(WellKnownTokenSource::new()),
    ]);

    let calldata = hex::decode(
        "69328dec\
         000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\
         ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\
         0000000000000000000000002f45665810956929bbfaa984d70a511ad08b0b54",
    )
    .unwrap();

    let to = "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: None,
        from: Some("0x2f45665810956929bbfaa984d70a511ad08b0b54"),
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Withdraw");
    assert_eq!(get_entry_value(&result, "Amount to withdraw"), "Max WETH");

    let interp = result.interpolated_intent.as_deref().unwrap();
    assert!(
        interp.contains("Max WETH"),
        "interpolated intent should contain 'Max WETH': {interp}"
    );
}

/// Real tx 0x1f7166e2: supplyWithPermit 13400 USDC on mainnet.
/// Verifies permit variant formatting with real data.
#[tokio::test]
async fn real_tx_supply_with_permit_usdc() {
    let descriptor = load_descriptor("aave-lpv3.json");
    let tokens = aave_token_source();

    let calldata = hex::decode(
        "02c205f0\
         000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\
         000000000000000000000000000000000000000000000000000000031eb3c600\
         00000000000000000000000044f2a3aa7fdda16a7bf66c68fba96508078d2bdc\
         0000000000000000000000000000000000000000000000000000000000000000\
         0000000000000000000000000000000000000000000000000000000069b6a5b9\
         000000000000000000000000000000000000000000000000000000000000001c\
         3c0980cd1d3bbc8d4e6d2e393e0913eeeaf25785629f0a535650dcf99b5176dd\
         0d838b39d2ef75a01d05e11911d6cf9abc53ef9a51f845a5e3445a9c853fe9a2",
    )
    .unwrap();

    let to = "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2";
    let descriptors = wrap_rd(descriptor, 1, to);
    let tx = TransactionContext {
        chain_id: 1,
        to,
        calldata: &calldata,
        value: None,
        from: Some("0x44f2a3aa7fdda16a7bf66c68fba96508078d2bdc"),
        implementation_address: None,
    };
    let result = format_calldata(&descriptors, &tx, &tokens).await.unwrap();

    assert_eq!(result.intent, "Supply");
    assert_eq!(get_entry_value(&result, "Amount to supply"), "13400 USDC");

    let interp = result.interpolated_intent.as_deref().unwrap();
    assert!(
        interp.contains("13400 USDC"),
        "interpolated intent should contain '13400 USDC': {interp}"
    );
}