Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Blockchain/PaymentURI.swift3// Description: Strict parser of what a scanned QR code or a pasted text may contain (plain address, BIP-21, EIP-681,4// Solana Pay transfer request, tron:, ripple:/xrpl:, stellar: / SEP-7 pay, cosmos:, ton://transfer, cardano:)5// and builder of the URI shown by the Receive screen. Nothing here touches the network, and nothing here is ever6// executed: the result only pre-fills the Send form, which the owner reviews and the backend re-validates.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation1112/** Why a scanned or pasted text was refused. */13public enum PaymentURIRejection: Error, Sendable, Equatable {14 case empty15 /** More than `PaymentURI.maxLength` characters. */16 case tooLong17 /** A control, line-separator or invisible formatting character (bidirectional overrides, zero-width…), raw or percent-encoded. */18 case controlCharacter19 /** A web or script scheme (http, https, javascript, data, file…): the app never opens or fetches what a QR code names. */20 case forbiddenScheme(String)21 case unknownScheme(String)22 /** Not the syntax of this scheme (missing parts, white space, fragment, stray separator, empty parameter…). */23 case malformed24 case missingAddress25 /** The address part is a form this app does not resolve (ENS or other names). */26 case unsupportedAddressForm27 /** BIP-21: a `req-…` parameter this app does not understand makes the whole URI invalid. */28 case requiredParameterUnknown(String)29 case duplicateParameter(String)30 /** A parameter outside the transfer subset of the scheme (raw payloads, contract-call arguments, issued currencies…). */31 case unsupportedParameter(String)32 case badAmount33 case badChainId34 /** Invalid percent-encoding or bytes that are not UTF-8. */35 case badEncoding36 /** A request to fetch, sign or submit a prepared transaction (Solana Pay transaction request, SEP-7 `tx`): always refused. */37 case transactionRequest38 /** EIP-681 function other than the ERC-20 `transfer`. */39 case unsupportedFunction(String)40 /** A memo / tag the backend cannot carry unchanged (hash memos, a tag that is not a 32-bit number, conflicting memo type). */41 case unsupportedMemo42 /** The URI names another network than the main one (SEP-7 `network_passphrase`). */43 case wrongNetwork44 /** `make`: the address is not the valid, normalized address of the network. */45 case invalidAddress46}4748/**49 What a QR code or a pasted text asks for. THIS IS ONLY A PRE-FILLED FORM: every field is untrusted text chosen by whoever50 made the code. The app shows it in the Send form, validates the address with `AddressValidator`, lets the owner review and51 change everything, and the backend validates again. No field is ever fetched, executed or sent without that review.52 */53public struct PaymentRequest: Sendable, Equatable {54 public enum NetworkHint: Sendable, Equatable {55 /** The scheme names one network of the registry (`bitcoin`, `solana`, `xrpl`…). */56 case networkId(String)57 /** `ethereum:` URI; `chainId` is the decimal chain id after "@", nil when the URI names none (any EVM network). */58 case evm(chainId: String?)59 }6061 /** Lower-case scheme of the URI; nil for a plain address. */62 public let scheme: String?63 public let networkHint: NetworkHint?64 /** The destination exactly as written (never altered, NOT validated: use `AddressValidator.check`). */65 public let address: String66 /** Amount in whole units as decimal text ("0.5"), when the URI gives one or when its base units convert exactly; validate with `amountText(decimals:)` once the asset is known. */67 public let amount: String?68 /** Amount in base units when the URI expresses it that way (EIP-681 `value` / `uint256`, TON nanotons). */69 public let amountBaseUnits: BaseUnits?70 /** Token hint: contract (EIP-681 transfer), mint (Solana Pay `spl-token`), jetton master, or `CODE:ISSUER` (Stellar). nil = the native coin. Only a hint: the app matches it against the server's allowlist. */71 public let asset: String?72 /** Destination memo / tag (XRP `dt`, Stellar memo, Cosmos memo, TON comment, Solana memo). */73 public let memo: String?74 public let label: String?75 public let message: String?76 /** Parameters that were understood as harmless and left out (fee hints, references, callbacks, unknown optional BIP-21 keys). */77 public let ignoredParameters: [String]7879 /** The networks of `among` this request can be for: the hinted one(s), or for a plain address those where it validates. */80 public func networks(among networks: [Network]) -> [Network] {81 switch networkHint {82 case .networkId(let id): networks.filter { JSText.same($0.id, id) }83 case .evm(let chainId): networks.filter { n in JSText.same(n.family, "evm") && (chainId.map { JSText.same(n.chainRef, $0) } ?? true) }84 case nil: AddressValidator.plausibleNetworks(for: address, among: networks)85 }86 }8788 /**89 The amount as canonical decimal text for an asset with `decimals` decimals, exactly (never rounded): nil when the request90 has no amount; throws when the text has more decimals than the asset or is out of range.91 */92 public func amountText(decimals: Int) throws(AmountError) -> String? {93 if let amountBaseUnits { return amountBaseUnits.formatted(decimals: decimals) }94 guard let amount else { return nil }95 return try BaseUnits.parse(amount, decimals: decimals).formatted(decimals: decimals)96 }97}9899public enum PaymentURI {100 /** Longest accepted input, in UTF-16 code units. */101 public static let maxLength = 2048102 static let stellarPublicPassphrase = "Public Global Stellar Network ; September 2015"103104 private static let forbiddenSchemes: Set<String> = ["http", "https", "javascript", "data", "file", "ftp", "ftps", "blob", "vbscript", "about", "ws", "wss", "intent", "content", "view-source", "chrome", "itms-services", "tel", "sms", "mailto"]105 /** scheme → network id of the registry */106 private static let schemeNetworks: [String: String] = [107 "bitcoin": "bitcoin", "litecoin": "litecoin", "dogecoin": "dogecoin", "bitcoincash": "bitcoincash", "solana": "solana", "tron": "tron",108 "ripple": "xrpl", "xrpl": "xrpl", "stellar": "stellar", "web+stellar": "stellar", "cosmos": "cosmos", "ton": "ton", "cardano": "cardano", "web+cardano": "cardano",109 ]110111 // MARK: parsing112113 public static func parse(_ text: String) throws(PaymentURIRejection) -> PaymentRequest {114 guard text.utf16.count <= maxLength else { throw .tooLong }115 let s = JSText.trim(JSText.scalars(text))116 guard !s.isEmpty else { throw .empty }117 guard !s.contains(where: isForbiddenScalar) else { throw .controlCharacter }118 guard !s.contains(where: JSText.isTrimmed), !s.contains(where: { $0.properties.isWhitespace }) else { throw .malformed }119120 guard let colon = s.firstIndex(of: ":"), isScheme(s[..<colon]) else {121 // plain address: at most what the backend accepts as a destination (130 characters)122 guard s.count <= 130 else { throw .malformed }123 return PaymentRequest(scheme: nil, networkHint: nil, address: JSText.string(s), amount: nil, amountBaseUnits: nil, asset: nil, memo: nil, label: nil, message: nil, ignoredParameters: [])124 }125 let scheme = JSText.string(JSText.lower(Array(s[..<colon])))126 guard !forbiddenSchemes.contains(scheme) else { throw .forbiddenScheme(scheme) }127 let rest = Array(s[(colon + 1)...])128 guard !rest.contains("#") else { throw .malformed }129 let question = rest.firstIndex(of: "?")130 let path = JSText.string(question.map { rest[..<$0] } ?? rest[...])131 let query = try Query(question.map { Array(rest[($0 + 1)...]) })132133 switch scheme {134 case "bitcoin", "litecoin", "dogecoin", "bitcoincash": return try bip21(scheme, path, query)135 case "ethereum": return try eip681(path, query)136 case "solana": return try solanaPay(path, query)137 case "tron": return try simple(scheme, path, query, memoKey: nil)138 case "cosmos": return try simple(scheme, path, query, memoKey: "memo")139 case "ripple", "xrpl": return try ripple(scheme, path, query)140 case "stellar", "web+stellar": return try stellar(scheme, path, query)141 case "ton": return try ton(path, query)142 case "cardano", "web+cardano": return try simple(scheme, path, query, memoKey: nil)143 default: throw .unknownScheme(scheme)144 }145 }146147 private static func isScheme(_ s: ArraySlice<Unicode.Scalar>) -> Bool {148 guard let first = s.first, first.isASCII, first.properties.isAlphabetic else { return false }149 return s.allSatisfy { $0.isASCII && ($0.properties.isAlphabetic || ("0"..."9").contains($0) || $0 == "+" || $0 == "." || $0 == "-") }150 }151152 /** C0/C1 controls, DEL, line/paragraph separators and invisible format characters (zero-width, bidirectional overrides, BOM, tags). */153 private static func isForbiddenScalar(_ u: Unicode.Scalar) -> Bool {154 switch u.properties.generalCategory {155 case .control, .format, .lineSeparator, .paragraphSeparator, .surrogate: true156 default: false157 }158 }159160 /** Decoded query of a URI: unique keys (matched in lower case), strict percent-decoding, no control character in a value. */161 private struct Query {162 private(set) var items: [(key: String, value: String)] = []163 private var consumed: Set<String> = []164165 init(_ raw: [Unicode.Scalar]?, repeatable: Set<String> = ["reference"]) throws(PaymentURIRejection) {166 guard let raw else { return }167 guard !raw.isEmpty else { return } // "scheme:address?" carries no parameter168 guard !raw.contains("?") else { throw .malformed }169 var seen = Set<String>()170 for piece in raw.split(separator: "&", omittingEmptySubsequences: false) {171 guard !piece.isEmpty else { throw .malformed }172 let eq = piece.firstIndex(of: "=")173 let key = try PaymentURI.percentDecoded(eq.map { piece[..<$0] } ?? piece).lowercased()174 let value = try PaymentURI.percentDecoded(eq.map { piece[($0 + 1)...] } ?? [])175 guard !key.isEmpty, key.unicodeScalars.allSatisfy({ $0.isASCII }) else { throw .malformed }176 if !seen.insert(key).inserted, !repeatable.contains(key) { throw .duplicateParameter(key) }177 items.append((key, value))178 }179 }180181 /** The value of `key`, marking it as understood. */182 mutating func take(_ key: String) -> String? {183 consumed.insert(key)184 return items.first { JSText.same($0.key, key) }?.value185 }186 mutating func ignore(_ keys: String...) -> [String] {187 var found: [String] = []188 for k in keys { consumed.insert(k); if items.contains(where: { JSText.same($0.key, k) }) { found.append(k) } }189 return found190 }191 /** Keys nobody took, in order of appearance, without repetition. */192 var unknown: [String] {193 var out: [String] = []194 for i in items where !consumed.contains(i.key) && !out.contains(i.key) { out.append(i.key) }195 return out196 }197 /** Every scheme except BIP-21 refuses what it does not understand. */198 func requireAllKnown() throws(PaymentURIRejection) { if let k = unknown.first { throw .unsupportedParameter(k) } }199 }200201 private static func percentDecoded(_ s: ArraySlice<Unicode.Scalar>) throws(PaymentURIRejection) -> String {202 var bytes = [UInt8](), i = s.startIndex203 func hexValue(_ u: Unicode.Scalar) -> UInt8? {204 switch u.value { case 48...57: UInt8(u.value - 48); case 65...70: UInt8(u.value - 55); case 97...102: UInt8(u.value - 87); default: nil }205 }206 while i < s.endIndex {207 if s[i] == "%" {208 guard i + 2 < s.endIndex, let h = hexValue(s[i + 1]), let l = hexValue(s[i + 2]) else { throw .badEncoding }209 bytes.append(h << 4 | l); i += 3210 } else {211 bytes.append(contentsOf: Array(String(s[i]).utf8)); i += 1212 }213 }214 guard let out = String(validating: bytes, as: UTF8.self) else { throw .badEncoding }215 guard !out.unicodeScalars.contains(where: isForbiddenScalar) else { throw .controlCharacter }216 return out217 }218219 /** An address inside a URI: printable ASCII without any URI separator. Never decoded, never altered. */220 private static func addressText(_ path: String, allowColon: Bool = false) throws(PaymentURIRejection) -> String {221 guard !path.isEmpty else { throw .missingAddress }222 let forbidden: Set<Unicode.Scalar> = ["%", "/", "?", "#", "@", "&", "=", "\\"]223 guard path.unicodeScalars.allSatisfy({ $0.isASCII && $0.value > 0x20 && $0.value < 0x7f && !forbidden.contains($0) && (allowColon || $0 != ":") }) else { throw .malformed }224 return path225 }226227 /** Whole-unit decimal text: digits, optionally "." and digits. No sign, no exponent, no grouping. */228 private static func decimalAmount(_ s: String?) throws(PaymentURIRejection) -> String? {229 guard let s else { return nil }230 let parts = s.utf8.split(separator: 0x2e, omittingEmptySubsequences: false)231 guard (1...2).contains(parts.count), parts.allSatisfy({ !$0.isEmpty && $0.count <= 60 && $0.allSatisfy { (48...57).contains($0) } }) else { throw .badAmount }232 return s233 }234235 /** Canonical unsigned integer of base units (no sign, no leading zero), at most 2^256 − 1. */236 private static func integerAmount(_ s: String?) throws(PaymentURIRejection) -> BaseUnits? {237 guard let s else { return nil }238 guard let v = try? BaseUnits(s), v <= .max256 else { throw .badAmount }239 return v240 }241242 /**243 EIP-681 number: digits, optional fraction, optional decimal exponent ("2.014e18"), evaluated exactly. Refused: a sign, an244 empty exponent, a result that is not an integer, anything above 2^256 − 1.245 */246 static func eip681Number(_ s: String) -> BaseUnits? {247 let u = Array(s.utf8)248 func isDigits(_ a: ArraySlice<UInt8>) -> Bool { !a.isEmpty && a.count <= 78 && a.allSatisfy { (48...57).contains($0) } }249 var mantissa = u[...], exponent = 0250 if let e = u.firstIndex(where: { $0 == 0x65 || $0 == 0x45 }) {251 let digits = u[(e + 1)...]252 guard isDigits(digits), digits.count <= 2, let value = Int(String(decoding: digits, as: UTF8.self)), value <= 77 else { return nil }253 exponent = value; mantissa = u[..<e]254 }255 let parts = mantissa.split(separator: 0x2e, omittingEmptySubsequences: false)256 guard (1...2).contains(parts.count), parts.allSatisfy(isDigits) else { return nil }257 var digits = Array(parts[0]), fraction = parts.count == 2 ? Array(parts[1]) : []258 if fraction.count > exponent {259 guard fraction[exponent...].allSatisfy({ $0 == 48 }) else { return nil } // would not be a whole number of base units260 fraction = Array(fraction[..<exponent])261 }262 digits += fraction + [UInt8](repeating: 48, count: exponent - fraction.count)263 let trimmed = digits.drop { $0 == 48 }264 guard trimmed.count <= 78, let v = try? BaseUnits(trimmed.isEmpty ? "0" : String(decoding: trimmed, as: UTF8.self)), v <= .max256 else { return nil }265 return v266 }267268 private static func isEVMAddress(_ s: String) -> Bool {269 let a = Array(s.utf8)270 return a.count == 42 && a[0] == 0x30 && a[1] == 0x78 && a[2...].allSatisfy { (48...57).contains($0) || (97...102).contains($0) || (65...70).contains($0) }271 }272273 // MARK: schemes274275 /** BIP-21: `bitcoin:<address>?amount=<BTC>&label=&message=`; unknown parameters are ignored unless they start with `req-`. */276 private static func bip21(_ scheme: String, _ path: String, _ query: Query) throws(PaymentURIRejection) -> PaymentRequest {277 var q = query278 let address = try addressText(path)279 let amount = try decimalAmount(q.take("amount")), label = q.take("label"), message = q.take("message")280 if let required = q.unknown.first(where: { $0.hasPrefix("req-") }) { throw .requiredParameterUnknown(required) }281 return PaymentRequest(scheme: scheme, networkHint: schemeNetworks[scheme].map { .networkId($0) }, address: address, amount: amount, amountBaseUnits: nil, asset: nil,282 memo: nil, label: label, message: message, ignoredParameters: q.unknown)283 }284285 /**286 EIP-681: `ethereum:[pay-]<address>[@<chainId>]?value=<wei>` (native coin) or287 `ethereum:[pay-]<token>[@<chainId>]/transfer?address=<to>&uint256=<base units>` (ERC-20). Any other function is refused.288 */289 private static func eip681(_ path: String, _ query: Query) throws(PaymentURIRejection) -> PaymentRequest {290 var q = query291 var target = Substring(path)292 if target.hasPrefix("pay-") { target = target.dropFirst(4) }293 var function: String?294 if let slash = target.firstIndex(of: "/") { function = String(target[target.index(after: slash)...]); target = target[..<slash] }295 var chainId: String?296 if let at = target.firstIndex(of: "@") {297 let c = String(target[target.index(after: at)...]); target = target[..<at]298 guard !c.isEmpty, c.utf8.count <= 20, c.utf8.allSatisfy({ (48...57).contains($0) }), c.utf8.first != 48 else { throw .badChainId }299 chainId = c300 }301 guard !target.isEmpty else { throw .missingAddress }302 guard isEVMAddress(String(target)) else {303 // an ENS name or anything that is not 0x + 40 hexadecimal digits: never resolved here304 guard target.unicodeScalars.allSatisfy({ $0.isASCII && ($0.properties.isAlphabetic || ("0"..."9").contains($0) || $0 == "." || $0 == "-" || $0 == "_") }) else { throw .malformed }305 throw .unsupportedAddressForm306 }307 let ignored = q.ignore("gas", "gaslimit", "gasprice")308 if let function {309 guard function == "transfer" else { throw .unsupportedFunction(function) }310 guard let to = q.take("address") else { throw .missingAddress }311 guard isEVMAddress(to) else { throw .unsupportedAddressForm }312 var units: BaseUnits?313 if let raw = q.take("uint256") { guard let v = eip681Number(raw) else { throw .badAmount }; units = v }314 try q.requireAllKnown() // in particular `value`: ether sent along with a token transfer315 return PaymentRequest(scheme: "ethereum", networkHint: .evm(chainId: chainId), address: to, amount: nil, amountBaseUnits: units, asset: String(target),316 memo: nil, label: nil, message: nil, ignoredParameters: ignored)317 }318 var units: BaseUnits?319 if let raw = q.take("value") { guard let v = eip681Number(raw) else { throw .badAmount }; units = v }320 try q.requireAllKnown()321 // wei → whole units: the native coin of every EVM network has 18 decimals322 return PaymentRequest(scheme: "ethereum", networkHint: .evm(chainId: chainId), address: String(target), amount: units?.formatted(decimals: 18), amountBaseUnits: units, asset: nil,323 memo: nil, label: nil, message: nil, ignoredParameters: ignored)324 }325326 /**327 Solana Pay TRANSFER request: `solana:<recipient>?amount=&spl-token=&reference=&label=&message=&memo=`. A transaction328 request (`solana:https://…`) asks the wallet to fetch a transaction from a server and sign it: always refused.329 */330 private static func solanaPay(_ path: String, _ query: Query) throws(PaymentURIRejection) -> PaymentRequest {331 var q = query332 let lower = path.lowercased()333 if lower.hasPrefix("http") || lower.contains("//") || lower.contains("%2f") || lower.contains("%3a") { throw .transactionRequest }334 let address = try addressText(path)335 let amount = try decimalAmount(q.take("amount"))336 var asset: String?337 if let mint = q.take("spl-token") {338 guard (32...44).contains(mint.utf8.count), mint.utf8.allSatisfy(Base58.isBase58) else { throw .malformed }339 asset = mint340 }341 let memo = q.take("memo"), label = q.take("label"), message = q.take("message"), ignored = q.ignore("reference")342 try q.requireAllKnown()343 return PaymentRequest(scheme: "solana", networkHint: .networkId("solana"), address: address, amount: amount, amountBaseUnits: nil, asset: asset, memo: memo, label: label, message: message, ignoredParameters: ignored)344 }345346 /** `tron:`, `cosmos:`, `cardano:` / `web+cardano:` (CIP-13): `<scheme>:<address>?amount=<whole units>` and, where the chain has one, `memo=`. */347 private static func simple(_ scheme: String, _ path: String, _ query: Query, memoKey: String?) throws(PaymentURIRejection) -> PaymentRequest {348 var q = query349 let address = try addressText(path)350 let amount = try decimalAmount(q.take("amount"))351 let memo = memoKey.flatMap { q.take($0) }352 try q.requireAllKnown()353 return PaymentRequest(scheme: scheme, networkHint: schemeNetworks[scheme].map { .networkId($0) }, address: address, amount: amount, amountBaseUnits: nil, asset: nil, memo: memo, label: nil, message: nil, ignoredParameters: [])354 }355356 /** `ripple:<address>?amount=<XRP>&dt=<destination tag>` (also `xrpl:`). The tag must be a canonical unsigned 32-bit number. */357 private static func ripple(_ scheme: String, _ path: String, _ query: Query) throws(PaymentURIRejection) -> PaymentRequest {358 var q = query359 let address = try addressText(path)360 let amount = try decimalAmount(q.take("amount"))361 let tag = q.take("dt")362 if let tag {363 guard !tag.isEmpty, tag.utf8.count <= 10, tag.utf8.allSatisfy({ (48...57).contains($0) }), tag == "0" || tag.utf8.first != 48, let v = UInt64(tag), v <= 0xffff_ffff else { throw .unsupportedMemo }364 }365 try q.requireAllKnown()366 return PaymentRequest(scheme: scheme, networkHint: .networkId("xrpl"), address: address, amount: amount, amountBaseUnits: nil, asset: nil, memo: tag, label: nil, message: nil, ignoredParameters: [])367 }368369 /**370 SEP-7 `web+stellar:pay?destination=&amount=&asset_code=&asset_issuer=&memo=&memo_type=&msg=` and the short371 `stellar:<address>?amount=&memo=`. The `tx` operation (sign a prepared transaction) is refused; `callback`,372 `origin_domain` and `signature` are never used.373 */374 private static func stellar(_ scheme: String, _ path: String, _ query: Query) throws(PaymentURIRejection) -> PaymentRequest {375 var q = query376 if path == "tx" { throw .transactionRequest }377 guard path == "pay" else {378 guard scheme == "stellar" else { throw .malformed }379 let address = try addressText(path)380 let amount = try decimalAmount(q.take("amount")), memo = q.take("memo")381 try q.requireAllKnown()382 return PaymentRequest(scheme: scheme, networkHint: .networkId("stellar"), address: address, amount: amount, amountBaseUnits: nil, asset: nil, memo: memo, label: nil, message: nil, ignoredParameters: [])383 }384 guard let destination = q.take("destination") else { throw .missingAddress }385 let address = try addressText(destination)386 if let passphrase = q.take("network_passphrase"), !JSText.same(passphrase, stellarPublicPassphrase) { throw .wrongNetwork }387 let amount = try decimalAmount(q.take("amount"))388 var asset: String?389 let code = q.take("asset_code"), issuer = q.take("asset_issuer")390 if let code {391 guard let issuer, (1...12).contains(code.utf8.count), code.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) }) else { throw .malformed }392 asset = "\(code):\(try addressText(issuer))"393 } else if issuer != nil { throw .malformed }394 let memo = q.take("memo"), memoType = q.take("memo_type")395 if let memoType {396 guard let memo else { throw .unsupportedMemo }397 // the backend derives the memo type from the text: a canonical 64-bit integer is an id, anything else is text398 let isCanonicalId = !memo.isEmpty && memo.utf8.count <= 20 && memo.utf8.allSatisfy({ (48...57).contains($0) }) && (memo == "0" || memo.utf8.first != 48) && UInt64(memo) != nil399 switch memoType {400 case "MEMO_TEXT": guard !isCanonicalId else { throw .unsupportedMemo }401 case "MEMO_ID": guard isCanonicalId else { throw .unsupportedMemo }402 default: throw .unsupportedMemo // MEMO_HASH, MEMO_RETURN403 }404 }405 let message = q.take("msg"), ignored = q.ignore("callback", "origin_domain", "signature")406 try q.requireAllKnown()407 return PaymentRequest(scheme: scheme, networkHint: .networkId("stellar"), address: address, amount: amount, amountBaseUnits: nil, asset: asset, memo: memo, label: nil, message: message, ignoredParameters: ignored)408 }409410 /** `ton://transfer/<address>?amount=<nanotons>&text=<comment>&jetton=<master>`. Raw payloads (`bin`, `init`) are refused. */411 private static func ton(_ path: String, _ query: Query) throws(PaymentURIRejection) -> PaymentRequest {412 var q = query413 let prefix = "//transfer/"414 guard path.hasPrefix(prefix) else { throw .malformed }415 let address = try addressText(String(path.dropFirst(prefix.count)), allowColon: true)416 let units = try integerAmount(q.take("amount")), text = q.take("text")417 var asset: String?418 if let jetton = q.take("jetton") { asset = try addressText(jetton, allowColon: true) }419 try q.requireAllKnown()420 return PaymentRequest(scheme: "ton", networkHint: .networkId("ton"), address: address, amount: asset == nil ? units?.formatted(decimals: 9) : nil, amountBaseUnits: units, asset: asset,421 memo: text, label: nil, message: nil, ignoredParameters: [])422 }423424 // MARK: receiving425426 /**427 The URI scheme `make` uses to carry an amount on `network`, nil when the family has no standard (TRON, XRP Ledger, Cosmos,428 Sui, Aptos, NEAR, Polkadot) or when the network is unknown to this build: the QR code is then the plain address.429 */430 public static func standardScheme(for network: Network) -> String? {431 guard let p = AddressParameters.find(id: network.id), JSText.same(p.family, network.family), JSText.same(p.chainRef, network.chainRef) else { return nil }432 switch p.family {433 case "evm": return "ethereum"434 case "btc", "bch": return p.id // bitcoin, litecoin, dogecoin, bitcoincash (BIP-21)435 case "sol": return "solana"436 case "stellar": return "web+stellar"437 case "ton": return "ton"438 case "cardano": return "web+cardano"439 default: return nil440 }441 }442443 /**444 Text of the Receive QR code. Without an amount: the address itself, as every wallet reads it. With an amount (decimal text445 in whole units of the NATIVE coin): the standard URI of the family (BIP-21, EIP-681, Solana Pay, SEP-7, ton://transfer,446 CIP-13), or the plain address where no standard exists (see `standardScheme`) — never an invented scheme.447 Throws `.invalidAddress` unless `address` is exactly the valid, normalized address of `network` (the amount form is448 never built for a network this build cannot verify), and `.badAmount` for a zero, malformed or over-precise amount.449 */450 public static func make(address: String, network: Network, amount: String? = nil) throws(PaymentURIRejection) -> String {451 let check = AddressValidator.check(address, network: network)452 if case .invalid = check { throw .invalidAddress }453 if case .valid(let normalized) = check, !JSText.same(normalized, address) { throw .invalidAddress }454 guard let amount else { return address }455 guard let units = try? BaseUnits.parse(amount, decimals: network.native.decimals), !units.isZero else { throw .badAmount }456 guard check.isValid, let scheme = standardScheme(for: network) else { return address }457 let text = units.formatted(decimals: network.native.decimals)458 switch scheme {459 case "ethereum": return "ethereum:\(address)@\(network.chainRef)?value=\(units)"460 case "bitcoincash": return "\(address)?amount=\(text)" // the normalized CashAddr already starts with "bitcoincash:"461 case "web+stellar": return "web+stellar:pay?destination=\(address)&amount=\(text)"462 case "ton": return "ton://transfer/\(address)?amount=\(units)"463 default: return "\(scheme):\(address)?amount=\(text)"464 }465 }466}467