SPB Git

Repository Public

WalletService+Chains.swift 43.3 KB 776 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraWallet/WalletService+Chains.swift8// Module           : Qyvora 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 Foundation42import QyvoraMath43import QyvoraCore44import QyvoraBitcoin45import QyvoraEthereum46import QyvoraNetworking47import QyvoraVault48import QyvoraSolana49import QyvoraTron5051/// Every endpoint of every chain, as one user-editable value.52public struct ChainEndpoints: Codable, Equatable, Sendable {53    /// UTXO indexers, EVM JSON-RPC and indexers, price API.54    public var core: EndpointConfiguration55    public var solana: SolanaEndpoints56    public var tron: TronEndpoints5758    public static let `default` = ChainEndpoints(core: .default, solana: .default, tron: .default)5960    public init(core: EndpointConfiguration, solana: SolanaEndpoints, tron: TronEndpoints) {61        self.core = core62        self.solana = solana63        self.tron = tron64    }65}6667/// Outcome of the synchronization of one chain.68public struct ChainSyncResult: Equatable, Sendable, Identifiable {69    public let chain: ChainID70    /// nil on success; otherwise the reason, ready to display.71    public let error: String?72    public var id: ChainID { chain }73    public var succeeded: Bool { error == nil }7475    /// For whoever keeps the outcomes it hears through `WalletEvent` in the same form as those `synchronize` returns.76    public init(chain: ChainID, error: String? = nil) {77        self.chain = chain78        self.error = error79    }80}8182extension WalletService {83    // MARK: Which networks are active8485    /// True for the networks of Bitcoin itself: `profile.bitcoinNetwork` chooses among them.86    static func isPrimaryUTXO(_ network: BitcoinNetwork) -> Bool { network.coin == .bitcoin }8788    /// The test network a chain uses in test mode: the user's choice when valid, else the default.89    static func chosenTestKind(main: ChainID, profile: WalletProfile) -> ChainKind? {90        guard let descriptor = ChainRegistry.descriptor(main) else { return nil }91        let chosen = profile.testNetworks[main.rawValue].flatMap { descriptor.testCounterparts.contains($0) ? $0 : nil } ?? descriptor.testCounterparts.first92        return chosen.flatMap(ChainRegistry.kind)93    }9495    /// The test network that takes the place of a Bitcoin main network when mainnet is not allowed.96    static func testNetwork(of network: BitcoinNetwork, profile: WalletProfile) -> BitcoinNetwork {97        if case .utxo(let n)? = chosenTestKind(main: ChainRegistry.id(network.mainCounterpart), profile: profile) { return n }98        return network.testCounterpart99    }100101    /// The network of each enabled chain, in display order. Bitcoin uses the primary Bitcoin network and the chain of102    /// the primary EVM network uses that network (the 1.0 setters move them); every other chain follows the network103    /// mode. A main network is never returned while mainnet is not enabled.104    static func activeKinds(_ profile: WalletProfile) -> [ChainKind] {105        var out = [ChainKind]()106        for descriptor in ChainRegistry.mainChains where profile.enabledChains.contains(descriptor.id) {107            let kind: ChainKind?108            switch descriptor.kind {109            case .utxo(let n) where isPrimaryUTXO(n): kind = .utxo(profile.bitcoinNetwork)110            case .evm(let n) where n.family == profile.ethereumNetwork.family: kind = .evm(profile.ethereumNetwork)111            default: kind = profile.networkMode == .main ? descriptor.kind : chosenTestKind(main: descriptor.id, profile: profile)112            }113            if let kind, kind.isTest || MainnetPolicy.mainnetEnabled { out.append(kind) }114        }115        return out116    }117118    func isPrimary(_ kind: ChainKind) -> Bool { kind == .utxo(profile.bitcoinNetwork) || kind == .evm(profile.ethereumNetwork) }119120    /// The active network named by `id`. Throws `unknownChain`, or `chainNotActive` when the chain is not enabled or the121    /// other network of the chain is the active one.122    func activeKind(_ id: ChainID) throws -> ChainKind {123        guard let kind = ChainRegistry.kind(id) else { throw WalletError.unknownChain(id.rawValue) }124        try requireAllowed(kind)125        guard Self.activeKinds(profile).contains(kind) || isPrimary(kind) else {126            throw WalletError.chainNotActive(ChainRegistry.descriptor(kind).displayName)127        }128        return kind129    }130131    /// Moves every chain to its main or its test network. The primary networks follow.132    func applyNetworkMode(_ mode: NetworkMode) {133        profile.networkMode = mode134        let bitcoin = mode == .main ? profile.bitcoinNetwork.mainCounterpart : Self.testNetwork(of: profile.bitcoinNetwork, profile: profile)135        if bitcoin != profile.bitcoinNetwork {136            profile.bitcoinNetwork = bitcoin137            bitcoinSnapshot = nil138            bitcoinError = nil139            paidScripts = []140            locallySpent = []141            forgetBitcoinSynchronization()142        }143        let evm = mode == .main ? profile.ethereumNetwork.mainCounterpart : profile.ethereumNetwork.testCounterpart144        if evm != profile.ethereumNetwork {145            forgetEVMSynchronization(profile.ethereumNetwork)146            profile.ethereumNetwork = evm147        }148        reconcileChainState()149    }150151    // MARK: Chains, mode, test networks (public)152153    /// Every network QYVORA supports (static data; the same as `ChainRegistry.all`).154    public nonisolated func supportedChains() -> [ChainDescriptor] { ChainRegistry.all }155156    /// The networks the wallet works on now, in display order.157    public func activeChains() -> [ChainDescriptor] { Self.activeKinds(profile).map(ChainRegistry.descriptor) }158159    /// Shows or hides a chain. `chain` is a main-network identifier (`ChainDescriptor.mainCounterpart`); a test160    /// identifier is accepted and means its chain. At least one chain stays enabled. No network, no secret.161    /// A watch-only wallet can only enable a chain it has an account for.162    public func setChainEnabled(_ chain: ChainID, enabled: Bool) async throws(WalletError) {163        try await run {164            guard let descriptor = ChainRegistry.descriptor(chain) else { throw WalletError.unknownChain(chain.rawValue) }165            var set = profile.enabledChains166            let main = descriptor.mainCounterpart167            if enabled {168                if !set.contains(main) { set.append(main) }169            } else {170                set.removeAll { $0 == main }171            }172            try applyEnabledChains(set)173        }174    }175176    /// Replaces the list of enabled chains (main-network identifiers; order is ignored, the registry order is used).177    /// Returns the chains that were left out, in registry order: on a watch-only wallet, the chains it has no account178    /// for (the others are enabled; the call fails only when none of the wanted chains has an account). Always empty179    /// on a full wallet.180    @discardableResult181    public func setEnabledChains(_ chains: [ChainID]) async throws(WalletError) -> [ChainID] {182        try await run {183            var mains = [ChainID]()184            for id in chains {185                guard let descriptor = ChainRegistry.descriptor(id) else { throw WalletError.unknownChain(id.rawValue) }186                if !mains.contains(descriptor.mainCounterpart) { mains.append(descriptor.mainCounterpart) }187            }188            // a watch-only wallet imported for some families only: the chains it has no account for are left out189            // and named, instead of refusing the whole list190            var skipped = [ChainID]()191            if profile.kind == .watchOnly {192                skipped = mains.filter { id in193                    guard !profile.enabledChains.contains(id), let descriptor = ChainRegistry.descriptor(id) else { return false }194                    return !hasAccount(descriptor.kind)195                }196                mains.removeAll { skipped.contains($0) }197                if mains.isEmpty, !skipped.isEmpty {198                    let names = ChainRegistry.mainChains.filter { skipped.contains($0.id) }.map(\.displayName).joined(separator: ", ")199                    throw WalletError.featureUnavailable("This watch-only wallet has no account for \(names).")200                }201            }202            try applyEnabledChains(mains)203            return ChainRegistry.mainChains.map(\.id).filter { skipped.contains($0) }204        }205    }206207    private func applyEnabledChains(_ wanted: [ChainID]) throws {208        let ordered = ChainRegistry.mainChains.map(\.id).filter { wanted.contains($0) }209        guard !ordered.isEmpty else { throw WalletError.invalidInput("At least one chain must stay enabled.") }210        if profile.kind == .watchOnly {211            for id in ordered where !profile.enabledChains.contains(id) {212                guard let descriptor = ChainRegistry.descriptor(id), hasAccount(descriptor.kind) else {213                    throw WalletError.featureUnavailable("This watch-only wallet has no account for \(ChainRegistry.descriptor(id)?.displayName ?? id.rawValue).")214                }215            }216        }217        guard ordered != profile.enabledChains else { return }218        profile.enabledChains = ordered219        // the primary EVM network stays on an enabled chain when there is one220        let evmChains = ordered.compactMap { id -> EthereumNetwork? in221            if case .evm(let n)? = ChainRegistry.kind(id) { return n }222            return nil223        }224        if !evmChains.contains(where: { $0.family == profile.ethereumNetwork.family }), let first = evmChains.first {225            let next = profile.networkMode == .main && MainnetPolicy.mainnetEnabled ? first.mainCounterpart : first.testCounterpart226            profile.ethereumNetwork = next227        }228        reconcileChainState()229        try saveProfile()230    }231232    /// Switches every enabled chain between its test network and its main network. `.main` throws `mainnetDisabled`233    /// unless `MainnetPolicy.mainnetEnabled` (an internal build that declares mainnet testing AND the user's opt-in);234    /// with a full wallet it also needs a fresh authentication. Balances of the networks left are no longer shown.235    public func setNetworkMode(_ mode: NetworkMode) async throws(WalletError) {236        try await run {237            if mode == .main {238                guard MainnetPolicy.mainnetEnabled else { throw WalletError.mainnetDisabled(WalletError.mainnetText) }239                // any chain that leaves a test network makes this a switch, whatever the stored mode says (QYV-SVC-080)240                if profile.networkMode != .main || profile.bitcoinNetwork.isTest || profile.ethereumNetwork.isTest { try await requireFreshAuthentication() }241            }242            let consistent = profile.networkMode == mode && profile.bitcoinNetwork.isTest == (mode == .test) && profile.ethereumNetwork.isTest == (mode == .test)243            guard !consistent else { return }244            applyNetworkMode(mode)245            try saveProfile()246        }247    }248249    /// Chooses the test network of a chain that has several: `.bitcoinSignet` or `.bitcoinTestnet`, `.solanaDevnet`250    /// or `.solanaTestnet`, `.tronNile` or `.tronShasta`. Takes effect at once in test mode. No network, no secret.251    public func setTestNetwork(_ test: ChainID) async throws(WalletError) {252        try await run {253            guard let descriptor = ChainRegistry.descriptor(test) else { throw WalletError.unknownChain(test.rawValue) }254            guard descriptor.isTest else { throw WalletError.invalidInput("\(descriptor.displayName) is not a test network.") }255            let main = descriptor.mainCounterpart256            guard profile.testNetworks[main.rawValue] != test || !Self.activeKinds(profile).contains(descriptor.kind) else { return }257            profile.testNetworks[main.rawValue] = test258            if case .utxo(let network) = descriptor.kind, Self.isPrimaryUTXO(network), profile.bitcoinNetwork.isTest, profile.bitcoinNetwork != network {259                profile.bitcoinNetwork = network260                bitcoinSnapshot = nil261                bitcoinError = nil262                paidScripts = []263                locallySpent = []264                forgetBitcoinSynchronization()265            }266            reconcileChainState()267            try saveProfile()268        }269    }270271    /// True when the wallet has an account of the family of `kind`.272    func hasAccount(_ kind: ChainKind) -> Bool {273        switch kind {274        case .utxo(let n): return profile.bitcoinAccounts[Self.accountKey(n)] != nil275        case .evm: return profile.ethereumAddress != nil276        case .solana: return profile.solanaAddress != nil277        case .tron: return profile.tronAddress != nil278        }279    }280281    /// Key of a UTXO account in `WalletProfile.bitcoinAccounts`.282    static func accountKey(_ network: BitcoinNetwork) -> String {283        isPrimaryUTXO(network) ? WalletProfile.coinKey(network) : network.rawValue284    }285286    // MARK: Endpoints287288    /// The endpoints of every chain.289    public func chainEndpoints() -> ChainEndpoints {290        ChainEndpoints(core: profile.endpoints, solana: profile.solanaEndpoints, tron: profile.tronEndpoints)291    }292293    /// Replaces the endpoints of every chain. Every URL must pass `EndpointConfiguration.isAcceptable` (https, or http294    /// to a local host), every key must be a network name. With a full wallet this needs a fresh authentication.295    /// Chain identity is checked again on next use; what was persisted for a chain whose endpoints changed is forgotten.296    public func setChainEndpoints(_ endpoints: ChainEndpoints) async throws(WalletError) {297        try await run { try await applyEndpoints(core: endpoints.core, solana: endpoints.solana, tron: endpoints.tron) }298    }299300    static let tronKeyFormat = "qyvora-trongrid-key"301302    private struct StoredTronKey: Codable {303        var format = WalletService.tronKeyFormat304        var key: String305    }306307    private func tronKeyRecord() async throws -> (id: UUID, key: String)? {308        for record in try await vault.records(ofType: .setting) where record.payload.count <= 512 {309            guard let stored = try? JSONDecoder().decode(StoredTronKey.self, from: Data(record.payload)), stored.format == Self.tronKeyFormat else { continue }310            return (record.id, stored.key)311        }312        return nil313    }314315    /// Stores (or, with nil or an empty text, removes) a TronGrid API key. The key lives in the vault only: never in the316    /// profile, never in a log, and it is sent to TronGrid hosts over https only. **Needs an unlocked vault (full317    /// wallet) and a fresh authentication.** A watch-only wallet has no vault: `featureUnavailable`.318    public func setTronAPIKey(_ key: String?) async throws(WalletError) {319        try await run {320            guard try requireWallet() == .full else { throw WalletError.featureUnavailable("A watch-only wallet has no vault to keep an API key in.") }321            guard await vault.isUnlocked else { throw WalletError.vaultLocked }322            try await requireFreshAuthentication()323            let text = key?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""324            let existing = try await tronKeyRecord()325            if text.isEmpty {326                if let existing { try await vault.deleteRecord(existing.id) }327                tronAPIKey = nil328                profile.hasTronAPIKey = false329            } else {330                guard let parsed = TronAPIKey(text) else { throw WalletError.invalidInput("This is not a TronGrid API key.") }331                var payload = Bytes((try? JSONEncoder().encode(StoredTronKey(key: text))) ?? Data())332                defer { SecureMemory.zero(&payload) }333                if let existing {334                    try await vault.updateRecord(existing.id, payload: payload)335                } else {336                    try await vault.addRecord(type: .setting, payload: payload)337                }338                tronAPIKey = parsed339                profile.hasTronAPIKey = true340            }341            try saveProfile()342        }343    }344345    /// Reads the TronGrid key from the vault after an unlock. Failures leave the wallet without a key (keyless access).346    func loadTronAPIKey() async {347        guard profile.kind == .full, await vault.isUnlocked else { return }348        let stored = (try? await tronKeyRecord())?.key349        tronAPIKey = stored.flatMap { TronAPIKey($0) }350        if profile.hasTronAPIKey != (tronAPIKey != nil) {351            profile.hasTronAPIKey = tronAPIKey != nil352            try? saveProfile()353        }354    }355356    // MARK: Events and progress357358    static func paidKey(_ kind: ChainKind, _ address: String) -> String { "\(ChainRegistry.id(kind).rawValue)|\(address)" }359360    private func legacyChain(_ kind: ChainKind) -> WalletChain? {361        guard isPrimary(kind) else { return nil }362        if case .evm = kind { return .ethereum }363        return nil   // Bitcoin sends the 1.0 events itself; `emit` mirrors them as chain events364    }365366    func noteSyncStarted(_ kind: ChainKind) {367        let id = ChainRegistry.id(kind)368        chainProgress[id] = nil369        emit(.chainSyncStarted(id))370        if let legacy = legacyChain(kind) { emit(.syncStarted(legacy)) }371    }372373    func noteProgress(_ kind: ChainKind, stage: String, completed: Int, total: Int?) {374        let id = ChainRegistry.id(kind)375        chainProgress[id] = ChainSyncProgress(stage: stage, completed: completed, total: total)376        emit(.chainSyncProgress(id, stage: stage, completed: completed, total: total))377        if let legacy = legacyChain(kind) { emit(.syncProgress(legacy, stage: stage, completed: completed, total: total)) }378    }379380    func noteSyncFinished(_ kind: ChainKind) {381        let id = ChainRegistry.id(kind)382        chainProgress[id] = nil383        emit(.chainSyncFinished(id))384        if let legacy = legacyChain(kind) { emit(.syncFinished(legacy)) }385    }386387    func noteSyncFailed(_ kind: ChainKind, reason: String) {388        let id = ChainRegistry.id(kind)389        chainProgress[id] = nil390        emit(.chainSyncFailed(id, reason: reason))391        if let legacy = legacyChain(kind) { emit(.syncFailed(legacy, reason: reason)) }392    }393394    func noteBroadcast(_ kind: ChainKind, id transaction: String) {395        emit(.chainTransactionBroadcast(ChainRegistry.id(kind), id: transaction))396        if isPrimary(kind), case .evm = kind { emit(.transactionBroadcast(.ethereum, id: transaction)) }397    }398399    /// The per-chain form of an event the Bitcoin code sends in its 1.0 form.400    func chainEvent(mirroring event: WalletEvent) -> WalletEvent? {401        let id = ChainRegistry.id(profile.bitcoinNetwork)402        switch event {403        case .syncStarted(.bitcoin): return .chainSyncStarted(id)404        case .syncProgress(.bitcoin, let stage, let completed, let total): return .chainSyncProgress(id, stage: stage, completed: completed, total: total)405        case .syncFinished(.bitcoin): return .chainSyncFinished(id)406        case .syncFailed(.bitcoin, let reason): return .chainSyncFailed(id, reason: reason)407        case .transactionBroadcast(.bitcoin, let transaction): return .chainTransactionBroadcast(id, id: transaction)408        default: return nil409        }410    }411412    // MARK: Synchronization413414    /// Chains synchronized at the same time at most. Each chain runs its own requests through the shared transport,415    /// which bounds the requests in flight and spaces them per host.416    static let chainSyncParallelism = 3417418    /// Synchronizes several chains (every active chain when `chains` is nil), a few at a time. **Network.**419    ///420    /// One chain failing never stops the others: the result lists every chain with its error, and each failure is421    /// also kept in the chain's snapshot (`ChainSnapshot.syncError`). For each chain the identity of the endpoints is422    /// verified once per session (genesis block or chain identifier) before anything they say is used. Progress is423    /// reported per chain through `events()`. In cold mode every chain fails with the cold-mode sentence and no424    /// request leaves the device.425    @discardableResult426    public func synchronize(chains: [ChainID]? = nil) async -> [ChainSyncResult] {427        let wanted = chains ?? Self.activeKinds(profile).map { ChainRegistry.id($0) }428        var seen = Set<ChainID>()429        let list = wanted.filter { seen.insert($0).inserted }430        guard !list.isEmpty else { return [] }431        return await withTaskGroup(of: (Int, ChainSyncResult).self) { group in432            var results = [ChainSyncResult?](repeating: nil, count: list.count)433            var next = 0434            func add(_ group: inout TaskGroup<(Int, ChainSyncResult)>) {435                let index = next436                let id = list[index]437                next += 1438                group.addTask {439                    do {440                        try await self.synchronize(chain: id)441                        return (index, ChainSyncResult(chain: id, error: nil))442                    } catch {443                        return (index, ChainSyncResult(chain: id, error: WalletMessages.text(for: error)))444                    }445                }446            }447            while next < min(Self.chainSyncParallelism, list.count) { add(&group) }448            while let (index, result) = await group.next() {449                results[index] = result450                if next < list.count { add(&group) }451            }452            return results.compactMap { $0 }453        }454    }455456    /// Synchronizes one active chain. **Network.** Errors: `unknownChain`, `chainNotActive`, `mainnetDisabled`,457    /// `offline`, `wrongChain`, `untrustedResponse`, `network`, `featureUnavailable` (no account of that family).458    public func synchronize(chain id: ChainID) async throws(WalletError) {459        try await run {460            switch try activeKind(id) {461            case .utxo(let network):462                if Self.isPrimaryUTXO(network) {463                    guard network == profile.bitcoinNetwork else { throw WalletError.chainNotActive(network.displayName) }464                    _ = try await syncBitcoin()465                } else {466                    _ = try await syncUTXOCoin(network)467                }468            case .evm(let network): _ = try await syncEVM(network)469            case .solana(let network): try await syncSolana(network)470            case .tron(let network): try await syncTron(network)471            }472        }473    }474475    /// Runs one synchronization of a Solana or TRON network; a concurrent call joins the running one.476    func runChainSync(_ kind: ChainKind, _ work: @escaping @Sendable () async throws -> Void) async throws {477        let id = ChainRegistry.id(kind)478        if let running = chainSyncTasks[id] { return try await running.value }479        let task = Task { try await work() }480        chainSyncTasks[id] = task481        noteSyncStarted(kind)482        do {483            try await task.value484            chainSyncTasks[id] = nil485            chainErrors[id] = nil486            noteSyncFinished(kind)487        } catch {488            chainSyncTasks[id] = nil489            let wrapped = WalletError.wrap(error, now: now())490            let reason = Self.describe(wrapped)491            chainErrors[id] = reason492            noteSyncFailed(kind, reason: reason)493            throw wrapped494        }495    }496497    // MARK: Snapshots498499    /// The snapshot of every active chain, in display order. No network, no secret; works while the vault is locked.500    public func chainSnapshots() async -> [ChainSnapshot] {501        var out = [ChainSnapshot]()502        for kind in Self.activeKinds(profile) { out.append(await chainSnapshot(kind)) }503        return out504    }505506    /// The snapshot of one active chain; nil when it is not active.507    public func chainSnapshot(_ id: ChainID) async -> ChainSnapshot? {508        guard let kind = ChainRegistry.kind(id), Self.activeKinds(profile).contains(kind) || isPrimary(kind) else { return nil }509        return await chainSnapshot(kind)510    }511512    func chainSnapshot(_ kind: ChainKind) async -> ChainSnapshot {513        let descriptor = ChainRegistry.descriptor(kind)514        let id = descriptor.id515        var data: ChainData?516        var error: String?517        var synchronizing = false518        var progress = chainProgress[id]519        var address: String?520        switch kind {521        case .utxo(let network):522            if network == profile.bitcoinNetwork {523                data = bitcoinSnapshot.map { Self.chainData($0) }524                error = bitcoinError525                synchronizing = bitcoinSyncTask != nil526                if let p = bitcoinProgress { progress = ChainSyncProgress(stage: p.stage, completed: p.completed, total: p.total) }527            } else if !Self.isPrimaryUTXO(network) {528                let state = utxoCoinStates[network]529                data = state?.snapshot.map { Self.chainData($0) }530                error = state?.error531                synchronizing = utxoCoinSyncTasks[network] != nil532            }533        case .evm(let network):534            address = profile.ethereumAddress?.checksummed535            data = evmSnapshots[network].map { Self.chainData($0) }536            error = evmErrors[network]537            synchronizing = evmSyncTasks[network] != nil538        case .solana(let network):539            address = profile.solanaAddress540            data = solanaRecords[network].map { Self.chainData($0) }541            error = chainErrors[id]542            synchronizing = chainSyncTasks[id] != nil543        case .tron(let network):544            address = profile.tronAddress545            data = tronRecords[network].map { Self.chainData($0) }546            error = chainErrors[id]547            synchronizing = chainSyncTasks[id] != nil548        }549        let state: Availability<ChainData>550        if let data {551            state = .available(data)552        } else if let error {553            state = .unavailable(reason: error)554        } else if !hasAccount(kind) {555            state = .unavailable(reason: "This wallet has no account on this chain.")556        } else {557            state = .notLoaded558        }559        return ChainSnapshot(chain: descriptor, isPrimary: isPrimary(kind), accountAddress: address, data: state, isSynchronizing: synchronizing,560                             progress: synchronizing ? progress : nil, syncError: error, receive: await receiveInformation(kind, data: data),561                             limits: Self.limits(kind))562    }563564    /// Where to be paid on a chain, from public profile data. No network.565    func receiveInformation(_ kind: ChainKind, data: ChainData?) async -> ChainReceive? {566        guard profile.kind != nil, hasAccount(kind) else { return nil }567        let descriptor = ChainRegistry.descriptor(kind)568        switch kind {569        case .utxo(let network):570            let found: WalletAddress?571            if Self.isPrimaryUTXO(network) {572                found = network == profile.bitcoinNetwork ? try? await nextReceiveAddress() : nil573            } else {574                found = try? nextCoinReceiveAddress(network)575            }576            guard let next = found else { return nil }577            var notes = ["A new address is given for every payment. Do not reuse an address: reuse links payments together and, after a spend, leaves coins behind a published key."]578            if profile.coldMode { notes.append("This device does not synchronize: it cannot know which addresses were already used.") }579            if network.cashAddrPrefix != nil { notes.append("Give the address with its prefix (\(network.cashAddrPrefix ?? ""):…), as shown.") }580            if !network.indexerAvailable { notes.append(Self.noIndexerText(network)) }581            return ChainReceive(address: next.address, derivationPath: next.path, rule: .freshAddressPerPayment, notes: notes)582        case .evm(let network):583            guard let address = profile.ethereumAddress else { return nil }584            return ChainReceive(address: address.checksummed, derivationPath: descriptor.derivationPath, rule: .fixedAddress, notes: [585                "This address is the same on every EVM network. Make sure the sender uses \(network.displayName): funds sent on another network arrive on that network, not here.",586            ])587        case .solana:588            guard let address = profile.solanaAddress else { return nil }589            var notes = ["A Solana address is the public key of the account itself: sharing it publishes the key."]590            if case .solana(let extras)? = data?.extras, !extras.accountExists {591                notes.append("This account does not exist on chain yet. Its first payment must be at least \(WalletMessages.sol(extras.systemAccountRent)) (the minimum every Solana account keeps).")592            }593            return ChainReceive(address: address, derivationPath: descriptor.derivationPath, rule: .fixedAddress, notes: notes)594        case .tron:595            guard let address = profile.tronAddress else { return nil }596            var notes = ["This address is the same on every TRON network."]597            if case .tron(let extras)? = data?.extras, !extras.isActivated {598                notes.append("This address is not activated yet: the first TRX it receives creates it (the sender pays the activation fee). Tokens can be received before that, but TRX is needed to move them.")599            }600            return ChainReceive(address: address, derivationPath: descriptor.derivationPath, rule: .fixedAddress, notes: notes)601        }602    }603604    /// The ceilings that apply to a chain now, as sentences; nil unless it is a main network on an unaudited build.605    static func limits(_ kind: ChainKind) -> ChainLimits? {606        guard !kind.isTest, MainnetPolicy.unauditedMainnet else { return nil }607        return limitSentences(kind)608    }609610    /// The ceilings of an unaudited build on a main network, as sentences, whether or not they apply now: the one611    /// wording, used by `limits` and shown by the mainnet warning before the user opts in (`previewLimits`).612    static func limitSentences(_ kind: ChainKind) -> ChainLimits? {613        let limits = MainnetPolicy.limits614        let tokenLine = "At most \(Int(limits.tokenUSDPerTransaction)) USD per token transfer. A dollar-pegged token counts for at least 0.90 USD a unit; any other token needs fresh prices from two sources that agree. A token whose price cannot be verified cannot be sent."615        switch kind {616        case .utxo(let network):617            return utxoLimits(network)618        case .evm(let network):619            let value = MainnetPolicy.nativeValueCeiling(for: network), fee = MainnetPolicy.feeCeiling(for: network)620            func text(_ ceiling: MainnetPolicy.Ceiling) -> String {621                MainnetPolicy.describe(ceiling, network: network) + (ceiling.needsPrice ? " (checked with fresh prices from two sources that agree; refused otherwise)" : "")622            }623            return ChainLimits(native: "At most \(text(value)) per transaction.", tokens: tokenLine + " Approvals are signed only to revoke an allowance.",624                               fee: "Maximum fee of a transaction: \(text(fee))" + (network.isOPStack ? ", L1 data fee included." : "."))625        case .solana:626            let l = MainnetPolicy.solanaLimits627            return ChainLimits(native: "At most \(Int(l.nativeUSDPerTransaction)) USD of SOL per transaction, checked with fresh prices from two sources that agree; refused otherwise.",628                               tokens: tokenLine,629                               fee: "Priority fee of a transaction: at most \(WalletMessages.sol(l.feePerTransaction)). A new token account for the recipient: at most \(WalletMessages.sol(MainnetPolicy.solanaAccountCreationLamportsCeiling)).")630        case .tron:631            let l = MainnetPolicy.tronLimits632            return ChainLimits(native: "At most \(Int(l.nativeUSDPerTransaction)) USD of TRX per transaction, checked with fresh prices from two sources that agree; refused otherwise.",633                               tokens: tokenLine, fee: "Fee limit and worst-case fee of a transaction: at most \(WalletMessages.trx(l.feePerTransaction)).")634        }635    }636637    static func utxoLimits(_ network: BitcoinNetwork) -> ChainLimits? {638        guard let l = MainnetPolicy.utxoLimits(network) else { return nil }639        let unit = network.ticker640        func coins(_ base: UInt64) -> String { BaseUnits.format(UInt256(base), decimals: network.decimals) + " " + unit }641        let native: String642        switch l.value {643        case .baseUnits(let v): native = "At most \(coins(v)) per transaction."644        case .usd(let usd): native = "At most \(Int(usd)) USD of \(unit) per transaction, checked with fresh prices from two sources that agree; refused otherwise."645        }646        return ChainLimits(native: native, tokens: nil, fee: "Fee of a transaction: at most \(coins(l.feePerTransaction)) and \(l.feeRatePerVByte) \(network.baseUnitName)s per virtual byte.")647    }648649    // MARK: Conversions to the uniform types650651    static func chainToken(_ token: TokenInfo) -> ChainToken {652        ChainToken(chain: ChainRegistry.id(token.network), address: token.address.checksummed, symbol: token.symbol, name: token.name, decimals: token.decimals,653                   standard: .erc20, priceID: token.priceID, isCustom: token.custom)654    }655656    static func chainData(_ s: BitcoinSnapshot) -> ChainData {657        let id = ChainRegistry.id(s.network)658        let history = s.transactions.map { t -> ActivityEntry in659            let direction: ActivityEntry.Direction660            switch t.direction {661            case .received: direction = .received662            case .sent: direction = .sent663            case .selfTransfer: direction = .selfTransfer664            }665            return ActivityEntry(chain: id, id: t.txid, hash: t.txid, direction: direction, counterparty: t.direction == .sent ? t.counterpartyAddresses.first : nil,666                                 amount: UInt256(t.amount), decimals: s.network.decimals, symbol: s.network.ticker, fee: t.fee.map { UInt256($0) },667                                 status: t.confirmations > 0 ? .confirmed(confirmations: UInt64(t.confirmations)) : .pending, time: t.time,668                                 blockHeight: t.blockHeight.map { UInt64($0) }, kind: .native)669        }670        let exposed = s.utxos.filter { $0.exposure == .revealedBySpend || $0.exposure == .revealedByScript }.count671        let exposure: ChainExposure672        if s.utxos.isEmpty {673            exposure = ChainExposure(publicKeyExposed: false, evidence: .spendHistory, outgoingTransactionCount: nil,674                                     statement: "No coin is held on \(s.network.displayName), so no key guards any value.")675        } else if exposed == 0 {676            exposure = ChainExposure(publicKeyExposed: false, evidence: .spendHistory, outgoingTransactionCount: nil,677                                     statement: "Every coin sits on an address that was never spent from: only hashes of the public keys are on chain.")678        } else {679            exposure = ChainExposure(publicKeyExposed: true, evidence: .spendHistory, outgoingTransactionCount: nil,680                                     statement: "\(exposed) coin(s) sit on addresses whose public key is already on chain.")681        }682        return ChainData(synchronizedAt: s.synchronizedAt, isFromPreviousSession: s.isFromPreviousSession, height: UInt64(s.tipHeight),683                         native: ChainNativeBalance(confirmed: UInt256(s.balance.confirmed), pending: UInt256(s.balance.pending), decimals: s.network.decimals,684                                                    symbol: s.network.ticker),685                         tokens: [], detectedTokens: [], history: .available(history), exposure: exposure, extras: .utxo(s),686                         notes: s.notes + (s.historyTruncated ? ["The history of an address is longer than what was read: balances are exact, the history may be partial."] : []))687    }688689    static func chainData(_ s: EthereumSnapshot) -> ChainData {690        let id = ChainRegistry.id(s.network)691        func balance(_ b: TokenBalance) -> ChainTokenBalance { ChainTokenBalance(token: chainToken(b.token), balance: b.balance, warning: nil) }692        let history: Availability<[ActivityEntry]>693        switch s.history {694        case .notLoaded: history = .notLoaded695        case .unavailable(let reason): history = .unavailable(reason: reason)696        case .available(let entries):697            history = .available(entries.map { e in698                let direction: ActivityEntry.Direction699                switch e.direction {700                case .received: direction = .received701                case .sent: direction = .sent702                case .selfTransfer: direction = .selfTransfer703                }704                var kind = ActivityEntry.Kind.native705                var decimals: Int? = s.network.nativeDecimals706                var symbol: String? = s.network.nativeSymbol707                switch e.kind {708                case .ether: break709                case .token(let address, let tokenSymbol, let tokenDecimals, let verified):710                    kind = .token(address: address, symbol: tokenSymbol, decimals: tokenDecimals, verified: verified)711                    decimals = tokenDecimals712                    symbol = tokenSymbol713                case .approval(let token): kind = .approval(token: token)714                case .contractCall(let method): kind = .contract(method: method)715                }716                let status: ActivityEntry.Status717                if !e.succeeded {718                    status = .failed719                } else if let block = e.blockNumber {720                    let depth = EthereumRPC.confirmations(of: block, head: s.blockNumber)721                    status = depth >= s.network.finalityConfirmations ? .finalized : .confirmed(confirmations: depth)722                } else {723                    status = .pending724                }725                return ActivityEntry(chain: id, id: e.id, hash: e.hash, direction: direction, counterparty: e.counterparty.isEmpty ? nil : e.counterparty,726                                     amount: e.amount, decimals: decimals, symbol: symbol, fee: e.fee, status: status, time: e.time, blockHeight: e.blockNumber,727                                     kind: kind)728            })729        }730        let exposure = s.latestNonce > 0731            ? ChainExposure(publicKeyExposed: true, evidence: .nonce, outgoingTransactionCount: s.latestNonce,732                            statement: "The account sent \(s.latestNonce) transaction(s) on \(s.network.displayName): its public key can be recovered from any of their signatures, on every EVM network.")733            : ChainExposure(publicKeyExposed: false, evidence: .nonce, outgoingTransactionCount: 0,734                            statement: "The account has not sent a transaction on \(s.network.displayName). The same key is used on every EVM network: one transaction on any of them publishes it.")735        return ChainData(synchronizedAt: s.synchronizedAt, isFromPreviousSession: s.isFromPreviousSession, height: s.blockNumber,736                         native: ChainNativeBalance(confirmed: s.balance, pending: .zero, decimals: s.network.nativeDecimals, symbol: s.network.nativeSymbol),737                         tokens: s.tokens.map(balance), detectedTokens: s.detectedTokens.map(balance), history: history, exposure: exposure, extras: .evm(s),738                         notes: s.notes)739    }740741    static func chainData(_ r: SolanaChainRecord) -> ChainData {742        let history: Availability<[ActivityEntry]> = r.history.map { .available($0) } ?? .unavailable(reason: r.historyReason ?? "The history was not read.")743        let funded = r.extras.accountExists744        let exposure = ChainExposure(745            publicKeyExposed: true, evidence: .addressIsPublicKey, outgoingTransactionCount: nil,746            statement: "A Solana address is the Ed25519 public key itself: the key is public as soon as the address is shared"747                + (funded ? ", and this account is on chain." : ". This account is not on chain yet.") + " Ed25519 does not resist a large quantum computer.")748        return ChainData(synchronizedAt: r.synchronizedAt, isFromPreviousSession: r.isFromPreviousSession ?? false, height: r.slot,749                         native: ChainNativeBalance(confirmed: UInt256(r.lamports), pending: .zero, decimals: SolanaNetwork.decimals, symbol: SolanaNetwork.symbol),750                         tokens: r.holdings.filter(\.listed).map(\.balance), detectedTokens: r.holdings.filter { !$0.listed }.map(\.balance),751                         history: history, exposure: exposure, extras: .solana(r.extras), notes: r.notes)752    }753754    static func chainData(_ r: TronChainRecord) -> ChainData {755        let history: Availability<[ActivityEntry]> = r.history.map { .available($0) } ?? .unavailable(reason: r.historyReason ?? "The history was not read.")756        let exposure: ChainExposure757        switch r.hasOutgoing {758        case true?:759            exposure = ChainExposure(publicKeyExposed: true, evidence: .history, outgoingTransactionCount: nil,760                                     statement: "The account has sent transactions on \(r.network.displayName): its public key can be recovered from any of their signatures.")761        case false?:762            exposure = ChainExposure(publicKeyExposed: false, evidence: .history, outgoingTransactionCount: nil,763                                     statement: r.isActivated ? "No transaction sent by this account was found on \(r.network.displayName): only the hash of its public key (the address) is public."764                                         : "This address has never been activated: it cannot have sent a transaction, and only the hash of its public key is public.")765        case nil:766            exposure = ChainExposure(publicKeyExposed: nil, evidence: .notMeasured, outgoingTransactionCount: nil,767                                     statement: "Whether this account has sent transactions on \(r.network.displayName) could not be measured (\(tronUnmeasuredReason(r))).")768        }769        return ChainData(synchronizedAt: r.synchronizedAt, isFromPreviousSession: r.isFromPreviousSession ?? false, height: r.blockNumber,770                         native: ChainNativeBalance(confirmed: UInt256(r.balanceSun), pending: .zero, decimals: TronUnits.decimals, symbol: r.network.symbol),771                         tokens: r.holdings.filter(\.listed).map(\.balance), detectedTokens: r.holdings.filter { !$0.listed }.map(\.balance),772                         history: history, exposure: exposure,773                         extras: .tron(TronExtras(isActivated: r.isActivated, resources: r.resources.value, parameters: r.parameters.value)), notes: r.notes)774    }775}776
Files main
Menu

Theme