mpp-br 0.8.1

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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
//! Shared client-side channel operations for Tempo session payments.
//!
//! Provides low-level helpers for escrow resolution, channel ID computation,
//! voucher/close/open payload construction, channel recovery from on-chain state,
//! and credential serialization.
//!
//! Ported from the TypeScript SDK's `ChannelOps.ts`.

use alloy::primitives::{Address, Bytes, TxKind, B256, U256};
use alloy::providers::Provider;
use alloy::signers::Signer;
use alloy::sol_types::{SolCall, SolValue};
use tempo_alloy::TempoNetwork;

use crate::error::{MppError, ResultExt};
use crate::protocol::core::{PaymentChallenge, PaymentCredential};
use crate::protocol::intents::SessionRequest;
use crate::protocol::methods::tempo::session::{SessionCredentialPayload, TempoSessionExt};
use crate::protocol::methods::tempo::voucher::{compute_channel_id, sign_voucher};
use crate::protocol::methods::tempo::MODERATO_CHAIN_ID;

/// Default escrow contract addresses per chain ID.
pub fn default_escrow_contract(chain_id: u64) -> Option<Address> {
    match chain_id {
        4217 => Some(
            "0x33b901018174DDabE4841042ab76ba85D4e24f25"
                .parse()
                .unwrap(),
        ),
        42431 => Some(
            "0xe1c4d3dce17bc111181ddf716f75bae49e61a336"
                .parse()
                .unwrap(),
        ),
        _ => None,
    }
}

/// Client-side channel entry tracking channel state.
#[derive(Debug, Clone)]
pub struct ChannelEntry {
    /// On-chain channel ID (keccak256 of channel parameters).
    pub channel_id: B256,
    /// Random salt used during channel creation.
    pub salt: B256,
    /// Running cumulative amount of all vouchers issued.
    pub cumulative_amount: u128,
    /// Escrow contract address.
    pub escrow_contract: Address,
    /// Chain ID where the escrow contract is deployed.
    pub chain_id: u64,
    /// Whether the channel has been opened on-chain.
    pub opened: bool,
}

/// Resolve chain ID from a session challenge's methodDetails.
pub fn resolve_chain_id(challenge: &PaymentChallenge) -> u64 {
    let session: Result<SessionRequest, _> = challenge.request.decode();
    session
        .ok()
        .and_then(|r| r.chain_id())
        .unwrap_or(MODERATO_CHAIN_ID)
}

/// Resolve escrow contract address from challenge methodDetails, an override, or defaults.
pub fn resolve_escrow(
    challenge: &PaymentChallenge,
    chain_id: u64,
    escrow_override: Option<Address>,
) -> Result<Address, MppError> {
    // Try challenge methodDetails first
    if let Ok(req) = challenge.request.decode::<SessionRequest>() {
        if let Ok(addr_str) = req.escrow_contract() {
            if let Ok(addr) = addr_str.parse::<Address>() {
                return Ok(addr);
            }
        }
    }

    // Then override
    if let Some(addr) = escrow_override {
        return Ok(addr);
    }

    // Then defaults
    default_escrow_contract(chain_id).ok_or_else(|| {
        MppError::InvalidConfig(
            "No escrowContract available. Provide it in parameters or ensure the server challenge includes it.".to_string(),
        )
    })
}

/// Build a `PaymentCredential` from a challenge and session payload.
pub fn build_credential(
    challenge: &PaymentChallenge,
    payload: SessionCredentialPayload,
    chain_id: u64,
    signer_address: Address,
) -> PaymentCredential {
    let echo = challenge.to_echo();
    let source = PaymentCredential::evm_did(chain_id, &signer_address.to_string());
    PaymentCredential::with_source(echo, source, payload)
}

