SPB Git

Repository Public

WalletService+Send.swift 51.9 KB 826 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraWallet/WalletService+Send.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 QyvoraSolana48import QyvoraTron4950// One way to pay on every chain: `prepareSend` builds a review (no secret), `signAndBroadcast` signs it locally and51// sends it, `track` follows it. The family-specific plan is carried in the body of the review.5253// MARK: - Types5455public enum SendFeeTier: String, Sendable, CaseIterable {56    case slow, normal, fast57}5859/// What the caller may choose for a payment. Fields that do not apply to a chain are ignored.60public struct SendOptions: Equatable, Sendable {61    /// Send everything: the whole token balance, or the native balance minus the fee.62    public var sendMax = false63    /// Fee choice where the chain has tiers (UTXO fee rate, EVM priority fee, Solana priority fee). TRON has none.64    public var feeTier: SendFeeTier = .normal65    /// UTXO chains: an explicit fee rate instead of the tier.66    public var bitcoinFeeRate: FeeRate?67    /// UTXO chains: coin control.68    public var coinControl: BitcoinCoinControl?69    /// EVM: replace the pending transaction of the account (same nonce).70    public var replacePending = false71    /// EVM: accept a contract as the recipient of the native coin.72    public var allowContractRecipient = false73    /// Solana (any asset) and TRON (TRX only): a public, permanent note attached to the payment. Never a secret.74    public var memo: String?75    /// Solana: an explicit compute-unit price in micro-lamports instead of the tier.76    public var solanaComputeUnitPrice: UInt64?77    /// The transaction will be carried to a cold device to be signed: TRON then gets a validity of thirty minutes78    /// instead of two. (A Solana transaction is valid for about a minute whatever is asked: its blockhash expires.)79    public var forColdSigning = false8081    public init() {}82}8384public struct SendWarning: Equatable, Sendable, Identifiable {85    /// Stable identifier ("first-payment", "own-address", "unaudited-mainnet", "solana.creates-token-account"…).86    public let id: String87    /// Sentence for the review screen.88    public let message: String89    /// True for a warning the user must acknowledge before signing (funds at risk).90    public let isCritical: Bool91}9293public struct SendFeeLine: Equatable, Sendable {94    public let label: String95    /// Base units of the native coin.96    public let amount: UInt25697}9899public struct SendFee: Equatable, Sendable {100    /// What the transaction is expected to cost, in base units of the native coin.101    public let expected: UInt256102    /// The most it can cost.103    public let maximum: UInt256104    public let symbol: String105    public let decimals: Int106    /// Fiat value of `expected` and `maximum` at the quote known now; nil without a quote.107    public let expectedFiat: Double?108    public let maximumFiat: Double?109    public let currency: DisplayCurrency110    /// True on a test network: the figure is what the same amount of the main-network coin would cost. Not real money.111    public let fiatIsReference: Bool112    /// True when the quote used is stale: show it with its date.113    public let fiatIsStale: Bool114    /// What the fee is made of.115    public let lines: [SendFeeLine]116}117118/// A payment ready for review, on any chain. Values cannot be created or altered outside the service.119public struct SendReview: Equatable, Sendable, Identifiable {120    public enum Body: Equatable, Sendable {121        case bitcoin(BitcoinSendPlan)122        case evm(EthereumSendReview)123        case solana(SolanaSendDetails)124        case tron(TronSendDetails)125    }126127    public let id: UUID128    public let chain: ChainDescriptor129    public let createdAt: Date130    /// The chain is a main network: real funds. Show the network banner accordingly.131    public let isMainnet: Bool132    /// Real funds handled by unaudited code: per-transaction limits apply (`limits`).133    public let unauditedMainnet: Bool134    public let limits: ChainLimits?135    /// The paying account; nil on a UTXO chain (the coins spent are in the body).136    public let from: String?137    public let recipient: String138    public let asset: ChainAsset139    /// Base units of the asset actually sent (for send-max, the computed amount).140    public let amount: UInt256141    public let amountDecimals: Int142    public let amountSymbol: String143    public let fee: SendFee144    /// The most native coin that can leave the account: the amount (when the asset is the native coin), the maximum145    /// fee and anything else the transaction locks (a new token account on Solana).146    public let totalNative: UInt256147    public let isSendMax: Bool148    public let warnings: [SendWarning]149    /// Facts to show under the figures.150    public let notes: [String]151    /// When the prepared transaction stops being valid; nil when it does not expire by time. TRON: the expiration152    /// written in the transaction. Solana: when its blockhash is expected to expire, about a minute after it was read153    /// (`WalletService.solanaBlockhashLifetime`); the chain decides by block height, so this is an estimate.154    public let expiresAt: Date?155    public let body: Body156157    public var hasCriticalWarning: Bool { warnings.contains(where: \.isCritical) }158}159160public struct SendResult: Equatable, Sendable {161    public let chain: ChainID162    /// Transaction identifier computed locally from the signed bytes (txid, 0x hash, Solana signature, TRON id).163    public let id: String164    /// The signed transaction as text (hex, or base64 on Solana).165    public let raw: String166    public let explorerURL: URL?167    /// Solana: block height after which the transaction can no longer be executed.168    public let lastValidBlockHeight: UInt64?169    /// TRON: when the transaction stops being valid.170    public let expiresAt: Date?171}172173public enum TransactionStatus: Equatable, Sendable {174    /// The endpoint does not know the transaction (not seen yet, or dropped).175    case notFound176    /// Seen, not in a block yet.177    case pending178    /// In a block, not final yet.179    case confirmed(blockHeight: UInt64?, confirmations: UInt64?, fee: UInt256?)180    /// Final by the chain's rule.181    case finalized(blockHeight: UInt64?, fee: UInt256?)182    /// Included and failed: the fee was paid, nothing else moved. `reason` is the chain's.183    case failed(blockHeight: UInt64?, reason: String?, fee: UInt256?)184    /// Never included and it can no longer be: a new transaction may be prepared.185    case expired186}187188/// Review of a transaction received by a cold device, on any chain.189public struct ColdTransactionReview: Equatable, Sendable {190    public enum Body: Equatable, Sendable {191        case bitcoin(PSBTReview)192        case evm(ColdEthereumReview)193        case solana(SolanaTransactionReview)194        case tron(TronTransactionReview)195    }196197    public let chain: ChainDescriptor198    /// Lines ready to display: what the transaction does, decoded on this device from the bytes that will be signed.199    public let summary: [String]200    public let warnings: [SendWarning]201    /// True when part of the transaction cannot be decoded: signing it is signing blind.202    public let requiresBlindSigning: Bool203    public let body: Body204    /// The tokens of this wallet's list (built-in or custom) that the transaction names, on Solana and TRON: their205    /// symbol and decimals let the review show an amount in token units. A token the wallet does not know is absent:206    /// its amount stays in base units. From the wallet's own list, never from the transaction or the network.207    public let knownTokens: [ChainToken]208    /// When set, this device does not sign the transaction, and the text says why (a test-network Solana or TRON209    /// transaction on an offline device of an unaudited build: QYV-APP-040). The screen shows it instead of the210    /// signature control; `signColdTransaction` refuses with the same sentence.211    public let signingRefusal: String?212213    init(chain: ChainDescriptor, summary: [String], warnings: [SendWarning], requiresBlindSigning: Bool, body: Body, knownTokens: [ChainToken] = [],214         signingRefusal: String? = nil) {215        self.signingRefusal = signingRefusal216        self.chain = chain217        self.summary = summary218        self.warnings = warnings219        self.requiresBlindSigning = requiresBlindSigning220        self.body = body221        self.knownTokens = knownTokens222    }223224    /// The token of the wallet's list at a contract or mint address named by the transaction; nil when it is unknown.225    public func knownToken(address: String) -> ChainToken? { knownTokens.first { $0.address == address } }226}227228public struct ColdSignedTransaction: Equatable, Sendable {229    public let review: ColdTransactionReview230    /// Transaction identifier, computed on the cold device; empty for a PSBT that still needs other signatures.231    public let id: String232    /// The signed transaction with its QR frames, to carry back to the online device.233    public let export: QRExport234}235236extension WalletService {237    // MARK: Addresses238239    /// What kind of address `text` is, as an English noun phrase with its article; nil when it is none the wallet knows.240    static func foreignFamily(_ text: String) -> (family: ChainFamily, name: String)? {241        let t = text.trimmingCharacters(in: .whitespacesAndNewlines)242        if t.hasPrefix("0x") || t.hasPrefix("0X"), t.utf8.count == 42, Hex.decode(String(t.dropFirst(2))) != nil { return (.evm, "an Ethereum (EVM)") }243        if TronAddress(any: t) != nil { return (.tron, "a TRON") }244        for network in BitcoinNetwork.allCases where (try? BitcoinAddress(t, network: network)) != nil {245            let name = network.mainCounterpart.displayName246            return (.utxo, (["A", "E", "I", "O", "U"].contains(String(name.prefix(1))) ? "an " : "a ") + name)247        }248        if SolanaPublicKey(base58: t) != nil { return (.solana, "a Solana") }249        return nil250    }251252    /// The refusal for a text that is not an address of the expected family.253    static func classifyForeign(_ text: String, expected: ChainFamily, chainName: String, expectedForm: String) -> AddressRefusal {254        let t = text.trimmingCharacters(in: .whitespacesAndNewlines)255        guard !t.isEmpty else { return .empty }256        if let found = foreignFamily(t), found.family != expected { return .wrongFamily(chain: chainName, found: found.name) }257        switch expected {258        case .evm:259            if t.hasPrefix("0x") || t.hasPrefix("0X"), t.utf8.count == 42, Hex.decode(String(t.dropFirst(2))) != nil { return .invalidChecksum(chain: chainName) }260        case .tron:261            if t.utf8.count == 34, t.hasPrefix("T"), Base58.bitcoin.decode(t) != nil { return .invalidChecksum(chain: chainName) }262        case .utxo, .solana:263            break264        }265        return .malformed(chain: chainName, expected: expectedForm)266    }267268    /// Validates a recipient for a chain and says what the user should know about it. No network, no secret.269    /// Errors: `unknownChain`, `address(…)` with the precise reason (wrong family, wrong network, checksum…).270    public func checkAddress(_ text: String, chain id: ChainID) async throws(WalletError) -> AddressCheck {271        try await run {272            guard let kind = ChainRegistry.kind(id) else { throw WalletError.unknownChain(id.rawValue) }273            return try checkAddress(text, kind: kind)274        }275    }276277    func checkAddress(_ text: String, kind: ChainKind) throws -> AddressCheck {278        let t = text.trimmingCharacters(in: .whitespacesAndNewlines)279        let id = ChainRegistry.id(kind)280        guard !t.isEmpty else { throw WalletError.address(.empty) }281        guard t.utf8.count <= 120 else { throw WalletError.address(.malformed(chain: ChainRegistry.descriptor(kind).displayName, expected: "An address is much shorter.")) }282        switch kind {283        case .utxo(let network):284            let coin = network.mainCounterpart.displayName285            do {286                let address = try BitcoinAddress(t, network: network)287                // a CashAddr typed without its prefix parses, but nothing in it says it was meant for this chain288                if let prefix = network.cashAddrPrefix, !address.isLegacyFormat, !t.contains(":") {289                    throw WalletError.address(.missingPrefix(chain: coin, prefix: prefix))290                }291                guard address.type != .witnessUnknown else {292                    throw WalletError.address(.unsupported("This address uses a witness version without assigned meaning; QYVORA does not send to it."))293                }294                var own = false295                // from public profile data, whatever the mainnet gate says: recognising an own address reads no chain296                let stored = profile.bitcoinAccounts[Self.accountKey(network)]297                if let account = stored.flatMap({ try? UTXOAccount(extendedKey: $0.extendedPublicKey, network: network) }),298                   account.locate(scriptPubKey: address.scriptPubKey, searchLimit: 200) != nil { own = true }299                var notes = own ? ["This is an address of this wallet."] : [String]()300                if address.isLegacyFormat, network.cashAddrPrefix != nil {301                    notes.append("This is the legacy form of a Bitcoin Cash address, which is also a valid Bitcoin address: make sure the recipient gave it for Bitcoin Cash.")302                }303                return AddressCheck(chain: id, canonical: address.string, isOwnAddress: own, notes: notes)304            } catch let e as BitcoinAddress.Error {305                // the former Litecoin script form is also a Bitcoin address: say that, not "a Bitcoin address"306                if e == .ambiguousLegacyFormat { throw WalletError.address(.unsupported(Self.describe(e, network: network))) }307                if let found = Self.foreignFamily(t) {308                    if found.family != .utxo { throw WalletError.address(.wrongFamily(chain: coin, found: found.name)) }309                    // an address of the UTXO family that this network refuses: another coin, or another network of this coin310                    for other in BitcoinNetwork.allCases where other != network && (try? BitcoinAddress(t, network: other)) != nil {311                        if other.coin == network.coin { throw WalletError.address(.wrongNetwork(chain: network.displayName, found: other.displayName)) }312                        throw WalletError.address(.wrongFamily(chain: coin, found: found.name))313                    }314                }315                if let prefix = network.cashAddrPrefix, !t.contains(":"), (try? BitcoinAddress(prefix + ":" + t, network: network)) != nil {316                    throw WalletError.address(.missingPrefix(chain: coin, prefix: prefix))317                }318                switch e {319                case .invalidChecksum: throw WalletError.address(.invalidChecksum(chain: coin))320                case .wrongNetwork: throw WalletError.address(.wrongNetwork(chain: network.displayName, found: "another network"))321                case .ambiguousLegacyFormat, .unsupportedAddressType: throw WalletError.address(.unsupported(Self.describe(e, network: network)))322                default: throw WalletError.address(.malformed(chain: coin, expected: Self.describe(e, network: network)))323                }324            }325        case .evm(let network):326            guard let address = EthereumAddress(t) else {327                throw WalletError.address(Self.classifyForeign(t, expected: .evm, chainName: network.displayName,328                                                               expectedForm: "An address on this network is 0x followed by 40 hexadecimal digits."))329            }330            guard !address.isZero else { throw WalletError.address(.zeroAddress) }331            let digits = t.dropFirst(2)332            let hasLower = digits.utf8.contains { $0 >= 0x61 && $0 <= 0x66 }, hasUpper = digits.utf8.contains { $0 >= 0x41 && $0 <= 0x46 }333            var notes = [String]()334            if !(hasLower && hasUpper) { notes.append(EthereumSendWarning.recipientWithoutChecksum.message) }335            let own = address == profile.ethereumAddress336            if own { notes.append("This is this wallet's own address.") }337            return AddressCheck(chain: id, canonical: address.checksummed, isOwnAddress: own, notes: notes)338        case .solana:339            guard let key = SolanaPublicKey(base58: t) else {340                throw WalletError.address(Self.classifyForeign(t, expected: .solana, chainName: "Solana", expectedForm: "A Solana address is 32 to 44 base58 characters."))341            }342            guard !SolanaProgram.reserved.contains(key) else { throw WalletError.address(.unsupported("This is a Solana program, not a wallet: funds sent there are lost.")) }343            var notes = ["A Solana address has no checksum: compare every character with its source."]344            if !key.isOnCurve { notes.append("This address is not a wallet key (it is a program-derived address): only the program it belongs to can move what is sent there.") }345            let own = key.base58 == profile.solanaAddress346            if own { notes.append("This is this wallet's own address.") }347            return AddressCheck(chain: id, canonical: key.base58, isOwnAddress: own, notes: notes)348        case .tron(let tronNetwork):349            if let address = TronAddress(t), address == tronNetwork.burnAddress {350                throw WalletError.address(.unsupported("This is the address in which TRON burns fees: nobody holds its key, and funds sent there are destroyed."))351            }352            guard let address = TronAddress(t) else {353                if TronAddress(hex: t) != nil {354                    throw WalletError.address(.unsupported("This is the hexadecimal form of a TRON address. Give the address in its usual form (34 characters starting with T), whose checksum detects typing errors."))355                }356                throw WalletError.address(Self.classifyForeign(t, expected: .tron, chainName: "TRON", expectedForm: "A TRON address has 34 characters and starts with T."))357            }358            guard !address.isZero else { throw WalletError.address(.zeroAddress) }359            let own = address.base58 == profile.tronAddress360            return AddressCheck(chain: id, canonical: address.base58, isOwnAddress: own, notes: own ? ["This is this wallet's own address."] : [])361        }362    }363364    /// The watch-only account of a UTXO network from public profile data.365    func utxoAccount(_ network: BitcoinNetwork) throws -> UTXOAccount {366        guard Self.isPrimaryUTXO(network) else { return try coinAccount(network) }367        return try bitcoinAccount(network)368    }369370    // MARK: Review assembly371372    func makeReview(kind: ChainKind, from: String?, recipient: String, asset: ChainAsset, amount: UInt256, decimals: Int, symbol: String,373                    expectedFee: UInt256, maximumFee: UInt256, feeLines: [SendFeeLine], totalNative: UInt256, isSendMax: Bool, warnings: [SendWarning],374                    notes: [String], expiresAt: Date?, body: SendReview.Body) -> SendReview {375        let descriptor = ChainRegistry.descriptor(kind)376        let currency = profile.displayCurrency377        let q = quote(descriptor.priceID, currency: currency)378        func fiat(_ base: UInt256) -> Double? {379            guard let q, let units = Double(BaseUnits.format(base, decimals: descriptor.nativeDecimals)), units.isFinite else { return nil }380            return units * q.price381        }382        let fee = SendFee(expected: expectedFee, maximum: maximumFee, symbol: descriptor.nativeSymbol, decimals: descriptor.nativeDecimals,383                          expectedFiat: fiat(expectedFee), maximumFiat: fiat(maximumFee), currency: currency, fiatIsReference: descriptor.isTest,384                          fiatIsStale: q?.isStale ?? false, lines: feeLines)385        return SendReview(id: UUID(), chain: descriptor, createdAt: now(), isMainnet: !descriptor.isTest,386                          unauditedMainnet: !descriptor.isTest && MainnetPolicy.unauditedMainnet, limits: Self.limits(kind), from: from, recipient: recipient,387                          asset: asset, amount: amount, amountDecimals: decimals, amountSymbol: symbol, fee: fee, totalNative: totalNative, isSendMax: isSendMax,388                          warnings: warnings, notes: notes, expiresAt: expiresAt, body: body)389    }390391    /// The EVM token a uniform token stands for: from the wallet's list, or from what the last synchronization detected.392    func evmToken(_ token: ChainToken, network: EthereumNetwork) throws -> TokenInfo {393        guard token.chain == ChainRegistry.id(network), let address = EthereumAddress(token.address) else {394            throw WalletError.ethereum(.tokenNetworkMismatch)395        }396        if let known = knownToken(address, network: network) { return known }397        // only what this session read on chain: a snapshot restored from the previous session is a file, and its398        // symbol and decimals would reach the review of what is signed (QYV-SVC-084)399        if let snapshot = evmSnapshots[network], !snapshot.isFromPreviousSession,400           let detected = snapshot.detectedTokens.first(where: { $0.token.address == address }) { return detected.token }401        if let verified = verifiedTokens["\(network.rawValue):\(address.checksummed)"] { return verified }402        throw WalletError.invalidInput("This token is not in the wallet's list. Add it first.")403    }404405    /// The TRON token a caller's value stands for, as the wallet knows it: from its list, or from what a406    /// synchronization of this session read on chain. The caller's symbol and decimals are not used: nothing in a407    /// TRC-20 transfer states them, so the review would show an amount nobody checked (QYV-SVC-103, as QYV-SVC-084).408    func tronToken(_ token: ChainToken, network: TronNetwork) throws -> ChainToken {409        guard token.chain == ChainRegistry.id(network), let contract = TronAddress(token.address) else { throw WalletError.invalidInput("This token belongs to another network.") }410        if let known = knownTronTokens(network).first(where: { $0.address == contract.base58 }) { return known }411        if let record = tronRecords[network], record.isFromPreviousSession != true,412           let detected = record.holdings.first(where: { !$0.listed && $0.token.address == contract.base58 }) { return detected.token }413        throw WalletError.invalidInput("This token is not in the wallet's list. Add it first.")414    }415416    /// The SPL token a caller's value stands for, as the wallet knows it (see `tronToken`).417    func solanaToken(_ token: ChainToken, network: SolanaNetwork) throws -> ChainToken {418        guard token.chain == ChainRegistry.id(network), let mint = SolanaPublicKey(base58: token.address) else { throw WalletError.invalidInput("This token belongs to another network.") }419        if let known = knownSolanaTokens(network).first(where: { $0.address == mint.base58 }) { return known }420        if let record = solanaRecords[network], record.isFromPreviousSession != true,421           let detected = record.holdings.first(where: { !$0.listed && $0.token.address == mint.base58 }) { return detected.token }422        throw WalletError.invalidInput("This token is not in the wallet's list. Add it first.")423    }424425    // MARK: Sending (public)426427    /// Builds a reviewable payment on any active chain. **Network** (except Bitcoin, built from the last snapshot).428    /// No secret is touched: a watch-only wallet can prepare, and export for a cold device.429    ///430    /// - `asset`: `.native`, or a token of that chain (from `ChainData.tokens` / `detectedTokens`).431    /// - `amount`: base units of the asset; ignored when `options.sendMax`.432    ///433    /// What is checked, on every chain: the recipient (`address(…)` refusals: wrong family, wrong network, checksum),434    /// balances read again on chain, fees bounded, the mainnet gate and the per-transaction limits of an unaudited435    /// build (`exceedsUnauditedLimit`, `unauditedLimitUnverifiable` when no fresh price exists). Then per family:436    /// - UTXO: as `prepareBitcoinSend` (needs a synchronized snapshot of this session).437    /// - EVM: as `prepareEthereumSend`, on the network of the chain (L1 data fee included on Base and OP Mainnet).438    /// - Solana: rent rules, token-account creation, Token-2022 rules, then a simulation by the node439    ///   (`simulationFailed`); a payment identical to one still in flight is refused (`transactionInFlight`).440    /// - TRON: latest irreversible block as reference, bandwidth and energy from the account's resources, activation441    ///   fee of a new recipient, energy from a simulation (`tron(…)` refusals).442    ///443    /// The review carries the warnings to show (first payment to this address, own address, mainnet on an unaudited444    /// build…). Errors: `unknownChain`, `chainNotActive`, `mainnetDisabled`, `offline`, and the family's refusals445    /// (`bitcoinBuild`, `ethereum`, `solana`, `tron`).446    public func prepareSend(chain id: ChainID, asset: ChainAsset, to: String, amount: UInt256,447                            options: SendOptions = SendOptions()) async throws(WalletError) -> SendReview {448        try await run {449            let kind = try activeKind(id)450            // the same validation, with the same precise refusals, on every chain451            let check = try checkAddress(to, kind: kind)452            switch kind {453            case .utxo(let network):454                guard case .native = asset else { throw WalletError.invalidInput("\(network.displayName) has no tokens.") }455                guard options.sendMax || amount.uint64 != nil else { throw WalletError.invalidInput("The amount is too large.") }456                var rate = options.bitcoinFeeRate457                if !Self.isPrimaryUTXO(network) {458                    if rate == nil {459                        let fees = try await coinFeeOptions(network)460                        switch options.feeTier {461                        case .slow: rate = fees.slow.rate462                        case .normal: rate = fees.normal.rate463                        case .fast: rate = fees.fast.rate464                        }465                    }466                    let control = options.coinControl ?? BitcoinCoinControl()467                    var plan = try await prepareCoinSend(network: network, to: check.canonical, amount: amount.uint64 ?? 0, feeRate: rate ?? .minimum(for: network),468                                                         sendMax: options.sendMax, coinControl: control)469                    var protected = false470                    // QYV-APP-062: a payment that only spends coins older than a chain split is valid on the other471                    // chain too. When the wallet holds a coin created after the split, that coin is added to the472                    // payment: a transaction spending a coin that exists on Bitcoin Cash only cannot be replayed.473                    let tip = utxoCoinStates[network]?.snapshot?.tipHeight474                    if Self.forkReplayWarning(plan, tipHeight: tip) != nil, !control.useOnlyRequired,475                       let guardCoin = Self.replayProtectingCoin(utxoCoinStates[network]?.snapshot, excluding: plan) {476                        var withGuard = control477                        withGuard.required.append(guardCoin)478                        if let safer = try? await prepareCoinSend(network: network, to: check.canonical, amount: amount.uint64 ?? 0, feeRate: rate ?? .minimum(for: network),479                                                                  sendMax: options.sendMax, coinControl: withGuard),480                           Self.forkReplayWarning(safer, tipHeight: tip) == nil {481                            plan = safer482                            protected = true483                        }484                    }485                    // A Base58 recipient on Bitcoin Cash is also a Bitcoin address: the review carries the warning as486                    // critical, so that the payment cannot be signed without the user having read it (QYV-SVC-065).487                    var extra = [SendWarning]()488                    if network.cashAddrPrefix != nil,489                       (try? BitcoinAddress(to.trimmingCharacters(in: .whitespacesAndNewlines), network: network))?.isLegacyFormat == true {490                        extra.append(SendWarning(id: Self.legacyAddressWarningID, message: Self.legacyAddressWarningText, isCritical: true))491                    }492                    if let replay = Self.forkReplayWarning(plan, tipHeight: tip) { extra.append(replay) }493                    if protected {494                        extra.append(SendWarning(id: Self.forkReplayProtectedID, message: "The coins chosen for this payment all existed before Bitcoin Cash separated from eCash. A coin of this wallet created after the separation was added, so that the transaction cannot be replayed on eCash or Bitcoin SV. Its value returns to this wallet as change.", isCritical: false))495                    }496                    return review(for: plan, extraWarnings: extra)497                }498                guard network == profile.bitcoinNetwork else { throw WalletError.chainNotActive(network.displayName) }499                if rate == nil {500                    let fees = try await bitcoinFeeOptions()501                    switch options.feeTier {502                    case .slow: rate = fees.slow.rate503                    case .normal: rate = fees.normal.rate504                    case .fast: rate = fees.fast.rate505                    }506                }507                let plan = try await prepareBitcoinSend(to: check.canonical, amount: amount.uint64 ?? 0, feeRate: rate ?? .minimumRelay, sendMax: options.sendMax,508                                                        coinControl: options.coinControl)509                return review(for: plan)510            case .evm(let network):511                var evmAsset = EthereumAsset.ether512                if case .token(let token) = asset { evmAsset = .token(try evmToken(token, network: network)) }513                let tier: EthereumFeeTier514                switch options.feeTier {515                case .slow: tier = .slow516                case .normal: tier = .normal517                case .fast: tier = .fast518                }519                // the text as typed goes down: the EVM path warns about an address without checksum520                let inner = try await prepareEthereumSend(asset: evmAsset, to: to, amount: amount, sendMax: options.sendMax, feeTier: tier,521                                                          replacePending: options.replacePending, allowContractRecipient: options.allowContractRecipient,522                                                          network: network)523                return review(for: inner)524            case .solana(let network):525                return try await prepareSolanaSend(network: network, asset: asset, to: check.canonical, amount: amount, options: options)526            case .tron(let network):527                return try await prepareTronSend(network: network, asset: asset, to: check.canonical, amount: amount, options: options)528            }529        }530    }531532    /// The uniform review of a Bitcoin plan (also for plans made with `prepareBitcoinSend` or `prepareSweepOfExposedBitcoin`).533    public func review(for plan: BitcoinSendPlan) -> SendReview { review(for: plan, extraWarnings: []) }534535    /// Identifier and text of the critical warning of a Bitcoin Cash payment whose recipient was given in Base58.536    static let legacyAddressWarningID = "bch.legacy-address"537    static let legacyAddressWarningText = "The recipient was given in the legacy address format, which is also a valid Bitcoin address. Coins sent to an address that was meant for Bitcoin can only be recovered if its owner holds the key in a Bitcoin Cash wallet (and not at all for most addresses starting with 3). Confirm with the recipient that this address is for Bitcoin Cash."538539    /// Last block Bitcoin Cash shares with eCash (XEC, split of 2020-11-15: block 661648 is Bitcoin Cash's own) and540    /// with Bitcoin SV (split of 2018-11-15: block 556767 is Bitcoin Cash's own). Both chains kept Bitcoin Cash's541    /// SIGHASH_FORKID with fork id 0: a transaction that only spends coins older than a split is valid on both sides.542    static let lastBlockSharedWithECash = 661_647543    static let lastBlockSharedWithBitcoinSV = 556_766544    static let forkReplayWarningID = "bch.replayable-on-forks"545    static let forkReplayProtectedID = "bch.replay-protected"546547    /// The smallest confirmed, unfrozen coin of the wallet created after the split from eCash that the plan does not548    /// already spend; nil when the wallet has none (QYV-APP-062). Heights are the indexer's (tip − confirmations + 1).549    static func replayProtectingCoin(_ snapshot: BitcoinSnapshot?, excluding plan: BitcoinSendPlan) -> BitcoinOutPoint? {550        guard plan.network == .bitcoinCash, let snapshot else { return nil }551        let tip = Int(snapshot.tipHeight)552        let spent = Set(plan.inputs.map(\.outPoint))553        return snapshot.utxos554            .filter { coin in555                guard !coin.isFrozen, coin.confirmations > 0, Int(coin.confirmations) <= tip + 1, !spent.contains(coin.utxo.outPoint) else { return false }556                return tip - Int(coin.confirmations) + 1 > lastBlockSharedWithECash557            }558            .min { $0.value != $1.value ? $0.value < $1.value : $0.id < $1.id }?.utxo.outPoint559    }560561    /// The critical warning of a Bitcoin Cash (main network) payment whose coins were all confirmed before a chain562    /// split: its signatures are valid on the other chain too, where anyone can broadcast it (QYV-APP-062).563    /// The heights are the indexer's; coins confirmed later can still descend from replayed transactions.564    static func forkReplayWarning(_ plan: BitcoinSendPlan, tipHeight: UInt32?) -> SendWarning? {565        guard plan.network == .bitcoinCash, let tip = tipHeight, !plan.inputs.isEmpty else { return nil }566        var newest = 0567        for input in plan.inputs {568            // an unconfirmed coin is not older than a split569            guard input.confirmations > 0, UInt64(input.confirmations) <= UInt64(tip) + 1 else { return nil }570            newest = max(newest, Int(tip) - Int(input.confirmations) + 1)571        }572        guard newest <= lastBlockSharedWithECash else { return nil }573        let chains = newest <= lastBlockSharedWithBitcoinSV ? "eCash (XEC) and Bitcoin SV" : "eCash (XEC)"574        return SendWarning(id: forkReplayWarningID, message: "Every coin of this payment existed before Bitcoin Cash separated from \(chains). The signed transaction is also valid there: anyone can broadcast it on that chain, and the coins you still hold there under the same keys would go to the same recipient. If you still hold coins on that chain, separate them before paying: a payment that also spends a coin existing on Bitcoin Cash only cannot be replayed.", isCritical: true)575    }576577    /// `review(for:)` with warnings that are not properties of the plan (how the recipient was written).578    func review(for plan: BitcoinSendPlan, extraWarnings: [SendWarning]) -> SendReview {579        let kind = ChainKind.utxo(plan.network)580        func critical(_ w: BitcoinSendWarning) -> Bool { w == .unauditedMainnet }581        func name(_ w: BitcoinSendWarning) -> String {582            switch w {583            case .destinationAlreadyPaid: return "btc.destination-already-paid"584            case .firstPaymentToAddress: return "first-payment"585            case .destinationIsOwnAddress: return "own-address"586            case .destinationReused: return "btc.destination-reused"587            case .exposedInputs: return "btc.exposed-inputs"588            case .highFeeShare: return "high-fee-share"589            case .highAbsoluteFee: return "btc.high-absolute-fee"590            case .dustAddedToFee: return "btc.dust-added-to-fee"591            case .unconfirmedInputs: return "btc.unconfirmed-inputs"592            case .mergesAddresses: return "btc.merges-addresses"593            case .unauditedMainnet: return "unaudited-mainnet"594            }595        }596        return makeReview(kind: kind, from: nil, recipient: plan.recipient, asset: .native, amount: UInt256(plan.amount), decimals: plan.network.decimals,597                          symbol: plan.network.ticker, expectedFee: UInt256(plan.fee), maximumFee: UInt256(plan.fee),598                          feeLines: [SendFeeLine(label: "Network fee (\(plan.virtualSize) vB at \(plan.effectiveFeeRate))", amount: UInt256(plan.fee))],599                          totalNative: UInt256(plan.totalSpent), isSendMax: plan.isSendMax,600                          warnings: extraWarnings + plan.warnings.map { SendWarning(id: name($0), message: $0.message, isCritical: critical($0)) },601                          // without SegWit the identifier covers the signatures: it is only known once the transaction is signed602                          notes: plan.network.supportsSegWit ? ["The transaction identifier is \(plan.txid)."] : [], expiresAt: nil, body: .bitcoin(plan))603    }604605    /// The uniform review of an EVM review (also for those made with `prepareEthereumSend` or `revokeApproval`).606    public func review(for inner: EthereumSendReview) -> SendReview {607        let network = inner.network608        let kind = ChainKind.evm(network)609        func name(_ w: EthereumSendWarning) -> (String, Bool) {610            switch w {611            case .recipientWithoutChecksum: return ("evm.no-checksum", false)612            case .recipientIsContract: return ("evm.recipient-is-contract", true)613            case .recipientIsOwnAddress: return ("own-address", false)614            case .firstPaymentToRecipient: return ("first-payment", false)615            case .replacesPendingTransaction: return ("evm.replaces-pending", false)616            case .highFeeShare: return ("high-fee-share", false)617            case .unlimitedApproval: return ("evm.unlimited-approval", true)618            case .blindSigning: return ("blind-signing", true)619            case .unknownTokenContract: return ("evm.unknown-token-contract", false)620            case .revokesApproval: return ("evm.revokes-approval", false)621            case .unauditedMainnet: return ("unaudited-mainnet", true)622            }623        }624        var asset = ChainAsset.native625        var decimals = network.nativeDecimals626        var symbol = network.nativeSymbol627        if case .token(let token) = inner.asset {628            asset = .token(Self.chainToken(token))629            decimals = token.decimals630            symbol = token.symbol631        }632        // expected: the base fee of the block read plus the priority fee, for the whole gas limit, plus the L1 data fee633        let tx = inner.transaction634        let perGas = min(tx.maxFeePerGas, inner.baseFee.addingReportingOverflow(tx.maxPriorityFeePerGas).0)635        let expected = perGas.multipliedReportingOverflow(by: tx.gasLimit).0.addingReportingOverflow(inner.l1DataFee).0636        var lines = [SendFeeLine(label: "Gas (limit \(tx.gasLimit))", amount: inner.maximumFee >= inner.l1DataFee ? inner.maximumFee - inner.l1DataFee : inner.maximumFee)]637        var notes = [String]()638        if !inner.l1DataFee.isZero {639            lines.append(SendFeeLine(label: "L1 data fee (with a margin of one quarter)", amount: inner.l1DataFee))640            notes.append("\(network.displayName) also charges an L1 data fee, quoted by the network for this transaction. It is not a field of the transaction: a cold device cannot verify it.")641        }642        return makeReview(kind: kind, from: inner.from.checksummed, recipient: inner.recipient.checksummed, asset: asset, amount: inner.amount, decimals: decimals,643                          symbol: symbol, expectedFee: min(expected, inner.maximumFee), maximumFee: inner.maximumFee, feeLines: lines,644                          totalNative: inner.maximumTotalCost, isSendMax: inner.isSendMax,645                          warnings: inner.warnings.map { w in646                              let (id, isCritical) = name(w)647                              return SendWarning(id: id, message: w.message, isCritical: isCritical)648                          },649                          notes: notes, expiresAt: nil, body: .evm(inner))650    }651652    /// Signs the reviewed payment locally and broadcasts it. **Needs an unlocked vault (full wallet) and a fresh653    /// authentication (`authenticationRequired` otherwise). Network.**654    ///655    /// On every chain: the key derived for the signature must be the account the vault vouches for, the limits of an656    /// unaudited build are applied again, the signature is verified, the signed transaction must be exactly the one657    /// reviewed, and the identifier is computed locally and compared with the endpoint's (`broadcastMismatch`).658    /// - Solana: simulated again just before signing; a review is signed once — calling again re-sends the same signed659    ///   bytes; a blockhash that expired gives `transactionExpired`.660    /// - TRON: `transactionExpired` after its validity; a refusal by the node is `broadcastRejected` (nothing moved).661    ///662    /// `acknowledged` holds the identifiers of the critical warnings of the review that the user confirmed having663    /// read, one by one. A critical warning that is not in it refuses the signature (`invalidInput`) before anything664    /// else happens: the acknowledgement is a rule of the service, not a courtesy of the screen (QYV-APP-020,665    /// QYV-APP-041, QYV-APP-060, QYV-APP-082).666    public func signAndBroadcast(_ review: SendReview, acknowledged: Set<String>) async throws(WalletError) -> SendResult {667        try Self.requireAcknowledged(review.warnings, acknowledged)668        return try await signAndBroadcast(review)669    }670671    /// Refuses unless every critical warning was acknowledged by its identifier.672    static func requireAcknowledged(_ warnings: [SendWarning], _ acknowledged: Set<String>) throws(WalletError) {673        let missing = warnings.filter { $0.isCritical && !acknowledged.contains($0.id) }674        guard missing.isEmpty else {675            throw WalletError.invalidInput("Nothing was signed: \(missing.count == 1 ? "a critical warning of this review was" : "\(missing.count) critical warnings of this review were") not acknowledged. Read \(missing.count == 1 ? "it" : "them") and confirm \(missing.count == 1 ? "it" : "each one") before signing.")676        }677    }678679    /// The signature itself, without the acknowledgement rule. Internal: the application reaches it only through680    /// `signAndBroadcast(_:acknowledged:)`.681    func signAndBroadcast(_ review: SendReview) async throws(WalletError) -> SendResult {682        try await run {683            // said before any request: a watch-only wallet prepares and exports, it does not sign684            guard try requireWallet() == .full else { throw WalletError.watchOnly }685            guard await vault.isUnlocked else { throw WalletError.vaultLocked }686            try await requireFreshAuthentication()687            switch review.body {688            case .bitcoin(let plan):689                let result = Self.isPrimaryUTXO(plan.network) ? try await signAndBroadcastBitcoin(plan) : try await signAndBroadcastCoin(plan)690                return SendResult(chain: review.chain.id, id: result.txid, raw: result.rawHex, explorerURL: review.chain.explorerTransactionURL(result.txid),691                                  lastValidBlockHeight: nil, expiresAt: nil)692            case .evm(let inner):693                let result = try await signAndBroadcastEthereum(inner)694                return SendResult(chain: review.chain.id, id: result.hash, raw: result.rawHex, explorerURL: review.chain.explorerTransactionURL(result.hash),695                                  lastValidBlockHeight: nil, expiresAt: nil)696            case .solana(let details): return try await signAndBroadcastSolana(review, details: details)697            case .tron(let details): return try await signAndBroadcastTron(review, details: details)698            }699        }700    }701702    /// Where a broadcast transaction stands. **Network** (except on UTXO chains, answered from the last snapshot:703    /// synchronize to refresh it).704    public func track(chain id: ChainID, id transaction: String) async throws(WalletError) -> TransactionStatus {705        try await run {706            switch try activeKind(id) {707            case .utxo(let network) where !Self.isPrimaryUTXO(network):708                return try trackCoin(transaction, network: network)709            case .utxo(let network):710                guard network == profile.bitcoinNetwork, let snapshot = bitcoinSnapshot else { throw WalletError.notSynchronized("Synchronize \(network.displayName) first.") }711                guard let entry = snapshot.transactions.first(where: { $0.txid == transaction.lowercased() }) else { return .notFound }712                guard entry.confirmations > 0 else { return .pending }713                let fee = entry.fee.map { UInt256($0) }714                return UInt64(entry.confirmations) >= UInt64(network.minimumConfirmationsHint)715                    ? .finalized(blockHeight: entry.blockHeight.map { UInt64($0) }, fee: fee)716                    : .confirmed(blockHeight: entry.blockHeight.map { UInt64($0) }, confirmations: UInt64(entry.confirmations), fee: fee)717            case .evm(let network):718                switch try await trackEthereumTransaction(hash: transaction, network: network) {719                case .pending: return .pending720                case .failed(let block, _, let fee): return .failed(blockHeight: block, reason: "The transaction was mined and reverted.", fee: fee)721                case .confirmed(let block, _, let fee):722                    let head = try await verifiedRPC(network).blockNumber()723                    let depth = EthereumRPC.confirmations(of: block, head: head)724                    return depth >= network.finalityConfirmations ? .finalized(blockHeight: block, fee: fee) : .confirmed(blockHeight: block, confirmations: depth, fee: fee)725                }726            case .solana(let network): return try await trackSolana(transaction, network: network)727            case .tron(let network): return try await trackTron(transaction, network: network)728            }729        }730    }731732    func trackSent(_ sent: SentTransaction) async throws -> TransactionStatus {733        switch sent.kind {734        case .solana(let network): return try await trackSolana(sent.id, network: network)735        case .tron(let network): return try await trackTron(sent.id, network: network)736        default: return .notFound737        }738    }739740    // MARK: Tokens (uniform)741742    /// Adds a token by contract or mint address on an active chain. **Network**: the token is read on chain.743    /// `label` is used on Solana only, where a mint carries no symbol (it is the user's own name for the token).744    public func addCustomToken(chain id: ChainID, address: String, label: String? = nil) async throws(WalletError) -> ChainToken {745        try await run {746            switch try activeKind(id) {747            case .utxo(let network): throw WalletError.invalidInput("\(network.displayName) has no tokens.")748            case .evm(let network): return Self.chainToken(try await addEVMToken(address: address, network: network))749            case .solana(let network): return try await addSolanaToken(mint: address, label: label, network: network)750            case .tron(let network): return try await addTronToken(contract: address, network: network)751            }752        }753    }754755    /// Moves a token of `detectedTokens` into the wallet's list. No network: it was read on chain at synchronization.756    public func acceptDetectedToken(_ token: ChainToken) async throws(WalletError) {757        try await run {758            switch ChainRegistry.kind(token.chain) {759            case .evm(let network)?: try await acceptDetectedToken(try evmToken(token, network: network))760            case .solana(let network)?:761                guard let record = solanaRecords[network], let holding = record.holdings.first(where: { !$0.listed && $0.token.id == token.id }) else {762                    throw WalletError.invalidInput("This token is not in the detected list.")763                }764                // only what this session read on chain enters the list (QYV-SVC-102)765                guard record.isFromPreviousSession != true else { throw WalletError.notSynchronized(Self.detectedFromPreviousSessionText) }766                profile.customSolanaTokens.removeAll { $0.id == token.id }767                profile.customSolanaTokens.append(holding.token)768                try saveProfile()769                alignSolanaHoldings(network)770            case .tron(let network)?:771                guard let record = tronRecords[network], let holding = record.holdings.first(where: { !$0.listed && $0.token.id == token.id }) else {772                    throw WalletError.invalidInput("This token is not in the detected list.")773                }774                // only what this session read on chain enters the list (QYV-SVC-102)775                guard record.isFromPreviousSession != true else { throw WalletError.notSynchronized(Self.detectedFromPreviousSessionText) }776                profile.customTronTokens.removeAll { $0.id == token.id }777                profile.customTronTokens.append(holding.token)778                try saveProfile()779                alignTronHoldings(network)780            default: throw WalletError.unknownChain(token.chain.rawValue)781            }782        }783    }784785    /// Removes a custom token from the list (built-in tokens can only be hidden).786    public func removeCustomToken(_ token: ChainToken) async throws(WalletError) {787        try await run {788            switch ChainRegistry.kind(token.chain) {789            case .evm(let network)?: try await removeCustomToken(try evmToken(token, network: network))790            case .solana(let network)?:791                profile.customSolanaTokens.removeAll { $0.id == token.id }792                try saveProfile()793                alignSolanaHoldings(network)794            case .tron(let network)?:795                profile.customTronTokens.removeAll { $0.id == token.id }796                try saveProfile()797                alignTronHoldings(network)798            default: throw WalletError.unknownChain(token.chain.rawValue)799            }800        }801    }802803    /// Hides (or shows again) a token, listed or detected. A hidden token is neither read nor reported.804    public func setTokenHidden(_ hidden: Bool, token: ChainToken) async throws(WalletError) {805        try await run {806            switch ChainRegistry.kind(token.chain) {807            case .evm(let network)?: try await setTokenHidden(hidden, token: try evmToken(token, network: network))808            case .solana(let network)?:809                try setHidden(hidden, id: token.id)810                alignSolanaHoldings(network)811            case .tron(let network)?:812                try setHidden(hidden, id: token.id)813                alignTronHoldings(network)814            default: throw WalletError.unknownChain(token.chain.rawValue)815            }816        }817    }818819    private func setHidden(_ hidden: Bool, id: String) throws {820        var set = Set(profile.hiddenTokens)821        if hidden { set.insert(id) } else { set.remove(id) }822        profile.hiddenTokens = set.sorted()823        try saveProfile()824    }825}826
Files main
Menu

Theme