Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/NFTs/NFTControls.swift3// Description: The two pieces of signer state that guard NFTs, each changed only through a passkey approval of a verified object: the list of destinations allowed to receive NFTs (and whether the signer's policy restricts transfers to it), and the Bitcoin-style outpoint lock list that keeps outputs which may carry inscriptions out of ordinary sends. Every change is prepared by the server, bound by the Core to its challenge, reviewed field by field, then approved. The heuristic "ordinary coin" declaration needs no passkey because it never lifts a signer lock — and the screen says so.4import SwiftUI5import SPWalletCore67@MainActor @Observable final class NFTControls {8 enum Pending { case allow(NFTAllowApproval), locks(UTXOLockApproval) }9 enum Step: Equatable { case idle, preparing, review, approving }1011 let model: AppModel12 let api: NFTAPI1314 private(set) var allow: NFTAllowList?15 private(set) var allowError: String?16 private(set) var locks: UTXOLocksView?17 private(set) var locksError: String?18 private(set) var loadingLocks = false19 var locksNetwork = ""2021 private(set) var pending: Pending?22 private(set) var step: Step = .idle23 var error: String?24 var result: String?2526 init(model: AppModel) { self.model = model; api = NFTAPI(model.client) }2728 func loadAllow() async {29 guard model.phase == .signedIn else { return }30 do { allow = try await api.allowList(); allowError = nil } catch { allowError = model.describe(error) }31 }3233 func loadLocks() async {34 guard model.phase == .signedIn, !locksNetwork.isEmpty, !loadingLocks else { return }35 loadingLocks = true; defer { loadingLocks = false }36 do {37 let v = try await api.utxoLocks(network: locksNetwork)38 guard v.network == locksNetwork else { return }39 locks = v; locksError = nil40 } catch { locks = nil; locksError = model.describe(error) }41 }4243 func prepareAllow(network: String, address: String, action: NFTAllowIntent.Action) async {44 guard model.canOperate, step == .idle else { return }45 step = .preparing; error = nil; result = nil46 do { pending = .allow(try await api.prepareAllowChange(NFTAllowRequest(network: network, address: address, action: action))); step = .review }47 catch { self.error = model.describe(error); step = .idle }48 }4950 func prepareLocks(action: UTXOLockIntent.Action, outpoints: [String]) async {51 guard model.canOperate, step == .idle, !outpoints.isEmpty, !locksNetwork.isEmpty else { return }52 step = .preparing; error = nil; result = nil53 do { pending = .locks(try await api.prepareUTXOLocks(UTXOLockRequest(network: locksNetwork, action: action, reason: .owner, outpoints: outpoints))); step = .review }54 catch { self.error = model.describe(error); step = .idle }55 }5657 func approve() async {58 guard let p = pending, step == .review else { return }59 step = .approving; error = nil60 do {61 switch p {62 case .allow(let a):63 let r = try await api.approveAllowChange(a, with: model.authenticator)64 result = "Liste des destinations modifiée par le signataire (\(r.action == "add" ? "ajout" : r.action == "remove" ? "retrait" : r.action) de \(r.address) sur \(r.network)) : \(r.entries) entrée(s) désormais. Empreinte acceptée : \(r.hash)"65 case .locks(let l):66 let r = try await api.approveUTXOLocks(l, with: model.authenticator)67 result = "Liste de verrous modifiée par le signataire sur \(r.network) : \(r.changed) sortie(s) changée(s), \(r.locked) verrouillée(s) désormais. Empreinte acceptée : \(r.hash)"68 }69 pending = nil; step = .idle70 } catch PasskeyError.cancelled { step = .review; return }71 catch {72 // whatever happened, the lists below are read again from the signer: they show the real state, nothing is assumed73 self.error = model.describe(error) + " — l’état réel est relu ci-dessous."74 pending = nil; step = .idle75 }76 async let a: Void = loadAllow()77 async let b: Void = loadLocks()78 _ = await (a, b)79 }8081 func cancel() { guard step != .approving else { return }; pending = nil; step = .idle }8283 /// No passkey: this only tells the server's coin selection that the owner looked at a HEURISTICALLY flagged output.84 func declare(outpoint: String, ordinary: Bool) async {85 guard model.canOperate, !locksNetwork.isEmpty else { return }86 error = nil87 do { _ = try await api.reviewUTXO(network: locksNetwork, outpoint: outpoint, ordinary: ordinary); await loadLocks() } catch { self.error = model.describe(error) }88 }89}9091struct NFTControlsPage: View {92 let model: AppModel93 let gallery: NFTGallery94 let back: () -> Void95 @State private var controls: NFTControls?9697 var body: some View {98 Page("Contrôles NFT du signataire", subtitle: "État tenu par le signataire isolé. Chaque modification est approuvée par votre passkey sur l’objet exact, vérifié par cette app.") {99 NFTBackBar(title: "Galerie", back: back)100 if !model.canOperate { Banner(.warning, "Session ou portefeuille indisponible : consultation seule, aucune modification possible.") }101 if let c = controls {102 if let e = c.error { Banner(.danger, e) }103 if let r = c.result { Banner(.ok, r) }104 NFTAllowCard(model: model, gallery: gallery, controls: c)105 NFTLocksCard(model: model, controls: c)106 } else { ProgressView() }107 }108 .task {109 if controls == nil {110 let c = NFTControls(model: model)111 c.locksNetwork = (model.networks?.value ?? []).first { $0.family == "btc" }?.id ?? ""112 controls = c113 }114 async let a: Void? = controls?.loadAllow()115 async let b: Void? = controls?.loadLocks()116 _ = await (a, b)117 }118 .sheet(isPresented: Binding(get: { controls?.step == .review || controls?.step == .approving }, set: { _ in })) {119 if let c = controls, let p = c.pending { NFTControlsReview(model: model, controls: c, pending: p) }120 }121 }122}123124// MARK: - Destination allow-list125126private struct NFTAllowCard: View {127 let model: AppModel128 let gallery: NFTGallery129 let controls: NFTControls130 @State private var network = ""131 @State private var address = ""132133 /// The allow-list exists on EVM networks and Solana (families of the server's registry), where the server prepares NFT transfers.134 private var networks: [SPWalletCore.Network] {135 (model.networks?.value ?? []).filter { n in (n.family == "evm" || n.family == "sol") && (gallery.capabilities?.chain(n.id)?.canPrepareTransfers ?? true) }136 }137 private var check: AddressCheck? {138 guard let n = model.network(network), !address.trimmingCharacters(in: .whitespaces).isEmpty else { return nil }139 return AddressValidator.check(address, network: n)140 }141 private var problem: String? {142 guard !network.isEmpty else { return "Choisissez un réseau." }143 switch check {144 case nil: return "Entrez l’adresse à autoriser."145 case .invalid(let r): return SendFlow.text(r)146 case .valid(let n): return n == model.address(on: network) ? "C’est l’adresse de ce portefeuille." : nil147 case .unverifiable: return nil148 }149 }150151 var body: some View {152 Card("Destinations autorisées à recevoir des NFT") {153 if let e = controls.allowError { Banner(.danger, e) }154 if let a = controls.allow {155 if !a.supported { Banner(.warning, "La version du signataire ne prend pas en charge les transferts de NFT : cette liste n’existe pas encore.") }156 Banner(a.allowlistOnly ? .info : .warning, a.allowlistOnly157 ? "Mode liste imposée : le signataire ne signe un transfert de NFT que vers une destination de cette liste."158 : "Mode liste non imposée : le signataire signe un transfert de NFT vers toute destination valide ; cette liste n’est alors qu’un registre. Le mode se règle dans la politique du signataire, pas depuis cette app.")159 if a.entries.isEmpty { Text("Aucune destination dans la liste.").foregroundStyle(.secondary) }160 ForEach(a.entries, id: \.self) { e in161 HStack(alignment: .firstTextBaseline, spacing: 10) {162 VStack(alignment: .leading, spacing: 1) {163 NFTPlain(e.address).font(Theme.monoSmall).textSelection(.enabled)164 NFTPlain("\(gallery.networkName(e.network))\(e.approvedAt.map { " · approuvée le \(Fmt.date(Date(timeIntervalSince1970: TimeInterval($0))))" } ?? "")").font(.caption).foregroundStyle(.secondary)165 }166 Spacer()167 Button("Retirer…", role: .destructive) { Task { await controls.prepareAllow(network: e.network, address: e.address, action: .remove) } }168 .disabled(!model.canOperate || controls.step != .idle || !a.supported)169 }170 Divider()171 }172 Text("Ajouter une destination").font(.subheadline.weight(.medium))173 HStack(alignment: .firstTextBaseline) {174 Picker("Réseau", selection: $network) {175 Text("Réseau…").tag("")176 ForEach(networks) { NFTPlain($0.name).tag($0.id) }177 }.labelsHidden().frame(width: 200)178 TextField("Adresse", text: $address).font(Theme.monoSmall).textFieldStyle(.roundedBorder)179 if controls.step == .preparing { ProgressView().controlSize(.small) }180 Button("Préparer l’ajout…") { Task { await controls.prepareAllow(network: network, address: check?.normalized ?? address, action: .add) } }181 .disabled(problem != nil || !model.canOperate || controls.step != .idle || !a.supported)182 }183 if let p = problem, !address.isEmpty { Text(p).font(.callout).foregroundStyle(Theme.negative) }184 else if case .unverifiable = check { Text("Format non vérifiable par cette version de l’app : le serveur validera l’adresse.").font(.callout).foregroundStyle(Theme.warning) }185 Text("Autoriser une destination donne au signataire le droit de signer des transferts de NFT vers elle : vérifiez chaque caractère sur l’écran d’approbation.").font(.caption).foregroundStyle(.secondary)186 } else if controls.allowError == nil {187 if model.phase == .signedIn { ProgressView().controlSize(.small) } else { Text("Indisponible hors connexion : cet état n’est lu que sur le signataire.").foregroundStyle(.secondary) }188 }189 }190 }191}192193// MARK: - Outpoint locks194195private struct NFTLocksCard: View {196 let model: AppModel197 @Bindable var controls: NFTControls198 @State private var selection = Set<String>()199200 private var networks: [SPWalletCore.Network] { (model.networks?.value ?? []).filter { $0.family == "btc" } }201202 static func reason(_ code: String) -> String {203 switch code {204 case "signer_locked": "verrouillée sur le signataire"205 case "ord_inscription": "inscription rapportée par le serveur ord"206 case "ord_rune": "rune rapportée par le serveur ord"207 case "ord_unindexed": "pas encore indexée par le serveur ord"208 case "ord_unlisted": "inconnue du serveur ord"209 case "ord_unavailable": "serveur ord injoignable : rien n’est dépensable"210 case "heuristic_small": "petite valeur (heuristique, pas une détection)"211 case "heuristic_envelope": "enveloppe d’inscription dans la transaction (heuristique)"212 default: code213 }214 }215 static func mode(_ m: String) -> String {216 switch m {217 case "ord": "Un serveur ord décide de ce qui porte une inscription ou une rune."218 case "heuristic": "Aucun serveur ord : seuls des indices (taille, enveloppe) signalent des sorties. Ce n’est PAS une détection d’inscriptions."219 case "locks_only": "Seuls les verrous du signataire protègent des sorties."220 case "ord_unavailable": "Le serveur ord configuré ne répond pas : par prudence, aucune sortie n’est dépensable par un envoi ordinaire."221 default: m222 }223 }224225 var body: some View {226 Card("Verrous de sorties (réseaux de type Bitcoin)", trailing: controls.loadingLocks ? AnyView(ProgressView().controlSize(.small)) : nil) {227 Text("Une sortie verrouillée n’est jamais dépensée par un envoi ordinaire : c’est ce qui protège une inscription (Ordinals) reçue à l’adresse du portefeuille. Ce portefeuille ne liste ni ne transfère aucune inscription.").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)228 if networks.isEmpty { Text("Aucun réseau de type Bitcoin dans le registre du serveur.").foregroundStyle(.secondary) }229 else {230 HStack {231 Picker("Réseau", selection: $controls.locksNetwork) { ForEach(networks) { NFTPlain($0.name).tag($0.id) } }.labelsHidden().frame(width: 220)232 Button { Task { await controls.loadLocks() } } label: { Label("Relire", systemImage: "arrow.clockwise") }.disabled(model.phase != .signedIn || controls.loadingLocks)233 Spacer()234 }235 .onChange(of: controls.locksNetwork) { selection = []; Task { await controls.loadLocks() } }236 }237 if let e = controls.locksError { Banner(.danger, e) }238 if let v = controls.locks { content(v) }239 else if model.phase != .signedIn { Text("Indisponible hors connexion : cet état n’est lu que sur le signataire et la chaîne.").foregroundStyle(.secondary) }240 }241 }242243 @ViewBuilder private func content(_ v: UTXOLocksView) -> some View {244 Field(label: "Adresse", value: v.address, mono: true)245 Banner(v.mode == "ord" ? .info : .warning, Self.mode(v.mode) + (v.ordHost.map { " Serveur ord : \($0)." } ?? "") + (v.ordError.map { " Erreur : \($0)." } ?? ""))246 if !v.signerSupportsLocks { Banner(.warning, "La version du signataire ne prend pas en charge les verrous de sorties : rien ne peut être verrouillé.") }247 if v.utxos.isEmpty { Text("Aucune sortie non dépensée à cette adresse.").foregroundStyle(.secondary) }248 else {249 Table(v.utxos, selection: $selection) {250 TableColumn("Sortie (txid:index)") { u in NFTPlain(u.outpoint).font(.system(.caption, design: .monospaced)).textSelection(.enabled).help(u.outpoint) }.width(min: 260, ideal: 420)251 TableColumn("Valeur") { u in NFTPlain("\(Fmt.amount(BaseUnits(UInt64(max(0, u.value))).formatted(decimals: v.decimals))) \(v.symbol)").monospacedDigit() }.width(min: 110, ideal: 130)252 TableColumn("Envoi ordinaire") { u in253 NFTPlain(u.spendable ? (u.reviewed ? "dépensable (déclarée ordinaire)" : "dépensable") : "exclue").foregroundStyle(u.spendable ? Color.primary : Theme.warning)254 }.width(min: 110, ideal: 170)255 TableColumn("Raisons") { u in256 let parts = u.excludedBy.map(Self.reason) + (u.signerLock.map { ["verrou « \($0.reason) » du \(Fmt.date(Date(timeIntervalSince1970: TimeInterval($0.at))))"] } ?? [])257 + (u.ord.map { o in (o.inscriptions.isEmpty ? [] : ["\(o.inscriptions.count) inscription(s)"]) + (o.runes.isEmpty ? [] : ["runes : \(o.runes.joined(separator: ", "))"]) } ?? [])258 NFTPlain(parts.isEmpty ? "—" : parts.joined(separator: " · ")).font(.caption).help(parts.joined(separator: "\n"))259 }260 }261 .frame(height: min(420, CGFloat(v.utxos.count) * 28 + 40))262 let chosen = v.utxos.filter { selection.contains($0.outpoint) }263 let toLock = chosen.filter { $0.signerLock == nil }.map(\.outpoint), toUnlock = chosen.filter { $0.signerLock != nil }.map(\.outpoint)264 let heuristicOnly = chosen.filter { !$0.excludedBy.isEmpty && $0.excludedBy.allSatisfy { $0.hasPrefix("heuristic_") } || $0.reviewed }265 HStack {266 Text(chosen.isEmpty ? "Sélectionnez des sorties dans le tableau." : "\(chosen.count) sortie(s) sélectionnée(s)").font(.callout).foregroundStyle(.secondary)267 Spacer()268 if controls.step == .preparing { ProgressView().controlSize(.small) }269 Button("Verrouiller (\(toLock.count))…") { Task { await controls.prepareLocks(action: .lock, outpoints: toLock) } }270 .disabled(toLock.isEmpty || toLock.count > 100 || !model.canOperate || controls.step != .idle || !v.signerSupportsLocks)271 Button("Déverrouiller (\(toUnlock.count))…", role: .destructive) { Task { await controls.prepareLocks(action: .unlock, outpoints: toUnlock) } }272 .disabled(toUnlock.isEmpty || toUnlock.count > 100 || !model.canOperate || controls.step != .idle || !v.signerSupportsLocks)273 }274 if let h = heuristicOnly.first, heuristicOnly.count == 1, chosen.count == 1 {275 HStack {276 Text("Cette sortie n’est signalée que par des indices. La déclarer « monnaie ordinaire » la rend dépensable par un envoi ordinaire. Cela ne demande pas de passkey : aucun verrou du signataire ni rapport ord n’est levé ainsi.").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)277 Spacer()278 Button(h.reviewed ? "Retirer la déclaration" : "Déclarer monnaie ordinaire") { Task { await controls.declare(outpoint: h.outpoint, ordinary: !h.reviewed) } }.disabled(!model.canOperate)279 }280 }281 }282 if !v.staleLocks.isEmpty {283 Divider()284 Text("Verrous sans sortie correspondante").font(.subheadline.weight(.medium))285 Text("Ces sorties ne sont plus parmi les pièces du portefeuille (dépensées ailleurs, ou jamais reçues). Les verrous peuvent être retirés.").font(.caption).foregroundStyle(.secondary)286 ForEach(v.staleLocks, id: \.self) { l in287 HStack {288 NFTPlain(l.outpoint).font(.system(.caption, design: .monospaced)).textSelection(.enabled)289 NFTPlain("« \(l.reason) » · \(Fmt.date(Date(timeIntervalSince1970: TimeInterval(l.at))))").font(.caption).foregroundStyle(.secondary)290 Spacer()291 Button("Déverrouiller…") { Task { await controls.prepareLocks(action: .unlock, outpoints: [l.outpoint]) } }.controlSize(.small)292 .disabled(!model.canOperate || controls.step != .idle || !v.signerSupportsLocks)293 }294 }295 }296 if let t = v.transfer, t != "supported" { NFTPlain("Transfert d’inscriptions : non construit\(v.transferReason.map { " — \(NFTText.blockReason($0))" } ?? "")").font(.caption).foregroundStyle(.secondary) }297 }298}299300// MARK: - Review of a verified change301302private struct NFTControlsReview: View {303 let model: AppModel304 let controls: NFTControls305 let pending: NFTControls.Pending306307 private var title: String { switch pending { case .allow: "Vérifier la modification de la liste des destinations NFT"; case .locks: "Vérifier la modification des verrous de sorties" } }308 private var digest: Data { switch pending { case .allow(let a): a.approval.digest; case .locks(let l): l.approval.digest } }309 private var expiry: Date { switch pending { case .allow(let a): a.intent.expiry; case .locks(let l): l.intent.expiry } }310311 /// The fields of the verified object, in full.312 private var lines: [ReviewLine] {313 switch pending {314 case .allow(let a):315 let i = a.intent316 return [317 .init(label: "Type d’opération", value: "Liste des destinations NFT du signataire (\(i.kind), version \(i.v))", style: .strong),318 .init(label: "Action", value: i.action == .add ? "AJOUTER cette destination" : "RETIRER cette destination", style: .strong),319 .init(label: "Réseau", value: "\(model.network(i.network)?.name ?? i.network) (\(i.network))"),320 .init(label: "Adresse", value: i.address, style: .address),321 .init(label: "Expiration de l’approbation", value: Fmt.dateSeconds(i.expiry)),322 .init(label: "Demande", value: i.requestId),323 .init(label: "Clé du portefeuille", value: i.keyId),324 .init(label: "Politique du signataire", value: "version \(i.policyVersion)"),325 ]326 case .locks(let l):327 let i = l.intent328 return [329 .init(label: "Type d’opération", value: "Verrous de sorties du signataire (\(i.kind), version \(i.v))", style: .strong),330 .init(label: "Action", value: i.action == .lock ? "VERROUILLER ces sorties" : "DÉVERROUILLER ces sorties", style: .strong),331 .init(label: "Motif enregistré", value: i.reason.rawValue),332 .init(label: "Réseau", value: "\(model.network(i.network)?.name ?? i.network) (\(i.network))"),333 .init(label: "Sorties (\(i.outpoints.count))", value: i.outpoints.map(\.key).joined(separator: "\n"), style: .address),334 .init(label: "Expiration de l’approbation", value: Fmt.dateSeconds(i.expiry)),335 .init(label: "Demande", value: i.requestId),336 .init(label: "Clé du portefeuille", value: i.keyId),337 .init(label: "Politique du signataire", value: "version \(i.policyVersion)"),338 ]339 }340 }341 private var consequence: (Banner.Kind, String) {342 switch pending {343 case .allow(let a) where a.intent.action == .add: (.warning, "Après cet ajout, le signataire acceptera de signer des transferts de NFT vers cette adresse. Un NFT envoyé à une mauvaise adresse est perdu : comparez chaque caractère.")344 case .allow: (.info, "Après ce retrait, si la politique impose la liste, le signataire refusera tout transfert de NFT vers cette adresse.")345 case .locks(let l) where l.intent.action == .unlock: (.warning, "Après ce déverrouillage, ces sorties pourront être dépensées par un envoi ordinaire. Si l’une d’elles porte une inscription, celle-ci partirait comme de la simple monnaie, sans retour possible.")346 case .locks: (.info, "Après ce verrouillage, le signataire refusera ces sorties comme entrées de toute transaction, jusqu’à leur déverrouillage par passkey.")347 }348 }349350 var body: some View {351 VStack(alignment: .leading, spacing: 0) {352 Text(title).font(.title2.weight(.semibold)).padding(20)353 Divider()354 ScrollView {355 VStack(alignment: .leading, spacing: 14) {356 Text("Ce que votre passkey va signer").font(.headline)357 ReviewLines(lines: lines)358 if case .allow(let a) = pending {359 VStack(alignment: .leading, spacing: 4) {360 Text("Adresse, par groupes de 4 caractères").font(.caption).foregroundStyle(.secondary)361 NFTPlain(Fmt.chunked(a.intent.address)).font(.system(.title3, design: .monospaced)).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)362 }363 .padding(10).frame(maxWidth: .infinity, alignment: .leading).background(Color.secondary.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))364 }365 Banner(consequence.0, consequence.1)366 BindingProof(digest: digest, expiry: expiry)367 }.padding(20)368 }369 Divider()370 HStack {371 Button("Annuler") { controls.cancel() }.disabled(controls.step == .approving)372 Spacer()373 if controls.step == .approving { ProgressView().controlSize(.small); Text("Passkey, puis signataire isolé…").foregroundStyle(.secondary) }374 Button { Task { await controls.approve() } } label: { Label("Approuver avec la passkey", systemImage: "touchid") }375 .buttonStyle(.borderedProminent).controlSize(.large).disabled(controls.step == .approving)376 }.padding(16)377 }378 .frame(width: 720, height: 640)379 .interactiveDismissDisabled()380 }381}382