SPB Git

Repository Public

WalletErrorMessages.swift 26.0 KB 397 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraWallet/WalletErrorMessages.swift8// Module           : Qyvora Wallet9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import QyvoraCore43import QyvoraBitcoin44import QyvoraNetworking45import QyvoraStorage46import QyvoraVault47import QyvoraIdentity48import QyvoraRecovery49import QyvoraSolana50import QyvoraTron5152/// The one place where errors become sentences. Every screen shows `WalletMessages.text(for:)` (or `userMessage`);53/// nothing interpolates an error value, so a Swift case name such as `invalidInput("…")` never reaches the user.54public enum WalletMessages {55    /// A plain English sentence for anything thrown by the service, by the layers under it or by the system frameworks56    /// around it. Errors of the lower layers go through the same conversion as inside the service (`WalletError.wrap`).57    public static func text(for error: any Error) -> String {58        if let e = error as? IdentityError { return identity(e) }59        if let e = error as? BackupError { return backup(e) }60        if let e = error as? RecoverySheetError { return recoverySheet(e) }61        return WalletError.wrap(error).userMessage62    }6364    static func storageReason(_ error: any Error) -> String {65        (error as? StorageError).map(storage) ?? "unexpected failure"66    }6768    static func storage(_ error: StorageError) -> String {69        switch error {70        case .notFound: return "the file or Keychain item does not exist"71        case .invalidName: return "the file name is not valid"72        case .io(let operation, let code): return "a file operation failed (\(operation), code \(code))"73        case .keychain(let status): return "the Keychain refused the operation (status \(status))"74        case .authenticationFailed: return "the biometric or passcode check failed or was cancelled"75        case .interactionNotAllowed: return "the item needs a biometric or passcode check that is not possible right now"76        case .secureEnclaveUnavailable: return "this device has no Secure Enclave"77        case .invalidData: return "the stored data is damaged or does not have the expected structure"78        }79    }8081    static func recoveryPhrase(_ error: BIP39.Error) -> String {82        switch error {83        case .invalidEntropyLength: return "The recovery phrase has an unsupported length."84        case .invalidWordCount: return "A recovery phrase has 12, 15, 18, 21 or 24 words."85        case .unknownWord(let position): return "Word \(position + 1) is not in the BIP-39 word list."86        case .invalidChecksum: return "The words do not form a valid recovery phrase (the checksum does not match). Check their order and spelling."87        }88    }8990    static func psbt(_ error: PSBTError) -> String {91        switch error {92        case .invalidBase64: return "It is not valid base64 text."93        case .invalidMagic: return "It is not a PSBT."94        case .duplicateKey, .invalidField, .serialization, .missingUnsignedTransaction, .unsignedTransactionNotEmpty:95            return "Its structure is not valid."96        case .unsupportedVersion(let version): return "PSBT version \(version) is not supported."97        case .inputIndexOutOfRange, .outputIndexOutOfRange: return "It refers to an input or output that does not exist."98        case .missingUTXO, .nonWitnessUTXORequired: return "It does not carry the outputs being spent, so the amounts cannot be verified."99        case .nonWitnessUTXOMismatch, .utxoMismatch, .witnessUTXOForNonWitnessInput:100            return "The outputs it claims to spend do not match the transaction: the amounts cannot be trusted."101        case .missingRedeemScript, .redeemScriptMismatch, .missingWitnessScript, .witnessScriptMismatch, .unsupportedScript:102            return "It spends a script type this wallet does not sign."103        case .sighashTypeNotAllowed: return "It asks for a signature type this wallet refuses (only SIGHASH_ALL is signed)."104        case .invalidPrivateKey, .invalidSignature: return "A signature in it is not valid."105        case .notEnoughSignatures, .notFinalized: return "It is not fully signed."106        case .differentTransactions, .nothingToCombine: return "The parts do not describe the same transaction."107        }108    }109110    static func identity(_ error: IdentityError) -> String {111        switch error {112        case .malformed, .invalidText: return "This is not a QYVORA identity, signature or package, or it is incomplete."113        case .unsupportedVersion(let version): return "It was made by a format version (\(version)) this build does not read."114        case .invalidKey: return "A key in it is not valid."115        case .invalidPurpose: return "It was signed for another purpose."116        case .signingFailed: return "The signature could not be produced."117        case .invalidSignature: return "The signature does not verify: the content was modified, or it was not signed by that identity."118        case .wrongRecipient: return "It was made for another device: this iPhone's identity cannot open it."119        case .unexpectedSender: return "It was not sent by the expected identity."120        case .decryptionFailed: return "It cannot be decrypted: it was modified, or it was made for another device."121        case .brokenChain: return "The rotation history of the identity is not consistent."122        case .vault(let inner): return inner.userMessage123        }124    }125126    static func backup(_ error: BackupError) -> String {127        switch error {128        case .truncated: return "The backup file is incomplete."129        case .badMagic: return "This is not a QYVORA backup file."130        case .unsupportedVersion(let version): return "The backup was written by a newer format (version \(version)) that this build does not read."131        case .checksumMismatch: return "The backup file was damaged in storage or in transit (its checksum does not match)."132        case .malformed: return "The backup file is not well formed."133        case .authenticationFailed: return "The backup password is wrong, or the file was modified."134        case .invalidSignature: return "The backup carries a signature that does not verify."135        case .signatureRequired: return "A signed backup was expected and this one is not signed."136        case .unexpectedSigner: return "The backup is signed, but not by the expected identity."137        case .recordIntegrity: return "A record of the backup does not match its digest."138        case .invalidParameters: return "The backup password is empty, or the backup is too large."139        case .kdfFailure: return "The key derivation failed (not enough memory)."140        case .signingFailed: return "The backup could not be signed."141        case .vault(let inner): return inner.userMessage142        }143    }144145    static func recoverySheet(_ error: RecoverySheetError) -> String {146        switch error {147        case .invalidMnemonic: return "The stored recovery phrase is not a valid BIP-39 phrase."148        case .derivationFailed: return "A key derivation failed."149        case .invalidParameters: return "Too many addresses were requested for the recovery sheet."150        }151    }152}153154extension WalletError {155    /// A plain English sentence, ready to display next to the action that failed. Every case has one.156    public var userMessage: String {157        switch self {158        case .mainnetDisabled(let text): return text159        case .noWallet: return "No wallet on this device."160        case .walletAlreadyExists: return "A wallet already exists on this device."161        case .watchOnly: return "This is a watch-only wallet: it holds no private key and cannot sign."162        case .vaultLocked: return "Unlock the vault first."163        case .authenticationRequired: return "Confirm it is you first: this action needs a fresh password, PIN or biometric check."164        case .wrongPassword: return "Wrong password."165        case .wrongPIN(let retry):166            return retry.map { "Wrong PIN. Next attempt possible at \($0.formatted(date: .omitted, time: .standard))." } ?? "Wrong PIN."167        case .pinLocked(_, let remaining): return "Too many wrong PINs. Try again in \(Self.duration(remaining))."168        case .biometricUnavailable(let text): return text169        case .vaultWiped:170            return "The vault was erased from this device after too many wrong PINs. Restore the wallet from its recovery phrase or from a backup."171        case .vault(let inner): return inner.userMessage172        case .invalidRecoveryPhrase(let text), .weakPassword(let text): return text173        case .invalidInput(let text), .invalidAddress(let text), .featureUnavailable(let text), .notSynchronized(let text),174             .unauditedLimitUnverifiable(let text):175            return text176        case .offline: return "Cold mode is on: this device makes no network request."177        case .network(let text): return "Network: \(text)"178        case .wrongChain(let text): return "An endpoint serves another chain than the one selected: \(text)"179        case .untrustedResponse(let text): return "An endpoint answered with data that fails validation (\(text))."180        case .bitcoinBuild(let inner): return inner.userMessage181        case .stalePlan(let text): return "This transaction can no longer be used: \(text)"182        case .ethereum(let refusal): return refusal.userMessage183        case .signingFailed(let text): return "Signing failed: \(text)"184        case .broadcastMismatch(let local, let remote):185            return "The endpoint reported another transaction identifier (\(remote)) than the one computed on this device (\(local)). Check the transaction in an explorer before sending again."186        case .invalidPSBT(let text): return "This PSBT cannot be used. \(text)"187        case .invalidPayload(let text): return text188        case .storage(let text): return "Storage: \(text)"189        case .exceedsUnauditedLimit(let limit): return "Above the limit of this unaudited build: \(limit)."190        case .unknownChain(let id): return "QYVORA does not know a chain named \(id)."191        case .chainNotActive(let name): return "\(name) is not active in this wallet. Enable the chain, or switch between test and main networks, first."192        case .address(let refusal): return refusal.message193        case .solana(let refusal): return refusal.userMessage194        case .tron(let refusal): return refusal.userMessage195        case .simulationFailed(let text): return "The network reports that this transaction would fail: \(text)"196        case .transactionInFlight(let id):197            return "The same payment was already sent (\(id.prefix(16))…) and is neither confirmed nor expired. A second one is not signed before the first can no longer go through: both could be executed."198        case .transactionExpired(let text): return "This transaction can no longer be executed: \(text) Prepare it again."199        case .broadcastRejected(let text): return "The network refused the transaction: \(text)"200        }201    }202203    static func duration(_ seconds: TimeInterval) -> String {204        let s = max(1, Int(seconds.rounded(.up)))205        if s < 120 { return "\(s) s" }206        if s < 7_200 { return "\((s + 59) / 60) min" }207        return "\((s + 3_599) / 3_600) h"208    }209}210211extension EthereumRefusal {212    /// A plain English sentence saying why the transaction was refused before anything was signed.213    public var userMessage: String {214        switch self {215        case .pendingTransaction(let latest, _):216            return "A previous transaction of this account (nonce \(latest)) is still pending. Wait for it to confirm, or replace it."217        case .invalidAddress: return "Not a valid Ethereum address, or its checksum does not verify."218        case .zeroAddress: return "The zero address cannot receive funds."219        case .recipientIsTokenContract: return "The recipient is the token contract itself: tokens sent there are lost."220        case .recipientIsContract: return "The recipient is a contract. Ether sent to a contract that cannot handle it is lost."221        case .tokenContractMissing: return "No token contract exists at this address on this network."222        case .zeroAmount: return "Enter an amount."223        case .insufficientBalance: return "The amount exceeds the balance read on chain."224        case .insufficientFundsForFee: return "Not enough ether to pay the maximum fee."225        case .gasLimitTooHigh(let estimated, let limit): return "The gas estimate (\(estimated)) exceeds the wallet's limit (\(limit))."226        case .simulationFailed(let text): return "The network reports that this transaction would fail: \(text)"227        case .unexpectedTokenReturn: return "The token contract answered unexpectedly; the transfer is refused."228        case .feeOutOfRange: return "The fee figures given by the endpoint are out of range."229        case .tokenNetworkMismatch: return "This token belongs to another network than the active one."230        case .chainMismatch(let expected, let found): return "The transaction names chain \(found); the active network is chain \(expected)."231        case .foreignSender: return "The transaction is not signed by this wallet's account."232        case .unsupportedTransaction(let text): return "This kind of transaction is not supported: \(text)"233        }234    }235}236237extension BitcoinBuildError {238    /// A plain English sentence saying why the Bitcoin transaction cannot be built.239    public var userMessage: String {240        switch self {241        case .noRecipients, .invalidAmount: return "Enter an amount."242        case .dustOutput: return "The amount is below the dust threshold: the network would not relay it."243        case .duplicateUTXO: return "The same coin was selected twice."244        case .requiredInputUnavailable(let outPoint):245            return "A selected coin cannot be spent (frozen, unconfirmed or already spent): \(outPoint.description)."246        case .unknownInputSize(let outPoint): return "A coin sits on a script this wallet cannot spend: \(outPoint.description)."247        case .insufficientFunds(let available, let required):248            return "Insufficient funds: \(available) sat spendable, \(required) sat needed (amount and fee)."249        case .changeScriptRequired: return "The transaction needs a change address and none is available."250        case .sendMaxBelowDust: return "After the fee, what remains is below the dust threshold."251        case .feeRateOutOfRange: return "The fee rate is outside the accepted range (1 to \(WalletService.bitcoinMaximumFeeRate) sat/vB)."252        case .feeExceedsCap(let fee, let cap): return "The fee (\(fee) sat) exceeds the wallet's cap (\(cap) sat)."253        case .absurdFee(let fee, let expected):254            return "The fee computed (\(fee) sat) is far above what the chosen rate explains (\(expected) sat); the transaction is refused."255        case .transactionTooLarge: return "The transaction would be too large. Select fewer coins or send a smaller amount."256        case .witnessScriptNotSupported: return "This network has no SegWit: a SegWit address cannot be paid on it."257        }258    }259}260261extension VaultError {262    /// A plain English sentence for a vault failure.263    public var userMessage: String {264        switch self {265        case .notFound: return "No vault exists on this device."266        case .alreadyExists: return "A vault already exists on this device."267        case .locked: return "Unlock the vault first."268        case .wrongPassword: return "Wrong password."269        case .wrongPIN(let retry):270            return retry.map { "Wrong PIN. Next attempt possible at \($0.formatted(date: .omitted, time: .standard))." } ?? "Wrong PIN."271        case .pinLocked(let until): return "Too many wrong PINs. Next attempt possible at \(until.formatted(date: .omitted, time: .standard))."272        case .wiped: return "The vault was erased from this device after too many wrong PINs."273        case .pinNotEnabled: return "PIN unlock is not enabled on this device."274        case .deviceSlotNotEnabled: return "Biometric unlock is not enabled for this vault."275        case .deviceAuthenticationFailed: return "The biometric check failed or was cancelled."276        case .deviceKeyUnavailable:277            return "The device key is no longer available (biometrics changed or the Keychain was reset). Unlock with the password."278        case .secureEnclaveUnavailable: return "This device has no Secure Enclave."279        case .corrupted: return "The vault file is damaged."280        case .integrityFailure: return "The vault file does not verify under its key: it was modified or damaged."281        case .recordNotFound: return "The record no longer exists in the vault."282        case .invalidParameters:283            return "The value is not accepted: the password is empty, or the PIN is not \(WalletService.pinLength) digits."284        case .kdfFailure: return "The key derivation failed (not enough memory)."285        case .selfTestFailed: return "The cryptographic self-test of the vault failed: the vault refuses to work."286        case .storage(let inner): return "Storage: \(WalletMessages.storage(inner))."287        }288    }289}290291extension WalletMessages {292    static func solana(_ error: SolanaError) -> String {293        switch error {294        case .invalidAddress: return "Not a Solana address."295        case .invalidBlockhash: return "The transaction carries an invalid blockhash."296        case .invalidSeed: return "The Solana key could not be derived."297        case .invalidProgramAddressSeeds: return "A program address of the transaction could not be derived."298        case .malformed(let what): return "This is not a Solana transaction the wallet can read (\(what))."299        case .tooManyAccounts: return "The transaction references too many accounts."300        case .invalidInstruction(let what): return "The transaction holds an instruction that cannot be encoded (\(what))."301        case .transactionTooLarge(let size): return "The transaction is too large for the network (\(size) bytes; the limit is 1232)."302        case .notASigner: return "This wallet's account is not a signer of the transaction."303        case .missingSignature: return "The transaction is not fully signed."304        }305    }306307    static func tronTransaction(_ error: TronTransaction.Error) -> String {308        switch error {309        case .invalidReferenceBlock: return "The reference block of the transaction is invalid."310        case .invalidExpiration: return "The expiration of the transaction is invalid."311        case .valueOutOfRange: return "An amount of the transaction is out of range."312        case .memoTooLong: return "The note is too long (256 bytes at most)."313        case .signerMismatch: return "The key of this wallet is not the owner of the transaction."314        case .blindSigningRefused: return "The transaction holds a contract QYVORA cannot decode. Blind signing must be allowed explicitly."315        case .invalidSignature: return "The signature produced does not verify."316        }317    }318319    static func sol(_ lamports: UInt64) -> String { SolanaAmount.formatLamports(lamports) + " SOL" }320    static func trx(_ sun: UInt64) -> String { TronUnits.formatTRX(sun) + " TRX" }321}322323extension AddressRefusal {324    /// A plain English sentence saying what is wrong with the address.325    public var message: String {326        switch self {327        case .empty: return "Enter an address."328        case .malformed(let chain, let expected): return "This is not a \(chain) address. \(expected)"329        case .wrongFamily(let chain, let found):330            return "This is \(found) address, not a \(chain) address. Funds sent to an address of another chain are lost: ask the recipient for their \(chain) address."331        case .wrongNetwork(let chain, let found): return "This address belongs to \(found), not to \(chain)."332        case .invalidChecksum(let chain): return "The checksum of this \(chain) address does not verify: a character is wrong."333        case .missingPrefix(let chain, let prefix):334            return "A \(chain) address must be given with its prefix (\(prefix):…): without it, it cannot be told from other formats."335        case .zeroAddress: return "The zero address cannot receive funds."336        case .unsupported(let text): return text337        }338    }339}340341extension SolanaSendRefusal {342    /// A plain English sentence saying why the Solana transfer was refused before anything was signed.343    public var userMessage: String {344        switch self {345        case .zeroAmount: return "Enter an amount."346        case .senderIsRecipient: return "The recipient is this wallet's own address."347        case .recipientIsReserved: return "The recipient is a program or a token mint, not a wallet: funds sent there are lost."348        case .recipientIsNotAWallet(let owner):349            return "This address is not a wallet: it is an account owned by the program \(owner.base58) (for instance a token account). Ask for the wallet address that owns it."350        case .insufficientLamports(let required, let available):351            return "Not enough SOL: \(WalletMessages.sol(required)) are needed (amount, fee and any new token account), \(WalletMessages.sol(available)) are available."352        case .senderBelowRentExemption(let remaining, let minimum, let maximumSendable):353            return "This would leave \(WalletMessages.sol(remaining)) on the account, below the \(WalletMessages.sol(minimum)) every Solana account must keep; the network would reject it. Send at most \(WalletMessages.sol(maximumSendable)), or send everything."354        case .recipientBelowRentExemption(let minimum):355            return "The recipient's account is new: it must receive at least \(WalletMessages.sol(minimum)) to exist on Solana."356        case .missingTokenData: return "This token (mint) does not exist on this network."357        case .noTokenAccount: return "This wallet holds none of this token."358        case .tokenAccountFrozen: return "This wallet's account for this token is frozen by the token's issuer."359        case .insufficientTokens: return "The amount exceeds the token balance read on chain."360        case .unsupportedToken(let reason): return "This token cannot be sent safely by QYVORA: \(reason)."361        case .invalidMemo: return "The note is empty, longer than 256 bytes or contains control characters."362        case .invalidComputeUnitLimit: return "The compute-unit limit is out of range."363        case .priorityFeeTooHigh(let lamports):364            return "The priority fee" + (lamports.map { " (\(WalletMessages.sol($0)))" } ?? "") + " is above the wallet's ceiling of \(WalletMessages.sol(SolanaSendPlanner.maximumPriorityFee))."365        case .buildFailed(let what): return "The transaction could not be built (\(what))."366        }367    }368}369370extension TronPlanError {371    /// A plain English sentence saying why the TRON transfer was refused before anything was signed.372    public var userMessage: String {373        switch self {374        case .zeroAmount: return "Enter an amount."375        case .recipientIsSender: return "The recipient is this wallet's own address."376        case .recipientIsZeroAddress: return "The zero address cannot receive funds."377        case .recipientIsTokenContract(let token): return "The recipient (\(token.base58)) is a token contract: funds sent there are lost."378        case .tokenIsNotAContract: return "No token contract exists at this address on this network."379        case .senderNotActivated: return "This TRON address has never been activated: it holds nothing yet and cannot send."380        case .insufficientBalance(let required, let available):381            return "Not enough TRX: \(WalletMessages.trx(required)) are needed (amount and network fee), \(WalletMessages.trx(available)) are available."382        case .insufficientTRXForFees(let required, let available):383            return "Not enough TRX to pay for this token transfer: up to \(WalletMessages.trx(required)) may be burned for bandwidth and energy, \(WalletMessages.trx(available)) are available."384        case .insufficientTokenBalance: return "The amount exceeds the token balance read on chain."385        case .simulationFailed(let text): return "The network reports that this transfer would fail: \(text)"386        case .invalidEnergyEstimate: return "The node gave no energy estimate for this transfer; no fee limit can be set."387        case .feeLimitTooHigh(let required, let cap):388            return "This transfer needs a fee limit of \(WalletMessages.trx(required)), above the ceiling of \(WalletMessages.trx(cap))."389        case .amountAboveLimit(let limit): return "Above the limit of this unaudited build: \(WalletMessages.trx(limit)) per transaction."390        case .clockSkew: return "The clock of this device and the latest block are too far apart: check the date and time, or the endpoint is out of date."391        case .invalidPolicy: return "The transfer settings are out of range."392        case .arithmeticOverflow: return "The amounts or the chain parameters are out of range."393        case .invalidTransaction(let inner): return WalletMessages.tronTransaction(inner)394        }395    }396}397
Files main
Menu

Theme