SPB Git

Repository Public

ChainDetailScreen.swift 13.7 KB 278 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Wallet/ChainDetailScreen.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 QyvoraWallet44import QyvoraUI4546/// One active chain: balance, actions, price, tokens, what only its family has, recent activity, key exposure and47/// the account's public details. Read from the chain's `ChainSnapshot`; what was not read is shown as not read.48struct ChainDetailScreen: View {49    let chainID: ChainID5051    @Environment(WalletStore.self) private var wallet52    @Environment(\.walletHooks) private var hooks53    @HideAmounts private var hideAmounts54    @State private var sheet: WalletSheet?5556    var body: some View {57        Group {58            if let snapshot = wallet.snapshot, let chain = snapshot.activeChain(chainID) {59                content(chain, snapshot)60            } else {61                UnavailableDataView(reason: "This network is not enabled in the current mode. Enable it from the list of networks.", title: "Network not active")62                    .padding(QSpace.xl).frame(maxWidth: .infinity, maxHeight: .infinity)63            }64        }65        .qScreen()66        .navigationTitle(wallet.snapshot?.activeChain(chainID)?.network.fullName ?? chainID.descriptor?.qNetwork.fullName ?? "Network")67        .navigationBarTitleDisplayMode(.inline)68        .toolbar {69            ToolbarItem(placement: .topBarTrailing) {70                Button { hideAmounts.toggle() } label: { Image(systemName: hideAmounts ? "eye.slash" : "eye") }71                    .accessibilityLabel(hideAmounts ? "Show amounts" : "Hide amounts")72            }73        }74        .qHaptic(.toggled, trigger: hideAmounts)75        .walletSheet($sheet)76        #if DEBUG77        .task(id: DebugNavigator.shared.serial) {78            if sheet != nil {79                sheet = nil80                try? await Task.sleep(for: .milliseconds(700))81            }82        }83        #endif84    }8586    func content(_ chain: ChainSnapshot, _ snapshot: WalletSnapshot) -> some View {87        ScrollView {88            VStack(alignment: .leading, spacing: QMetric.sectionSpacing) {89                VStack(alignment: .leading, spacing: QSpace.xl) {90                    header(chain, snapshot)91                    QuickActionBar([92                        .send(isEnabled: chain.data.value != nil) { sheet = .send(SendPrefill(chain: chain.id)) },93                        .receive(isEnabled: chain.receive != nil) { sheet = .receive(chain.id) },94                    ])95                }96                syncNotice(chain)97                if let limits = chain.limits { WalletLimitsCard(limits: limits) }98                PriceChartSection(assetID: chain.chain.priceID, currency: snapshot.currency, isTestNetwork: chain.chain.isTest).id("price")99                if chain.chain.capabilities.tokens { ChainTokensSection(chain: chain, snapshot: snapshot, hidden: hideAmounts).id("tokens") }100                ChainFamilyPanel(chain: chain, hidden: hideAmounts).id("family")101                activity(chain).id("activity")102                exposure(chain).id("exposure")103                account(chain).id("account")104                if let address = chain.accountAddress, let url = chain.chain.explorerAddressURL(address) {105                    WalletExplorerLink(title: "View the account on a block explorer", url: url)106                }107                Color.clear.frame(height: 1).id("bottom")108            }109            .padding(.horizontal, QMetric.screenPadding)110            .padding(.top, QSpace.l)111            .padding(.bottom, QSpace.xl)112            .frame(maxWidth: 640)113            .frame(maxWidth: .infinity)114        }115        .debugScroll()116        .refreshable { await wallet.synchronize(chains: [chain.id]) }117    }118119    // MARK: Header120121    func header(_ chain: ChainSnapshot, _ snapshot: WalletSnapshot) -> some View {122        let line = snapshot.nativeLine(chain.id)123        return VStack(alignment: .leading, spacing: QSpace.m) {124            HStack(spacing: QSpace.m) {125                ChainGlyph(chain.network, size: .large)126                VStack(alignment: .leading, spacing: QSpace.xs) {127                    QEyebrow("\(chain.chain.nativeName) balance")128                    NetworkBadge(chain.network, style: .plain)129                }130                Spacer(minLength: 0)131            }132            if let data = chain.data.value {133                AmountText(units: data.native.total, decimals: data.native.decimals, symbol: data.native.symbol,134                           fiat: WalletChainFormat.fiat(line, currency: snapshot.currency), style: .balance, hidden: hideAmounts)135                    .privacySensitive()136                    .qNumericTransition()137                if !data.native.pending.isZero {138                    WalletNoteLine(text: "Includes \(hideAmounts ? "••••" : WalletChainFormat.amount(data.native.pending, decimals: data.native.decimals, symbol: data.native.symbol)) not confirmed yet.",139                                   systemImage: "clock")140                }141                if chain.chain.isTest {142                    WalletNoteLine(text: "Test coins have no monetary value; the figure in \(snapshot.currency.rawValue.uppercased()) is what the same amount is worth on the main network.", systemImage: "flask")143                }144            } else {145                Text("—").font(QFont.display).foregroundStyle(QColor.textTertiary).accessibilityLabel("Balance not known")146                WalletNoteLine(text: chain.isSynchronizing ? "Reading the balance." : "The balance has not been read yet.", systemImage: "arrow.triangle.2.circlepath")147            }148        }149        .frame(maxWidth: .infinity, alignment: .leading)150    }151152    @ViewBuilder153    func syncNotice(_ chain: ChainSnapshot) -> some View {154        let state = wallet.syncState(of: chain)155        switch state {156        case .syncing:157            SyncBanner(state, title: wallet.chainProgress[chain.id]?.text ?? "Synchronizing")158        case .failed:159            SyncBanner(state, title: chain.data.value == nil ? "Could not be synchronized" : "The last refresh failed; older figures are shown") {160                Task { await wallet.synchronize(chains: [chain.id]) }161            }162        case .stale:163            SyncBanner(state) { Task { await wallet.synchronize(chains: [chain.id]) } }164        case .idle:165            EmptyView()166        }167    }168169    // MARK: Activity170171    @ViewBuilder172    func activity(_ chain: ChainSnapshot) -> some View {173        if let data = chain.data.value {174            switch data.history {175            case .unavailable(let reason):176                VStack(alignment: .leading, spacing: QSpace.s) {177                    QEyebrow("Recent activity")178                    UnavailableDataView(reason: reason, title: "History is not available on \(chain.chain.displayName)", compact: true)179                    WalletNoteLine(text: "The balance above is read on chain and is complete.")180                }181            case .notLoaded:182                QListSection("Recent activity") { ForEach(0..<3, id: \.self) { _ in QSkeletonRow() } }183            case .available(let entries):184                let items = ActivityItem.sorted(entries.map { ActivityItem(entry: $0, chain: chain.chain) })185                if items.isEmpty {186                    VStack(alignment: .leading, spacing: QSpace.s) {187                        QEyebrow("Recent activity")188                        WalletNoteLine(text: "No transaction was found for this account on \(chain.chain.displayName).", systemImage: "tray")189                    }190                } else {191                    QListSection("Recent activity") {192                        ForEach(items.prefix(5)) { item in193                            NavigationLink(value: item.route) { ActivityRow(item: item, hidden: hideAmounts, showsDate: true) }.buttonStyle(.qRow)194                        }195                        if items.count > 5 {196                            NavigationLink(value: WalletRoute.activity(chain.id)) {197                                HStack {198                                    Text("All \(items.count) entries").font(QFont.callout.weight(.medium)).foregroundStyle(QColor.violet)199                                    Spacer()200                                    Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(QColor.textTertiary).accessibilityHidden(true)201                                }202                                .frame(minHeight: QMetric.minTap + 6)203                                .contentShape(Rectangle())204                            }205                            .buttonStyle(.qRow)206                        }207                    }208                }209            }210        }211    }212213    // MARK: Exposure214215    @ViewBuilder216    func exposure(_ chain: ChainSnapshot) -> some View {217        if let exposure = chain.data.value?.exposure {218            let badge: (String, String, QBadge.Tone) = {219                switch exposure.publicKeyExposed {220                case true?: return ("Public key exposed", "eye", .warning)221                case false?: return ("Public key not exposed", "eye.slash", .positive)222                case nil: return ("Not measured", "questionmark", .neutral)223                }224            }()225            ReviewSection("Public-key exposure",226                          footnote: "\(chain.chain.signatureScheme) signatures do not resist a large quantum computer. QYVORA's post-quantum cryptography protects the vault on this device, not \(chain.chain.nativeName) transactions.") {227                VStack(alignment: .leading, spacing: QSpace.s) {228                    QBadge(badge.0, systemImage: badge.1, tone: badge.2)229                    Text(exposure.statement).font(QFont.callout).foregroundStyle(QColor.textPrimary).fixedSize(horizontal: false, vertical: true)230                    if let count = exposure.outgoingTransactionCount, count > 0 {231                        Text("Transactions sent by the account: \(count)").font(QFont.caption).foregroundStyle(QColor.textSecondary)232                    }233                }234                .padding(.vertical, QSpace.m)235                .frame(maxWidth: .infinity, alignment: .leading)236                .accessibilityElement(children: .combine)237                if let open = hooks.openShield {238                    Button { open(ShieldSection(chain.chain)) } label: {239                        HStack {240                            Label("Open in the Shield", systemImage: "shield.lefthalf.filled").font(QFont.callout.weight(.medium)).foregroundStyle(QColor.violet)241                            Spacer()242                            Image(systemName: "arrow.up.forward").font(.footnote.weight(.semibold)).foregroundStyle(QColor.textTertiary).accessibilityHidden(true)243                        }244                        .frame(minHeight: QMetric.minTap + 6)245                        .contentShape(Rectangle())246                    }247                    .buttonStyle(.qRow)248                    .accessibilityHint("Opens the Shield tab")249                }250            }251        }252    }253254    // MARK: Account255256    @ViewBuilder257    func account(_ chain: ChainSnapshot) -> some View {258        if let single = chain.data.value?.notes.first(where: { $0.hasPrefix(WalletService.singleIndexerNotePrefix) }) {259            WarningBanner(.warning, title: "Read from one source", message: single)260        }261        ReviewSection("Account", footnote: chain.data.value.flatMap { data in262            let rest = data.notes.filter { !$0.hasPrefix(WalletService.singleIndexerNotePrefix) }263            return rest.isEmpty ? nil : rest.joined(separator: " ")264        }) {265            if let address = chain.accountAddress {266                ReviewRow("Address", value: address, emphasis: .address, copyValue: address).privacySensitive()267            }268            ReviewRow("Derivation path", value: chain.chain.derivationPath)269            ReviewRow("Signature scheme", value: chain.chain.signatureScheme)270            if let chainID = chain.chain.evmChainID { ReviewRow("Chain ID", value: String(chainID)) }271            if let data = chain.data.value {272                ReviewRow(chain.chain.heightNoun + " read", value: data.height.formatted(.number.grouping(.never)))273                ReviewRow("Read", value: WalletFormat.timestamp(data.synchronizedAt), secondary: data.isFromPreviousSession ? "Previous session" : nil)274            }275        }276    }277}278
Files main
Menu

Theme