Skip to main content

foundry_common/provider/mpp/
transport.rs

1//! Foundry policy for the canonical MPP Alloy HTTP transport.
2
3use alloy_chains::Chain;
4use alloy_json_rpc::{RequestPacket, ResponsePacket, RpcError};
5use alloy_transport::{TransportError, TransportErrorKind, TransportFut};
6use alloy_transport_mpp::{MppHttpTransport, MppWsConnect};
7use mpp::{
8    MppError, PaymentErrorDetails,
9    client::{
10        PaymentContext, PaymentProvider, TempoAccountsProvider,
11        tempo::{
12            autoswap::{AutoswapConfig, DEFAULT_SLIPPAGE_BPS},
13            session::store::{SqliteChannelStore, SqliteChannelStoreOptions},
14        },
15    },
16    protocol::{
17        core::{PaymentChallenge, PaymentCredential},
18        intents::{ChargeRequest, SessionRequest},
19        methods::tempo::{TempoChargeExt, TempoSessionExt},
20    },
21};
22use std::{
23    collections::HashMap,
24    env, fmt, io,
25    io::IsTerminal,
26    process::{Command, Stdio},
27    sync::{Arc, Mutex, MutexGuard, PoisonError},
28    task,
29};
30use tempo_alloy::accounts::{TempoAccountsError, TempoAccountsStore, TempoAccountsWallet};
31use tower::Service;
32use url::Url;
33
34/// Keep high-fanout fork database reads from overwhelming paid RPC endpoints.
35const MAX_CONCURRENT_MPP_HTTP_REQUESTS: usize = 4;
36
37/// Open a channel with 0.02 tokens when the server does not suggest a deposit.
38const DEFAULT_MPP_SESSION_DEPOSIT: u128 = 20_000;
39
40/// Never let a paid RPC reserve more than one six-decimal token automatically.
41const MAX_MPP_SESSION_DEPOSIT: u128 = 1_000_000;
42
43/// The MPP transport used by Foundry's runtime transport builder.
44#[derive(Clone, Debug)]
45pub struct LazyMppHttpTransport(MppHttpTransport<LazyAccountsProvider>);
46
47impl LazyMppHttpTransport {
48    /// Create a transport that opens Tempo Accounts only after a paid challenge. Without
49    /// `payments`, 402 challenges are never paid and no funding flow is started.
50    pub fn lazy(
51        client: reqwest::Client,
52        url: Url,
53        headers: reqwest::header::HeaderMap,
54        payments: bool,
55    ) -> Self {
56        let provider = LazyAccountsProvider::new(url.to_string(), payments);
57        Self(
58            MppHttpTransport::new(client, url, provider)
59                .with_headers(headers)
60                .with_max_concurrent_requests(MAX_CONCURRENT_MPP_HTTP_REQUESTS),
61        )
62    }
63
64    /// Return the underlying HTTP client.
65    pub const fn client(&self) -> &reqwest::Client {
66        self.0.client()
67    }
68}
69
70impl Service<RequestPacket> for LazyMppHttpTransport {
71    type Response = ResponsePacket;
72    type Error = TransportError;
73    type Future = TransportFut<'static>;
74
75    fn poll_ready(&mut self, cx: &mut task::Context<'_>) -> task::Poll<Result<(), Self::Error>> {
76        self.0.poll_ready(cx)
77    }
78
79    fn call(&mut self, request: RequestPacket) -> Self::Future {
80        let retry = request.clone();
81        let mut transport = self.0.clone();
82        let provider = self.0.payment_provider().clone();
83        Box::pin(async move {
84            match transport.call(request).await {
85                Err(error) => {
86                    let Some(problem) = insufficient_balance_details(&error).filter(|problem| {
87                        provider.payments && problem.problem_type.ends_with("/insufficient-balance")
88                    }) else {
89                        return Err(error);
90                    };
91                    let context = provider.take_funding_context(problem.challenge_id.as_deref());
92                    if run_interactive_tempo_fund(&context)
93                        .await
94                        .map_err(TransportErrorKind::custom)?
95                    {
96                        match transport.call(retry).await {
97                            Err(error) => {
98                                let Some(problem) =
99                                    insufficient_balance_details(&error).filter(|problem| {
100                                        problem.problem_type.ends_with("/insufficient-balance")
101                                    })
102                                else {
103                                    return Err(error);
104                                };
105                                let context =
106                                    provider.take_funding_context(problem.challenge_id.as_deref());
107                                Err(with_transport_funding_help(error, &context))
108                            }
109                            result => result,
110                        }
111                    } else {
112                        Err(with_transport_funding_help(error, &context))
113                    }
114                }
115                result => result,
116            }
117        })
118    }
119}
120
121/// Build the canonical MPP WebSocket connector with Foundry's lazy Accounts
122/// provider. Without `payments`, a challenge closes the connection without paying.
123pub(crate) fn lazy_mpp_ws_connect(url: &Url, payments: bool) -> MppWsConnect<LazyAccountsProvider> {
124    let mut origin = url.clone();
125    let http_scheme = match origin.scheme() {
126        "ws" => Some("http"),
127        "wss" => Some("https"),
128        _ => None,
129    };
130    if let Some(http_scheme) = http_scheme {
131        let _ = origin.set_scheme(http_scheme);
132    }
133    MppWsConnect::new(url.to_string(), LazyAccountsProvider::new(origin.to_string(), payments))
134}
135
136/// Lazily resolves a chain-bound MPP Charge provider from Tempo Accounts.
137///
138/// HTTP payment mechanics live in `alloy-transport-mpp`; this wrapper contains
139/// only Foundry CLI policy: account-store discovery, optional interactive login
140/// and funding, and session channel configuration.
141#[derive(Clone)]
142pub struct LazyAccountsProvider {
143    inner: Arc<Mutex<HashMap<Option<u64>, TempoAccountsProvider>>>,
144    funding_by_challenge: Arc<Mutex<HashMap<String, FundingContext>>>,
145    origin: String,
146    /// Whether 402 challenges from `origin` may be paid.
147    payments: bool,
148}
149
150impl fmt::Debug for LazyAccountsProvider {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        f.debug_struct("LazyAccountsProvider")
153            .field("origin", &redacted_url(&self.origin))
154            .finish_non_exhaustive()
155    }
156}
157
158impl LazyAccountsProvider {
159    /// Create a provider for payments requested by `origin`. Without `payments`, 402 challenges
160    /// are never paid.
161    pub fn new(origin: String, payments: bool) -> Self {
162        Self {
163            inner: Arc::new(Mutex::new(HashMap::new())),
164            funding_by_challenge: Arc::new(Mutex::new(HashMap::new())),
165            origin,
166            payments,
167        }
168    }
169
170    fn resolve(&self, chain_id: Option<u64>) -> Result<TempoAccountsProvider, MppError> {
171        let mut providers = lock_map(&self.inner);
172        if let Some(provider) = providers.get(&chain_id) {
173            return Ok(provider.clone());
174        }
175
176        let mut provider = TempoAccountsProvider::from_default_store().map_err(|error| {
177            MppError::InvalidConfig(format!(
178                "RPC endpoint returned HTTP 402 Payment Required, but the Tempo Accounts store \
179                 could not provide a Charge wallet: {error}\n\nAuthorize an access key with:\n  \
180                 cast tempo login\n\nIn a headless environment, use:\n  cast tempo login --no-browser"
181            ))
182        })?;
183        if let Some(chain_id) = chain_id {
184            provider = provider.with_expected_chain_id(chain_id);
185        }
186        let request_url =
187            Url::parse(&self.origin).map_err(|error| MppError::InvalidConfig(error.to_string()))?;
188        let store = SqliteChannelStore::open(SqliteChannelStoreOptions {
189            namespace: request_url.origin().ascii_serialization(),
190            path: None,
191            request_url: Some(redacted_url(&self.origin)),
192        })
193        .map_err(|error| {
194            MppError::InvalidConfig(format!("failed to open Tempo channel store: {error}"))
195        })?;
196        provider = provider
197            .with_autoswap(AutoswapConfig::new(
198                crate::tempo::PATH_USD_ADDRESS,
199                DEFAULT_SLIPPAGE_BPS,
200            ))
201            .with_session_store(Arc::new(store))
202            .with_session_default_deposit(DEFAULT_MPP_SESSION_DEPOSIT)
203            .with_session_top_up_amount(DEFAULT_MPP_SESSION_DEPOSIT)
204            .with_session_max_deposit(MAX_MPP_SESSION_DEPOSIT);
205        providers.insert(chain_id, provider.clone());
206        Ok(provider)
207    }
208
209    fn invalidate(&self) {
210        lock_map(&self.inner).clear();
211    }
212
213    fn funding_context(&self, challenge: &PaymentChallenge) -> FundingContext {
214        let (chain_id, token) = extract_challenge_chain_and_currency(challenge);
215        let context = FundingContext {
216            wallet_address: lock_map(&self.inner)
217                .values()
218                .next()
219                .and_then(|provider| provider.wallet().active_account().ok())
220                .or_else(|| {
221                    TempoAccountsStore::try_open_default().ok().flatten()?.active_account().ok()
222                }),
223            token,
224            chain_id: chain_id.map(Chain::from_id),
225        };
226        let mut contexts = lock_map(&self.funding_by_challenge);
227        if contexts.len() >= 32
228            && !contexts.contains_key(&challenge.id)
229            && let Some(oldest) = contexts.keys().next().cloned()
230        {
231            contexts.remove(&oldest);
232        }
233        contexts.insert(challenge.id.clone(), context.clone());
234        context
235    }
236
237    fn take_funding_context(&self, challenge_id: Option<&str>) -> FundingContext {
238        let mut contexts = lock_map(&self.funding_by_challenge);
239        let context =
240            challenge_id.and_then(|challenge_id| contexts.remove(challenge_id)).or_else(|| {
241                (contexts.len() == 1)
242                    .then(|| contexts.keys().next().cloned())
243                    .flatten()
244                    .and_then(|challenge_id| contexts.remove(&challenge_id))
245            });
246        context.unwrap_or_else(|| FundingContext {
247            wallet_address: TempoAccountsStore::try_open_default()
248                .ok()
249                .flatten()
250                .and_then(|store| store.active_account().ok()),
251            ..Default::default()
252        })
253    }
254
255    async fn needs_access_key(
256        &self,
257        challenge: &PaymentChallenge,
258        chain_id: u64,
259    ) -> Result<bool, MppError> {
260        match TempoAccountsStore::try_open_default() {
261            Ok(None) => Ok(true),
262            Ok(Some(_)) => {
263                let provider = self.resolve(Some(chain_id))?;
264                has_access_key_for_challenge(&provider, challenge, chain_id)
265                    .await
266                    .map(|has_access_key| !has_access_key)
267            }
268            Err(error) => Err(MppError::InvalidConfig(format!(
269                "failed to inspect Tempo Accounts store: {error}"
270            ))),
271        }
272    }
273}
274
275impl PaymentProvider for LazyAccountsProvider {
276    fn supports(&self, method: &str, intent: &str) -> bool {
277        self.payments && method == "tempo" && matches!(intent, "session" | "charge")
278    }
279
280    async fn pay(&self, challenge: &PaymentChallenge) -> Result<PaymentCredential, MppError> {
281        let (chain_id, _) = extract_challenge_chain_and_currency(challenge);
282        let provider = self.resolve(chain_id)?;
283        match provider.pay(challenge).await {
284            Ok(credential) => Ok(credential),
285            Err(error @ MppError::InsufficientBalance(_)) => {
286                let context = self.funding_context(challenge);
287                if run_interactive_tempo_fund(&context).await? {
288                    provider.pay(challenge).await
289                } else {
290                    Err(with_funding_help(error, &context))
291                }
292            }
293            Err(error) => Err(error),
294        }
295    }
296
297    async fn pay_with_context(
298        &self,
299        challenge: &PaymentChallenge,
300        context: PaymentContext,
301    ) -> Result<PaymentCredential, MppError> {
302        let (chain_id, _) = extract_challenge_chain_and_currency(challenge);
303        let provider = self.resolve(chain_id)?;
304        match provider.pay_with_context(challenge, context.clone()).await {
305            Ok(credential) => Ok(credential),
306            Err(error @ MppError::InsufficientBalance(_)) => {
307                let funding = self.funding_context(challenge);
308                if run_interactive_tempo_fund(&funding).await? {
309                    provider.pay_with_context(challenge, context).await
310                } else {
311                    Err(with_funding_help(error, &funding))
312                }
313            }
314            Err(error) => Err(error),
315        }
316    }
317
318    async fn prepare_http_payment_challenge(
319        &self,
320        challenge: &PaymentChallenge,
321        _context: PaymentContext,
322    ) -> Result<Option<PaymentChallenge>, MppError> {
323        self.funding_context(challenge);
324        let (Some(chain_id), _) = extract_challenge_chain_and_currency(challenge) else {
325            return Ok(Some(challenge.clone()));
326        };
327        if !interactive_login_allowed()
328            || !Url::parse(&self.origin)
329                .is_ok_and(|origin| crate::tempo::is_known_tempo_endpoint(&origin))
330        {
331            return Ok(Some(challenge.clone()));
332        }
333
334        if !self.needs_access_key(challenge, chain_id).await? {
335            return Ok(Some(challenge.clone()));
336        }
337
338        let config = crate::tempo::EnsureAccessKeyConfig::from_env(chain_id);
339        crate::tempo::ensure_access_key(config).await.map_err(|error| {
340            MppError::InvalidConfig(format!("Tempo access key authorization failed: {error}"))
341        })?;
342        self.invalidate();
343        Ok(None)
344    }
345
346    async fn commit_payment(
347        &self,
348        challenge: &PaymentChallenge,
349        credential: &PaymentCredential,
350    ) -> Result<(), MppError> {
351        lock_map(&self.funding_by_challenge).remove(&challenge.id);
352        let (chain_id, _) = extract_challenge_chain_and_currency(challenge);
353        self.resolve(chain_id)?.commit_payment(challenge, credential).await
354    }
355
356    async fn rollback_payment(
357        &self,
358        challenge: &PaymentChallenge,
359        credential: &PaymentCredential,
360    ) -> Result<(), MppError> {
361        let (chain_id, _) = extract_challenge_chain_and_currency(challenge);
362        self.resolve(chain_id)?.rollback_payment(challenge, credential).await
363    }
364
365    fn abandon_payment(&self, challenge: &PaymentChallenge, credential: &PaymentCredential) {
366        let (chain_id, _) = extract_challenge_chain_and_currency(challenge);
367        if let Ok(provider) = self.resolve(chain_id) {
368            provider.abandon_payment(challenge, credential);
369        }
370    }
371
372    fn accept_payment_header(&self) -> Option<String> {
373        self.payments.then(|| "tempo/session, tempo/charge;q=0.5".to_owned())
374    }
375}
376
377async fn has_access_key_for_challenge(
378    provider: &TempoAccountsProvider,
379    challenge: &PaymentChallenge,
380    chain_id: u64,
381) -> Result<bool, MppError> {
382    if challenge.intent.as_str() == "charge" {
383        return provider.has_access_key_for_challenge(challenge).await;
384    }
385    // Read the store with Foundry's own `tempo-alloy` rather than through `provider.wallet()`:
386    // mpp may link a different `tempo-alloy`, whose error type Foundry cannot match on.
387    let wallet = TempoAccountsWallet::from_default_store().map_err(|error| {
388        MppError::InvalidConfig(format!("failed to open Tempo Accounts store: {error}"))
389    })?;
390    match wallet.with_chain_id(chain_id).active_access_key() {
391        Ok(_) => Ok(true),
392        Err(TempoAccountsError::MissingAccessKey { .. }) => Ok(false),
393        Err(error) => Err(MppError::InvalidConfig(format!(
394            "failed to inspect Tempo Accounts access key: {error}"
395        ))),
396    }
397}
398
399#[derive(Clone, Debug, Default)]
400struct FundingContext {
401    wallet_address: Option<alloy_primitives::Address>,
402    token: Option<String>,
403    chain_id: Option<Chain>,
404}
405
406impl FundingContext {
407    fn help(&self) -> String {
408        let mut command = "tempo wallet fund".to_owned();
409        if let Some(address) = self.wallet_address {
410            command.push_str(&format!(" --address {address}"));
411        }
412        if let Some(chain) = self.chain_id.filter(|chain| chain.is_tempo()) {
413            command.push_str(&format!(" --network {chain}"));
414        }
415        let token = self
416            .token
417            .as_ref()
418            .map(|token| format!("Requested payment token: {token}\n\n"))
419            .unwrap_or_default();
420        format!(
421            "\n\nTempo wallet payment could not be funded for this paid RPC request.\n\n{token}\
422             Fund the wallet, then rerun the command:\n  {command}\n\n\
423             If this CLI is running on a remote or headless host, use:\n  {command} --no-browser"
424        )
425    }
426}
427
428fn with_funding_help(error: MppError, context: &FundingContext) -> MppError {
429    MppError::InsufficientBalance(Some(format!("{error}{}", context.help())))
430}
431
432fn insufficient_balance_details(error: &TransportError) -> Option<PaymentErrorDetails> {
433    let RpcError::Transport(kind) = error else {
434        return None;
435    };
436    let http = kind.as_http_error().filter(|http| http.status == 402)?;
437    let mut deserializer = serde_json::Deserializer::from_str(&http.body);
438    <PaymentErrorDetails as serde::Deserialize>::deserialize(&mut deserializer).ok()
439}
440
441fn with_transport_funding_help(error: TransportError, context: &FundingContext) -> TransportError {
442    match error {
443        RpcError::Transport(TransportErrorKind::HttpError(http)) => {
444            TransportErrorKind::http_error(http.status, format!("{}{}", http.body, context.help()))
445        }
446        error => error,
447    }
448}
449
450fn interactive_login_allowed() -> bool {
451    !cfg!(test) && env::var_os("CI").is_none() && io::stderr().is_terminal()
452}
453
454fn interactive_fund_allowed() -> bool {
455    if cfg!(test) || env::var_os("CI").is_some() {
456        return false;
457    }
458    if env::var("FOUNDRY_MPP_NO_AUTO_FUND").ok().is_some_and(|value| {
459        !(value == "0" || value.eq_ignore_ascii_case("false") || value.eq_ignore_ascii_case("off"))
460    }) {
461        return false;
462    }
463    io::stdin().is_terminal() && io::stderr().is_terminal()
464}
465
466async fn run_interactive_tempo_fund(context: &FundingContext) -> Result<bool, MppError> {
467    if !interactive_fund_allowed() {
468        return Ok(false);
469    }
470
471    let binary = env::var("TEMPO_BIN").unwrap_or_else(|_| "tempo".to_owned());
472    let mut args = vec!["wallet".to_owned(), "fund".to_owned()];
473    if let Some(address) = context.wallet_address {
474        args.push("--address".to_owned());
475        args.push(address.to_string());
476    }
477    if let Some(chain) = context.chain_id.filter(|chain| chain.is_tempo()) {
478        args.push("--network".to_owned());
479        args.push(chain.to_string());
480    }
481    let help = context.help();
482    let status = tokio::task::spawn_blocking(move || {
483        Command::new(binary)
484            .args(args)
485            .stdin(Stdio::inherit())
486            .stdout(Stdio::inherit())
487            .stderr(Stdio::inherit())
488            .status()
489    })
490    .await
491    .map_err(|error| MppError::InvalidConfig(format!("failed to join wallet fund: {error}{help}")))?
492    .map_err(|error| {
493        MppError::InvalidConfig(format!("failed to run wallet fund: {error}{help}"))
494    })?;
495    if status.success() {
496        Ok(true)
497    } else {
498        Err(MppError::InvalidConfig(format!("wallet fund exited with status {status}{help}")))
499    }
500}
501
502/// Extract `(chainId, currency)` from a Tempo Charge or Session challenge.
503pub(super) fn extract_challenge_chain_and_currency(
504    challenge: &PaymentChallenge,
505) -> (Option<u64>, Option<String>) {
506    if challenge.method.as_str() != "tempo" {
507        return (None, None);
508    }
509    match challenge.intent.as_str() {
510        "charge" => challenge
511            .request
512            .decode::<ChargeRequest>()
513            .map(|request| (request.chain_id(), Some(request.currency)))
514            .unwrap_or_default(),
515        "session" => challenge
516            .request
517            .decode::<SessionRequest>()
518            .map(|request| (request.chain_id(), Some(request.currency)))
519            .unwrap_or_default(),
520        _ => (None, None),
521    }
522}
523
524fn lock_map<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
525    mutex.lock().unwrap_or_else(PoisonError::into_inner)
526}
527
528fn redacted_url(raw: &str) -> String {
529    let Ok(mut redacted) = Url::parse(raw) else {
530        return "<invalid>".to_owned();
531    };
532    let _ = redacted.set_username("");
533    let _ = redacted.set_password(None);
534    redacted.set_query(None);
535    redacted.to_string()
536}
537
538#[cfg(test)]
539mod tests {
540    use super::*;
541    use mpp::protocol::core::{Base64UrlJson, IntentName, MethodName};
542
543    fn challenge(method: &str, intent: &str) -> PaymentChallenge {
544        PaymentChallenge {
545            id: "test".to_owned(),
546            realm: "rpc.example".to_owned(),
547            method: MethodName::new(method),
548            intent: IntentName::new(intent),
549            request: Base64UrlJson::from_value(&serde_json::json!({
550                "amount": "1",
551                "currency": "0x20c0000000000000000000000000000000000000",
552                "recipient": "0x0000000000000000000000000000000000000001",
553                "methodDetails": {"chainId": 42431}
554            }))
555            .unwrap(),
556            expires: None,
557            description: None,
558            digest: None,
559            opaque: None,
560            header: None,
561        }
562    }
563
564    #[test]
565    fn extracts_tempo_charge_routing() {
566        assert_eq!(
567            extract_challenge_chain_and_currency(&challenge("tempo", "charge")),
568            (Some(42431), Some("0x20c0000000000000000000000000000000000000".to_owned()))
569        );
570        assert_eq!(
571            extract_challenge_chain_and_currency(&challenge("tempo", "session")),
572            (Some(42431), Some("0x20c0000000000000000000000000000000000000".to_owned()))
573        );
574        assert_eq!(
575            extract_challenge_chain_and_currency(&challenge("stripe", "charge")),
576            (None, None)
577        );
578    }
579
580    #[test]
581    fn advertises_sessions_before_charges() {
582        let provider = LazyAccountsProvider::new("https://rpc.example".to_owned(), true);
583        assert_eq!(
584            provider.accept_payment_header().as_deref(),
585            Some("tempo/session, tempo/charge;q=0.5")
586        );
587
588        // Endpoints without payments must not advertise or accept any challenge.
589        let provider = LazyAccountsProvider::new("https://rpc.example".to_owned(), false);
590        assert_eq!(provider.accept_payment_header(), None);
591        assert!(!provider.supports("tempo", "session"));
592        assert!(!provider.supports("tempo", "charge"));
593    }
594
595    #[test]
596    fn debug_redacts_origin_secrets() {
597        let provider = LazyAccountsProvider::new(
598            "https://user:password@example.com/rpc?token=secret".to_owned(),
599            true,
600        );
601        let debug = format!("{provider:?}");
602        assert!(!debug.contains("password"));
603        assert!(!debug.contains("secret"));
604        assert!(debug.contains("https://example.com/rpc"));
605    }
606
607    #[tokio::test]
608    async fn missing_accounts_store_is_detected_before_provider_resolution() {
609        let _guard = crate::tempo::test_env_mutex().lock().await;
610        let directory = tempfile::tempdir().unwrap();
611        // SAFETY: serialized with every other test that mutates TEMPO_HOME.
612        unsafe { env::set_var(crate::tempo::TEMPO_HOME_ENV, directory.path()) };
613
614        let provider = LazyAccountsProvider::new("https://rpc.mpp.tempo.xyz".to_owned(), true);
615        assert!(provider.needs_access_key(&challenge("tempo", "charge"), 42431).await.unwrap());
616        assert!(lock_map(&provider.inner).is_empty());
617
618        // SAFETY: serialized with every other test that mutates TEMPO_HOME.
619        unsafe { env::remove_var(crate::tempo::TEMPO_HOME_ENV) };
620    }
621
622    #[test]
623    fn recognizes_structured_insufficient_balance_with_http_diagnostics() {
624        let error = TransportErrorKind::http_error(
625            402,
626            concat!(
627                r#"{"type":"https://paymentauth.org/problems/insufficient-balance","#,
628                r#""title":"Insufficient Balance","status":402,"detail":"fund me"}"#,
629                "\n\nHTTP diagnostics:\nserver: test"
630            )
631            .to_owned(),
632        );
633        let problem = insufficient_balance_details(&error).unwrap();
634        assert!(problem.problem_type.ends_with("/insufficient-balance"));
635    }
636
637    #[test]
638    fn appends_funding_help_to_structured_402() {
639        let error = TransportErrorKind::http_error(
640            402,
641            r#"{"type":"https://paymentauth.org/problems/insufficient-balance"}"#.to_owned(),
642        );
643        let error = with_transport_funding_help(
644            error,
645            &FundingContext {
646                token: Some("0x20c0000000000000000000000000000000000000".to_owned()),
647                chain_id: Some(Chain::from_id(42431)),
648                ..Default::default()
649            },
650        );
651        let RpcError::Transport(kind) = error else { panic!("expected transport error") };
652        let http = kind.as_http_error().expect("expected HTTP error");
653        assert_eq!(http.status, 402);
654        assert!(http.body.contains("insufficient-balance"));
655        assert!(http.body.contains("Requested payment token"));
656        assert!(http.body.contains("tempo wallet fund"));
657    }
658
659    #[test]
660    fn funding_contexts_are_selected_by_challenge_id() {
661        let provider = LazyAccountsProvider::new("https://rpc.mpp.tempo.xyz".to_owned(), true);
662        let first = challenge("tempo", "charge");
663        let mut second = challenge("tempo", "charge");
664        second.id = "second".to_owned();
665        second.request = Base64UrlJson::from_value(&serde_json::json!({
666            "amount": "1",
667            "currency": "0x20c0000000000000000000000000000000000001",
668            "recipient": "0x0000000000000000000000000000000000000001",
669            "methodDetails": {"chainId": 4217}
670        }))
671        .unwrap();
672
673        provider.funding_context(&first);
674        provider.funding_context(&second);
675        let second_context = provider.take_funding_context(Some("second"));
676        let first_context = provider.take_funding_context(Some("test"));
677
678        assert_eq!(second_context.chain_id, Some(Chain::from_id(4217)));
679        assert_eq!(
680            second_context.token.as_deref(),
681            Some("0x20c0000000000000000000000000000000000001")
682        );
683        assert_eq!(first_context.chain_id, Some(Chain::from_id(42431)));
684        assert_eq!(
685            first_context.token.as_deref(),
686            Some("0x20c0000000000000000000000000000000000000")
687        );
688    }
689}