SPB Git

Repository Public

WalletChainAdapter.swift 14.1 KB 301 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Wallet/WalletChainAdapter.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// The one place where the chains of the wallet service (`ChainDescriptor`, `ChainSnapshot`) become what the design47// system draws (`QChain`, `QNetwork`, `QSyncState`). Every wallet screen goes through these extensions: no screen48// maps a chain identifier to a glyph, a name or a colour by itself.4950extension ChainDescriptor {51    /// The chain of the design system this network belongs to (a test network belongs to the chain of its main network).52    var qChain: QChain {53        switch mainCounterpart {54        case .bitcoin: return .bitcoin55        case .litecoin: return .litecoin56        case .dogecoin: return .dogecoin57        case .bitcoinCash: return .bitcoinCash58        case .ethereum: return .ethereum59        case .base: return .base60        case .arbitrum: return .arbitrum61        case .optimism: return .optimism62        case .polygon: return .polygon63        case .bsc: return .bsc64        case .avalanche: return .avalanche65        case .solana: return .solana66        case .tron: return .tron67        default:68            // an identifier this build does not know: the family decides the glyph, the name stays the service's69            switch family {70            case .utxo: return .bitcoin71            case .evm: return .ethereum72            case .solana: return .solana73            case .tron: return .tron74            }75        }76    }7778    /// The network as the design system shows it, named by the service and by nothing else: the short name in badges79    /// and pickers ("Arb Sepolia", "Signet"), the display name wherever the network is named on its own ("Arbitrum80    /// Sepolia", "Bitcoin Signet"), the test flag and, on an EVM network, its chain identifier.81    var qNetwork: QNetwork {82        QNetwork(chain: qChain, name: shortName, fullName: displayName, isTest: isTest, detail: evmChainID.map { "Chain ID \($0)" })83    }8485    /// False where a mistyped character of an address cannot be detected. A Solana address is a bare public key;86    /// Bitcoin-family, EVM (EIP-55, as the wallet writes it) and TRON (Base58Check) addresses carry a checksum.87    var addressHasChecksum: Bool { family != .solana }8889    /// What a token is called on this chain.90    var tokenStandardName: String {91        switch family {92        case .utxo: return "token"93        case .evm: return "ERC-20 token"94        case .solana: return "SPL token"95        case .tron: return "TRC-20 token"96        }97    }9899    /// What identifies a token on this chain, for the "add a token" form.100    var tokenAddressNoun: String { family == .solana ? "mint address" : "contract address" }101102    /// How the chain words the height the data was read at.103    var heightNoun: String { family == .solana ? "Slot" : "Block" }104}105106extension ChainID {107    var descriptor: ChainDescriptor? { ChainRegistry.descriptor(self) }108}109110extension BitcoinNetwork {111    /// The network of a UTXO coin named by a Bitcoin-family value (Shield reports, PSBT reviews): the same names as112    /// its descriptor gives (`QNetwork(_: BitcoinNetwork)` reads them from `QyvoraCore`).113    var qNetwork: QNetwork { QNetwork(self) }114}115116extension ChainToken {117    var qNetwork: QNetwork? { chain.descriptor?.qNetwork }118}119120extension ChainSnapshot {121    var network: QNetwork { chain.qNetwork }122123    /// Native balance in base units as a digit string; nil while it is not known (a dash is shown, never a zero).124    var nativeUnits: String? { data.value.map { $0.native.total.description } }125126    var tokens: [ChainTokenBalance] { data.value?.tokens ?? [] }127    var detectedTokens: [ChainTokenBalance] { data.value?.detectedTokens ?? [] }128129    /// Tokens of the list that hold something (a balance that could not be read counts: it is shown as unknown).130    var heldTokens: [ChainTokenBalance] {131        tokens.filter {132            switch $0.balance {133            case .available(let v): return !v.isZero134            case .unavailable: return true135            case .notLoaded: return false136            }137        }138    }139140    var utxoSnapshot: BitcoinSnapshot? {141        if case .utxo(let s)? = data.value?.extras { return s }142        return nil143    }144145    var evmSnapshot: EthereumSnapshot? {146        if case .evm(let s)? = data.value?.extras { return s }147        return nil148    }149150    var solanaExtras: SolanaExtras? {151        if case .solana(let s)? = data.value?.extras { return s }152        return nil153    }154155    var tronExtras: TronExtras? {156        if case .tron(let s)? = data.value?.extras { return s }157        return nil158    }159160    /// The address a row or a header can show: the account on an account chain, the next receive address otherwise.161    var displayAddress: String? { accountAddress ?? receive?.address }162}163164@MainActor165extension WalletStore {166    /// State of the synchronization of one chain, as the rows and banners show it: running (with the measured167    /// fraction when the service reports a total), failed with its reason, restored from the previous session, or168    /// up to date as of the last reading.169    func syncState(of chain: ChainSnapshot) -> QSyncState {170        if chain.isSynchronizing || queuedChains.contains(chain.id) { return .syncing(progress: syncFraction(of: chain.id)) }171        if let reason = chain.syncError { return .failed(reason: reason) }172        guard let data = chain.data.value else {173            if case .unavailable(let reason) = chain.data { return .failed(reason: reason) }174            return .idle(updated: nil)175        }176        return data.isFromPreviousSession ? .stale(since: data.synchronizedAt) : .idle(updated: data.synchronizedAt)177    }178179    /// One state for the whole wallet: syncing while any chain runs, failed when every chain failed, stale when what180    /// is shown comes from the previous session, otherwise idle as of the oldest reading.181    func overallSyncState(_ snapshot: WalletSnapshot) -> QSyncState {182        let states = snapshot.chains.map { syncState(of: $0) }183        let running = states.filter { if case .syncing = $0 { return true } else { return false } }.count184        if running > 0 {185            let done = snapshot.chains.count - running186            return .syncing(progress: snapshot.chains.count > 1 ? Double(done) / Double(snapshot.chains.count) : syncFraction(of: snapshot.chains[0].id))187        }188        let failures = states.compactMap { state -> String? in189            if case .failed(let reason) = state { return reason }190            return nil191        }192        if !failures.isEmpty, failures.count == states.count { return .failed(reason: failures.count == 1 ? failures[0] : "No network could be synchronized. " + failures[0]) }193        if snapshot.valuation.isFromPreviousSession { return .stale(since: snapshot.valuation.balancesAsOf) }194        return .idle(updated: snapshot.valuation.balancesAsOf)195    }196}197198extension WalletSnapshot {199    /// Valuation line of the native coin of a chain; nil before the chain has a snapshot.200    func nativeLine(_ chain: ChainID) -> ValuationLine? {201        valuation.lines.first { $0.chain == chain && !$0.id.contains(":") }202    }203204    /// Valuation line of a token; nil when it holds nothing or the chain has no snapshot.205    func tokenLine(_ token: ChainToken) -> ValuationLine? {206        valuation.lines.first { $0.chain == token.chain && $0.id.hasSuffix(":" + token.address) }207    }208209    func quote(of chain: ChainDescriptor) -> MarketQuote? { market.quotes[chain.priceID] }210    func quote(of token: ChainToken) -> MarketQuote? { token.priceID.flatMap { market.quotes[$0] } }211212    /// The active chain an identifier stands for: the chain itself or, for an identifier of the other mode (a main213    /// identifier while the wallet is on test networks, and the reverse), the network of the same chain that is214    /// active now. nil when the chain is not enabled.215    func activeChain(_ id: ChainID) -> ChainSnapshot? {216        if let exact = chain(id) { return exact }217        guard let main = id.descriptor?.mainCounterpart else { return nil }218        return chains.first { $0.chain.mainCounterpart == main }219    }220221    var isTestMode: Bool { !chains.contains { !$0.chain.isTest } }222    var canSign: Bool { profile.kind == .full }223224    /// The sentence of the unaudited-mainnet notice, when it applies.225    var unauditedNotice: String? {226        unauditedMainnet ? "Real funds, unaudited cryptography. Per-transaction limits apply on every network; keep only small amounts in this wallet." : nil227    }228}229230/// Formatting of chain amounts for places that need a string (review lines, notes). Rows use `AmountText`.231enum WalletChainFormat {232    /// "0.0421 BTC", "10,154,631.88 SOL": exact unless `maxFractionDigits` cuts it (cut, never rounded up), thousands233    /// grouped, trailing zeros removed.234    static func amount(_ units: UInt256, decimals: Int, symbol: String, maxFractionDigits: Int? = nil) -> String {235        AmountFormat.format(units: units.description, decimals: decimals, maxFractionDigits: maxFractionDigits) + " " + symbol236    }237238    static func native(_ units: UInt256, _ chain: ChainDescriptor, maxFractionDigits: Int? = nil) -> String {239        amount(units, decimals: chain.nativeDecimals, symbol: chain.nativeSymbol, maxFractionDigits: maxFractionDigits)240    }241242    /// An amount in few characters, for places where an arbitrary token balance must not push the layout: four243    /// significant digits, thousands as K, M, B, T and a power of ten beyond. Cut, never rounded up.244    static func short(_ units: UInt256, decimals: Int) -> String {245        let text = BaseUnits.format(units, decimals: decimals, maxFractionDigits: 4)246        let whole = text.split(separator: ".").first.map(String.init) ?? text247        guard whole.count > 4 else { return text }248        let suffixes = ["", "K", "M", "B", "T"]249        let group = (whole.count - 1) / 3250        if group < suffixes.count {251            let head = whole.count - group * 3252            let fraction = String(whole.dropFirst(head).prefix(2))253            return whole.prefix(head) + (fraction == "00" ? "" : "." + fraction) + suffixes[group]254        }255        return "\(whole.prefix(1)).\(whole.dropFirst().prefix(2)) × 10^\(whole.count - 1)"256    }257258    static func sol(_ lamports: UInt64) -> String { amount(UInt256(lamports), decimals: 9, symbol: "SOL") }259    static func trx(_ sun: UInt64) -> String { amount(UInt256(sun), decimals: 6, symbol: "TRX") }260261    /// Fiat line of a valuation line: the value on a main network, "ref." and the value on a test network.262    static func fiat(_ line: ValuationLine?, currency: DisplayCurrency) -> String? {263        guard let line else { return nil }264        if let value = line.value { return WalletFormat.fiat(value, currency) }265        if let reference = line.referenceValue { return "ref. " + WalletFormat.fiat(reference, currency) }266        return nil267    }268269    /// Fiat value of a chain's holdings (coin and tokens): the real value, or a labelled reference value.270    static func fiat(_ valuation: ChainValuation?, currency: DisplayCurrency) -> String? {271        guard let valuation else { return nil }272        if let value = valuation.realValue { return WalletFormat.fiat(value, currency) }273        if let reference = valuation.referenceValue { return "ref. " + WalletFormat.fiat(reference, currency) }274        return nil275    }276277    /// Fiat value of an amount at a quote; "ref." on a test network, the quote's date when it is stale.278    static func fiat(units: UInt256, decimals: Int, quote: MarketQuote?, isTest: Bool, datesStalePrice: Bool = true) -> String? {279        guard let value = WalletFormat.fiat(units: units, decimals: decimals, quote: quote), let quote else { return nil }280        var text = (isTest ? "ref. " : "") + WalletFormat.fiat(value, quote.currency)281        if quote.isStale, datesStalePrice {282            let today = Calendar.current.isDateInToday(quote.fetchedAt)283            text += " (price of \(quote.fetchedAt.formatted(date: today ? .omitted : .abbreviated, time: .shortened)))"284        }285        return text286    }287288    /// The 24 h change of a quote as the design system shows it.289    static func change(_ quote: MarketQuote?) -> QChange? {290        guard let percent = quote?.change24h, percent.isFinite else { return nil }291        return QChange(fraction: percent / 100)292    }293294    /// The typed decimal text of an amount as base units; nil when it is not a number of at most `decimals` decimals.295    static func baseUnits(_ text: String, decimals: Int) -> UInt256? {296        let normalized = text.replacingOccurrences(of: ",", with: ".").trimmingCharacters(in: .whitespaces)297        guard !normalized.isEmpty, let digits = AmountFormat.parse(normalized, decimals: decimals) else { return nil }298        return UInt256(decimal: digits)299    }300}301
Files main
Menu

Theme