Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/Wallet/WalletCommon.swift8// Module : Wallet9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//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 QyvoraWallet44import QyvoraUI4546/// Keys of the interface preferences kept in the app's defaults (not secrets).47enum WalletPreference {48 /// Privacy toggle of the dashboard: masks every amount.49 static let hideAmounts = "wallet.hideAmounts"50}5152/// The privacy toggle "hide amounts", shared by the wallet screens. With `DashboardListingPreference` below it is all53/// these screens keep in the user defaults: one Boolean, no secret, no address, no amount. Declared here once so that there is a single place54/// to review (`@HideAmounts private var hideAmounts`).55@propertyWrapper56struct HideAmounts: DynamicProperty {57 @AppStorage(WalletPreference.hideAmounts) private var stored = false5859 var wrappedValue: Bool {60 get { stored }61 nonmutating set { stored = newValue }62 }6364 var projectedValue: Binding<Bool> { $stored }65}6667/// How the dashboard lists the wallet ("Networks" or "Assets"): the second and last preference the wallet screens68/// keep in the user defaults, declared here with the first so that there is one place to review. It is the raw value69/// of a two-case choice of presentation: no secret, no address, no amount, nothing about the wallet's content.70@propertyWrapper71struct DashboardListingPreference: DynamicProperty {72 @AppStorage("wallet.dashboardListing") private var stored = "Networks"7374 var wrappedValue: String {75 get { stored }76 nonmutating set { stored = newValue }77 }7879 var projectedValue: Binding<String> { $stored }80}8182/// Entry points into screens owned by the security area (Shield, Vault, Recovery). `MainShell` supplies them83/// through the environment; a nil hook hides the action that would call it.84struct WalletHooks {85 /// Opens the recovery-phrase backup verification (Recovery area).86 var openRecoveryBackup: (() -> Void)?87 /// Opens the cold-mode settings (Cold mode area).88 var openColdMode: (() -> Void)?89 /// Switches to the Shield tab and scrolls to one of its sections.90 var openShield: ((ShieldSection) -> Void)?91 /// Opens the network settings of the Settings area (network mode, test networks, chain list, endpoints). The92 /// dashboard's "Manage networks" sheet offers it as "All network settings".93 var openNetworkSettings: (() -> Void)?94}9596/// Sections of the Shield tab that other screens link to: one per account of the wallet. The raw value is the97/// identifier of the section there (`SecShieldExposureSection`).98enum ShieldSection: String, Sendable, CaseIterable {99 /// Public-key exposure of the Bitcoin coins and addresses.100 case bitcoin101 /// The same for the Litecoin, Dogecoin and Bitcoin Cash accounts.102 case litecoin103 case dogecoin104 case bitcoinCash = "bitcoin-cash"105 /// Public-key exposure of the EVM account (one key for every EVM network) and its open token approvals.106 case ethereum107 /// Public-key exposure of the Solana account.108 case solana109 /// Public-key exposure of the TRON account.110 case tron111112 /// The section that reports on the account a network belongs to (main or test network alike).113 init(_ chain: ChainDescriptor) {114 switch chain.family {115 case .evm: self = .ethereum116 case .solana: self = .solana117 case .tron: self = .tron118 case .utxo:119 // each UTXO coin has its own account; the section is named after the coin's main network120 self = ShieldSection(rawValue: chain.mainCounterpart.rawValue) ?? .bitcoin121 }122 }123}124125/// A row that leads to a section of the Shield tab; hidden when the host supplies no way to get there.126struct ShieldLinkRow: View {127 let title: String128 let subtitle: String129 let section: ShieldSection130 @Environment(\.walletHooks) private var hooks131132 var body: some View {133 if let open = hooks.openShield {134 Button { open(section) } label: {135 HStack {136 QNavigationLabel(title, subtitle: subtitle, systemImage: "shield.lefthalf.filled")137 Image(systemName: "arrow.up.forward").font(.footnote.weight(.semibold)).foregroundStyle(QColor.textTertiary)138 .accessibilityHidden(true)139 }140 .contentShape(Rectangle())141 }142 .buttonStyle(.plain)143 .accessibilityHint("Opens the Shield tab")144 }145 }146}147148extension EnvironmentValues {149 @Entry var walletHooks = WalletHooks()150}151152/// Error of an action, shown next to the control that caused it.153struct InlineError: View {154 let message: String?155156 var body: some View {157 if let message {158 Label(message, systemImage: "exclamationmark.triangle")159 .font(QFont.callout)160 .foregroundStyle(QColor.negative)161 .fixedSize(horizontal: false, vertical: true)162 .frame(maxWidth: .infinity, alignment: .leading)163 .accessibilityLabel("Error: \(message)")164 }165 }166}167168/// Permanent notice shown wherever real funds are handled by the unaudited engine. The ceilings of each chain are169/// the service's sentences (`ChainSnapshot.limits`, `SendReview.limits`) and are shown on the chain and in the review.170struct UnauditedMainnetNotice: View {171 var body: some View {172 WarningBanner(.critical, title: "Real funds, unaudited cryptography",173 message: "Main networks are on. This build signs with cryptography that has not been independently audited. Per-transaction limits apply on every network; keep only small amounts in this wallet.")174 }175}176177/// The per-transaction ceilings of a chain on an unaudited build, as the service words them.178struct WalletLimitsCard: View {179 let limits: ChainLimits180181 var body: some View {182 ReviewSection("Limits of this unaudited build") {183 ForEach(limits.lines, id: \.self) { line in184 Label {185 Text(line).font(QFont.footnote).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)186 } icon: {187 Image(systemName: "ruler").font(.footnote).foregroundStyle(QColor.warning)188 }189 .padding(.vertical, QSpace.m)190 .frame(maxWidth: .infinity, alignment: .leading)191 }192 }193 }194}195196/// A row of a `QListSection` that pushes or opens something: icon tile, title, subtitle and a chevron.197struct WalletActionRow: View {198 let title: String199 var subtitle: String?200 let systemImage: String201 var tint: Color = QColor.textPrimary202 var trailing: String?203 var external = false204 let action: () -> Void205206 var body: some View {207 Button(action: action) {208 HStack(spacing: QSpace.m) {209 QNavigationLabel(title, subtitle: subtitle, systemImage: systemImage, tint: tint, trailing: trailing)210 Image(systemName: external ? "arrow.up.forward" : "chevron.right")211 .font(.footnote.weight(.semibold)).foregroundStyle(QColor.textTertiary).accessibilityHidden(true)212 }213 .frame(minHeight: QMetric.rowMinHeight)214 .contentShape(Rectangle())215 }216 .buttonStyle(.qRow)217 }218}219220/// A sentence with a small glyph, for the remarks the service attaches to a chain, an address or a review.221struct WalletNoteLine: View {222 let text: String223 var systemImage = "info.circle"224 var tone: Color = QColor.textSecondary225226 var body: some View {227 Label {228 Text(text).font(QFont.footnote).foregroundStyle(tone).fixedSize(horizontal: false, vertical: true)229 } icon: {230 Image(systemName: systemImage).font(.footnote).foregroundStyle(tone)231 }232 .frame(maxWidth: .infinity, alignment: .leading)233 }234}235236/// Link to a public block explorer, with what following it reveals.237struct WalletExplorerLink: View {238 let title: String239 let url: URL240 @Environment(\.openURL) private var openURL241242 var body: some View {243 VStack(alignment: .leading, spacing: QSpace.s) {244 Button { openURL(url) } label: {245 Label(title, systemImage: "arrow.up.forward.square").frame(maxWidth: .infinity)246 }247 .buttonStyle(.qSecondary)248 .accessibilityHint("Opens \(url.host() ?? "the explorer") in the browser")249 Text("Opens \(url.host() ?? "a public explorer") in the browser. The site sees this device's IP address together with what you look up; QYVORA itself never queries it.")250 .font(QFont.caption).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)251 }252 }253}254255/// A labelled value of a detail screen; long values wrap, monospaced values can be copied.256struct DetailRow: View {257 let label: String258 let value: String259 var mono = false260 var copyable = false261 var sensitive = false262263 var body: some View {264 VStack(alignment: .leading, spacing: 4) {265 Text(label).font(QFont.caption).foregroundStyle(QColor.textSecondary)266 HStack(alignment: .firstTextBaseline, spacing: 6) {267 Text(mono ? UnbrokenValue.wrappable(value) : value)268 .font(mono ? QFont.mono : QFont.body)269 .foregroundStyle(QColor.textPrimary)270 .fixedSize(horizontal: false, vertical: true)271 .frame(maxWidth: .infinity, alignment: .leading)272 .privacySensitive(sensitive)273 if copyable { CopyButton(value, title: "Copy \(label.lowercased())") }274 }275 }276 .accessibilityElement(children: .contain)277 .accessibilityLabel(mono ? "\(label): \(MiddleTruncation.grouped(value))" : "\(label): \(value)")278 }279}280281/// Hairline between rows of a card.282struct RowDivider: View {283 var inset: CGFloat = 0284 var body: some View { Divider().overlay(QColor.stroke).padding(.leading, inset) }285}286287/// Collects the frames of a QR sequence (`qyv1:<index>/<total>:…`) or one plain text, for `QRScannerView(collect:)`.288@MainActor289@Observable290final class FrameCollector {291 private(set) var frames: [Int: String] = [:]292 private(set) var plain: String?293294 /// The complete payload in the form the service accepts: every frame, or the single text.295 var payload: [String] {296 if let plain { return [plain] }297 return frames.sorted { $0.key < $1.key }.map(\.value)298 }299300 func reset() {301 frames = [:]302 plain = nil303 }304305 func collect(_ text: String) -> QRScanProgress {306 let value = text.trimmingCharacters(in: .whitespacesAndNewlines)307 guard value.hasPrefix("qyv1:") else {308 // Several frames pasted together, one per line, are accepted as well.309 let lines = value.split(whereSeparator: \.isNewline).map(String.init)310 if lines.count > 1, lines.allSatisfy({ $0.hasPrefix("qyv1:") }) {311 var last = QRScanProgress(collected: 0)312 for line in lines { last = collect(line) }313 return last314 }315 plain = value316 return QRScanProgress(collected: 1, total: 1, isComplete: true)317 }318 let parts = value.split(separator: ":", maxSplits: 3)319 let position = parts.count > 1 ? parts[1].split(separator: "/") : []320 guard position.count == 2, let index = Int(position[0]), let total = Int(position[1]), total > 0, total <= 10_000, index >= 0, index <= total else {321 return QRScanProgress(collected: frames.count, total: nil, note: "This code is not a QYVORA frame.")322 }323 if let known = frames.first, !known.value.hasPrefix("qyv1:") { frames = [:] }324 frames[index] = value325 return QRScanProgress(collected: frames.count, total: total, isComplete: frames.count >= total)326 }327}328329/// State of a value loaded by a screen from the network.330enum Loadable<Value: Sendable>: Sendable {331 case idle332 case loading333 case loaded(Value)334 case failed(String)335336 var value: Value? {337 if case .loaded(let v) = self { return v }338 return nil339 }340341 var isLoading: Bool {342 if case .loading = self { return true }343 return false344 }345}346347/// Sheets and full-screen covers are separate presentations: the root view's privacy cover does not reach348/// them. Every presented wallet screen applies this so that it is hidden in the app switcher as well.349struct PresentedPrivacyCover: ViewModifier {350 @Environment(\.scenePhase) private var scenePhase351352 func body(content: Content) -> some View {353 content.qPrivacyCover(isActive: scenePhase != .active)354 }355}356357extension View {358 func presentedPrivacyCover() -> some View { modifier(PresentedPrivacyCover()) }359}360361extension WalletStore {362 /// Synchronizes the Bitcoin account alone. A failure is reported by the snapshot, not thrown.363 func synchronizeBitcoin() async {364 guard let service, snapshot?.hasWallet == true, snapshot?.profile.coldMode != true else { return }365 _ = try? await service.syncBitcoin()366 await refresh()367 }368369 /// Synchronizes the Ethereum account alone. A failure is reported by the snapshot, not thrown.370 func synchronizeEthereum() async {371 guard let service, snapshot?.hasWallet == true, snapshot?.profile.coldMode != true else { return }372 _ = try? await service.syncEthereum()373 await refresh()374 }375}376