SPB Git

Repository Public

SendFlow.swift 19.8 KB 434 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Wallet/SendFlow.swift8// Module           : 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 SwiftUI42import QyvoraCore43import QyvoraBitcoin44import QyvoraWallet45import QyvoraUI4647/// State of one payment, from the choice of the asset to the result. It holds no secret: what the user types, the48/// review built by the service and the outcome. The same model serves every chain; what differs by family (fee49/// choice, memo, coin control) is read from the chain's descriptor.50@MainActor51@Observable52final class SendModel {53    enum Step: Equatable { case asset, form, review, export, result }5455    var step: Step = .asset56    var chainID: ChainID?57    /// nil: the coin of the chain.58    var token: ChainToken?5960    var recipient = ""61    var validity: FieldValidity = .empty62    var check: AddressCheck?6364    var amountText = ""65    /// True while the amount is typed in the display currency.66    var amountInFiat = false67    var sendMax = false6869    var tier: FeeTier.Kind = .normal70    var utxoFees: Loadable<BitcoinFeeOptions> = .idle71    /// The service's estimate of the fee of a plain transfer of the chosen asset (EVM and Solana tiers, TRON72    /// resources); nil while it is being read or when it could not be. The review states the real fee.73    var feeQuote: SendFeeQuote?74    /// UTXO chains: custom fee rate in sat/vB, as typed.75    var customRate = ""76    /// Solana: custom compute-unit price in micro-lamports, as typed.77    var customUnitPrice = ""78    var selectedCoins: Set<BitcoinOutPoint> = []79    var onlySelectedCoins = false80    var includeUnconfirmed = false81    var memo = ""82    var replacePending = false83    var allowContract = false84    /// Set once the service refused a contract as the recipient of the coin: the form then offers to proceed.85    var offersAllowContract = false8687    var preparing = false88    var error: String?89    /// Identifier of an identical payment still in flight (`transactionInFlight`): no second one is offered.90    var inFlightID: String?9192    var review: SendReview?93    /// True for a review handed over by the Shield (sweep, revocation): there is no form to go back to.94    var isHandedOver = false95    /// True when the review on screen replaced one that lapsed.96    var wasRefreshed = false97    var acknowledged: Set<String> = []98    var authenticating = false99    var signing = false100    var signError: String?101    var expired = false102103    var export: QRExport?104    var result: SendResult?105106    var descriptor: ChainDescriptor? { chainID?.descriptor }107    var asset: ChainAsset { token.map { .token($0) } ?? .native }108    var decimals: Int { token?.decimals ?? descriptor?.nativeDecimals ?? 0 }109    var symbol: String { token?.symbol ?? descriptor?.nativeSymbol ?? "" }110111    /// True while the wallet may still broadcast what was signed: nothing that would send again is offered.112    var isBusy: Bool { preparing || signing || authenticating }113114    func select(chain: ChainID, token: ChainToken?) {115        if chainID != chain {116            recipient = ""117            validity = .empty118            check = nil119            utxoFees = .idle120            selectedCoins = []121            onlySelectedCoins = false122            memo = ""123            tier = .normal124        }125        if chainID != chain || self.token != token {126            amountText = ""127            amountInFiat = false128            sendMax = false129        }130        chainID = chain131        self.token = token132        error = nil133        inFlightID = nil134        offersAllowContract = false135        allowContract = false136        step = .form137    }138139    /// Balance the payment can draw on, in base units; nil while it is not known.140    func available(_ chain: ChainSnapshot) -> UInt256? {141        guard let data = chain.data.value else { return nil }142        if let token { return (data.tokens + data.detectedTokens).first { $0.token.id == token.id }?.balance.value }143        // unconfirmed coins are spent only when coin control allows them144        return chain.chain.family == .utxo && !includeUnconfirmed ? data.native.confirmed : data.native.total145    }146147    func quote(_ snapshot: WalletSnapshot) -> MarketQuote? {148        if let token { return snapshot.quote(of: token) }149        return descriptor.flatMap { snapshot.quote(of: $0) }150    }151152    /// The amount in base units of the asset; nil when the text is not an amount. In fiat mode the text is divided153    /// by the quote and cut (never rounded up) to the decimals the asset has, eight at most.154    func baseAmount(quote: MarketQuote?) -> UInt256? {155        if amountInFiat {156            guard let quote, quote.price > 0, let fiat = Decimal(string: amountText.replacingOccurrences(of: ",", with: ".")), fiat > 0 else { return nil }157            var units = fiat / Decimal(quote.price), cut = Decimal()158            NSDecimalRound(&cut, &units, min(decimals, 8), .down)159            return WalletChainFormat.baseUnits(NSDecimalNumber(decimal: cut).stringValue, decimals: decimals)160        }161        return WalletChainFormat.baseUnits(amountText, decimals: decimals)162    }163164    func options(watchOnly: Bool) -> SendOptions {165        var o = SendOptions()166        o.sendMax = sendMax167        switch tier {168        case .slow: o.feeTier = .slow169        case .fast: o.feeTier = .fast170        case .normal, .custom: o.feeTier = .normal171        }172        guard let descriptor else { return o }173        switch descriptor.family {174        case .utxo:175            if tier == .custom, let value = Double(customRate.replacingOccurrences(of: ",", with: ".")) { o.bitcoinFeeRate = FeeRate.fromEstimate(satPerVByte: value) }176            if !selectedCoins.isEmpty || includeUnconfirmed {177                o.coinControl = BitcoinCoinControl(required: Array(selectedCoins), useOnlyRequired: onlySelectedCoins && !selectedCoins.isEmpty, includeUnconfirmed: includeUnconfirmed)178            }179        case .evm:180            o.replacePending = replacePending181            o.allowContractRecipient = allowContract182        case .solana:183            if tier == .custom, let price = UInt64(customUnitPrice) { o.solanaComputeUnitPrice = price }184        case .tron:185            break186        }187        let note = memo.trimmingCharacters(in: .whitespacesAndNewlines)188        if supportsMemo, !note.isEmpty { o.memo = note }189        o.forColdSigning = watchOnly190        return o191    }192193    /// A public note exists on Solana (any asset) and on TRON for TRX only.194    var supportsMemo: Bool {195        guard let descriptor, descriptor.capabilities.memo else { return false }196        return descriptor.family == .tron ? token == nil : true197    }198199    /// Why the form cannot be submitted yet; nil when it can.200    func formProblem(chain: ChainSnapshot, quote: MarketQuote?) -> String? {201        guard case .valid = validity else { return "" }202        if tier == .custom {203            if chain.chain.family == .utxo, FeeRate.fromEstimate(satPerVByte: Double(customRate.replacingOccurrences(of: ",", with: ".")) ?? -1) == nil { return "" }204            if chain.chain.family == .solana, UInt64(customUnitPrice) == nil { return "" }205        }206        if sendMax { return nil }207        guard !amountText.isEmpty else { return "" }208        guard let amount = baseAmount(quote: quote), !amount.isZero else { return "Not an amount." }209        if let available = available(chain), amount > available { return "More than the available balance." }210        return nil211    }212213    /// Builds the review with the service. `watchOnly` asks for the longer validity a cold signature needs.214    func prepare(_ wallet: WalletStore, snapshot: WalletSnapshot, refreshing: Bool = false) async {215        guard let chainID, !preparing else { return }216        let amount = sendMax ? UInt256.zero : (baseAmount(quote: quote(snapshot)) ?? .zero)217        let asset = asset, to = check?.canonical ?? recipient.trimmingCharacters(in: .whitespacesAndNewlines), options = options(watchOnly: snapshot.isWatchOnly)218        preparing = true219        error = nil220        signError = nil221        inFlightID = nil222        defer { preparing = false }223        do {224            let built = try await wallet.run { try await $0.prepareSend(chain: chainID, asset: asset, to: to, amount: amount, options: options) }225            review = built226            acknowledged = []227            expired = false228            wasRefreshed = refreshing229            export = nil230            step = .review231        } catch {232            if let e = error as? WalletError {233                if case .transactionInFlight(let id) = e { inFlightID = id }234                if case .ethereum(.recipientIsContract) = e { offersAllowContract = true }235            }236            let message = WalletStore.message(for: error)237            if refreshing { signError = message; expired = true } else { self.error = message }238        }239    }240241    /// When the review on screen stops being valid, as the service states it (TRON: the expiration of the242    /// transaction; Solana: the expected end of its blockhash); nil when it does not expire by time.243    var deadline: Date? { review?.expiresAt }244245    var criticalWarnings: [SendWarning] { review?.warnings.filter(\.isCritical) ?? [] }246    var allAcknowledged: Bool { criticalWarnings.allSatisfy { acknowledged.contains($0.id) } }247}248249/// The one send flow of the wallet, for every chain: asset → recipient, amount and fee → review → signature (or250/// export to a cold device) → result with live status.251struct SendFlow: View {252    @Environment(WalletStore.self) private var wallet253    @Environment(\.dismiss) private var dismiss254    @State private var model = SendModel()255    private let prefill: SendPrefill?256    private let handedReview: SendReview?257258    init(prefill: SendPrefill) {259        self.prefill = prefill260        self.handedReview = nil261    }262263    /// Opens directly at the review of a plan built elsewhere (sweep of exposed coins, revocation of an approval).264    init(review: SendReview) {265        self.prefill = nil266        self.handedReview = review267    }268269    var body: some View {270        Group {271            if let snapshot = wallet.snapshot {272                switch model.step {273                case .asset:274                    SendAssetPicker(model: model, snapshot: snapshot, onClose: close)275                case .form:276                    if let chain = model.chainID.flatMap({ snapshot.chain($0) }) {277                        SendFormView(model: model, chain: chain, snapshot: snapshot, onClose: close)278                    } else {279                        SendAssetPicker(model: model, snapshot: snapshot, onClose: close)280                    }281                case .review, .export:282                    if let review = model.review {283                        SendReviewView(model: model, review: review, snapshot: snapshot, onClose: close)284                    }285                case .result:286                    if let result = model.result {287                        SendResultView(result: result, amountLine: model.review.map { WalletChainFormat.amount($0.amount, decimals: $0.amountDecimals, symbol: $0.amountSymbol) },288                                       onDone: close, onSendAnother: model.isHandedOver ? nil : { restart() })289                    }290                }291            }292        }293        .qSheetChrome(detents: QDetents.full)294        .qAnimation(value: model.step)295        .onAppear { start() }296        #if DEBUG297        .task { await debugFill() }298        #endif299    }300301    func close() { dismiss() }302303    func start() {304        guard model.chainID == nil, model.review == nil else { return }305        if let handedReview {306            model.review = handedReview307            model.chainID = handedReview.chain.id308            model.isHandedOver = true309            model.step = .review310            return311        }312        guard let prefill, let id = prefill.chain, let chain = wallet.snapshot?.activeChain(id) else { return }313        let token = prefill.tokenAddress.flatMap { address in314            (chain.tokens + chain.detectedTokens).first { $0.token.address.caseInsensitiveCompare(address) == .orderedSame }?.token315        }316        // a scanned request for a token this wallet does not list is not silently turned into a payment of the coin317        if prefill.tokenAddress != nil, token == nil {318            model.chainID = chain.id319            model.error = "The scanned request names a token that is not in this wallet's list for \(chain.chain.displayName). Add the token first."320            model.step = .asset321            return322        }323        model.select(chain: chain.id, token: token)324        if let recipient = prefill.recipient { model.recipient = recipient }325        if let amount = prefill.amount { model.amountText = amount }326        if let memo = prefill.memo { model.memo = memo }327    }328329    func restart() {330        let chain = model.chainID, token = model.token331        model = SendModel()332        if let chain { model.select(chain: chain, token: token) }333    }334335    #if DEBUG336    /// `-QYSendTo`, `-QYSendAmount`, `-QYSendMax`, `-QYSendReview`, `-QYSendExport`: fills the form through the same337    /// state as the controls, then asks the service for the review.338    func debugFill() async {339        guard handedReview == nil, DebugLaunch.sendRecipient != nil || DebugLaunch.sendAmount != nil || DebugLaunch.sendMax else { return }340        try? await Task.sleep(for: .milliseconds(400))341        if let to = DebugLaunch.sendRecipient { model.recipient = to }342        if let amount = DebugLaunch.sendAmount { model.amountText = amount }343        if DebugLaunch.sendMax { model.sendMax = true }344        if let tier = DebugLaunch.defaults.string(forKey: "QYSendTier").flatMap(FeeTier.Kind.init(rawValue:)) { model.tier = tier }345        if let memo = DebugLaunch.defaults.string(forKey: "QYSendMemo") { model.memo = memo }346        guard DebugLaunch.sendReview || DebugLaunch.sendExport, let snapshot = wallet.snapshot else { return }347        try? await Task.sleep(for: .milliseconds(1200))348        await model.prepare(wallet, snapshot: snapshot)349        if DebugLaunch.sendExport, let review = model.review {350            model.export = try? await wallet.run { try await $0.exportUnsigned(review) }351            if model.export != nil { model.step = .export }352        }353    }354    #endif355}356357// MARK: - Asset picker358359/// Every asset that can be sent: the coin of each active chain and the tokens that hold a balance, searchable.360struct SendAssetPicker: View {361    @Bindable var model: SendModel362    let snapshot: WalletSnapshot363    let onClose: () -> Void364365    @HideAmounts private var hideAmounts366    @State private var search = ""367368    struct Entry: Identifiable {369        let id: String370        let chain: ChainSnapshot371        let token: ChainToken?372        let name: String373        let symbol: String374        let decimals: Int375        let units: UInt256376        let fiat: String?377        let value: Double378    }379380    var entries: [Entry] {381        var out = [Entry]()382        for chain in snapshot.chains {383            guard let data = chain.data.value else { continue }384            let line = snapshot.nativeLine(chain.id)385            out.append(Entry(id: chain.id.rawValue, chain: chain, token: nil, name: chain.chain.nativeName, symbol: data.native.symbol, decimals: data.native.decimals,386                             units: data.native.total, fiat: WalletChainFormat.fiat(line, currency: snapshot.currency), value: line?.value ?? line?.referenceValue ?? 0))387            for held in data.tokens {388                guard let balance = held.balance.value else { continue }389                let tokenLine = snapshot.tokenLine(held.token)390                out.append(Entry(id: held.id, chain: chain, token: held.token, name: held.token.name, symbol: held.token.symbol, decimals: held.token.decimals,391                                 units: balance, fiat: WalletChainFormat.fiat(tokenLine, currency: snapshot.currency), value: tokenLine?.value ?? tokenLine?.referenceValue ?? 0))392            }393        }394        let q = search.trimmingCharacters(in: .whitespaces).lowercased()395        let filtered = out.filter { entry in396            if q.isEmpty { return !entry.units.isZero }397            return entry.name.lowercased().contains(q) || entry.symbol.lowercased().contains(q) || entry.chain.chain.displayName.lowercased().contains(q)398        }399        return filtered.enumerated().sorted { a, b in a.element.value != b.element.value ? a.element.value > b.element.value : a.offset < b.offset }.map(\.element)400    }401402    var body: some View {403        let entries = entries404        let unread = snapshot.chains.filter { $0.data.value == nil }405        return SendScaffold(title: snapshot.isWatchOnly ? "Prepare a payment" : "Send", subtitle: "Choose what to send", onBack: nil, onClose: onClose) {406            if snapshot.isWatchOnly {407                WarningBanner(.info, title: "Watch-only wallet", message: "This device prepares the transaction and shows it as a QR code; the device that holds the keys signs it.")408            }409            InlineError(message: model.error)410            WalletSearchField(text: $search, prompt: "Search a coin, a token or a network")411            if entries.isEmpty {412                EmptyStateView(systemImage: search.isEmpty ? "tray" : "magnifyingglass", title: search.isEmpty ? "Nothing to send" : "No match",413                               message: search.isEmpty ? "No enabled network holds a balance that was read. Receive first, or synchronize."414                                                       : "No coin or token of the enabled networks matches. Assets without balance appear when searched by name.")415                    .frame(maxWidth: .infinity)416                    .padding(.vertical, QSpace.xl)417            } else {418                QListSection(footnote: unread.isEmpty ? nil : "Not read yet, so not listed: \(unread.map(\.chain.displayName).joined(separator: ", ")).") {419                    ForEach(entries) { entry in420                        Button { model.select(chain: entry.chain.id, token: entry.token) } label: {421                            AssetRow(asset: entry.token.map { .token(symbol: $0.symbol, network: entry.chain.network) } ?? .native(entry.chain.network), name: entry.name,422                                     note: entry.chain.chain.isTest ? entry.chain.chain.shortName : nil, units: entry.units.description, decimals: entry.decimals, symbol: entry.symbol, fiat: entry.fiat, hidden: hideAmounts)423                        }424                        .buttonStyle(.qRow)425                    }426                }427            }428        } footer: {429            EmptyView()430        }431        .qHaptic(.selection, trigger: model.chainID)432    }433}434
Files main
Menu

Theme