SPB Git

Repository Public

NFTProtectionsView.swift 29.3 KB 427 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Features/NFTs/NFTProtectionsView.swift10// Description      : The two signer-side protections around NFTs. (1) The list11//                    of destinations allowed to receive NFTs: every addition or12//                    removal is an object the passkey approves. (2) The lock13//                    list of Bitcoin-style outputs, which keeps an output that14//                    may carry an inscription out of ordinary sends: locking15//                    and unlocking are passkey-approved; declaring a16//                    heuristically flagged output an ordinary coin is not (it17//                    lifts no lock). Each approval shows the verified object in18//                    full — network, action, address or outpoints, digest —19//                    before the passkey prompt.20// Module           : Features21// Repository       : https://git.spboucher.ai/sp-wallet-ios22// Created          : 2026-11-1823// Last Modified    : 2026-11-1824//25// =============================================================================26// AUTHOR & PROFESSIONAL AFFILIATION27// =============================================================================28//29// Author           : Simon-Pierre Boucher30// Position         : Professor of Finance31// Institution      : Université du Québec en Outaouais (UQO)32// Department       : Département des sciences administratives33// Organization     : SP Boucher34//35// Website          : https://spboucher.ai36// Git              : https://git.spboucher.ai37//38// =============================================================================39// OFFICIAL CONTACT DIRECTORY40// =============================================================================41//42// General          : info@spboucher.ai43// Professional     : contact@spboucher.ai44// Direct           : simon@spboucher.ai45// Research         : research@spboucher.ai46// Development      : dev@spboucher.ai47// Support          : support@spboucher.ai48// Security/Admin   : admin@spboucher.ai49// Notifications    : notifications@spboucher.ai50//51// Preferred Contact: support@spboucher.ai52//53// =============================================================================54// COPYRIGHT & INTELLECTUAL PROPERTY55// =============================================================================56//57// Copyright (c) 202658// Simon-Pierre Boucher59//60// All rights reserved where applicable.61//62// This file is governed by the applicable project license,63// copyright notices, institutional agreements and relevant law.64//65// Unless expressly authorized by the applicable license or66// rights holder, copying, redistribution, sublicensing,67// publication and commercial exploitation are not permitted.68//69// Existing third-party rights and notices remain unaffected.70//71// =============================================================================72// CONFIDENTIALITY & SECURITY73// =============================================================================74//75// Classification   : Public76// Distribution     : Public repository; use is governed by the project license77// Security Contact : admin@spboucher.ai78//79// Access to this source does not independently grant permission80// to redistribute or disclose confidential materials.81//82// Do not embed credentials, private keys, access tokens,83// certificates or confidential personal information.84//85// =============================================================================86// LICENSE & MAINTENANCE87// =============================================================================88//89// License          : None specified (no license file in this repository)90// Maintainer       : Simon-Pierre Boucher91// Technical Contact: dev@spboucher.ai92//93// =============================================================================94// END OF SP BOUCHER SOURCE HEADER95// =============================================================================9697import SwiftUI98import SPWalletCore99100enum NFTProtections {101    /** The reason recorded with a lock: what flagged the output, else the owner's own decision. */102    static func lockReason(for row: UTXOLockRow) -> UTXOLockIntent.Reason {103        if row.excludedBy.contains(where: { $0.hasPrefix("ord_") }) { return .ord }104        if row.excludedBy.contains(where: { $0.hasPrefix("heuristic_") }) { return .heuristic }105        return .owner106    }107    /** Outputs an ord server flags and that the signer does not refuse yet. */108    static func unprotectedByOrd(_ v: UTXOLocksView) -> [UTXOLockRow] { v.utxos.filter { $0.signerLock == nil && $0.excludedBy.contains { $0.hasPrefix("ord_") } } }109    /** Only an output held back by heuristics alone can be declared an ordinary coin. */110    static func canDeclareOrdinary(_ row: UTXOLockRow) -> Bool { row.signerLock == nil && !row.excludedBy.isEmpty && row.excludedBy.allSatisfy { $0.hasPrefix("heuristic_") } }111}112113/** A prepared, verified change waiting for the passkey. */114enum NFTProtectionPending: Identifiable {115    case allow(NFTAllowApproval)116    case locks(UTXOLockApproval)117    var id: String { digest.hex }118    var digest: Data { switch self { case .allow(let a): a.approval.digest; case .locks(let l): l.approval.digest } }119    var expiry: Date { switch self { case .allow(let a): a.intent.expiry; case .locks(let l): l.intent.expiry } }120}121122struct NFTProtectionsView: View {123    let ctx: NFTContext124    @Environment(AppModel.self) private var model125    let capabilities: NFTCapabilities?126127    private enum Tab: Hashable { case allow, outputs }128    @State private var tab: Tab = .allow129    @State private var allow: NFTAllowList?130    @State private var allowError: Error?131    @State private var locks: UTXOLocksView?132    @State private var locksError: Error?133    @State private var utxoNetwork: String?134    @State private var newNetwork: String?135    @State private var newAddress = ""136    @State private var busy = false137    @State private var error: Error?138    @State private var pending: NFTProtectionPending?139    @State private var lastResult: String?140141    var body: some View {142        ScrollView {143            VStack(alignment: .leading, spacing: Theme.Space.section) {144                NFTFixtureBanner(ctx: ctx)145                FreshnessBanner()146                Picker(String(localized: "Protection"), selection: $tab) {147                    Text(String(localized: "Destinations autorisées")).tag(Tab.allow)148                    Text(String(localized: "Sorties Bitcoin")).tag(Tab.outputs)149                }.pickerStyle(.segmented).accessibilityIdentifier("nft.protections.tab")150                if !model.canOperate { Notice(tone: .warn, title: String(localized: "Protections indisponibles hors ligne"), message: String(localized: "Ces listes vivent sur le signataire : elles ne se lisent et ne se modifient qu’en ligne, avec ta clé d’accès.")) }151                if let r = lastResult { Notice(tone: .ok, title: String(localized: "Changement accepté par le signataire"), message: r).accessibilityIdentifier("nft.protections.result") }152                if let e = error { NFTErrorNotice(error: e).accessibilityIdentifier("nft.protections.error") }153                switch tab {154                case .allow: allowSection155                case .outputs: outputsSection156                }157            }158            .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12).frame(maxWidth: 680).frame(maxWidth: .infinity)159        }160        .spPage().navigationTitle(String(localized: "Protections")).navigationBarTitleDisplayMode(.inline)161        .task(id: "\(model.canOperate)|\(utxoNetwork ?? "")") { await load() }162        .sheet(item: $pending, onDismiss: { Task { await load() } }) { p in163            NFTProtectionReview(ctx: ctx, pending: p) { summary in lastResult = summary }.wallet(model)164        }165    }166167    // MARK: data168169    private var allowNetworks: [(id: String, name: String)] {170        let fromCaps = (capabilities?.chains ?? []).filter { $0.canPrepareTransfers }.map { ($0.network, $0.name) }171        if !fromCaps.isEmpty { return fromCaps.map { (id: $0.0, name: $0.1) } }172        return (model.networks.value ?? []).filter { $0.family == "evm" || $0.family == "sol" }.map { (id: $0.id, name: $0.name) }173    }174    private var utxoNetworks: [(id: String, name: String)] {175        let fromCaps = (capabilities?.chains ?? []).filter { $0.family == "btc" }.map { (id: $0.network, name: $0.name) }176        let fromWallet = (model.networks.value ?? []).filter { $0.family == "btc" && model.account($0.id) != nil }.map { (id: $0.id, name: $0.name) }177        var seen = Set<String>()178        return (fromWallet + fromCaps).filter { seen.insert($0.id).inserted }179    }180181    private func load() async {182        if newNetwork == nil { newNetwork = allowNetworks.first?.id }183        if utxoNetwork == nil { utxoNetwork = utxoNetworks.first { $0.id == "bitcoin" }?.id ?? utxoNetworks.first?.id }184        guard model.canOperate else { return }185        do { allow = try await ctx.api.allowList(); allowError = nil } catch { allowError = error }186        if let n = utxoNetwork {187            do { locks = try await ctx.api.utxoLocks(network: n); locksError = nil } catch { locks = nil; locksError = error }188        }189    }190191    private func prepare(_ make: @escaping @Sendable (NFTAPI) async throws -> NFTProtectionPending) async {192        guard !busy else { return }193        busy = true; error = nil; lastResult = nil194        defer { busy = false }195        do { pending = try await make(ctx.api) } catch { self.error = error }196    }197198    // MARK: allow-list199200    private var newAddressCheck: AddressVerdict? {201        let a = newAddress.trimmingCharacters(in: .whitespacesAndNewlines)202        guard !a.isEmpty, let id = newNetwork else { return nil }203        guard let n = model.network(id) else { return .unverifiable }204        return AddressChecks.check(a, network: n, own: model.account(id)?.address)205    }206207    @ViewBuilder private var allowSection: some View {208        Text(String(localized: "Liste, tenue par le signataire, des destinations autorisées à recevoir des NFT. Chaque ajout ou retrait est approuvé avec ta clé d’accès.")).font(.spCallout).foregroundStyle(Theme.mute)209        if let a = allow {210            if !a.supported { Notice(tone: .warn, title: String(localized: "Le signataire ne prend pas encore en charge les envois de NFT"), message: String(localized: "La liste ne peut pas être modifiée.")) }211            Notice(tone: a.allowlistOnly ? .info : .neutral,212                   title: a.allowlistOnly ? String(localized: "Mode liste blanche : ACTIF") : String(localized: "Mode liste blanche : inactif"),213                   message: a.allowlistOnly ? String(localized: "Le signataire ne signe un envoi de NFT que vers une destination de cette liste.")214                    : String(localized: "La politique du signataire n’exige pas que la destination soit dans cette liste. La liste reste tenue pour le jour où elle l’exigera."))215                .accessibilityIdentifier("nft.allow.mode")216            VStack(alignment: .leading, spacing: 0) {217                if a.entries.isEmpty { Text(String(localized: "Aucune destination approuvée.")).font(.spCallout).foregroundStyle(Theme.mute).padding(.vertical, 6).accessibilityIdentifier("nft.allow.empty") }218                ForEach(Array(a.entries.enumerated()), id: \.offset) { i, e in219                    if i > 0 { Divider() }220                    VStack(alignment: .leading, spacing: 6) {221                        HStack(spacing: 8) { NetworkIcon(network: e.network, size: 22); Text(model.network(e.network)?.name ?? e.network).font(.spBody.weight(.semibold)); Spacer() }222                        Text(verbatim: e.address).font(.spMono).foregroundStyle(Theme.ink).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)223                        if let t = e.approvedAt { Text(String(localized: "Approuvée le \(Date(timeIntervalSince1970: TimeInterval(t)).formatted(date: .abbreviated, time: .shortened))")).font(.spFootnote).foregroundStyle(Theme.mute) }224                        Button { Task { await prepare { .allow(try await $0.prepareAllowChange(NFTAllowRequest(network: e.network, address: e.address, action: .remove))) } } } label: { Label(String(localized: "Retirer (clé d’accès)"), systemImage: "minus.circle") }225                            .buttonStyle(.bordered).font(.spCallout.weight(.semibold)).disabled(busy || !model.canOperate || !a.supported).accessibilityIdentifier("nft.allow.remove")226                    }.padding(.vertical, 8).accessibilityElement(children: .contain).accessibilityIdentifier("nft.allow.entry")227                }228            }.spCard(padding: 16)229230            VStack(alignment: .leading, spacing: 10) {231                Text(String(localized: "Ajouter une destination")).font(.spHeadline)232                Picker(String(localized: "Réseau"), selection: $newNetwork) { ForEach(allowNetworks, id: \.id) { n in Text(n.name).tag(Optional(n.id)) } }.pickerStyle(.menu)233                TextField(String(localized: "Adresse de destination"), text: $newAddress, axis: .vertical)234                    .font(.spMono).textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.asciiCapable).lineLimit(1...4)235                    .padding(12).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small)).accessibilityIdentifier("nft.allow.address")236                if case .invalid(let why)? = newAddressCheck { Label(why, systemImage: "xmark.octagon.fill").font(.spFootnote).foregroundStyle(Theme.danger).accessibilityIdentifier("nft.allow.addressError") }237                let ok: Bool = { guard let c = newAddressCheck, newNetwork != nil else { return false }; if case .invalid = c { return false }; return true }()238                Button {239                    let n = newNetwork ?? "", addr = newAddress240                    Task { await prepare { .allow(try await $0.prepareAllowChange(NFTAllowRequest(network: n, address: addr, action: .add))) } }241                } label: { HStack { if busy { ProgressView().tint(Theme.onPrimary) }; Text(String(localized: "Préparer l’ajout")) } }242                    .buttonStyle(.spPrimary).disabled(!ok || busy || !model.canOperate || !a.supported).accessibilityIdentifier("nft.allow.prepare")243                Text(String(localized: "L’ajout est d’abord préparé par le serveur ; tu vérifies ensuite l’adresse en entier avant d’approuver avec la clé d’accès.")).font(.spFootnote).foregroundStyle(Theme.mute)244            }.spCard()245        } else if let e = allowError, model.canOperate { NFTErrorNotice(error: e) { Task { await load() } } }246        else if model.canOperate { ProgressView().frame(maxWidth: .infinity).padding(.vertical, 30) }247    }248249    // MARK: Bitcoin-style outputs250251    @ViewBuilder private var outputsSection: some View {252        Text(String(localized: "Les inscriptions Bitcoin ne sont ni listées ni transférées par ce portefeuille. Ce qui est fait : protéger les sorties pour qu’un envoi ordinaire ne les dépense pas.")).font(.spCallout).foregroundStyle(Theme.mute)253        if utxoNetworks.isEmpty { Notice(tone: .info, title: String(localized: "Aucun réseau de type Bitcoin dans ce portefeuille")) }254        if utxoNetworks.count > 1 {255            Picker(String(localized: "Réseau"), selection: $utxoNetwork) { ForEach(utxoNetworks, id: \.id) { n in Text(n.name).tag(Optional(n.id)) } }.pickerStyle(.menu).accessibilityIdentifier("nft.utxo.network")256        }257        if let d = locks {258            let mode = NFTText.utxoMode(d.mode, host: d.ordHost)259            Notice(tone: mode.1, title: mode.0).accessibilityIdentifier("nft.utxo.mode")260            Notice(tone: .info, title: String(localized: "Une sortie verrouillée est refusée par le SIGNATAIRE dans tout envoi ordinaire."), message: String(localized: "Verrouiller comme déverrouiller demande la clé d’accès."))261            if !d.signerSupportsLocks { Notice(tone: .warn, title: String(localized: "Le signataire ne prend pas encore en charge la liste de verrouillage.")) }262            if let e = d.ordError { Notice(tone: .warn, title: String(localized: "Erreur du serveur ord"), message: e) }263            let flagged = NFTProtections.unprotectedByOrd(d)264            if !flagged.isEmpty, d.signerSupportsLocks {265                Button { Task { await prepare { .locks(try await $0.prepareUTXOLocks(UTXOLockRequest(network: d.network, action: .lock, reason: .ord, outpoints: flagged.map(\.outpoint)))) } } } label: { Label(String(localized: "Verrouiller les \(flagged.count) sorties signalées par ord (clé d’accès)"), systemImage: "lock") }266                    .buttonStyle(.spSecondary).disabled(busy || !model.canOperate).accessibilityIdentifier("nft.utxo.lockAll")267            }268            VStack(alignment: .leading, spacing: 0) {269                FieldRow(label: String(localized: "Adresse lue"), value: d.address, mono: true, copyable: true)270                if d.utxos.isEmpty { Divider(); Text(String(localized: "Aucune sortie confirmée sur cette adresse.")).font(.spCallout).foregroundStyle(Theme.mute).padding(.vertical, 8).accessibilityIdentifier("nft.utxo.empty") }271                ForEach(d.utxos) { u in Divider(); output(u, in: d) }272            }.spCard(padding: 16)273            if !d.staleLocks.isEmpty {274                VStack(alignment: .leading, spacing: 8) {275                    Text(String(localized: "Verrous sur des sorties qui ne sont plus à cette adresse :")).font(.spFootnote).foregroundStyle(Theme.mute)276                    ForEach(d.staleLocks, id: \.outpoint) { l in277                        Text(verbatim: l.outpoint).font(.system(size: 12, design: .monospaced)).foregroundStyle(Theme.ink).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)278                        Button { Task { await prepare { .locks(try await $0.prepareUTXOLocks(UTXOLockRequest(network: d.network, action: .unlock, reason: .owner, outpoints: [l.outpoint]))) } } } label: { Label(String(localized: "Déverrouiller (clé d’accès)"), systemImage: "lock.open") }279                            .buttonStyle(.bordered).font(.spCallout.weight(.semibold)).disabled(busy || !model.canOperate || !d.signerSupportsLocks)280                    }281                }.spCard(padding: 16)282            }283            if d.transfer == "not_supported" { Text(NFTText.transferBlock(d.transferReason ?? "ordinals_transfer_not_supported")).font(.spFootnote).foregroundStyle(Theme.mute) }284        } else if let e = locksError, model.canOperate {285            Notice(tone: .warn, title: String(localized: "Les sorties de cette adresse n’ont pas pu être lues."), message: NFTText.errorMessage(e).detail).accessibilityIdentifier("nft.utxo.error")286        } else if model.canOperate, utxoNetwork != nil { ProgressView().frame(maxWidth: .infinity).padding(.vertical, 30) }287    }288289    private func output(_ u: UTXOLockRow, in d: UTXOLocksView) -> some View {290        let value = (try? BaseUnits(String(u.value)))?.formatted(decimals: d.decimals) ?? String(u.value)291        let state: (String, Tone, String) = u.signerLock != nil ? (String(localized: "Verrouillée (signataire)"), .ok, "lock.fill")292            : u.spendable ? (String(localized: "Dépensable"), .neutral, "checkmark") : (String(localized: "Tenue à l’écart"), .warn, "exclamationmark.triangle.fill")293        return VStack(alignment: .leading, spacing: 6) {294            HStack(alignment: .firstTextBaseline) {295                Masked(text: Money.exact(value) + " " + d.symbol).font(.spBody.weight(.semibold)).monospacedDigit()296                Spacer()297                Pill(text: state.0, tone: state.1, icon: state.2)298            }299            Text(verbatim: u.outpoint).font(.system(size: 12, design: .monospaced)).foregroundStyle(Theme.mute).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)300            ForEach(u.excludedBy, id: \.self) { r in Text("· " + NFTText.utxoWhy(r)).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }301            if u.reviewed { Text(String(localized: "· Tu l’as déclarée pièce ordinaire.")).font(.spFootnote).foregroundStyle(Theme.mute) }302            if let ord = u.ord, !ord.inscriptions.isEmpty { Text(verbatim: ord.inscriptions.joined(separator: "\n")).font(.system(size: 11.5, design: .monospaced)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }303            HStack(spacing: 8) {304                if d.signerSupportsLocks {305                    if u.signerLock != nil {306                        Button { Task { await prepare { .locks(try await $0.prepareUTXOLocks(UTXOLockRequest(network: d.network, action: .unlock, reason: .owner, outpoints: [u.outpoint]))) } } } label: { Label(String(localized: "Déverrouiller"), systemImage: "lock.open") }307                            .accessibilityIdentifier("nft.utxo.unlock")308                    } else {309                        let reason = NFTProtections.lockReason(for: u)310                        Button { Task { await prepare { .locks(try await $0.prepareUTXOLocks(UTXOLockRequest(network: d.network, action: .lock, reason: reason, outpoints: [u.outpoint]))) } } } label: { Label(String(localized: "Verrouiller"), systemImage: "lock") }311                            .accessibilityIdentifier("nft.utxo.lock")312                    }313                }314                if NFTProtections.canDeclareOrdinary(u) {315                    Button(u.reviewed ? String(localized: "Annuler « pièce ordinaire »") : String(localized: "C’est une pièce ordinaire")) { Task { await declare(u, ordinary: !u.reviewed, network: d.network) } }316                        .accessibilityIdentifier("nft.utxo.review")317                }318            }.buttonStyle(.bordered).font(.spCallout.weight(.semibold)).disabled(busy || !model.canOperate)319        }320        .padding(.vertical, 8).accessibilityElement(children: .contain).accessibilityIdentifier("nft.utxo.row")321    }322323    /** No passkey here, as the server models it: this lifts no signer lock and no ord report, it only records that the owner looked. */324    private func declare(_ u: UTXOLockRow, ordinary: Bool, network: String) async {325        busy = true; error = nil326        defer { busy = false }327        do { _ = try await ctx.api.reviewUTXO(network: network, outpoint: u.outpoint, ordinary: ordinary); await load() } catch { self.error = error }328    }329}330331/** The review of one list change: the verified object in full, then the passkey. Never dismissed by an accidental swipe. */332struct NFTProtectionReview: View {333    let ctx: NFTContext334    @Environment(AppModel.self) private var model335    @Environment(\.dismiss) private var dismiss336    let pending: NFTProtectionPending337    let onAccepted: (String) -> Void338    @State private var busy = false339    @State private var error: Error?340    @State private var lostAnswer = false341342    var body: some View {343        NavigationStack {344            ScrollView {345                VStack(alignment: .leading, spacing: Theme.Space.section) {346                    NFTFixtureBanner(ctx: ctx)347                    Text(headline).font(.system(size: 24, weight: .semibold)).tracking(-0.4).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)348                        .accessibilityIdentifier("nft.protection.headline")349                    NFTFactCard(rows: rows).accessibilityIdentifier("nft.protection.object")350                    VStack(alignment: .leading, spacing: 0) {351                        TimelineView(.periodic(from: .now, by: 1)) { c in352                            let left = Int(pending.expiry.timeIntervalSince(c.date))353                            FieldRow(label: String(localized: "Fenêtre d’approbation"), value: left > 0 ? String(localized: "expire dans \(left) s") : String(localized: "expirée"), tone: left > 15 ? nil : .danger)354                        }355                        Divider()356                        FieldRow(label: String(localized: "Empreinte de l’objet (défi signé par la clé d’accès)"), value: pending.digest.hex, mono: true, copyable: true).accessibilityIdentifier("nft.protection.digest")357                    }.spCard(padding: 16)358                    Label(String(localized: "L’app a vérifié que l’objet ci-dessus est bien le changement demandé et que son empreinte est le défi demandé à ta clé d’accès. Le signataire le revérifie avant de l’appliquer."), systemImage: "checkmark.shield.fill")359                        .font(.spFootnote).foregroundStyle(Theme.mute)360                    if lostAnswer { Notice(tone: .warn, title: String(localized: "Réponse perdue"), message: String(localized: "L’approbation est partie mais la réponse n’est pas revenue. Ferme cette fiche : la liste est relue telle que le signataire la tient. Ne signe pas une seconde fois.")) }361                    if let e = error { NFTErrorNotice(error: e).accessibilityIdentifier("nft.protection.error") }362                    TimelineView(.periodic(from: .now, by: 1)) { c in363                        let expired = pending.expiry <= c.date364                        VStack(spacing: 10) {365                            if expired { Notice(tone: .warn, title: String(localized: "Fenêtre expirée"), message: String(localized: "Ferme et prépare de nouveau le changement.")) }366                            Button { Task { await approve() } } label: { HStack { if busy { ProgressView().tint(Theme.onPrimary) } else { Image(systemName: "person.badge.key.fill") }; Text(String(localized: "Approuver avec la clé d’accès")) } }367                                .buttonStyle(.spPrimary).disabled(busy || expired || lostAnswer || !model.canOperate).accessibilityIdentifier("nft.protection.approve")368                        }369                    }370                }371                .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12).frame(maxWidth: 620).frame(maxWidth: .infinity)372            }373            .spPage().navigationTitle(String(localized: "Vérifier et approuver")).navigationBarTitleDisplayMode(.inline)374            .toolbar { ToolbarItem(placement: .cancellationAction) { Button(lostAnswer ? String(localized: "Fermer") : String(localized: "Annuler")) { dismiss() }.disabled(busy).accessibilityIdentifier("nft.protection.cancel") } }375        }376        .interactiveDismissDisabled()377    }378379    private var headline: String {380        switch pending {381        case .allow(let a): a.intent.action == .add ? String(localized: "Autoriser une destination pour les NFT") : String(localized: "Retirer une destination autorisée")382        case .locks(let l): l.intent.action == .lock ? String(localized: "Verrouiller \(l.intent.outpoints.count) sortie(s)") : String(localized: "Déverrouiller \(l.intent.outpoints.count) sortie(s)")383        }384    }385386    private var rows: [(String, String, Bool)] {387        switch pending {388        case .allow(let a):389            let i = a.intent390            return [(String(localized: "Action"), i.action == .add ? String(localized: "ajouter à la liste") : String(localized: "retirer de la liste"), false),391                    (String(localized: "Réseau"), model.network(i.network)?.name ?? i.network, false),392                    (String(localized: "Adresse"), i.address, true),393                    (String(localized: "Demande"), i.requestId, true),394                    (String(localized: "Clé du signataire · version de politique"), "\(i.keyId) · v\(i.policyVersion)", true)]395        case .locks(let l):396            let i = l.intent397            let reason: String = { switch i.reason { case .owner: String(localized: "décision du propriétaire"); case .ord: String(localized: "signalée par le serveur ord"); case .heuristic: String(localized: "signalée par l’heuristique") } }()398            return [(String(localized: "Action"), i.action == .lock ? String(localized: "verrouiller") : String(localized: "déverrouiller"), false),399                    (String(localized: "Réseau"), model.network(i.network)?.name ?? i.network, false),400                    (String(localized: "Motif enregistré"), reason, false)]401                + i.outpoints.enumerated().map { (String(localized: "Sortie \($0.offset + 1) sur \(i.outpoints.count) (transaction:index)"), $0.element.key, true) }402                + [(String(localized: "Demande"), i.requestId, true), (String(localized: "Clé du signataire · version de politique"), "\(i.keyId) · v\(i.policyVersion)", true)]403        }404    }405406    private func approve() async {407        guard !busy else { return }408        busy = true; error = nil409        defer { busy = false }410        do {411            switch pending {412            case .allow(let a):413                let r = try await ctx.api.approveAllowChange(a, with: model.env.passkeys)414                onAccepted(String(localized: "Liste des destinations : \(r.entries) entrée(s) après le changement. Empreinte acceptée : \(r.hash)"))415            case .locks(let l):416                let r = try await ctx.api.approveUTXOLocks(l, with: model.env.passkeys)417                onAccepted(String(localized: "\(r.changed) sortie(s) modifiée(s), \(r.locked) verrouillée(s) sur ce réseau. Empreinte acceptée : \(r.hash)"))418            }419            dismiss()420        } catch PasskeyError.cancelled {421            // dismissed: nothing signed, nothing changed422        } catch let e as APIError where e.isOffline {423            lostAnswer = true // the list is re-read when this sheet closes: the real state decides, never a second signature424        } catch { self.error = error }425    }426}427
Files main
Menu

Theme