taler-ios

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

WalletBackendRequest.swift (10194B)


      1 /*
      2  * This file is part of GNU Taler, ©2022-25 Taler Systems S.A.
      3  * See LICENSE.md
      4  */
      5 /**
      6  * @author Jonathan Buchanan
      7  * @author Marc Stibane
      8  */
      9 import Foundation
     10 import AnyCodable
     11 import taler_swift
     12 
     13 /// A request sent to the wallet backend.
     14 struct WalletBackendRequest: Encodable {
     15     /// The operation name of the request.
     16     var operation: String
     17     
     18     /// The body of the request as JSON.
     19     var args: AnyEncodable
     20 }
     21 
     22 protocol WalletBackendFormattedRequest {
     23     associatedtype Args: Encodable
     24     associatedtype Response: Decodable
     25     
     26     var operation: String { get }
     27     func args() -> Args
     28 }
     29 // MARK: -
     30 /// The scope of a currency: either global or a dedicated exchange
     31 struct ScopeInfo: Codable, Hashable {
     32     enum ScopeInfoType: String, Codable {
     33         case global
     34         case exchange
     35         case auditor
     36         case exchangeLegacyKeys = "exchange-legacy-keys"
     37         case unknown     // => type unknown, currency name taken from amount
     38 
     39         /// A scope type this app does not know must not make the whole balance list undecodable.
     40         /// NOTE: `unknown` is app-invented and wallet-core's codecForScopeInfo rejects it,
     41         /// so a degraded ScopeInfo must never be sent back as an argument.
     42         init(from decoder: Decoder) throws {
     43             let raw = try decoder.singleValueContainer().decode(String.self)
     44             self = ScopeInfoType(rawValue: raw) ?? .unknown
     45         }
     46     }
     47     var type: ScopeInfoType
     48     var currency: String        // 3-char ISO 4217 code for global currency. Regional MUST be >= 4 letters
     49     var noFees: Bool?           // only for "global". Regional have this field per Exchange
     50     var url: String?            // only for "exchange", "auditor" and "exchange-legacy-keys"
     51     var masterPub: String?      // only for "exchange-legacy-keys": the superseded key
     52     var isValid: Bool {
     53         switch type {
     54             case .global, .exchange, .auditor: return true
     55             default: return false
     56         }
     57     }
     58 
     59     public static func zero() -> ScopeInfo {
     60         ScopeInfo(type: .unknown, currency: UNKNOWN)
     61     }
     62     public static func zero(_ currency: String) -> ScopeInfo {
     63         ScopeInfo(type: .unknown, currency: currency)
     64     }
     65     public static func < (lhs: ScopeInfo, rhs: ScopeInfo) -> Bool {
     66         if lhs.type == .global {
     67             if rhs.type == .global {        // both global ==> alphabetic currency
     68                 return lhs.currency < rhs.currency
     69             }
     70             return true                     // global comes first
     71         }
     72         if rhs.type == .global {
     73             return false                    // global comes first
     74         }
     75         if lhs.currency == rhs.currency {
     76             if let lhsBaseURL = lhs.url {
     77                 if let rhsBaseURL = rhs.url {
     78                     return lhsBaseURL < rhsBaseURL
     79                 }
     80                 return true
     81             }
     82             if rhs.url != nil {
     83                 return false
     84             }
     85             // fall thru
     86         }
     87         return lhs.currency < rhs.currency
     88     }
     89     public static func == (lhs: ScopeInfo, rhs: ScopeInfo) -> Bool {
     90         if let lhsBaseURL = lhs.url {
     91             if let rhsBaseURL = rhs.url {
     92                 if lhsBaseURL != rhsBaseURL { return false }    // different exchanges
     93                                                                 // else fall thru and check type & currency
     94             } else { return false }                             // left but not right
     95         } else if rhs.url != nil {
     96             return false                                        // right but not left
     97         }
     98         return lhs.type == rhs.type &&
     99         lhs.currency == rhs.currency &&
    100         lhs.masterPub == rhs.masterPub      // two legacy-key scopes of one exchange differ
    101     }
    102     public func hash(into hasher: inout Hasher) {
    103         hasher.combine(type)
    104         if let url {
    105             hasher.combine(url)
    106         }
    107         hasher.combine(currency)
    108         hasher.combine(masterPub)
    109     }
    110 }
    111 // MARK: -
    112 /// A billing or mailing location.
    113 struct Location: Codable, Equatable, Hashable {
    114     var country: String?
    115     var country_subdivision: String?
    116     var district: String?
    117     var town: String?
    118     var town_location: String?
    119     var post_code: String?
    120     var street: String?
    121     var building_name: String?
    122     var building_number: String?
    123     var address_lines: [String]?
    124 }
    125 
    126 /// Information identifying a merchant.
    127 struct MerchantInfo: Identifiable, Codable, Hashable, Sendable {
    128     var name: String
    129     var email: String?
    130     var website: String?
    131     var logo: String?       // ImageDataUrl
    132     var address: Location?
    133     var jurisdiction: Location?
    134 
    135     var id: String {
    136         return name + (email ?? EMPTYSTRING)
    137     }
    138 }
    139 
    140 /// A tax made on a payment.
    141 struct Tax: Codable, Hashable {
    142     var name: String
    143     var tax: Amount
    144 }
    145 
    146 /// A product being purchased from a merchant.
    147 /// https://docs.taler.net/core/api-merchant.html#the-contract-terms
    148 struct ProductSold: Codable, Identifiable, Hashable {
    149     let productId: String?
    150     let productName: String?
    151 //    let productGroupId: Int?
    152     let description: String
    153     let descriptionI18n: I18nDict?
    154     let quantity: Int?
    155     let unitQuantity: String?       // float with max 6 fractional digits
    156     let unit: String?               // MerchantUnit?
    157     let price: Amount?              // deprecated - use prices
    158     let prices: [Amount]?
    159     let pricesAreNet: Bool?
    160     let image: String?              // product image 128x128 encoded
    161     let taxes: [Tax]?
    162     let deliveryDate: Timestamp?
    163     let productMoneyPot: Int?
    164 
    165     var id: String { productId ?? "unknown" }
    166 
    167     var locDescription: String {
    168         self.descriptionI18n?.localized ?? self.description
    169     }
    170 
    171     enum CodingKeys: String, CodingKey {
    172         case productId = "product_id"
    173         case productName = "product_name"
    174 //        case productGroupId = "product_group_id"
    175         case description
    176         case descriptionI18n = "description_i18n"
    177         case quantity
    178         case unitQuantity = "unit_quantity"
    179 //        case unitAllowFraction = "unit_allow_fraction"
    180         case unit
    181         case price
    182 //        case unitPrice = "unit_price"
    183         case prices
    184         case pricesAreNet = "prices_are_net"
    185         case image
    186         case taxes
    187         case deliveryDate = "delivery_date"
    188         case productMoneyPot = "product_money_pot"
    189     }
    190 }
    191 
    192 
    193 /// Brief information about an order.
    194 struct OrderShortInfo: Codable {
    195     var orderId: String
    196     var merchant: MerchantInfo
    197     var summary: String
    198     var summary_i18n: I18nDict?
    199 //    var products: [Product]?      // MerchantContractTerms has [ProductSold]
    200     var fulfillmentUrl: String?
    201     var fulfillmentMessage: String?
    202     var fulfillmentMessage_i18n: I18nDict?
    203     var contractTermsHash: String?
    204 
    205     var locSummary: String {
    206         self.summary_i18n?.localized ?? self.summary
    207     }
    208 }
    209 // MARK: -
    210 /// A request to force update an exchange.
    211 struct WalletBackendForceUpdateRequest: WalletBackendFormattedRequest {
    212     var operation: String { "addRequest" }
    213     func args() -> Args { Args(exchangeBaseUrl: exchangeBaseUrl) }
    214 
    215     var exchangeBaseUrl: String
    216     struct Args: Encodable {
    217         var exchangeBaseUrl: String
    218     }
    219 
    220     struct Response: Decodable {}
    221 }
    222 
    223 /// A request to deposit funds.
    224 struct WalletBackendCreateDepositGroupRequest: WalletBackendFormattedRequest {
    225     var operation: String { "createDepositGroup" }
    226     func args() -> Args { Args(depositPayToUri: depositePayToUri, amount: amount) }
    227 
    228     var depositePayToUri: String
    229     var amount: Amount
    230     
    231     struct Args: Encodable {
    232         var depositPayToUri: String
    233         var amount: Amount
    234     }
    235     
    236     struct Response: Decodable {
    237         var depositGroupId: String
    238     }
    239 }
    240 
    241 /// A request to get information about a payment request.
    242 struct WalletBackendPreparePayRequest: WalletBackendFormattedRequest {
    243     var operation: String { "preparePay" }
    244     func args() -> Args { Args(talerPayUri: talerPayUri) }
    245     var talerPayUri: String
    246 
    247     struct Args: Encodable {
    248         var talerPayUri: String
    249     }
    250 
    251     struct Response: Decodable {}
    252 }
    253 
    254 // MARK: -
    255 struct IntegrationTestArgs: Codable {
    256     var exchangeBaseUrl: String
    257     var bankBaseUrl: String
    258     var merchantBaseUrl: String
    259     var merchantApiKey: String
    260     var amountToWithdraw: String
    261     var amountToSpend: String
    262 }
    263 
    264 /// A request to run a basic integration test.
    265 struct WalletBackendRunIntegrationTestRequest: WalletBackendFormattedRequest {
    266     var operation: String { "runIntegrationTest" }
    267     func args() -> Args { integrationTestArgs }
    268     var integrationTestArgs: IntegrationTestArgs
    269     
    270     typealias Args = IntegrationTestArgs
    271     
    272     struct Response: Decodable {}
    273 }
    274 
    275 struct TestPayArgs: Codable {
    276     var merchantBaseUrl: String
    277     var merchantApiKey: String
    278     var amount: String
    279     var summary: String
    280 }
    281 
    282 /// A request to make a test payment.
    283 struct WalletBackendTestPayRequest: WalletBackendFormattedRequest {
    284     var operation: String { "testPay" }
    285     func args() -> Args { testPayArgs }
    286 
    287     var testPayArgs: TestPayArgs
    288     typealias Args = TestPayArgs
    289     
    290     struct Response: Decodable {}
    291 }
    292 
    293 struct Coin: Codable {
    294     var denom_pub: String
    295     var denom_pub_hash: String
    296     var denom_value: String
    297     var coin_pub: String
    298     var exchange_base_url: String
    299     var remaining_value: String
    300     var refresh_parent_coin_pub: String
    301     var withdrawal_reserve_pub: String
    302     var coin_suspended: Bool
    303 }
    304 
    305 /// A request to dump all coins to JSON.
    306 struct WalletBackendDumpCoinsRequest: WalletBackendFormattedRequest {
    307     var operation: String { "dumpCoins" }
    308     func args() -> Args { Args() }
    309     struct Args: Encodable { }
    310 
    311     struct Response: Decodable {
    312         var coins: [Coin]
    313     }
    314     
    315 }
    316 
    317 /// A request to suspend or unsuspend a coin.
    318 struct WalletBackendSuspendCoinRequest: WalletBackendFormattedRequest {
    319     struct Response: Decodable {}
    320     var operation: String { "setCoinSuspended" }
    321     func args() -> Args { Args(coinPub: coinPub, suspended: suspended) }
    322 
    323     var coinPub: String
    324     var suspended: Bool
    325     
    326     struct Args: Encodable {
    327         var coinPub: String
    328         var suspended: Bool
    329     }
    330 }
    331 
    332