mpp 0.12.0

Rust SDK for the Machine Payments Protocol (MPP)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! Payment provider trait and implementations.
//!
//! The `PaymentProvider` trait abstracts over payment execution, allowing
//! different payment methods (Tempo, Stripe, etc.) to be used with the
//! HTTP client extensions.

use crate::error::MppError;
use crate::protocol::core::{PaymentChallenge, PaymentCredential};
use reqwest::header::HeaderMap;
use reqwest::Url;
use std::future::Future;

/// HTTP request context available while creating a payment credential.
///
/// Session providers use this to submit management credentials, such as a
/// channel top-up, to the same resource before replaying the paid request.
#[derive(Clone, Debug)]
pub struct PaymentContext {
    /// URL of the request that returned the payment challenge.
    pub url: Url,
    /// Caller-provided request headers to preserve for management requests.
    pub headers: HeaderMap,
}

/// Trait for payment providers that can execute payments for challenges.
///
/// Implement this trait to add support for custom payment methods.
/// PaymentProvider is the client-side counterpart to server-side method traits
/// like [`ChargeMethod`](crate::protocol::traits::ChargeMethod).
///
/// # Examples
///
/// ```ignore
/// use mpp::client::PaymentProvider;
/// use mpp::protocol::core::{PaymentChallenge, PaymentCredential, PaymentPayload};
/// use mpp::MppError;
///
/// #[derive(Clone)]
/// struct MyProvider { /* ... */ }
///
/// impl PaymentProvider for MyProvider {
///     fn supports(&self, method: &str, intent: &str) -> bool {
///         method == "my_network" && intent == "charge"
///     }
///
///     async fn pay(&self, challenge: &PaymentChallenge) -> Result<PaymentCredential, MppError> {
///         // 1. Parse the challenge request
///         // 2. Execute payment (sign tx, call API, etc.)
///         // 3. Return credential with proof
///         let echo = challenge.to_echo();
///         Ok(PaymentCredential::new(echo, PaymentPayload::hash("0x...")))
///     }
/// }
/// ```
pub trait PaymentProvider: Clone + Send + Sync {
    /// Check if this provider supports the given method and intent combination.
    ///
    /// This allows clients to filter providers based on challenge requirements
    /// before attempting payment.
    ///
    /// # Arguments
    ///
    /// * `method` - Payment method name (e.g., "tempo", "stripe")
    /// * `intent` - Payment intent name (e.g., "charge", "authorize")
    ///
    /// # Returns
    ///
    /// `true` if this provider can handle the combination.
    fn supports(&self, method: &str, intent: &str) -> bool;

