polyc-payments 2026.9.0

Machine Payments Protocol (MPP/Tempo) integration for polychrome: the control-plane composition/glue layer over the standalone outbound, inbound, wallet-delegation, egress, and spend-policy primitive crates, plus the payment proxy/wallet views.
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
//! Environment-driven configuration for the payments crate.
//!
//! [`PaymentsConfig`](crate::config::PaymentsConfig) is loaded once from the
//! process environment via
//! [`PaymentsConfig::from_env`](crate::config::PaymentsConfig::from_env) and
//! feeds both payment directions:
//!
//! - the **outbound** client builds a `TempoProvider` from the wallet signer
//!   (parsed from `TEMPO_SIGNER_KEY`) and the RPC URL — the chain id is
//!   validated from the server challenge, not passed to the constructor;
//! - the **inbound** server's `TempoBuilder` consumes the recipient, realm,
//!   chain id and the HMAC `secret_key` (the challenge-signing key, which is
//!   distinct from the wallet signer).
//!
//! Secrets (the wallet signer key and the HMAC secret) are never emitted by the
//! [`Debug`] impl.
//!
//! [`from_env`](crate::config::PaymentsConfig::from_env) is a thin wrapper over
//! the pure [`from_lookup`](crate::config::PaymentsConfig::from_lookup), which
//! takes a key→value lookup
//! closure. This keeps the parsing logic testable without mutating the
//! process-global environment (the workspace forbids the `unsafe` block that
//! `std::env::set_var` requires under edition 2024).

use std::env;
use std::fmt;
use std::path::PathBuf;

use mpp::PrivateKeySigner;

use polyc_crypto::sensitive::Sensitive;
use polyc_wallet_delegation::keystore::KeystoreError;

use crate::{MODERATO_CHAIN_ID, MODERATO_RPC_URL};

/// Environment variable holding the outbound wallet signer key (0x-prefixed or
/// bare 32-byte hex).
const ENV_SIGNER_KEY: &str = "TEMPO_SIGNER_KEY";
/// Inbound fee-payer **sponsor** signer key. When set, the inbound 402 server
/// issues `feePayer: true` challenges and co-signs (sponsors) the gas for a
/// client's payment transaction. Must be a DISTINCT account from the payer (the
/// node rejects `fee_payer == sender`) and hold native gas.
const ENV_FEE_PAYER_KEY: &str = "TEMPO_FEE_PAYER_KEY";
/// Path to the Tempo wallet `keys.toml` (a delegated keychain access key
/// provisioned by `tempo wallet login`). When set, the outbound client signs in
/// keychain mode instead of with a raw `TEMPO_SIGNER_KEY`.
const ENV_WALLET_KEYS_PATH: &str = "TEMPO_WALLET_KEYS_PATH";
/// Tempo wallet home directory. When `TEMPO_WALLET_KEYS_PATH` is unset but this
/// is set, the keystore is read from `$TEMPO_HOME/wallet/keys.toml`.
const ENV_TEMPO_HOME: &str = "TEMPO_HOME";
/// Token contract address (`0x…`) outbound payments settle in. Required for
/// keychain selection (the key is chosen by its onchain limit for this token).
const ENV_CURRENCY: &str = "TEMPO_CURRENCY";
/// Decimal scale of `TEMPO_CURRENCY` (e.g. 6 for pathUSD / standard 6-decimal
/// stablecoins). Used to convert the human-readable dollar cap + conversation
/// budget into the token's base units. Defaults to 6.
const ENV_CURRENCY_DECIMALS: &str = "TEMPO_CURRENCY_DECIMALS";
/// Upper bound on the settlement-token decimal scale, matching the ceiling tempo
/// MPP enforces (`mpp::server::parse_dollar_amount` rejects `> 38` with
/// `Overflow`). Bounding here keeps config fail-closed at the source: a larger
/// value would make every dollar→base-unit conversion return `None` and panic
/// the per-call cap and conversation-budget fallbacks downstream.
const MAX_CURRENCY_DECIMALS: u32 = 38;
/// Opt-in gate for the raw-key (`Direct`) signer. The control-plane proxy refuses
/// to sign with a raw `TEMPO_SIGNER_KEY` unless this is set truthy — production
/// fails closed so it cannot silently run on an unbounded hot key.
const ENV_ALLOW_RAW_SIGNER: &str = "POLYCHROME_ALLOW_RAW_SIGNER";
/// Whether outbound keychain payments force **self-settlement** — a fully-signed
/// `0x76` the client pays its own gas for — instead of the fee-payer `0x78`
/// envelope a facilitator must co-sign. Defaults to `false` (fee-payer
/// settlement); set truthy to force self-settlement.
const ENV_SELF_SETTLE: &str = "TEMPO_SELF_SETTLE";
/// Optional override for the JSON-RPC endpoint.
const ENV_RPC_URL: &str = "TEMPO_RPC_URL";
/// Optional override for the chain id used by the inbound server builder.
const ENV_CHAIN_ID: &str = "TEMPO_CHAIN_ID";
/// Inbound payment recipient address.
const ENV_RECIPIENT: &str = "TEMPO_RECIPIENT";
/// Optional override for the inbound realm (defaults to `polychrome`).
const ENV_REALM: &str = "TEMPO_REALM";
/// Inbound HMAC challenge-signing secret (distinct from the wallet signer).
const ENV_HMAC_SECRET: &str = "TEMPO_HMAC_SECRET";
/// Optional override for the block-explorer base URL.
const ENV_EXPLORER_URL: &str = "TEMPO_EXPLORER_URL";
/// Optional default outbound spend ceiling (decimal dollars, e.g. `"0.10"`)
/// applied to `paid_fetch` calls that omit a per-call `max_spend`.
const ENV_MAX_SPEND: &str = "TEMPO_MAX_SPEND";
/// Comma-separated allowlist of hosts an outbound `paid_fetch` may pay
/// (`TEMPO_PAID_HOST_ALLOWLIST`, for example `api.foo.com,data.bar.io`). When
/// set, the proxy refuses to pay any host not on the list (fail closed) — a
/// set-but-degenerate value (no valid hosts, e.g. `","`) therefore denies every
/// host rather than silently disabling the control. When unset, no positive
/// allowlist applies and only the SSRF deny-list guards the destination. Hosts
/// are matched case-insensitively; the port is ignored.
const ENV_PAID_HOST_ALLOWLIST: &str = "TEMPO_PAID_HOST_ALLOWLIST";
/// Pre-signing per-transaction spend cap (decimal dollars, e.g. `"0.50"`). A
/// `paid_fetch` whose per-call ceiling exceeds this pre-authorization is
/// rejected before signing. Unset ⇒ no per-transaction pre-auth bound.
const ENV_PRESIGN_PER_TX_CAP: &str = "TEMPO_PRESIGN_PER_TX_CAP";
/// Pre-signing per-session spend cap (decimal dollars, e.g. `"5.00"`). A
/// `paid_fetch` whose running session total would exceed this pre-authorization
/// is rejected before signing. Unset ⇒ no per-session pre-auth bound.
const ENV_PRESIGN_PER_SESSION_CAP: &str = "TEMPO_PRESIGN_PER_SESSION_CAP";
/// Trusted AP2-mandate issuer public key (hex-encoded ed25519, the same
/// encoding `polyc_crypto::Signer::public_key_bytes` produces). The feature
/// gate for mandate-chain pre-authorization: unset (the default) ⇒ mandates
/// are OFF and any presented chain is ignored — behavior is exactly the
/// SpendCap-only path. Set ⇒ a presented Intent→Cart→Payment chain must
/// verify against this key end-to-end or the payment is refused. A
/// set-but-undecodable value fails closed at load.
const ENV_MANDATE_ISSUER_PUBKEY: &str = "TEMPO_MANDATE_ISSUER_PUBKEY";
/// Per-conversation aggregate outbound spend budget (decimal dollars, e.g.
/// `"1.00"`). Defaults to `"1.00"` when unset. Parsed here (rather than read
/// directly by the control plane) so the wallet-page view and the enforcing
/// budget derive the SAME figure from the SAME source — see
/// [`PaymentsConfig::conversation_budget_base_units`].
const ENV_CONVERSATION_BUDGET: &str = "TEMPO_CONVERSATION_BUDGET";
/// Built-in default for [`ENV_CONVERSATION_BUDGET`] when unset.
const DEFAULT_CONVERSATION_BUDGET: &str = "1.00";