/// Create a voucher payload by signing a voucher.
pub async fn create_voucher_payload<S: Signer + ?Sized>(
    signer: &S,
    channel_id: B256,
    cumulative_amount: u128,
    escrow_contract: Address,
    chain_id: u64,
) -> Result<SessionCredentialPayload, MppError> {
    let sig = sign_voucher(
        signer,
        channel_id,
        cumulative_amount,
        escrow_contract,
        chain_id,
    )
    .await?;

    Ok(SessionCredentialPayload::Voucher {
        channel_id: channel_id.to_string(),
        cumulative_amount: cumulative_amount.to_string(),
        signature: alloy::hex::encode_prefixed(&sig),
    })
}

/// Create a close payload by signing a voucher with close action.
pub async fn create_close_payload<S: Signer + ?Sized>(
    signer: &S,
    channel_id: B256,
    cumulative_amount: u128,
    escrow_contract: Address,
    chain_id: u64,
) -> Result<SessionCredentialPayload, MppError> {
    let sig = sign_voucher(
        signer,
        channel_id,
        cumulative_amount,
        escrow_contract,
        chain_id,
    )
    .await?;

    Ok(SessionCredentialPayload::Close {
        channel_id: channel_id.to_string(),
        cumulative_amount: cumulative_amount.to_string(),
        signature: alloy::hex::encode_prefixed(&sig),
    })
}

/// Options for creating an open payload.
pub struct OpenPayloadOptions {
    pub authorized_signer: Option<Address>,
    pub escrow_contract: Address,
    pub payee: Address,
    pub currency: Address,
    pub deposit: u128,
    pub initial_amount: u128,
    pub chain_id: u64,
    pub fee_payer: bool,
}

/// Create an open payload: builds approve+open multicall transaction, signs it,
/// and signs the initial voucher.
///
/// Builds a Tempo transaction (type 0x76) containing:
/// 1. `TIP20.approve(escrow, deposit)`
/// 2. `escrow.open(payee, token, deposit, salt, authorizedSigner)`
///
/// Then signs an initial voucher for `initial_amount`.
pub async fn create_open_payload<P, S>(
    provider: &P,
    signer: &S,
    signing_mode: Option<&crate::client::tempo::signing::TempoSigningMode>,
    payer: Address,
    options: OpenPayloadOptions,
) -> Result<(ChannelEntry, SessionCredentialPayload), MppError>
where
    P: Provider<TempoNetwork>,
    S: Signer + ?Sized,
{
    use alloy::sol;
    use tempo_primitives::transaction::Call;

    let default_mode = crate::client::tempo::signing::TempoSigningMode::Direct;
    let signing_mode = signing_mode.unwrap_or(&default_mode);

    let authorized_signer = options.authorized_signer.unwrap_or(payer);

    // Generate random salt
    let salt = B256::random();

    // Compute channel ID
    let channel_id = compute_channel_id(
        payer,
        options.payee,
        options.currency,
        salt,
        authorized_signer,
        options.escrow_contract,
        options.chain_id,
    );

    // Build approve calldata
    use tempo_alloy::contracts::precompiles::ITIP20;

    sol! {
        interface IEscrow {
            function open(
                address payee,
                address token,
                uint128 deposit,
                bytes32 salt,
                address authorizedSigner
            ) external;
        }
    }

    let approve_data =
        ITIP20::approveCall::new((options.escrow_contract, U256::from(options.deposit)))
            .abi_encode();

    let open_data = IEscrow::openCall::new((
        options.payee,
        options.currency,
        options.deposit,
        salt,
        authorized_signer,
    ))
    .abi_encode();

    // Build Tempo multicall transaction
    let calls = vec![
        Call {
            to: TxKind::Call(options.currency),
            value: U256::ZERO,
            input: Bytes::from(approve_data),
        },
        Call {
            to: TxKind::Call(options.escrow_contract),
            value: U256::ZERO,
            input: Bytes::from(open_data),
        },
    ];

    let nonce = provider
        .get_transaction_count(payer)
        .await
        .mpp_http("failed to get nonce")?;

    let gas_price = provider
        .get_gas_price()
        .await
        .mpp_http("failed to get gas price")?;

    let tempo_tx = crate::client::tempo::charge::tx_builder::build_tempo_tx(
        crate::client::tempo::charge::tx_builder::TempoTxOptions {
            calls,
            chain_id: options.chain_id,
            fee_token: options.currency,
            nonce,
            nonce_key: U256::ZERO,
            gas_limit: 2_000_000,
            max_fee_per_gas: gas_price,
            max_priority_fee_per_gas: gas_price,
            fee_payer: options.fee_payer,
            valid_before: None,
            key_authorization: signing_mode.key_authorization().cloned(),
        },
    );

    let tx_bytes =
        crate::client::tempo::signing::sign_and_encode_async(tempo_tx, signer, signing_mode)
            .await?;
    let signed_tx_hex = alloy::hex::encode_prefixed(&tx_bytes);

    // Sign the initial voucher
    let voucher_sig = sign_voucher(
        signer,
        channel_id,
        options.initial_amount,
        options.escrow_contract,
        options.chain_id,
    )
    .await?;

    let entry = ChannelEntry {
        channel_id,
        salt,
        cumulative_amount: options.initial_amount,
        escrow_contract: options.escrow_contract,
        chain_id: options.chain_id,
        opened: true,
    };

    let payload = SessionCredentialPayload::Open {
        payload_type: "transaction".to_string(),
        channel_id: channel_id.to_string(),
        transaction: signed_tx_hex,
        authorized_signer: Some(authorized_signer.to_string()),
        cumulative_amount: options.initial_amount.to_string(),
        signature: alloy::hex::encode_prefixed(&voucher_sig),
    };

    Ok((entry, payload))
}

