SPB Git

Repository Public

SendReviewView.swift 23.9 KB 436 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Wallet/SendReviewView.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 QyvoraEthereum45import QyvoraWallet46import QyvoraUI4748/// The review of a payment, built entirely from the service's `SendReview`: the network first, then the recipient,49/// the amount, the fee (expected and maximum), the most that can leave the account, every warning with its sentence,50/// and what only the family of the chain has. A full wallet signs here after a fresh authentication; a watch-only51/// wallet exports the transaction for a cold device and imports it back signed.52struct SendReviewView: View {53    @Bindable var model: SendModel54    let review: SendReview55    let snapshot: WalletSnapshot56    let onClose: () -> Void5758    @Environment(WalletStore.self) private var wallet59    @State private var importing = false60    @State private var exporting = false6162    var chain: ChainDescriptor { review.chain }63    var nativeQuote: MarketQuote? { snapshot.quote(of: chain) }64    var canGoBack: Bool { !model.isHandedOver && !model.isBusy }6566    var body: some View {67        Group {68            if model.step == .export, let export = model.export {69                exportStep(export)70            } else {71                reviewStep72            }73        }74        .requiresReauthentication(isPresented: $model.authenticating, reason: "Sign and broadcast this \(chain.displayName) transaction") { sign() }75        .sheet(isPresented: $importing) {76            SignedImportSheet(title: "Signed transaction") { frames in broadcast(frames) }77        }78        .task(id: review.id) { await watchDeadline() }79        .qHaptic(trigger: model.signError) { $0 == nil ? nil : .failed }80        .qHaptic(.warning, trigger: model.expired)81    }8283    // MARK: Review8485    var reviewStep: some View {86        SendScaffold(title: "Review", subtitle: snapshot.isWatchOnly ? "Nothing is signed on this device" : "Nothing is signed until you confirm",87                     onBack: canGoBack ? { model.step = .form } : nil, onClose: onClose) {88            NetworkReviewBanner(network: chain.qNetwork, unauditedNotice: review.unauditedMainnet ? snapshot.unauditedNotice ?? "Real funds, unaudited cryptography. Per-transaction limits apply." : nil)89            if model.wasRefreshed {90                WalletNoteLine(text: "The previous review lapsed and was built again from the current state of the chain. Figures may have changed: read them again.",91                               systemImage: "arrow.triangle.2.circlepath", tone: QColor.warning)92            }93            expiry94            payment95            fee.id("fee")96            total97            warnings.id("warnings")98            if let limits = review.limits { WalletLimitsCard(limits: limits) }99            details.id("details")100            if !review.notes.isEmpty {101                VStack(alignment: .leading, spacing: QSpace.s) {102                    ForEach(review.notes, id: \.self) { WalletNoteLine(text: $0) }103                }104            }105        } footer: {106            InlineError(message: model.signError)107            if model.expired {108                if canGoBack || !model.isHandedOver {109                    Button("Build the review again") { Task { await model.prepare(wallet, snapshot: wallet.snapshot ?? snapshot, refreshing: true) } }110                        .buttonStyle(.qPrimary)111                        .disabled(model.isBusy)112                } else {113                    Text("Close this sheet and build the transaction again from the Shield.").font(QFont.callout).foregroundStyle(QColor.textSecondary)114                }115            } else if snapshot.isWatchOnly {116                LoadingButton("Export for signing", loadingTitle: "Preparing the QR code", systemImage: "qrcode", state: exporting ? .loading : .idle) { export() }117                    .disabled(exporting || !chain.capabilities.coldSigning)118                if !model.criticalWarnings.isEmpty {119                    Text("The warning\(model.criticalWarnings.count == 1 ? "" : "s") above \(model.criticalWarnings.count == 1 ? "is" : "are") acknowledged on the device that signs, which shows \(model.criticalWarnings.count == 1 ? "it" : "them") again from the bytes it receives.")120                        .font(QFont.caption).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)121                }122                if !chain.capabilities.coldSigning {123                    Text("Cold signing is not available for \(chain.displayName) yet: a payment on this network is signed on the device that holds the keys.")124                        .font(QFont.caption).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)125                }126                Button { importing = true } label: { Label("Import the signed transaction", systemImage: "qrcode.viewfinder").frame(maxWidth: .infinity) }127                    .buttonStyle(.qSecondary)128            } else {129                if !model.allAcknowledged {130                    Text("Acknowledge the warning\(model.criticalWarnings.count == 1 ? "" : "s") above to sign.")131                        .font(QFont.caption).foregroundStyle(QColor.textSecondary)132                }133                SlideToConfirm("Slide to sign and send", buttonTitle: "Sign and send", isEnabled: model.allAcknowledged && !model.isBusy, isWorking: model.signing) {134                    model.signError = nil135                    model.authenticating = true136                }137            }138        }139    }140141    /// Validity of the prepared transaction, counted down. A lapsed review is built again when that is possible.142    @ViewBuilder var expiry: some View {143        if model.expired {144            WarningBanner(.warning, title: "This review is no longer valid", message: "The prepared transaction can no longer be executed. Build it again from the current state of the chain.")145        } else if let deadline = model.deadline {146            TimelineView(.periodic(from: .now, by: 1)) { context in147                let remaining = max(0, deadline.timeIntervalSince(context.date))148                HStack(spacing: QSpace.s) {149                    Image(systemName: "timer").foregroundStyle(remaining < 20 ? QColor.warning : QColor.textSecondary)150                    Text(review.chain.family == .solana ? "Tied to a recent blockhash: valid about" : "Valid for")151                        .font(QFont.callout).foregroundStyle(QColor.textSecondary)152                    Text(CountdownFormat.text(remaining)).font(QFont.amount).foregroundStyle(remaining < 20 ? QColor.warning : QColor.textPrimary)153                        .qNumericTransition()154                    Spacer(minLength: 0)155                }156                .accessibilityElement(children: .ignore)157                .accessibilityLabel("This review stays valid for about \(Int(remaining)) seconds")158            }159        }160    }161162    var payment: some View {163        ReviewSection(model.isHandedOver ? "Transaction" : "Payment") {164            if let from = review.from { ReviewRow("From", value: from, emphasis: .address) }165            ReviewRow("To", value: review.recipient, emphasis: .address, copyValue: review.recipient)166            ReviewRow(review.isSendMax ? "Amount (everything)" : "Amount",167                      value: WalletChainFormat.amount(review.amount, decimals: review.amountDecimals, symbol: review.amountSymbol),168                      secondary: amountFiat, emphasis: .strong)169            if case .token(let token) = review.asset {170                ReviewRow(chain.family == .solana ? "Token mint" : "Token contract", value: token.address, emphasis: .address)171                if token.isCustom {172                    // the decimals of a token added by its address were read from the network: the amount that is173                    // signed is the one in base units (QYV-SVC-044)174                    ReviewRow("Amount in base units, as signed", value: review.amount.description,175                              secondary: "This token was added by its address: its \(review.amountDecimals) decimals come from the endpoint that answered, not from the built-in list.",176                              emphasis: .mono)177                }178            }179        }180        .privacySensitive()181    }182183    var amountFiat: String? {184        switch review.asset {185        case .native: return WalletChainFormat.fiat(units: review.amount, decimals: review.amountDecimals, quote: nativeQuote, isTest: chain.isTest)186        case .token(let token): return WalletChainFormat.fiat(units: review.amount, decimals: review.amountDecimals, quote: snapshot.quote(of: token), isTest: chain.isTest)187        }188    }189190    func feeFiat(_ value: Double?) -> String? {191        value.map { (review.fee.fiatIsReference ? "ref. " : "") + WalletFormat.fiat($0, review.fee.currency) }192    }193194    var feeFootnote: String? {195        var parts = [String]()196        if review.fee.expectedFiat != nil || review.fee.maximumFiat != nil {197            if review.fee.fiatIsReference { parts.append("Fiat figures are a reference at main-network prices: test coins have no value.") }198            if review.fee.fiatIsStale { parts.append("The price used is not current" + (nativeQuote.map { " (\($0.fetchedAt.formatted(date: .abbreviated, time: .shortened)))" } ?? "") + ".") }199        } else {200            parts.append("No price is known for \(review.fee.symbol): the fee is shown in the coin only.")201        }202        return parts.isEmpty ? nil : parts.joined(separator: " ")203    }204205    var fee: some View {206        ReviewSection("Network fee", footnote: feeFootnote) {207            ReviewRow("Expected", value: WalletChainFormat.amount(review.fee.expected, decimals: review.fee.decimals, symbol: review.fee.symbol),208                      secondary: feeFiat(review.fee.expectedFiat))209            if review.fee.maximum != review.fee.expected {210                ReviewRow("At most", value: WalletChainFormat.amount(review.fee.maximum, decimals: review.fee.decimals, symbol: review.fee.symbol),211                          secondary: feeFiat(review.fee.maximumFiat))212            }213            ForEach(Array(review.fee.lines.enumerated()), id: \.offset) { _, line in214                ReviewRow(line.label, value: WalletChainFormat.amount(line.amount, decimals: review.fee.decimals, symbol: review.fee.symbol))215            }216        }217    }218219    var total: some View {220        ReviewSection(footnote: totalFootnote) {221            ReviewRow("Most \(review.fee.symbol) that can leave the account", value: WalletChainFormat.native(review.totalNative, chain),222                      secondary: WalletChainFormat.fiat(units: review.totalNative, decimals: chain.nativeDecimals, quote: nativeQuote, isTest: chain.isTest),223                      emphasis: .strong)224        }225        .privacySensitive()226    }227228    var totalFootnote: String? {229        if case .token = review.asset {230            return "Plus \(WalletChainFormat.amount(review.amount, decimals: review.amountDecimals, symbol: review.amountSymbol)) of the token."231        }232        return "The amount, the maximum fee and anything else this transaction locks."233    }234235    /// Every warning of the service, with its sentence. A critical one carries a switch that must be turned on; the236    /// identifiers acknowledged go to the service with the signature request, which refuses without them.237    var warnings: some View {238        WarningAcknowledgementList(warnings: review.warnings, acknowledged: $model.acknowledged, showsControls: !snapshot.isWatchOnly,239                                   informative: ["tron.node-checked", "bch.replay-protected"])240    }241242    // MARK: Family details243244    @ViewBuilder var details: some View {245        switch review.body {246        case .bitcoin(let plan): bitcoinDetails(plan)247        case .evm(let inner): evmDetails(inner)248        case .solana(let details):249            let plan = details.plan250            ReviewSection("Solana details", footnote: "Simulated by the node on current chain state just before this review; simulated again before the signature.") {251                ReviewRow("Signature fee", value: WalletChainFormat.sol(plan.signatureFee))252                ReviewRow("Priority fee", value: WalletChainFormat.sol(plan.priorityFee),253                          secondary: "\(plan.computeUnitPrice.formatted()) µ-lamports × \(plan.computeUnitLimit.formatted()) units reserved")254                ReviewRow("Units used in the simulation", value: details.simulatedUnits.map { $0.formatted() } ?? "Not reported by the node")255                if plan.accountCreationCost > 0 {256                    ReviewRow("New token account for the recipient", value: WalletChainFormat.sol(plan.accountCreationCost),257                              secondary: "Locked in that account; it belongs to the recipient. Not a fee")258                } else if case .token = review.asset {259                    ReviewRow("New token account for the recipient", value: "None needed")260                }261                ReviewRow("Your SOL after the payment", value: WalletChainFormat.sol(plan.senderLamportsAfter))262                ReviewRow("Last valid block height", value: details.lastValidBlockHeight.formatted(.number.grouping(.never)))263            }264        case .tron(let details):265            let plan = details.plan266            ReviewSection("TRON details", footnote: "Resources as the account stands now. If its free resources are used up before the transaction is included, it burns more, up to the maximum fee above.") {267                ReviewRow("Bandwidth", value: "\(plan.bandwidthBytes.formatted()) bytes", secondary: bandwidthText(details))268                if plan.energyLimit > 0 || plan.energyEstimate > 0 {269                    ReviewRow("Energy", value: "\(plan.energyEstimate.formatted()) units simulated",270                              secondary: "Limit \(plan.energyLimit.formatted()) · the account has \(plan.energyAvailable.formatted())"271                                + (plan.energyFeeSun > 0 ? " · \(WalletChainFormat.trx(plan.energyFeeSun)) burned" : " · nothing burned"))272                    ReviewRow("Fee limit of the call", value: WalletChainFormat.trx(plan.feeLimitSun))273                }274                if plan.activationFeeSun > 0 { ReviewRow("Activation of the recipient", value: WalletChainFormat.trx(plan.activationFeeSun), secondary: "The address is new: this payment creates it") }275                if plan.memoFeeSun > 0 { ReviewRow("Note", value: WalletChainFormat.trx(plan.memoFeeSun)) }276                ReviewRow("Valid until", value: details.expiresAt.formatted(date: .omitted, time: .standard))277            }278        }279    }280281    func bandwidthText(_ details: TronSendDetails) -> String {282        let plan = details.plan283        switch plan.bandwidthSource {284        case .staked: return "From staked bandwidth: nothing burned"285        case .free: return "From the free daily allowance: nothing burned"286        case .burned: return "Neither allowance covers it: \(WalletChainFormat.trx(plan.bandwidthFeeSun)) burned"287        case .accountCreation: return "Replaced by the account-creation fee"288        }289    }290291    func bitcoinDetails(_ plan: BitcoinSendPlan) -> some View {292        let symbol = chain.nativeSymbol, decimals = chain.nativeDecimals293        func coins(_ value: UInt64) -> String { WalletChainFormat.amount(UInt256(value), decimals: decimals, symbol: symbol) }294        return ReviewSection("\(chain.nativeName) details", footnote: "Size \(plan.virtualSize) vB at \(plan.effectiveFeeRate.description) (asked: \(plan.targetFeeRate.description)).") {295            ReviewRow("Coins spent", value: "\(plan.inputs.count)", secondary: coins(plan.inputs.reduce(0) { $0 + $1.value }))296            ForEach(plan.inputs.prefix(6)) { input in297                ReviewRow(input.address.map { MiddleTruncation.truncate($0, head: 10, tail: 6) } ?? "Coin without address form", value: coins(input.value),298                          secondary: WalletFormat.exposureLabel(input.exposure) + (input.confirmations == 0 ? " · unconfirmed" : ""))299            }300            if plan.inputs.count > 6 { ReviewRow("Other coins", value: "\(plan.inputs.count - 6) more") }301            if let change = plan.changeAddress, plan.changeValue > 0 {302                ReviewRow("Change, back to this wallet", value: coins(plan.changeValue), secondary: MiddleTruncation.truncate(change, head: 10, tail: 6))303            } else {304                ReviewRow("Change", value: "None")305            }306        }307        .privacySensitive()308    }309310    func evmDetails(_ inner: EthereumSendReview) -> some View {311        ReviewSection("\(chain.displayName) details") {312            switch inner.call {313            case .etherTransfer:314                ReviewRow("Call", value: "Plain transfer, no call data")315            case .tokenTransfer(let token, let contract, let to, let amount):316                ReviewRow("Call", value: "transfer", secondary: "Decoded from the call data that will be signed")317                ReviewRow("Token contract called", value: contract.checksummed, emphasis: .address)318                ReviewRow("Beneficiary in the call", value: to.checksummed, emphasis: .address)319                ReviewRow("Amount in the call", value: token.map { WalletChainFormat.amount(amount, decimals: $0.decimals, symbol: $0.symbol) } ?? "\(amount.description) base units")320            case .tokenApproval(let token, let contract, let spender, let amount):321                ReviewRow("Call", value: amount.isZero ? "approve, set to zero (revocation)" : "approve", secondary: "Decoded from the call data that will be signed")322                ReviewRow("Token contract called", value: contract.checksummed, emphasis: .address)323                ReviewRow("Spender", value: spender.checksummed, emphasis: .address)324                ReviewRow("Allowance", value: token.map { WalletChainFormat.amount(amount, decimals: $0.decimals, symbol: $0.symbol) } ?? "\(amount.description) base units")325            case .unknown(let dataHex):326                ReviewRow("Call data, not decoded", value: dataHex, emphasis: .mono)327            }328            ReviewRow("Nonce", value: String(inner.nonce))329            ReviewRow("Gas limit", value: inner.gasLimit.formatted())330            ReviewRow("Maximum fee per gas", value: gwei(inner.transaction.maxFeePerGas), secondary: "Base fee of the block read: \(gwei(inner.baseFee))")331            ReviewRow("Priority fee per gas", value: gwei(inner.transaction.maxPriorityFeePerGas))332            if !inner.l1DataFee.isZero {333                ReviewRow("L1 data fee", value: WalletChainFormat.native(inner.l1DataFee, chain), secondary: "Quoted by the network, with a margin; included in the maximum fee")334            }335            ReviewRow("Chain ID", value: String(inner.transaction.chainID))336        }337    }338339    func gwei(_ wei: UInt256) -> String { BaseUnits.format(wei, decimals: 9, maxFractionDigits: 4) + " gwei" }340341    // MARK: Export342343    func exportStep(_ export: QRExport) -> some View {344        SendScaffold(title: "Sign on the cold device", subtitle: chain.qNetwork.fullName, onBack: model.isBusy ? nil : { model.step = .review }, onClose: onClose) {345            NetworkReviewBanner(network: chain.qNetwork, unauditedNotice: review.unauditedMainnet ? snapshot.unauditedNotice : nil)346            expiry347            ColdExportView(export: export, payloadName: payloadName, urgency: urgency)348            InlineError(message: model.signError)349        } footer: {350            LoadingButton("Import the signed transaction", loadingTitle: "Checking and broadcasting", systemImage: "qrcode.viewfinder", state: model.signing ? .loading : .idle) {351                importing = true352            }353            .disabled(model.signing)354        }355    }356357    var payloadName: String {358        if case .bitcoin = review.body { return "PSBT" }359        return "unsigned transaction"360    }361362    var urgency: String? {363        switch review.body {364        case .solana: return "A Solana transaction is valid for about a minute after it was prepared: scan, sign and bring it back without delay."365        case .tron: return "This TRON transaction must be signed and broadcast before \(review.expiresAt?.formatted(date: .omitted, time: .shortened) ?? "it expires")."366        case .bitcoin, .evm: return nil367        }368    }369370    // MARK: Actions371372    /// Waits for the validity of the review to lapse, then builds it again when the form is still there and nothing373    /// is being signed. A review being authenticated or exported is never replaced under the user's eyes.374    func watchDeadline() async {375        guard let deadline = model.deadline else { return }376        let wait = deadline.timeIntervalSinceNow377        if wait > 0 { try? await Task.sleep(for: .seconds(wait)) }378        guard !Task.isCancelled, model.result == nil, model.review?.id == review.id, model.step == .review || model.step == .export else { return }379        if model.isHandedOver || model.isBusy || model.step == .export {380            model.expired = true381        } else {382            await model.prepare(wallet, snapshot: wallet.snapshot ?? snapshot, refreshing: true)383        }384    }385386    func sign() {387        guard !model.signing else { return }388        model.signing = true389        model.signError = nil390        let reviewed = review391        Task {392            defer { model.signing = false }393            do {394                let acknowledged = model.acknowledged395                model.result = try await wallet.run { try await $0.signAndBroadcast(reviewed, acknowledged: acknowledged) }396                model.step = .result397            } catch {398                if case .transactionExpired? = error as? WalletError { model.expired = true }399                if case .stalePlan? = error as? WalletError { model.expired = true }400                model.signError = WalletStore.message(for: error)401            }402        }403    }404405    func export() {406        guard !exporting else { return }407        exporting = true408        model.signError = nil409        let reviewed = review410        Task {411            defer { exporting = false }412            do {413                model.export = try await wallet.run { try await $0.exportUnsigned(reviewed) }414                model.step = .export415            } catch {416                model.signError = WalletStore.message(for: error)417            }418        }419    }420421    func broadcast(_ frames: [String]) {422        guard !model.signing else { return }423        model.signing = true424        model.signError = nil425        Task {426            defer { model.signing = false }427            do {428                model.result = try await wallet.run { try await $0.broadcastSigned(frames) }429                model.step = .result430            } catch {431                model.signError = WalletStore.message(for: error)432            }433        }434    }435}436
Files main
Menu

Theme