/// Environment variables that carry — directly or indirectly — a **signer
/// source** (an outbound payment key, or the inbound fee-payer sponsor key).
///
/// The harness sandbox must never have any of these set (signing is
/// control-plane-only); the harness boots fail-closed if it finds one.
/// `TEMPO_HOME` is included because [`from_lookup`](PaymentsConfig::from_lookup)
/// derives `$TEMPO_HOME/wallet/keys.toml` from it, so a harness with only
/// `TEMPO_HOME` set would indirectly hold a keychain key.
/// `TEMPO_FEE_PAYER_KEY` is a funded sponsor account — leaking it into the
/// untrusted sandbox would let agent code drain the fee sponsor.
///
/// **Keep this in sync** when adding any new signer-source field to
/// [`PaymentsConfig`].
pub const SIGNER_ENV_VARS: &[&str] = &[
    ENV_SIGNER_KEY,
    ENV_WALLET_KEYS_PATH,
    ENV_TEMPO_HOME,
    ENV_FEE_PAYER_KEY,
];

/// Default realm advertised by the inbound 402 challenge.
const DEFAULT_REALM: &str = "polychrome";

/// Default block-explorer base URL for the Tempo Moderato testnet.
///
/// Moderato is served by a Blockscout instance whose transaction path is
/// `/tx/0x<hash>` and address path `/address/0x<addr>`. The mainnet
/// `explore.tempo.xyz` host is **not** correct for the testnet — the single
/// source is [`crate::MODERATO_EXPLORER_URL`].
const DEFAULT_EXPLORER_URL: &str = crate::MODERATO_EXPLORER_URL;

/// Configuration shared by the outbound client and the inbound server.
///
/// Built from the environment via [`PaymentsConfig::from_env`]. The wallet
/// signer key and the HMAC secret are redacted by the [`Debug`] impl.
pub struct PaymentsConfig {
    /// Raw-key wallet signer parsed from `TEMPO_SIGNER_KEY`, if present. Used to
    /// build the outbound `TempoProvider` in `Direct` mode. Optional: a keychain
    /// deployment (and any inbound-only deployment) carries no raw signer. Never
    /// logged.
    signer: Option<PrivateKeySigner>,
    /// Inbound fee-payer **sponsor** signer parsed from `TEMPO_FEE_PAYER_KEY`, if
    /// present. When set, the inbound 402 server sponsors client gas: it issues
    /// `feePayer: true` challenges and co-signs the client's transaction with
    /// this key. Must be a DISTINCT, gas-funded account from the payer (the node
    /// rejects `fee_payer == sender`). `None` ⇒ no sponsorship (unchanged
    /// behavior). Never logged.
    fee_payer_key: Option<PrivateKeySigner>,
    /// JSON-RPC endpoint. Defaults to [`MODERATO_RPC_URL`]; override with
    /// `TEMPO_RPC_URL`.
    pub rpc_url: String,
    /// Chain id fed to the inbound `TempoBuilder.chain_id(..)`. Defaults to
    /// [`MODERATO_CHAIN_ID`]; override with `TEMPO_CHAIN_ID`. Not passed to the
    /// outbound provider constructor (validated from the challenge instead).
    pub chain_id: u64,
    /// Inbound payment recipient address (`TEMPO_RECIPIENT`).
    pub recipient: Option<String>,
    /// Inbound realm advertised in the 402 challenge. Defaults to `polychrome`;
    /// override with `TEMPO_REALM`.
    pub realm: String,
    /// Inbound HMAC challenge-signing secret (`TEMPO_HMAC_SECRET`). Never
    /// logged.
    hmac_secret: Option<Sensitive<String>>,
    /// Block-explorer base URL used to build verified settlement links.
    ///
    /// Defaults to `https://explore.testnet.tempo.xyz`; override with
    /// `TEMPO_EXPLORER_URL`.
    /// Non-secret, so it is shown by the [`Debug`] impl.
    pub explorer_url: String,
    /// Optional default outbound spend ceiling (decimal dollars, e.g. `"0.10"`)
    /// from `TEMPO_MAX_SPEND`, applied to outbound `paid_fetch` payments that
    /// omit a per-call `max_spend`. When unset, `paid_fetch` falls back to a
    /// conservative built-in default so an outbound payment is never uncapped.
    /// Non-secret, so it is shown by the [`Debug`] impl.
    pub max_spend: Option<String>,
    /// Path to the Tempo wallet `keys.toml`, if configured (from
    /// `TEMPO_WALLET_KEYS_PATH`, or `$TEMPO_HOME/wallet/keys.toml`). When set,
    /// [`resolve_outbound_client`](Self::resolve_outbound_client) signs in
    /// keychain mode. Non-secret (a path), so shown by the [`Debug`] impl.
    pub keys_path: Option<PathBuf>,
    /// Token contract address outbound payments settle in (`TEMPO_CURRENCY`).
    /// Required for keychain selection. Non-secret.
    pub currency: Option<String>,
    /// Decimal scale of [`currency`](Self::currency) (`TEMPO_CURRENCY_DECIMALS`,
    /// default 6). Used to scale the dollar cap + conversation budget into the
    /// token's base units. Non-secret.
    pub currency_decimals: u32,
    /// Whether the raw-key (`Direct`) signer is explicitly allowed
    /// (`POLYCHROME_ALLOW_RAW_SIGNER`). Defaults to `false` so production fails
    /// closed rather than silently signing with an unbounded hot key.
    pub allow_raw_signer: bool,
    /// Whether outbound payments force self-settlement (`TEMPO_SELF_SETTLE`,
    /// default `false`). When `true`, the payment provider rewrites any
    /// fee-payer challenge so the client signs a complete `0x76` and pays its
    /// own gas from the (funded) settlement account, rather than emitting the
    /// `0x78` fee-payer envelope that a merchant facilitator co-signs and
    /// broadcasts. Off by default because Tempo's model — and our own inbound
    /// merchant — sponsor the gas; opt in only for a merchant that accepts a
    /// client-settled payment. Non-secret.
    pub self_settle: bool,
    /// Allowlist of hosts an outbound `paid_fetch` may pay
    /// (`TEMPO_PAID_HOST_ALLOWLIST`). `None` ⇒ the variable is unset: no
    /// positive allowlist (only the SSRF deny-list applies). `Some(list)` ⇒ pay
    /// only these hosts (fail closed); an empty list — a set-but-degenerate
    /// value — denies every host rather than failing open. Hosts are stored
    /// lowercased; matching ignores the port. This is the static form of the
    /// governed merchant registry — a catalog-driven dynamic allowlist is a
    /// later addition. Non-secret.
    pub paid_host_allowlist: Option<Vec<String>>,
    /// Pre-signing per-transaction spend cap in settlement-token base units
    /// (`TEMPO_PRESIGN_PER_TX_CAP`, parsed from dollars at load). `None` ⇒ no
    /// per-transaction pre-authorization bound. Non-secret.
    presign_per_tx_base_units: Option<u128>,
    /// Pre-signing per-session spend cap in settlement-token base units
    /// (`TEMPO_PRESIGN_PER_SESSION_CAP`, parsed from dollars at load). `None` ⇒
    /// no per-session pre-authorization bound. Non-secret.
    presign_per_session_base_units: Option<u128>,
    /// Trusted AP2-mandate issuer public key, decoded from the hex in
    /// `TEMPO_MANDATE_ISSUER_PUBKEY`. `None` ⇒ mandate-chain
    /// pre-authorization is OFF (the default; zero behavior change).
    /// Non-secret (a public key).
    mandate_issuer_public_key: Option<Vec<u8>>,
    /// Per-conversation aggregate outbound spend budget, in settlement-token
    /// base units (`TEMPO_CONVERSATION_BUDGET`, parsed from dollars at load;
    /// defaults to the base-unit equivalent of `"1.00"` when unset). The
    /// single source both `build_outbound_payment_ctx`'s enforcing
    /// durable spend authority and the
    /// wallet-page deployment-ceilings view derive their figure from — see
    /// [`Self::conversation_budget_base_units`]. Non-secret.
    conversation_budget_base_units: u128,
}