    /// Select one challenge from the supported, unexpired candidates.
    ///
    /// Candidates have already been ordered by the caller's `Accept-Payment`
    /// preferences. The default preserves that order. Providers may override
    /// this to choose between otherwise equivalent offers using complete
    /// challenge details such as currency, chain, or amount. Returning `None`
    /// rejects every candidate.
    fn select_challenge<'a>(
        &self,
        challenges: &[&'a PaymentChallenge],
    ) -> Option<&'a PaymentChallenge> {
        challenges.first().copied()
    }

    /// Execute payment for the given challenge and return a credential.
    ///
    /// This method should:
    /// 1. Parse the challenge request for payment details
    /// 2. Execute the payment (sign transaction, call API, etc.)
    /// 3. Build and return a `PaymentCredential` with the proof
    fn pay(
        &self,
        challenge: &PaymentChallenge,
    ) -> impl Future<Output = Result<PaymentCredential, MppError>> + Send;

    /// Execute payment with access to the challenged HTTP request.
    ///
    /// Most providers only need the challenge and inherit this default. A
    /// session provider may use the URL and headers to top up its channel via
    /// the resource's management endpoint before returning a voucher.
    fn pay_with_context(
        &self,
        challenge: &PaymentChallenge,
        context: PaymentContext,
    ) -> impl Future<Output = Result<PaymentCredential, MppError>> + Send {
        let _ = context;
        self.pay(challenge)
    }

    /// Prepare a challenge before creating an HTTP payment credential.
    ///
    /// Providers that need interactive setup may perform it here. Returning
    /// `None` asks the client to discard the current challenge and repeat the
    /// original unauthenticated request, so setup never signs an expired
    /// challenge. Other providers inherit the challenge unchanged.
    fn prepare_http_payment_challenge(
        &self,
        challenge: &PaymentChallenge,
        context: PaymentContext,
    ) -> impl Future<Output = Result<Option<PaymentChallenge>, MppError>> + Send {
        let challenge = challenge.clone();
        async move {
            let _ = context;
            Ok(Some(challenge))
        }
    }

    /// Reconcile a challenge before opening an application WebSocket.
    ///
    /// Session providers may use this hook to refresh persisted state from the
    /// server before creating the socket-bound credential. Other providers
    /// inherit the challenge unchanged.
    fn prepare_application_websocket_challenge(
        &self,
        challenge: &PaymentChallenge,
        context: PaymentContext,
    ) -> impl Future<Output = Result<PaymentChallenge, MppError>> + Send {
        let challenge = challenge.clone();
        async move {
            let _ = context;
            Ok(challenge)
        }
    }

    /// Commit optimistic provider state after the server accepts a credential.
    fn commit_payment(
        &self,
        challenge: &PaymentChallenge,
        credential: &PaymentCredential,
    ) -> impl Future<Output = Result<(), MppError>> + Send {
        let _ = (challenge, credential);
        async { Ok(()) }
    }

    /// Roll back optimistic provider state after the credential was not sent
    /// or the server definitively rejected it.
    ///
    /// Callers must not invoke this hook after an ambiguous transport failure:
    /// the server may have accepted the credential even if its response was
    /// lost.
    fn rollback_payment(
        &self,
        challenge: &PaymentChallenge,
        credential: &PaymentCredential,
    ) -> impl Future<Output = Result<(), MppError>> + Send {
        let _ = (challenge, credential);
        async { Ok(()) }
    }

    /// Release transient delivery state when a paid request future is dropped.
    ///
    /// This hook is synchronous because cancellation is observed from `Drop`.
    /// Providers must preserve any durable or ambiguously delivered payment
    /// state; this is only for resources such as delivery-ordering leases.
    fn abandon_payment(&self, challenge: &PaymentChallenge, credential: &PaymentCredential) {
        let _ = (challenge, credential);
    }

    /// Build an `Accept-Payment` header value from this provider's supported methods.
    ///
    /// Returns `None` if the provider does not advertise specific methods.
    /// The default implementation returns `None`; providers that know their
    /// supported `(method, intent)` pairs should override this.
    fn accept_payment_header(&self) -> Option<String> {
        None
    }
}

pub(crate) async fn commit_payments<P: PaymentProvider>(
    provider: &P,
    payments: &[(PaymentChallenge, PaymentCredential)],
) -> Result<(), MppError> {
    for (challenge, credential) in payments {
        provider.commit_payment(challenge, credential).await?;
    }
    Ok(())
}

pub(crate) async fn rollback_payments<P: PaymentProvider>(
    provider: &P,
    payments: &[(PaymentChallenge, PaymentCredential)],
) -> Result<(), MppError> {
    for (challenge, credential) in payments {
        provider.rollback_payment(challenge, credential).await?;
    }
    Ok(())
}

pub(crate) struct PendingPayments<P: PaymentProvider> {
    provider: P,
    payments: Vec<(PaymentChallenge, PaymentCredential)>,
}

impl<P: PaymentProvider> PendingPayments<P> {
    pub(crate) fn new(provider: P) -> Self {
        Self {
            provider,
            payments: Vec::new(),
        }
    }

    pub(crate) async fn commit(&mut self) -> Result<(), MppError> {
        commit_payments(&self.provider, &self.payments).await?;
        self.payments.clear();
        Ok(())
    }

    pub(crate) async fn rollback(&mut self) -> Result<(), MppError> {
        rollback_payments(&self.provider, &self.payments).await?;
        self.payments.clear();
        Ok(())
    }
}

impl<P: PaymentProvider> std::ops::Deref for PendingPayments<P> {
    type Target = Vec<(PaymentChallenge, PaymentCredential)>;

    fn deref(&self) -> &Self::Target {
        &self.payments
    }
}

impl<P: PaymentProvider> std::ops::DerefMut for PendingPayments<P> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.payments
    }
}

