SPB Git

Repository Public

ChainFamilyPanel.swift 19.1 KB 392 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Wallet/ChainFamilyPanel.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 QyvoraBitcoin44import QyvoraWallet45import QyvoraUI4647/// What only one family of chains has, read from `ChainExtras`: coins and addresses on UTXO chains, nonces on EVM48/// networks, rent on Solana, activation and resources on TRON.49struct ChainFamilyPanel: View {50    let chain: ChainSnapshot51    let hidden: Bool5253    var body: some View {54        switch chain.data.value?.extras {55        case .utxo(let snapshot)?: utxo(snapshot)56        case .evm(let snapshot)?: evm(snapshot)57        case .solana(let extras)?: solana(extras)58        case .tron(let extras)?: tron(extras)59        case nil: EmptyView()60        }61    }6263    // MARK: UTXO6465    func utxo(_ s: BitcoinSnapshot) -> some View {66        let exposed = s.utxos.filter { $0.exposure == .revealedBySpend || $0.exposure == .revealedByScript }.count67        let frozen = s.utxos.filter(\.isFrozen).count68        let used = s.addresses.filter(\.isUsed).count69        var coinNote = s.utxos.isEmpty ? "No unspent output" : "\(exposed) with a published key"70        if frozen > 0 { coinNote += " · \(frozen) frozen" }71        return QListSection("Coins and addresses", footnote: "\(chain.chain.nativeName) is held as separate coins on separate addresses. A new address is given for every payment; a coin whose address was already spent from sits behind a published key.",72                            separatorInset: 58) {73            NavigationLink(value: WalletRoute.coins(chain.id)) {74                linkRow("Coins", subtitle: coinNote, systemImage: "circle.grid.2x2", trailing: "\(s.utxos.count)")75            }76            .buttonStyle(.qRow)77            NavigationLink(value: WalletRoute.addresses(chain.id)) {78                linkRow("Addresses and labels", subtitle: s.reusedAddresses.isEmpty ? "\(used) used" : "\(used) used · \(s.reusedAddresses.count) reused", systemImage: "number",79                        trailing: "\(s.addresses.count)")80            }81            .buttonStyle(.qRow)82        }83    }8485    func linkRow(_ title: String, subtitle: String, systemImage: String, trailing: String) -> some View {86        HStack(spacing: QSpace.m) {87            QNavigationLabel(title, subtitle: subtitle, systemImage: systemImage, trailing: trailing)88            Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(QColor.textTertiary).accessibilityHidden(true)89        }90        .frame(minHeight: QMetric.rowMinHeight)91        .contentShape(Rectangle())92    }9394    // MARK: EVM9596    func evm(_ s: EthereumSnapshot) -> some View {97        ReviewSection("Account on \(chain.chain.displayName)",98                      footnote: "The same address is used on every EVM network, with a separate balance and a separate nonce on each. Funds sent to it on a network that is not enabled are not lost: they appear when that network is enabled.") {99            ReviewRow("Transactions sent (nonce)", value: String(s.latestNonce))100            if s.hasPendingTransaction {101                ReviewRow("Pending", value: s.pendingNonce > s.latestNonce + 1 ? "\(s.pendingNonce - s.latestNonce) transactions waiting" : "1 transaction waiting",102                          secondary: "Nonce \(s.latestNonce). A new payment waits behind it, or replaces it.")103            } else {104                ReviewRow("Pending", value: "None")105            }106            switch s.approvals {107            case .available(let approvals):108                ReviewRow("Open token approvals", value: String(approvals.count), secondary: approvals.isEmpty ? nil : "Listed in the Shield, where they can be revoked")109            case .unavailable(let reason):110                ReviewRow("Open token approvals", value: "Not read", secondary: reason)111            case .notLoaded:112                ReviewRow("Open token approvals", value: "Not read yet")113            }114        }115    }116117    // MARK: Solana118119    func solana(_ e: SolanaExtras) -> some View {120        ReviewSection("Account on \(chain.chain.displayName)",121                      footnote: "A Solana address is the public key of the account itself. Every account must keep a minimum balance (rent) or hold nothing at all; each token is held in a separate token account that locks its own minimum, returned when that account is closed.") {122            ReviewRow("On chain", value: e.accountExists ? "Yes" : "Not yet", secondary: e.accountExists ? nil : "Created by the first payment it receives")123            ReviewRow("Minimum balance of an account", value: WalletChainFormat.sol(e.systemAccountRent),124                      secondary: e.accountExists ? nil : "A first payment below this is rejected")125            ReviewRow("Token accounts", value: String(e.tokenAccountCount))126            ReviewRow("Locked by a new token account", value: WalletChainFormat.sol(e.tokenAccountRent),127                      secondary: e.token2022AccountRent == e.tokenAccountRent ? "Paid by whoever creates it" : "Token-2022: \(WalletChainFormat.sol(e.token2022AccountRent)). Paid by whoever creates it")128        }129    }130131    // MARK: TRON132133    func tron(_ e: TronExtras) -> some View {134        let r = e.resources135        return VStack(alignment: .leading, spacing: QSpace.l) {136            ReviewSection("Account on \(chain.chain.displayName)") {137                ReviewRow("Activated", value: e.isActivated ? "Yes" : "Not yet",138                          secondary: e.isActivated ? nil : "The first TRX it receives creates it; the sender pays \(WalletChainFormat.trx(e.parameters.accountActivationFeeSun)) for that")139            }140            ReviewSection("Resources", footnote: resourceMeaning(e)) {141                ChainResourceMeter(title: "Free bandwidth today", available: r.freeBandwidth, limit: r.freeNetLimit, unit: "bytes")142                if r.netLimit > 0 { ChainResourceMeter(title: "Staked bandwidth", available: r.stakedBandwidth, limit: r.netLimit, unit: "bytes") }143                ChainResourceMeter(title: "Energy", available: r.energy, limit: r.energyLimit, unit: "units")144            }145        }146    }147148    func resourceMeaning(_ e: TronExtras) -> String {149        let p = e.parameters150        return "Bandwidth pays for the bytes of a transaction: a TRX transfer takes about 270. When neither allowance covers a whole transaction, every byte is paid in TRX (\(WalletChainFormat.trx(p.bandwidthPriceSun)) per byte). "151            + "Energy pays for token transfers; without energy from staking, TRX is burned instead (\(WalletChainFormat.trx(p.energyPriceSun)) per unit). The review of a payment shows the exact figures."152    }153}154155/// A resource of a TRON account: what is left, of how much, as figures and as a bar. An account without a limit156/// (no staked energy) says so instead of showing an empty bar.157private struct ChainResourceMeter: View {158    let title: String159    let available: UInt64160    let limit: UInt64161    let unit: String162163    var body: some View {164        VStack(alignment: .leading, spacing: QSpace.s) {165            HStack(alignment: .firstTextBaseline) {166                Text(title).font(QFont.callout).foregroundStyle(QColor.textSecondary)167                Spacer(minLength: QSpace.s)168                Text(limit == 0 ? "None" : "\(available.formatted()) of \(limit.formatted()) \(unit)")169                    .font(QFont.figure).foregroundStyle(QColor.textPrimary).multilineTextAlignment(.trailing)170            }171            if limit > 0 {172                GeometryReader { geo in173                    ZStack(alignment: .leading) {174                        Capsule().fill(QColor.surfaceSunken)175                        Capsule().fill(QColor.accentLine).frame(width: max(4, geo.size.width * CGFloat(Double(available) / Double(limit))))176                    }177                }178                .frame(height: 6)179                .accessibilityHidden(true)180            }181        }182        .padding(.vertical, QSpace.m)183        .accessibilityElement(children: .ignore)184        .accessibilityLabel(limit == 0 ? "\(title): none" : "\(title): \(available) of \(limit) \(unit) left")185    }186}187188// MARK: - Coins189190/// Unspent outputs of a UTXO chain with their key-exposure class and the freeze switch of coin control.191struct ChainCoinsScreen: View {192    let chainID: ChainID193194    @Environment(WalletStore.self) private var wallet195    @Environment(\.walletHooks) private var hooks196    @HideAmounts private var hideAmounts197    @State private var error: String?198199    var chain: ChainSnapshot? { wallet.snapshot?.activeChain(chainID) }200201    var body: some View {202        ScrollView {203            VStack(alignment: .leading, spacing: QSpace.xl) {204                if let chain, let coins = chain.utxoSnapshot {205                    if coins.utxos.isEmpty {206                        EmptyStateView(systemImage: "circle.grid.2x2", title: "No coin", message: "This account holds no unspent output on \(chain.chain.displayName).")207                            .frame(maxWidth: .infinity).padding(.top, QSpace.xxl)208                    } else {209                        InlineError(message: error)210                        QListSection("\(coins.utxos.count) unspent output\(coins.utxos.count == 1 ? "" : "s")",211                                     footnote: "A frozen coin is never selected automatically. Exposure says whether the public key of the coin's address is already on chain.",212                                     separatorInset: QMetric.padding) {213                            ForEach(coins.utxos) { utxo in row(utxo, chain.chain) }214                        }215                        if chain.chain.mainCounterpart == .bitcoin, let open = hooks.openShield {216                            QListSection(separatorInset: 58) {217                                WalletActionRow(title: "Key exposure in the Shield", subtitle: "What exposure means, and the coins that can be moved to fresh addresses",218                                                systemImage: "shield.lefthalf.filled", external: true) { open(.bitcoin) }219                            }220                        }221                    }222                } else {223                    UnavailableDataView(reason: chain?.syncError ?? "This network has not been synchronized yet.", title: "Coins not loaded") {224                        Task { await wallet.synchronize(chains: [chainID]) }225                    }226                    .padding(.top, QSpace.xxl)227                }228            }229            .padding(.horizontal, QMetric.screenPadding)230            .padding(.vertical, QSpace.l)231            .frame(maxWidth: 640)232            .frame(maxWidth: .infinity)233        }234        .qScreen()235        .navigationTitle("Coins")236        .navigationBarTitleDisplayMode(.inline)237        .refreshable { await wallet.synchronize(chains: [chainID]) }238    }239240    func row(_ utxo: WalletUTXO, _ descriptor: ChainDescriptor) -> some View {241        VStack(alignment: .leading, spacing: QSpace.s) {242            HStack(alignment: .center) {243                AmountText(units: utxo.value, decimals: descriptor.nativeDecimals, symbol: descriptor.nativeSymbol, hidden: hideAmounts).privacySensitive()244                Spacer()245                Toggle("Frozen", isOn: Binding(get: { utxo.isFrozen }, set: { setFrozen($0, utxo) }))246                    .labelsHidden()247                    .tint(QColor.violet)248                    .accessibilityLabel("Freeze this coin")249            }250            if let label = utxo.address.flatMap({ wallet.snapshot?.profile.addressLabels[$0] }) {251                Text(label).font(QFont.callout).foregroundStyle(QColor.textPrimary)252            }253            if let address = utxo.address { AddressText(address, copyable: false).privacySensitive() }254            FlowLayout(spacing: QSpace.s) {255                QBadge(WalletFormat.exposureLabel(utxo.exposure), tone: WalletFormat.exposureTone(utxo.exposure))256                QBadge(utxo.confirmations == 0 ? "Unconfirmed" : "\(utxo.confirmations) conf.", tone: utxo.confirmations == 0 ? .warning : .neutral)257                if utxo.isFrozen { QBadge("Frozen", systemImage: "snowflake", tone: .accent) }258            }259            Text(utxo.exposureExplanation).font(QFont.caption).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)260            Text(utxo.id).font(QFont.mono).foregroundStyle(QColor.textTertiary).lineLimit(1).truncationMode(.middle)261                .accessibilityLabel("Output \(utxo.utxo.outPoint.index) of transaction \(MiddleTruncation.truncate(utxo.utxo.outPoint.txid))")262        }263        .padding(.vertical, QSpace.m)264    }265266    func setFrozen(_ frozen: Bool, _ utxo: WalletUTXO) {267        let outPoint = utxo.utxo.outPoint268        error = nil269        Task {270            do {271                try await wallet.run { try await $0.setFrozen(frozen, outPoint: outPoint) }272                await wallet.refresh()273            } catch {274                self.error = WalletStore.message(for: error)275            }276        }277    }278}279280// MARK: - Addresses281282/// Discovered addresses of a UTXO chain (receive and change) with labels, usage and reuse flags.283struct ChainAddressesScreen: View {284    let chainID: ChainID285286    @Environment(WalletStore.self) private var wallet287    @HideAmounts private var hideAmounts288    @State private var editing: WalletAddress?289    @State private var labelText = ""290    @State private var error: String?291292    var chain: ChainSnapshot? { wallet.snapshot?.activeChain(chainID) }293294    var body: some View {295        ScrollView {296            LazyVStack(alignment: .leading, spacing: QSpace.xl) {297                if let chain, let coins = chain.utxoSnapshot {298                    InlineError(message: error)299                    section("Receive addresses", coins.addresses.filter { $0.chain == .receive }, chain.chain,300                            footnote: "The gap after the last used address is scanned up to 20 unused addresses.")301                    section("Change addresses", coins.addresses.filter { $0.chain == .change }, chain.chain, footnote: nil)302                } else {303                    UnavailableDataView(reason: chain?.syncError ?? "This network has not been synchronized yet.", title: "Addresses not loaded") {304                        Task { await wallet.synchronize(chains: [chainID]) }305                    }306                    .padding(.top, QSpace.xxl)307                }308            }309            .padding(.horizontal, QMetric.screenPadding)310            .padding(.vertical, QSpace.l)311            .frame(maxWidth: 640)312            .frame(maxWidth: .infinity)313        }314        .qScreen()315        .navigationTitle("Addresses")316        .navigationBarTitleDisplayMode(.inline)317        .alert("Label", isPresented: Binding(get: { editing != nil }, set: { if !$0 { editing = nil } })) {318            TextField("Label", text: $labelText)319            Button("Save") { saveLabel() }320            Button("Cancel", role: .cancel) { editing = nil }321        } message: {322            Text("Labels stay on this device. Leave empty to remove the label.")323        }324    }325326    @ViewBuilder327    func section(_ title: String, _ addresses: [WalletAddress], _ descriptor: ChainDescriptor, footnote: String?) -> some View {328        if !addresses.isEmpty {329            QListSection(title, footnote: footnote, separatorInset: QMetric.padding) {330                ForEach(addresses) { address in row(address, descriptor) }331            }332        }333    }334335    /// Labels are read from the profile: `setAddressLabel` updates it at once.336    func label(_ address: String) -> String? { wallet.snapshot?.profile.addressLabels[address] }337338    func row(_ address: WalletAddress, _ descriptor: ChainDescriptor) -> some View {339        let label = label(address.address)340        return VStack(alignment: .leading, spacing: QSpace.s) {341            HStack(alignment: .firstTextBaseline) {342                Text(label ?? "No label")343                    .font(QFont.headline)344                    .foregroundStyle(label == nil ? QColor.textTertiary : QColor.textPrimary)345                Spacer()346                Button(label == nil ? "Add label" : "Edit") {347                    labelText = label ?? ""348                    editing = address349                }350                .font(.callout.weight(.medium))351                .buttonStyle(.borderless)352                .tint(QColor.violet)353            }354            AddressText(address.address, head: 12, tail: 8).privacySensitive()355            FlowLayout(spacing: QSpace.s) {356                if address.isReused {357                    QBadge("Reused", systemImage: "exclamationmark.triangle", tone: .warning)358                } else if address.isUsed {359                    QBadge("Used", tone: .neutral)360                } else {361                    QBadge("Unused", tone: .positive)362                }363                if address.isUsed { QBadge(WalletFormat.exposureLabel(address.exposure), tone: WalletFormat.exposureTone(address.exposure)) }364                if address.transactionCount > 0 { QBadge("\(address.transactionCount) tx", tone: .neutral) }365            }366            HStack {367                Text(address.path).font(QFont.mono).foregroundStyle(QColor.textTertiary)368                Spacer()369                if address.balance > 0 {370                    AmountText(units: address.balance, decimals: descriptor.nativeDecimals, symbol: descriptor.nativeSymbol, style: .compact, hidden: hideAmounts)371                }372            }373        }374        .padding(.vertical, QSpace.m)375    }376377    func saveLabel() {378        guard let address = editing?.address else { return }379        let text = labelText380        editing = nil381        error = nil382        Task {383            do {384                try await wallet.run { try await $0.setAddressLabel(text, for: address) }385                await wallet.refresh()386            } catch {387                self.error = WalletStore.message(for: error)388            }389        }390    }391}392
Files main
Menu

Theme