impl PaymentsConfig {
    /// Loads configuration from the process environment.
    ///
    /// # Errors
    ///
    /// Returns [`PaymentsConfigError::InvalidSignerKey`] when `TEMPO_SIGNER_KEY`
    /// is set but cannot be parsed as a 32-byte hex private key, and
    /// [`PaymentsConfigError::InvalidChainId`] when `TEMPO_CHAIN_ID` is set but
    /// not a valid `u64`. The raw signer is **optional** (keychain and
    /// inbound-only deployments carry none); the outbound signing path is chosen
    /// and validated later by [`resolve_outbound_client`](Self::resolve_outbound_client).
    pub fn from_env() -> Result<Self, PaymentsConfigError> {
        Self::from_lookup(|key| env::var(key).ok())
    }

    /// Loads configuration from an arbitrary key→value lookup.
    ///
    /// This is the pure core of [`from_env`](Self::from_env); the latter simply
    /// supplies `std::env::var`. Tests drive this directly with an in-memory map
    /// to avoid mutating the process-global environment.
    ///
    /// # Errors
    ///
    /// See [`from_env`](Self::from_env).
    pub fn from_lookup<F>(lookup: F) -> Result<Self, PaymentsConfigError>
    where
        F: Fn(&str) -> Option<String>,
    {
        // Treat blank/whitespace-only values as absent for every key.
        let get = |key: &str| -> Option<String> {
            lookup(key).and_then(|v| {
                let t = v.trim();
                if t.is_empty() {
                    None
                } else {
                    Some(t.to_string())
                }
            })
        };

        // Both signer keys are optional (keychain and inbound-only deployments
        // carry no raw key), but a present-but-malformed key fails loud — a
        // typo'd key must not be silently ignored. The raw signer feeds the
        // outbound `Direct` provider; the fee-payer key sponsors inbound gas.
        let signer =
            parse_optional_signer(get(ENV_SIGNER_KEY), PaymentsConfigError::InvalidSignerKey)?;
        let fee_payer_key = parse_optional_signer(
            get(ENV_FEE_PAYER_KEY),
            PaymentsConfigError::InvalidFeePayerKey,
        )?;

        let rpc_url = get(ENV_RPC_URL).unwrap_or_else(|| MODERATO_RPC_URL.to_string());

        let chain_id = match get(ENV_CHAIN_ID) {
            Some(s) => s
                .parse::<u64>()
                .map_err(|e| PaymentsConfigError::InvalidChainId(e.to_string()))?,
            None => MODERATO_CHAIN_ID,
        };

        let recipient = get(ENV_RECIPIENT);
        let realm = get(ENV_REALM).unwrap_or_else(|| DEFAULT_REALM.to_string());
        let hmac_secret = get(ENV_HMAC_SECRET).map(Sensitive::new);
        let explorer_url =
            get(ENV_EXPLORER_URL).unwrap_or_else(|| DEFAULT_EXPLORER_URL.to_string());

        // Keychain keys.toml: explicit path wins; otherwise derive from
        // $TEMPO_HOME/wallet/keys.toml when TEMPO_HOME is set.
        let keys_path = get(ENV_WALLET_KEYS_PATH).map(PathBuf::from).or_else(|| {
            get(ENV_TEMPO_HOME).map(|home| PathBuf::from(home).join("wallet").join("keys.toml"))
        });
        let currency = get(ENV_CURRENCY);
        let currency_decimals = match get(ENV_CURRENCY_DECIMALS) {
            Some(s) => {
                let d = s
                    .trim()
                    .parse::<u32>()
                    .map_err(|e| PaymentsConfigError::InvalidCurrencyDecimals(e.to_string()))?;
                // Reject out-of-range decimals at the source (tempo MPP caps at
                // 38). Otherwise every base-unit conversion returns `None` and
                // the downstream cap/budget `expect`s would panic — fail closed
                // with a clear config error instead.
                if d > MAX_CURRENCY_DECIMALS {
                    return Err(PaymentsConfigError::InvalidCurrencyDecimals(format!(
                        "{d} exceeds the maximum settlement-token decimals ({MAX_CURRENCY_DECIMALS})"
                    )));
                }
                d
            }
            None => crate::amount::DEFAULT_DECIMALS,
        };
        // Validated NOW, at the configured decimals, so a set-but-unparseable
        // ceiling fails config load rather than being silently reported as a
        // spendable figure (the wallet page's `default_max_spend_base_units`)
        // while every real payment call rejects it (`resolve_cap_base_units`
        // in `proxy.rs`) — the two must never disagree about whether this
        // deployment's default cap actually works. The raw dollar string is
        // kept (not the parsed base units): `resolve_cap_base_units` folds
        // it against a per-call value at call time, and `to_outbound_config`
        // hands the string on to `polyc-payments-client`'s own config.
        let max_spend = validate_max_spend(get(ENV_MAX_SPEND), currency_decimals)?;
        let allow_raw_signer = get(ENV_ALLOW_RAW_SIGNER).is_some_and(|v| is_truthy(&v));
        // Self-settle defaults OFF: Tempo's model is fee-payer sponsorship (a
        // funded sponsor co-signs the gas), which our own inbound merchant does,
        // so the outbound client should present a fee-payer transaction, not pay
        // its own gas. Opt in only for a merchant that accepts client-settled
        // payments.
        let self_settle = get(ENV_SELF_SETTLE).is_some_and(|v| is_truthy(&v));

        // Parse the host allowlist: split on commas, trim, lowercase, drop empty
        // entries. `None` means strictly "the variable is unset" — a variable
        // that is set but yields no hosts (e.g. just commas) stays `Some(empty)`
        // and so DENIES every host. An operator who set the knob intended an
        // allowlist; silently disabling it on a degenerate value would fail
        // open on a payment-egress control.
        let paid_host_allowlist = get(ENV_PAID_HOST_ALLOWLIST).map(|raw| {
            raw.split(',')
                .map(|h| h.trim().to_ascii_lowercase())
                .filter(|h| !h.is_empty())
                .collect::<Vec<String>>()
        });

        // Pre-signing spend caps: parse the dollar strings into base units at the
        // configured decimals NOW, so the proxy's pre-auth check is infallible. A
        // set-but-unparseable value fails closed at load (a misconfigured spend
        // control must not silently become unbounded).
        let parse_presign = |env: &str| -> Result<Option<u128>, PaymentsConfigError> {
            get(env).map_or(Ok(None), |raw| {
                crate::amount::dollars_to_base_units(&raw, currency_decimals)
                    .map(Some)
                    .ok_or_else(|| {
                        PaymentsConfigError::InvalidPresignCap(format!(
                            "{env} value {raw:?} is not a valid dollar amount"
                        ))
                    })
            })
        };
        let presign_per_tx_base_units = parse_presign(ENV_PRESIGN_PER_TX_CAP)?;
        let presign_per_session_base_units = parse_presign(ENV_PRESIGN_PER_SESSION_CAP)?;

        // Conversation budget: same fail-closed parse as the presign caps, just
        // always-present (see `parse_conversation_budget`'s own doc comment).
        let conversation_budget_base_units =
            parse_conversation_budget(get(ENV_CONVERSATION_BUDGET), currency_decimals)?;

        // Mandate issuer key: decode the hex NOW so a set-but-garbled key fails
        // closed at load — a misconfigured trust root must never silently
        // disable (or worse, mis-verify) the mandate gate.
        let mandate_issuer_public_key = parse_mandate_issuer_key(get(ENV_MANDATE_ISSUER_PUBKEY))?;

        Ok(Self {
            signer,
            fee_payer_key,
            rpc_url,
            chain_id,
            recipient,
            realm,
            hmac_secret,
            explorer_url,
            max_spend,
            keys_path,
            currency,
            currency_decimals,
            allow_raw_signer,
            self_settle,
            paid_host_allowlist,
            presign_per_tx_base_units,
            presign_per_session_base_units,
            mandate_issuer_public_key,
            conversation_budget_base_units,
        })
    }

