SPB Git

Repository Public

WalletService+Market.swift 20.4 KB 360 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraWallet/WalletService+Market.swift8// Module           : Qyvora Wallet9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//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 Foundation42import QyvoraCore43import QyvoraEthereum44import QyvoraNetworking45import QyvoraSolana46import QyvoraTron4748/// A price of the second source, with the moment it was read.49struct PriceCheck: Equatable, Sendable {50    var price: Double51    var fetchedAt: Date52}5354/// Quotes kept in memory and persisted as "last known" values with their dates.55struct MarketCache: Codable, Equatable, Sendable {56    struct Entry: Codable, Equatable, Sendable {57        var price: Double58        var change24h: Double?59        var change7d: Double?60        var sparkline7d: [Double]61        var fetchedAt: Date62        /// True for an entry read back from disk: a value of a previous session is never current.63        var fromDisk = false6465        enum CodingKeys: String, CodingKey { case price, change24h, change7d, sparkline7d, fetchedAt }66    }6768    /// currency → asset identifier → entry69    var quotes: [String: [String: Entry]] = [:]7071    mutating func markAllPersisted() {72        for c in quotes.keys { for id in (quotes[c] ?? [:]).keys { quotes[c]?[id]?.fromDisk = true } }73    }74}7576extension WalletService {77    static let bitcoinPriceID = "bitcoin"78    static let ethereumPriceID = "ethereum"7980    /// Identifiers the wallet wants prices for: bitcoin and ethereum (the primary chains), the native coin of every81    /// active chain and every listed token that has an identifier. One batched request fetches them all.82    func priceIDs() -> [String] {83        var ids = [Self.bitcoinPriceID, Self.ethereumPriceID]84        func add(_ id: String?) {85            if let id, !ids.contains(id) { ids.append(id) }86        }87        for t in listedTokens(profile.ethereumNetwork) { add(t.priceID) }88        for kind in Self.activeKinds(profile) {89            add(ChainRegistry.descriptor(kind).priceID)90            switch kind {91            case .utxo: break92            case .evm(let network): for t in listedTokens(network) { add(t.priceID) }93            case .solana(let network): for t in listedSolanaTokens(network) { add(t.priceID) }94            case .tron(let network): for t in listedTronTokens(network) { add(t.priceID) }95            }96        }97        return ids98    }99100    func quote(_ id: String, currency: DisplayCurrency) -> MarketQuote? {101        guard let e = market.quotes[currency.rawValue]?[id] else { return nil }102        let age = now().timeIntervalSince(e.fetchedAt)103        return MarketQuote(id: id, currency: currency, price: e.price, change24h: e.change24h, change7d: e.change7d, sparkline7d: e.sparkline7d,104                           fetchedAt: e.fetchedAt, isStale: e.fromDisk || age > Self.quoteFreshness || age < -60)105    }106107    /// How the dollar ceiling of an asset is converted into units on an unaudited mainnet build (QYV-SVC-087).108    enum LimitPricing: Equatable, Sendable {109        /// A built-in token pegged to the US dollar (`pegUSD` in the built-in tables): one source,110        /// `MainnetPolicy.stablecoinCeilingPrice` — never under 0.90, refused outside 0.50…2.00.111        case dollarPegged112        /// Everything else, native coins included: two independent sources that agree, the higher of the two, and the113        /// floor of `MainnetPolicy.minimumPlausibleUSDPrice` where the asset has one.114        case twoSources115    }116117    /// The first source's USD quote of `id`, if it is fresh; fetched when the cache has none. nil: no usable quote.118    private func firstSourceUSDPrice(_ id: String) async -> Double? {119        if let q = quote(id, currency: .usd), !q.isStale { return q.price.isFinite && q.price > 0 && q.price < 1e12 ? q.price : nil }120        guard !gate.isOffline else { return nil }121        let client = PriceClient(configuration: profile.endpoints, transport: gate)122        guard client.isConfigured, let fetched = try? await client.quotes(ids: [id], currency: "usd")[id],123              fetched.price.isFinite, fetched.price > 0, fetched.price < 1e12 else { return nil }124        market.quotes["usd", default: [:]][id] = MarketCache.Entry(price: fetched.price, change24h: nil, change7d: nil, sparkline7d: [], fetchedAt: now())125        return fetched.price126    }127128    /// The second source's USD price of `id`, if it is fresh; fetched when the session has none. nil: no usable price.129    private func secondSourceUSDPrice(_ id: String) async -> Double? {130        if let known = priceChecks[id] {131            let age = now().timeIntervalSince(known.fetchedAt)132            if age <= Self.quoteFreshness, age >= -60 { return known.price }133            priceChecks[id] = nil134        }135        guard !gate.isOffline else { return nil }136        let client = PriceClient(configuration: profile.endpoints, transport: gate)137        guard let price = (try? await client.checkPrice(id: id)) ?? nil else { return nil }138        priceChecks[id] = PriceCheck(price: price, fetchedAt: now())139        return price140    }141142    /// The USD price a dollar ceiling of the asset `id` is checked with on an unaudited mainnet build, or a refusal143    /// (`unauditedLimitUnverifiable`). Called when a payment is prepared and again before it is signed.144    ///145    /// The ceiling is `units × price ≤ dollars`: a price that is too low allows more units, so every rule below errs146    /// towards the higher price or refuses.147    /// - `.dollarPegged`: one fresh quote of the first source; refused outside 0.50…2.00 USD; otherwise148    ///   `max(quote, 0.90)`.149    /// - `.twoSources`: a fresh quote of each source; refused when one of them has none, when they differ by more than150    ///   5 %, or when the agreed price is under the floor of a native coin; otherwise the higher of the two.151    /// A stale quote (older than `quoteFreshness`, read back from disk, or dated in the future) is never used.152    func limitUSDPrice(_ id: String, pricing: LimitPricing = .twoSources) async throws -> Double {153        let unknown = WalletError.unauditedLimitUnverifiable("No fresh price is available for this asset, so its value cannot be checked against the limit.")154        guard let first = await firstSourceUSDPrice(id) else { throw unknown }155        switch pricing {156        case .dollarPegged:157            guard let price = MainnetPolicy.stablecoinCeilingPrice(quote: first) else {158                throw WalletError.unauditedLimitUnverifiable("The price source gave a price out of the plausible range for a dollar-pegged token (0.50 to 2.00 USD), so the transfer cannot be checked against the limit.")159            }160            return price161        case .twoSources:162            guard let second = await secondSourceUSDPrice(id) else {163                throw WalletError.unauditedLimitUnverifiable("Only one price source gave a fresh price for this asset. Its price cannot be cross-checked, so its value cannot be checked against the limit.")164            }165            var agreement = MainnetPolicy.agreedCeilingPrice(first, second)166            if agreement == nil, !gate.isOffline {167                // the two quotes may have been read minutes apart: read both again, once, before refusing168                market.quotes["usd"]?[id] = nil169                priceChecks[id] = nil170                if let a = await firstSourceUSDPrice(id), let b = await secondSourceUSDPrice(id) { agreement = MainnetPolicy.agreedCeilingPrice(a, b) }171            }172            guard let agreed = agreement else {173                throw WalletError.unauditedLimitUnverifiable("The two price sources disagree on the price of this asset by more than \(Int(MainnetPolicy.priceAgreementTolerance * 100)) %, so its value cannot be checked against the limit.")174            }175            // a price under the floor of a native coin is no price: it would turn a dollar ceiling into any amount (QYV-SVC-082)176            guard MainnetPolicy.isPlausibleUSDPrice(agreed, priceID: id) else {177                throw WalletError.unauditedLimitUnverifiable("The price sources gave a price for this asset that is not plausible, so its value cannot be checked against the limit.")178            }179            return agreed180        }181    }182183    /// Quotes known right now, each with its date and stale flag. No network.184    public func marketSnapshot() -> MarketSnapshot {185        let currency = profile.displayCurrency186        var quotes = [String: MarketQuote]()187        for id in (market.quotes[currency.rawValue] ?? [:]).keys { if let q = quote(id, currency: currency) { quotes[id] = q } }188        var reason = marketError189        if reason == nil, profile.coldMode { reason = "Cold mode is on: prices are not fetched." }190        if reason == nil, profile.endpoints.priceAPI.isEmpty { reason = "No price source is configured." }191        if reason == nil, quotes.isEmpty { reason = "Prices have not been fetched yet." }192        if reason == nil, quotes.values.allSatisfy(\.isStale) { reason = "Prices are last known values and may be out of date." }193        return MarketSnapshot(currency: currency, quotes: quotes, unavailableReason: reason)194    }195196    /// Fetches, in one batched request, the quotes of the native coin of every active chain and of every listed token197    /// that has a price identifier, in the display currency. **Network.**198    /// On failure the last known quotes are kept (they turn stale with time) and the error is thrown.199    @discardableResult200    public func refreshMarket() async throws(WalletError) -> MarketSnapshot {201        try await run {202            if gate.isOffline { throw WalletError.offline }203            let currency = profile.displayCurrency204            let client = PriceClient(configuration: profile.endpoints, transport: gate)205            guard client.isConfigured else { throw WalletError.featureUnavailable("No price source is configured.") }206            let fetched: [String: PriceClient.Quote]207            do {208                fetched = try await client.quotes(ids: priceIDs(), currency: currency.rawValue)209            } catch {210                let wrapped = WalletError.wrap(error, now: now())211                marketError = "Prices are unavailable: " + Self.describe(wrapped)212                throw wrapped213            }214            let wanted = Set(priceIDs())215            let stamp = now()216            var accepted = 0217            for (id, q) in fetched where wanted.contains(id) {218                // bounds: a price is a finite, non-negative number of plausible size219                guard q.price.isFinite, q.price >= 0, q.price < 1e12 else { continue }220                func bounded(_ v: Double?) -> Double? { v.flatMap { $0.isFinite && abs($0) < 1e6 ? $0 : nil } }221                let spark = q.sparkline7d.count <= 400 ? q.sparkline7d.filter { $0.isFinite && $0 >= 0 && $0 < 1e12 } : []222                market.quotes[currency.rawValue, default: [:]][id] = MarketCache.Entry(223                    price: q.price, change24h: bounded(q.change24h), change7d: bounded(q.change7d), sparkline7d: spark, fetchedAt: stamp)224                accepted += 1225            }226            guard accepted > 0 else {227                marketError = "Prices are unavailable: the price source returned no usable quote."228                throw WalletError.untrustedResponse("no usable quote")229            }230            marketError = nil231            try? marketStore.save(market)232            emit(.marketUpdated)233            return marketSnapshot()234        }235    }236237    /// Price history of an asset ("bitcoin", "ethereum" or a token's `priceID`) in the display currency. **Network.**238    /// When the fetch fails and an earlier chart of this session exists, it is returned flagged stale; otherwise throws.239    public func priceChart(assetID: String, range: ChartRange) async throws(WalletError) -> PriceChart {240        try await run {241            let currency = profile.displayCurrency242            let key = "\(assetID)|\(currency.rawValue)|\(range.rawValue)"243            if let cached = charts[key], now().timeIntervalSince(cached.fetchedAt) < Self.quoteFreshness, now() >= cached.fetchedAt { return cached }244            func stale() -> PriceChart? {245                charts[key].map { PriceChart(assetID: $0.assetID, currency: $0.currency, range: $0.range, points: $0.points, fetchedAt: $0.fetchedAt, isStale: true) }246            }247            do {248                if gate.isOffline { throw WalletError.offline }249                let client = PriceClient(configuration: profile.endpoints, transport: gate)250                guard client.isConfigured else { throw WalletError.featureUnavailable("No price source is configured.") }251                let raw = try await client.chart(id: assetID, currency: currency.rawValue, days: range.days)252                let points = raw.filter { $0.price.isFinite && $0.price >= 0 && $0.price < 1e12 && $0.date.timeIntervalSince1970 > 1_230_000_000 }253                    .sorted { $0.date < $1.date }254                guard !points.isEmpty, points.count <= 20_000 else { throw WalletError.untrustedResponse("empty or oversized price history") }255                let chart = PriceChart(assetID: assetID, currency: currency, range: range, points: points, fetchedAt: now(), isStale: false)256                charts[key] = chart257                return chart258            } catch {259                if let old = stale() { return old }260                throw error261            }262        }263    }264265    /// Valuation of what the snapshots hold, at the quotes known now. No network.266    public func portfolioValuation() -> PortfolioValuation {267        let currency = profile.displayCurrency268        var lines = [ValuationLine]()269        var unpriced = [String]()270        var real: Double?, reference: Double?271        var stale = false272        var oldest: Date?273274        func add(chain: ChainID, id: String, symbol: String, name: String, amount: UInt256, decimals: Int, isTest: Bool, priceID: String?) {275            let text = BaseUnits.format(amount, decimals: decimals)276            let q = priceID.flatMap { quote($0, currency: currency) }277            var value: Double?278            if let q, let units = Double(text), units.isFinite {279                value = units * q.price280                stale = stale || q.isStale281                oldest = oldest.map { min($0, q.fetchedAt) } ?? q.fetchedAt282            } else if !amount.isZero {283                unpriced.append(symbol)284            }285            if let value {286                if isTest { reference = (reference ?? 0) + value } else { real = (real ?? 0) + value }287            }288            lines.append(ValuationLine(id: id, symbol: symbol, name: name, amount: text, isTestNetwork: isTest, value: isTest ? nil : value,289                                       referenceValue: isTest ? value : nil, price: q, chain: chain))290        }291292        var dates = [Date]()293        var previous = false294        for kind in Self.activeKinds(profile) {295            let descriptor = ChainRegistry.descriptor(kind)296            let data: ChainData?297            switch kind {298            case .utxo(let network):299                data = network == profile.bitcoinNetwork ? bitcoinSnapshot.map { Self.chainData($0) }300                    : (Self.isPrimaryUTXO(network) ? nil : utxoCoinStates[network]?.snapshot.map { Self.chainData($0) })301            case .evm(let network): data = evmSnapshots[network].map { Self.chainData($0) }302            case .solana(let network): data = solanaRecords[network].map { Self.chainData($0) }303            case .tron(let network): data = tronRecords[network].map { Self.chainData($0) }304            }305            guard let data else { continue }306            dates.append(data.synchronizedAt)307            previous = previous || data.isFromPreviousSession308            // the two primary chains keep the line identifiers of 1.0309            var nativeID = descriptor.id.rawValue310            if kind == .utxo(profile.bitcoinNetwork) { nativeID = "btc" }311            if kind == .evm(profile.ethereumNetwork) { nativeID = "eth" }312            add(chain: descriptor.id, id: nativeID, symbol: descriptor.nativeSymbol, name: descriptor.displayName, amount: data.native.total,313                decimals: descriptor.nativeDecimals, isTest: descriptor.isTest, priceID: descriptor.priceID)314            for t in data.tokens {315                guard case .available(let balance) = t.balance, !balance.isZero else { continue }316                var id = t.token.id317                if case .evm(let network) = kind { id = "\(network.rawValue):\(t.token.address)" }318                add(chain: descriptor.id, id: id, symbol: t.token.symbol, name: t.token.name, amount: balance, decimals: t.token.decimals, isTest: descriptor.isTest,319                    priceID: t.token.priceID)320            }321        }322        var chains = [ChainValuation]()323        for kind in Self.activeKinds(profile) {324            let id = ChainRegistry.id(kind)325            let own = lines.filter { $0.chain == id }326            guard !own.isEmpty else { continue }327            let real = own.compactMap(\.value), reference = own.compactMap(\.referenceValue)328            chains.append(ChainValuation(chain: id, realValue: real.isEmpty ? nil : real.reduce(0, +), referenceValue: reference.isEmpty ? nil : reference.reduce(0, +)))329        }330        return PortfolioValuation(currency: currency, lines: lines, realValue: real, referenceValue: reference,331                                  isTestNetwork: lines.contains(where: \.isTestNetwork), isStale: stale, pricedAt: oldest, unpricedAssets: unpriced,332                                  isFromPreviousSession: previous, balancesAsOf: dates.min(), chains: chains)333    }334335    // MARK: Dashboard336337    /// Everything a dashboard renders, in one value. No network, no secret; works while the vault is locked.338    public func snapshot() async -> WalletSnapshot {339        var receive: String?340        if profile.kind != nil, let a = try? await nextReceiveAddress() { receive = a.address }341        func state<T>(_ value: T?, _ error: String?, _ has: Bool) -> Availability<T> {342            if let value { return .available(value) }343            if let error { return .unavailable(reason: error) }344            if !has { return .unavailable(reason: "This wallet has no account on this chain.") }345            return .notLoaded346        }347        let hasBitcoin = profile.bitcoinAccounts[WalletProfile.coinKey(profile.bitcoinNetwork)] != nil348        return WalletSnapshot(349            profile: profile, hasWallet: profile.kind != nil, vault: await vaultStatus(), mainnetEnabled: MainnetPolicy.mainnetEnabled,350            mainnetAvailable: MainnetPolicy.mainnetAvailable,351            isMainnet: Self.activeKinds(profile).contains { !$0.isTest } || !profile.bitcoinNetwork.isTest || !profile.ethereumNetwork.isTest,352            unauditedMainnet: MainnetPolicy.unauditedMainnet, unauditedLimits: MainnetPolicy.limits,353            bitcoin: state(bitcoinSnapshot, bitcoinError, hasBitcoin), ethereum: state(ethereumSnapshot, ethereumError, profile.ethereumAddress != nil),354            bitcoinSyncError: bitcoinError, ethereumSyncError: ethereumError,355            isSynchronizingBitcoin: bitcoinSyncTask != nil, isSynchronizingEthereum: evmSyncTasks[profile.ethereumNetwork] != nil,356            bitcoinReceiveAddress: receive,357            market: marketSnapshot(), valuation: portfolioValuation(), chains: await chainSnapshots(), networkMode: profile.networkMode)358    }359}360
Files main
Menu

Theme