SPB Git

Repository Public

SecColdSignView.swift 31.6 KB 580 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Security/SecColdSignView.swift8// Module           : Security9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// 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 QyvoraMath43import QyvoraCore44import QyvoraBitcoin45import QyvoraEthereum46import QyvoraSolana47import QyvoraTron48import QyvoraWallet49import QyvoraUI5051/// Signs a transaction of any chain on the cold device: scan the frames shown by the online device or paste the text,52/// read what the bytes do (`reviewColdTransaction`: decoded on this device, no network, no secret), authenticate, sign53/// (`signColdTransaction`) and show the signed transaction as QR frames for the online device to broadcast.54///55/// What cannot be decoded needs an explicit extra confirmation (blind signing); the service refuses it on a main56/// network while the build is unaudited. A PSBT whose input amounts rest on its own word alone keeps the separate57/// confirmation of QYVORA 1.0 (`signColdTransaction(acceptUnverifiedAmounts:)`).58struct SecColdSignView: View {59    /// What the signature produced, whatever the path that made it.60    private struct Outcome: Equatable {61        let chain: ChainDescriptor62        /// Empty for a PSBT that still needs other signatures.63        let id: String64        let export: QRExport65        let partiallySigned: Bool66        let signaturesAdded: Int?67    }6869    @Environment(WalletStore.self) private var store70    @State private var text = ""71    @State private var input: [String] = []72    @State private var review: ColdTransactionReview?73    @State private var outcome: Outcome?74    @State private var allowBlind = false75    /// Explicit, separate confirmation asked when the input amounts rest on the PSBT's word alone (QYV-SVC-008).76    @State private var acceptUnverified = false77    /// Identifiers of the critical warnings the user acknowledged, one by one. The service asks for them.78    @State private var acknowledged: Set<String> = []79    @State private var error: String?80    @State private var busy = false81    @State private var scanning = false82    @State private var reauthenticate = false83    @State private var commits = 084    @State private var failures = 08586    private var snapshot: WalletSnapshot? { store.snapshot }87    private var isWatchOnly: Bool { snapshot?.profile.kind == .watchOnly }8889    var body: some View {90        SecurityScroll {91            if let outcome {92                done(outcome)93            } else if let review {94                reviewed(review)95            } else {96                entry97            }98        }99        .navigationTitle("Sign a transaction")100        .navigationBarTitleDisplayMode(.inline)101        .sheet(isPresented: $scanning) {102            PayloadScannerSheet(title: "Scan the transaction", prompt: "Keep the code of the online device in the frame") { load($0) }103        }104        .requiresReauthentication(isPresented: $reauthenticate, reason: "Sign this transaction offline") { sign() }105        .qHaptic(.committed, trigger: commits)106        .qHaptic(.failed, trigger: failures)107        .qHaptic(trigger: review?.requiresBlindSigning) { $0 == true ? .warning : nil }108        .sensoryFeedback(.success, trigger: outcome != nil) { _, new in new }109        #if DEBUG110        .task {111            if let payload = SecurityDebug.coldPayload(snapshot: store.snapshot) {112                text = payload113                load(PayloadText.frames(fromPasted: payload))114            }115            if SecurityDebug.action == "sign" {116                for await _ in SecurityDebug.advances() {117                    allowBlind = true118                    acceptUnverified = true119                    acknowledged = Set(review?.warnings.filter(\.isCritical).map(\.id) ?? [])120                    reauthenticate = true121                }122            }123        }124        #endif125    }126127    // MARK: Entry128129    @ViewBuilder private var entry: some View {130        Explanation("Scan the code shown by the online device, or paste the unsigned transaction. The chain is recognised from the bytes; what they do is decoded here before anything is signed.")131        PayloadInputCard(title: "Unsigned transaction", placeholder: "PSBT (cHNidP8B…), 0x02…, or qyvtx1|u|…", text: $text) { scanning = true }132        SecInlineError(error)133        LoadingButton("Review", loadingTitle: "Decoding", systemImage: "doc.text.magnifyingglass", state: busy ? .loading : .idle) {134            load(PayloadText.frames(fromPasted: text))135        }136        .disabled(text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)137        QListSection("Accepted here", footnote: "The chain of the transaction must be enabled on this device, in the same network mode as on the online device.") {138            SecFactRow(label: "Bitcoin", value: "PSBT, base64")139            SecFactRow(label: "Ethereum and EVM networks", value: "Unsigned EIP-1559 payload, 0x02…")140            SecFactRow(label: "Solana and TRON", value: "QYVORA envelope, qyvtx1|u|…")141        }142    }143144    // MARK: Review145146    @ViewBuilder private func reviewed(_ r: ColdTransactionReview) -> some View {147        let network = r.chain.qNetwork148        QyvoraUI.NetworkReviewBanner(network: network,149                            unauditedNotice: !r.chain.isTest && snapshot?.unauditedMainnet != false150                                ? "Unaudited software: per-transaction limits apply and the service refuses what it cannot check offline." : nil)151            .id("network")152        if let refusal = r.signingRefusal {153            WarningBanner(.critical, title: "Not signed on this device", message: refusal)154                .id("refusal")155        }156        let critical = Self.acknowledgeable(r)157        if !critical.isEmpty, r.signingRefusal == nil, !isWatchOnly {158            WarningBanner(.critical, title: critical.count == 1 ? "One warning to acknowledge" : "\(critical.count) warnings to acknowledge",159                          message: "Read what this transaction does, then acknowledge \(critical.count == 1 ? "the warning" : "each warning") under the decoded lines. Signing stays unavailable until then.")160                .id("critical")161        }162        switch r.body {163        case .bitcoin(let psbt): bitcoin(psbt)164        case .evm(let inner): evm(inner)165        case .solana(let decoded): solana(decoded)166        case .tron(let decoded): tron(decoded)167        }168        summary(r)169        // every warning of the service, in its order; a critical one carries its own acknowledgement (the consent170        // to blind signing keeps its separate section below)171        WarningAcknowledgementList(warnings: r.warnings.filter { $0.id != "blind-signing" }, acknowledged: $acknowledged,172                                   showsControls: !isWatchOnly && r.signingRefusal == nil)173            .id("warnings")174        confirmations(r)175        SecInlineError(error)176        if r.signingRefusal != nil {177            Explanation("Nothing can be signed here for this transaction. The lines above are still what its bytes say.")178        } else if isWatchOnly {179            WarningBanner(.info, title: "Watch-only wallet",180                          message: "This device holds public keys only: it can review a transaction but not sign it. Signing happens on the device that holds the keys.")181        } else {182            SlideToConfirm("Slide to sign", buttonTitle: "Sign", isEnabled: canSign(r), isWorking: busy) {183                commits += 1184                reauthenticate = true185            }186            .id("sign")187            Text("Signing needs the vault unlocked and a fresh authentication. It uses no network: the signed transaction leaves this device only as a QR code.")188                .font(QFont.caption)189                .foregroundStyle(QColor.textSecondary)190                .fixedSize(horizontal: false, vertical: true)191        }192        Button("Discard") { reset() }.buttonStyle(.qSecondary).disabled(busy)193    }194195    /// The critical warnings acknowledged one by one (blind signing has its own consent).196    static func acknowledgeable(_ r: ColdTransactionReview) -> [SendWarning] {197        r.warnings.filter { $0.isCritical && $0.id != "blind-signing" }198    }199200    private func canSign(_ r: ColdTransactionReview) -> Bool {201        if r.signingRefusal != nil { return false }202        if !WarningAcknowledgementList.isComplete(Self.acknowledgeable(r), acknowledged) { return false }203        if r.requiresBlindSigning, !allowBlind { return false }204        if case .bitcoin(let psbt) = r.body, needsUnverifiedAcceptance(psbt), unverifiedRefused(psbt) || !acceptUnverified { return false }205        return !busy206    }207208    /// The lines the service wrote from the bytes, in full and in its order. The ones that state a limit of an offline209    /// device are marked.210    private func summary(_ r: ColdTransactionReview) -> some View {211        ReviewSection("Decoded on this device",212                      footnote: "Every line is read from the bytes that will be signed. Marked lines say what an offline device cannot verify: the online device showed those figures when it prepared the transaction.") {213            ForEach(Array(r.summary.enumerated()), id: \.offset) { _, line in214                let limit = Self.statesOfflineLimit(line)215                HStack(alignment: .firstTextBaseline, spacing: QSpace.s) {216                    Image(systemName: limit ? "exclamationmark.triangle" : "circle.fill")217                        .font(limit ? QFont.footnote : .system(size: 5))218                        .foregroundStyle(limit ? QColor.warning : QColor.textTertiary)219                        .frame(width: 18)220                        .accessibilityHidden(true)221                    Text(SecurityFormat.breakingLongTokens(line))222                        .font(QFont.callout)223                        .foregroundStyle(QColor.textPrimary)224                        .fixedSize(horizontal: false, vertical: true)225                        .accessibilityLabel(limit ? "Cannot be verified offline. \(line)" : line)226                }227                .frame(maxWidth: .infinity, alignment: .leading)228                .accessibilityElement(children: .combine)229            }230        }231        .id("summary")232    }233234    static func statesOfflineLimit(_ line: String) -> Bool {235        let lowered = line.lowercased()236        return ["cannot verify", "cannot be computed", "cannot be verified", "without delay", "unknown (", "cannot decode"].contains { lowered.contains($0) }237    }238239    @ViewBuilder private func confirmations(_ r: ColdTransactionReview) -> some View {240        if r.requiresBlindSigning {241            QListSection("Blind signing", footnote: "On a main network this build does not sign what it cannot decode, whatever is chosen here.") {242                Toggle(isOn: $allowBlind) {243                    Text("I trust the source of this transaction and accept to sign a part of it without knowing what it does")244                        .font(QFont.callout)245                        .foregroundStyle(QColor.textPrimary)246                        .fixedSize(horizontal: false, vertical: true)247                }248                .tint(QColor.negative)249                .padding(.vertical, QSpace.m)250                SecTextRow(text: "What cannot be decoded can move any asset or grant any permission of this account.", systemImage: QTone.critical.systemImage, tone: .critical)251            }252            .id("blind")253        }254        if case .bitcoin(let psbt) = r.body, needsUnverifiedAcceptance(psbt) {255            WarningBanner(.critical, title: "The fee is not verified",256                          message: "This PSBT states the amounts of its inputs without the previous transactions, so this device cannot check the fee shown above. A dishonest online device could make the real fee much larger.")257            if unverifiedRefused(psbt) {258                Explanation("On mainnet this build does not sign such a PSBT. Export it again from an up-to-date QYVORA on the online device: it then carries the previous transactions.")259            } else {260                QListSection {261                    Toggle(isOn: $acceptUnverified) {262                        Text("I trust the device that prepared this PSBT and accept that the fee cannot be verified.")263                            .font(QFont.callout)264                            .foregroundStyle(QColor.textPrimary)265                            .fixedSize(horizontal: false, vertical: true)266                    }267                    .tint(QColor.warning)268                    .padding(.vertical, QSpace.m)269                }270            }271        }272    }273274    private func needsUnverifiedAcceptance(_ r: PSBTReview) -> Bool { r.fee != nil && !r.inputAmountsVerified }275276    /// Unverified amounts are never signed on mainnet while the engine is unaudited (the service refuses as well).277    private func unverifiedRefused(_ r: PSBTReview) -> Bool {278        !r.network.isTest && (snapshot?.unauditedMainnet ?? true)279    }280281    // MARK: Bitcoin (PSBT)282283    @ViewBuilder private func bitcoin(_ r: PSBTReview) -> some View {284        ReviewSection("Payment") {285            ReviewRow("Sent to others", value: SecChain.amount(r.sentToOthers, on: r.network), emphasis: .strong)286            ReviewRow("Returning to this wallet", value: SecChain.amount(r.returningToWallet, on: r.network))287            ReviewRow("Fee", value: r.fee.map { SecChain.amount($0, on: r.network) } ?? "Unknown (an input amount is missing)",288                      secondary: r.fee == nil ? nil : (r.inputAmountsVerified ? "Input amounts verified" : "Input amounts NOT verified"))289            ReviewRow("Estimated size", value: "\(r.virtualSizeEstimate) vB")290            ReviewRow("Transaction ID", value: r.txid, emphasis: .mono)291        }292        if r.isFullySigned {293            WarningBanner(.info, message: "Every input of this PSBT is already signed.")294        }295        ReviewSection("Outputs · \(r.outputs.count)", footnote: "Ownership is verified by deriving this wallet's own keys, never taken from the PSBT's claims.") {296            ForEach(r.outputs) { output in297                VStack(alignment: .leading, spacing: 6) {298                    HStack(alignment: .firstTextBaseline) {299                        Text("Output \(output.index)").font(QFont.callout).foregroundStyle(QColor.textSecondary)300                        Spacer(minLength: QSpace.s)301                        Text(SecChain.amount(output.value, on: r.network)).font(QFont.amount).foregroundStyle(QColor.textPrimary)302                    }303                    if let address = output.address {304                        ChunkedAddressText(address, font: QFont.mono.weight(.medium))305                    } else {306                        Text("Script without address form").font(QFont.callout).foregroundStyle(QColor.textSecondary)307                    }308                    if output.isMine {309                        QBadge(output.isChange ? "Yours · change, verified by derivation" : "Yours · verified by derivation", systemImage: "checkmark.circle", tone: .positive)310                        if let path = output.derivationPath {311                            Text(path).font(QFont.mono).foregroundStyle(QColor.textSecondary)312                        }313                    } else {314                        QBadge("Leaves this wallet", systemImage: "arrow.up.right", tone: .warning)315                    }316                }317                .frame(maxWidth: .infinity, alignment: .leading)318                .accessibilityElement(children: .combine)319            }320        }321        .id("outputs")322        ReviewSection("Inputs · \(r.inputs.count)") {323            ForEach(r.inputs) { input in324                VStack(alignment: .leading, spacing: 6) {325                    HStack(alignment: .firstTextBaseline) {326                        Text(MiddleTruncation.truncate(input.outPoint.description, head: 10, tail: 8)).font(QFont.mono).foregroundStyle(QColor.textPrimary)327                        Spacer(minLength: QSpace.s)328                        Text(input.value.map { SecChain.amount($0, on: r.network) } ?? "Amount unknown").font(QFont.amount).foregroundStyle(QColor.textPrimary)329                    }330                    HStack(spacing: 6) {331                        QBadge(input.isMine ? "Yours" : "Not yours", tone: input.isMine ? .positive : .neutral)332                        if input.isSigned { QBadge("Already signed", tone: .neutral) }333                    }334                    if let path = input.derivationPath {335                        Text(path).font(QFont.mono).foregroundStyle(QColor.textSecondary)336                    }337                }338                .frame(maxWidth: .infinity, alignment: .leading)339                .accessibilityElement(children: .combine)340            }341        }342        .id("inputs")343    }344345    // MARK: EVM346347    private func native(_ wei: UInt256, _ network: EthereumNetwork) -> String {348        SecChain.amount(wei, decimals: network.nativeDecimals, symbol: network.nativeSymbol)349    }350351    @ViewBuilder private func evm(_ r: ColdEthereumReview) -> some View {352        ReviewSection("What this transaction does") {353            switch r.call {354            case .etherTransfer:355                ReviewRow("Action", value: "Transfer of \(r.network.nativeSymbol)")356                ReviewRow("Amount", value: native(r.transaction.value, r.network), emphasis: .strong)357                if let to = r.transaction.to { ReviewRow("To", value: to.checksummed, emphasis: .address) }358            case .tokenTransfer(let token, let contract, let to, let amount):359                ReviewRow("Action", value: "Token transfer")360                ReviewRow("Amount", value: Self.tokenAmount(amount, token), emphasis: .strong)361                ReviewRow("Beneficiary", value: to.checksummed, emphasis: .address)362                ReviewRow("Token", value: token.map { "\($0.name) (\($0.symbol))" } ?? "Not in this wallet's token list")363                ReviewRow("Token contract", value: contract.checksummed, emphasis: .address)364            case .tokenApproval(let token, let contract, let spender, let amount):365                ReviewRow("Action", value: amount.isZero ? "Revocation of an allowance" : "Token approval")366                ReviewRow("Allowance", value: ERC20.isUnlimited(amount) ? "Unlimited" : Self.tokenAmount(amount, token), emphasis: .strong)367                ReviewRow("Spender", value: spender.checksummed, emphasis: .address)368                ReviewRow("Token", value: token.map { "\($0.name) (\($0.symbol))" } ?? "Not in this wallet's token list")369                ReviewRow("Token contract", value: contract.checksummed, emphasis: .address)370            case .unknown(let dataHex):371                ReviewRow("Action", value: "Call data QYVORA cannot decode")372                if let to = r.transaction.to { ReviewRow("Contract called", value: to.checksummed, emphasis: .address) }373                ReviewRow("Raw call data · \(dataHex.count / 2) bytes", value: String(dataHex.prefix(600)) + (dataHex.count > 600 ? "…" : ""), emphasis: .mono)374            }375        }376        .id("call")377        ReviewSection("Transaction", footnote: r.network.isOPStack378            ? "On this network a further L1 data fee is charged when the transaction is included. It depends on chain state and cannot be verified offline."379            : nil) {380            if let to = r.transaction.to, !isPlainTransfer(r) { ReviewRow("Transaction to", value: to.checksummed, emphasis: .address) }381            ReviewRow("Value attached", value: native(r.transaction.value, r.network))382            ReviewRow("Nonce", value: "\(r.transaction.nonce)")383            ReviewRow("Gas limit", value: "\(r.transaction.gasLimit)")384            ReviewRow("Maximum fee", value: native(r.maximumFee, r.network))385            ReviewRow("Maximum total cost", value: native(r.maximumTotalCost, r.network), emphasis: .strong)386        }387    }388389    private func isPlainTransfer(_ r: ColdEthereumReview) -> Bool {390        if case .etherTransfer = r.call { return true }391        if case .unknown = r.call { return true }392        return false393    }394395    /// The amount of a token the wallet's list knows, in token units; in base units, and saying so, otherwise.396    static func tokenAmount(_ amount: UInt256, _ token: ChainToken?) -> String {397        if let token { return BaseUnits.format(amount, decimals: token.decimals) + " " + token.symbol }398        return "\(amount.description) base units (decimals unknown)"399    }400401    static func tokenAmount(_ amount: UInt256, _ token: TokenInfo?) -> String {402        if let token { return BaseUnits.format(amount, decimals: token.decimals) + " " + token.symbol }403        return "\(amount.description) base units (decimals unknown)"404    }405406    // MARK: Solana407408    @ViewBuilder private func solana(_ r: SolanaTransactionReview) -> some View {409        ReviewSection("Instructions · \(r.instructions.count)", footnote: "A token of this wallet's list is named by its symbol. For any other token the amount is in base units: an offline device cannot read a token's name from the chain.") {410            ForEach(Array(r.instructions.enumerated()), id: \.offset) { index, instruction in411                VStack(alignment: .leading, spacing: 6) {412                    HStack(spacing: 6) {413                        Text("\(index + 1)").font(QFont.mono).foregroundStyle(QColor.textSecondary)414                        if instruction.isUnknown { QBadge("Not decoded", systemImage: QTone.critical.systemImage, tone: .negative) }415                    }416                    if case .systemTransfer(_, let to, let lamports) = instruction {417                        Text("Transfer \(SolanaAmount.formatLamports(lamports)) SOL")418                            .font(Font.system(.title3, design: .rounded, weight: .semibold).monospacedDigit())419                            .foregroundStyle(QColor.textPrimary)420                        Text("To").font(QFont.callout).foregroundStyle(QColor.textSecondary)421                        ChunkedAddressText(to.base58, font: QFont.mono.weight(.medium))422                    } else if case .tokenTransferChecked(_, _, let mint, let destination, _, let amount, _) = instruction,423                              let known = review?.knownToken(address: mint.base58) {424                        Text("Transfer \(Self.tokenAmount(UInt256(amount), known))")425                            .font(Font.system(.title3, design: .rounded, weight: .semibold).monospacedDigit())426                            .foregroundStyle(QColor.textPrimary)427                        Text("To the token account").font(QFont.callout).foregroundStyle(QColor.textSecondary)428                        ChunkedAddressText(destination.base58, font: QFont.mono.weight(.medium))429                        Text("Mint").font(QFont.callout).foregroundStyle(QColor.textSecondary)430                        ChunkedAddressText(mint.base58, font: QFont.mono.weight(.medium))431                    } else {432                        Text(SecurityFormat.breakingLongTokens(instruction.summary))433                            .font(QFont.callout)434                            .foregroundStyle(QColor.textPrimary)435                            .fixedSize(horizontal: false, vertical: true)436                    }437                }438                .frame(maxWidth: .infinity, alignment: .leading)439                .accessibilityElement(children: .ignore)440                .accessibilityLabel("Instruction \(index + 1): \(instruction.summary)")441            }442        }443        .id("instructions")444        ReviewSection("Transaction", footnote: "A Solana transaction is valid for about a minute after it was prepared: its blockhash expires. Sign and return it without delay.") {445            ReviewRow("Fee payer", value: r.feePayer.base58, emphasis: .address)446            ReviewRow("Signers", value: "\(r.signers.count)")447            ReviewRow("Signature fee", value: SolanaAmount.formatLamports(r.signatureFee) + " SOL")448            ReviewRow("Priority fee", value: r.priorityFee.map { SolanaAmount.formatLamports($0) + " SOL" } ?? "Cannot be computed from this transaction")449            ReviewRow("Recent blockhash", value: r.recentBlockhash, emphasis: .mono)450            if r.usesAddressLookupTables {451                ReviewRow("Address lookup tables", value: "Used: some accounts are not in the message")452            }453        }454    }455456    // MARK: TRON457458    @ViewBuilder private func tron(_ r: TronTransactionReview) -> some View {459        ReviewSection("What this transaction does") {460            switch r.action {461            case .trxTransfer(_, let to, let amountSun):462                ReviewRow("Action", value: "Transfer of TRX")463                ReviewRow("Amount", value: TronUnits.formatTRX(amountSun) + " TRX", emphasis: .strong)464                ReviewRow("To", value: to.base58, emphasis: .address)465            case .trc20Transfer(_, let token, let to, let amount):466                ReviewRow("Action", value: "TRC-20 token transfer")467                let known = review?.knownToken(address: token.base58)468                ReviewRow("Amount", value: Self.tokenAmount(amount, known), emphasis: .strong)469                ReviewRow("To", value: to.base58, emphasis: .address)470                ReviewRow("Token", value: known.map { "\($0.name) (\($0.symbol))" } ?? "Not in this wallet's token list")471                ReviewRow("Token contract", value: token.base58, emphasis: .address)472            case .trc20Approve(_, let token, let spender, let amount):473                ReviewRow("Action", value: amount.isZero ? "Revocation of an allowance" : "TRC-20 approval")474                let known = review?.knownToken(address: token.base58)475                ReviewRow("Allowance", value: ERC20.isUnlimited(amount) ? "Unlimited" : Self.tokenAmount(amount, known), emphasis: .strong)476                ReviewRow("Spender", value: spender.base58, emphasis: .address)477                ReviewRow("Token", value: known.map { "\($0.name) (\($0.symbol))" } ?? "Not in this wallet's token list")478                ReviewRow("Token contract", value: token.base58, emphasis: .address)479            case .contractCall(_, let contract, let callValueSun, let data, _, _):480                ReviewRow("Action", value: "Contract call QYVORA shows raw")481                ReviewRow("Contract", value: contract.base58, emphasis: .address)482                ReviewRow("TRX attached", value: TronUnits.formatTRX(callValueSun) + " TRX")483                ReviewRow("Call data · \(data.count) bytes", value: Hex.encode(Bytes(data.prefix(300))) + (data.count > 300 ? "…" : ""), emphasis: .mono)484            case .unknownContract(let type, let typeName, _, let value):485                ReviewRow("Action", value: "Contract QYVORA cannot decode")486                ReviewRow("Contract type", value: typeName ?? String(type))487                ReviewRow("Size", value: "\(value.count) bytes")488            }489            if let memo = r.memoText { ReviewRow("Public note", value: memo) }490        }491        .id("call")492        ReviewSection("Transaction") {493            if let owner = r.owner { ReviewRow("From", value: owner.base58, emphasis: .address) }494            ReviewRow("Fee limit", value: r.feeLimitSun > 0 ? TronUnits.formatTRX(r.feeLimitSun) + " TRX" : "None set")495            ReviewRow("Valid until", value: r.expirationDate.formatted(date: .abbreviated, time: .standard))496            ReviewRow("Transaction ID", value: r.txIDHex, emphasis: .mono)497        }498    }499500    // MARK: Result501502    @ViewBuilder private func done(_ outcome: Outcome) -> some View {503        ResultView(status: outcome.partiallySigned ? .pending : .sent,504                   title: outcome.partiallySigned ? "Partially signed" : "Signed, not broadcast",505                   message: outcome.partiallySigned506                       ? "This PSBT still needs other signatures. Show this code to the next signer or to the online device. Nothing was sent from this device."507                       : "Show this code to the online device, which broadcasts the transaction. Nothing was sent from this device.",508                   identifier: outcome.id.isEmpty ? nil : outcome.id, network: outcome.chain.qNetwork)509        if let added = outcome.signaturesAdded {510            Text("\(added) signature\(added == 1 ? "" : "s") added by this device.")511                .font(QFont.callout)512                .foregroundStyle(QColor.textSecondary)513                .frame(maxWidth: .infinity, alignment: .center)514        }515        QRExportCard(frames: outcome.export.frames, text: outcome.export.text, label: "Signed transaction")516            .id("qr")517        if outcome.chain.family == .solana {518            WarningBanner(.warning, message: "A Solana transaction expires about a minute after it was prepared: scan this code on the online device now.")519        }520        Button("Sign another") { reset() }.buttonStyle(.qSecondary)521    }522523    // MARK: Actions524525    private func reset() {526        text = ""527        input = []528        review = nil529        outcome = nil530        allowBlind = false531        acceptUnverified = false532        acknowledged = []533        error = nil534    }535536    private func load(_ frames: [String]) {537        guard !frames.isEmpty, !busy else { return }538        busy = true539        error = nil540        allowBlind = false541        acceptUnverified = false542        acknowledged = []543        Task {544            do {545                review = try await store.run { try await $0.reviewColdTransaction(frames) }546                input = frames547            } catch {548                self.error = SecurityError.text(error)549                failures += 1550            }551            busy = false552        }553    }554555    private func sign() {556        guard !input.isEmpty, !busy, let review else { return }557        busy = true558        error = nil559        let frames = input560        let blind = review.requiresBlindSigning && allowBlind561        var accepts = false562        if case .bitcoin(let psbt) = review.body { accepts = needsUnverifiedAcceptance(psbt) && acceptUnverified }563        let unverifiedPSBT = accepts564        let confirmed = acknowledged565        Task {566            do {567                // one call for every chain; the separate confirmation of unverified input amounts concerns a PSBT only568                let signed = try await store.run { try await $0.signColdTransaction(frames, allowBlindSigning: blind, acceptUnverifiedAmounts: unverifiedPSBT, acknowledged: confirmed) }569                var partial = false570                if case .bitcoin(let psbt) = signed.review.body { partial = !psbt.isFullySigned }571                outcome = Outcome(chain: signed.review.chain, id: signed.id, export: signed.export, partiallySigned: partial, signaturesAdded: nil)572            } catch {573                self.error = SecurityError.text(error)574                failures += 1575            }576            busy = false577        }578    }579}580
Files main
Menu

Theme