mpp 0.15.0

Rust SDK for the Machine Payments Protocol (MPP)
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
use super::*;

#[test]
fn test_transfer_selector() {
    // transfer(address,uint256) = 0xa9059cbb
    assert_eq!(TRANSFER_SELECTOR, [0xa9, 0x05, 0x9c, 0xbb]);
}

#[test]
fn test_transfer_with_memo_selector() {
    // transferWithMemo(address,uint256,bytes32) = 0x95777d59
    assert_eq!(TRANSFER_WITH_MEMO_SELECTOR, [0x95, 0x77, 0x7d, 0x59]);
}

#[test]
fn test_calldata_length_constants() {
    // Verify the expected calldata lengths match ABI encoding
    // transfer(address,uint256): 4 + 32 + 32 = 68
    // transferWithMemo(address,uint256,bytes32): 4 + 32 + 32 + 32 = 100
    const TRANSFER_CALLDATA_LEN: usize = 4 + 32 + 32;
    const TRANSFER_WITH_MEMO_CALLDATA_LEN: usize = 4 + 32 + 32 + 32;

    assert_eq!(TRANSFER_CALLDATA_LEN, 68);
    assert_eq!(TRANSFER_WITH_MEMO_CALLDATA_LEN, 100);
}

#[test]
fn test_selector_parsing_short_input() {
    // Ensure short inputs don't panic - test with various short lengths
    let short_inputs: Vec<&[u8]> = vec![&[], &[0xa9], &[0xa9, 0x05], &[0xa9, 0x05, 0x9c]];

    for input in short_inputs {
        // This mimics the parsing logic - should not panic
        if input.len() >= 4 {
            let _selector: [u8; 4] = input[..4].try_into().unwrap_or([0; 4]);
        }
    }
}

#[test]
fn test_validate_transaction_transfers_rejects_unexpected_fee_payer_calls() {
    let provider =
        alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_http("http://127.0.0.1:1".parse().unwrap());
    let method = ChargeMethod::new(provider);

    let currency = Address::repeat_byte(0x20);
    let recipient = Address::repeat_byte(0x33);
    let expected = vec![Transfer {
        amount: U256::from(100u64),
        recipient,
        memo: None,
    }];

    let tx_bytes = encode_signed_tx(
        vec![
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(currency),
                value: U256::ZERO,
                input: make_transfer_input(recipient, U256::from(100u64)),
            },
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(Address::repeat_byte(0x44)),
                value: U256::ZERO,
                input: Bytes::from(vec![0u8; 4]),
            },
        ],
        MAX_FEE_PAYER_GAS_LIMIT,
    );

    let error = method
        .validate_transaction_transfers(&tx_bytes, currency, &expected, CHAIN_ID, true)
        .unwrap_err();

    assert!(
        error.to_string().contains("disallowed call pattern")
            || error.to_string().contains("no matching payment call")
    );
}

#[test]
fn test_validate_transaction_transfers_rejects_fee_payer_with_too_many_transfers() {
    let provider =
        alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_http("http://127.0.0.1:1".parse().unwrap());
    let method = ChargeMethod::new(provider);

    let currency = Address::repeat_byte(0x20);
    let recipient = Address::repeat_byte(0x33);
    let transfer = Transfer {
        amount: U256::from(100u64),
        recipient,
        memo: None,
    };
    let call = tempo_alloy::primitives::transaction::Call {
        to: TxKind::Call(currency),
        value: U256::ZERO,
        input: make_transfer_input(recipient, U256::from(100u64)),
    };
    let validate = |transfers: usize| {
        let tx_bytes = encode_signed_tx(vec![call.clone(); transfers], MAX_FEE_PAYER_GAS_LIMIT);
        let expected = vec![transfer.clone(); transfers];
        method.validate_transaction_transfers(&tx_bytes, currency, &expected, CHAIN_ID, true)
    };

    validate(11).unwrap();
    let error = validate(12).unwrap_err();
    assert!(
        error.to_string().contains("disallowed call pattern"),
        "{error}"
    );
}

