SPB Git

Repository Public

SweepExposedSheet.swift 9.9 KB 227 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Security/SweepExposedSheet.swift8// Module           : Security9// 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 SwiftUI42import QyvoraCore43import QyvoraBitcoin44import QyvoraWallet45import QyvoraUI4647extension BitcoinFeeOption.Tier {48    var title: String {49        switch self {50        case .slow: return "Slow"51        case .normal: return "Normal"52        case .fast: return "Fast"53        }54    }5556    var kind: FeeTier.Kind {57        switch self {58        case .slow: return .slow59        case .normal: return .normal60        case .fast: return .fast61        }62    }63}6465/// Prepares the sweep of every output whose public key is on chain to one fresh address of this wallet.66///67/// The plan comes from `prepareSweepOfExposed(chain:)`, for Bitcoin as for Litecoin, Dogecoin and Bitcoin Cash. When68/// the wallet screens installed a review handoff, the plan is handed to their review (`onPlan`); otherwise this sheet69/// shows the plan itself and signs after a fresh authentication.70struct SweepExposedSheet: View {71    /// The UTXO network whose exposed coins are swept.72    let network: BitcoinNetwork73    /// True when a review screen takes the plan over.74    let handsOff: Bool75    let onPlan: (BitcoinSendPlan) -> Void7677    @Environment(WalletStore.self) private var store78    @Environment(\.dismiss) private var dismiss79    @State private var fees: BitcoinFeeOptions?80    @State private var tier: FeeTier.Kind = .normal81    @State private var plan: BitcoinSendPlan?82    @State private var result: SendResult?83    @State private var paidFee: UInt64?84    @State private var error: String?85    @State private var busy = false86    @State private var reauthenticate = false87    @State private var commits = 08889    var body: some View {90        QSheetScaffold("Sweep exposed coins",91                       subtitle: "One transaction moves every output whose public key is on chain to a never-used address of this wallet.",92                       onClose: { dismiss() }) {93            if let result {94                done(result)95            } else if let plan {96                review(plan)97            } else {98                setup99            }100            SecInlineError(error)101        } footer: {102            footer103        }104        .interactiveDismissDisabled(busy)105        .task { await loadFees() }106        .requiresReauthentication(isPresented: $reauthenticate, reason: "Sign the sweep transaction") { sign() }107        .qHaptic(.committed, trigger: commits)108        .qHaptic(trigger: result) { $0 == nil ? nil : .sent }109        .qHaptic(trigger: error) { $0 == nil ? nil : .failed }110    }111112    @ViewBuilder var footer: some View {113        if result != nil {114            Button("Done") { dismiss() }.buttonStyle(.qPrimary)115        } else if plan != nil {116            SlideToConfirm("Slide to sign and broadcast", buttonTitle: "Sign and broadcast", isEnabled: !busy, isWorking: busy) {117                commits += 1118                reauthenticate = true119            }120            Button("Change the fee rate") { plan = nil }121                .buttonStyle(.qSecondary)122                .disabled(busy)123        } else if let fees {124            LoadingButton("Prepare the sweep", loadingTitle: "Building the transaction", systemImage: "arrow.right.arrow.left",125                          state: busy ? .loading : .idle) { prepare(fees) }126        } else if error != nil {127            Button("Try again") { Task { await loadFees() } }.buttonStyle(.qSecondary)128        }129    }130131    @ViewBuilder var setup: some View {132        WarningBanner(.info, message: "The sweep pays a network fee and links the swept addresses together on chain. The new output is protected by a hash of its key until it is spent; this does not make \(network.mainCounterpart.displayName) quantum-resistant.")133        if let fees {134            VStack(alignment: .leading, spacing: QSpace.s) {135                QEyebrow("Fee rate").padding(.leading, 2)136                FeeTierPicker(tiers: fees.all.map { option in137                    FeeTier(option.tier.kind, timeHint: option.targetBlocks.map { "about \($0) block(s)" } ?? "no estimate", fee: nil, rate: option.rate.description)138                }, selection: $tier)139                if fees.source == .minimumRelayFloor {140                    Label("The endpoint gave no usable estimate: every tier is the minimum relay fee.", systemImage: "info.circle")141                        .font(QFont.caption)142                        .foregroundStyle(QColor.textSecondary)143                        .fixedSize(horizontal: false, vertical: true)144                }145            }146        } else if error == nil {147            SecSkeletonSection(title: "Fee rate", rows: 3)148        }149    }150151    @ViewBuilder func review(_ plan: BitcoinSendPlan) -> some View {152        QyvoraUI.NetworkReviewBanner(network: plan.network.qNetwork,153                                     unauditedNotice: !plan.network.isTest && store.snapshot?.unauditedMainnet == true154                                         ? "Unaudited software: per-transaction limits apply." : nil)155        ReviewSection("Transaction to sign") {156            ReviewRow("Amount moved", value: SecChain.amount(plan.amount, on: plan.network), emphasis: .strong)157            ReviewRow("To your address", value: plan.recipient, emphasis: .address)158            ReviewRow("Inputs", value: "\(plan.inputs.count) exposed output(s)")159            ReviewRow("Network fee", value: SecChain.amount(plan.fee, on: plan.network), secondary: "\(plan.effectiveFeeRate.description) · \(plan.virtualSize) vB")160        }161        ForEach(Array(plan.warnings.enumerated()), id: \.offset) { _, warning in162            WarningBanner(.warning, message: warning.message)163        }164    }165166    @ViewBuilder func done(_ result: SendResult) -> some View {167        ResultView(status: .pending, title: "Sweep broadcast",168                   message: "The transaction was accepted by the endpoint. It appears in the activity once seen on the network.",169                   identifier: result.id)170        if let paidFee {171            ReviewSection {172                ReviewRow("Network fee", value: SecChain.amount(paidFee, on: network))173            }174        }175    }176177    func loadFees() async {178        error = nil179        do {180            guard let chain = ChainRegistry.descriptor(of: network)?.id else { return }181            fees = try await store.run { try await $0.feeOptions(chain: chain) }182        } catch {183            self.error = SecurityError.text(error)184        }185    }186187    func prepare(_ fees: BitcoinFeeOptions) {188        guard let option = fees.all.first(where: { $0.tier.kind == tier }), !busy else { return }189        busy = true190        error = nil191        let rate = option.rate192        guard let chain = ChainRegistry.descriptor(of: network)?.id else { return }193        Task {194            do {195                let built = try await store.run { try await $0.prepareSweepOfExposed(chain: chain, feeRate: rate) }196                if handsOff { onPlan(built) } else { plan = built }197            } catch WalletError.exceedsUnauditedLimit(let limit) {198                // the service offers no partial sweep: say what that means instead of a bare refusal199                self.error = "The exposed coins of this wallet are worth more than the limit of this unaudited build (\(limit)). A sweep moves all of them in one transaction, so it is refused as a whole. Move part of them first with ordinary payments to an address of this wallet, using coin control, then sweep the rest."200            } catch {201                self.error = SecurityError.text(error)202            }203            busy = false204        }205    }206207    func sign() {208        guard let plan, !busy else { return }209        busy = true210        error = nil211        Task {212            do {213                // the uniform path signs every UTXO coin (Bitcoin's own call signs Bitcoin only)214                // This minimal review is used only when no review screen is installed. It has no acknowledgement215                // controls, so it states none: the service refuses a plan that carries a critical warning (a main216                // network of an unaudited build), which is then signed from the wallet's review.217                result = try await store.run { service in try await service.signAndBroadcast(await service.review(for: plan), acknowledged: []) }218                paidFee = plan.fee219                self.plan = nil220            } catch {221                self.error = SecurityError.text(error)222            }223            busy = false224        }225    }226}227
Files main
Menu

Theme