Skip to main content

adk_payments/wallet/
use_based.rs

1//! The use-based rail: metered APIs and model tokens paid per use, x402-style
2//! (spec 3.5 §7.14, §13 Q5).
3//!
4//! A metered resource answers `402 Payment Required` with what it accepts. The caller
5//! reads the [`PaymentChallenge`]s with its [`UseBasedScheme`], asks the wallet to pay one
6//! ([`Wallet::pay_challenge`](super::Wallet::pay_challenge)) — the category's mandate,
7//! payee rules and cap apply before any money moves — and retries the request with the
8//! [`PaymentProof`] the settled payment carries. The scheme hides the wire: x402 with a
9//! facilitator, or any other use-based protocol.
10
11use std::collections::HashMap;
12use std::sync::{Arc, Mutex};
13
14use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
15use async_trait::async_trait;
16use chrono::Utc;
17use serde::{Deserialize, Serialize};
18use serde_json::{Value, json};
19
20use super::error::{WALLET_RAIL_DATA_MISMATCH_CODE, refused};
21use super::policy::{Payee, RailRef};
22use super::rail::{PaymentRail, RailPayment, RailSettlement};
23
24/// What a metered resource asked for in its `402 Payment Required` answer.
25///
26/// # Example
27///
28/// ```
29/// use adk_payments::wallet::PaymentChallenge;
30///
31/// let challenge = PaymentChallenge::new("https://api.models.example/v1/generate", "acct-models", 12, "USD");
32/// assert_eq!(challenge.payee().domain.as_deref(), Some("api.models.example"));
33/// ```
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "camelCase")]
36pub struct PaymentChallenge {
37    /// The payment scheme, such as x402's `exact`.
38    pub scheme: String,
39    /// The settlement network, when the scheme names one.
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub network: Option<String>,
42    /// The URL of the metered resource.
43    pub resource: String,
44    /// Who is paid: the resource's payee id on the scheme.
45    pub pay_to: String,
46    /// The price, in minor units of `currency`.
47    pub amount: u64,
48    /// ISO 4217 currency code.
49    pub currency: String,
50    /// What the payment buys.
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub description: Option<String>,
53    /// How long the resource honours a payment for this challenge.
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub max_timeout_seconds: Option<u64>,
56    /// Scheme-specific fields.
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub extra: Option<Value>,
59}
60
61impl PaymentChallenge {
62    /// A challenge from `resource` asking `amount` minor units of `currency` for `pay_to`,
63    /// under the `exact` scheme.
64    pub fn new(resource: &str, pay_to: &str, amount: u64, currency: &str) -> Self {
65        Self {
66            scheme: "exact".to_string(),
67            network: None,
68            resource: resource.to_string(),
69            pay_to: pay_to.to_string(),
70            amount,
71            currency: currency.to_ascii_uppercase(),
72            description: None,
73            max_timeout_seconds: None,
74            extra: None,
75        }
76    }
77
78    /// The payee the wallet's mandate is checked against: `pay_to` on the resource's host.
79    pub fn payee(&self) -> Payee {
80        let payee = Payee::new(&self.pay_to);
81        match host_of(&self.resource) {
82            Some(host) => payee.with_domain(host),
83            None => payee,
84        }
85    }
86}
87
88/// The host of `url`, lowercased, without user info or port.
89pub(crate) fn host_of(url: &str) -> Option<String> {
90    let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
91    let authority = rest.split(['/', '?', '#']).next()?;
92    let authority = authority.rsplit_once('@').map_or(authority, |(_, host)| host);
93    let host = if authority.starts_with('[') {
94        authority.split_once(']').map(|(host, _)| &host[1..])?
95    } else {
96        authority.split(':').next()?
97    };
98    (!host.is_empty()).then(|| host.to_ascii_lowercase())
99}
100
101/// What the caller attaches when it retries a metered request: x402's `X-PAYMENT` header,
102/// or the scheme's own.
103///
104/// # Example
105///
106/// ```
107/// use adk_payments::wallet::PaymentProof;
108///
109/// let proof = PaymentProof { header: "X-PAYMENT".into(), value: "...".into() };
110/// assert_eq!(proof.header, "X-PAYMENT");
111/// ```
112#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(rename_all = "camelCase")]
114pub struct PaymentProof {
115    /// The request header to set.
116    pub header: String,
117    /// Its value.
118    pub value: String,
119}
120
121/// What a scheme reports for a paid challenge.
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(rename_all = "camelCase")]
124pub struct UseBasedPayment {
125    /// The scheme's or facilitator's reference for the payment.
126    pub reference: String,
127    /// What the caller attaches when it retries the request.
128    pub proof: PaymentProof,
129}
130
131/// A use-based payment protocol (spec 3.5 §7.14): x402 or another 402 challenge and
132/// response.
133///
134/// The wallet has already checked the mandate, reserved the cap and debited its provider
135/// when it calls [`pay`](Self::pay); the scheme turns the funds into the proof the resource
136/// accepts.
137#[async_trait]
138pub trait UseBasedScheme: Send + Sync {
139    /// The scheme's name, such as `x402`.
140    fn name(&self) -> &str;
141
142    /// Reads the challenges in a `402 Payment Required` answer's body.
143    ///
144    /// # Errors
145    ///
146    /// Returns an `InvalidInput` error when the body is not this scheme's challenge.
147    fn challenges(&self, body: &Value) -> Result<Vec<PaymentChallenge>>;
148
149    /// Pays `challenge` with the funds `payment` debited.
150    ///
151    /// # Errors
152    ///
153    /// Returns the scheme's error when the payment did not settle; the wallet then voids
154    /// the debit.
155    async fn pay(
156        &self,
157        challenge: &PaymentChallenge,
158        payment: &RailPayment,
159    ) -> Result<UseBasedPayment>;
160}
161
162/// The use-based rail adapter for metered APIs and model tokens (spec 3.5 §7.14).
163///
164/// A payment's rail data is the [`PaymentChallenge`] it answers; a challenge whose payee,
165/// host, amount or currency differs from the payment the wallet allowed is refused before
166/// any money moves.
167///
168/// # Example
169///
170/// ```
171/// use std::sync::Arc;
172/// use adk_payments::wallet::{InMemoryUseBasedScheme, PaymentRail, RailRef, UseBasedRail};
173///
174/// let rail = UseBasedRail::new(Arc::new(InMemoryUseBasedScheme::new()));
175/// assert_eq!(rail.rail(), RailRef::use_based());
176/// ```
177pub struct UseBasedRail {
178    scheme: Arc<dyn UseBasedScheme>,
179}
180
181impl UseBasedRail {
182    /// A rail paying through `scheme`.
183    pub fn new(scheme: Arc<dyn UseBasedScheme>) -> Self {
184        Self { scheme }
185    }
186
187    /// The scheme, to read challenges with.
188    pub fn scheme(&self) -> &Arc<dyn UseBasedScheme> {
189        &self.scheme
190    }
191}
192
193fn challenge_of(payment: &RailPayment) -> Result<PaymentChallenge> {
194    let data = payment.rail_data.clone().ok_or_else(|| {
195        refused(
196            WALLET_RAIL_DATA_MISMATCH_CODE,
197            "a use-based payment carries the challenge it answers as its rail data",
198        )
199    })?;
200    serde_json::from_value(data).map_err(|error| {
201        refused(
202            WALLET_RAIL_DATA_MISMATCH_CODE,
203            format!("the use-based rail data is not a payment challenge: {error}"),
204        )
205    })
206}
207
208#[async_trait]
209impl PaymentRail for UseBasedRail {
210    fn rail(&self) -> RailRef {
211        RailRef::use_based()
212    }
213
214    fn check(&self, payment: &RailPayment) -> Result<()> {
215        let challenge = challenge_of(payment)?;
216        let mismatch = |what: String| Err(refused(WALLET_RAIL_DATA_MISMATCH_CODE, what));
217        if challenge.pay_to != payment.payee.id {
218            return mismatch(format!(
219                "the challenge pays {}, not payee {}",
220                challenge.pay_to, payment.payee.id
221            ));
222        }
223        if let Some(domain) = &payment.payee.domain
224            && challenge.payee().domain.as_deref() != Some(domain.to_ascii_lowercase().as_str())
225        {
226            return mismatch(format!(
227                "the challenge comes from {}, not the payee's domain {domain}",
228                challenge.resource
229            ));
230        }
231        if challenge.amount != payment.amount
232            || !challenge.currency.eq_ignore_ascii_case(&payment.currency)
233        {
234            return mismatch(format!(
235                "the challenge asks {} {}, not the {} {} the wallet allowed",
236                challenge.amount, challenge.currency, payment.amount, payment.currency
237            ));
238        }
239        Ok(())
240    }
241
242    async fn execute(&self, payment: &RailPayment) -> Result<RailSettlement> {
243        let challenge = challenge_of(payment)?;
244        let paid = self.scheme.pay(&challenge, payment).await?;
245        Ok(RailSettlement {
246            reference: paid.reference,
247            amount: payment.amount,
248            settled_at: Utc::now(),
249            proof: Some(serde_json::to_value(&paid.proof).unwrap_or(Value::Null)),
250        })
251    }
252}
253
254/// A hermetic [`UseBasedScheme`] for tests and local fixtures, shaped like x402.
255///
256/// It reads x402's `{"accepts": [...]}` body, with `asset` as the ISO 4217 currency and
257/// `maxAmountRequired` in its minor units, and answers with an `X-PAYMENT` token that
258/// [`verify`](Self::verify) accepts once. It moves no money of its own: the wallet's
259/// provider debit is the payment.
260///
261/// # Example
262///
263/// ```
264/// use adk_payments::wallet::{InMemoryUseBasedScheme, UseBasedScheme};
265/// use serde_json::json;
266///
267/// let scheme = InMemoryUseBasedScheme::new();
268/// let challenges = scheme.challenges(&json!({
269///     "x402Version": 1,
270///     "accepts": [{
271///         "scheme": "exact", "resource": "https://api.models.example/v1/generate",
272///         "payTo": "acct-models", "maxAmountRequired": "12", "asset": "USD"
273///     }]
274/// }))?;
275/// assert_eq!(challenges[0].amount, 12);
276/// # Ok::<(), adk_core::AdkError>(())
277/// ```
278#[derive(Debug, Clone, Default)]
279pub struct InMemoryUseBasedScheme {
280    issued: Arc<Mutex<HashMap<String, (PaymentChallenge, bool)>>>,
281}
282
283impl InMemoryUseBasedScheme {
284    /// A scheme with no payments yet.
285    pub fn new() -> Self {
286        Self::default()
287    }
288
289    /// Whether `value` is an unspent payment for `challenge`; a verified payment is spent,
290    /// so a replayed header is refused.
291    pub fn verify(&self, challenge: &PaymentChallenge, value: &str) -> bool {
292        let mut issued = self.issued.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
293        match issued.get_mut(value) {
294            Some((paid, spent)) if paid == challenge && !*spent => {
295                *spent = true;
296                true
297            }
298            _ => false,
299        }
300    }
301
302    /// How many challenges were paid.
303    pub fn paid(&self) -> usize {
304        self.issued.lock().unwrap_or_else(std::sync::PoisonError::into_inner).len()
305    }
306}
307
308#[async_trait]
309impl UseBasedScheme for InMemoryUseBasedScheme {
310    fn name(&self) -> &str {
311        "x402-local"
312    }
313
314    fn challenges(&self, body: &Value) -> Result<Vec<PaymentChallenge>> {
315        let invalid = |reason: &str| {
316            AdkError::new(
317                ErrorComponent::Tool,
318                ErrorCategory::InvalidInput,
319                "wallet.use_based.invalid_challenge",
320                format!("not an x402 payment requirement: {reason}"),
321            )
322        };
323        let accepts =
324            body.get("accepts").and_then(Value::as_array).ok_or_else(|| invalid("no accepts"))?;
325        accepts
326            .iter()
327            .map(|item| {
328                let text = |key: &str| item.get(key).and_then(Value::as_str).map(str::to_string);
329                let amount = text("maxAmountRequired")
330                    .and_then(|amount| amount.parse::<u64>().ok())
331                    .ok_or_else(|| invalid("maxAmountRequired is not an amount"))?;
332                Ok(PaymentChallenge {
333                    scheme: text("scheme").unwrap_or_else(|| "exact".to_string()),
334                    network: text("network"),
335                    resource: text("resource").ok_or_else(|| invalid("no resource"))?,
336                    pay_to: text("payTo").ok_or_else(|| invalid("no payTo"))?,
337                    amount,
338                    currency: text("asset")
339                        .ok_or_else(|| invalid("no asset"))?
340                        .to_ascii_uppercase(),
341                    description: text("description"),
342                    max_timeout_seconds: item.get("maxTimeoutSeconds").and_then(Value::as_u64),
343                    extra: item.get("extra").cloned(),
344                })
345            })
346            .collect()
347    }
348
349    async fn pay(
350        &self,
351        challenge: &PaymentChallenge,
352        payment: &RailPayment,
353    ) -> Result<UseBasedPayment> {
354        let token = json!({
355            "scheme": challenge.scheme,
356            "payTo": challenge.pay_to,
357            "amount": challenge.amount,
358            "currency": challenge.currency,
359            "payment": payment.payment_id,
360        });
361        let value = hex::encode(token.to_string());
362        self.issued
363            .lock()
364            .unwrap_or_else(std::sync::PoisonError::into_inner)
365            .entry(value.clone())
366            .or_insert_with(|| (challenge.clone(), false));
367        Ok(UseBasedPayment {
368            reference: format!("x402-local:{}", payment.payment_id),
369            proof: PaymentProof { header: "X-PAYMENT".to_string(), value },
370        })
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377
378    #[test]
379    fn hosts_drop_scheme_user_info_port_and_path() {
380        assert_eq!(
381            host_of("https://API.example.com:8443/v1?x=1").as_deref(),
382            Some("api.example.com")
383        );
384        assert_eq!(host_of("http://user:pw@example.com/").as_deref(), Some("example.com"));
385        assert_eq!(host_of("https://[::1]:8080/x").as_deref(), Some("::1"));
386        assert_eq!(host_of("example.com/path").as_deref(), Some("example.com"));
387        assert_eq!(host_of("https:///nohost"), None);
388    }
389}