tap-msg 0.7.0

Core message processing library for the Transaction Authorization Protocol
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
//! Payment types for TAP messages.
//!
//! This module defines the structure of payment messages and related types
//! used in the Transaction Authorization Protocol (TAP).

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use tap_caip::AssetId;

use crate::error::{Error, Result};
use crate::message::agent::TapParticipant;
use crate::message::tap_message_trait::{TapMessage as TapMessageTrait, TapMessageBody};
use crate::message::{Agent, Party};
use crate::settlement_address::SettlementAddress;
use crate::TapMessage;

/// A supported asset entry that can be either a simple asset identifier
/// or a pricing object with amount and expiry (TAIP-14).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SupportedAsset {
    /// Simple asset identifier (CAIP-19 or DTI) for ~1:1 stablecoins.
    Simple(AssetId),
    /// Pricing object with asset, amount, and optional expiry.
    Priced(AssetPricing),
}

/// Pricing object for supported assets (TAIP-14).
///
/// Specifies a specific amount of an asset or currency needed to settle a payment,
/// with an optional expiration timestamp for the exchange rate.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssetPricing {
    /// Asset identifier (CAIP-19, DTI, or ISO 4217 currency code).
    pub asset: String,
    /// Decimal string of the amount needed.
    pub amount: String,
    /// ISO 8601 timestamp when this rate expires (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires: Option<String>,
}

/// Invoice reference that can be either a URL or an Invoice object
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum InvoiceReference {
    /// URL to an invoice
    Url(String),
    /// Structured invoice object
    Object(Box<crate::message::Invoice>),
}

impl InvoiceReference {
    /// Check if this is a URL reference
    pub fn is_url(&self) -> bool {
        matches!(self, InvoiceReference::Url(_))
    }

    /// Check if this is an object reference
    pub fn is_object(&self) -> bool {
        matches!(self, InvoiceReference::Object(_))
    }

    /// Get the URL if this is a URL reference
    pub fn as_url(&self) -> Option<&str> {
        match self {
            InvoiceReference::Url(url) => Some(url),
            _ => None,
        }
    }

    /// Get the invoice object if this is an object reference
    pub fn as_object(&self) -> Option<&crate::message::Invoice> {
        match self {
            InvoiceReference::Object(invoice) => Some(invoice.as_ref()),
            _ => None,
        }
    }

    /// Validate the invoice reference
    pub fn validate(&self) -> Result<()> {
        match self {
            InvoiceReference::Url(url) => {
                // Basic URL validation - just check it's not empty
                if url.is_empty() {
                    return Err(Error::Validation("Invoice URL cannot be empty".to_string()));
                }
                // Could add more URL validation here if needed
                Ok(())
            }
            InvoiceReference::Object(invoice) => {
                // Validate the invoice object
                invoice.validate()
            }
        }
    }
}

/// Payment message body (TAIP-14).
///
/// A Payment is a DIDComm message initiated by the merchant's agent and sent
/// to the customer's agent to request a blockchain payment. It must include either
/// an asset or a currency to denominate the payment, along with the amount and
/// recipient information.
#[derive(Debug, Clone, Serialize, Deserialize, TapMessage)]
#[tap(
    message_type = "https://tap.rsvp/schema/1.0#Payment",
    initiator,
    authorizable,
    transactable
)]
pub struct Payment {
    /// Asset identifier (CAIP-19 format).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub asset: Option<AssetId>,

    /// Payment amount.
    pub amount: String,

    /// Currency code for fiat amounts (e.g., USD).
    #[serde(rename = "currency", skip_serializing_if = "Option::is_none")]
    pub currency_code: Option<String>,

    /// Supported assets for this payment (when currency_code is specified).
    /// Can be simple asset identifiers or pricing objects with amounts.
    #[serde(rename = "supportedAssets", skip_serializing_if = "Option::is_none")]
    pub supported_assets: Option<Vec<SupportedAsset>>,

    /// Customer (payer) details.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[tap(participant)]
    pub customer: Option<Party>,

    /// Merchant (payee) details.
    #[tap(participant)]
    pub merchant: Party,

    /// Transaction identifier (only available after creation).
    #[serde(skip)]
    #[tap(transaction_id)]
    pub transaction_id: Option<String>,

    /// Memo for the payment (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memo: Option<String>,

    /// Expiration time in ISO 8601 format (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expiry: Option<String>,

    /// Invoice details (optional) per TAIP-16 - can be either a URL or an Invoice object
    #[serde(skip_serializing_if = "Option::is_none")]
    pub invoice: Option<InvoiceReference>,

    /// Other agents involved in the payment.
    #[serde(default)]
    #[tap(participant_list)]
    pub agents: Vec<Agent>,

    /// Connection ID for linking to Connect messages
    #[serde(skip_serializing_if = "Option::is_none")]
    #[tap(connection_id)]
    pub connection_id: Option<String>,