#[test]
fn test_validate_transaction_transfers_accepts_fee_payer_approve_swap_prefix() {
    let provider =
        alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_http("http://127.0.0.1:1".parse().unwrap());
    let method = ChargeMethod::new(provider);

    let currency = Address::repeat_byte(0x20);
    let recipient = Address::repeat_byte(0x33);
    let token_in = Address::repeat_byte(0x11);
    let expected = vec![Transfer {
        amount: U256::from(100u64),
        recipient,
        memo: None,
    }];

    let tx_bytes = encode_signed_tx(
        vec![
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(token_in),
                value: U256::ZERO,
                input: make_approve_input(STABLECOIN_DEX_ADDRESS, U256::from(100u64)),
            },
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(STABLECOIN_DEX_ADDRESS),
                value: U256::ZERO,
                input: make_swap_input(token_in, currency, 100),
            },
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(currency),
                value: U256::ZERO,
                input: make_transfer_input(recipient, U256::from(100u64)),
            },
        ],
        MAX_FEE_PAYER_GAS_LIMIT,
    );

    method
        .validate_transaction_transfers(&tx_bytes, currency, &expected, CHAIN_ID, true)
        .unwrap();
}

#[test]
fn test_validate_transaction_transfers_accepts_exact_machine_token_route() {
    let provider =
        alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_http("http://127.0.0.1:1".parse().unwrap());
    let method = ChargeMethod::new(provider);
    let currency = Address::repeat_byte(0x20);
    let expected = vec![Transfer {
        amount: U256::from(100u64),
        recipient: Address::repeat_byte(0x33),
        memo: Some([0xab; 32]),
    }];
    let route = super::super::super::machine_token::route(CHAIN_ID, currency, &expected).unwrap();
    let tx_bytes = encode_signed_tx(route.calls.to_vec(), MAX_FEE_PAYER_GAS_LIMIT);

    let settlement_sender = method
        .validate_transaction_transfers_with_machine_token(
            &tx_bytes,
            currency,
            &expected,
            CHAIN_ID,
            TransactionValidationOptions {
                require_exact_calls: true,
                machine_token_enabled: true,
                challenge_binding: None,
            },
        )
        .unwrap();
    assert_eq!(settlement_sender, Some(route.settlement_sender));

    assert!(method
        .validate_transaction_transfers_with_machine_token(
            &tx_bytes,
            currency,
            &expected,
            CHAIN_ID,
            TransactionValidationOptions {
                require_exact_calls: true,
                ..Default::default()
            },
        )
        .is_err());
}

