mpp 0.12.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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
//! 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::consensus::SignableTransaction;
use alloy::primitives::{keccak256, Address, Bytes, TxKind, Uint, B256, U256};
use alloy::providers::Provider;
use alloy::signers::Signer;
use alloy::sol_types::{SolCall, SolValue};
use tempo_alloy::contracts::precompiles::{ITIP20ChannelReserve, TIP20_CHANNEL_RESERVE_ADDRESS};
use tempo_alloy::primitives::transaction::{Call, SignatureType, TempoTransaction};
use tempo_alloy::rpc::TempoTransactionRequest;
use tempo_alloy::TempoNetwork;

use crate::client::tempo::charge::tx_builder::{build_tempo_tx, estimate_gas, TempoTxOptions};
use crate::error::{MppError, ResultExt};
use crate::protocol::core::{PaymentChallenge, PaymentCredential};
use crate::protocol::intents::SessionRequest;
use crate::protocol::methods::tempo::precompile_voucher::{
    compute_precompile_channel_id, compute_precompile_channel_id_with_escrow,
    sign_precompile_voucher, sign_precompile_voucher_primitive,
    sign_precompile_voucher_primitive_with_escrow, sign_precompile_voucher_with_escrow,
    PRECOMPILE_MAX_CUMULATIVE_AMOUNT,
};
use crate::protocol::methods::tempo::session::{
    ChannelDescriptor, SessionCredentialPayload, TempoSessionExt,
};
use crate::protocol::methods::tempo::voucher::{compute_channel_id, sign_voucher};
use crate::protocol::methods::tempo::CHAIN_ID;

#[cfg(feature = "tempo")]
const EXPIRING_NONCE_VALID_BEFORE_SECS: u64 = 25;

/// 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,
    /// Latest known channel deposit.
    pub deposit: u128,
    /// Full TIP-1034 descriptor. Legacy contract channels do not have one.
    pub descriptor: Option<ChannelDescriptor>,
    /// Immutable machine-token settlement route, when enabled.
    pub settlement_route: Option<crate::protocol::methods::tempo::session::SettlementRoute>,
    /// 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(CHAIN_ID)
}

/// Resolve escrow contract address from an override, challenge hints, or defaults.
pub fn resolve_escrow(
    challenge: &PaymentChallenge,
    chain_id: u64,
    escrow_override: Option<Address>,
) -> Result<Address, MppError> {
    // Match MPPx: an explicit client override wins over server hints.
    if let Some(addr) = escrow_override {
        return Ok(addr);
    }

    if let Ok(req) = challenge.request.decode::<SessionRequest>() {
        if let Some(details) = req.method_details.as_ref() {
            for key in ["escrowContract", "escrow"] {
                if let Some(addr) = details
                    .get(key)
                    .and_then(serde_json::Value::as_str)
                    .and_then(|value| value.parse::<Address>().ok())
                {
                    return Ok(addr);
                }
            }
        }
        if req.is_tip1034_session() {
            return Ok(TIP20_CHANNEL_RESERVE_ADDRESS);
        }
    }

    // Legacy sessions retain their chain-specific escrow fallback.
    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(
    signer: &impl Signer,
    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(),
        descriptor: None,
        settlement_route: None,
        cumulative_amount: cumulative_amount.to_string(),
        signature: alloy::hex::encode_prefixed(&sig),
    })
}

