Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/Security/SecNetworksSettingsView.swift8// Module : Security9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// 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 QyvoraWallet44import QyvoraUI4546// MARK: - Limits of an unaudited build4748/// The per-transaction limits of a main network on an unaudited build, as sentences.49///50/// The sentences are the service's: `ChainSnapshot.limits` once the chain is active on its main network, and51/// `ChainRegistry.previewLimits(for:)` before the switch (when the warning must list them). Nothing is reworded here.52enum SecLimits {53 struct Entry: Identifiable, Equatable {54 let chain: ChainDescriptor55 let lines: [String]56 var id: ChainID { chain.id }57 }5859 /// One entry per enabled chain, in registry order.60 static func entries(_ snapshot: WalletSnapshot?) -> [Entry] {61 let enabled = snapshot?.profile.enabledChains ?? ChainRegistry.defaultEnabled62 return ChainRegistry.mainChains.filter { enabled.contains($0.id) }.map { chain in63 // the service's own sentences: those that apply now once main networks are on, the same ones before64 Entry(chain: chain, lines: snapshot?.chain(chain.id)?.limits?.lines ?? ChainRegistry.previewLimits(for: chain).lines)65 }66 }67}6869/// The limits of every enabled chain, one card per chain.70struct SecLimitsList: View {71 let entries: [SecLimits.Entry]7273 var body: some View {74 VStack(alignment: .leading, spacing: QSpace.m) {75 ForEach(entries) { entry in76 QListSection {77 SecChainHeader(network: entry.chain.qNetwork, detail: entry.chain.nativeSymbol)78 ForEach(entry.lines, id: \.self) { SecTextRow(text: $0) }79 }80 }81 }82 }83}8485// MARK: - Networks settings8687/// Networks settings: the global network mode (test networks / main networks), the chains shown by the wallet grouped88/// by family, the test network of the chains that have several, and the endpoints.89///90/// Self-contained: it takes the wallet store from the environment, registers no route and can be pushed on any91/// navigation stack (`SecNetworksSettingsView()`).92struct SecNetworksSettingsView: View {93 @Environment(WalletStore.self) private var store94 @State private var error: String?95 @State private var busy = false96 @State private var showMainnetWarning = false97 @State private var mainnetConfirmed = false98 @State private var reauthenticate = false99 @State private var showEndpoints = false100 @State private var modeChanges = 0101 @State private var failures = 0102103 private var snapshot: WalletSnapshot? { store.snapshot }104105 var body: some View {106 SecurityScroll {107 if let startupError = store.startupError {108 UnavailableDataView(reason: startupError, title: "Wallet storage unavailable", compact: true)109 }110 SecInlineError(error)111 if let snapshot {112 modeSection(snapshot).id("mode")113 if snapshot.unauditedMainnet {114 VStack(alignment: .leading, spacing: QSpace.s) {115 QEyebrow("Limits per transaction").padding(.leading, 2)116 SecLimitsList(entries: SecLimits.entries(snapshot))117 }118 .id("limits")119 }120 ForEach(ChainRegistry.groups) { group in121 chainSection(group, snapshot).id("chains-\(group.id)")122 }123 endpointsSection(snapshot).id("endpoints")124 } else if store.startupError == nil {125 SecSkeletonSection(title: "Network mode", rows: 2)126 SecSkeletonSection(title: ChainRegistry.groups.first?.title, rows: 4)127 }128 }129 .navigationTitle("Networks")130 .navigationBarTitleDisplayMode(.inline)131 .navigationDestination(isPresented: $showEndpoints) { EndpointsEditorView() }132 .fullScreenCover(isPresented: $showMainnetWarning, onDismiss: {133 guard mainnetConfirmed else { return }134 mainnetConfirmed = false135 if snapshot?.vault.exists == true { reauthenticate = true } else { enterMainMode() }136 }) {137 MainnetWarningView(entries: SecLimits.entries(snapshot), onConfirm: {138 mainnetConfirmed = true139 showMainnetWarning = false140 }, onCancel: { showMainnetWarning = false })141 }142 .requiresReauthentication(isPresented: $reauthenticate, reason: "Switch to the main networks") { enterMainMode() }143 .qHaptic(.selection, trigger: modeChanges)144 .qHaptic(.failed, trigger: failures)145 #if DEBUG146 .task {147 await SecurityDebug.prepare(store)148 if SecurityDebug.screen == "mainnet-warning" { showMainnetWarning = true }149 if SecurityDebug.action == "endpoints" { showEndpoints = true }150 // `-QYSecAction main-mode`: what follows the confirmed warning (authentication, opt-in, mode); `test-mode`: back151 if SecurityDebug.action == "main-mode", store.snapshot?.networkMode != .main {152 if store.snapshot?.vault.exists == true { reauthenticate = true } else { enterMainMode() }153 }154 if SecurityDebug.action == "test-mode", store.snapshot?.networkMode == .main { leaveMainMode() }155 }156 #endif157 }158159 // MARK: Mode160161 private func modeSection(_ snapshot: WalletSnapshot) -> some View {162 let isMain = snapshot.networkMode == .main && snapshot.mainnetEnabled163 return QListSection("Network mode", footnote: modeFootnote(snapshot), separatorInset: QMetric.padding) {164 modeRow("Test networks", "Coins without monetary value. The default.", selected: !isMain, tone: .neutral) {165 if isMain { leaveMainMode() }166 }167 if snapshot.mainnetAvailable {168 modeRow("Main networks", "Real funds. Internal testing only, with per-transaction limits. Not audited.", selected: isMain, tone: .warning) {169 if !isMain { showMainnetWarning = true }170 }171 }172 }173 .disabled(busy)174 }175176 private func modeFootnote(_ snapshot: WalletSnapshot) -> String {177 if !snapshot.mainnetAvailable {178 return "This build operates on test networks only: the cryptographic engine has not been independently audited."179 }180 if snapshot.isMainnet {181 return "The enabled chains are on their main networks: balances are real funds. Choosing test networks returns every chain to its test network."182 }183 return "Choosing main networks first shows a warning to read, then asks for your password, PIN or biometrics. It applies to every enabled chain at once."184 }185186 private func modeRow(_ title: String, _ detail: String, selected: Bool, tone: QTone, action: @escaping () -> Void) -> some View {187 Button(action: action) {188 HStack(spacing: QSpace.m) {189 Image(systemName: selected ? "largecircle.fill.circle" : "circle")190 .font(.title3)191 .foregroundStyle(selected ? (tone == .warning ? QColor.warning : QColor.violet) : QColor.strokeStrong)192 .accessibilityHidden(true)193 VStack(alignment: .leading, spacing: 3) {194 HStack(spacing: 6) {195 Text(title).font(QFont.headline).foregroundStyle(QColor.textPrimary)196 if tone == .warning {197 Image(systemName: "exclamationmark.triangle").font(QFont.caption).foregroundStyle(QColor.warning).accessibilityHidden(true)198 }199 }200 Text(detail).font(QFont.caption).foregroundStyle(QColor.textSecondary)201 }202 .fixedSize(horizontal: false, vertical: true)203 Spacer(minLength: 0)204 }205 .padding(.vertical, QSpace.m)206 .frame(minHeight: QMetric.rowMinHeight)207 }208 .buttonStyle(.qRow)209 .accessibilityElement(children: .combine)210 .accessibilityAddTraits(selected ? [.isSelected, .isButton] : [.isButton])211 }212213 // MARK: Chains214215 /// The network a chain uses now: its main network in main mode, its chosen test network otherwise.216 private func activeDescriptor(_ main: ChainDescriptor, _ snapshot: WalletSnapshot) -> ChainDescriptor {217 if snapshot.networkMode == .main, snapshot.mainnetEnabled { return main }218 return SecChain.chosenTestNetwork(of: main.id, profile: snapshot.profile) ?? main219 }220221 private func hasAccount(_ main: ChainDescriptor, _ profile: WalletProfile) -> Bool {222 switch main.family {223 case .evm: return profile.ethereumAddress != nil224 case .solana: return profile.solanaAddress != nil225 case .tron: return profile.tronAddress != nil226 case .utxo:227 if main.id == .bitcoin { return profile.bitcoinAccounts["test"] != nil || profile.bitcoinAccounts["main"] != nil }228 let keys = ([main.id] + main.testCounterparts).compactMap { ChainRegistry.descriptor($0) }.compactMap { $0.utxoNetwork?.rawValue }229 return keys.contains { profile.bitcoinAccounts[$0] != nil }230 }231 }232233 private func chainSection(_ group: ChainGroup, _ snapshot: WalletSnapshot) -> some View {234 let enabled = snapshot.profile.enabledChains235 let testMode = !(snapshot.networkMode == .main && snapshot.mainnetEnabled)236 return QListSection(group.title, footnote: group.accountNote) {237 ForEach(group.chains) { main in238 let active = activeDescriptor(main, snapshot)239 let isOn = enabled.contains(main.id)240 ChainPickerRow(network: active.qNetwork, note: note(active), lockedReason: lockedReason(main, isOn: isOn, snapshot),241 isOn: Binding(get: { isOn }, set: { setEnabled(main, $0, active: active) }))242 if isOn, testMode, main.testCounterparts.count > 1 {243 testNetworkRow(main, active)244 }245 }246 }247 .disabled(busy)248 }249250 private func note(_ active: ChainDescriptor) -> String {251 ([active.nativeSymbol] + SecChain.capabilityNotes(active)).joined(separator: " · ")252 }253254 private func lockedReason(_ main: ChainDescriptor, isOn: Bool, _ snapshot: WalletSnapshot) -> String? {255 if isOn, snapshot.profile.enabledChains.count <= 1 { return "At least one chain stays enabled" }256 if !isOn, snapshot.profile.kind == .watchOnly, !hasAccount(main, snapshot.profile) { return "This watch-only wallet has no account for this chain" }257 return nil258 }259260 private func testNetworkRow(_ main: ChainDescriptor, _ active: ChainDescriptor) -> some View {261 let choices = main.testCounterparts.compactMap { ChainRegistry.descriptor($0) }262 return SecMenuRow(title: "Test network", subtitle: "\(main.displayName) has \(choices.count) test networks", systemImage: "flask",263 choices: choices.map(\.id), name: { id in ChainRegistry.descriptor(id)?.shortName ?? id.rawValue },264 selection: Binding(get: { active.id }, set: { setTestNetwork($0) }))265 }266267 // MARK: Endpoints268269 private func endpointsSection(_ snapshot: WalletSnapshot) -> some View {270 QListSection("Servers", footnote: snapshot.profile.coldMode271 ? "Cold mode is on: the wallet makes no network request at all."272 : "QYVORA has no server of its own: it queries the endpoints listed there, which you can replace by your own nodes.") {273 SecActionRow(title: "Network endpoints", subtitle: "Indexers, RPC nodes and the price API of every chain", systemImage: "point.3.connected.trianglepath.dotted",274 trailing: snapshot.profile.hasTronAPIKey ? "TRON key set" : nil) { showEndpoints = true }275 }276 }277278 // MARK: Actions279280 private func perform(_ operation: @escaping @Sendable (WalletService) async throws -> Void, then: (@MainActor () -> Void)? = nil) {281 guard !busy else { return }282 busy = true283 error = nil284 Task {285 do {286 try await store.run(operation)287 await store.refresh()288 modeChanges += 1289 then?()290 } catch {291 self.error = SecurityError.text(error)292 failures += 1293 }294 busy = false295 }296 }297298 /// Synchronizes in the background what a change made visible; failures are reported by the snapshot.299 private func synchronize(_ chains: [ChainID]?) {300 // through the store: the dashboard and the Shield show the same queue, progress and results301 Task {302 if let chains { await store.synchronize(chains: chains) } else { await store.synchronize() }303 }304 }305306 private func setEnabled(_ main: ChainDescriptor, _ enabled: Bool, active: ChainDescriptor) {307 perform({ try await $0.setChainEnabled(main.id, enabled: enabled) }, then: { if enabled { synchronize([active.id]) } })308 }309310 private func setTestNetwork(_ test: ChainID) {311 perform({ try await $0.setTestNetwork(test) }, then: { synchronize([test]) })312 }313314 /// After the warning was read and the vault accepted a credential: the opt-in, then the mode.315 private func enterMainMode() {316 perform({ service in317 _ = try await service.setMainnetOptIn(true)318 try await service.setNetworkMode(.main)319 }, then: { synchronize(nil) })320 }321322 /// Returns every chain to its test network (done by the service when the opt-in is withdrawn).323 private func leaveMainMode() {324 perform({ _ = try await $0.setMainnetOptIn(false) }, then: { synchronize(nil) })325 }326}327