#[test]
fn test_validate_transaction_transfers_checks_challenge_bound_memo() {
    let provider =
        alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_http("http://127.0.0.1:1".parse().unwrap());
    let method = ChargeMethod::new(provider);
    let currency = Address::repeat_byte(0x20);
    let recipient = Address::repeat_byte(0x33);
    let amount = U256::from(100u64);
    let bound = attribution::encode("challenge-123", "api.example.com", None);
    let cases = [
        ("matching challenge", Some(bound), true),
        (
            "wrong challenge",
            Some(attribution::encode(
                "challenge-456",
                "api.example.com",
                None,
            )),
            false,
        ),
        (
            "wrong realm",
            Some(attribution::encode(
                "challenge-123",
                "other.example.com",
                None,
            )),
            false,
        ),
        ("non-MPP memo", Some([0xab; 32]), false),
        ("plain transfer", None, false),
    ];

    for require_exact_calls in [false, true] {
        for (name, memo, should_accept) in cases {
            for split in [false, true] {
                for reverse in [false, true] {
                    let mut expected = vec![Transfer {
                        amount,
                        recipient,
                        memo: None,
                    }];
                    let input = match memo {
                        Some(memo) => make_transfer_with_memo_input(recipient, amount, memo),
                        None => make_transfer_input(recipient, amount),
                    };
                    let mut calls = vec![tempo_alloy::primitives::transaction::Call {
                        to: TxKind::Call(currency),
                        value: U256::ZERO,
                        input,
                    }];
                    if split {
                        let split_recipient = Address::repeat_byte(0x44);
                        expected.push(Transfer {
                            amount,
                            recipient: split_recipient,
                            memo: Some([0xcd; 32]),
                        });
                        calls.push(tempo_alloy::primitives::transaction::Call {
                            to: TxKind::Call(currency),
                            value: U256::ZERO,
                            input: make_transfer_with_memo_input(
                                split_recipient,
                                amount,
                                [0xcd; 32],
                            ),
                        });
                    }
                    if reverse {
                        calls.reverse();
                    }
                    let tx_bytes = encode_signed_tx(calls, MAX_FEE_PAYER_GAS_LIMIT);
                    let result = method.validate_transaction_transfers_with_machine_token(
                        &tx_bytes,
                        currency,
                        &expected,
                        CHAIN_ID,
                        TransactionValidationOptions {
                            require_exact_calls,
                            challenge_binding: Some(("challenge-123", "api.example.com")),
                            ..Default::default()
                        },
                    );
                    assert_eq!(result.is_ok(), should_accept,
                        "case: {name}, exact: {require_exact_calls}, split: {split}, reverse: {reverse}");
                    if let Err(error) = result {
                        assert!(
                            error
                                .to_string()
                                .contains("memo is not bound to this challenge"),
                            "case: {name}; unexpected error: {error}"
                        );
                    }
                }
            }
        }
    }
}

#[test]
fn test_validate_transaction_transfers_rejects_conflicting_attribution() {
    let provider =
        alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_http("http://127.0.0.1:1".parse().unwrap());
    let method = ChargeMethod::new(provider);
    let currency = Address::repeat_byte(0x20);
    let recipient = Address::repeat_byte(0x33);
    let split_recipient = Address::repeat_byte(0x44);
    let amount = U256::from(100u64);
    let realm = "api.example.com";
    // One transaction paying the primary transfer of `challenge-456` and
    // the split of `challenge-123`.
    let calls = vec![
        tempo_alloy::primitives::transaction::Call {
            to: TxKind::Call(currency),
            value: U256::ZERO,
            input: make_transfer_with_memo_input(
                recipient,
                amount,
                attribution::encode("challenge-456", realm, None),
            ),
        },
        tempo_alloy::primitives::transaction::Call {
            to: TxKind::Call(currency),
            value: U256::ZERO,
            input: make_transfer_with_memo_input(
                split_recipient,
                amount,
                attribution::encode("challenge-123", realm, None),
            ),
        },
    ];
    let primary = Transfer {
        amount,
        recipient,
        memo: None,
    };
    let split = Transfer {
        amount,
        recipient: split_recipient,
        memo: None,
    };

    for reverse in [false, true] {
        let mut calls = calls.clone();
        if reverse {
            calls.reverse();
        }
        let tx_bytes = encode_signed_tx(calls, MAX_FEE_PAYER_GAS_LIMIT);
        let validate = |challenge_id, expected: &[Transfer], require_exact_calls| {
            method.validate_transaction_transfers_with_machine_token(
                &tx_bytes,
                currency,
                expected,
                CHAIN_ID,
                TransactionValidationOptions {
                    require_exact_calls,
                    challenge_binding: Some((challenge_id, realm)),
                    ..Default::default()
                },
            )
        };

        for require_exact_calls in [false, true] {
            let error = validate(
                "challenge-123",
                &[primary.clone(), split.clone()],
                require_exact_calls,
            )
            .unwrap_err();
            assert!(
                error
                    .to_string()
                    .contains("memo is not bound to this challenge"),
                "unexpected error: {error}"
            );
        }
        // The unmatched split transfer does not affect the other challenge.
        assert!(validate("challenge-456", std::slice::from_ref(&primary), false).is_ok());
    }
}

