SPB Git

Repository Public

WalletTypes.swift 51.9 KB 1,098 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraWallet/WalletTypes.swift8// Module           : Qyvora Wallet9// 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 Foundation42import QyvoraMath43import QyvoraCore44import QyvoraBitcoin45import QyvoraEthereum46import QyvoraNetworking47import QyvoraStorage48import QyvoraVault49import QyvoraSolana50import QyvoraTron5152// MARK: - Errors5354/// Why an Ethereum transaction was refused before anything was signed.55public enum EthereumRefusal: Error, Equatable, Sendable {56    /// A previous transaction of the account is still pending (pending nonce ≠ latest nonce).57    case pendingTransaction(latestNonce: UInt64, pendingNonce: UInt64)58    /// Not "0x" + 40 hexadecimal digits, or a mixed-case address whose EIP-55 checksum is wrong.59    case invalidAddress60    case zeroAddress61    /// Tokens sent to their own contract are lost.62    case recipientIsTokenContract63    /// The destination of a plain ether transfer is a contract (pass `allowContractRecipient` to proceed with a warning).64    case recipientIsContract65    /// The token address holds no code on this network.66    case tokenContractMissing67    case zeroAmount68    /// The amount exceeds the balance read on chain.69    case insufficientBalance(available: UInt256, required: UInt256)70    /// Not enough ether to pay the maximum fee.71    case insufficientFundsForFee(available: UInt256, required: UInt256)72    /// The gas estimate (after the safety margin) exceeds the wallet's limit.73    case gasLimitTooHigh(estimated: UInt64, limit: UInt64)74    /// `eth_estimateGas` or `eth_call` reported that the call would fail.75    case simulationFailed(String)76    /// The token returned something else than nothing or `true`.77    case unexpectedTokenReturn78    /// Fee figures from the endpoint are out of range.79    case feeOutOfRange80    /// The token belongs to another network than the active one.81    case tokenNetworkMismatch82    /// The payload names another chain than the active network.83    case chainMismatch(expected: UInt64, found: UInt64)84    /// The transaction is not signed by, or not sent from, this wallet's account.85    case foreignSender86    /// Contract creation, access lists and other shapes QYVORA 1.0 does not sign.87    case unsupportedTransaction(String)88}8990/// Errors of `WalletService`. No case carries secret data.91public enum WalletError: Error, Equatable, Sendable {92    /// Mainnet is disabled until the independent audit is recorded. The text is ready to display.93    case mainnetDisabled(String)94    /// No wallet exists on this device yet.95    case noWallet96    case walletAlreadyExists97    /// The operation needs private keys and this wallet is watch-only.98    case watchOnly99    /// The vault must be unlocked first.100    case vaultLocked101    case wrongPassword102    /// The action is sensitive and no credential (password, PIN, biometrics) was verified recently enough103    /// (QYV-APP-002). Authenticate again with one of the `unlock` calls, then repeat the action.104    case authenticationRequired105    /// A new vault or backup password is below the minimum the service accepts (QYV-APP-001); the text says why.106    case weakPassword(String)107    /// Wrong PIN; `retryAllowedAt` is set when a waiting time now applies.108    case wrongPIN(retryAllowedAt: Date?)109    /// Too many wrong PINs: nothing is accepted before `until` (`remaining` seconds from now).110    case pinLocked(until: Date, remaining: TimeInterval)111    /// Biometric unlock cannot be used; the text says why. Use the password.112    case biometricUnavailable(String)113    /// The wipe-after-N-wrong-PINs policy erased the vault from this device.114    case vaultWiped115    case vault(VaultError)116    case invalidRecoveryPhrase(String)117    case invalidInput(String)118    case invalidAddress(String)119    /// Cold mode is on: the service makes no network call.120    case offline121    case network(String)122    /// An endpoint serves another chain than the one selected (genesis hash or chain id mismatch).123    case wrongChain(String)124    /// An endpoint answered with data that fails validation.125    case untrustedResponse(String)126    /// The operation needs a synchronized snapshot.127    case notSynchronized(String)128    case bitcoinBuild(BitcoinBuildError)129    /// The plan no longer matches the wallet (inputs spent, network changed, plan altered).130    case stalePlan(String)131    case ethereum(EthereumRefusal)132    case signingFailed(String)133    /// The endpoint reported another transaction identifier than the one computed locally.134    case broadcastMismatch(local: String, remote: String)135    case invalidPSBT(String)136    case invalidPayload(String)137    case storage(String)138    /// The feature depends on a protocol or a module that is not available.139    case featureUnavailable(String)140    /// Mainnet on an unaudited build: the transaction exceeds the per-transaction ceiling. `limit` is ready to display141    /// (e.g. "0.002 BTC").142    case exceedsUnauditedLimit(limit: String)143    /// Mainnet on an unaudited build: the value of the transaction cannot be checked against the ceiling144    /// (no fresh price for the token, undecodable call, approval of a non-zero amount). The text says why.145    case unauditedLimitUnverifiable(String)146    /// The identifier names no chain QYVORA supports.147    case unknownChain(String)148    /// The chain is not active: it is not enabled, or the other network of the chain is the active one. The text names it.149    case chainNotActive(String)150    /// The recipient is not an address the wallet can pay on this chain.151    case address(AddressRefusal)152    /// A Solana transfer was refused before anything was signed.153    case solana(SolanaSendRefusal)154    /// A TRON transfer was refused before anything was signed.155    case tron(TronPlanError)156    /// A simulation of the transaction on current chain state failed; the text is the node's reason. Nothing was sent.157    case simulationFailed(String)158    /// A payment with the same recipient, asset and amount was broadcast and is neither confirmed nor expired. A second159    /// one is not signed before the first can no longer be executed: both could go through. `id` is the first one's.160    case transactionInFlight(id: String)161    /// The transaction can no longer be executed (Solana blockhash or TRON expiration passed). Prepare a new one.162    case transactionExpired(String)163    /// The network refused the signed transaction; the text is its reason. Nothing moved.164    case broadcastRejected(String)165}166167extension WalletError {168    static let mainnetText = "Mainnet is disabled: QYVORA's cryptographic engine has not been independently audited yet. "169        + "Creating, synchronizing, signing and watch-only viewing are available on test networks only, unless this is an "170        + "internal build and mainnet was switched on in the settings."171172    static let unauditedText = "Real funds on mainnet: this build signs with cryptography that has not been independently "173        + "audited. Per-transaction limits apply; keep only small amounts in this wallet."174175    static func from(_ error: VaultError, now: Date) -> WalletError {176        switch error {177        case .locked: return .vaultLocked178        case .wrongPassword: return .wrongPassword179        case .wrongPIN(let at): return .wrongPIN(retryAllowedAt: at)180        case .pinLocked(let until): return .pinLocked(until: until, remaining: max(0, until.timeIntervalSince(now)))181        case .wiped: return .vaultWiped182        case .notFound: return .noWallet183        case .alreadyExists: return .walletAlreadyExists184        case .deviceSlotNotEnabled: return .biometricUnavailable("Biometric unlock is not enabled for this vault.")185        case .deviceAuthenticationFailed: return .biometricUnavailable("The biometric check failed or was cancelled.")186        case .deviceKeyUnavailable: return .biometricUnavailable("The device key is no longer available (biometrics changed or the Keychain was reset). Unlock with the password.")187        case .secureEnclaveUnavailable: return .biometricUnavailable("This device has no Secure Enclave.")188        default: return .vault(error)189        }190    }191192    static func from(_ error: NetworkError) -> WalletError {193        switch error {194        case .offline: return .offline195        case .disagreement(let text): return .untrustedResponse("the endpoints disagree (\(text))")196        case .invalidResponse(let what): return .untrustedResponse(what)197        case .invalidURL, .http, .rpc, .unsupported: return .network(error.summary)198        case .allEndpointsFailed(let failures):199            // cold mode only: a device that simply has no connection is a network failure, with its reason200            let cold = !failures.isEmpty && failures.allSatisfy { $0.hasSuffix(NetworkError.coldModeSummary) }201            return cold ? .offline : .network(failures.joined(separator: "; "))202        }203    }204205    /// Maps anything thrown by the lower layers to a `WalletError`.206    static func wrap(_ error: any Error, now: Date = Date()) -> WalletError {207        if let e = error as? WalletError { return e }208        if let e = error as? EthereumRefusal { return .ethereum(e) }209        if let e = error as? VaultError { return .from(e, now: now) }210        if let e = error as? NetworkError { return .from(e) }211        if let e = error as? BitcoinBuildError { return .bitcoinBuild(e) }212        if let e = error as? StorageError { return .storage(WalletMessages.storage(e)) }213        if let e = error as? PSBTError { return .invalidPSBT(WalletMessages.psbt(e)) }214        if let e = error as? BIP39.Error { return .invalidRecoveryPhrase(WalletMessages.recoveryPhrase(e)) }215        if let e = error as? AddressRefusal { return .address(e) }216        if let e = error as? SolanaSendRefusal { return .solana(e) }217        if let e = error as? TronPlanError { return .tron(e) }218        if let e = error as? SolanaError { return .invalidPayload(WalletMessages.solana(e)) }219        if let e = error as? TronTransaction.Error { return .signingFailed(WalletMessages.tronTransaction(e)) }220        if error is TronProtobufError { return .invalidPayload("This is not a TRON transaction the wallet can read.") }221        if error is CancellationError { return .network("the operation was cancelled") }222        // a transport failure (no connection, DNS, timeout…): its reason, never the name of its Swift type223        return .network(NetworkError.transportSummary(error))224    }225}226227// MARK: - Generic state228229/// State of a value that comes from the network. The service never substitutes a placeholder for missing data.230public enum Availability<Value: Sendable & Equatable>: Sendable, Equatable {231    /// Nothing was requested yet.232    case notLoaded233    case available(Value)234    /// The data could not be obtained; the reason is ready to display.235    case unavailable(reason: String)236237    public var value: Value? {238        if case .available(let v) = self { return v }239        return nil240    }241}242243// MARK: - Profile244245public enum WalletKind: String, Codable, Sendable {246    /// The recovery phrase is in the vault: the device can sign.247    case full248    /// Public keys only.249    case watchOnly250}251252public enum DisplayCurrency: String, Codable, Sendable, CaseIterable {253    case usd, cad, eur254}255256/// Public data of a BIP-84 account (never secret).257public struct BitcoinAccountPublicData: Codable, Equatable, Sendable {258    /// Account key at m/84'/coin'/0' in plain BIP-32 form (xpub… / tpub…).259    public var extendedPublicKey: String260    /// Hexadecimal fingerprint of the master key (8 digits), when known; needed for PSBT key origins.261    public var masterFingerprint: String?262}263264/// The non-secret, persistent profile of the wallet. Stored as JSON through QyvoraStorage.265public struct WalletProfile: Codable, Equatable, Sendable {266    public var version = WalletProfile.currentVersion267    /// nil while no wallet exists.268    public var kind: WalletKind?269    public var bitcoinNetwork: BitcoinNetwork = .signet270    public var ethereumNetwork: EthereumNetwork = .sepolia271    /// Account public data by coin type: "test" (testnet and signet share it) and "main".272    public var bitcoinAccounts: [String: BitcoinAccountPublicData] = [:]273    public var ethereumAddress: EthereumAddress?274    /// Used receive / change indices per Bitcoin network (raw value), kept between launches.275    public var usedReceiveIndices: [String: [UInt32]] = [:]276    public var usedChangeIndices: [String: [UInt32]] = [:]277    /// User labels by address text.278    public var addressLabels: [String: String] = [:]279    /// Frozen UTXOs ("txid:vout"): never selected automatically.280    public var frozenUTXOs: [String] = []281    public var customTokens: [TokenInfo] = []282    /// `TokenInfo.id` of tokens the user hid.283    public var hiddenTokens: [String] = []284    public var endpoints: EndpointConfiguration = .default285    public var displayCurrency: DisplayCurrency = .usd286    public var autoLock: AutoLockPolicy = .after(seconds: 300)287    public var lastBackupDate: Date?288    public var lastBackupSigned: Bool?289    /// When true the service performs no network call at all.290    public var coldMode = false291    /// Strength of the vault password measured when it was set (never the password).292    public var passwordQuality: PasswordQuality.Level?293    public var recoveryPhraseVerified = false294    /// Whether a BIP-39 passphrase is part of the wallet (the passphrase itself is in the vault).295    public var usesPassphrase = false296    /// The user switched mainnet on in the settings. Has an effect only on a build that allows mainnet.297    public var mainnetOptIn = false298299    // Multi-chain (profile version 2). Everything below is absent from a profile written by QYVORA 1.0 and takes the300    // default shown: such a wallet keeps Bitcoin and Ethereum on its test networks, exactly as before.301302    /// Chains the user wants to see, as main-network identifiers (`ChainDescriptor.mainCounterpart`).303    public var enabledChains: [ChainID] = ChainRegistry.defaultEnabled304    /// Test networks (default) or main networks, for every enabled chain. `.main` only while mainnet is enabled.305    public var networkMode: NetworkMode = .test306    /// Test network chosen for a chain that has several, by main identifier (Bitcoin: Signet or Testnet; Solana: devnet307    /// or testnet; TRON: Nile or Shasta). A chain without entry uses `ChainRegistry.defaultTestNetwork`.308    public var testNetworks: [String: ChainID] = [:]309    /// Solana account (base58; the Ed25519 public key at m/44'/501'/0'/0'), the same on every cluster.310    public var solanaAddress: String?311    /// TRON account (Base58Check, m/44'/195'/0'/0/0), the same on every network.312    public var tronAddress: String?313    public var solanaEndpoints: SolanaEndpoints = .default314    public var tronEndpoints: TronEndpoints = .default315    /// SPL tokens added by the user.316    public var customSolanaTokens: [ChainToken] = []317    /// TRC-20 tokens added by the user.318    public var customTronTokens: [ChainToken] = []319    /// True when a TronGrid API key is stored in the vault (the key itself is never in the profile).320    public var hasTronAPIKey = false321322    public init() {}323324    /// The highest address index a profile may record as used: twice what a scan covers (`WalletService.maximumScanIndex`).325    static let maximumUsedIndex: UInt32 = 4_000326327    /// Tolerant decoding: a key missing from an older profile keeps its default.328    public init(from decoder: any Decoder) throws {329        self.init()330        let c = try decoder.container(keyedBy: CodingKeys.self)331        func get<T: Decodable>(_ key: CodingKeys, _ current: T) throws -> T { try c.decodeIfPresent(T.self, forKey: key) ?? current }332        version = try get(.version, version)333        kind = try c.decodeIfPresent(WalletKind.self, forKey: .kind)334        bitcoinNetwork = try get(.bitcoinNetwork, bitcoinNetwork)335        ethereumNetwork = try get(.ethereumNetwork, ethereumNetwork)336        bitcoinAccounts = try get(.bitcoinAccounts, bitcoinAccounts)337        ethereumAddress = try c.decodeIfPresent(EthereumAddress.self, forKey: .ethereumAddress)338        // the profile file is not authenticated: an index no scan can have produced is dropped, so that nothing339        // computed from these lists (next address, search windows) overflows or grows without bound (QYV-SVC-104)340        usedReceiveIndices = try get(.usedReceiveIndices, usedReceiveIndices).mapValues { $0.filter { $0 <= Self.maximumUsedIndex } }341        usedChangeIndices = try get(.usedChangeIndices, usedChangeIndices).mapValues { $0.filter { $0 <= Self.maximumUsedIndex } }342        addressLabels = try get(.addressLabels, addressLabels)343        frozenUTXOs = try get(.frozenUTXOs, frozenUTXOs)344        customTokens = try get(.customTokens, customTokens)345        hiddenTokens = try get(.hiddenTokens, hiddenTokens)346        endpoints = try get(.endpoints, endpoints)347        displayCurrency = try get(.displayCurrency, displayCurrency)348        autoLock = try get(.autoLock, autoLock)349        lastBackupDate = try c.decodeIfPresent(Date.self, forKey: .lastBackupDate)350        lastBackupSigned = try c.decodeIfPresent(Bool.self, forKey: .lastBackupSigned)351        coldMode = try get(.coldMode, coldMode)352        passwordQuality = try c.decodeIfPresent(PasswordQuality.Level.self, forKey: .passwordQuality)353        recoveryPhraseVerified = try get(.recoveryPhraseVerified, recoveryPhraseVerified)354        usesPassphrase = try get(.usesPassphrase, usesPassphrase)355        mainnetOptIn = try get(.mainnetOptIn, mainnetOptIn)356        // identifiers this version does not know are dropped; an empty list falls back to the default357        let known = Set(ChainRegistry.mainChains.map(\.id))358        var seen = Set<ChainID>()359        let stored = (try c.decodeIfPresent([ChainID].self, forKey: .enabledChains) ?? enabledChains).filter { known.contains($0) && seen.insert($0).inserted }360        enabledChains = stored.isEmpty ? ChainRegistry.defaultEnabled : stored361        networkMode = (try? c.decodeIfPresent(NetworkMode.self, forKey: .networkMode)) ?? networkMode362        testNetworks = (try? c.decodeIfPresent([String: ChainID].self, forKey: .testNetworks)) ?? testNetworks363        solanaAddress = try c.decodeIfPresent(String.self, forKey: .solanaAddress)364        tronAddress = try c.decodeIfPresent(String.self, forKey: .tronAddress)365        solanaEndpoints = (try? c.decodeIfPresent(SolanaEndpoints.self, forKey: .solanaEndpoints)) ?? solanaEndpoints366        tronEndpoints = (try? c.decodeIfPresent(TronEndpoints.self, forKey: .tronEndpoints)) ?? tronEndpoints367        customSolanaTokens = (try? c.decodeIfPresent([ChainToken].self, forKey: .customSolanaTokens)) ?? []368        customTronTokens = (try? c.decodeIfPresent([ChainToken].self, forKey: .customTronTokens)) ?? []369        hasTronAPIKey = try get(.hasTronAPIKey, hasTronAPIKey)370        // a profile written by 1.0 on a main network was in "main" mode without saying so371        if (try c.decodeIfPresent(NetworkMode.self, forKey: .networkMode)) == nil, bitcoinNetwork == .mainnet, !ethereumNetwork.isTest {372            networkMode = .main373        }374        version = Self.currentVersion375    }376377    /// 1: QYVORA 1.0 (Bitcoin and Ethereum). 2: multi-chain.378    public static let currentVersion = 2379380    static func coinKey(_ network: BitcoinNetwork) -> String { network.isTest ? "test" : "main" }381}382383// MARK: - Bitcoin state384385public struct BitcoinBalance: Equatable, Sendable {386    /// Satoshis in confirmed unspent outputs.387    public let confirmed: UInt64388    /// Satoshis in unconfirmed unspent outputs (incoming payments and own change waiting for a block).389    public let pending: UInt64390    public var total: UInt64 { confirmed + pending }391}392393public struct WalletAddress: Equatable, Sendable, Identifiable {394    public let address: String395    public let chain: BIP84Account.Chain396    public let index: UInt32397    /// Full path, e.g. m/84'/1'/0'/0/5.398    public let path: String399    /// The address appears in at least one transaction.400    public let isUsed: Bool401    public let transactionCount: Int402    /// Unspent satoshis on the address.403    public let balance: UInt64404    /// Paid by more than one transaction, or paid again after a spend.405    public let isReused: Bool406    public let exposure: PublicKeyExposure407    public let label: String?408    public var id: String { address }409}410411public struct WalletUTXO: Equatable, Sendable, Identifiable {412    public let utxo: BitcoinUTXO413    public let exposure: PublicKeyExposure414    /// One sentence explaining the exposure.415    public let exposureExplanation: String416    /// Coin control: excluded from automatic selection.417    public let isFrozen: Bool418    public let label: String?419    public var id: String { utxo.outPoint.description }420    public var value: UInt64 { utxo.value }421    public var confirmations: UInt32 { utxo.confirmations }422    public var address: String? { utxo.address }423}424425public struct BitcoinHistoryEntry: Equatable, Sendable, Identifiable {426    public enum Direction: String, Sendable { case received, sent, selfTransfer }427428    public let txid: String429    public let direction: Direction430    /// Change of the wallet balance caused by the transaction, in satoshis (negative when it left the wallet, fee included).431    public let netAmount: Int64432    /// Amount shown to the user: received value, value sent to others (fee excluded), or 0 for a self transfer.433    public let amount: UInt64434    /// Fee in satoshis, known only when the wallet funded every input.435    public let fee: UInt64?436    public let confirmations: UInt32437    public let blockHeight: UInt32?438    /// Block time; nil while unconfirmed.439    public let time: Date?440    /// Addresses of the other side (payers cannot be known reliably; these are the non-wallet outputs for a send).441    public let counterpartyAddresses: [String]442    /// Wallet addresses credited by the transaction.443    public let walletAddresses: [String]444    public var id: String { txid }445    public var isConfirmed: Bool { confirmations > 0 }446}447448public struct BitcoinSnapshot: Equatable, Sendable {449    public let network: BitcoinNetwork450    public let tipHeight: UInt32451    public let synchronizedAt: Date452    public let balance: BitcoinBalance453    public let utxos: [WalletUTXO]454    /// Newest first (unconfirmed, then by height).455    public let transactions: [BitcoinHistoryEntry]456    /// Every discovered address of both chains up to the gap limit, receive chain first.457    public let addresses: [WalletAddress]458    /// The next never-used receive address.459    public let receiveAddress: WalletAddress460    /// Addresses that show reuse.461    public let reusedAddresses: [WalletAddress]462    /// True when an address has more history than the wallet pages through; balances stay exact, history may be partial.463    public let historyTruncated: Bool464    /// Non-fatal remarks of the synchronization.465    public let notes: [String]466    /// Funding / spending events, for the Quantum Shield.467    public let activity: [ScriptActivity]468    /// True when the snapshot was restored from the last synchronization of a previous launch: it is the last known469    /// state as of `synchronizedAt`, not a fresh reading. Show it as such; payments are not built from it.470    public internal(set) var isFromPreviousSession = false471}472473public struct BitcoinFeeOption: Equatable, Sendable, Identifiable {474    public enum Tier: String, Sendable, CaseIterable { case slow, normal, fast }475    public let tier: Tier476    public let rate: FeeRate477    /// Confirmation target of the estimate used, in blocks; nil for a floor value.478    public let targetBlocks: Int?479    public var id: String { tier.rawValue }480}481482public struct BitcoinFeeOptions: Equatable, Sendable {483    public enum Source: String, Sendable {484        /// From the endpoint's fee estimates (floored and capped).485        case estimates486        /// The endpoint gave no usable estimate: every tier is the minimum relay fee. Label it as such.487        case minimumRelayFloor488    }489    public let slow: BitcoinFeeOption490    public let normal: BitcoinFeeOption491    public let fast: BitcoinFeeOption492    public let source: Source493    public var all: [BitcoinFeeOption] { [slow, normal, fast] }494}495496/// Coin control for one send.497public struct BitcoinCoinControl: Equatable, Sendable {498    /// Outputs that must be spent.499    public var required: [BitcoinOutPoint]500    /// Spend exactly `required`.501    public var useOnlyRequired: Bool502    /// Allow unconfirmed outputs in automatic selection.503    public var includeUnconfirmed: Bool504505    public init(required: [BitcoinOutPoint] = [], useOnlyRequired: Bool = false, includeUnconfirmed: Bool = false) {506        self.required = required507        self.useOnlyRequired = useOnlyRequired508        self.includeUnconfirmed = includeUnconfirmed509    }510}511512public enum BitcoinSendWarning: Equatable, Sendable {513    /// The destination already received a payment from this wallet.514    case destinationAlreadyPaid515    /// No payment from this wallet to the destination is known (QYV-APP-010): the moment to compare the address.516    case firstPaymentToAddress517    /// The destination is an address of this wallet.518    case destinationIsOwnAddress519    /// The destination itself has been used before (own address with history).520    case destinationReused521    /// Inputs spend addresses whose public key is already on chain.522    case exposedInputs(count: Int)523    /// The fee exceeds 5 % of the amount.524    case highFeeShare(basisPoints: Int)525    /// The fee exceeds the wallet's warning threshold.526    case highAbsoluteFee(fee: UInt64, threshold: UInt64)527    /// A remainder too small for a change output was left to the fee.528    case dustAddedToFee(amount: UInt64)529    case unconfirmedInputs(count: Int)530    /// Several inputs are spent together, which links their addresses.531    case mergesAddresses(count: Int)532    /// Mainnet on an unaudited build: real funds are handled by cryptography that has not been audited.533    case unauditedMainnet534535    /// Sentence for the review screen.536    public var message: String {537        switch self {538        case .destinationAlreadyPaid: return "This wallet already paid this address. Reusing an address links the payments together."539        case .firstPaymentToAddress: return "First payment to this address: this wallet has no record of paying it before. Compare every character with the address you were given, on its original source."540        case .destinationIsOwnAddress: return "The destination is an address of this wallet."541        case .destinationReused: return "The destination address has already been used."542        case .exposedInputs(let n): return "\(n) input(s) spend addresses whose public key is already on chain."543        case .highFeeShare(let bp): return "The fee is \(bp / 100).\(String(format: "%02d", bp % 100)) % of the amount."544        case .highAbsoluteFee(let fee, let t): return "The fee (\(fee) sat) is above \(t) sat."545        case .dustAddedToFee(let a): return "\(a) sat too small for a change output are added to the fee."546        case .unconfirmedInputs(let n): return "\(n) input(s) are not confirmed yet."547        case .mergesAddresses(let n): return "Coins of \(n) addresses are spent together, which links these addresses."548        case .unauditedMainnet: return WalletError.unauditedText549        }550    }551}552553/// A reviewable Bitcoin transaction. Building it touches no secret. Values cannot be created or altered outside the service.554public struct BitcoinSendPlan: Equatable, Sendable, Identifiable {555    public enum Purpose: String, Sendable { case payment, sweepExposed }556557    public struct Input: Equatable, Sendable, Identifiable {558        public let outPoint: BitcoinOutPoint559        public let address: String?560        public let value: UInt64561        public let confirmations: UInt32562        public let exposure: PublicKeyExposure563        public var id: String { outPoint.description }564    }565566    public struct Output: Equatable, Sendable, Identifiable {567        public let index: Int568        /// nil for a script without address form.569        public let address: String?570        public let value: UInt64571        /// The output returns to this wallet's change chain.572        public let isChange: Bool573        /// The output pays an address of this wallet (change included).574        public let isMine: Bool575        public var id: Int { index }576    }577578    public let id: UUID579    public let purpose: Purpose580    public let network: BitcoinNetwork581    public let createdAt: Date582    /// The underlying plan (unsigned transaction, selected UTXOs).583    public let plan: BitcoinTransactionPlan584    public let recipient: String585    /// Satoshis paid to the recipient.586    public let amount: UInt64587    public let fee: UInt64588    public let virtualSize: Int589    /// Rate asked for.590    public let targetFeeRate: FeeRate591    /// Lower bound of the rate actually paid.592    public let effectiveFeeRate: FeeRate593    public let inputs: [Input]594    public let outputs: [Output]595    public let changeAddress: String?596    public let changeValue: UInt64597    public let isSendMax: Bool598    public let warnings: [BitcoinSendWarning]599    /// Satoshis leaving the wallet: amount + fee (for a sweep, the fee only).600    public var totalSpent: UInt64 { (purpose == .sweepExposed ? 0 : amount) + fee }601    /// Identifier the transaction will have (SegWit: independent of the signatures).602    public var txid: String { plan.transaction.txid }603}604605public struct BitcoinBroadcastResult: Equatable, Sendable {606    /// Computed locally from the signed transaction.607    public let txid: String608    public let rawHex: String609    public let fee: UInt64610    public let virtualSize: Int611}612613/// Text split into numbered QR frames (`qyv1:<index>/<total>:<checksum>:<base64url>`, the Recovery module's `QRChunker`).614public struct QRExport: Equatable, Sendable {615    /// The payload as text (base64 PSBT, 0x-hex transaction, or JSON).616    public let text: String617    /// Frames to show one after the other; a single frame when the payload is small.618    public let frames: [String]619}620621public struct PSBTReview: Equatable, Sendable {622    public struct Input: Equatable, Sendable, Identifiable {623        public let outPoint: BitcoinOutPoint624        public let address: String?625        /// nil when the PSBT does not carry the spent output.626        public let value: UInt64?627        /// The input spends a script of this wallet, verified by derivation.628        public let isMine: Bool629        public let derivationPath: String?630        public let isSigned: Bool631        public var id: String { outPoint.description }632    }633634    public struct Output: Equatable, Sendable, Identifiable {635        public let index: Int636        public let address: String?637        public let value: UInt64638        /// Verified by deriving the wallet's own keys — never taken from the PSBT's claims.639        public let isMine: Bool640        /// Mine and on the change chain.641        public let isChange: Bool642        public let derivationPath: String?643        public var id: Int { index }644    }645646    public let network: BitcoinNetwork647    public let txid: String648    public let inputs: [Input]649    public let outputs: [Output]650    /// nil when an input amount is unknown.651    public let fee: UInt64?652    /// Sum of the outputs that leave the wallet.653    public let sentToOthers: UInt64654    /// Sum of the outputs that return to the wallet.655    public let returningToWallet: UInt64656    public let virtualSizeEstimate: Int657    public let warnings: [String]658    /// Lines ready to display on the cold device.659    public let summary: [String]660    public let isFullySigned: Bool661    /// True when the amounts the fee is computed from do not rest on the PSBT's word alone (QYV-SVC-008): the662    /// transaction has a single input (its SegWit signature commits to its amount), or every input carries its663    /// previous transaction (hashed to the outpoint) or is an output this wallet read itself. When false the fee664    /// shown may be forged and `signPSBT` needs `acceptUnverifiedAmounts`.665    public let inputAmountsVerified: Bool666}667668public struct SignedPSBT: Equatable, Sendable {669    public let review: PSBTReview670    public let signaturesAdded: Int671    public let export: QRExport672}673674// MARK: - Ethereum state675676public struct TokenBalance: Equatable, Sendable, Identifiable {677    public let token: TokenInfo678    /// Read on chain with `balanceOf`.679    public let balance: Availability<UInt256>680    public var id: String { token.id }681}682683public struct EthereumHistoryEntry: Equatable, Sendable, Identifiable {684    public enum Direction: String, Sendable { case received, sent, selfTransfer }685    public enum Kind: Equatable, Sendable {686        case ether687        /// A token transfer; symbol and decimals come from the wallet's verified list when the token is known,688        /// otherwise from the indexer (`verified` false).689        case token(address: String, symbol: String?, decimals: Int?, verified: Bool)690        /// An `approve` call sent by the account.691        case approval(token: String)692        /// Any other contract call (value may be zero).693        case contractCall(method: String?)694    }695696    public let hash: String697    public let kind: Kind698    public let direction: Direction699    public let counterparty: String700    /// Wei or token base units.701    public let amount: UInt256702    /// Fee in wei, for transactions sent by the account when the indexer reports it.703    public let fee: UInt256?704    public let succeeded: Bool705    public let time: Date?706    public let blockNumber: UInt64?707    public let id: String708}709710public struct TokenApproval: Equatable, Sendable, Identifiable {711    public let token: TokenInfo712    public let spender: EthereumAddress713    /// Current on-chain allowance (non-zero).714    public let allowance: UInt256715    public let isUnlimited: Bool716    public var id: String { "\(token.id):\(spender.checksummed)" }717}718719public struct EthereumSnapshot: Equatable, Sendable {720    public let network: EthereumNetwork721    public let address: EthereumAddress722    public let synchronizedAt: Date723    public let blockNumber: UInt64724    /// Wei.725    public let balance: UInt256726    public let latestNonce: UInt64727    public let pendingNonce: UInt64728    /// A transaction of the account is waiting in the mempool.729    public var hasPendingTransaction: Bool { pendingNonce != latestNonce }730    /// Built-in and custom tokens that are not hidden.731    public let tokens: [TokenBalance]732    /// Tokens reported by the indexer, read on chain, not yet accepted by the user. Never mixed with `tokens`.733    public let detectedTokens: [TokenBalance]734    /// Newest first.735    public let history: Availability<[EthereumHistoryEntry]>736    /// Non-zero allowances granted by the account.737    public let approvals: Availability<[TokenApproval]>738    public let notes: [String]739    /// True when the snapshot was restored from the last synchronization of a previous launch: it is the last known740    /// state as of `synchronizedAt`, not a fresh reading.741    public internal(set) var isFromPreviousSession = false742743    /// The same snapshot with other token lists (the wallet's token list changed between two synchronizations).744    func with(tokens: [TokenBalance], detectedTokens: [TokenBalance]) -> EthereumSnapshot {745        EthereumSnapshot(network: network, address: address, synchronizedAt: synchronizedAt, blockNumber: blockNumber, balance: balance,746                         latestNonce: latestNonce, pendingNonce: pendingNonce, tokens: tokens, detectedTokens: detectedTokens, history: history,747                         approvals: approvals, notes: notes, isFromPreviousSession: isFromPreviousSession)748    }749}750751public enum EthereumAsset: Equatable, Sendable {752    case ether753    case token(TokenInfo)754}755756public enum EthereumFeeTier: String, Sendable, CaseIterable {757    /// Half the suggested priority fee.758    case slow759    /// The suggested priority fee.760    case normal761    /// Twice the suggested priority fee.762    case fast763}764765public enum EthereumSendWarning: Equatable, Sendable {766    /// The address was given without checksum (all lower or upper case): typing errors cannot be detected.767    case recipientWithoutChecksum768    case recipientIsContract769    case recipientIsOwnAddress770    /// No payment from this account to the recipient appears in the history the wallet read (QYV-APP-010).771    case firstPaymentToRecipient772    /// The transaction replaces the pending one with the same nonce.773    case replacesPendingTransaction(nonce: UInt64)774    /// The maximum fee exceeds 5 % of the ether amount.775    case highFeeShare(basisPoints: Int)776    /// Unlimited token allowance.777    case unlimitedApproval778    /// The call data is not a call QYVORA can decode: the user would sign blind.779    case blindSigning780    /// The token contract is not in the wallet's token list.781    case unknownTokenContract782    case revokesApproval783    /// Mainnet on an unaudited build: real funds are handled by cryptography that has not been audited.784    case unauditedMainnet785786    public var message: String {787        switch self {788        case .recipientWithoutChecksum: return "The address has no checksum: a typing error cannot be detected. Compare it carefully."789        case .recipientIsContract: return "The destination is a contract. Ether sent to a contract that cannot handle it is lost."790        case .recipientIsOwnAddress: return "The destination is this wallet's own address."791        case .firstPaymentToRecipient: return "First payment to this address: the history of this account shows no earlier payment to it. Compare every character with the address you were given, on its original source."792        case .replacesPendingTransaction(let n): return "This replaces the pending transaction with nonce \(n)."793        case .highFeeShare(let bp): return "The maximum fee is \(bp / 100).\(String(format: "%02d", bp % 100)) % of the amount."794        case .unlimitedApproval: return "This approval lets the spender move an unlimited amount of the token."795        case .blindSigning: return "Blind signing: QYVORA cannot decode this call data. Sign only if you fully trust its source."796        case .unknownTokenContract: return "The contract called is not a token of this wallet's list."797        case .revokesApproval: return "This sets the spender's allowance to zero."798        case .unauditedMainnet: return WalletError.unauditedText799        }800    }801}802803/// What the call data of a transaction means.804public enum EthereumCallDescription: Equatable, Sendable {805    /// No call data: a plain ether transfer.806    case etherTransfer807    case tokenTransfer(token: TokenInfo?, contract: EthereumAddress, to: EthereumAddress, amount: UInt256)808    case tokenApproval(token: TokenInfo?, contract: EthereumAddress, spender: EthereumAddress, amount: UInt256)809    /// Undecodable call data, shown as raw hexadecimal.810    case unknown(dataHex: String)811}812813/// A reviewable Ethereum transaction. Values cannot be created or altered outside the service.814public struct EthereumSendReview: Equatable, Sendable, Identifiable {815    public let id: UUID816    public let network: EthereumNetwork817    public let createdAt: Date818    public let from: EthereumAddress819    public let asset: EthereumAsset820    /// The beneficiary (for a token transfer, not the token contract).821    public let recipient: EthereumAddress822    /// Wei or token base units.823    public let amount: UInt256824    public let transaction: EIP1559Transaction825    public let call: EthereumCallDescription826    public let feeTier: EthereumFeeTier827    public let baseFee: UInt256828    /// gasLimit × maxFeePerGas, plus `l1DataFee` on an OP-Stack network, in wei.829    public let maximumFee: UInt256830    /// maximumFee + value of the native coin: the most the transaction can cost, in wei.831    public let maximumTotalCost: UInt256832    public let isSendMax: Bool833    public let warnings: [EthereumSendWarning]834    /// Part of `maximumFee` that is the L1 data fee of an OP-Stack network (Base, OP Mainnet), as quoted by the835    /// network's GasPriceOracle plus a margin of one quarter; zero on every other network. It is charged by the836    /// network on top of gas × price and is not a field of the transaction.837    public internal(set) var l1DataFee: UInt256 = .zero838    public var nonce: UInt64 { transaction.nonce }839    public var gasLimit: UInt64 { transaction.gasLimit }840}841842public struct EthereumBroadcastResult: Equatable, Sendable {843    /// "0x…" hash computed locally from the signed bytes.844    public let hash: String845    public let rawHex: String846    public let nonce: UInt64847}848849public enum EthereumTransactionStatus: Equatable, Sendable {850    /// Not mined yet (or unknown to the endpoint).851    case pending852    case confirmed(blockNumber: UInt64, gasUsed: UInt64, feePaid: UInt256?)853    /// Mined and reverted; the fee was still paid.854    case failed(blockNumber: UInt64, gasUsed: UInt64, feePaid: UInt256?)855}856857/// Review of an unsigned transaction received by the cold device.858public struct ColdEthereumReview: Equatable, Sendable {859    public let network: EthereumNetwork860    public let transaction: EIP1559Transaction861    public let call: EthereumCallDescription862    public let maximumFee: UInt256863    public let maximumTotalCost: UInt256864    public let warnings: [EthereumSendWarning]865    /// Lines ready to display.866    public let summary: [String]867}868869public struct ColdSignedEthereum: Equatable, Sendable {870    public let review: ColdEthereumReview871    public let hash: String872    /// 0x-hex raw signed transaction, with its QR frames, to carry back to the online device.873    public let export: QRExport874}875876// MARK: - Market877878public struct MarketQuote: Equatable, Sendable, Identifiable {879    /// CoinGecko identifier ("bitcoin", "ethereum", "usd-coin"…).880    public let id: String881    public let currency: DisplayCurrency882    public let price: Double883    public let change24h: Double?884    public let change7d: Double?885    /// Hourly prices of the last seven days, oldest first; may be empty.886    public let sparkline7d: [Double]887    public let fetchedAt: Date888    /// True when the quote is older than `WalletService.quoteFreshness` or comes from the persisted last-known cache.889    /// A stale quote must be labelled with its date, never presented as current.890    public let isStale: Bool891}892893public enum ChartRange: String, Sendable, CaseIterable {894    case day, week, month, year895896    public var days: Int {897        switch self {898        case .day: return 1899        case .week: return 7900        case .month: return 30901        case .year: return 365902        }903    }904}905906public struct PriceChart: Equatable, Sendable {907    public let assetID: String908    public let currency: DisplayCurrency909    public let range: ChartRange910    public let points: [PriceClient.PricePoint]911    public let fetchedAt: Date912    public let isStale: Bool913}914915public struct MarketSnapshot: Equatable, Sendable {916    public let currency: DisplayCurrency917    /// By asset identifier. An asset without entry has no known price.918    public let quotes: [String: MarketQuote]919    /// Why quotes are missing or stale, when they are.920    public let unavailableReason: String?921}922923public struct ValuationLine: Equatable, Sendable, Identifiable {924    public let id: String925    public let symbol: String926    public let name: String927    /// Exact decimal amount of the asset, as text.928    public let amount: String929    public let isTestNetwork: Bool930    /// Fiat value of real (mainnet) holdings; nil on a test network or without price.931    public let value: Double?932    /// On a test network: what the same amount of the mainnet asset would be worth. Not money the user owns.933    public let referenceValue: Double?934    public let price: MarketQuote?935    /// The chain the asset is on.936    public let chain: ChainID937}938939/// Value of what one chain holds. Real value on a main network, reference value on a test network, never both.940public struct ChainValuation: Equatable, Sendable, Identifiable {941    public let chain: ChainID942    public let realValue: Double?943    public let referenceValue: Double?944    public var id: ChainID { chain }945}946947/// Portfolio valuation in the display currency. Test-network coins have no monetary value: they are only ever counted948/// in `referenceValue`, flagged by `isTestNetwork`.949public struct PortfolioValuation: Equatable, Sendable {950    public let currency: DisplayCurrency951    public let lines: [ValuationLine]952    /// Sum of the mainnet lines with a price; nil when there is none.953    public let realValue: Double?954    /// Sum of the test-network lines at mainnet prices; nil when there is none. Must be labelled as a reference value.955    public let referenceValue: Double?956    /// True when at least one line is on a test network.957    public let isTestNetwork: Bool958    /// True when a quote used is stale.959    public let isStale: Bool960    /// Oldest fetch date among the quotes used.961    public let pricedAt: Date?962    /// Assets that hold a balance but have no price.963    public let unpricedAssets: [String]964    /// True when a balance used comes from a snapshot restored from the previous session: the value is the last known965    /// one, as of `balancesAsOf`, not a fresh reading.966    public let isFromPreviousSession: Bool967    /// Oldest synchronization date among the snapshots used; nil when no chain has a snapshot.968    public let balancesAsOf: Date?969    /// The same valuation per chain, for the chains that hold something or have a snapshot.970    public let chains: [ChainValuation]971}972973// MARK: - Dashboard974975public struct VaultStatus: Equatable, Sendable {976    public let exists: Bool977    public let isUnlocked: Bool978    public let biometricEnabled: Bool979    public let pinEnabled: Bool980}981982/// Everything a dashboard needs, in one value.983public struct WalletSnapshot: Equatable, Sendable {984    public let profile: WalletProfile985    public let hasWallet: Bool986    public let vault: VaultStatus987    /// `MainnetPolicy.mainnetEnabled` when the snapshot was taken.988    public let mainnetEnabled: Bool989    /// This build may offer the mainnet switch (`MainnetPolicy.mainnetAvailable`).990    public let mainnetAvailable: Bool991    /// An active network is a mainnet: balances are real funds.992    public let isMainnet: Bool993    /// Real funds are handled by unaudited code: show a permanent notice; `unauditedLimits` apply to every transaction.994    public let unauditedMainnet: Bool995    /// Per-transaction ceilings while `unauditedMainnet` is true.996    public let unauditedLimits: MainnetPolicy.Limits997    public let bitcoin: Availability<BitcoinSnapshot>998    public let ethereum: Availability<EthereumSnapshot>999    /// Error of the last failed synchronization, ready to display; nil after a success. Set whether or not an older1000    /// snapshot is still shown (when none is, the chain's state is `.unavailable` with the same reason).1001    public let bitcoinSyncError: String?1002    public let ethereumSyncError: String?1003    public let isSynchronizingBitcoin: Bool1004    public let isSynchronizingEthereum: Bool1005    /// Next receive address from the cached indices; available while locked and offline.1006    public let bitcoinReceiveAddress: String?1007    public let market: MarketSnapshot1008    public let valuation: PortfolioValuation1009    /// Every active chain, in display order: for each enabled chain, its main network in `.main` mode and its chosen1010    /// test network in `.test` mode. `bitcoin` and `ethereum` above are the two primary chains among them, in the form1011    /// the 1.0 screens read.1012    public let chains: [ChainSnapshot]1013    public let networkMode: NetworkMode10141015    /// The snapshot of one chain, nil when it is not active.1016    public func chain(_ id: ChainID) -> ChainSnapshot? { chains.first { $0.id == id } }1017}10181019public enum WalletChain: String, Sendable { case bitcoin, ethereum }10201021public enum WalletEvent: Equatable, Sendable {1022    case walletCreated1023    case walletDeleted1024    case profileChanged1025    case vaultUnlocked1026    case vaultLocked1027    case syncStarted(WalletChain)1028    /// `completed` of `total` steps; `total` is nil while unknown. Real counts, never an estimate.1029    case syncProgress(WalletChain, stage: String, completed: Int, total: Int?)1030    case syncFinished(WalletChain)1031    case syncFailed(WalletChain, reason: String)1032    case transactionBroadcast(WalletChain, id: String)1033    case marketUpdated1034    // Per-chain events, sent for every chain (the two primary chains also send the four events above).1035    case chainSyncStarted(ChainID)1036    /// `completed` of `total` steps; `total` is nil while unknown. Real counts, never an estimate.1037    case chainSyncProgress(ChainID, stage: String, completed: Int, total: Int?)1038    case chainSyncFinished(ChainID)1039    case chainSyncFailed(ChainID, reason: String)1040    case chainTransactionBroadcast(ChainID, id: String)1041}10421043/// What a watch-only package holds, as both devices show it before an import (QYV-APP-080).1044public struct WatchOnlyPreview: Equatable, Sendable {1045    public struct Account: Equatable, Sendable, Identifiable {1046        public let chain: ChainID1047        /// Name of the network the address is written for ("Bitcoin Signet", "Solana").1048        public let name: String1049        /// The first receive address of the account (index 0), or the account address itself.1050        public let address: String1051        /// False for an address written for a test network.1052        public let isMainnet: Bool1053        public let detail: String1054        public var id: String { chain.rawValue + "|" + address }1055    }10561057    /// Five groups of four hexadecimal digits (`WalletService.watchOnlyFingerprint`).1058    public let fingerprint: String1059    /// Format version of the package.1060    public let version: Int1061    public let accounts: [Account]1062    /// Accounts of the package this build could not derive an address for, by a short description.1063    public let unreadable: [String]10641065    /// The groups of the fingerprint, for display and for reading aloud.1066    public var fingerprintGroups: [String] { fingerprint.split(separator: "-").map(String.init) }1067}10681069/// The "watch-only package" a cold device shows to its online companion.1070public struct WatchOnlyPackage: Codable, Equatable, Sendable {1071    public struct Bitcoin: Codable, Equatable, Sendable {1072        public var network: BitcoinNetwork1073        public var extendedPublicKey: String1074        public var masterFingerprint: String?1075        /// BIP-389 descriptor `wpkh([fp/84h/ch/0h]xpub/<0;1>/*)#…`, importable in other wallets.1076        public var descriptor: String1077        public var receiveDescriptor: String1078        public var changeDescriptor: String1079    }10801081    public var format = "qyvora-watch-only"1082    /// 1: Bitcoin and Ethereum. 2: adds `solanaAddress`, `tronAddress` and `accounts`. A version-1 package is still1083    /// accepted; a reader of version 1 ignores the new fields (it would import Bitcoin and Ethereum only).1084    public var version = WatchOnlyPackage.currentVersion1085    public var bitcoin: Bitcoin?1086    /// The EVM account: the same address on every EVM network.1087    public var ethereumAddress: String?1088    public var solanaAddress: String?1089    public var tronAddress: String?1090    /// Account keys of the other UTXO coins, by `BitcoinNetwork` raw value. Empty when the wallet has none.1091    public var accounts: [String: BitcoinAccountPublicData]?1092    /// Chains enabled on the device that made the package (main-network identifiers): the importing device shows the1093    /// same ones. Absent in a package of version 1.1094    public var enabledChains: [String]?10951096    public static let currentVersion = 21097}1098
Files main
Menu

Theme