/// On-chain channel state returned by the escrow contract.
#[derive(Debug, Clone)]
pub struct OnChainChannel {
    pub payer: Address,
    pub payee: Address,
    pub token: Address,
    pub authorized_signer: Address,
    pub deposit: u128,
    pub settled: u128,
    pub close_requested_at: u64,
    pub finalized: bool,
}

/// Read on-chain channel state from the escrow contract.
pub async fn get_on_chain_channel<P: Provider<TempoNetwork>>(
    provider: &P,
    escrow_contract: Address,
    channel_id: B256,
) -> Result<OnChainChannel, MppError> {
    use alloy::sol;

    sol! {
        interface IEscrowRead {
            function getChannel(bytes32 channelId) external view returns (
                bool finalized,
                uint64 closeRequestedAt,
                address payer,
                address payee,
                address token,
                address authorizedSigner,
                uint128 deposit,
                uint128 settled
            );
        }
    }

    let call_data = IEscrowRead::getChannelCall::new((channel_id,)).abi_encode();

    use tempo_alloy::rpc::TempoTransactionRequest;

    let mut tx_req = TempoTransactionRequest::default();
    tx_req.inner =
        tx_req
            .inner
            .to(escrow_contract)
            .input(alloy::rpc::types::TransactionInput::new(Bytes::from(
                call_data,
            )));

    let result = provider
        .call(tx_req)
        .await
        .mpp_http("failed to read channel")?;

    let decoded =
        <(bool, u64, Address, Address, Address, Address, u128, u128)>::abi_decode(&result)
            .mpp_http("failed to decode channel data")?;

    Ok(OnChainChannel {
        finalized: decoded.0,
        close_requested_at: decoded.1,
        payer: decoded.2,
        payee: decoded.3,
        token: decoded.4,
        authorized_signer: decoded.5,
        deposit: decoded.6,
        settled: decoded.7,
    })
}