#[test]
fn test_machine_token_route_checks_challenge_binding() {
    let provider =
        alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_http("http://127.0.0.1:1".parse().unwrap());
    let method = ChargeMethod::new(provider);
    let currency = Address::repeat_byte(0x20);
    let expected = vec![Transfer {
        amount: U256::from(100),
        recipient: Address::repeat_byte(0x33),
        memo: None,
    }];
    for (memo, should_accept) in [
        (
            attribution::encode("challenge-123", "api.example.com", None),
            true,
        ),
        (
            attribution::encode("challenge-456", "api.example.com", None),
            false,
        ),
        (
            attribution::encode("challenge-123", "other.example.com", None),
            false,
        ),
        ([0xab; 32], false),
    ] {
        let mut actual = expected.clone();
        actual[0].memo = Some(memo);
        let route = super::super::super::machine_token::route(CHAIN_ID, currency, &actual).unwrap();
        let tx_bytes = encode_signed_tx(route.calls.to_vec(), MAX_FEE_PAYER_GAS_LIMIT);
        let result = method.validate_transaction_transfers_with_machine_token(
            &tx_bytes,
            currency,
            &expected,
            CHAIN_ID,
            TransactionValidationOptions {
                require_exact_calls: true,
                machine_token_enabled: true,
                challenge_binding: Some(("challenge-123", "api.example.com")),
            },
        );
        assert_eq!(result.is_ok(), should_accept);
        match result {
            Ok(sender) => assert_eq!(sender, Some(route.settlement_sender)),
            Err(error) => assert!(error
                .to_string()
                .contains("memo is not bound to this challenge")),
        }
    }
}

#[test]
fn test_legacy_primary_memo_does_not_disable_challenge_binding() {
    let provider =
        alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_http("http://127.0.0.1:1".parse().unwrap());
    let method = ChargeMethod::new(provider);
    let currency = Address::repeat_byte(0x20);
    let recipient = Address::repeat_byte(0x33);
    let amount = U256::from(100);
    for (memo, should_accept) in [
        (
            attribution::encode("challenge-123", "api.example.com", None),
            true,
        ),
        ([0xab; 32], false),
    ] {
        let tx_bytes = encode_signed_tx(
            vec![tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(currency),
                value: U256::ZERO,
                input: make_transfer_with_memo_input(recipient, amount, memo),
            }],
            MAX_FEE_PAYER_GAS_LIMIT,
        );
        let request = ChargeRequest {
            amount: amount.to_string(),
            currency: format!("{currency:#x}"),
            recipient: Some(format!("{recipient:#x}")),
            method_details: Some(
                serde_json::json!({ "chainId": CHAIN_ID, "memo": alloy::hex::encode_prefixed([0xab; 32]) }),
            ),
            ..Default::default()
        };
        let result = method.validate_transaction_credential(
            &alloy::hex::encode_prefixed(&tx_bytes),
            &request,
            CHAIN_ID,
            "challenge-123",
            "api.example.com",
        );
        assert_eq!(result.is_ok(), should_accept);
    }
}

