Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/Wallet/DashboardView.swift8// Module : Wallet9// 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/// Wallet tab: total value, network mode, quick actions, allocation and the list of networks or assets.47/// Everything shown comes from `WalletStore.snapshot`; a value that is not known is shown as not known.48struct DashboardView: View {49 enum Listing: String, CaseIterable, Identifiable {50 case chains = "Networks"51 case assets = "Assets"52 var id: String { rawValue }53 }5455 @Environment(WalletStore.self) private var wallet56 @Environment(\.walletHooks) private var hooks57 @HideAmounts private var hideAmounts58 @DashboardListingPreference private var listingRaw59 @State private var sheet: WalletSheet?60 @State private var authPreview = false61 @Namespace private var zoom6263 var listing: Listing { Listing(rawValue: listingRaw) ?? .chains }6465 var body: some View {66 Group {67 if let snapshot = wallet.snapshot, snapshot.hasWallet {68 content(snapshot)69 } else if wallet.snapshot == nil {70 DashboardSkeleton()71 } else {72 EmptyStateView(systemImage: "wallet.bifold", title: "No wallet on this device",73 message: "Create, restore or watch a wallet from the start screen.")74 .padding(QSpace.xl)75 .frame(maxWidth: .infinity, maxHeight: .infinity)76 }77 }78 .qScreen()79 .navigationTitle("Wallet")80 .navigationBarTitleDisplayMode(.inline)81 .toolbar {82 ToolbarItem(placement: .topBarTrailing) {83 if let snapshot = wallet.snapshot, snapshot.hasWallet {84 let state = wallet.overallSyncState(snapshot)85 if state.isVisibleInRow { SyncPill(state, style: .inline) }86 }87 }88 }89 .walletSheet($sheet)90 .walletDestinations(namespace: zoom)91 .task { await wallet.synchronizeOnceIfNeeded() }92 .onChange(of: sheet) { old, new in93 // chains enabled in the sheet have no reading yet: read them once it closes94 if old == .networks, new == nil { Task { await wallet.synchronizeUnreadChains() } }95 }96 #if DEBUG97 .task(id: DebugNavigator.shared.serial) {98 // A screen change of the tour closes what is presented, then opens the requested sheet.99 if sheet != nil || authPreview {100 sheet = nil101 authPreview = false102 try? await Task.sleep(for: .milliseconds(700))103 }104 if let listing = DebugLaunch.defaults.string(forKey: "QYListing") { listingRaw = listing == "assets" ? Listing.assets.rawValue : Listing.chains.rawValue }105 sheet = DebugLaunch.initialWalletSheet106 authPreview = DebugLaunch.screen == "auth"107 }108 .requiresReauthentication(isPresented: $authPreview, reason: "Sign and broadcast this transaction") {}109 #endif110 }111112 func content(_ snapshot: WalletSnapshot) -> some View {113 ScrollView {114 VStack(alignment: .leading, spacing: QMetric.sectionSpacing) {115 VStack(alignment: .leading, spacing: QSpace.xl) {116 DashboardHeader(snapshot: snapshot, hidden: hideAmounts, onToggleHidden: { hideAmounts.toggle() }, onOpenNetworks: { sheet = .networks })117 QuickActionBar([118 .send { sheet = .send(SendPrefill()) },119 .receive { sheet = .receive(nil) },120 .scan { sheet = .scan },121 .more { sheet = .more },122 ])123 }124 notices(snapshot)125 DashboardAllocation(snapshot: snapshot, hidden: hideAmounts)126 VStack(alignment: .leading, spacing: QSpace.l) {127 Picker("Listing", selection: $listingRaw) {128 ForEach(Listing.allCases) { Text($0.rawValue).tag($0.rawValue) }129 }130 .pickerStyle(.segmented)131 .accessibilityLabel("Show networks or assets")132 switch listing {133 case .chains: DashboardChainList(snapshot: snapshot, hidden: hideAmounts, namespace: zoom)134 case .assets: DashboardAssetList(snapshot: snapshot, hidden: hideAmounts, namespace: zoom)135 }136 }137 .id("assets")138 DashboardDetectedNotice(snapshot: snapshot)139 Button { sheet = .networks } label: {140 Label("Manage networks", systemImage: "slider.horizontal.3").frame(maxWidth: .infinity)141 }142 .buttonStyle(.qSecondary)143 .accessibilityHint("Enables or disables networks")144 Color.clear.frame(height: 1).id("bottom")145 }146 .padding(.horizontal, QMetric.screenPadding)147 .padding(.top, QSpace.m)148 .padding(.bottom, QSpace.xl)149 .frame(maxWidth: 640)150 .frame(maxWidth: .infinity)151 }152 .debugScroll()153 .refreshable { await wallet.synchronize() }154 }155156 /// Banners about the state of the wallet, most important first; nothing when there is nothing to say.157 @ViewBuilder158 func notices(_ snapshot: WalletSnapshot) -> some View {159 let failed = snapshot.chains.filter { chain in160 if case .failed = wallet.syncState(of: chain) { return true }161 return false162 }163 let neverFunded = snapshot.chains.allSatisfy { $0.data.value.map { $0.native.total.isZero && $0.tokens.allSatisfy { $0.balance.value?.isZero ?? true } } ?? false }164 if snapshot.profile.coldMode || !failed.isEmpty || (snapshot.profile.kind == .full && !snapshot.profile.recoveryPhraseVerified) || neverFunded {165 VStack(alignment: .leading, spacing: QSpace.m) {166 if snapshot.profile.coldMode {167 WarningBanner(.info, title: "Cold mode is on",168 message: "This device makes no network request. Balances and prices are the last values it synchronized, if any.",169 actionTitle: hooks.openColdMode == nil ? nil : "Cold mode settings", action: hooks.openColdMode)170 } else if failed.count == 1, let chain = failed.first {171 SyncBanner(wallet.syncState(of: chain), title: "\(chain.chain.displayName) could not be synchronized") {172 Task { await wallet.synchronize(chains: [chain.id]) }173 }174 } else if failed.count > 1 {175 SyncBanner(.failed(reason: failed.map(\.chain.displayName).joined(separator: ", ") + ". Open a network to read its reason."),176 title: "\(failed.count) networks could not be synchronized") {177 Task { await wallet.synchronize(chains: failed.map(\.id)) }178 }179 }180 if snapshot.profile.kind == .full, !snapshot.profile.recoveryPhraseVerified {181 WarningBanner(.warning, title: "Recovery phrase not verified",182 message: "The written copy of the recovery phrase was never checked on this device. Without a correct copy the wallet cannot be restored.",183 actionTitle: hooks.openRecoveryBackup == nil ? nil : "Verify now", action: hooks.openRecoveryBackup)184 }185 if neverFunded, failed.isEmpty {186 WarningBanner(.info, title: "Nothing received yet",187 message: snapshot.isTestMode188 ? "The enabled networks hold no coin. Use Receive to show an address; on test networks coins come from public faucets and have no value."189 : "The enabled networks hold no coin. Use Receive to show an address.",190 actionTitle: "Receive", action: { sheet = .receive(nil) })191 }192 }193 .id("sync")194 }195 }196}197198// MARK: - Header199200/// Network mode, total value and the notes that qualify it.201private struct DashboardHeader: View {202 let snapshot: WalletSnapshot203 let hidden: Bool204 let onToggleHidden: () -> Void205 let onOpenNetworks: () -> Void206207 var valuation: PortfolioValuation { snapshot.valuation }208 var isReference: Bool { valuation.realValue == nil && valuation.referenceValue != nil }209210 var total: String? {211 if let real = valuation.realValue { return WalletFormat.fiat(real, valuation.currency) }212 if let reference = valuation.referenceValue { return WalletFormat.fiat(reference, valuation.currency) }213 return nil214 }215216 var body: some View {217 VStack(alignment: .leading, spacing: QSpace.l) {218 modeIndicator219 PortfolioHeader(title: isReference ? "Reference value" : "Total balance", total: total, change: change, isHidden: hidden,220 referenceLabel: isReference ? "Test-network coins valued at main-network prices. They have no monetary value and cannot be exchanged for money." : nil,221 onToggleHidden: onToggleHidden) {222 if snapshot.unauditedMainnet { UnauditedMainnetNotice() }223 }224 .privacySensitive()225 if !notes.isEmpty {226 VStack(alignment: .leading, spacing: QSpace.xs) {227 ForEach(notes, id: \.text) { note in228 WalletNoteLine(text: note.text, systemImage: note.image, tone: note.warning ? QColor.warning : QColor.textSecondary)229 }230 }231 }232 }233 }234235 /// "TEST NETWORKS" or "MAIN NETWORKS", never a colour alone; the watch-only state sits next to it.236 var modeIndicator: some View {237 let isMain = snapshot.networkMode == .main && snapshot.isMainnet238 let pill = Button(action: onOpenNetworks) {239 HStack(spacing: 6) {240 Image(systemName: isMain ? "circle.fill" : "flask").imageScale(.small)241 Text(isMain ? "MAIN NETWORKS" : "TEST NETWORKS").kerning(QMetric.tagKerning).lineLimit(1)242 Text("· \(snapshot.chains.count)").monospacedDigit().lineLimit(1)243 Image(systemName: "chevron.right").imageScale(.small).foregroundStyle(QColor.textTertiary)244 }245 .font(QFont.tag)246 .foregroundStyle(isMain ? QColor.warning : QColor.blue)247 .padding(.horizontal, 10)248 .frame(minHeight: 30)249 .background(Capsule().fill(QColor.surface))250 .overlay(Capsule().strokeBorder(isMain ? QColor.warning.opacity(0.6) : QColor.stroke, style: StrokeStyle(lineWidth: 1, dash: isMain ? [] : [4, 3])))251 .contentShape(Capsule())252 }253 .buttonStyle(.qPressable)254 .accessibilityLabel(isMain ? "Main networks, real funds. \(snapshot.chains.count) enabled." : "Test networks, coins without value. \(snapshot.chains.count) enabled.")255 .accessibilityHint("Opens the list of networks")256 // side by side when both fit on one line each, stacked otherwise (large text, narrow screens)257 return ViewThatFits(in: .horizontal) {258 HStack(spacing: QSpace.s) {259 pill.fixedSize()260 badges.fixedSize()261 Spacer(minLength: 0)262 }263 VStack(alignment: .leading, spacing: QSpace.s) {264 pill265 HStack(spacing: QSpace.s) { badges }266 }267 }268 }269270 @ViewBuilder var badges: some View {271 if snapshot.isWatchOnly { QBadge("Watch-only", systemImage: "eye", tone: .accent) }272 if snapshot.profile.coldMode { QBadge("Cold", systemImage: "snowflake", tone: .neutral) }273 }274275 struct Note { let text: String; let image: String; let warning: Bool }276277 var notes: [Note] {278 var out = [Note]()279 if total == nil {280 if snapshot.chains.allSatisfy({ $0.data.value == nil }) {281 out.append(Note(text: "Not synchronized yet: no balance is known.", image: "arrow.triangle.2.circlepath", warning: false))282 } else if let reason = snapshot.market.unavailableReason {283 out.append(Note(text: reason, image: "chart.line.downtrend.xyaxis", warning: false))284 } else {285 out.append(Note(text: "No priced asset holds a balance.", image: "info.circle", warning: false))286 }287 }288 if valuation.realValue != nil, let reference = valuation.referenceValue {289 out.append(Note(text: "Test-network coins are not counted above (reference value \(hidden ? "••••" : WalletFormat.fiat(reference, valuation.currency))).", image: "flask", warning: false))290 }291 if valuation.isFromPreviousSession, let asOf = valuation.balancesAsOf {292 out.append(Note(text: "Balances of \(asOf.formatted(date: .abbreviated, time: .shortened)), from the previous session. Not refreshed yet.", image: "clock.arrow.circlepath", warning: false))293 }294 if total != nil, valuation.isStale, let pricedAt = valuation.pricedAt {295 out.append(Note(text: "Prices of \(pricedAt.formatted(date: .abbreviated, time: .shortened)), not current.", image: "clock", warning: true))296 }297 if !valuation.unpricedAssets.isEmpty {298 out.append(Note(text: "No price for \(valuation.unpricedAssets.joined(separator: ", ")): not included in the value.", image: "questionmark.circle", warning: false))299 }300 return out301 }302303 /// 24 h change of the priced lines, weighted by their value. nil when no line has a 24 h figure.304 var change: QChange? {305 var now = 0.0, before = 0.0306 for line in valuation.lines {307 guard let value = line.value ?? line.referenceValue, value > 0, let percent = line.price?.change24h, percent > -100 else { continue }308 now += value309 before += value / (1 + percent / 100)310 }311 // A change figure next to a value that displays as zero would only mislead.312 guard before > 0, now >= 0.01 else { return nil }313 // the amount is added while it stays short enough to sit next to the percentage on one line314 let amount = WalletFormat.fiat(abs(now - before), valuation.currency)315 return QChange(fraction: now / before - 1, amount: amount.count <= 12 ? amount : nil)316 }317}318319// MARK: - Allocation320321/// Shares of the portfolio by network. Shown only when at least two networks hold a priced value.322private struct DashboardAllocation: View {323 let snapshot: WalletSnapshot324 let hidden: Bool325326 var items: [AllocationItem] {327 snapshot.valuation.chains.compactMap { line in328 guard let descriptor = line.chain.descriptor, let value = line.realValue ?? line.referenceValue, value >= 0.01 else { return nil }329 return AllocationItem(id: line.chain.rawValue, label: descriptor.qNetwork.fullName, value: value,330 detail: WalletFormat.fiat(value, snapshot.currency), color: descriptor.qChain.tintColor)331 }332 }333334 var body: some View {335 if items.count >= 2 {336 VStack(alignment: .leading, spacing: QSpace.m) {337 QEyebrow(snapshot.valuation.realValue == nil ? "Allocation by network · reference values" : "Allocation by network")338 AllocationBar(items: items, maxSegments: 5, hidden: hidden)339 }340 }341 }342}343344// MARK: - Networks345346/// The active chains, one `ChainRow` each; grouped by family once the list is long enough for headers to help.347private struct DashboardChainList: View {348 let snapshot: WalletSnapshot349 let hidden: Bool350 let namespace: Namespace.ID351 @Environment(WalletStore.self) private var wallet352353 var body: some View {354 if snapshot.chains.count > 5 {355 ForEach(ChainFamily.allCases, id: \.self) { family in356 let chains = snapshot.chains.filter { $0.chain.family == family }357 if !chains.isEmpty {358 QListSection(ChainRegistry.groups.first { $0.family == family }?.title) { rows(chains) }359 }360 }361 } else {362 QListSection { rows(snapshot.chains) }363 }364 }365366 @ViewBuilder367 func rows(_ chains: [ChainSnapshot]) -> some View {368 ForEach(chains) { chain in369 NavigationLink(value: WalletRoute.chain(chain.id)) {370 ChainRow(network: chain.network, units: chain.nativeUnits,371 fiat: WalletChainFormat.fiat(snapshot.valuation.chains.first { $0.chain == chain.id }, currency: snapshot.currency),372 sync: wallet.syncState(of: chain), hidden: hidden)373 }374 .buttonStyle(.qRow)375 .qMatchedSource(id: WalletRoute.chain(chain.id), in: namespace)376 .accessibilityHint(tokenHint(chain))377 }378 }379380 func tokenHint(_ chain: ChainSnapshot) -> String {381 let held = chain.heldTokens.count382 return held == 0 ? "Opens the network" : "Opens the network. \(held) token\(held == 1 ? "" : "s") held."383 }384}385386// MARK: - Assets387388/// Every coin and every held token across the active chains, the most valuable first; each row carries its network.389private struct DashboardAssetList: View {390 struct Entry: Identifiable {391 let id: String392 let route: WalletRoute393 let asset: QAssetIdentity394 let name: String395 let note: String?396 let units: String397 let decimals: Int398 let symbol: String399 let fiat: String?400 let value: Double401 let change: QChange?402 let warning: String?403 }404405 let snapshot: WalletSnapshot406 let hidden: Bool407 let namespace: Namespace.ID408409 var entries: [Entry] {410 var out = [Entry]()411 for chain in snapshot.chains {412 guard let data = chain.data.value else { continue }413 let network = chain.network414 let nativeLine = snapshot.nativeLine(chain.id)415 out.append(Entry(id: chain.id.rawValue, route: .chain(chain.id), asset: .native(network), name: chain.chain.nativeName, note: chain.chain.isTest ? chain.chain.shortName : nil,416 units: data.native.total.description, decimals: data.native.decimals, symbol: data.native.symbol,417 fiat: WalletChainFormat.fiat(nativeLine, currency: snapshot.currency), value: nativeLine?.value ?? nativeLine?.referenceValue ?? 0,418 change: chain.chain.isTest ? nil : WalletChainFormat.change(snapshot.quote(of: chain.chain)), warning: nil))419 for held in chain.heldTokens {420 let line = snapshot.tokenLine(held.token)421 out.append(Entry(id: held.id, route: .token(chain: chain.id, address: held.token.address), asset: .token(symbol: held.token.symbol, network: network),422 name: held.token.name, note: chain.chain.isTest ? chain.chain.shortName : nil, units: held.balance.value?.description ?? "0", decimals: held.token.decimals,423 symbol: held.token.symbol, fiat: WalletChainFormat.fiat(line, currency: snapshot.currency),424 value: line?.value ?? line?.referenceValue ?? 0, change: chain.chain.isTest ? nil : WalletChainFormat.change(snapshot.quote(of: held.token)),425 warning: held.balance.value == nil ? "Balance not read" : held.warning))426 }427 }428 // stable: by value, then in the order of the networks429 return out.enumerated().sorted { a, b in a.element.value != b.element.value ? a.element.value > b.element.value : a.offset < b.offset }.map(\.element)430 }431432 var body: some View {433 let entries = entries434 let unread = snapshot.chains.filter { $0.data.value == nil }435 if entries.isEmpty {436 QListSection {437 ForEach(0..<min(4, max(2, snapshot.chains.count)), id: \.self) { _ in QSkeletonRow() }438 }439 .accessibilityLabel("Assets are not loaded yet")440 } else {441 QListSection(footnote: unread.isEmpty ? nil : "Not read yet: \(unread.map(\.chain.displayName).joined(separator: ", ")).") {442 ForEach(entries) { entry in443 NavigationLink(value: entry.route) {444 AssetRow(asset: entry.asset, name: entry.name, note: entry.warning ?? entry.note, units: entry.units, decimals: entry.decimals, symbol: entry.symbol,445 fiat: entry.fiat, change: entry.change, hidden: hidden)446 }447 .buttonStyle(.qRow)448 .qMatchedSource(id: entry.route, in: namespace)449 }450 }451 }452 }453}454455// MARK: - Detected tokens456457/// Tokens found on the accounts that the user has not accepted: named, never valued, with the way to review them.458private struct DashboardDetectedNotice: View {459 let snapshot: WalletSnapshot460461 var body: some View {462 let chains = snapshot.chains.filter { !$0.detectedTokens.isEmpty }463 let count = chains.reduce(0) { $0 + $1.detectedTokens.count }464 if count > 0 {465 QListSection("Detected tokens", footnote: "Anyone can send a token to an address. Detected tokens are kept apart and are not counted in the total until you accept them; hide the ones you do not recognise.") {466 ForEach(chains) { chain in467 NavigationLink(value: WalletRoute.chain(chain.id)) {468 HStack(spacing: QSpace.m) {469 ChainGlyph(chain.network)470 VStack(alignment: .leading, spacing: 2) {471 Text("\(chain.detectedTokens.count) on \(chain.chain.displayName)").font(QFont.body).foregroundStyle(QColor.textPrimary)472 Text(chain.detectedTokens.prefix(4).map(\.token.symbol).joined(separator: ", ") + (chain.detectedTokens.count > 4 ? "…" : ""))473 .font(QFont.caption).foregroundStyle(QColor.textSecondary).lineLimit(1)474 }475 Spacer(minLength: QSpace.s)476 Text("Review").font(QFont.callout).foregroundStyle(QColor.violet)477 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(QColor.textTertiary).accessibilityHidden(true)478 }479 .frame(minHeight: QMetric.rowMinHeight)480 .contentShape(Rectangle())481 }482 .buttonStyle(.qRow)483 .accessibilityElement(children: .combine)484 }485 }486 }487 }488}489490// MARK: - Loading491492/// The shape of the dashboard while the first snapshot is read from disk.493private struct DashboardSkeleton: View {494 var body: some View {495 ScrollView {496 VStack(alignment: .leading, spacing: QMetric.sectionSpacing) {497 VStack(alignment: .leading, spacing: QSpace.m) {498 QSkeletonBlock(width: 120, height: 10)499 QSkeletonBlock(width: 220, height: 34)500 QSkeletonBlock(width: 140, height: 12)501 }502 QListSection {503 ForEach(0..<4, id: \.self) { _ in QSkeletonRow() }504 }505 }506 .padding(QMetric.screenPadding)507 .frame(maxWidth: 640)508 .frame(maxWidth: .infinity)509 }510 .scrollDisabled(true)511 .accessibilityElement(children: .ignore)512 .accessibilityLabel("Loading the wallet")513 }514}515