    /// The per-conversation aggregate outbound spend budget, in
    /// settlement-token base units (`TEMPO_CONVERSATION_BUDGET`, default
    /// `"1.00"`).
    ///
    /// This is the single figure both the enforcing
    /// durable spend authority and the
    /// wallet page's deployment-ceilings view derive from — see the
    /// module-level plumbing note on
    /// [`conversation_budget_base_units`](Self::conversation_budget_base_units).
    #[must_use]
    pub const fn conversation_budget_base_units(&self) -> u128 {
        self.conversation_budget_base_units
    }

    /// The effective default per-payment spend ceiling, in settlement-token
    /// base units: `TEMPO_MAX_SPEND` scaled to base units when set, else the
    /// built-in `crate::proxy::DEFAULT_CAP` the proxy itself falls back to.
    ///
    /// Mirrors `resolve_cap_base_units`'s no-request-value branch exactly, so
    /// a reader is never shown a figure narrower or wider than what the proxy
    /// actually enforces on a call that supplies no per-call `max_spend`. A
    /// payment is never uncapped, so this is never `None`. The mirror holds
    /// exactly because `from_lookup` already validated `TEMPO_MAX_SPEND` at
    /// load (see `validate_max_spend`) — `self.max_spend` can only be `None`
    /// or a value this function's own re-parse is guaranteed to succeed on,
    /// so this can never silently report a spendable figure for a ceiling the
    /// proxy would actually reject every payment against.
    ///
    /// # Panics
    ///
    /// Does not panic in practice: the only fallback re-parses the
    /// compile-time constant `crate::proxy::DEFAULT_CAP` at
    /// `self.currency_decimals`, which `from_lookup` already bounds to the
    /// tempo-MPP ceiling.
    #[must_use]
    pub fn default_max_spend_base_units(&self) -> u128 {
        self.max_spend
            .as_deref()
            .and_then(|s| crate::amount::dollars_to_base_units(s, self.currency_decimals))
            .unwrap_or_else(|| {
                crate::amount::dollars_to_base_units(
                    crate::proxy::DEFAULT_CAP,
                    self.currency_decimals,
                )
                .expect("default cap parses")
            })
    }

    /// The operator-granted pre-signing spend cap (per-transaction /
    /// per-session pre-authorization), in settlement-token base units.
    ///
    /// [`SpendCap::unlimited`](polyc_spend_policy::presign::SpendCap::unlimited) when neither
    /// `TEMPO_PRESIGN_PER_TX_CAP` nor `TEMPO_PRESIGN_PER_SESSION_CAP` is set.
    #[must_use]
    pub const fn presign_spend_cap(&self) -> polyc_spend_policy::presign::SpendCap {
        polyc_spend_policy::presign::SpendCap::new(
            self.presign_per_tx_base_units,
            self.presign_per_session_base_units,
        )
    }

    /// The trusted AP2-mandate issuer public key
    /// (`TEMPO_MANDATE_ISSUER_PUBKEY`), if configured.
    ///
    /// `None` ⇒ mandate-chain pre-authorization is off (the default) and the
    /// proxy ignores any presented chain.
    #[must_use]
    pub fn mandate_issuer_public_key(&self) -> Option<&[u8]> {
        self.mandate_issuer_public_key.as_deref()
    }

    /// Returns the raw-key wallet signer, if `TEMPO_SIGNER_KEY` was set.
    #[must_use]
    pub const fn signer(&self) -> Option<&PrivateKeySigner> {
        self.signer.as_ref()
    }

    /// Returns the inbound fee-payer **sponsor** signer, if `TEMPO_FEE_PAYER_KEY`
    /// was set. When present, the inbound 402 server sponsors client gas by
    /// issuing `feePayer: true` challenges and co-signing with this key.
    #[must_use]
    pub const fn fee_payer_signer(&self) -> Option<&PrivateKeySigner> {
        self.fee_payer_key.as_ref()
    }

    /// Whether a deployment env signer source is configured (keychain path or raw key).
    #[must_use]
    pub const fn has_signer_source(&self) -> bool {
        self.keys_path.is_some() || self.signer().is_some()
    }

    /// Returns the inbound HMAC challenge-signing secret, if configured.
    #[must_use]
    pub fn hmac_secret(&self) -> Option<&str> {
        self.hmac_secret.as_ref().map(|s| s.expose().as_str())
    }

    /// Returns the recipient required to build the inbound server.
    ///
    /// # Errors
    ///
    /// Returns [`PaymentsConfigError::MissingRecipient`] when `TEMPO_RECIPIENT`
    /// is unset.
    pub fn require_recipient(&self) -> Result<&str, PaymentsConfigError> {
        self.recipient
            .as_deref()
            .ok_or(PaymentsConfigError::MissingRecipient)
    }

    /// Returns the HMAC secret required to build the inbound server.
    ///
    /// # Errors
    ///
    /// Returns [`PaymentsConfigError::MissingHmacSecret`] when
    /// `TEMPO_HMAC_SECRET` is unset.
    pub fn require_hmac_secret(&self) -> Result<&str, PaymentsConfigError> {
        self.hmac_secret
            .as_ref()
            .map(|s| s.expose().as_str())
            .ok_or(PaymentsConfigError::MissingHmacSecret)
    }

    /// Builds the standalone `polyc-payments-client` crate's own minimal
    /// outbound configuration from this config's already-parsed
    /// outbound-relevant fields, without re-reading the environment.
    ///
    /// This is the composition seam issue #723 introduced: the outbound
    /// 402-gated client, its signer resolution, balance reads, and explorer-link
    /// resolution moved to `polyc-payments-client` behind its own pure
    /// `OutboundConfig`, so this (broader, inbound-carrying) config hands over
    /// only the overlapping fields rather than depending back on that crate's
    /// env var parsing.
    fn to_outbound_config(&self) -> polyc_payments_client::config::OutboundConfig {
        polyc_payments_client::config::OutboundConfig::from_parts(
            polyc_payments_client::config::OutboundConfigParts {
                signer: self.signer.clone(),
                rpc_url: self.rpc_url.clone(),
                chain_id: self.chain_id,
                explorer_url: self.explorer_url.clone(),
                max_spend: self.max_spend.clone(),
                keys_path: self.keys_path.clone(),
                currency: self.currency.clone(),
                currency_decimals: self.currency_decimals,
                allow_raw_signer: self.allow_raw_signer,
            },
        )
    }