impl<P: PaymentProvider> Drop for PendingPayments<P> {
    fn drop(&mut self) {
        for (challenge, credential) in &self.payments {
            self.provider.abandon_payment(challenge, credential);
        }
    }
}

/// A provider that wraps multiple payment providers and picks the right one.
///
/// `MultiProvider` iterates through its providers and uses the first one that
/// supports the challenge's method and intent combination.
///
/// # Examples
///
/// ```ignore
/// use mpp::client::{MultiProvider, TempoProvider};
///
/// let provider = MultiProvider::new()
///     .with(TempoProvider::new(signer, "https://rpc.moderato.tempo.xyz")?);
///
/// // Automatically picks the right provider based on challenge.method
/// let resp = client.get(url).send_with_payment(&provider).await?;
/// ```
#[derive(Clone)]
pub struct MultiProvider {
    providers: Vec<Box<dyn DynPaymentProvider>>,
}

impl MultiProvider {
    /// Create a new empty multi-provider.
    pub fn new() -> Self {
        Self {
            providers: Vec::new(),
        }
    }

    /// Add a provider to the list.
    pub fn with<P: PaymentProvider + 'static>(mut self, provider: P) -> Self {
        self.providers.push(Box::new(provider));
        self
    }

    /// Add a provider to the list (mutable reference version).
    pub fn add<P: PaymentProvider + 'static>(&mut self, provider: P) -> &mut Self {
        self.providers.push(Box::new(provider));
        self
    }

    /// Check if any provider supports the given method and intent.
    pub fn has_support(&self, method: &str, intent: &str) -> bool {
        self.providers
            .iter()
            .any(|p| p.dyn_supports(method, intent))
    }
}

impl Default for MultiProvider {
    fn default() -> Self {
        Self::new()
    }
}

impl PaymentProvider for MultiProvider {
    fn supports(&self, method: &str, intent: &str) -> bool {
        self.has_support(method, intent)
    }

    fn select_challenge<'a>(
        &self,
        challenges: &[&'a PaymentChallenge],
    ) -> Option<&'a PaymentChallenge> {
        let first = challenges.first()?;
        let provider = self
            .providers
            .iter()
            .find(|provider| provider.dyn_supports(first.method.as_str(), first.intent.as_str()))?;
        let candidates = challenges
            .iter()
            .copied()
            .filter(|challenge| {
                provider.dyn_supports(challenge.method.as_str(), challenge.intent.as_str())
            })
            .collect::<Vec<_>>();
        provider.dyn_select_challenge(&candidates)
    }

    async fn pay(&self, challenge: &PaymentChallenge) -> Result<PaymentCredential, MppError> {
        let method = challenge.method.as_str();
        let intent = challenge.intent.as_str();

        for provider in &self.providers {
            if provider.dyn_supports(method, intent) {
                return provider.dyn_pay(challenge).await;
            }
        }

        Err(MppError::UnsupportedPaymentMethod(format!(
            "no provider supports method={}, intent={}",
            method, intent
        )))
    }

    async fn pay_with_context(
        &self,
        challenge: &PaymentChallenge,
        context: PaymentContext,
    ) -> Result<PaymentCredential, MppError> {
        let method = challenge.method.as_str();
        let intent = challenge.intent.as_str();

        for provider in &self.providers {
            if provider.dyn_supports(method, intent) {
                return provider.dyn_pay_with_context(challenge, context).await;
            }
        }

        Err(MppError::UnsupportedPaymentMethod(format!(
            "no provider supports method={}, intent={}",
            method, intent
        )))
    }

    async fn prepare_http_payment_challenge(
        &self,
        challenge: &PaymentChallenge,
        context: PaymentContext,
    ) -> Result<Option<PaymentChallenge>, MppError> {
        let method = challenge.method.as_str();
        let intent = challenge.intent.as_str();

        for provider in &self.providers {
            if provider.dyn_supports(method, intent) {
                return provider
                    .dyn_prepare_http_payment_challenge(challenge, context)
                    .await;
            }
        }

        Err(MppError::UnsupportedPaymentMethod(format!(
            "no provider supports method={}, intent={}",
            method, intent
        )))
    }

    async fn prepare_application_websocket_challenge(
        &self,
        challenge: &PaymentChallenge,
        context: PaymentContext,
    ) -> Result<PaymentChallenge, MppError> {
        let method = challenge.method.as_str();
        let intent = challenge.intent.as_str();

        for provider in &self.providers {
            if provider.dyn_supports(method, intent) {
                return provider
                    .dyn_prepare_application_websocket_challenge(challenge, context)
                    .await;
            }
        }

        Err(MppError::UnsupportedPaymentMethod(format!(
            "no provider supports method={}, intent={}",
            method, intent
        )))
    }

    async fn commit_payment(
        &self,
        challenge: &PaymentChallenge,
        credential: &PaymentCredential,
    ) -> Result<(), MppError> {
        let method = challenge.method.as_str();
        let intent = challenge.intent.as_str();

        for provider in &self.providers {
            if provider.dyn_supports(method, intent) {
                return provider.dyn_commit_payment(challenge, credential).await;
            }
        }

        Err(MppError::UnsupportedPaymentMethod(format!(
            "no provider supports method={}, intent={}",
            method, intent
        )))
    }

    async fn rollback_payment(
        &self,
        challenge: &PaymentChallenge,
        credential: &PaymentCredential,
    ) -> Result<(), MppError> {
        let method = challenge.method.as_str();
        let intent = challenge.intent.as_str();

        for provider in &self.providers {
            if provider.dyn_supports(method, intent) {
                return provider.dyn_rollback_payment(challenge, credential).await;
            }
        }

        Err(MppError::UnsupportedPaymentMethod(format!(
            "no provider supports method={}, intent={}",
            method, intent
        )))
    }

    fn abandon_payment(&self, challenge: &PaymentChallenge, credential: &PaymentCredential) {
        let method = challenge.method.as_str();
        let intent = challenge.intent.as_str();

        for provider in &self.providers {
            if provider.dyn_supports(method, intent) {
                provider.dyn_abandon_payment(challenge, credential);
                return;
            }
        }
    }

    fn accept_payment_header(&self) -> Option<String> {
        let headers: Vec<String> = self
            .providers
            .iter()
            .filter_map(|p| p.dyn_accept_payment_header())
            .collect();

        if headers.is_empty() {
            None
        } else {
            Some(headers.join(", "))
        }
    }
}

