taler-ios

iOS apps for GNU Taler (wallet)
Log | Files | Refs | README | LICENSE

Model+Payment.swift (27725B)


      1 /*
      2  * This file is part of GNU Taler, ©2022-26 Taler Systems S.A.
      3  * See LICENSE.md
      4  */
      5 /**
      6  * @author Marc Stibane
      7  */
      8 import Foundation
      9 import taler_swift
     10 import AnyCodable
     11 //import SymLog
     12 
     13 typealias I18nDict = [String: String]           // two-char language code, e.g. "de", "en"
     14 extension I18nDict {
     15     var localized: String? {
     16         if !self.isEmpty {
     17             for code in Locale.preferredLanguageCodes {
     18                 if let i18n = self[code] {
     19                     return i18n
     20                 }
     21             }
     22         }
     23         return nil
     24     }
     25 }
     26 // MARK: - ContractTerms
     27 
     28 struct TokenIssuePublicKey: Codable {
     29     let cipher: String          // "RSA", "CS"
     30 
     31     // RSA public key
     32     let rsaPub: String?         // RSA public key converted to Crockford Base32
     33 
     34     // CS public key
     35     let csPub: String?          // 32-byte value representing a point on Curve25519
     36 
     37     // Start time of this key's signatures validity period
     38     let signatureValidityStart: Timestamp
     39 
     40     // End time of this key's signatures validity period
     41     let signatureValidityEnd: Timestamp
     42 
     43     enum CodingKeys: String, CodingKey {
     44         case cipher
     45         case rsaPub = "rsa_pub"
     46         case csPub = "cs_pub"
     47         case signatureValidityStart = "signature_validity_start"
     48         case signatureValidityEnd = "signature_validity_end"
     49     }
     50 }
     51 
     52 struct ContractTokenDetails: Codable {
     53     let clazz: String                           // "subscription", "discount"
     54 
     55     // Array of domain names where this subscription can be safely used
     56     // (e.g. the issuer warrants that these sites will re-issue tokens of this type
     57     // if the respective contract says so).  May contain "*" for any domain or subdomain.
     58     let trustedDomains: [String]?               // only for subscription
     59 
     60     // Array of domain names where this discount token is intended to be used.
     61     // May contain "*" for any domain or subdomain.  Users should be warned about sites
     62     // proposing to consume discount tokens of this type that are not in this list that
     63     // the merchant is accepting a coupon from a competitor and thus may be attaching
     64     // different semantics (like get 20% discount for my competitors 30% discount token).
     65     let expectedDomains: [String]?              // only for discount
     66 
     67     enum CodingKeys: String, CodingKey {
     68         case clazz = "class"
     69         case trustedDomains = "trusted_domains"
     70         case expectedDomains = "expected_domains"
     71     }
     72 
     73     var isDiscount: Bool {
     74         clazz.lowercased() == "discount"
     75     }
     76     var isSubscription: Bool {
     77         clazz.lowercased() == "subscription"
     78     }
     79 }
     80 
     81 struct ContractTokenFamily: Codable {
     82     // Human-readable name of the token family.
     83     let name: String
     84 
     85     // Human-readable description of the semantics of this token family (for display).
     86     let description: String
     87 
     88     // Map from IETF BCP 47 language tags to localized descriptions.
     89     let descriptionI18n: I18nDict?
     90 
     91     // Public keys used to validate tokens issued by this token family.
     92     let keys: [TokenIssuePublicKey]
     93 
     94     // Kind-specific information of the token
     95     let details: ContractTokenDetails
     96 
     97     // Must a wallet understand this token type to
     98     // process contracts that use or issue it?
     99     let critical: Bool
    100 
    101     enum CodingKeys: String, CodingKey {
    102         case name, description
    103         case descriptionI18n = "description_i18n"
    104         case keys, details, critical
    105     }
    106 
    107     var isDiscount: Bool {
    108         details.isDiscount
    109     }
    110     var isSubscription: Bool {
    111         details.isSubscription
    112     }
    113 }
    114 
    115 struct ContractInput: Codable, Hashable {
    116     let type: String                            // "token"
    117 
    118     // Slug of the token family in the token_families map on the order
    119     let tokenFamilySlug: String?
    120 
    121     // Number of tokens of this type required.
    122     // Defaults to one if the field is not provided.
    123     let count: Int?
    124 
    125     enum CodingKeys: String, CodingKey {
    126         case type, count
    127         case tokenFamilySlug = "token_family_slug"
    128     }
    129 }
    130 
    131 struct ContractOutput: Codable, Hashable {
    132     let type: String                            // "token"
    133 
    134     // Slug of the token family in the token_families map on the order
    135     let tokenFamilySlug: String?
    136 
    137     // Number of tokens of this type required.
    138     // Defaults to one if the field is not provided.
    139     let count: Int?
    140 
    141     // Index of the public key for this output token
    142     // in the ContractTokenFamily keys array.
    143     let keyIndex: Int
    144 
    145     enum CodingKeys: String, CodingKey {
    146         case type, count
    147         case tokenFamilySlug = "token_family_slug"
    148         case keyIndex = "key_index"
    149     }
    150 }
    151 
    152 struct ContractOutputTaxReceipt: Codable, Hashable {
    153     let type: String                            // "tax-receipt"
    154 
    155     // Array of base URLs of donation authorities that can be
    156     // used to issue the tax receipts. The client must select one.
    157     let donauUrls: [String]
    158 
    159     // Total amount that will be on the tax receipt.
    160     let amount: Amount?
    161 
    162     enum CodingKeys: String, CodingKey {
    163         case type, amount
    164         case donauUrls = "donau_urls"
    165     }
    166 }
    167 
    168 /// wallet-core sends a union discriminated on "type" - a tax-receipt output has neither
    169 /// "key_index" nor "token_family_slug", so decoding it as ContractOutput throws and takes
    170 /// the whole getChoicesForPayment response with it, leaving nothing for the user to confirm.
    171 enum ContractOutputAny: Codable, Hashable {
    172     case token(ContractOutput)
    173     case taxReceipt(ContractOutputTaxReceipt)
    174     case unknown(String)                        // a type added after this was written
    175 
    176     private enum TypeKey: String, CodingKey {
    177         case type
    178     }
    179 
    180     init(from decoder: Decoder) throws {
    181         let container = try decoder.container(keyedBy: TypeKey.self)
    182         switch try container.decode(String.self, forKey: .type) {
    183             case "token":       self = .token(try ContractOutput(from: decoder))
    184             case "tax-receipt": self = .taxReceipt(try ContractOutputTaxReceipt(from: decoder))
    185             case let other:     self = .unknown(other)
    186         }
    187     }
    188 
    189     func encode(to encoder: Encoder) throws {
    190         switch self {
    191             case .token(let output):      try output.encode(to: encoder)
    192             case .taxReceipt(let output): try output.encode(to: encoder)
    193             case .unknown(let type):
    194                 var container = encoder.container(keyedBy: TypeKey.self)
    195                 try container.encode(type, forKey: .type)
    196         }
    197     }
    198 }
    199 
    200 struct ContractChoice: Codable, Hashable {
    201     let amount: Amount                          // Total amount payable
    202     let maxFee: Amount                          // Maximum deposit fee covered by the merchant
    203     let description: String?                    //
    204     let descriptionI18n: I18nDict?              //      "      localized     "
    205     let inputs: [ContractInput]
    206     let outputs: [ContractOutputAny]
    207 
    208     enum CodingKeys: String, CodingKey {
    209         case amount, description
    210         case maxFee = "max_fee"
    211         case descriptionI18n = "description_i18n"
    212         case inputs, outputs
    213     }
    214 
    215     var locDescription: String? {
    216         self.descriptionI18n?.localized ?? self.description
    217     }
    218 }
    219 
    220 struct MerchantContractTerms: Codable {
    221     let version: Int?                   // v0 doesn't know this
    222 
    223     // ContractTermsV0
    224     let amount: Amount?                 // Total amount payable
    225     let maxFee: Amount?                 // Maximum deposit fee covered by the merchant
    226 
    227     // ContractTermsCommon
    228     let summary: String                 // Human-readable short summary of the contract
    229     let summaryI18n: I18nDict?          //      "      localized     "
    230     let orderID: String                 // uniquely identify the purchase within one merchant instance
    231     let publicReorderURL: String?       // URL meant to share the shopping cart
    232     let fulfillmentURL: String?         // Fulfillment URL to view the product or delivery status
    233     let fulfillmentMessage: String?     // Plain text fulfillment message in the merchant's default language
    234     let fulfillmentMessageI18n: I18nDict?//      "      localized     ", keyed by BCP-47 tag
    235     let products: [ProductSold]?        // Products that are sold in this contract
    236     let timestamp: Timestamp            // Time when the contract was generated by the merchant
    237     let refundDeadline: Timestamp?      // Deadline for refunds
    238     let payDeadline: Timestamp          // Deadline to pay for the contract
    239     let wireTransferDeadline: Timestamp?// Deadline for the wire transfer
    240     let merchantPub: String             // Public key of the merchant
    241     let merchantBaseURL: String         // Base URL of the merchant's backend
    242     let merchant: MerchantInfo
    243     let hWire: String                   // Hash of the merchant's wire details
    244     let wireMethod: String              // merchant wants to use
    245     let exchanges: [ExchangeForPay]
    246     let deliveryLocation: Location?     // Delivery location for (all!) products
    247     let deliveryDate: Timestamp?        // indicating when the order should be delivered
    248     let nonce: String                   // used to ensure freshness
    249     let autoRefund: Duration?
    250     let extra: Extra?                   // Extra data, interpreted by the merchant only
    251     let minimumAge: Int?
    252 
    253     let defaultMoneyPot: Int?
    254 
    255 // deprecated   let auditors: [Auditor]?
    256 
    257     // ContractTermsV1
    258     let choices: [ContractChoice]?
    259     // Map of storing metadata and issue keys of
    260     // token families referenced in this contract.
    261     // @since protocol **vSUBSCRIBE**
    262     let tokenFamilies: [String: ContractTokenFamily]?   // token_family_slug: String
    263 
    264     enum CodingKeys: String, CodingKey {
    265         case version
    266         case amount
    267         case maxFee = "max_fee"
    268 
    269         case summary
    270         case summaryI18n = "summary_i18n"
    271         case orderID = "order_id"
    272         case publicReorderURL = "public_reorder_url"
    273         case fulfillmentURL = "fulfillment_url"
    274         case fulfillmentMessage = "fulfillment_message"
    275         case fulfillmentMessageI18n = "fulfillment_message_i18n"
    276         case products
    277         case timestamp
    278         case refundDeadline = "refund_deadline"
    279         case payDeadline = "pay_deadline"
    280         case wireTransferDeadline = "wire_transfer_deadline"
    281         case merchantPub = "merchant_pub"
    282         case merchantBaseURL = "merchant_base_url"
    283         case merchant
    284         case hWire = "h_wire"
    285         case wireMethod = "wire_method"
    286         case exchanges
    287         case deliveryLocation = "delivery_location"
    288         case deliveryDate = "delivery_date"
    289         case nonce
    290         case autoRefund = "auto_refund"
    291         case extra
    292         case minimumAge = "minimum_age"
    293         case defaultMoneyPot = "default_money_pot"
    294 
    295 //        case auditors
    296         case choices
    297         case tokenFamilies = "token_families"
    298     }
    299 
    300     func timeToPay(_ debug: Bool) -> Int? {
    301         if let milliseconds = try? self.payDeadline.milliseconds() {
    302             let date = Date(milliseconds: milliseconds)
    303             let now = Date.now
    304             let timeInterval = now.timeIntervalSince(date)
    305             if timeInterval < 0 {
    306                 let result = Int(-timeInterval)
    307                 if debug {
    308 //                  symLog?.log("\(timeInterval) seconds left to pay")
    309                     print("\(result) seconds left to pay")
    310                 }
    311                 return result
    312             } else if debug {
    313 //              symLog?.log("\(date) - \(now) = \(timeInterval)")
    314                 print("\(date) - \(now) = \(timeInterval)")
    315             }
    316             return 0
    317         } else if debug {
    318 //            symLog?.log("no milliseconds")
    319             print("no milliseconds in payDeadline")
    320         }
    321         return nil
    322     }
    323 
    324     var locSummary: String {
    325         self.summaryI18n?.localized ?? self.summary
    326     }
    327 }
    328 // MARK: - Auditor
    329 struct Auditor: Codable {
    330     let name: String
    331     let auditorPub: String
    332     let url: String
    333 
    334     enum CodingKeys: String, CodingKey {
    335         case name
    336         case auditorPub = "auditor_pub"
    337         case url
    338     }
    339 }
    340 // MARK: - Exchange
    341 struct ExchangeForPay: Codable {
    342     let url: String
    343     let masterPub: String
    344 
    345     enum CodingKeys: String, CodingKey {
    346         case url
    347         case masterPub = "master_pub"
    348     }
    349 }
    350 // MARK: - Extra
    351 struct Extra: Codable {
    352     let articleName: String?
    353 
    354     enum CodingKeys: String, CodingKey {
    355         case articleName = "article_name"
    356     }
    357 }
    358 // MARK: -
    359 enum PreparePayResultType: String, Codable {
    360     case paymentPossible = "payment-possible"
    361     case alreadyConfirmed = "already-confirmed"
    362     case insufficientBalance = "insufficient-balance"
    363     case choiceSelection = "choice-selection"
    364 }
    365 
    366 struct ExchangeFeeGapEstimate: Codable {
    367     let balanceAvailable: Amount
    368     let balanceMaterial: Amount
    369     let balanceExchangeDepositable: Amount
    370     let balanceAgeAcceptable: Amount
    371     let balanceReceiverAcceptable: Amount
    372     let balanceReceiverDepositable: Amount
    373     let maxEffectiveSpendAmount: Amount
    374 }
    375 
    376 struct PerScopeDetails: Codable {
    377     let scopeInfo: ScopeInfo
    378 }
    379 
    380 /// The result from PreparePayForUri2 and preparePayForTemplate2
    381 struct PreparePayResult2: Codable {
    382     let transactionId: String
    383 }
    384 /// A request to get an exchange's payment contract terms.
    385 fileprivate struct PreparePayForUri: WalletBackendFormattedRequest {
    386     typealias Response = PreparePayResult2
    387     var operation: String { "preparePayForUriV2" }
    388     func args() -> Args { Args(talerPayUri: talerPayUri) }  // No progressToken! use waitTransactionState
    389 
    390     var talerPayUri: String
    391     struct Args: Encodable {
    392         var talerPayUri: String
    393     }
    394 }
    395 
    396 /**
    397  * Forced coin selection for deposits/payments.
    398  */
    399 struct ValueContribution: Codable {
    400     var value: Amount
    401     var contribution: Amount
    402 }
    403 
    404 struct ForcedCoinSel: Codable {
    405     var coins: [ValueContribution]
    406 }
    407 
    408 enum ChoiceSelectionDetailStatus: String, Codable {
    409     case paymentPossible = "payment-possible"
    410     case insufficientBalance = "insufficient-balance"
    411 }
    412 
    413 enum TokenAvailabilityHint: String, Codable {
    414     case walletTokensAvailableInsufficient = "wallet-tokens-available-insufficient"
    415     case merchantUnexpected = "merchant-unexpected"
    416     case merchantUntrusted = "merchant-untrusted"
    417 
    418 }
    419 
    420 struct TokenFamily: Codable, Hashable, Equatable {
    421     var causeHint: TokenAvailabilityHint?
    422     var requested: Int
    423     var available: Int
    424     var unexpected: Int
    425     var untrusted: Int
    426 }
    427 
    428 struct TokenDetails: Codable, Hashable, Equatable {
    429     var tokensRequested: Int
    430     var tokensAvailable: Int
    431     var tokensUnexpected: Int
    432     var tokensUntrusted: Int
    433     var perTokenFamily: [String: TokenFamily]
    434 }
    435 
    436 struct ChoiceSelectionDetail: Codable, Hashable, Sendable {
    437     var status: ChoiceSelectionDetailStatus
    438     var amountRaw: Amount
    439     var scopeInfo: ScopeInfo?                                   // only if wallet-core has the info
    440     var amountEffective: Amount?                                // only if possible
    441     var tokenDetails: TokenDetails?                             // only if possible
    442     var balanceDetails: PaymentInsufficientBalanceDetails?      // only if insufficient
    443 }
    444 
    445 typealias ChoiceTriple = (ChoiceSelectionDetail, ContractChoice, Int)
    446 typealias ChoicesTuple = (String?, ChoicesForPayment?)        // txID
    447 
    448 struct ChoicesForPayment: Codable {
    449     var choices: [ChoiceSelectionDetail]
    450     /**
    451      * Index of the choice in @e choices array to present to the user as default.
    452      * Won´t be set if no default selection is configured or no choice is payable,
    453      * otherwise, it will always be 0 for v0 orders.
    454      */
    455     var defaultChoiceIndex: Int?
    456     /**
    457      * Whether the choice referenced by @e automaticExecutableIndex
    458      * should be confirmed automatically without user interaction.
    459      *
    460      * If true, the wallet should call `confirmPay' immediately afterwards
    461      * If false, the user should be first prompted to select and confirm a choice.
    462      * Undefined when no choices are payable.
    463      */
    464     var automaticExecution: Bool?
    465     var automaticExecutableIndex: Int?
    466 
    467     var contractTerms: MerchantContractTerms
    468 
    469     func choiceTriple() -> ([ChoiceTriple], Bool)? {
    470         let terms = self.contractTerms
    471         if let ctChoices = terms.choices {
    472             let combined = Array(zip(choices, ctChoices, ctChoices.indices))
    473             return (combined, true)
    474         } else if let amount = terms.amount {       // V0 = only 1 option
    475             let maxFee = terms.maxFee ?? Amount.zero(currency: amount.currencyStr)
    476             let ctChoice = ContractChoice(amount: amount,
    477                                           maxFee: maxFee,
    478                                      description: terms.summary,
    479                                  descriptionI18n: terms.summaryI18n,
    480                                           inputs: [],
    481                                          outputs: [])
    482             let combined = Array(zip(choices, [ctChoice], [0]))
    483             return (combined, false)
    484         }
    485 //        symLog.log("  ❗️Yikes, neither choices nor amount in contractTerms!\n\(stack)")
    486         return nil
    487     }
    488 }
    489 
    490 /// A request to get an exchange's payment contract terms.
    491 fileprivate struct GetChoicesForPayment: WalletBackendFormattedRequest {
    492     typealias Response = ChoicesForPayment
    493     var operation: String { "getChoicesForPayment" }
    494     func args() -> Args { Args(transactionId: transactionId, forcedCoinSel: forcedCoinSel) }
    495 
    496     var transactionId: String
    497     var forcedCoinSel: ForcedCoinSel?
    498     struct Args: Encodable {
    499         var transactionId: String
    500         var forcedCoinSel: ForcedCoinSel?
    501     }
    502 }
    503 
    504 struct TemplateParams: Codable {
    505     let amount: Amount?                     // Total amount payable
    506     let summary: String?                    // Human-readable short summary of the contract
    507 }
    508 
    509 /// A request to get an exchange's payment contract terms.
    510 fileprivate struct PreparePayForTemplateRequest: WalletBackendFormattedRequest {
    511     typealias Response = PreparePayResult2
    512     var operation: String { "preparePayForTemplateV2" }
    513     func args() -> Args { Args(talerPayTemplateUri: talerPayTemplateUri, templateParams: templateParams,
    514                                progressToken: talerPayTemplateUri) }
    515 
    516     var talerPayTemplateUri: String
    517     var templateParams: TemplateParams
    518     struct Args: Encodable {
    519         var talerPayTemplateUri: String
    520         var templateParams: TemplateParams
    521         var progressToken: String
    522     }
    523 }
    524 // MARK: -
    525 enum TemplateType: String, Codable {
    526     case fixedOrder = "fixed-order"
    527     case inventoryCart = "inventory-cart"
    528     case paivana
    529 }
    530 
    531 struct TemplateContractDetails: Codable {
    532     let summary: String?                // Human-readable short summary of the contract. Editable if nil
    533     let currency: String?               // specify currency when amount is nil - unspecified if nil
    534     let payDuration: Duration?
    535     let maxPickupDuration: Duration?
    536     let minimumAge: Int?
    537     let requestTip: Bool?
    538 
    539     let templateType: TemplateType?
    540     let amount: Amount?                 // Total amount payable. Fixed if this field exists, editable if nil
    541     let scopeInfo: ScopeInfo?           // unfortunately this DOESN'T exist - but it should
    542     let websiteRegex: String?
    543     let choices: [OrderChoice]?
    544 
    545     enum CodingKeys: String, CodingKey {
    546         case summary, currency, amount
    547         case scopeInfo, choices
    548         case minimumAge = "minimum_age"
    549         case requestTip = "request_tip"
    550         case payDuration = "pay_duration"
    551         case maxPickupDuration = "max_pickup_duration"
    552         case websiteRegex = "website_regex"
    553         case templateType = "template_type"
    554     }
    555 }
    556 
    557 struct OrderChoice: Codable {
    558     let amount: Amount
    559     let tip: Amount?
    560     let description: String?
    561     let descriptionI18n: I18nDict?
    562     let inputs: [OrderInput]?
    563     let outputs: [OrderOutput]?     // TODO: OrderOutputTaxReceipt
    564     let maxFee: Amount?
    565 
    566     enum CodingKeys: String, CodingKey {
    567         case amount, tip, description
    568         case descriptionI18n = "description_i18n"
    569         case inputs, outputs
    570         case maxFee = "max_fee"
    571     }
    572 }
    573 
    574 struct OrderInput: Codable {    // see ContractInput
    575     let type: String                            // "token"
    576 
    577     // Token family slug as configured in the merchant backend.
    578     // Slug is unique across all configured tokens of a merchant.
    579     let tokenFamilySlug: String?
    580 
    581     // How many units of the input are required.
    582     // Defaults to 1 if not specified.
    583     // Output with count == 0 are ignored by the merchant backend.
    584     let count: Int?
    585 
    586     enum CodingKeys: String, CodingKey {
    587         case type, count
    588         case tokenFamilySlug = "token_family_slug"
    589     }
    590 }
    591 
    592 struct OrderOutput: Codable {   // TODO: ContractOutput
    593     let type: String                            // "token"
    594 
    595     // Token family slug as configured in the merchant backend.
    596     // Slug is unique across all configured tokens of a merchant.
    597     let tokenFamilySlug: String?
    598 
    599     // How many units of the output are issued by the merchant.
    600     // Defaults to 1 if not specified.
    601     // Output with count == 0 are ignored by the merchant backend.
    602     let count: Int?
    603 
    604     // When should the output token be valid. Can be specified if the
    605     // desired validity period should be in the future (like selling
    606     // a subscription for the next month). Optional. If not given,
    607     // the validity is supposed to be "now" (time of order creation).
    608     let validAt: Timestamp?
    609 
    610     enum CodingKeys: String, CodingKey {
    611         case type, count
    612         case tokenFamilySlug = "token_family_slug"
    613         case validAt = "valid_at"
    614     }
    615 }
    616 
    617 struct OrderOutputTaxReceipt: Codable {
    618     let type: String                            // "tax-receipt"
    619 }
    620 
    621 struct TemplateContractDetailsDefaults: Codable {
    622     let summary: String?                // Default 'Human-readable summary' when editable: empty if nil
    623     let currency: String?               // Default currency when unspecified: any if nil (e.g. donations)
    624     let amount: Amount?                 // Default amount when editable: unspecified if nil
    625 }
    626 
    627 struct TalerMerchantTemplateDetails: Codable {
    628     let templateContract: TemplateContractDetails
    629     let editableDefaults: TemplateContractDetailsDefaults?
    630     let requiredCurrency: String?
    631     enum CodingKeys: String, CodingKey {
    632         case templateContract = "template_contract"
    633         case editableDefaults = "editable_defaults"
    634         case requiredCurrency = "required_currency"
    635     }
    636 }
    637 
    638 struct AvailableBalance: Codable {
    639     let scopeInfo: ScopeInfo
    640     let amountAvailable: Amount
    641 }
    642 
    643 /// The result from checkPayForTemplate
    644 struct WalletTemplateDetails: Codable {
    645     let templateDetails: TalerMerchantTemplateDetails
    646     let supportedCurrencies: [String]
    647     let availableBalances: [AvailableBalance]?
    648 }
    649 /// A request to get an exchange's payment contract terms.
    650 fileprivate struct CheckPayForTemplate: WalletBackendFormattedRequest {
    651     typealias Response = WalletTemplateDetails
    652     var operation: String { "checkPayForTemplate" }
    653     func args() -> Args { Args(talerPayTemplateUri: talerPayTemplateUri, progressToken: talerPayTemplateUri) }
    654 
    655     var talerPayTemplateUri: String
    656     struct Args: Encodable {
    657         var talerPayTemplateUri: String
    658         var progressToken: String
    659     }
    660 }
    661 // MARK: -
    662 /// The result from confirmPayForUri
    663 struct ConfirmPayResult: Decodable {
    664     var type: String?                               // done || pending
    665     var contractTerms: MerchantContractTerms?       // only if type==done
    666     var transactionId: String
    667     var lastError: TalerErrorDetail?                // might, but only if type==pending
    668 }
    669 
    670 /// A request to get an exchange's payment details.
    671 fileprivate struct ConfirmPayForUri: WalletBackendFormattedRequest {
    672     typealias Response = ConfirmPayResult
    673     var operation: String { "confirmPay" }
    674     func args() -> Args { Args(transactionId: transactionId, noWait: true,
    675                                  choiceIndex: choiceIndex) }
    676     var transactionId: String
    677     var choiceIndex: Int?
    678     struct Args: Encodable {
    679         var transactionId: String
    680         var noWait: Bool?
    681         var useDonau: Bool?
    682         var sessionId: String?
    683         var forcedCoinSel: ForcedCoinSel?
    684         /**
    685          * Whether token selection should be forced
    686          * e.g. use tokens with non-matching `expected_domains'
    687          *
    688          * Only applies to v1 orders.
    689          */
    690         var forcedTokenSel: Bool?
    691         /**
    692          * Only applies to v1 orders.
    693          */
    694         var choiceIndex: Int?
    695     }
    696 }
    697 
    698 struct UnclaimPaymentResult: Decodable {
    699     var talerPayUri: String
    700 }
    701 
    702 fileprivate struct UnclaimPayment: WalletBackendFormattedRequest {
    703     typealias Response = UnclaimPaymentResult
    704     var operation: String { "unclaimPayment" }
    705     func args() -> Args { Args(transactionId: transactionId, progressToken: transactionId) }
    706 
    707     var transactionId: String
    708     struct Args: Encodable {
    709         var transactionId: String
    710         var progressToken: String?
    711     }
    712 }
    713 // MARK: -
    714 extension WalletModel {
    715     /// load payment details. Networking involved
    716     nonisolated func checkPayForTemplate(_ talerPayTemplateUri: String, viewHandles: Bool = false)
    717       async throws -> WalletTemplateDetails {
    718         let request = CheckPayForTemplate(talerPayTemplateUri: talerPayTemplateUri)
    719         let controller = Controller.shared
    720         controller.progressOperation = request.operation
    721         controller.progressToken = talerPayTemplateUri
    722         let (response, _) = try await sendRequest(request, viewHandles: viewHandles)
    723         return response
    724     }
    725 
    726     nonisolated func preparePayForTemplate(_ talerPayTemplateUri: String, amount: Amount?, summary: String?, viewHandles: Bool = false)
    727       async throws -> PreparePayResult2 {
    728         let templateParams = TemplateParams(amount: amount, summary: summary)
    729         let request = PreparePayForTemplateRequest(talerPayTemplateUri: talerPayTemplateUri, templateParams: templateParams)
    730         let controller = Controller.shared
    731         controller.progressOperation = request.operation
    732         controller.progressToken = talerPayTemplateUri
    733         let (response, _) = try await sendRequest(request, viewHandles: viewHandles)
    734         return response
    735     }
    736 
    737     nonisolated func getChoicesForPayment(_ transactionId: String, viewHandles: Bool = false)
    738       async throws -> ChoicesForPayment {
    739         let request = GetChoicesForPayment(transactionId: transactionId, forcedCoinSel: nil)
    740         let (response, _) = try await sendRequest(request, viewHandles: viewHandles)
    741         return response
    742     }
    743 
    744     nonisolated func preparePayForUri(_ talerPayUri: String, viewHandles: Bool = false)
    745       async throws -> PreparePayResult2 {
    746         let request = PreparePayForUri(talerPayUri: talerPayUri)
    747         let (response, _) = try await sendRequest(request, viewHandles: viewHandles)
    748         return response
    749     }
    750 
    751     nonisolated func confirmPay(_ transactionId: String, choiceIndex: Int?, viewHandles: Bool = false)
    752       async throws -> ConfirmPayResult {
    753         let request = ConfirmPayForUri(transactionId: transactionId,
    754                                        choiceIndex: choiceIndex)
    755         let (response, _) = try await sendRequest(request, viewHandles: viewHandles)
    756         return response
    757     }
    758 
    759     nonisolated func unclaimPayment(_ transactionId: String, viewHandles: Bool = false)
    760       async throws -> String {
    761         let request = UnclaimPayment(transactionId: transactionId)
    762         let controller = Controller.shared
    763         controller.progressOperation = request.operation
    764         controller.progressToken = transactionId
    765         let (response, _) = try await sendRequest(request, viewHandles: viewHandles)
    766         return response.talerPayUri
    767     }
    768 }