#[test]
fn test_validate_transaction_transfers_accepts_fee_payer_approve_swap_prefix_with_splits() {
    let provider =
        alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_http("http://127.0.0.1:1".parse().unwrap());
    let method = ChargeMethod::new(provider);

    let currency = Address::repeat_byte(0x20);
    let primary_recipient = Address::repeat_byte(0x33);
    let split_recipient = Address::repeat_byte(0x34);
    let token_in = Address::repeat_byte(0x11);
    let expected = vec![
        Transfer {
            amount: U256::from(90u64),
            recipient: primary_recipient,
            memo: None,
        },
        Transfer {
            amount: U256::from(10u64),
            recipient: split_recipient,
            memo: None,
        },
    ];

    let tx_bytes = encode_signed_tx(
        vec![
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(token_in),
                value: U256::ZERO,
                input: make_approve_input(STABLECOIN_DEX_ADDRESS, U256::from(100u64)),
            },
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(STABLECOIN_DEX_ADDRESS),
                value: U256::ZERO,
                input: make_swap_input(token_in, currency, 100),
            },
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(currency),
                value: U256::ZERO,
                input: make_transfer_input(primary_recipient, U256::from(90u64)),
            },
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(currency),
                value: U256::ZERO,
                input: make_transfer_input(split_recipient, U256::from(10u64)),
            },
        ],
        MAX_FEE_PAYER_GAS_LIMIT,
    );

    method
        .validate_transaction_transfers(&tx_bytes, currency, &expected, CHAIN_ID, true)
        .unwrap();
}

#[test]
fn test_validate_transaction_transfers_rejects_fee_payer_swap_without_approve() {
    let provider =
        alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_http("http://127.0.0.1:1".parse().unwrap());
    let method = ChargeMethod::new(provider);

    let currency = Address::repeat_byte(0x20);
    let recipient = Address::repeat_byte(0x33);
    let token_in = Address::repeat_byte(0x11);
    let expected = vec![Transfer {
        amount: U256::from(100u64),
        recipient,
        memo: None,
    }];

    let tx_bytes = encode_signed_tx(
        vec![
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(STABLECOIN_DEX_ADDRESS),
                value: U256::ZERO,
                input: make_swap_input(token_in, currency, 100),
            },
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(currency),
                value: U256::ZERO,
                input: make_transfer_input(recipient, U256::from(100u64)),
            },
        ],
        MAX_FEE_PAYER_GAS_LIMIT,
    );

    let error = method
        .validate_transaction_transfers(&tx_bytes, currency, &expected, CHAIN_ID, true)
        .unwrap_err();

    assert!(
        error.to_string().contains("disallowed call pattern")
            || error.to_string().contains("no matching payment call")
    );
}

#[test]
fn test_validate_transaction_transfers_rejects_fee_payer_wrong_approve_spender() {
    let provider =
        alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_http("http://127.0.0.1:1".parse().unwrap());
    let method = ChargeMethod::new(provider);

    let currency = Address::repeat_byte(0x20);
    let recipient = Address::repeat_byte(0x33);
    let token_in = Address::repeat_byte(0x11);
    let expected = vec![Transfer {
        amount: U256::from(100u64),
        recipient,
        memo: None,
    }];

    let tx_bytes = encode_signed_tx(
        vec![
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(token_in),
                value: U256::ZERO,
                input: make_approve_input(Address::repeat_byte(0x99), U256::from(100u64)),
            },
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(STABLECOIN_DEX_ADDRESS),
                value: U256::ZERO,
                input: make_swap_input(token_in, currency, 100),
            },
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(currency),
                value: U256::ZERO,
                input: make_transfer_input(recipient, U256::from(100u64)),
            },
        ],
        MAX_FEE_PAYER_GAS_LIMIT,
    );

    let error = method
        .validate_transaction_transfers(&tx_bytes, currency, &expected, CHAIN_ID, true)
        .unwrap_err();

    assert!(error.to_string().contains("approve spender is not the DEX"));
}