    /// Resolves the outbound payment client for a given key source — the
    /// deployment's own env-configured signer
    /// ([`KeySource::FileSecret`](polyc_payments_client::resolver::KeySource::FileSecret))
    /// or a persona's delegated key
    /// ([`KeySource::DelegatedScopedKey`](polyc_payments_client::resolver::KeySource::DelegatedScopedKey)).
    ///
    /// Delegates to `polyc-payments-client`'s
    /// `OutboundConfig::resolve_client`, which owns the actual resolution
    /// order; see there for details.
    ///
    /// # Errors
    ///
    /// See [`PaymentsConfigError`].
    pub async fn resolve_client(
        &self,
        source: polyc_payments_client::resolver::KeySource<'_>,
        now_unix: u64,
    ) -> Result<polyc_payments_client::outbound::PaymentsClient, PaymentsConfigError> {
        self.to_outbound_config()
            .resolve_client(source, now_unix)
            .await
            .map_err(Into::into)
    }

    /// Resolves the outbound payment client from this deployment's own
    /// env-configured signer (a keychain `keys.toml` or a gated raw key).
    ///
    /// Delegates to `polyc-payments-client`'s
    /// `OutboundConfig::resolve_outbound_client`.
    ///
    /// # Errors
    ///
    /// See [`PaymentsConfigError`].
    pub async fn resolve_outbound_client(
        &self,
        now_unix: u64,
    ) -> Result<polyc_payments_client::outbound::PaymentsClient, PaymentsConfigError> {
        self.to_outbound_config()
            .resolve_outbound_client(now_unix)
            .await
            .map_err(Into::into)
    }

    /// Reads the onchain registration status of a delegated keychain key for
    /// `(chain_id, currency)`.
    ///
    /// Delegates to `polyc-payments-client`'s
    /// `OutboundConfig::resolve_keychain_status`.
    ///
    /// # Errors
    ///
    /// See [`PaymentsConfigError`].
    pub async fn resolve_keychain_status(
        &self,
        keys_toml: &str,
        currency: &str,
        now_unix: u64,
    ) -> Result<polyc_payments_client::outbound::KeychainRegistrationStatus, PaymentsConfigError>
    {
        self.to_outbound_config()
            .resolve_keychain_status(keys_toml, currency, now_unix)
            .await
            .map_err(Into::into)
    }
}

impl From<polyc_payments_client::config::OutboundConfigError> for PaymentsConfigError {
    /// Maps `polyc-payments-client`'s own outbound config/resolution error onto
    /// this crate's broader [`PaymentsConfigError`] — a 1:1 mapping for every
    /// overlapping variant, so an existing caller matching on (say)
    /// [`PaymentsConfigError::RawSignerNotAllowed`] sees identical behavior to
    /// before the outbound client moved crates.
    fn from(e: polyc_payments_client::config::OutboundConfigError) -> Self {
        use polyc_payments_client::config::OutboundConfigError as E;
        match e {
            E::InvalidSignerKey(s) => Self::InvalidSignerKey(s),
            E::InvalidChainId(s) => Self::InvalidChainId(s),
            E::InvalidCurrencyDecimals(s) => Self::InvalidCurrencyDecimals(s),
            E::MissingCurrency => Self::MissingCurrency,
            E::InvalidKeysFile(s) => Self::InvalidKeysFile(s),
            E::KeySelection(k) => Self::KeySelection(k),
            E::RawSignerNotAllowed => Self::RawSignerNotAllowed,
            E::MissingSigner => Self::MissingSigner,
            E::Client(s) => Self::Client(s),
        }
    }
}

impl From<polyc_payments_server::config::InboundConfigError> for PaymentsConfigError {
    /// Maps `polyc-payments-server`'s own inbound config error onto this
    /// crate's broader [`PaymentsConfigError`] — a 1:1 mapping for every
    /// variant, so an existing caller matching on (say)
    /// [`PaymentsConfigError::MissingRecipient`] sees identical behavior to
    /// before the inbound server moved crates.
    fn from(e: polyc_payments_server::config::InboundConfigError) -> Self {
        use polyc_payments_server::config::InboundConfigError as E;
        match e {
            E::InvalidChainId(s) => Self::InvalidChainId(s),
            E::InvalidFeePayerKey(s) => Self::InvalidFeePayerKey(s),
            E::MissingRecipient => Self::MissingRecipient,
            E::MissingHmacSecret => Self::MissingHmacSecret,
            E::MissingCurrency(chain_id) => Self::InboundMissingCurrency(chain_id),
        }
    }
}

impl fmt::Debug for PaymentsConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PaymentsConfig")
            .field("signer", &self.signer.as_ref().map(|_| "<redacted>"))
            .field(
                "fee_payer_key",
                &self.fee_payer_key.as_ref().map(|_| "<redacted>"),
            )
            .field("rpc_url", &self.rpc_url)
            .field("chain_id", &self.chain_id)
            .field("recipient", &self.recipient)
            .field("realm", &self.realm)
            .field("explorer_url", &self.explorer_url)
            .field("max_spend", &self.max_spend)
            .field("keys_path", &self.keys_path)
            .field("currency", &self.currency)
            .field("currency_decimals", &self.currency_decimals)
            .field("allow_raw_signer", &self.allow_raw_signer)
            .field("self_settle", &self.self_settle)
            .field("paid_host_allowlist", &self.paid_host_allowlist)
            .field("presign_per_tx_base_units", &self.presign_per_tx_base_units)
            .field(
                "presign_per_session_base_units",
                &self.presign_per_session_base_units,
            )
            .field(
                "mandate_issuer_public_key",
                &self.mandate_issuer_public_key.as_ref().map(hex::encode),
            )
            .field(
                "conversation_budget_base_units",
                &self.conversation_budget_base_units,
            )
            .field(
                "hmac_secret",
                &self.hmac_secret.as_ref().map(|_| "<redacted>"),
            )
            .finish()
    }
}

/// Parses a boolean-ish environment flag. Truthy: `1`, `true`, `yes`, `on`
/// (case-insensitive). Everything else is false.
/// Parses an optional hex private key: `None` stays `None`; a present value must
/// parse as a 32-byte key or `on_err` maps the failure to a config error (fail
/// loud on a typo'd key rather than silently ignoring it).
fn parse_optional_signer(
    raw: Option<String>,
    on_err: impl FnOnce(String) -> PaymentsConfigError,
) -> Result<Option<PrivateKeySigner>, PaymentsConfigError> {
    match raw {
        Some(r) => Ok(Some(r.parse().map_err(
            |e: <PrivateKeySigner as std::str::FromStr>::Err| on_err(e.to_string()),
        )?)),
        None => Ok(None),
    }
}

/// Validates `TEMPO_MAX_SPEND`'s optional dollar figure (`raw`, already
/// blank-collapsed-to-`None`) at `decimals`, returning it UNCHANGED — the raw
/// string, not the parsed base units, since `crate::proxy`'s
/// `resolve_cap_base_units` and `PaymentsConfig::to_outbound_config` both
/// need the string form.
///
/// `None` stays `None` (the deployment sets no default cap; the built-in
/// `crate::proxy::DEFAULT_CAP` applies). A set-but-unparseable value fails
/// config load rather than being silently accepted and then rejected on
/// every real payment call — this is the same fail-fast contract the presign
/// caps and the conversation budget already enforce.
fn validate_max_spend(
    raw: Option<String>,
    decimals: u32,
) -> Result<Option<String>, PaymentsConfigError> {
    if let Some(dollars) = &raw
        && crate::amount::dollars_to_base_units(dollars, decimals).is_none()
    {
        return Err(PaymentsConfigError::InvalidMaxSpend(format!(
            "{ENV_MAX_SPEND} value {dollars:?} is not a valid dollar amount"
        )));
    }
    Ok(raw)
}

/// Decodes an optional hex-encoded trusted AP2-mandate issuer public key.
/// `None` stays `None` (mandates off); a present-but-undecodable value fails
/// closed rather than silently disabling the mandate gate.
fn parse_mandate_issuer_key(raw: Option<String>) -> Result<Option<Vec<u8>>, PaymentsConfigError> {
    raw.map(|raw| {
        hex::decode(&raw).map_err(|e| {
            PaymentsConfigError::InvalidMandateIssuerKey(format!(
                "{ENV_MANDATE_ISSUER_PUBKEY} is not valid hex: {e}"
            ))
        })
    })
    .transpose()
}