/// Object-safe version of PaymentProvider for use in MultiProvider.
trait DynPaymentProvider: Send + Sync {
    fn dyn_supports(&self, method: &str, intent: &str) -> bool;
    fn dyn_select_challenge<'a>(
        &self,
        challenges: &[&'a PaymentChallenge],
    ) -> Option<&'a PaymentChallenge>;
    fn dyn_pay<'a>(
        &'a self,
        challenge: &'a PaymentChallenge,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<PaymentCredential, MppError>> + Send + 'a>>;
    fn dyn_pay_with_context<'a>(
        &'a self,
        challenge: &'a PaymentChallenge,
        context: PaymentContext,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<PaymentCredential, MppError>> + Send + 'a>>;
    fn dyn_prepare_http_payment_challenge<'a>(
        &'a self,
        challenge: &'a PaymentChallenge,
        context: PaymentContext,
    ) -> std::pin::Pin<
        Box<dyn Future<Output = Result<Option<PaymentChallenge>, MppError>> + Send + 'a>,
    >;
    fn dyn_prepare_application_websocket_challenge<'a>(
        &'a self,
        challenge: &'a PaymentChallenge,
        context: PaymentContext,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<PaymentChallenge, MppError>> + Send + 'a>>;
    fn dyn_commit_payment<'a>(
        &'a self,
        challenge: &'a PaymentChallenge,
        credential: &'a PaymentCredential,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<(), MppError>> + Send + 'a>>;
    fn dyn_rollback_payment<'a>(
        &'a self,
        challenge: &'a PaymentChallenge,
        credential: &'a PaymentCredential,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<(), MppError>> + Send + 'a>>;
    fn dyn_abandon_payment(&self, challenge: &PaymentChallenge, credential: &PaymentCredential);
    fn dyn_accept_payment_header(&self) -> Option<String>;
    fn clone_box(&self) -> Box<dyn DynPaymentProvider>;
}