#[test]
fn test_validate_transaction_transfers_rejects_fee_payer_wrong_approve_target() {
    let provider =
        alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_http("http://127.0.0.1:1".parse().unwrap());
    let method = ChargeMethod::new(provider);

    let currency = Address::repeat_byte(0x20);
    let recipient = Address::repeat_byte(0x33);
    let token_in = Address::repeat_byte(0x11);
    let expected = vec![Transfer {
        amount: U256::from(100u64),
        recipient,
        memo: None,
    }];

    let tx_bytes = encode_signed_tx(
        vec![
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(Address::repeat_byte(0x99)),
                value: U256::ZERO,
                input: make_approve_input(STABLECOIN_DEX_ADDRESS, U256::from(100u64)),
            },
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(STABLECOIN_DEX_ADDRESS),
                value: U256::ZERO,
                input: make_swap_input(token_in, currency, 100),
            },
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(currency),
                value: U256::ZERO,
                input: make_transfer_input(recipient, U256::from(100u64)),
            },
        ],
        MAX_FEE_PAYER_GAS_LIMIT,
    );

    let error = method
        .validate_transaction_transfers(&tx_bytes, currency, &expected, CHAIN_ID, true)
        .unwrap_err();

    assert!(error
        .to_string()
        .contains("approve target is not the swap input token"));
}

#[test]
fn test_validate_transaction_transfers_rejects_fee_payer_wrong_swap_target() {
    let provider =
        alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_http("http://127.0.0.1:1".parse().unwrap());
    let method = ChargeMethod::new(provider);

    let currency = Address::repeat_byte(0x20);
    let recipient = Address::repeat_byte(0x33);
    let token_in = Address::repeat_byte(0x11);
    let expected = vec![Transfer {
        amount: U256::from(100u64),
        recipient,
        memo: None,
    }];

    let tx_bytes = encode_signed_tx(
        vec![
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(token_in),
                value: U256::ZERO,
                input: make_approve_input(STABLECOIN_DEX_ADDRESS, U256::from(100u64)),
            },
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(Address::repeat_byte(0x98)),
                value: U256::ZERO,
                input: make_swap_input(token_in, currency, 100),
            },
            tempo_alloy::primitives::transaction::Call {
                to: TxKind::Call(currency),
                value: U256::ZERO,
                input: make_transfer_input(recipient, U256::from(100u64)),
            },
        ],
        MAX_FEE_PAYER_GAS_LIMIT,
    );

    let error = method
        .validate_transaction_transfers(&tx_bytes, currency, &expected, CHAIN_ID, true)
        .unwrap_err();

    assert!(error.to_string().contains("swap target is not the DEX"));
}

/// The swap prefix must only acquire the charge: the approval covers
/// exactly the swap input, and the swap buys exactly the payment.
#[test]
fn test_validate_transaction_transfers_rejects_fee_payer_unbound_swap_prefix() {
    let provider =
        alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_http("http://127.0.0.1:1".parse().unwrap());
    let method = ChargeMethod::new(provider);

    let currency = Address::repeat_byte(0x20);
    let recipient = Address::repeat_byte(0x33);
    let split_recipient = Address::repeat_byte(0x34);
    let token_in = Address::repeat_byte(0x11);
    let expected = vec![
        Transfer {
            amount: U256::from(90u64),
            recipient,
            memo: None,
        },
        Transfer {
            amount: U256::from(10u64),
            recipient: split_recipient,
            memo: None,
        },
    ];

    let validate = |approve_amount: u64, token_out: Address, amount_out: u128| {
        let tx_bytes = encode_signed_tx(
            vec![
                tempo_alloy::primitives::transaction::Call {
                    to: TxKind::Call(token_in),
                    value: U256::ZERO,
                    input: make_approve_input(STABLECOIN_DEX_ADDRESS, U256::from(approve_amount)),
                },
                tempo_alloy::primitives::transaction::Call {
                    to: TxKind::Call(STABLECOIN_DEX_ADDRESS),
                    value: U256::ZERO,
                    input: Bytes::from(
                        IStablecoinDEX::swapExactAmountOutCall {
                            tokenIn: token_in,
                            tokenOut: token_out,
                            amountOut: amount_out,
                            maxAmountIn: 101,
                        }
                        .abi_encode(),
                    ),
                },
                tempo_alloy::primitives::transaction::Call {
                    to: TxKind::Call(currency),
                    value: U256::ZERO,
                    input: make_transfer_input(recipient, U256::from(90u64)),
                },
                tempo_alloy::primitives::transaction::Call {
                    to: TxKind::Call(currency),
                    value: U256::ZERO,
                    input: make_transfer_input(split_recipient, U256::from(10u64)),
                },
            ],
            MAX_FEE_PAYER_GAS_LIMIT,
        );
        method.validate_transaction_transfers(&tx_bytes, currency, &expected, CHAIN_ID, true)
    };

    validate(101, currency, 100).expect("bound swap prefix is accepted");

    for (approve_amount, token_out, amount_out, expected_error) in [
        (
            u64::MAX,
            currency,
            100,
            "approve amount does not match the swap max input",
        ),
        (
            101,
            Address::repeat_byte(0x21),
            100,
            "swap output token is not the payment currency",
        ),
        (
            101,
            currency,
            1_000,
            "swap output does not match the payment amount",
        ),
        (
            101,
            currency,
            90,
            "swap output does not match the payment amount",
        ),
    ] {
        let error = validate(approve_amount, token_out, amount_out).unwrap_err();
        assert!(
            error.to_string().contains(expected_error),
            "expected `{expected_error}`, got: {error}"
        );
    }
}