    /// Fallback settlement addresses for payment flexibility (optional)
    #[serde(
        rename = "fallbackSettlementAddresses",
        skip_serializing_if = "Option::is_none"
    )]
    pub fallback_settlement_addresses: Option<Vec<SettlementAddress>>,

    /// Additional metadata (optional).
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, serde_json::Value>,
}

/// Builder for Payment objects.
#[derive(Default)]
pub struct PaymentBuilder {
    asset: Option<AssetId>,
    amount: Option<String>,
    currency_code: Option<String>,
    supported_assets: Option<Vec<SupportedAsset>>,
    customer: Option<Party>,
    merchant: Option<Party>,
    transaction_id: Option<String>,
    memo: Option<String>,
    expiry: Option<String>,
    invoice: Option<InvoiceReference>,
    agents: Vec<Agent>,
    fallback_settlement_addresses: Option<Vec<SettlementAddress>>,
    metadata: HashMap<String, serde_json::Value>,
}

impl PaymentBuilder {
    /// Set the asset for this payment
    pub fn asset(mut self, asset: AssetId) -> Self {
        self.asset = Some(asset);
        self
    }

    /// Set the amount for this payment
    pub fn amount(mut self, amount: String) -> Self {
        self.amount = Some(amount);
        self
    }

    /// Set the currency code for this payment
    pub fn currency_code(mut self, currency_code: String) -> Self {
        self.currency_code = Some(currency_code);
        self
    }

    /// Set the supported assets for this payment
    pub fn supported_assets(mut self, supported_assets: Vec<SupportedAsset>) -> Self {
        self.supported_assets = Some(supported_assets);
        self
    }

    /// Add a simple supported asset for this payment
    pub fn add_supported_asset(mut self, asset: AssetId) -> Self {
        if let Some(assets) = &mut self.supported_assets {
            assets.push(SupportedAsset::Simple(asset));
        } else {
            self.supported_assets = Some(vec![SupportedAsset::Simple(asset)]);
        }
        self
    }

    /// Add a priced supported asset for this payment
    pub fn add_priced_asset(mut self, pricing: AssetPricing) -> Self {
        if let Some(assets) = &mut self.supported_assets {
            assets.push(SupportedAsset::Priced(pricing));
        } else {
            self.supported_assets = Some(vec![SupportedAsset::Priced(pricing)]);
        }
        self
    }

    /// Set the customer for this payment
    pub fn customer(mut self, customer: Party) -> Self {
        self.customer = Some(customer);
        self
    }

    /// Set the merchant for this payment
    pub fn merchant(mut self, merchant: Party) -> Self {
        self.merchant = Some(merchant);
        self
    }

    /// Set the transaction ID for this payment
    pub fn transaction_id(mut self, transaction_id: String) -> Self {
        self.transaction_id = Some(transaction_id);
        self
    }

    /// Set the memo for this payment
    pub fn memo(mut self, memo: String) -> Self {
        self.memo = Some(memo);
        self
    }

    /// Set the expiration time for this payment
    pub fn expiry(mut self, expiry: String) -> Self {
        self.expiry = Some(expiry);
        self
    }

    /// Set the invoice for this payment with an Invoice object
    pub fn invoice(mut self, invoice: crate::message::Invoice) -> Self {
        self.invoice = Some(InvoiceReference::Object(Box::new(invoice)));
        self
    }

    /// Set the invoice URL for this payment
    pub fn invoice_url(mut self, url: String) -> Self {
        self.invoice = Some(InvoiceReference::Url(url));
        self
    }

    /// Add an agent to this payment
    pub fn add_agent(mut self, agent: Agent) -> Self {
        self.agents.push(agent);
        self
    }

    /// Set all agents for this payment
    pub fn agents(mut self, agents: Vec<Agent>) -> Self {
        self.agents = agents;
        self
    }

    /// Add a metadata field
    pub fn add_metadata(mut self, key: String, value: serde_json::Value) -> Self {
        self.metadata.insert(key, value);
        self
    }

    /// Set all metadata for this payment
    pub fn metadata(mut self, metadata: HashMap<String, serde_json::Value>) -> Self {
        self.metadata = metadata;
        self
    }

    /// Add a fallback settlement address
    pub fn add_fallback_settlement_address(mut self, address: SettlementAddress) -> Self {
        if let Some(addresses) = &mut self.fallback_settlement_addresses {
            addresses.push(address);
        } else {
            self.fallback_settlement_addresses = Some(vec![address]);
        }
        self
    }

    /// Set all fallback settlement addresses
    pub fn fallback_settlement_addresses(mut self, addresses: Vec<SettlementAddress>) -> Self {
        self.fallback_settlement_addresses = Some(addresses);
        self
    }