impl<P: PaymentProvider + 'static> DynPaymentProvider for P {
    fn dyn_supports(&self, method: &str, intent: &str) -> bool {
        PaymentProvider::supports(self, method, intent)
    }

    fn dyn_select_challenge<'a>(
        &self,
        challenges: &[&'a PaymentChallenge],
    ) -> Option<&'a PaymentChallenge> {
        PaymentProvider::select_challenge(self, challenges)
    }

    fn dyn_pay<'a>(
        &'a self,
        challenge: &'a PaymentChallenge,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<PaymentCredential, MppError>> + Send + 'a>>
    {
        Box::pin(PaymentProvider::pay(self, challenge))
    }

    fn dyn_pay_with_context<'a>(
        &'a self,
        challenge: &'a PaymentChallenge,
        context: PaymentContext,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<PaymentCredential, MppError>> + Send + 'a>>
    {
        Box::pin(PaymentProvider::pay_with_context(self, challenge, context))
    }

    fn dyn_prepare_http_payment_challenge<'a>(
        &'a self,
        challenge: &'a PaymentChallenge,
        context: PaymentContext,
    ) -> std::pin::Pin<
        Box<dyn Future<Output = Result<Option<PaymentChallenge>, MppError>> + Send + 'a>,
    > {
        Box::pin(PaymentProvider::prepare_http_payment_challenge(
            self, challenge, context,
        ))
    }

    fn dyn_prepare_application_websocket_challenge<'a>(
        &'a self,
        challenge: &'a PaymentChallenge,
        context: PaymentContext,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<PaymentChallenge, MppError>> + Send + 'a>>
    {
        Box::pin(PaymentProvider::prepare_application_websocket_challenge(
            self, challenge, context,
        ))
    }

    fn dyn_commit_payment<'a>(
        &'a self,
        challenge: &'a PaymentChallenge,
        credential: &'a PaymentCredential,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<(), MppError>> + Send + 'a>> {
        Box::pin(PaymentProvider::commit_payment(self, challenge, credential))
    }

    fn dyn_rollback_payment<'a>(
        &'a self,
        challenge: &'a PaymentChallenge,
        credential: &'a PaymentCredential,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<(), MppError>> + Send + 'a>> {
        Box::pin(PaymentProvider::rollback_payment(
            self, challenge, credential,
        ))
    }

    fn dyn_abandon_payment(&self, challenge: &PaymentChallenge, credential: &PaymentCredential) {
        PaymentProvider::abandon_payment(self, challenge, credential);
    }

    fn dyn_accept_payment_header(&self) -> Option<String> {
        PaymentProvider::accept_payment_header(self)
    }

    fn clone_box(&self) -> Box<dyn DynPaymentProvider> {
        Box::new(self.clone())
    }
}

impl Clone for Box<dyn DynPaymentProvider> {
    fn clone(&self) -> Self {
        self.clone_box()
    }
}

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

    #[derive(Clone)]
    struct MockProvider {
        method: &'static str,
        intent: &'static str,
    }

    impl PaymentProvider for MockProvider {
        fn supports(&self, method: &str, intent: &str) -> bool {
            self.method == method && self.intent == intent
        }

        async fn pay(&self, challenge: &PaymentChallenge) -> Result<PaymentCredential, MppError> {
            use crate::protocol::core::PaymentPayload;
            Ok(PaymentCredential::new(
                challenge.to_echo(),
                PaymentPayload::hash(format!("mock-{}", self.method)),
            ))
        }
    }

    #[test]
    fn test_multi_provider_supports() {
        let multi = MultiProvider::new()
            .with(MockProvider {
                method: "tempo",
                intent: "charge",
            })
            .with(MockProvider {
                method: "stripe",
                intent: "charge",
            });

        assert!(multi.has_support("tempo", "charge"));
        assert!(multi.has_support("stripe", "charge"));
        assert!(!multi.has_support("bitcoin", "charge"));
        assert!(!multi.has_support("tempo", "authorize"));
    }

    #[test]
    fn test_multi_provider_empty() {
        let multi = MultiProvider::new();
        assert!(!multi.has_support("tempo", "charge"));
    }

    #[test]
    fn test_multi_provider_clone() {
        let multi = MultiProvider::new().with(MockProvider {
            method: "tempo",
            intent: "charge",
        });

        let cloned = multi.clone();
        assert!(cloned.has_support("tempo", "charge"));
    }
}