#[test]
fn test_validate_transaction_transfers_rejects_fee_payer_gas_limit_above_max() {
    let provider =
        alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_http("http://127.0.0.1:1".parse().unwrap());
    let method = ChargeMethod::new(provider);

    let currency = Address::repeat_byte(0x20);
    let recipient = Address::repeat_byte(0x33);
    let expected = vec![Transfer {
        amount: U256::from(100u64),
        recipient,
        memo: None,
    }];

    let tx_bytes = encode_signed_tx(
        vec![tempo_alloy::primitives::transaction::Call {
            to: TxKind::Call(currency),
            value: U256::ZERO,
            input: make_transfer_input(recipient, U256::from(100u64)),
        }],
        MAX_FEE_PAYER_GAS_LIMIT + 1,
    );

    let error = method
        .validate_transaction_transfers(&tx_bytes, currency, &expected, CHAIN_ID, true)
        .unwrap_err();

    assert!(error.to_string().contains("exceeds maximum"));
}

#[test]
fn test_policy_override_adjusts_fee_payer_gas_limit() {
    let currency = Address::repeat_byte(0x20);
    let recipient = Address::repeat_byte(0x33);
    let expected = vec![Transfer {
        amount: U256::from(100u64),
        recipient,
        memo: None,
    }];
    let calls = vec![tempo_alloy::primitives::transaction::Call {
        to: TxKind::Call(currency),
        value: U256::ZERO,
        input: make_transfer_input(recipient, U256::from(100u64)),
    }];

    let build_method = || {
        let provider =
            alloy::providers::ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
                .connect_http("http://127.0.0.1:1".parse().unwrap());
        ChargeMethod::new(provider)
    };

    // Lower ceiling: default (2M) would accept 2.5M, override (500k) rejects.
    let lowered = build_method().with_fee_payer_policy_override(FeePayerPolicyOverride {
        max_gas: Some(500_000),
        ..Default::default()
    });
    let tx_under_default_over_override = encode_signed_tx(calls.clone(), 500_001);
    let error = lowered
        .validate_transaction_transfers(
            &tx_under_default_over_override,
            currency,
            &expected,
            CHAIN_ID,
            true,
        )
        .unwrap_err();
    assert!(error.to_string().contains("exceeds maximum 500000"));

    // Raise ceiling: default (2M) would reject 2.5M, override (3M) accepts.
    let raised = build_method().with_fee_payer_policy_override(FeePayerPolicyOverride {
        max_gas: Some(3_000_000),
        ..Default::default()
    });
    let tx_over_default_under_override = encode_signed_tx(calls, 2_500_000);
    raised
        .validate_transaction_transfers(
            &tx_over_default_under_override,
            currency,
            &expected,
            CHAIN_ID,
            true,
        )
        .expect("override should raise ceiling above default");
}