Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/Wallet/WalletScanFlow.swift8// Module : Wallet9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0512// Last Modified : 2026-12-0513//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI42import QyvoraCore43import QyvoraRecovery44import QyvoraWallet45import QyvoraUI4647// `WalletScanParser` (what a scanned text is, and the rules that bound a payment request) lives in the engine:48// Sources/QyvoraWallet/PaymentRequests.swift, with its tests.4950/// The Scan action of the dashboard: reads one code (or a sequence of QYVORA frames), works out what it is and hands51/// over to the flow that handles it. An address that is valid on several networks is never guessed: the user chooses.52struct WalletScanFlow: View {53 /// Closes this sheet (nil) or replaces it with another wallet sheet.54 let open: (WalletSheet?) -> Void5556 @Environment(WalletStore.self) private var wallet57 @State private var collector = FrameCollector()58 @State private var outcome: Outcome?59 @State private var resolving = false6061 enum Outcome {62 /// The address is valid on several active networks.63 case choose(address: String, payment: WalletScanParser.Payment?, chains: [ChainSnapshot])64 case signed([String])65 case message(title: String, text: String, systemImage: String, offersNetworks: Bool)66 }6768 var body: some View {69 Group {70 switch outcome {71 case nil: scanner72 case .choose(let address, let payment, let chains)?: chooser(address, payment, chains)73 case .signed(let frames)?: SendSignedImportFlow(initialPayload: frames)74 case .message(let title, let text, let systemImage, let offersNetworks)?: message(title, text, systemImage, offersNetworks)75 }76 }77 .qSheetChrome(detents: QDetents.full)78 .qHaptic(trigger: resolving) { $0 ? .selection : nil }79 #if DEBUG80 .task {81 if let text = DebugLaunch.defaults.string(forKey: "QYScanText") {82 try? await Task.sleep(for: .milliseconds(500))83 _ = collector.collect(text)84 await resolve(collector.payload)85 }86 }87 #endif88 }8990 var scanner: some View {91 VStack(spacing: QSpace.l) {92 SheetHeader("Scan", subtitle: "An address, a payment request or a QYVORA code") { open(nil) }93 if resolving {94 ProgressView("Reading the code").frame(maxWidth: .infinity, maxHeight: .infinity)95 } else {96 QRScannerView(prompt: "Point the camera at a QR code", collect: { collector.collect($0) }, onComplete: {97 let payload = collector.payload98 Task { await resolve(payload) }99 })100 }101 }102 .padding(QMetric.screenPadding)103 .qScreen()104 }105106 // MARK: Resolution107108 func resolve(_ payload: [String]) async {109 guard let snapshot = wallet.snapshot, let service = wallet.service, !payload.isEmpty else { return }110 resolving = true111 defer { resolving = false }112 // a sequence of frames carries a text: read it to know what it is (the service checks it again before any use)113 var text = payload[0]114 if payload.count > 1 || text.hasPrefix(QRChunker.prefix + ":") {115 guard let bytes = try? QRAssembler.assemble(payload) else {116 outcome = .message(title: "Incomplete code", text: "These QYVORA frames do not reassemble: a frame is missing or belongs to another set. Scan the whole sequence again.",117 systemImage: "qrcode", offersNetworks: false)118 return119 }120 guard let decoded = String(validating: bytes, as: UTF8.self) else {121 // a binary payload: the encrypted package of a device-to-device transfer122 outcome = .message(title: "Wallet transfer", text: "These frames carry an encrypted package, as a device-to-device transfer does. It is received from the start screen of a device without a wallet.",123 systemImage: "arrow.left.arrow.right", offersNetworks: false)124 return125 }126 text = decoded127 }128 switch WalletScanParser.parse(text) {129 case .signedTransaction:130 outcome = .signed(payload)131 case .unsignedTransaction:132 outcome = .message(title: "Unsigned transaction", text: "This is a transaction waiting for a signature. It is signed on the device that holds the keys, in cold mode (Shield, Cold mode). This screen broadcasts transactions that are already signed.",133 systemImage: "signature", offersNetworks: false)134 case .watchOnlyPackage:135 outcome = .message(title: "Watch-only package", text: "This code describes the public accounts of another QYVORA wallet. It is imported when a watch-only wallet is created, from the start screen of a device without a wallet. This device already has one.",136 systemImage: "eye", offersNetworks: false)137 case .identity:138 outcome = .message(title: "QYVORA identity", text: "This is the public identity of a QYVORA user. It is used to verify a signed message or to receive a wallet transfer: open the Shield tab, Identity.",139 systemImage: "person.text.rectangle", offersNetworks: false)140 case .transferPackage:141 outcome = .message(title: "Wallet transfer", text: "This code is part of a device-to-device transfer. It is received from the start screen of a device without a wallet.",142 systemImage: "arrow.left.arrow.right", offersNetworks: false)143 case .unsupported(let reason):144 // nothing of such a request is used: the screen says why and offers no payment145 outcome = .message(title: "Payment request not usable", text: reason, systemImage: "exclamationmark.triangle", offersNetworks: false)146 case .payment(let payment):147 await route(address: payment.address, payment: payment, snapshot: snapshot, service: service)148 case .text(let value):149 await route(address: value, payment: nil, snapshot: snapshot, service: service)150 }151 }152153 /// Finds the active chains on which the address is valid. One: the send form opens. Several: the user chooses.154 /// None: the screen says what the text is, when the service recognises it on a network that is not enabled.155 func route(address: String, payment: WalletScanParser.Payment?, snapshot: WalletSnapshot, service: WalletService) async {156 guard address.count <= WalletScanParser.maximumAddressLength else {157 outcome = .message(title: "Not recognised", text: "This code is not an address, a payment request or a QYVORA code.", systemImage: "questionmark.square.dashed", offersNetworks: false)158 return159 }160 var candidates = snapshot.chains161 if let payment {162 candidates = candidates.filter { payment.matches($0.chain) }163 }164 var matches = [ChainSnapshot]()165 for chain in candidates where (try? await service.checkAddress(address, chain: chain.id)) != nil { matches.append(chain) }166 if matches.count == 1 {167 open(.send(prefill(address: address, payment: payment, chain: matches[0])))168 return169 }170 if matches.count > 1 {171 outcome = .choose(address: address, payment: payment, chains: matches)172 return173 }174 // valid on a network of the current mode that is not enabled?175 let active = Set(snapshot.chains.map(\.id))176 var inactive = [ChainDescriptor]()177 for descriptor in ChainRegistry.all where descriptor.isTest == snapshot.isTestMode && !active.contains(descriptor.id) {178 if let payment, !payment.matches(descriptor) { continue }179 if (try? await service.checkAddress(address, chain: descriptor.id)) != nil, !inactive.contains(where: { $0.mainCounterpart == descriptor.mainCounterpart }) {180 inactive.append(descriptor)181 }182 }183 if !inactive.isEmpty {184 let names = inactive.map(\.qNetwork.chain.name)185 let unique = names.reduce(into: [String]()) { if !$0.contains($1) { $0.append($1) } }186 outcome = .message(title: "Network not enabled",187 text: "This is a valid address on \(unique.joined(separator: ", ")), which \(unique.count == 1 ? "is" : "are") not enabled in this wallet. Enable the network to pay this address.",188 systemImage: "slider.horizontal.3", offersNetworks: true)189 } else if let payment, let chain = candidates.first {190 let reason = (try? await service.checkAddress(address, chain: chain.id)) == nil ? await refusal(address, chain.id, service) : nil191 outcome = .message(title: "Payment request not usable", text: reason ?? "The address of this \(payment.scheme) request is not valid on \(chain.chain.displayName).",192 systemImage: "exclamationmark.triangle", offersNetworks: false)193 } else {194 outcome = .message(title: "Not recognised",195 text: payment == nil ? "This is not an address of a network QYVORA supports in the current mode (\(snapshot.isTestMode ? "test networks" : "main networks")), nor a payment request, nor a QYVORA code."196 : "This payment request is for a network that is not enabled in this wallet.",197 systemImage: "questionmark.square.dashed", offersNetworks: payment != nil)198 }199 }200201 func refusal(_ address: String, _ chain: ChainID, _ service: WalletService) async -> String? {202 do {203 _ = try await service.checkAddress(address, chain: chain)204 return nil205 } catch {206 return WalletStore.message(for: error)207 }208 }209210 func prefill(address: String, payment: WalletScanParser.Payment?, chain: ChainSnapshot) -> SendPrefill {211 var prefill = SendPrefill(chain: chain.id, recipient: address)212 guard let payment else { return prefill }213 prefill.tokenAddress = payment.token214 prefill.memo = payment.memo215 prefill.amount = payment.amount216 if let base = payment.baseAmount, let units = UInt256(decimal: base) {217 if let token = payment.token {218 if let decimals = (chain.tokens + chain.detectedTokens).first(where: { $0.token.address.caseInsensitiveCompare(token) == .orderedSame })?.token.decimals {219 prefill.amount = BaseUnits.format(units, decimals: decimals)220 }221 } else {222 prefill.amount = BaseUnits.format(units, decimals: chain.chain.nativeDecimals)223 }224 }225 return prefill226 }227228 // MARK: Outcomes229230 func chooser(_ address: String, _ payment: WalletScanParser.Payment?, _ chains: [ChainSnapshot]) -> some View {231 QSheetScaffold("Which network?", subtitle: "This address is valid on \(chains.count) enabled networks", onClose: { open(nil) }) {232 ReviewSection {233 ReviewRow("Scanned address", value: address, emphasis: .address)234 }235 .privacySensitive()236 WarningBanner(.warning, message: "The same address exists on every network of this family, but the funds do not. Choose the network the recipient expects: what is sent on another one does not arrive where they look.")237 QListSection {238 ForEach(chains) { chain in239 Button { open(.send(prefill(address: address, payment: payment, chain: chain))) } label: {240 HStack(spacing: QSpace.m) {241 ChainGlyph(chain.network)242 VStack(alignment: .leading, spacing: 2) {243 HStack(spacing: 6) {244 Text(chain.network.fullName).font(QFont.body).foregroundStyle(QColor.textPrimary)245 if chain.chain.isTest { QTestTag() }246 }247 Text(chain.chain.evmChainID.map { "\(chain.chain.nativeSymbol) · Chain ID \($0)" } ?? chain.chain.nativeSymbol)248 .font(QFont.caption).foregroundStyle(QColor.textSecondary)249 }250 Spacer(minLength: QSpace.s)251 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(QColor.textTertiary).accessibilityHidden(true)252 }253 .frame(minHeight: QMetric.rowMinHeight)254 .contentShape(Rectangle())255 }256 .buttonStyle(.qRow)257 .accessibilityElement(children: .combine)258 }259 }260 }261 }262263 func message(_ title: String, _ text: String, _ systemImage: String, _ offersNetworks: Bool) -> some View {264 QSheetScaffold("Scan", onClose: { open(nil) }) {265 EmptyStateView(systemImage: systemImage, title: title, message: text)266 .frame(maxWidth: .infinity)267 .padding(.vertical, QSpace.xxl)268 } footer: {269 if offersNetworks {270 Button { open(.networks) } label: { Label("Manage networks", systemImage: "slider.horizontal.3").frame(maxWidth: .infinity) }271 .buttonStyle(.qSecondary)272 }273 Button("Scan another code") {274 collector.reset()275 outcome = nil276 }277 .buttonStyle(.qPrimary)278 }279 }280}281