/// Parses the per-conversation budget's dollar figure (`raw`, already
/// blank-collapsed-to-`None` by the shared `get` helper in
/// [`PaymentsConfig::from_lookup`]) into settlement-token base units at
/// `decimals`. Unset falls back to [`DEFAULT_CONVERSATION_BUDGET`]; a
/// set-but-unparseable value fails closed, exactly like the presign caps.
fn parse_conversation_budget(
    raw: Option<String>,
    decimals: u32,
) -> Result<u128, PaymentsConfigError> {
    let dollars = raw.unwrap_or_else(|| DEFAULT_CONVERSATION_BUDGET.to_owned());
    crate::amount::dollars_to_base_units(&dollars, decimals).ok_or_else(|| {
        PaymentsConfigError::InvalidConversationBudget(format!(
            "{ENV_CONVERSATION_BUDGET} value {dollars:?} is not a valid dollar amount"
        ))
    })
}

fn is_truthy(v: &str) -> bool {
    matches!(
        v.trim().to_ascii_lowercase().as_str(),
        "1" | "true" | "yes" | "on"
    )
}

/// Errors raised while building [`PaymentsConfig`] from the environment or
/// resolving the outbound client.
#[derive(Debug, thiserror::Error)]
pub enum PaymentsConfigError {
    /// `TEMPO_SIGNER_KEY` is unset or empty. Retained for callers that treat a
    /// missing key as a hard error; `from_lookup` itself no longer raises it
    /// (the raw signer is optional).
    #[error("TEMPO_SIGNER_KEY is not set")]
    MissingSignerKey,
    /// `TEMPO_SIGNER_KEY` is set but is not a valid 32-byte hex private key.
    #[error("TEMPO_SIGNER_KEY is invalid: {0}")]
    InvalidSignerKey(String),
    /// `TEMPO_FEE_PAYER_KEY` is set but is not a valid 32-byte hex private key.
    #[error("TEMPO_FEE_PAYER_KEY is invalid: {0}")]
    InvalidFeePayerKey(String),
    /// `TEMPO_CHAIN_ID` is set but is not a valid `u64`.
    #[error("TEMPO_CHAIN_ID is invalid: {0}")]
    InvalidChainId(String),
    /// `TEMPO_PRESIGN_PER_TX_CAP` / `TEMPO_PRESIGN_PER_SESSION_CAP` is set but is
    /// not a parseable dollar amount (fail closed: a misconfigured spend control
    /// must not silently become unbounded).
    #[error("pre-signing spend cap is invalid: {0}")]
    InvalidPresignCap(String),
    /// `TEMPO_CONVERSATION_BUDGET` is set but is not a parseable dollar amount
    /// (fail closed: a misconfigured budget must not silently become
    /// unbounded).
    #[error("conversation budget is invalid: {0}")]
    InvalidConversationBudget(String),
    /// `TEMPO_MAX_SPEND` is set but is not a parseable dollar amount (fail
    /// closed at load: the deployment's own default spend ceiling must never
    /// silently degrade to a figure the payment path then rejects on every
    /// call, or one wider than intended).
    #[error("TEMPO_MAX_SPEND is invalid: {0}")]
    InvalidMaxSpend(String),
    /// `TEMPO_MANDATE_ISSUER_PUBKEY` is set but is not decodable hex (fail
    /// closed: a garbled trust root must not silently disable the mandate
    /// gate).
    #[error("mandate issuer key is invalid: {0}")]
    InvalidMandateIssuerKey(String),
    /// `TEMPO_CURRENCY_DECIMALS` is set but is not a valid `u32`.
    #[error("TEMPO_CURRENCY_DECIMALS is invalid: {0}")]
    InvalidCurrencyDecimals(String),
    /// The inbound server requires `TEMPO_RECIPIENT`, which is unset.
    #[error("TEMPO_RECIPIENT is not set")]
    MissingRecipient,
    /// The inbound server requires `TEMPO_HMAC_SECRET`, which is unset.
    #[error("TEMPO_HMAC_SECRET is not set")]
    MissingHmacSecret,
    /// Keychain mode is configured but `TEMPO_CURRENCY` (the token to select the
    /// access key by) is unset.
    #[error("TEMPO_CURRENCY is required for keychain signing but is not set")]
    MissingCurrency,
    /// The INBOUND server's `TEMPO_CURRENCY` is unset and `chain_id` has no
    /// known default settlement token (issue #806's mainnet path — see
    /// [`polyc_payments_server::config::default_currency_for_chain`]).
    #[error(
        "no TEMPO_CURRENCY configured and chain id {0} has no known default settlement token; set TEMPO_CURRENCY explicitly"
    )]
    InboundMissingCurrency(u64),
    /// The configured `keys.toml` could not be read.
    #[error("keys.toml could not be read: {0}")]
    InvalidKeysFile(String),
    /// Parsing/fail-closed selection over `keys.toml` failed.
    #[error("keys.toml selection failed: {0}")]
    KeySelection(#[from] KeystoreError),
    /// A raw `TEMPO_SIGNER_KEY` is configured but `POLYCHROME_ALLOW_RAW_SIGNER`
    /// is not set — refuse rather than sign with an unbounded hot key.
    #[error(
        "raw TEMPO_SIGNER_KEY signing is disabled; set POLYCHROME_ALLOW_RAW_SIGNER=1 to allow it (prefer a keychain keys.toml)"
    )]
    RawSignerNotAllowed,
    /// No signer is configured at all (neither a keychain `keys.toml` nor a raw
    /// `TEMPO_SIGNER_KEY`).
    #[error("no outbound signer configured (set TEMPO_WALLET_KEYS_PATH or TEMPO_SIGNER_KEY)")]
    MissingSigner,
    /// The outbound client could not be built from the resolved signer.
    #[error("outbound client build failed: {0}")]
    Client(String),
}

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

    /// Anvil account #0 key and its deterministic address. The key is a public
    /// well-known test vector (not a secret); it is used only to assert that
    /// the parsed signer derives the expected address.
    const TEST_KEY_0X: &str = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
    const TEST_KEY_BARE: &str = "ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
    const TEST_ADDR: &str = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266";

    /// Builds a lookup closure backed by an in-memory map.
    fn map_lookup(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
        let map: HashMap<String, String> = pairs
            .iter()
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
            .collect();
        move |key: &str| map.get(key).cloned()
    }

    /// A value that makes `var` introduce signing material into a config.
    fn signing_value_for(var: &str) -> &'static str {
        match var {
            ENV_SIGNER_KEY | ENV_FEE_PAYER_KEY => TEST_KEY_0X,
            ENV_WALLET_KEYS_PATH => "/tmp/polychrome-test/keys.toml",
            ENV_TEMPO_HOME => "/tmp/polychrome-test-home",
            other => panic!("no test value for signer-bearing var {other}"),
        }
    }

    /// Whether `cfg` holds signing material from ANY source. Must name every
    /// signer-bearing field; a new field missing here fails the completeness
    /// invariant below.
    fn config_holds_signing_material(cfg: &PaymentsConfig) -> bool {
        cfg.signer().is_some() || cfg.fee_payer_signer().is_some() || cfg.keys_path.is_some()
    }

    // Invariant: the harness trip-wire ([`SIGNER_ENV_VARS`]) covers exactly the
    // env vars that introduce signing material — bidirectionally, so a future
    // signer field can't be forgotten from it (and no stale entry over-restricts
    // the sandbox for a non-signing var).
    #[test]
    fn signer_env_vars_covers_every_signing_key_source() {
        // Every signer-bearing var flows through `PaymentsConfig`: each must be
        // tripwired AND actually introduce signing material into the config.
        let config_signer_vars = [
            ENV_SIGNER_KEY,       // raw Direct signer
            ENV_FEE_PAYER_KEY,    // inbound fee-payer sponsor
            ENV_WALLET_KEYS_PATH, // explicit keychain keys.toml
            ENV_TEMPO_HOME,       // derives $TEMPO_HOME/wallet/keys.toml
        ];

        for var in config_signer_vars {
            assert!(
                SIGNER_ENV_VARS.contains(&var),
                "{var} carries signing material but is missing from SIGNER_ENV_VARS \
                 (the harness boot tripwire) — the untrusted sandbox could hold a signer"
            );
            let cfg = PaymentsConfig::from_lookup(map_lookup(&[(var, signing_value_for(var))]))
                .expect("config builds with a signer-bearing var set");
            assert!(
                config_holds_signing_material(&cfg),
                "{var} is listed as signer-bearing but the config shows no signing material"
            );
        }
        // Converse: every tripwire entry is a known signing-key source — no stale
        // entry that would over-restrict the sandbox for a non-signing var. A new
        // signer var added to SIGNER_ENV_VARS must be classified above too.
        for var in SIGNER_ENV_VARS {
            assert!(
                config_signer_vars.contains(var),
                "SIGNER_ENV_VARS lists {var}, which is not a classified signing-key source"
            );
        }
    }

    #[test]
    fn config_paid_host_allowlist_parses_fail_closed() {
        // Unset ⇒ None (no positive allowlist).
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[])).expect("config builds");
        assert!(cfg.paid_host_allowlist.is_none());

        // A normal list: split on commas, trimmed, lowercased, empties dropped.
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[(
            ENV_PAID_HOST_ALLOWLIST,
            " API.Foo.com, data.bar.io ,,",
        )]))
        .expect("config builds");
        assert_eq!(
            cfg.paid_host_allowlist.as_deref(),
            Some(&["api.foo.com".to_string(), "data.bar.io".to_string()][..])
        );

        // Set but degenerate (no valid hosts) ⇒ Some(empty) — an allowlist that
        // denies everything, NOT a silently-disabled control. (A fully-blank
        // value is collapsed to "unset" by the shared `get` helper, like every
        // other knob.)
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[(ENV_PAID_HOST_ALLOWLIST, " , ,")]))
            .expect("config builds");
        assert_eq!(cfg.paid_host_allowlist.as_deref(), Some(&[][..]));
    }

    #[test]
    fn config_presign_caps_parse_to_base_units_and_fail_closed() {
        // Unset ⇒ an unlimited pre-authorization (no pre-signing cap).
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[])).expect("config builds");
        assert!(cfg.presign_spend_cap().is_unlimited());

        // Dollar strings are scaled to base units at the configured decimals
        // (default 6): $0.50 → 500000, $5.00 → 5000000.
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[
            (ENV_PRESIGN_PER_TX_CAP, "0.50"),
            (ENV_PRESIGN_PER_SESSION_CAP, "5.00"),
        ]))
        .expect("config builds");
        let cap = cfg.presign_spend_cap();
        assert_eq!(cap.per_tx(), Some(500_000));
        assert_eq!(cap.per_session(), Some(5_000_000));

        // A set-but-unparseable cap fails closed at load — a spend control must
        // never silently degrade to unbounded.
        assert!(matches!(
            PaymentsConfig::from_lookup(map_lookup(&[(ENV_PRESIGN_PER_TX_CAP, "not-a-number")])),
            Err(PaymentsConfigError::InvalidPresignCap(_))
        ));
    }

    #[test]
    fn config_conversation_budget_defaults_and_parses_to_base_units() {
        // Unset ⇒ the built-in default ($1.00) scaled to base units.
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[])).expect("config builds");
        assert_eq!(cfg.conversation_budget_base_units(), 1_000_000);

        // Set ⇒ that dollar figure scaled at the configured decimals.
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[(ENV_CONVERSATION_BUDGET, "2.50")]))
            .expect("config builds");
        assert_eq!(cfg.conversation_budget_base_units(), 2_500_000);

        // A set-but-unparseable budget fails closed at load — a misconfigured
        // budget must never silently become unbounded.
        assert!(matches!(
            PaymentsConfig::from_lookup(map_lookup(&[(ENV_CONVERSATION_BUDGET, "not-a-number")])),
            Err(PaymentsConfigError::InvalidConversationBudget(_))
        ));
    }

    #[test]
    fn config_default_max_spend_falls_back_to_the_built_in_ceiling() {
        // No TEMPO_MAX_SPEND ⇒ the same built-in DEFAULT_CAP ("0.10") the
        // proxy itself falls back to on a call with no per-call max_spend.
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[])).expect("config builds");
        assert_eq!(cfg.default_max_spend_base_units(), 100_000);

        // TEMPO_MAX_SPEND set ⇒ that figure scaled to base units, not the
        // built-in default.
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[(ENV_MAX_SPEND, "0.25")]))
            .expect("config builds");
        assert_eq!(cfg.default_max_spend_base_units(), 250_000);
    }

    /// A set-but-unparseable `TEMPO_MAX_SPEND` fails config LOAD, not just
    /// every subsequent payment call. Before this, a garbled deployment cap
    /// loaded fine, `resolve_cap_base_units` (`proxy.rs`) rejected every
    /// real payment against it (`RejectReason::InvalidMaxSpend`), and
    /// `default_max_spend_base_units` silently reported the built-in
    /// `DEFAULT_CAP` as though it were spendable — a deployment that in fact
    /// refuses every payment would have shown the wallet page a real-looking
    /// ceiling. Failing at load closes that gap: the two surfaces can no
    /// longer disagree about whether the configured cap works at all.
    #[test]
    fn config_load_fails_closed_on_an_unparseable_default_max_spend() {
        assert!(matches!(
            PaymentsConfig::from_lookup(map_lookup(&[(ENV_MAX_SPEND, "not-a-number")])),
            Err(PaymentsConfigError::InvalidMaxSpend(_))
        ));
        // An overflowing magnitude fails the same way as the presign caps and
        // the conversation budget do.
        let overflowing = "999999999999999999999999999999999999999999999999999999";
        assert!(matches!(
            PaymentsConfig::from_lookup(map_lookup(&[(ENV_MAX_SPEND, overflowing)])),
            Err(PaymentsConfigError::InvalidMaxSpend(_))
        ));
    }

    /// Consistency: the ceiling `build_outbound_payment_ctx` hands the spend
    /// authority is the SAME figure
    /// [`PaymentsConfig::conversation_budget_base_units`] reports to the wallet
    /// page. Both derive from this one accessor — this test pins that they
    /// cannot drift apart even if a future edit re-introduces a second
    /// `TEMPO_CONVERSATION_BUDGET` read somewhere.
    #[test]
    fn the_conversation_budget_accessor_is_the_only_ceiling_reader() {
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[(ENV_CONVERSATION_BUDGET, "3.00")]))
            .expect("config builds");
        assert_eq!(cfg.conversation_budget_base_units(), 3_000_000);
    }

    #[test]
    fn config_mandate_issuer_key_parses_and_fails_closed() {
        // Unset ⇒ None: mandates are OFF by default (the presented-chain
        // gate never engages; zero behavior change).
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[])).expect("config builds");
        assert!(cfg.mandate_issuer_public_key().is_none());

        // A valid hex key decodes to its bytes.
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[(
            ENV_MANDATE_ISSUER_PUBKEY,
            "deadbeef00112233",
        )]))
        .expect("config builds");
        assert_eq!(
            cfg.mandate_issuer_public_key(),
            Some(&[0xde, 0xad, 0xbe, 0xef, 0x00, 0x11, 0x22, 0x33][..])
        );

        // Set-but-undecodable fails closed at load — a garbled trust root
        // must never silently disable the mandate gate.
        assert!(matches!(
            PaymentsConfig::from_lookup(map_lookup(&[(ENV_MANDATE_ISSUER_PUBKEY, "not-hex")])),
            Err(PaymentsConfigError::InvalidMandateIssuerKey(_))
        ));
    }

    #[test]
    fn config_currency_decimals_bounded_to_mpp_ceiling() {
        // Unset ⇒ the default scale.
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[])).expect("config builds");
        assert_eq!(cfg.currency_decimals, crate::amount::DEFAULT_DECIMALS);

        // The tempo-MPP ceiling (38) is accepted.
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[(ENV_CURRENCY_DECIMALS, "38")]))
            .expect("38 is the max and must parse");
        assert_eq!(cfg.currency_decimals, MAX_CURRENCY_DECIMALS);

        // Above the ceiling ⇒ fail closed at config time (no downstream panic).
        assert!(matches!(
            PaymentsConfig::from_lookup(map_lookup(&[(ENV_CURRENCY_DECIMALS, "39")])),
            Err(PaymentsConfigError::InvalidCurrencyDecimals(_))
        ));

        // Non-numeric ⇒ the same error variant.
        assert!(matches!(
            PaymentsConfig::from_lookup(map_lookup(&[(ENV_CURRENCY_DECIMALS, "abc")])),
            Err(PaymentsConfigError::InvalidCurrencyDecimals(_))
        ));
    }

    #[test]
    fn config_from_env_reads_signer_key() {
        // 0x-prefixed form.
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[(ENV_SIGNER_KEY, TEST_KEY_0X)]))
            .expect("0x key should parse");
        assert_eq!(format!("{}", cfg.signer().unwrap().address()), TEST_ADDR);

        // Bare (no 0x) form parses to the same address.
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[(ENV_SIGNER_KEY, TEST_KEY_BARE)]))
            .expect("bare key should parse");
        assert_eq!(format!("{}", cfg.signer().unwrap().address()), TEST_ADDR);

        // Surrounding whitespace is trimmed.
        let padded = format!("  {TEST_KEY_0X}\n");
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[(ENV_SIGNER_KEY, &padded)]))
            .expect("whitespace-padded key should parse");
        assert_eq!(format!("{}", cfg.signer().unwrap().address()), TEST_ADDR);
    }

    #[test]
    fn config_signer_key_is_optional_but_validated() {
        // Unset → no signer (keychain/inbound-only deployments).
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[])).expect("unset signer is allowed");
        assert!(cfg.signer().is_none());

        // Blank is treated as absent, not an error.
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[(ENV_SIGNER_KEY, "   ")]))
            .expect("blank signer is allowed");
        assert!(cfg.signer().is_none());

        // Present-but-non-hex still fails loud (a typo'd key is an error).
        match PaymentsConfig::from_lookup(map_lookup(&[(ENV_SIGNER_KEY, "not-hex")])) {
            Err(PaymentsConfigError::InvalidSignerKey(_)) => {}
            other => panic!("expected InvalidSignerKey, got {other:?}"),
        }
    }

    #[test]
    fn config_defaults_to_moderato() {
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[(ENV_SIGNER_KEY, TEST_KEY_0X)]))
            .expect("defaults");
        assert_eq!(cfg.rpc_url, MODERATO_RPC_URL);
        assert_eq!(cfg.chain_id, MODERATO_CHAIN_ID);

        // Overrides are honored.
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[
            (ENV_SIGNER_KEY, TEST_KEY_0X),
            (ENV_RPC_URL, "https://rpc.example.test"),
            (ENV_CHAIN_ID, "12345"),
        ]))
        .expect("overrides");
        assert_eq!(cfg.rpc_url, "https://rpc.example.test");
        assert_eq!(cfg.chain_id, 12345);
    }

    #[test]
    fn config_reads_optional_max_spend() {
        // Absent by default (the tool falls back to its built-in ceiling).
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[(ENV_SIGNER_KEY, TEST_KEY_0X)]))
            .expect("defaults");
        assert!(cfg.max_spend.is_none());

        // Honored when set; blank is treated as absent.
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[
            (ENV_SIGNER_KEY, TEST_KEY_0X),
            (ENV_MAX_SPEND, "0.25"),
        ]))
        .expect("max_spend");
        assert_eq!(cfg.max_spend.as_deref(), Some("0.25"));

        let cfg = PaymentsConfig::from_lookup(map_lookup(&[
            (ENV_SIGNER_KEY, TEST_KEY_0X),
            (ENV_MAX_SPEND, "   "),
        ]))
        .expect("blank max_spend");
        assert!(
            cfg.max_spend.is_none(),
            "blank max_spend is treated as absent"
        );
    }

    #[test]
    fn config_reads_recipient_and_realm() {
        // Defaults: no recipient/hmac, realm defaults to "polychrome".
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[(ENV_SIGNER_KEY, TEST_KEY_0X)]))
            .expect("defaults");
        assert_eq!(cfg.realm, "polychrome");
        assert!(cfg.recipient.is_none());
        assert!(cfg.hmac_secret().is_none());
        assert!(matches!(
            cfg.require_recipient(),
            Err(PaymentsConfigError::MissingRecipient)
        ));
        assert!(matches!(
            cfg.require_hmac_secret(),
            Err(PaymentsConfigError::MissingHmacSecret)
        ));

        // Populated: recipient, realm override, hmac secret.
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[
            (ENV_SIGNER_KEY, TEST_KEY_0X),
            (ENV_RECIPIENT, "0xabc0000000000000000000000000000000000def"),
            (ENV_REALM, "custom-realm"),
            (ENV_HMAC_SECRET, "super-secret-hmac"),
        ]))
        .expect("populated");
        assert_eq!(
            cfg.require_recipient().unwrap(),
            "0xabc0000000000000000000000000000000000def"
        );
        assert_eq!(cfg.realm, "custom-realm");
        assert_eq!(cfg.require_hmac_secret().unwrap(), "super-secret-hmac");
    }

    #[test]
    fn config_explorer_url_defaults_to_moderato_testnet() {
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[(ENV_SIGNER_KEY, TEST_KEY_0X)]))
            .expect("defaults");
        assert_eq!(cfg.explorer_url, "https://explore.testnet.tempo.xyz");
    }

    #[test]
    fn config_explorer_url_override_is_honored() {
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[
            (ENV_SIGNER_KEY, TEST_KEY_0X),
            (ENV_EXPLORER_URL, "https://explorer.example.test"),
        ]))
        .expect("override");
        assert_eq!(cfg.explorer_url, "https://explorer.example.test");
    }

    #[test]
    fn signer_key_never_logged() {
        let cfg = PaymentsConfig::from_lookup(map_lookup(&[
            (ENV_SIGNER_KEY, TEST_KEY_0X),
            (ENV_HMAC_SECRET, "super-secret-hmac"),
        ]))
        .expect("config");
        let dbg = format!("{cfg:?}");

        // The raw private key hex must never appear (either form).
        assert!(
            !dbg.contains(TEST_KEY_BARE),
            "Debug leaked signer key: {dbg}"
        );
        assert!(!dbg.contains(TEST_KEY_0X), "Debug leaked signer key: {dbg}");
        // The HMAC secret must never appear.
        assert!(
            !dbg.contains("super-secret-hmac"),
            "Debug leaked hmac secret: {dbg}"
        );
        // The wallet address must not appear — Debug must not disclose it.
        assert!(
            !dbg.contains(TEST_ADDR),
            "Debug leaked wallet address: {dbg}"
        );
        assert!(
            !dbg.contains("signer_address"),
            "Debug must not include a signer_address field: {dbg}"
        );
        // Redaction markers should be present.
        assert!(dbg.contains("<redacted>"), "Debug missing redaction: {dbg}");
    }
}