/// Attempt to recover an existing on-chain channel.
///
/// If the channel has a positive deposit and is not finalized, returns a
/// [`ChannelEntry`] with `cumulative_amount` set to the on-chain settled
/// amount (the safe starting point for new vouchers).
///
/// Returns `None` if the channel doesn't exist, has zero deposit,
/// or is already finalized.
pub async fn try_recover_channel<P: Provider<TempoNetwork>>(
    provider: &P,
    escrow_contract: Address,
    channel_id: B256,
    chain_id: u64,
) -> Option<ChannelEntry> {
    let on_chain = get_on_chain_channel(provider, escrow_contract, channel_id)
        .await
        .ok()?;

    if on_chain.deposit > 0 && !on_chain.finalized {
        Some(ChannelEntry {
            channel_id,
            salt: B256::ZERO,
            cumulative_amount: on_chain.settled,
            escrow_contract,
            chain_id,
            opened: true,
        })
    } else {
        None
    }
}

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

    #[test]
    fn test_default_escrow_contract() {
        assert!(default_escrow_contract(4217).is_some());
        assert!(default_escrow_contract(42431).is_some());
        assert!(default_escrow_contract(1).is_none());
    }

    #[test]
    fn test_channel_entry_clone() {
        let entry = ChannelEntry {
            channel_id: B256::ZERO,
            salt: B256::ZERO,
            cumulative_amount: 1000,
            escrow_contract: Address::ZERO,
            chain_id: 42431,
            opened: true,
        };
        let cloned = entry.clone();
        assert_eq!(cloned.cumulative_amount, 1000);
        assert!(cloned.opened);
    }

    #[test]
    fn test_resolve_escrow_from_override() {
        use crate::protocol::core::{Base64UrlJson, PaymentChallenge};

        let challenge = PaymentChallenge {
            id: "test".to_string(),
            realm: "test".to_string(),
            method: "tempo".into(),
            intent: "session".into(),
            request: Base64UrlJson::from_value(&serde_json::json!({
                "amount": "1000",
                "unitType": "second",
                "currency": "0x123"
            }))
            .unwrap(),
            expires: None,
            description: None,
            digest: None,
            opaque: None,
        };

        let override_addr: Address = "0x1111111111111111111111111111111111111111"
            .parse()
            .unwrap();
        let result = resolve_escrow(&challenge, 42431, Some(override_addr)).unwrap();
        assert_eq!(result, override_addr);
    }

    #[test]
    fn test_resolve_escrow_from_default() {
        use crate::protocol::core::{Base64UrlJson, PaymentChallenge};

        let challenge = PaymentChallenge {
            id: "test".to_string(),
            realm: "test".to_string(),
            method: "tempo".into(),
            intent: "session".into(),
            request: Base64UrlJson::from_value(&serde_json::json!({
                "amount": "1000",
                "unitType": "second",
                "currency": "0x123"
            }))
            .unwrap(),
            expires: None,
            description: None,
            digest: None,
            opaque: None,
        };

        let result = resolve_escrow(&challenge, 42431, None).unwrap();
        assert_eq!(result, default_escrow_contract(42431).unwrap());
    }

    #[test]
    fn test_resolve_escrow_from_challenge() {
        use crate::protocol::core::{Base64UrlJson, PaymentChallenge};

        let escrow_addr = "0x2222222222222222222222222222222222222222";
        let challenge = PaymentChallenge {
            id: "test".to_string(),
            realm: "test".to_string(),
            method: "tempo".into(),
            intent: "session".into(),
            request: Base64UrlJson::from_value(&serde_json::json!({
                "amount": "1000",
                "unitType": "second",
                "currency": "0x123",
                "methodDetails": {
                    "escrowContract": escrow_addr
                }
            }))
            .unwrap(),
            expires: None,
            description: None,
            digest: None,
            opaque: None,
        };

        let result = resolve_escrow(&challenge, 42431, None).unwrap();
        assert_eq!(result, escrow_addr.parse::<Address>().unwrap());
    }

    #[test]
    fn test_resolve_escrow_no_source() {
        use crate::protocol::core::{Base64UrlJson, PaymentChallenge};

        let challenge = PaymentChallenge {
            id: "test".to_string(),
            realm: "test".to_string(),
            method: "tempo".into(),
            intent: "session".into(),
            request: Base64UrlJson::from_value(&serde_json::json!({
                "amount": "1000",
                "unitType": "second",
                "currency": "0x123"
            }))
            .unwrap(),
            expires: None,
            description: None,
            digest: None,
            opaque: None,
        };

        let result = resolve_escrow(&challenge, 9999, None);
        assert!(result.is_err());
    }

    #[test]
    fn test_build_credential() {
        use crate::protocol::core::{Base64UrlJson, PaymentChallenge};

        let challenge = PaymentChallenge {
            id: "test-id".to_string(),
            realm: "api.example.com".to_string(),
            method: "tempo".into(),
            intent: "session".into(),
            request: Base64UrlJson::from_value(&serde_json::json!({
                "amount": "1000",
                "unitType": "second",
                "currency": "0x123"
            }))
            .unwrap(),
            expires: None,
            description: None,
            digest: None,
            opaque: None,
        };

        let payload = SessionCredentialPayload::Voucher {
            channel_id: "0xabc".to_string(),
            cumulative_amount: "5000".to_string(),
            signature: "0xdef".to_string(),
        };

        let addr: Address = "0x1111111111111111111111111111111111111111"
            .parse()
            .unwrap();
        let cred = build_credential(&challenge, payload, 42431, addr);
        assert!(cred.source.is_some());
        assert!(cred.source.unwrap().contains("42431"));
    }

    #[cfg(feature = "evm")]
    #[tokio::test]
    async fn test_create_voucher_payload() {
        use alloy::signers::local::PrivateKeySigner;

        let signer = PrivateKeySigner::random();
        let channel_id = B256::repeat_byte(0xAB);
        let escrow: Address = "0x5555555555555555555555555555555555555555"
            .parse()
            .unwrap();

        let payload = create_voucher_payload(&signer, channel_id, 1000, escrow, 42431)
            .await
            .unwrap();

        match payload {
            SessionCredentialPayload::Voucher {
                channel_id: cid,
                cumulative_amount,
                signature,
            } => {
                assert!(cid.starts_with("0x"));
                assert_eq!(cumulative_amount, "1000");
                assert!(signature.starts_with("0x"));
            }
            _ => panic!("Expected Voucher variant"),
        }
    }

    #[cfg(feature = "evm")]
    #[tokio::test]
    async fn test_create_close_payload() {
        use alloy::signers::local::PrivateKeySigner;

        let signer = PrivateKeySigner::random();
        let channel_id = B256::repeat_byte(0xCD);
        let escrow: Address = "0x5555555555555555555555555555555555555555"
            .parse()
            .unwrap();

        let payload = create_close_payload(&signer, channel_id, 2000, escrow, 42431)
            .await
            .unwrap();

        match payload {
            SessionCredentialPayload::Close {
                channel_id: cid,
                cumulative_amount,
                signature,
            } => {
                assert!(cid.starts_with("0x"));
                assert_eq!(cumulative_amount, "2000");
                assert!(signature.starts_with("0x"));
            }
            _ => panic!("Expected Close variant"),
        }
    }

    #[test]
    fn test_resolve_chain_id_from_challenge() {
        use crate::protocol::core::{Base64UrlJson, PaymentChallenge};

        let challenge = PaymentChallenge {
            id: "test".to_string(),
            realm: "test".to_string(),
            method: "tempo".into(),
            intent: "session".into(),
            request: Base64UrlJson::from_value(&serde_json::json!({
                "amount": "1000",
                "unitType": "second",
                "currency": "0x123",
                "methodDetails": { "escrowContract": "0xabc", "chainId": 4217 }
            }))
            .unwrap(),
            expires: None,
            description: None,
            digest: None,
            opaque: None,
        };

        assert_eq!(resolve_chain_id(&challenge), 4217);
    }

    #[test]
    fn test_resolve_chain_id_default() {
        use crate::protocol::core::{Base64UrlJson, PaymentChallenge};

        let challenge = PaymentChallenge {
            id: "test".to_string(),
            realm: "test".to_string(),
            method: "tempo".into(),
            intent: "session".into(),
            request: Base64UrlJson::from_value(&serde_json::json!({
                "amount": "1000",
                "unitType": "second",
                "currency": "0x123"
            }))
            .unwrap(),
            expires: None,
            description: None,
            digest: None,
            opaque: None,
        };

        assert_eq!(resolve_chain_id(&challenge), MODERATO_CHAIN_ID);
    }

    #[test]
    fn test_resolve_chain_id_malformed_request_falls_back() {
        use crate::protocol::core::{Base64UrlJson, PaymentChallenge};

        let challenge = PaymentChallenge {
            id: "test".to_string(),
            realm: "test".to_string(),
            method: "tempo".into(),
            intent: "session".into(),
            request: Base64UrlJson::from_value(&serde_json::json!({
                "not_a_valid_field": true
            }))
            .unwrap(),
            expires: None,
            description: None,
            digest: None,
            opaque: None,
        };

        // Should fall back to MODERATO_CHAIN_ID on decode failure
        assert_eq!(resolve_chain_id(&challenge), MODERATO_CHAIN_ID);
    }

    #[test]
    fn test_resolve_escrow_challenge_has_invalid_address() {
        use crate::protocol::core::{Base64UrlJson, PaymentChallenge};

        // escrowContract present but not a valid address
        let challenge = PaymentChallenge {
            id: "test".to_string(),
            realm: "test".to_string(),
            method: "tempo".into(),
            intent: "session".into(),
            request: Base64UrlJson::from_value(&serde_json::json!({
                "amount": "1000",
                "unitType": "second",
                "currency": "0x123",
                "methodDetails": {
                    "escrowContract": "not-an-address"
                }
            }))
            .unwrap(),
            expires: None,
            description: None,
            digest: None,
            opaque: None,
        };

        // Invalid address in challenge should fall back to default
        let result = resolve_escrow(&challenge, 42431, None).unwrap();
        assert_eq!(result, default_escrow_contract(42431).unwrap());
    }

    #[test]
    fn test_resolve_escrow_override_takes_precedence_over_default() {
        use crate::protocol::core::{Base64UrlJson, PaymentChallenge};

        let challenge = PaymentChallenge {
            id: "test".to_string(),
            realm: "test".to_string(),
            method: "tempo".into(),
            intent: "session".into(),
            request: Base64UrlJson::from_value(&serde_json::json!({
                "amount": "1000",
                "unitType": "second",
                "currency": "0x123"
            }))
            .unwrap(),
            expires: None,
            description: None,
            digest: None,
            opaque: None,
        };

        let override_addr: Address = "0x3333333333333333333333333333333333333333"
            .parse()
            .unwrap();
        let result = resolve_escrow(&challenge, 42431, Some(override_addr)).unwrap();
        assert_eq!(
            result, override_addr,
            "override should take precedence over default"
        );
        assert_ne!(result, default_escrow_contract(42431).unwrap());
    }

    #[test]
    fn test_default_escrow_contract_known_chains() {
        let mainnet = default_escrow_contract(4217).unwrap();
        assert_eq!(
            mainnet,
            "0x33b901018174DDabE4841042ab76ba85D4e24f25"
                .parse::<Address>()
                .unwrap()
        );

        let moderato = default_escrow_contract(42431).unwrap();
        assert_eq!(
            moderato,
            "0xe1c4d3dce17bc111181ddf716f75bae49e61a336"
                .parse::<Address>()
                .unwrap()
        );
    }

    #[test]
    fn test_default_escrow_contract_unknown_chain() {
        assert!(default_escrow_contract(0).is_none());
        assert!(default_escrow_contract(999999).is_none());
    }

    #[test]
    fn test_build_credential_did_format() {
        use crate::protocol::core::{Base64UrlJson, PaymentChallenge};

        let challenge = PaymentChallenge {
            id: "test-id".to_string(),
            realm: "api.example.com".to_string(),
            method: "tempo".into(),
            intent: "session".into(),
            request: Base64UrlJson::from_value(&serde_json::json!({
                "amount": "1000",
                "unitType": "second",
                "currency": "0x123"
            }))
            .unwrap(),
            expires: None,
            description: None,
            digest: None,
            opaque: None,
        };

        let payload = SessionCredentialPayload::Voucher {
            channel_id: "0xabc".to_string(),
            cumulative_amount: "5000".to_string(),
            signature: "0xdef".to_string(),
        };

        let addr: Address = "0x1111111111111111111111111111111111111111"
            .parse()
            .unwrap();
        let cred = build_credential(&challenge, payload, 4217, addr);
        let did = cred.source.as_ref().unwrap();
        let expected = format!("did:pkh:eip155:4217:{}", addr);
        assert_eq!(did, &expected, "DID should match exact pkh format");
    }

    #[cfg(feature = "evm")]
    #[tokio::test]
    async fn test_create_voucher_payload_zero_amount() {
        use alloy::signers::local::PrivateKeySigner;

        let signer = PrivateKeySigner::random();
        let channel_id = B256::repeat_byte(0xAB);
        let escrow: Address = "0x5555555555555555555555555555555555555555"
            .parse()
            .unwrap();

        let payload = create_voucher_payload(&signer, channel_id, 0, escrow, 42431)
            .await
            .unwrap();

        match payload {
            SessionCredentialPayload::Voucher {
                cumulative_amount, ..
            } => {
                assert_eq!(cumulative_amount, "0");
            }
            _ => panic!("Expected Voucher variant"),
        }
    }

    #[cfg(feature = "evm")]
    #[tokio::test]
    async fn test_create_close_payload_zero_amount() {
        use alloy::signers::local::PrivateKeySigner;

        let signer = PrivateKeySigner::random();
        let channel_id = B256::repeat_byte(0xCD);
        let escrow: Address = "0x5555555555555555555555555555555555555555"
            .parse()
            .unwrap();

        let payload = create_close_payload(&signer, channel_id, 0, escrow, 42431)
            .await
            .unwrap();

        match payload {
            SessionCredentialPayload::Close {
                cumulative_amount, ..
            } => {
                assert_eq!(cumulative_amount, "0");
            }
            _ => panic!("Expected Close variant"),
        }
    }

    #[cfg(feature = "evm")]
    #[tokio::test]
    async fn test_create_voucher_payload_large_amount() {
        use alloy::signers::local::PrivateKeySigner;

        let signer = PrivateKeySigner::random();
        let channel_id = B256::repeat_byte(0xAB);
        let escrow: Address = "0x5555555555555555555555555555555555555555"
            .parse()
            .unwrap();

        let large_amount = u128::MAX;
        let payload = create_voucher_payload(&signer, channel_id, large_amount, escrow, 42431)
            .await
            .unwrap();

        match payload {
            SessionCredentialPayload::Voucher {
                cumulative_amount, ..
            } => {
                assert_eq!(cumulative_amount, u128::MAX.to_string());
            }
            _ => panic!("Expected Voucher variant"),
        }
    }

    #[test]
    fn test_channel_entry_debug() {
        let entry = ChannelEntry {
            channel_id: B256::ZERO,
            salt: B256::ZERO,
            cumulative_amount: 0,
            escrow_contract: Address::ZERO,
            chain_id: 42431,
            opened: false,
        };
        let debug = format!("{:?}", entry);
        assert!(debug.contains("ChannelEntry"));
        assert!(debug.contains("42431"));
    }

    #[test]
    fn test_resolve_escrow_challenge_priority_order() {
        use crate::protocol::core::{Base64UrlJson, PaymentChallenge};

        // Challenge has a valid escrow, override is also present.
        // Challenge should take priority.
        let escrow_addr = "0x2222222222222222222222222222222222222222";
        let override_addr: Address = "0x3333333333333333333333333333333333333333"
            .parse()
            .unwrap();
        let challenge = PaymentChallenge {
            id: "test".to_string(),
            realm: "test".to_string(),
            method: "tempo".into(),
            intent: "session".into(),
            request: Base64UrlJson::from_value(&serde_json::json!({
                "amount": "1000",
                "unitType": "second",
                "currency": "0x123",
                "methodDetails": {
                    "escrowContract": escrow_addr
                }
            }))
            .unwrap(),
            expires: None,
            description: None,
            digest: None,
            opaque: None,
        };

        let result = resolve_escrow(&challenge, 42431, Some(override_addr)).unwrap();
        assert_eq!(
            result,
            escrow_addr.parse::<Address>().unwrap(),
            "challenge escrow should take priority over override"
        );
    }
}