/// Voucher payload for TIP-1034 precompile escrow (EIP-712 domain pinned to
/// `TIP20_CHANNEL_RESERVE_ADDRESS`).
#[cfg(feature = "tempo")]
pub async fn create_precompile_voucher_payload(
    signer: &impl Signer,
    channel_id: B256,
    cumulative_amount: u128,
    chain_id: u64,
) -> Result<SessionCredentialPayload, MppError> {
    let sig = sign_precompile_voucher(signer, channel_id, cumulative_amount, chain_id).await?;

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

/// Native primitive-signature version of [`create_precompile_voucher_payload`].
#[cfg(feature = "tempo")]
pub async fn create_precompile_voucher_payload_primitive(
    signer: &impl Signer<tempo_alloy::primitives::transaction::PrimitiveSignature>,
    channel_id: B256,
    cumulative_amount: u128,
    chain_id: u64,
) -> Result<SessionCredentialPayload, MppError> {
    let signature =
        sign_precompile_voucher_primitive(signer, channel_id, cumulative_amount, chain_id).await?;
    Ok(SessionCredentialPayload::Voucher {
        channel_id: channel_id.to_string(),
        descriptor: None,
        settlement_route: None,
        cumulative_amount: cumulative_amount.to_string(),
        signature: alloy::hex::encode_prefixed(&signature),
    })
}

/// Voucher payload for TIP-1034 with the descriptor required for recovery.
#[cfg(feature = "tempo")]
pub async fn create_precompile_voucher_payload_with_descriptor(
    signer: &impl Signer,
    descriptor: ChannelDescriptor,
    cumulative_amount: u128,
    chain_id: u64,
) -> Result<SessionCredentialPayload, MppError> {
    create_precompile_voucher_payload_with_descriptor_and_escrow(
        signer,
        descriptor,
        cumulative_amount,
        TIP20_CHANNEL_RESERVE_ADDRESS,
        chain_id,
    )
    .await
}

/// Native primitive-signature voucher payload with the descriptor required for recovery.
#[cfg(feature = "tempo")]
pub async fn create_precompile_voucher_payload_with_descriptor_primitive(
    signer: &impl Signer<tempo_alloy::primitives::transaction::PrimitiveSignature>,
    descriptor: ChannelDescriptor,
    cumulative_amount: u128,
    chain_id: u64,
) -> Result<SessionCredentialPayload, MppError> {
    let channel_id = compute_precompile_channel_id_from_descriptor_with_escrow(
        &descriptor,
        TIP20_CHANNEL_RESERVE_ADDRESS,
        chain_id,
    )?;
    let signature = sign_precompile_voucher_primitive_with_escrow(
        signer,
        channel_id,
        cumulative_amount,
        TIP20_CHANNEL_RESERVE_ADDRESS,
        chain_id,
    )
    .await?;

    Ok(SessionCredentialPayload::Voucher {
        channel_id: channel_id.to_string(),
        descriptor: Some(descriptor),
        settlement_route: None,
        cumulative_amount: cumulative_amount.to_string(),
        signature: alloy::hex::encode_prefixed(&signature),
    })
}

/// Voucher payload for TIP-1034 with an explicit escrow/precompile address.
#[cfg(feature = "tempo")]
pub async fn create_precompile_voucher_payload_with_descriptor_and_escrow(
    signer: &impl Signer,
    descriptor: ChannelDescriptor,
    cumulative_amount: u128,
    escrow_contract: Address,
    chain_id: u64,
) -> Result<SessionCredentialPayload, MppError> {
    let channel_id = compute_precompile_channel_id_from_descriptor_with_escrow(
        &descriptor,
        escrow_contract,
        chain_id,
    )?;
    let sig = sign_precompile_voucher_with_escrow(
        signer,
        channel_id,
        cumulative_amount,
        escrow_contract,
        chain_id,
    )
    .await?;

    Ok(SessionCredentialPayload::Voucher {
        channel_id: channel_id.to_string(),
        descriptor: Some(descriptor),
        settlement_route: None,
        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(
    signer: &impl Signer,
    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(),
        descriptor: None,
        settlement_route: None,
        cumulative_amount: cumulative_amount.to_string(),
        signature: alloy::hex::encode_prefixed(&sig),
    })
}

/// Close payload for TIP-1034 precompile escrow.
#[cfg(feature = "tempo")]
pub async fn create_precompile_close_payload(
    signer: &impl Signer,
    channel_id: B256,
    cumulative_amount: u128,
    chain_id: u64,
) -> Result<SessionCredentialPayload, MppError> {
    let sig = sign_precompile_voucher(signer, channel_id, cumulative_amount, chain_id).await?;

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

/// Native primitive-signature version of [`create_precompile_close_payload`].
#[cfg(feature = "tempo")]
pub async fn create_precompile_close_payload_primitive(
    signer: &impl Signer<tempo_alloy::primitives::transaction::PrimitiveSignature>,
    channel_id: B256,
    cumulative_amount: u128,
    chain_id: u64,
) -> Result<SessionCredentialPayload, MppError> {
    let signature =
        sign_precompile_voucher_primitive(signer, channel_id, cumulative_amount, chain_id).await?;
    Ok(SessionCredentialPayload::Close {
        channel_id: channel_id.to_string(),
        descriptor: None,
        settlement_route: None,
        cumulative_amount: cumulative_amount.to_string(),
        signature: alloy::hex::encode_prefixed(&signature),
    })
}

/// Close payload for TIP-1034 with the descriptor required for recovery.
#[cfg(feature = "tempo")]
pub async fn create_precompile_close_payload_with_descriptor(
    signer: &impl Signer,
    channel_id: B256,
    descriptor: ChannelDescriptor,
    cumulative_amount: u128,
    chain_id: u64,
) -> Result<SessionCredentialPayload, MppError> {
    create_precompile_close_payload_with_descriptor_and_escrow(
        signer,
        channel_id,
        descriptor,
        cumulative_amount,
        TIP20_CHANNEL_RESERVE_ADDRESS,
        chain_id,
    )
    .await
}

/// Native primitive-signature close payload with the descriptor required for recovery.
#[cfg(feature = "tempo")]
pub async fn create_precompile_close_payload_with_descriptor_primitive(
    signer: &impl Signer<tempo_alloy::primitives::transaction::PrimitiveSignature>,
    channel_id: B256,
    descriptor: ChannelDescriptor,
    cumulative_amount: u128,
    chain_id: u64,
) -> Result<SessionCredentialPayload, MppError> {
    let expected_channel_id = compute_precompile_channel_id_from_descriptor_with_escrow(
        &descriptor,
        TIP20_CHANNEL_RESERVE_ADDRESS,
        chain_id,
    )?;
    if expected_channel_id != channel_id {
        return Err(MppError::InvalidConfig(
            "TIP-1034 close descriptor does not match channel_id".to_string(),
        ));
    }

    let signature = sign_precompile_voucher_primitive_with_escrow(
        signer,
        channel_id,
        cumulative_amount,
        TIP20_CHANNEL_RESERVE_ADDRESS,
        chain_id,
    )
    .await?;

    Ok(SessionCredentialPayload::Close {
        channel_id: channel_id.to_string(),
        descriptor: Some(descriptor),
        settlement_route: None,
        cumulative_amount: cumulative_amount.to_string(),
        signature: alloy::hex::encode_prefixed(&signature),
    })
}

/// Close payload for TIP-1034 with a descriptor and explicit escrow/precompile verifier.
#[cfg(feature = "tempo")]
pub async fn create_precompile_close_payload_with_descriptor_and_escrow(
    signer: &impl Signer,
    channel_id: B256,
    descriptor: ChannelDescriptor,
    cumulative_amount: u128,
    escrow_contract: Address,
    chain_id: u64,
) -> Result<SessionCredentialPayload, MppError> {
    let expected_channel_id = compute_precompile_channel_id_from_descriptor_with_escrow(
        &descriptor,
        escrow_contract,
        chain_id,
    )?;
    if expected_channel_id != channel_id {
        return Err(MppError::InvalidConfig(
            "TIP-1034 close descriptor does not match channel_id".to_string(),
        ));
    }

    let sig = sign_precompile_voucher_with_escrow(
        signer,
        channel_id,
        cumulative_amount,
        escrow_contract,
        chain_id,
    )
    .await?;

    Ok(SessionCredentialPayload::Close {
        channel_id: channel_id.to_string(),
        descriptor: Some(descriptor),
        settlement_route: None,
        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 + Clone,
{
    use alloy::sol;
    use tempo_alloy::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 gas_price = provider
        .get_gas_price()
        .await
        .mpp_http("failed to get gas price")?;

    let (nonce, nonce_key, valid_before) = session_transaction_nonce_fields();

    let key_authorization = crate::client::tempo::signing::keychain::resolve_key_authorization(
        provider,
        signing_mode,
        signer.address(),
    )
    .await?;

    let tempo_tx = build_tempo_tx(TempoTxOptions {
        calls,
        chain_id: options.chain_id,
        fee_token: options.currency,
        nonce,
        nonce_key,
        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,
        key_authorization,
    });

    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,
        deposit: options.deposit,
        descriptor: None,
        settlement_route: None,
        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,
        descriptor: None,
        settlement_route: None,
        authorized_signer: Some(authorized_signer.to_string()),
        cumulative_amount: options.initial_amount.to_string(),
        signature: alloy::hex::encode_prefixed(&voucher_sig),
    };

    Ok((entry, payload))
}

/// Whether `addr` is the T5 TIP-1034 reserve channel precompile.
pub fn is_precompile_escrow(addr: Address) -> bool {
    addr == TIP20_CHANNEL_RESERVE_ADDRESS
}

/// Compute the precompile's `expiringNonceHash` =
/// `keccak256(encode_for_signing(unsigned_tx) || sender)`. Must be called
/// before signing; mutating `unsigned_tx` after invalidates the channel id.
#[cfg(feature = "tempo")]
pub fn compute_expiring_nonce_hash(unsigned_tx: &TempoTransaction, sender: Address) -> B256 {
    let mut buf = Vec::with_capacity(unsigned_tx.payload_len_for_signature() + 20);
    unsigned_tx.encode_for_signing(&mut buf);
    buf.extend_from_slice(sender.as_slice());
    keccak256(buf)
}

/// Compute `expiringNonceHash` for a fee-sponsored TIP-1034 channel open.
///
/// The sender signature is verified against the submitted transaction, but
/// TIP-1034 derives channel identity from the fee-payer hash preimage that
/// marks the transaction as sponsorable.
#[cfg(feature = "tempo")]
pub fn compute_fee_payer_expiring_nonce_hash(
    unsigned_tx: &TempoTransaction,
    sender: Address,
) -> B256 {
    let mut tx = unsigned_tx.clone();
    tx.fee_payer_signature = Some(alloy::primitives::Signature::new(
        U256::ZERO,
        U256::ZERO,
        false,
    ));
    compute_expiring_nonce_hash(&tx, sender)
}

/// Build the wire descriptor for a TIP-1034 precompile channel.
#[cfg(feature = "tempo")]
#[allow(clippy::too_many_arguments)]
pub fn build_channel_descriptor(
    payer: Address,
    payee: Address,
    operator: Address,
    token: Address,
    salt: B256,
    authorized_signer: Address,
    expiring_nonce_hash: B256,
) -> ChannelDescriptor {
    ChannelDescriptor {
        payer: payer.to_string(),
        payee: payee.to_string(),
        operator: operator.to_string(),
        token: token.to_string(),
        salt: salt.to_string(),
        authorized_signer: authorized_signer.to_string(),
        expiring_nonce_hash: expiring_nonce_hash.to_string(),
    }
}

#[cfg(feature = "tempo")]
fn parse_precompile_amount(value: u128, label: &str) -> Result<Uint<96, 2>, MppError> {
    if value > PRECOMPILE_MAX_CUMULATIVE_AMOUNT {
        return Err(MppError::InvalidConfig(format!(
            "{label} {value} exceeds precompile uint96 max"
        )));
    }
    Ok(Uint::<96, 2>::from(value))
}

#[cfg(feature = "tempo")]
fn session_transaction_nonce_fields() -> (u64, U256, Option<u64>) {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    (
        0,
        U256::MAX,
        Some(now.saturating_add(EXPIRING_NONCE_VALID_BEFORE_SECS)),
    )
}

/// Returns a random past timestamp for a repeatable transaction.
///
/// MPPx adds `validAfter` to top-ups so two otherwise identical expiring
/// transactions do not serialize to the same replay-protection hash.
#[cfg(feature = "tempo")]
fn random_past_valid_after() -> Option<std::num::NonZeroU64> {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    let latest = now.saturating_sub(60);
    if latest == 0 {
        return None;
    }

    let random = B256::random();
    let mut prefix = [0u8; 8];
    prefix.copy_from_slice(&random[..8]);
    let timestamp = (u64::from_be_bytes(prefix) % latest).max(1);
    std::num::NonZeroU64::new(timestamp)
}

#[cfg(feature = "tempo")]
fn session_estimation_request(
    options: &TempoTxOptions,
    valid_after: Option<std::num::NonZeroU64>,
    payer: Address,
    signer: Address,
    signature_type: SignatureType,
    keychain: bool,
) -> TempoTransactionRequest {
    let mut request = TempoTransactionRequest {
        calls: options.calls.clone(),
        key_authorization: options.key_authorization.clone(),
        valid_before: options.valid_before.and_then(std::num::NonZeroU64::new),
        valid_after,
        ..Default::default()
    }
    .with_fee_token(options.fee_token)
    .with_nonce_key(options.nonce_key);
    request.inner.from = Some(payer);
    request.inner.chain_id = Some(options.chain_id);
    request.inner.nonce = Some(options.nonce);
    request.inner.max_fee_per_gas = Some(options.max_fee_per_gas);
    request.inner.max_priority_fee_per_gas = Some(options.max_priority_fee_per_gas);
    request.key_type = Some(signature_type);
    if keychain {
        request.key_id = Some(signer);
    }
    request
}

/// Convert a JSON wire descriptor into the generated precompile ABI tuple.
#[cfg(feature = "tempo")]
pub fn precompile_descriptor_from_wire(
    descriptor: &ChannelDescriptor,
) -> Result<ITIP20ChannelReserve::ChannelDescriptor, MppError> {
    Ok(ITIP20ChannelReserve::ChannelDescriptor {
        payer: descriptor.payer.parse().map_err(|e| {
            MppError::InvalidConfig(format!("invalid TIP-1034 descriptor payer: {e}"))
        })?,
        payee: descriptor.payee.parse().map_err(|e| {
            MppError::InvalidConfig(format!("invalid TIP-1034 descriptor payee: {e}"))
        })?,
        operator: descriptor.operator.parse().map_err(|e| {
            MppError::InvalidConfig(format!("invalid TIP-1034 descriptor operator: {e}"))
        })?,
        token: descriptor.token.parse().map_err(|e| {
            MppError::InvalidConfig(format!("invalid TIP-1034 descriptor token: {e}"))
        })?,
        salt: descriptor.salt.parse().map_err(|e| {
            MppError::InvalidConfig(format!("invalid TIP-1034 descriptor salt: {e}"))
        })?,
        authorizedSigner: descriptor.authorized_signer.parse().map_err(|e| {
            MppError::InvalidConfig(format!("invalid TIP-1034 descriptor authorizedSigner: {e}"))
        })?,
        expiringNonceHash: descriptor.expiring_nonce_hash.parse().map_err(|e| {
            MppError::InvalidConfig(format!(
                "invalid TIP-1034 descriptor expiringNonceHash: {e}"
            ))
        })?,
    })
}

/// Compute a TIP-1034 channel ID from a wire descriptor.
#[cfg(feature = "tempo")]
pub fn compute_precompile_channel_id_from_descriptor(
    descriptor: &ChannelDescriptor,
    chain_id: u64,
) -> Result<B256, MppError> {
    compute_precompile_channel_id_from_descriptor_with_escrow(
        descriptor,
        TIP20_CHANNEL_RESERVE_ADDRESS,
        chain_id,
    )
}

/// Compute a TIP-1034 channel ID from a wire descriptor and explicit escrow.
#[cfg(feature = "tempo")]
pub fn compute_precompile_channel_id_from_descriptor_with_escrow(
    descriptor: &ChannelDescriptor,
    escrow_contract: Address,
    chain_id: u64,
) -> Result<B256, MppError> {
    let descriptor = precompile_descriptor_from_wire(descriptor)?;
    Ok(compute_precompile_channel_id_with_escrow(
        descriptor.payer,
        descriptor.payee,
        descriptor.operator,
        descriptor.token,
        descriptor.salt,
        descriptor.authorizedSigner,
        descriptor.expiringNonceHash,
        escrow_contract,
        chain_id,
    ))
}

/// ABI-encode `open(payee, operator, token, uint96 deposit, salt, authorizedSigner)`.
#[cfg(feature = "tempo")]
pub fn encode_precompile_open_call(
    payee: Address,
    operator: Address,
    token: Address,
    deposit: u128,
    salt: B256,
    authorized_signer: Address,
) -> Result<Bytes, MppError> {
    Ok(Bytes::from(
        ITIP20ChannelReserve::openCall::new((
            payee,
            operator,
            token,
            parse_precompile_amount(deposit, "deposit")?,
            salt,
            authorized_signer,
        ))
        .abi_encode(),
    ))
}

/// ABI-encode `topUp(descriptor, uint96 additionalDeposit)`.
#[cfg(feature = "tempo")]
pub fn encode_precompile_top_up_call(
    descriptor: &ChannelDescriptor,
    additional_deposit: u128,
) -> Result<Bytes, MppError> {
    Ok(Bytes::from(
        ITIP20ChannelReserve::topUpCall::new((
            precompile_descriptor_from_wire(descriptor)?,
            parse_precompile_amount(additional_deposit, "additional_deposit")?,
        ))
        .abi_encode(),
    ))
}

/// ABI-encode `getChannel(descriptor)`.
#[cfg(feature = "tempo")]
pub fn encode_precompile_get_channel_call(
    descriptor: &ChannelDescriptor,
) -> Result<Bytes, MppError> {
    Ok(Bytes::from(
        ITIP20ChannelReserve::getChannelCall::new((precompile_descriptor_from_wire(descriptor)?,))
            .abi_encode(),
    ))
}

/// ABI-encode `getChannelState(channelId)`.
#[cfg(feature = "tempo")]
pub fn encode_precompile_get_channel_state_call(channel_id: B256) -> Bytes {
    Bytes::from(ITIP20ChannelReserve::getChannelStateCall::new((channel_id,)).abi_encode())
}

/// ABI-encode `requestClose(descriptor)`.
#[cfg(feature = "tempo")]
pub fn encode_precompile_request_close_call(
    descriptor: &ChannelDescriptor,
) -> Result<Bytes, MppError> {
    Ok(Bytes::from(
        ITIP20ChannelReserve::requestCloseCall::new(
            (precompile_descriptor_from_wire(descriptor)?,),
        )
        .abi_encode(),
    ))
}

/// ABI-encode `withdraw(descriptor)`.
#[cfg(feature = "tempo")]
pub fn encode_precompile_withdraw_call(descriptor: &ChannelDescriptor) -> Result<Bytes, MppError> {
    Ok(Bytes::from(
        ITIP20ChannelReserve::withdrawCall::new((precompile_descriptor_from_wire(descriptor)?,))
            .abi_encode(),
    ))
}

/// Build a descriptor-backed TIP-1034 top-up credential payload.
#[cfg(feature = "tempo")]
pub fn create_precompile_top_up_payload(
    channel_id: B256,
    descriptor: ChannelDescriptor,
    transaction: String,
    additional_deposit: u128,
) -> SessionCredentialPayload {
    SessionCredentialPayload::TopUp {
        payload_type: "transaction".to_string(),
        channel_id: channel_id.to_string(),
        transaction,
        descriptor: Some(descriptor),
        settlement_route: None,
        additional_deposit: additional_deposit.to_string(),
    }
}

/// Options for [`create_precompile_open_payload`]. Replaces `escrow_contract`
/// (always the precompile) with `operator`. `deposit` and `initial_amount`
/// must fit `uint96`.
pub struct OpenPrecompilePayloadOptions {
    /// Calls executed atomically before the channel open.
    pub prefix_calls: Vec<Call>,
    /// Optional relayer for `settle`/`close`; `Address::ZERO` = payee-only.
    pub operator: Address,
    /// Voucher signer; defaults to `payer` if `None`.
    pub authorized_signer: Option<Address>,
    pub payee: Address,
    pub currency: Address,
    /// Token used to pay gas when the open is not sponsored.
    pub fee_token: Address,
    pub deposit: u128,
    pub initial_amount: u128,
    pub chain_id: u64,
    pub fee_payer: bool,
    /// Descriptor salt override used to bind settlement route metadata.
    pub salt: Option<B256>,
}

/// Options for a descriptor-backed TIP-1034 top-up transaction.
pub struct TopUpPrecompilePayloadOptions<'a> {
    /// Calls executed atomically before the channel top-up.
    pub prefix_calls: Vec<Call>,
    /// Existing channel descriptor.
    pub descriptor: &'a ChannelDescriptor,
    /// Token used to pay gas when the top-up is not sponsored.
    pub fee_token: Address,
    /// Amount added to the existing channel deposit.
    pub additional_deposit: u128,
    /// Tempo chain ID.
    pub chain_id: u64,
    /// Whether the server may sponsor this management transaction.
    pub fee_payer: bool,
}

/// Open payload targeting the TIP-1034 reserve precompile. The escrow open
/// itself needs no approval because the precompile is on the TIP-1035 implicit
/// approvals list; optional prefix calls may acquire the deposit currency.
/// Channel id is derived against the complete unsigned tx's `expiringNonceHash`.
#[cfg(feature = "tempo")]
pub async fn create_precompile_open_payload<P, S>(
    provider: &P,
    signer: &S,
    signing_mode: Option<&crate::client::tempo::signing::TempoSigningMode>,
    payer: Address,
    options: OpenPrecompilePayloadOptions,
) -> Result<(ChannelEntry, SessionCredentialPayload), MppError>
where
    P: Provider<TempoNetwork>,
    S: Clone + Into<crate::client::tempo::signing::TempoPrimitiveSigner>,
{
    if options.deposit > PRECOMPILE_MAX_CUMULATIVE_AMOUNT {
        return Err(MppError::InvalidConfig(format!(
            "deposit {} exceeds precompile uint96 max",
            options.deposit
        )));
    }
    if options.initial_amount > PRECOMPILE_MAX_CUMULATIVE_AMOUNT {
        return Err(MppError::InvalidConfig(format!(
            "initial_amount {} exceeds precompile uint96 max",
            options.initial_amount
        )));
    }

    let default_mode = crate::client::tempo::signing::TempoSigningMode::Direct;
    let signing_mode = signing_mode.unwrap_or(&default_mode);
    let primitive_signer = signer.clone().into();
    let signature_type = primitive_signer.signature_type();

    let authorized_signer = options.authorized_signer.unwrap_or(payer);
    let salt = options.salt.unwrap_or_else(B256::random);

    let open_data = ITIP20ChannelReserve::openCall::new((
        options.payee,
        options.operator,
        options.currency,
        Uint::<96, 2>::from(options.deposit),
        salt,
        authorized_signer,
    ))
    .abi_encode();

    let mut calls = options.prefix_calls;
    calls.push(Call {
        to: TxKind::Call(TIP20_CHANNEL_RESERVE_ADDRESS),
        value: U256::ZERO,
        input: Bytes::from(open_data),
    });

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

    let (nonce, nonce_key, valid_before) = session_transaction_nonce_fields();

    let key_authorization = crate::client::tempo::signing::keychain::resolve_key_authorization(
        provider,
        signing_mode,
        primitive_signer.address(),
    )
    .await?;

    let mut transaction_options = TempoTxOptions {
        calls,
        chain_id: options.chain_id,
        fee_token: options.fee_token,
        nonce,
        nonce_key,
        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,
        key_authorization,
    };
    if !options.fee_payer {
        let request = session_estimation_request(
            &transaction_options,
            None,
            payer,
            primitive_signer.address(),
            signature_type,
            matches!(
                signing_mode,
                crate::client::tempo::signing::TempoSigningMode::Keychain { .. }
            ),
        );
        transaction_options.gas_limit = estimate_gas(provider, request).await?;
    }
    let unsigned_tx = build_tempo_tx(transaction_options);
    // Derive id from the unsigned tx before signing; expiringNonceHash binds
    // the signing-payload bytes.
    let expiring_nonce_hash = if options.fee_payer {
        compute_fee_payer_expiring_nonce_hash(&unsigned_tx, payer)
    } else {
        compute_expiring_nonce_hash(&unsigned_tx, payer)
    };
    let descriptor = build_channel_descriptor(
        payer,
        options.payee,
        options.operator,
        options.currency,
        salt,
        authorized_signer,
        expiring_nonce_hash,
    );
    let channel_id = compute_precompile_channel_id(
        payer,
        options.payee,
        options.operator,
        options.currency,
        salt,
        authorized_signer,
        expiring_nonce_hash,
        options.chain_id,
    );

    let tx_bytes = if options.fee_payer {
        crate::client::tempo::signing::sign_and_encode_fee_payer_envelope_primitive_async(
            unsigned_tx,
            &primitive_signer,
            signing_mode,
        )
        .await?
    } else {
        crate::client::tempo::signing::sign_and_encode_primitive_async(
            unsigned_tx,
            &primitive_signer,
            signing_mode,
        )
        .await?
    };
    let signed_tx_hex = alloy::hex::encode_prefixed(&tx_bytes);

    let voucher_sig = sign_precompile_voucher_primitive(
        &primitive_signer,
        channel_id,
        options.initial_amount,
        options.chain_id,
    )
    .await?;

    let entry = ChannelEntry {
        channel_id,
        salt,
        cumulative_amount: options.initial_amount,
        deposit: options.deposit,
        descriptor: Some(descriptor.clone()),
        settlement_route: None,
        escrow_contract: TIP20_CHANNEL_RESERVE_ADDRESS,
        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,
        descriptor: Some(descriptor),
        settlement_route: None,
        authorized_signer: Some(authorized_signer.to_string()),
        cumulative_amount: options.initial_amount.to_string(),
        signature: alloy::hex::encode_prefixed(&voucher_sig),
    };

    Ok((entry, payload))
}

/// Prepare and sign a descriptor-backed TIP-1034 top-up transaction.
///
/// This mirrors MPPx's `createTopUpPayload`: the returned transaction is sent
/// to the MPP server as a management credential, and the server broadcasts it
/// before accepting a voucher that requires the additional headroom.
#[cfg(feature = "tempo")]
pub async fn create_precompile_top_up_transaction_payload<P, S>(
    provider: &P,
    signer: &S,
    signing_mode: Option<&crate::client::tempo::signing::TempoSigningMode>,
    payer: Address,
    options: TopUpPrecompilePayloadOptions<'_>,
) -> Result<SessionCredentialPayload, MppError>
where
    P: Provider<TempoNetwork>,
    S: Clone + Into<crate::client::tempo::signing::TempoPrimitiveSigner>,
{
    let additional_deposit =
        parse_precompile_amount(options.additional_deposit, "additional_deposit")?;
    if additional_deposit.is_zero() {
        return Err(MppError::InvalidConfig(
            "top-up amount must be greater than zero".into(),
        ));
    }

    let default_mode = crate::client::tempo::signing::TempoSigningMode::Direct;
    let signing_mode = signing_mode.unwrap_or(&default_mode);
    let primitive_signer = signer.clone().into();
    let signature_type = primitive_signer.signature_type();
    let descriptor = precompile_descriptor_from_wire(options.descriptor)?;
    let mut calls = options.prefix_calls;
    calls.push(Call {
        to: TxKind::Call(TIP20_CHANNEL_RESERVE_ADDRESS),
        value: U256::ZERO,
        input: Bytes::from(
            ITIP20ChannelReserve::topUpCall::new((descriptor, additional_deposit)).abi_encode(),
        ),
    });
    let gas_price = provider
        .get_gas_price()
        .await
        .mpp_http("failed to get gas price")?;
    let (nonce, nonce_key, valid_before) = session_transaction_nonce_fields();

    let key_authorization = crate::client::tempo::signing::keychain::resolve_key_authorization(
        provider,
        signing_mode,
        primitive_signer.address(),
    )
    .await?;
    let valid_after = random_past_valid_after();
    let mut transaction_options = TempoTxOptions {
        calls,
        chain_id: options.chain_id,
        fee_token: options.fee_token,
        nonce,
        nonce_key,
        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,
        key_authorization,
    };
    if !options.fee_payer {
        let request = session_estimation_request(
            &transaction_options,
            valid_after,
            payer,
            primitive_signer.address(),
            signature_type,
            matches!(
                signing_mode,
                crate::client::tempo::signing::TempoSigningMode::Keychain { .. }
            ),
        );
        transaction_options.gas_limit = estimate_gas(provider, request).await?;
    }
    let mut unsigned_tx = build_tempo_tx(transaction_options);
    unsigned_tx.valid_after = valid_after;
    let tx_bytes = if options.fee_payer {
        crate::client::tempo::signing::sign_and_encode_fee_payer_envelope_primitive_async(
            unsigned_tx,
            &primitive_signer,
            signing_mode,
        )
        .await?
    } else {
        crate::client::tempo::signing::sign_and_encode_primitive_async(
            unsigned_tx,
            &primitive_signer,
            signing_mode,
        )
        .await?
    };
    let channel_id =
        compute_precompile_channel_id_from_descriptor(options.descriptor, options.chain_id)?;
    Ok(create_precompile_top_up_payload(
        channel_id,
        options.descriptor.clone(),
        alloy::hex::encode_prefixed(&tx_bytes),
        options.additional_deposit,
    ))
}

/// 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, is not finalized, is not pending
/// close, matches the expected payer, payee, token, and authorized signer,
/// 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,
/// is already finalized, is pending close, or doesn't match the expected
/// payer/payee/token/authorized signer.
#[allow(clippy::too_many_arguments)]
pub async fn try_recover_channel<P: Provider<TempoNetwork>>(
    provider: &P,
    escrow_contract: Address,
    channel_id: B256,
    chain_id: u64,
    expected_payer: Address,
    expected_payee: Address,
    expected_token: Address,
    expected_authorized_signer: Address,
) -> Option<ChannelEntry> {
    let on_chain = get_on_chain_channel(provider, escrow_contract, channel_id)
        .await
        .ok()?;

    let actual_authorized_signer = if on_chain.authorized_signer == Address::ZERO {
        on_chain.payer
    } else {
        on_chain.authorized_signer
    };

    if on_chain.deposit > 0
        && !on_chain.finalized
        && on_chain.close_requested_at == 0
        && on_chain.payer == expected_payer
        && on_chain.payee == expected_payee
        && on_chain.token == expected_token
        && actual_authorized_signer == expected_authorized_signer
    {
        Some(ChannelEntry {
            channel_id,
            salt: B256::ZERO,
            cumulative_amount: on_chain.settled,
            deposit: on_chain.deposit,
            descriptor: None,
            settlement_route: None,
            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());
    }

    #[cfg(feature = "tempo")]
    #[test]
    fn test_is_precompile_escrow() {
        use tempo_alloy::contracts::precompiles::TIP20_CHANNEL_RESERVE_ADDRESS;
        assert!(is_precompile_escrow(TIP20_CHANNEL_RESERVE_ADDRESS));
        assert!(is_precompile_escrow(
            "0x4D50500000000000000000000000000000000000"
                .parse()
                .unwrap()
        ));
        assert!(!is_precompile_escrow(
            default_escrow_contract(4217).unwrap()
        ));
        assert!(!is_precompile_escrow(
            default_escrow_contract(42431).unwrap()
        ));
        assert!(!is_precompile_escrow(Address::ZERO));
    }

    #[cfg(feature = "tempo")]
    #[test]
    fn test_compute_expiring_nonce_hash_matches_on_chain_formula() {
        // Mirrors tempo `unique_tx_identifier_from_signable`
        // (crates/primitives/src/transaction/mod.rs L37-L45).
        use alloy::consensus::SignableTransaction;
        use alloy::primitives::keccak256;
        use tempo_alloy::primitives::transaction::TempoTransaction;

        let payer = Address::repeat_byte(0xAA);
        let calls = vec![tempo_alloy::primitives::transaction::Call {
            to: TxKind::Call(Address::repeat_byte(0x11)),
            value: U256::ZERO,
            input: alloy::primitives::Bytes::new(),
        }];

        let tx: TempoTransaction = build_tempo_tx(TempoTxOptions {
            calls,
            chain_id: 4217,
            fee_token: Address::repeat_byte(0x22),
            nonce: 7,
            nonce_key: U256::ZERO,
            gas_limit: 500_000,
            max_fee_per_gas: 1_000_000_000,
            max_priority_fee_per_gas: 100_000_000,
            fee_payer: false,
            valid_before: None,
            key_authorization: None,
        });

        let got = compute_expiring_nonce_hash(&tx, payer);

        let mut expected_buf = Vec::with_capacity(tx.payload_len_for_signature() + 20);
        tx.encode_for_signing(&mut expected_buf);
        expected_buf.extend_from_slice(payer.as_slice());
        assert_eq!(got, keccak256(expected_buf));

        let other_sender = Address::repeat_byte(0xBB);
        assert_ne!(compute_expiring_nonce_hash(&tx, other_sender), got);
    }

    #[cfg(feature = "tempo")]
    #[test]
    fn session_transactions_use_expiring_nonces_without_sponsorship() {
        let before = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let (nonce, nonce_key, valid_before) = session_transaction_nonce_fields();

        assert_eq!(nonce, 0);
        assert_eq!(nonce_key, U256::MAX);
        let valid_before = valid_before.expect("session transaction sets valid_before");
        assert!(valid_before >= before);
        assert!(valid_before <= before + EXPIRING_NONCE_VALID_BEFORE_SECS + 1);
    }

    #[cfg(feature = "tempo")]
    #[test]
    fn repeatable_top_ups_get_past_valid_after_entropy() {
        let mut transaction = build_tempo_tx(TempoTxOptions {
            calls: vec![],
            chain_id: 4217,
            fee_token: Address::repeat_byte(0x22),
            nonce: 0,
            nonce_key: U256::MAX,
            gas_limit: 500_000,
            max_fee_per_gas: 1_000_000_000,
            max_priority_fee_per_gas: 100_000_000,
            fee_payer: false,
            valid_before: None,
            key_authorization: None,
        });
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        transaction.valid_after = random_past_valid_after();
        let valid_after = transaction
            .valid_after
            .expect("top-ups get transaction entropy");

        assert!(valid_after.get() <= now.saturating_sub(60));
    }

    #[cfg(feature = "tempo")]
    #[tokio::test]
    async fn test_create_precompile_open_payload_rejects_uint96_overflow() {
        use crate::protocol::methods::tempo::precompile_voucher::PRECOMPILE_MAX_CUMULATIVE_AMOUNT;
        use alloy::providers::ProviderBuilder;
        use alloy::signers::local::PrivateKeySigner;

        let signer = PrivateKeySigner::random();
        let payer = signer.address();
        // Validation runs before any network IO.
        let provider = ProviderBuilder::<_, _, TempoNetwork>::default()
            .connect_http("http://localhost:1".parse().unwrap());

        let opts = OpenPrecompilePayloadOptions {
            prefix_calls: Vec::new(),
            operator: Address::ZERO,
            authorized_signer: None,
            payee: Address::repeat_byte(0x11),
            currency: Address::repeat_byte(0x22),
            fee_token: Address::repeat_byte(0x22),
            deposit: PRECOMPILE_MAX_CUMULATIVE_AMOUNT + 1,
            initial_amount: 1,
            chain_id: 4217,
            fee_payer: false,
            salt: None,
        };
        let err = create_precompile_open_payload(&provider, &signer, None, payer, opts)
            .await
            .expect_err("deposit > uint96 must be rejected");
        assert!(matches!(err, MppError::InvalidConfig(_)));
    }

    #[cfg(feature = "tempo")]
    #[tokio::test]
    async fn top_up_stops_when_preflight_reverts() {
        use alloy::{
            providers::{mock::Asserter, ProviderBuilder},
            signers::local::PrivateKeySigner,
        };

        let asserter = Asserter::new();
        asserter.push_success(&"0x4a817c800");
        asserter.push_failure_msg("execution reverted: insufficient balance");
        let provider =
            ProviderBuilder::new_with_network::<TempoNetwork>().connect_mocked_client(asserter);
        let signer = PrivateKeySigner::random();
        let payer = signer.address();
        let descriptor = ChannelDescriptor {
            payer: payer.to_string(),
            payee: Address::repeat_byte(0x11).to_string(),
            operator: Address::ZERO.to_string(),
            token: Address::repeat_byte(0x22).to_string(),
            salt: B256::repeat_byte(0x33).to_string(),
            authorized_signer: payer.to_string(),
            expiring_nonce_hash: B256::repeat_byte(0x44).to_string(),
        };

        let error = create_precompile_top_up_transaction_payload(
            &provider,
            &signer,
            None,
            payer,
            TopUpPrecompilePayloadOptions {
                prefix_calls: vec![],
                descriptor: &descriptor,
                fee_token: Address::repeat_byte(0x22),
                additional_deposit: 5_000_000,
                chain_id: 4217,
                fee_payer: false,
            },
        )
        .await
        .expect_err("a reverting top-up must fail before it is signed");

        assert!(matches!(
            error,
            MppError::Tempo(crate::client::tempo::TempoClientError::InsufficientBalance { .. })
        ));
    }

    #[test]
    fn test_channel_entry_clone() {
        let entry = ChannelEntry {
            channel_id: B256::ZERO,
            salt: B256::ZERO,
            cumulative_amount: 1000,
            deposit: 0,
            descriptor: None,
            settlement_route: None,
            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());
    }

    #[cfg(feature = "tempo")]
    #[test]
    fn tip1034_challenge_without_escrow_uses_canonical_precompile() {
        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",
                "currency": Address::repeat_byte(0x44).to_string(),
                "methodDetails": { "sessionProtocol": "v2" }
            }))
            .unwrap(),
            expires: None,
            description: None,
            digest: None,
            opaque: None,
        };

        assert_eq!(
            resolve_escrow(&challenge, 4217, None).unwrap(),
            TIP20_CHANNEL_RESERVE_ADDRESS
        );
    }

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

        let hinted = Address::repeat_byte(0x22);
        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",
                "currency": Address::repeat_byte(0x44).to_string(),
                "methodDetails": { "escrow": hinted.to_string() }
            }))
            .unwrap(),
            expires: None,
            description: None,
            digest: None,
            opaque: None,
        };

        assert_eq!(resolve_escrow(&challenge, 4217, None).unwrap(), hinted);
    }

    #[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(),
            descriptor: None,
            settlement_route: None,
            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,
                descriptor,
                cumulative_amount,
                signature,
                ..
            } => {
                assert!(cid.starts_with("0x"));
                assert!(descriptor.is_none());
                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,
                descriptor,
                cumulative_amount,
                signature,
                ..
            } => {
                assert!(cid.starts_with("0x"));
                assert!(descriptor.is_none());
                assert_eq!(cumulative_amount, "2000");
                assert!(signature.starts_with("0x"));
            }
            _ => panic!("Expected Close variant"),
        }
    }

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

        let signer = PrivateKeySigner::random();
        let descriptor = build_channel_descriptor(
            Address::repeat_byte(0x11),
            Address::repeat_byte(0x22),
            Address::ZERO,
            Address::repeat_byte(0x33),
            B256::repeat_byte(0x44),
            Address::repeat_byte(0x55),
            B256::repeat_byte(0x66),
        );

        let err = create_precompile_close_payload_with_descriptor(
            &signer,
            B256::repeat_byte(0x77),
            descriptor,
            2000,
            42431,
        )
        .await
        .expect_err("descriptor/channel mismatch should fail");

        assert!(err.to_string().contains("does not match channel_id"));
    }

    #[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), 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,
        };

        // Match MPPx's default Tempo client: mainnet when no chain is advertised.
        assert_eq!(resolve_chain_id(&challenge), 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(),
            descriptor: None,
            settlement_route: None,
            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,
            deposit: 0,
            descriptor: None,
            settlement_route: None,
            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_override_priority_order() {
        use crate::protocol::core::{Base64UrlJson, PaymentChallenge};

        // Match MPPx: an explicit caller override wins over a challenge hint.
        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, override_addr,
            "override should take priority over challenge escrow"
        );
    }

    /// `try_recover_channel` must reject a channel whose on-chain payer,
    /// payee, token, or authorized signer doesn't match the expected values,
    /// or that is pending close.
    ///
    /// Since `try_recover_channel` calls `get_on_chain_channel` (which does
    /// an RPC call we can't mock here), we test the validation predicate
    /// directly against `OnChainChannel` values — the same struct and field
    /// comparisons used in the real function.
    ///
    /// Helper: evaluates the same predicate used by `try_recover_channel`.
    fn recovery_accepts(
        on_chain: &OnChainChannel,
        expected_payer: Address,
        expected_payee: Address,
        expected_token: Address,
        expected_authorized_signer: Address,
    ) -> bool {
        let actual_authorized_signer = if on_chain.authorized_signer == Address::ZERO {
            on_chain.payer
        } else {
            on_chain.authorized_signer
        };
        on_chain.deposit > 0
            && !on_chain.finalized
            && on_chain.close_requested_at == 0
            && on_chain.payer == expected_payer
            && on_chain.payee == expected_payee
            && on_chain.token == expected_token
            && actual_authorized_signer == expected_authorized_signer
    }

    #[test]
    fn test_recovery_rejects_wrong_payer() {
        let payer: Address = "0x1111111111111111111111111111111111111111"
            .parse()
            .unwrap();
        let payee: Address = "0x2222222222222222222222222222222222222222"
            .parse()
            .unwrap();
        let token: Address = "0x3333333333333333333333333333333333333333"
            .parse()
            .unwrap();
        let wrong_payer: Address = "0x9999999999999999999999999999999999999999"
            .parse()
            .unwrap();

        let on_chain = OnChainChannel {
            payer,
            payee,
            token,
            authorized_signer: Address::ZERO,
            deposit: 1_000,
            settled: 0,
            close_requested_at: 0,
            finalized: false,
        };

        assert!(
            recovery_accepts(&on_chain, payer, payee, token, payer),
            "should accept when all fields match"
        );
        assert!(
            !recovery_accepts(&on_chain, wrong_payer, payee, token, payer),
            "should reject wrong payer"
        );
    }

    #[test]
    fn test_recovery_rejects_wrong_payee() {
        let payer: Address = "0x1111111111111111111111111111111111111111"
            .parse()
            .unwrap();
        let payee: Address = "0x2222222222222222222222222222222222222222"
            .parse()
            .unwrap();
        let token: Address = "0x3333333333333333333333333333333333333333"
            .parse()
            .unwrap();
        let wrong_payee: Address = "0x9999999999999999999999999999999999999999"
            .parse()
            .unwrap();

        let on_chain = OnChainChannel {
            payer,
            payee,
            token,
            authorized_signer: Address::ZERO,
            deposit: 1_000,
            settled: 0,
            close_requested_at: 0,
            finalized: false,
        };

        assert!(
            !recovery_accepts(&on_chain, payer, wrong_payee, token, payer),
            "should reject wrong payee"
        );
    }

    #[test]
    fn test_recovery_rejects_wrong_token() {
        let payer: Address = "0x1111111111111111111111111111111111111111"
            .parse()
            .unwrap();
        let payee: Address = "0x2222222222222222222222222222222222222222"
            .parse()
            .unwrap();
        let token: Address = "0x3333333333333333333333333333333333333333"
            .parse()
            .unwrap();
        let wrong_token: Address = "0x9999999999999999999999999999999999999999"
            .parse()
            .unwrap();

        let on_chain = OnChainChannel {
            payer,
            payee,
            token,
            authorized_signer: Address::ZERO,
            deposit: 1_000,
            settled: 0,
            close_requested_at: 0,
            finalized: false,
        };

        assert!(
            !recovery_accepts(&on_chain, payer, payee, wrong_token, payer),
            "should reject wrong token"
        );
    }

    #[test]
    fn test_recovery_rejects_wrong_authorized_signer() {
        let payer: Address = "0x1111111111111111111111111111111111111111"
            .parse()
            .unwrap();
        let payee: Address = "0x2222222222222222222222222222222222222222"
            .parse()
            .unwrap();
        let token: Address = "0x3333333333333333333333333333333333333333"
            .parse()
            .unwrap();
        let client_signer: Address = "0x4444444444444444444444444444444444444444"
            .parse()
            .unwrap();
        let wrong_signer: Address = "0x9999999999999999999999999999999999999999"
            .parse()
            .unwrap();

        let on_chain = OnChainChannel {
            payer,
            payee,
            token,
            authorized_signer: wrong_signer,
            deposit: 1_000,
            settled: 0,
            close_requested_at: 0,
            finalized: false,
        };

        assert!(
            !recovery_accepts(&on_chain, payer, payee, token, client_signer),
            "should reject channel with wrong authorized_signer"
        );
    }

    #[test]
    fn test_recovery_accepts_zero_authorized_signer_when_payer_matches() {
        let payer: Address = "0x1111111111111111111111111111111111111111"
            .parse()
            .unwrap();
        let payee: Address = "0x2222222222222222222222222222222222222222"
            .parse()
            .unwrap();
        let token: Address = "0x3333333333333333333333333333333333333333"
            .parse()
            .unwrap();

        let on_chain = OnChainChannel {
            payer,
            payee,
            token,
            authorized_signer: Address::ZERO,
            deposit: 1_000,
            settled: 0,
            close_requested_at: 0,
            finalized: false,
        };

        assert!(
            recovery_accepts(&on_chain, payer, payee, token, payer),
            "Address::ZERO authorized_signer should normalize to payer"
        );
    }

    #[test]
    fn test_recovery_rejects_pending_close() {
        let payer: Address = "0x1111111111111111111111111111111111111111"
            .parse()
            .unwrap();
        let payee: Address = "0x2222222222222222222222222222222222222222"
            .parse()
            .unwrap();
        let token: Address = "0x3333333333333333333333333333333333333333"
            .parse()
            .unwrap();

        let on_chain = OnChainChannel {
            payer,
            payee,
            token,
            authorized_signer: Address::ZERO,
            deposit: 1_000,
            settled: 0,
            close_requested_at: 1_700_000_000,
            finalized: false,
        };

        assert!(
            !recovery_accepts(&on_chain, payer, payee, token, payer),
            "should reject channel pending close"
        );
    }
}