SPB Git

Repository Public

WalletStore.swift 12.6 KB 281 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/WalletStore.swift8// Module           : Sources9// 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 QyvoraBitcoin44import QyvoraNetworking45import QyvoraStorage46import QyvoraVault47import QyvoraWallet4849/// The application's single connection to the wallet service: it owns the `WalletService` actor,50/// republishes its snapshot for SwiftUI and funnels every call through `run` so that activity,51/// errors and refreshes are handled in one place. Screens never keep wallet state of their own.52@MainActor53@Observable54final class WalletStore {55    /// nil when the service could not be created (storage unavailable); `startupError` then says why.56    let service: WalletService?57    private(set) var startupError: String?58    /// Latest aggregate state. nil until the first refresh.59    private(set) var snapshot: WalletSnapshot?60    /// Where a running synchronization stands, with the real counts reported by the service.61    struct SyncProgress: Equatable, Sendable {62        var stage: String63        var completed: Int64        var total: Int?6566        /// "Scanning receive addresses · 12 of 40", or the stage alone while no count is known.67        var text: String {68            if let total, total > 0 { return "\(stage) · \(completed) of \(total)" }69            return completed > 0 ? "\(stage) · \(completed)" : stage70        }71    }7273    /// Latest progress of each chain while it synchronizes; nil when that chain is not synchronizing. The two chains74    /// run at the same time, so each keeps its own.75    private(set) var bitcoinProgress: SyncProgress?76    private(set) var ethereumProgress: SyncProgress?77    /// Progress of every chain that is synchronizing now, by chain identifier (real counts from the service).78    private(set) var chainProgress: [ChainID: SyncProgress] = [:]79    /// Outcome of the last synchronization of each chain in this session, as the service reports it: nil error on80    /// success, the reason otherwise. A chain without entry has not been synchronized since the launch.81    private(set) var chainResults: [ChainID: ChainSyncResult] = [:]82    /// Chains whose synchronization was asked for and has not ended yet (the service runs a few at a time, so a83    /// chain can be waiting for its turn before its first event).84    private(set) var queuedChains: Set<ChainID> = []85    /// True while `synchronize()` runs for the whole wallet.86    private(set) var isSynchronizingAll = false87    private var didAutoSynchronize = false88    private var eventTask: Task<Void, Never>?8990    /// True when this build declares `QYInternalMainnet` in its Info.plist (internal TestFlight builds).91    static var internalBuildAllowsMainnet: Bool {92        Bundle.main.object(forInfoDictionaryKey: "QYInternalMainnet") as? Bool ?? false93    }9495    init() {96        do {97            let files = try FileStore.applicationSupport()98            let keychain = SystemKeychainStore()99            let vault = Vault(fileStore: files, keychain: keychain, secureEnclave: SystemSecureEnclaveKey(keychain: keychain))100            service = try WalletService(vault: vault, fileStore: files, transport: URLSessionTransport(),101                                        internalBuildAllowsMainnet: Self.internalBuildAllowsMainnet)102        } catch {103            service = nil104            startupError = WalletMessages.text(for: error)105        }106    }107108    /// Starts listening to service events and loads the first snapshot. Call once from the root view.109    func start() {110        guard eventTask == nil, let service else { return }111        eventTask = Task { [weak self] in112            await self?.refresh()113            for await event in await service.events() {114                guard let self else { return }115                await self.handle(event)116            }117        }118    }119120    func progress(of chain: WalletChain) -> SyncProgress? {121        chain == .bitcoin ? bitcoinProgress : ethereumProgress122    }123124    private func setProgress(_ progress: SyncProgress?, for chain: WalletChain) {125        switch chain {126        case .bitcoin: bitcoinProgress = progress127        case .ethereum: ethereumProgress = progress128        }129    }130131    /// Progress events only move the progress of their chain (a busy account emits one per address and per history132    /// page); every other event changes the state and reloads the snapshot. The two primary chains send both the 1.0133    /// events and the per-chain ones: the snapshot is reloaded once, on the per-chain event.134    private func handle(_ event: WalletEvent) async {135        switch event {136        case .syncProgress(let chain, let stage, let completed, let total):137            setProgress(SyncProgress(stage: stage, completed: completed, total: total), for: chain)138        case .syncStarted(let chain):139            setProgress(SyncProgress(stage: "Connecting", completed: 0, total: nil), for: chain)140        case .syncFinished(let chain), .syncFailed(let chain, _):141            setProgress(nil, for: chain)142        case .chainSyncProgress(let id, let stage, let completed, let total):143            chainProgress[id] = SyncProgress(stage: stage, completed: completed, total: total)144        case .chainSyncStarted(let id):145            chainProgress[id] = SyncProgress(stage: "Connecting", completed: 0, total: nil)146            await refresh()147        case .chainSyncFinished(let id):148            chainProgress[id] = nil149            queuedChains.remove(id)150            chainResults[id] = ChainSyncResult(chain: id)151            await refresh()152        case .chainSyncFailed(let id, let reason):153            chainProgress[id] = nil154            queuedChains.remove(id)155            chainResults[id] = ChainSyncResult(chain: id, error: reason)156            await refresh()157        case .walletCreated, .walletDeleted:158            didAutoSynchronize = false159            chainProgress = [:]160            chainResults = [:]161            queuedChains = []162            await refresh()163        default:164            await refresh()165        }166    }167168    /// The measured fraction of a chain's synchronization, when the service reports a total; nil otherwise.169    func syncFraction(of chain: ChainID) -> Double? {170        guard let p = chainProgress[chain], let total = p.total, total > 0 else { return nil }171        return min(1, max(0, Double(p.completed) / Double(total)))172    }173174    func refresh() async {175        guard let service else { return }176        snapshot = await service.snapshot()177    }178179    /// Runs one service call: records user activity (auto-lock timer), executes, refreshes the snapshot.180    /// Errors are rethrown as `WalletError` for the calling screen to present next to the action.181    @discardableResult182    func run<T: Sendable>(_ operation: @Sendable (WalletService) async throws -> T) async throws -> T {183        guard let service else { throw WalletError.storage(startupError ?? "wallet storage is unavailable") }184        await service.noteActivity()185        defer { Task { await self.refresh() } }186        return try await operation(service)187    }188189    /// Synchronizes every active chain and the market data; failures are reported per chain in the snapshot190    /// (`ChainSnapshot.syncError`) and in `chainResults`, never thrown.191    /// Every screen synchronizes through the store (this method or `synchronize(chains:)`), never through the service:192    /// the queue, the progress and the results are then the same wherever they are shown.193    func synchronize() async {194        guard let service, snapshot?.hasWallet == true, snapshot?.profile.coldMode != true else { return }195        if isSynchronizingAll {196            // a whole-wallet synchronization is running: add only what it does not cover (a chain enabled or a197            // network mode changed since it started)198            let missing = await service.activeChains().map(\.id).filter { !queuedChains.contains($0) }199            await synchronize(chains: missing)200            return201        }202        isSynchronizingAll = true203        defer { isSynchronizingAll = false }204        await service.noteActivity()205        queuedChains.formUnion(await service.activeChains().map(\.id))206        async let chains = service.synchronize(chains: nil)207        async let market: Void = { _ = try? await service.refreshMarket() }()208        let (results, _) = await (chains, market)209        record(results)210        await refresh()211    }212213    /// Synchronizes some chains only (retry of a failed chain, refresh of a chain's screen). The market data is214    /// left as it is.215    func synchronize(chains: [ChainID]) async {216        guard let service, snapshot?.hasWallet == true, snapshot?.profile.coldMode != true, !chains.isEmpty else { return }217        await service.noteActivity()218        queuedChains.formUnion(chains)219        record(await service.synchronize(chains: chains))220        await refresh()221    }222223    /// Fetches the quotes again without touching the chains.224    func refreshMarket() async {225        guard let service, snapshot?.profile.coldMode != true else { return }226        _ = try? await service.refreshMarket()227        await refresh()228    }229230    /// The automatic synchronization of a launch: once, when a chain has no reading of this session (nothing loaded,231    /// or only the state restored from the previous session). Later refreshes are the user's.232    func synchronizeOnceIfNeeded() async {233        guard !didAutoSynchronize, let snapshot, snapshot.hasWallet else { return }234        didAutoSynchronize = true235        let unread = snapshot.chains.contains { chain in236            guard !chain.isSynchronizing else { return false }237            return chain.data.value.map(\.isFromPreviousSession) ?? true238        }239        if unread { await synchronize() }240    }241242    /// Synchronizes the active chains that have no data at all (chains the user has just enabled).243    func synchronizeUnreadChains() async {244        await refresh()245        guard let snapshot else { return }246        let unread = snapshot.chains.filter { chain in chain.data.value == nil && !chain.isSynchronizing && chain.syncError == nil }.map(\.id)247        guard !unread.isEmpty else { return }248        async let market: Void = refreshMarket()249        async let chains: Void = synchronize(chains: unread)250        _ = await (market, chains)251    }252253    private func record(_ results: [ChainSyncResult]) {254        for result in results {255            chainResults[result.chain] = result256            queuedChains.remove(result.chain)257            chainProgress[result.chain] = nil258        }259    }260261    /// Locks the vault when the auto-lock policy says so. Returns true when it locked.262    func autoLockIfNeeded() async -> Bool {263        guard let service else { return false }264        let locked = (try? await service.autoLockIfNeeded()) ?? false265        if locked { await refresh() }266        return locked267    }268269    func lock() async {270        guard let service else { return }271        await service.lock()272        await refresh()273    }274275    /// A plain English sentence for any error, suitable for an inline message. The sentences live in the service276    /// (`WalletMessages`), in one place for the wallet and the security screens: nothing here interpolates an error.277    static func message(for error: Error) -> String {278        WalletMessages.text(for: error)279    }280}281
Files main
Menu

Theme