    /// Build the Payment object
    ///
    /// # Panics
    ///
    /// Panics if required fields are not set
    pub fn build(self) -> Payment {
        // Ensure either asset or currency_code is provided
        if self.asset.is_none() && self.currency_code.is_none() {
            panic!("Either asset or currency_code is required");
        }

        Payment {
            asset: self.asset,
            amount: self.amount.expect("Amount is required"),
            currency_code: self.currency_code,
            supported_assets: self.supported_assets,
            customer: self.customer,
            merchant: self.merchant.expect("Merchant is required"),
            transaction_id: self.transaction_id,
            memo: self.memo,
            expiry: self.expiry,
            invoice: self.invoice,
            agents: self.agents,
            connection_id: None,
            fallback_settlement_addresses: self.fallback_settlement_addresses,
            metadata: self.metadata,
        }
    }
}

impl Payment {
    /// Creates a builder for constructing Payment objects
    pub fn builder() -> PaymentBuilder {
        PaymentBuilder::default()
    }

    /// Creates a new Payment with an asset
    pub fn with_asset(asset: AssetId, amount: String, merchant: Party, agents: Vec<Agent>) -> Self {
        Self {
            asset: Some(asset),
            amount,
            currency_code: None,
            supported_assets: None,
            customer: None,
            merchant,
            transaction_id: None,
            memo: None,
            expiry: None,
            invoice: None,
            agents,
            connection_id: None,
            fallback_settlement_addresses: None,
            metadata: HashMap::new(),
        }
    }

    /// Creates a new Payment with a currency
    pub fn with_currency(
        currency_code: String,
        amount: String,
        merchant: Party,
        agents: Vec<Agent>,
    ) -> Self {
        Self {
            asset: None,
            amount,
            currency_code: Some(currency_code),
            supported_assets: None,
            customer: None,
            merchant,
            transaction_id: None,
            memo: None,
            expiry: None,
            invoice: None,
            agents,
            connection_id: None,
            fallback_settlement_addresses: None,
            metadata: HashMap::new(),
        }
    }

    /// Creates a new Payment with a currency and supported assets
    pub fn with_currency_and_assets(
        currency_code: String,
        amount: String,
        supported_assets: Vec<SupportedAsset>,
        merchant: Party,
        agents: Vec<Agent>,
    ) -> Self {
        Self {
            asset: None,
            amount,
            currency_code: Some(currency_code),
            supported_assets: Some(supported_assets),
            customer: None,
            merchant,
            transaction_id: None,
            memo: None,
            expiry: None,
            invoice: None,
            agents,
            connection_id: None,
            fallback_settlement_addresses: None,
            metadata: HashMap::new(),
        }
    }

    /// Custom validation for Payment messages
    pub fn validate(&self) -> Result<()> {
        // Validate either asset or currency_code is provided
        if self.asset.is_none() && self.currency_code.is_none() {
            return Err(Error::Validation(
                "Either asset or currency_code must be provided".to_string(),
            ));
        }

        // Validate asset ID if provided
        if let Some(asset) = &self.asset {
            if asset.namespace().is_empty() || asset.reference().is_empty() {
                return Err(Error::Validation("Asset ID is invalid".to_string()));
            }
        }

        // Validate amount
        if self.amount.is_empty() {
            return Err(Error::Validation("Amount is required".to_string()));
        }

        // Validate amount is a finite positive number
        match self.amount.parse::<f64>() {
            Ok(amount) if !amount.is_finite() => {
                return Err(Error::Validation(
                    "Amount must be a finite number".to_string(),
                ));
            }
            Ok(amount) if amount <= 0.0 => {
                return Err(Error::Validation("Amount must be positive".to_string()));
            }
            Err(_) => {
                return Err(Error::Validation(
                    "Amount must be a valid number".to_string(),
                ));
            }
            _ => {}
        }

        // Validate merchant
        if self.merchant.id().is_empty() {
            return Err(Error::Validation("Merchant ID is required".to_string()));
        }

        // Validate supported_assets if provided
        if let Some(supported_assets) = &self.supported_assets {
            if supported_assets.is_empty() {
                return Err(Error::Validation(
                    "Supported assets list cannot be empty".to_string(),
                ));
            }

            for (i, supported) in supported_assets.iter().enumerate() {
                match supported {
                    SupportedAsset::Simple(asset) => {
                        if asset.namespace().is_empty() || asset.reference().is_empty() {
                            return Err(Error::Validation(format!(
                                "Supported asset at index {} is invalid",
                                i
                            )));
                        }
                    }
                    SupportedAsset::Priced(pricing) => {
                        if pricing.asset.is_empty() {
                            return Err(Error::Validation(format!(
                                "Supported asset at index {} has empty asset identifier",
                                i
                            )));
                        }
                        if pricing.amount.is_empty() {
                            return Err(Error::Validation(format!(
                                "Supported asset at index {} has empty amount",
                                i
                            )));
                        }
                    }
                }
            }
        }

        // If invoice is provided, validate it
        if let Some(invoice) = &self.invoice {
            // Call the validate method on the invoice
            if let Err(e) = invoice.validate() {
                return Err(Error::Validation(format!(
                    "Invoice validation failed: {}",
                    e
                )));
            }
        }

        Ok(())
    }
}