SPB Git

Repository Public

RevokeApprovalSheet.swift 7.3 KB 172 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Security/RevokeApprovalSheet.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 QyvoraQuantumShield44import QyvoraWallet45import QyvoraUI4647extension EthereumFeeTier {48    var title: String {49        switch self {50        case .slow: return "Slow"51        case .normal: return "Normal"52        case .fast: return "Fast"53        }54    }55}5657/// Builds the transaction that sets a token allowance back to zero (`revokeApproval`).58///59/// With a review handoff installed, the review is handed to the wallet screens (`onReview`); otherwise this sheet60/// shows it and signs after a fresh authentication.61struct RevokeApprovalSheet: View {62    let approval: TokenApprovalExposure63    /// True when a review screen takes the review over.64    let handsOff: Bool65    let onReview: (EthereumSendReview) -> Void6667    @Environment(WalletStore.self) private var store68    @Environment(\.dismiss) private var dismiss69    @State private var tier: EthereumFeeTier = .normal70    @State private var review: EthereumSendReview?71    @State private var result: SendResult?72    @State private var error: String?73    @State private var busy = false74    @State private var reauthenticate = false75    @State private var commits = 07677    var body: some View {78        QSheetScaffold("Revoke approval", subtitle: "Sets the allowance of this spender on \(approval.token.symbol) to zero.", onClose: { dismiss() }) {79            if let result {80                ResultView(status: .pending, title: "Revocation broadcast",81                           message: "The allowance is zero once the transaction is mined. Synchronize later to confirm it.", identifier: result.id)82            } else if let review {83                reviewed(review)84            } else {85                setup86            }87            SecInlineError(error)88        } footer: {89            if result != nil {90                Button("Done") { dismiss() }.buttonStyle(.qPrimary)91            } else if review != nil {92                SlideToConfirm("Slide to sign and broadcast", buttonTitle: "Sign and broadcast", isEnabled: !busy, isWorking: busy) {93                    commits += 194                    reauthenticate = true95                }96            } else {97                LoadingButton("Prepare the revocation", loadingTitle: "Estimating gas", systemImage: "xmark.circle", state: busy ? .loading : .idle) { prepare() }98            }99        }100        .interactiveDismissDisabled(busy)101        .requiresReauthentication(isPresented: $reauthenticate, reason: "Sign the revocation") { sign() }102        .qHaptic(.committed, trigger: commits)103        .qHaptic(.selection, trigger: tier)104        .qHaptic(trigger: result) { $0 == nil ? nil : .sent }105        .qHaptic(trigger: error) { $0 == nil ? nil : .failed }106    }107108    @ViewBuilder var setup: some View {109        ReviewSection("Approval") {110            ReviewRow("Token", value: "\(approval.token.name) (\(approval.token.symbol))")111            ReviewRow("Token contract", value: approval.token.address.checksummed, emphasis: .address)112            ReviewRow("Spender", value: approval.spender.checksummed, emphasis: .address)113            ReviewRow("Current allowance", value: approval.isUnlimited ? "Unlimited" : "Limited")114        }115        ReviewSection("Priority fee", footnote: "Revoking is a transaction: it costs gas, paid in the network's native coin.") {116            Picker("Priority fee", selection: $tier) {117                ForEach(EthereumFeeTier.allCases, id: \.self) { Text($0.title).tag($0) }118            }119            .pickerStyle(.segmented)120        }121    }122123    @ViewBuilder func reviewed(_ review: EthereumSendReview) -> some View {124        QyvoraUI.NetworkReviewBanner(network: QNetwork(review.network),125                                     unauditedNotice: !review.network.isTest && store.snapshot?.unauditedMainnet == true126                                         ? "Unaudited software: per-transaction limits apply." : nil)127        ReviewSection("Transaction to sign") {128            ReviewRow("Call", value: "approve(spender, 0)", emphasis: .strong)129            ReviewRow("Spender", value: review.recipient.checksummed, emphasis: .address)130            ReviewRow("Maximum fee", value: SecChain.amount(review.maximumFee, decimals: review.network.nativeDecimals, symbol: review.network.nativeSymbol))131            ReviewRow("Nonce", value: "\(review.nonce)")132            ReviewRow("Gas limit", value: "\(review.gasLimit)")133        }134        ForEach(Array(review.warnings.enumerated()), id: \.offset) { _, warning in135            WarningBanner(warning == .revokesApproval ? .info : .warning, message: warning.message)136        }137    }138139    func prepare() {140        guard !busy else { return }141        busy = true142        error = nil143        let token = approval.token, spender = approval.spender, tier = tier144        Task {145            do {146                let built = try await store.run { try await $0.revokeApproval(token: token, spender: spender, feeTier: tier) }147                if handsOff { onReview(built) } else { review = built }148            } catch {149                self.error = SecurityError.text(error)150            }151            busy = false152        }153    }154155    func sign() {156        guard let review, !busy else { return }157        busy = true158        error = nil159        Task {160            do {161                // Same rule as the sweep: this minimal review states no acknowledgement, the uniform door refuses a162                // review that carries a critical warning.163                result = try await store.run { service in try await service.signAndBroadcast(await service.review(for: review), acknowledged: []) }164                self.review = nil165            } catch {166                self.error = SecurityError.text(error)167            }168            busy = false169        }170    }171}172
Files main
Menu

Theme