SPB Git

Repository Public

NFTAccessViews.swift 21.6 KB 365 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Features/NFTs/NFTAccessViews.swift10// Description      : The three screens around the gallery: what the server11//                    really reads on each network (the capability matrix, as12//                    served), the explicit lookup / manual tracking of an NFT13//                    by its chain identifier (the way an EVM NFT is opened when14//                    automatic discovery is not configured), and the addresses15//                    an NFT can be received on, with their warnings.16// Module           : Features17// Repository       : https://git.spboucher.ai/sp-wallet-ios18// Created          : 2026-11-1819// Last Modified    : 2026-11-1820//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import SwiftUI94import SPWalletCore9596// MARK: - capability matrix9798struct NFTNetworksView: View {99    let ctx: NFTContext100    let capabilities: Loaded<NFTCapabilities>101102    var body: some View {103        ScrollView {104            VStack(alignment: .leading, spacing: Theme.Space.section) {105                NFTFixtureBanner(ctx: ctx)106                FreshnessBanner()107                Text(String(localized: "État réel de l’inventaire NFT pour chacun des réseaux du portefeuille, tel que le serveur le déclare.")).font(.spCallout).foregroundStyle(Theme.mute)108                if let caps = capabilities.value {109                    if capabilities.isCached, let at = capabilities.savedAt { Notice(tone: .info, title: String(localized: "État enregistré le \(at.formatted(date: .abbreviated, time: .shortened))"), icon: "clock") }110                    ForEach(caps.chains) { c in chain(c) }111                    providers(caps)112                } else if let e = capabilities.error { NFTErrorNotice(error: e) }113                else { EmptyState(icon: "list.bullet.rectangle", title: String(localized: "État des réseaux non disponible")) }114            }115            .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12).frame(maxWidth: 760).frame(maxWidth: .infinity)116        }117        .spPage().navigationTitle(String(localized: "Réseaux : ce qui est lu")).navigationBarTitleDisplayMode(.inline)118    }119120    private func chain(_ c: NFTChainCapability) -> some View {121        let inv = NFTText.inventory(c.inventory)122        return VStack(alignment: .leading, spacing: 8) {123            HStack(spacing: 10) {124                NetworkIcon(network: c.network, size: 28)125                Text(c.name).font(.spHeadline).foregroundStyle(Theme.ink)126                Spacer()127                Pill(text: inv.0, tone: inv.1)128            }129            Text(NFTText.inventoryReason(c.reason)).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)130            if let u = c.unlockedBy {131                NFTInlineMono(prefix: String(localized: "Débloqué par le réglage serveur : "), mono: u)132            }133            ForEach(c.sections, id: \.section) { s in134                let st = NFTText.sectionStatus(s.status)135                HStack(alignment: .firstTextBaseline) {136                    Text(NFTText.section(s.section)).font(.spFootnote).foregroundStyle(Theme.ink)137                    Spacer()138                    Text(st.0 + (s.status == "ok" ? " · \(s.count)" + (s.truncated ? "+" : "") : "") + (s.code.map { " (\($0))" } ?? "")).font(.spFootnote.weight(.medium)).foregroundStyle(st.1.color)139                }140            }141            Divider()142            fact(String(localized: "Standards lus"), c.standards.isEmpty ? String(localized: "aucun") : c.standards.map { NFTText.standard($0) }.joined(separator: ", "))143            fact(String(localized: "Ouverture par identifiant"), NFTText.yesNo(c.lookup))144            fact(String(localized: "Suivi manuel"), NFTText.yesNo(c.manualAdd))145            fact(String(localized: "Réception"), NFTText.yesNo(c.receive))146            fact(String(localized: "Envoi"), c.canPrepareTransfers147                 ? String(localized: "préparable pour : \((c.transferStandards ?? []).map { NFTText.standard($0) }.joined(separator: ", "))")148                 : String(localized: "non pris en charge") + (c.transferReason.map { " — " + NFTText.transferBlock($0) } ?? ""))149            fact(String(localized: "Données de marché (lecture)"), NFTText.yesNo(c.marketRead))150            fact(String(localized: "Actions de marché"), c.marketWrite ? String(localized: "déclarées par le serveur, non construites dans cette app") : String(localized: "non construites"))151        }152        .spCard(padding: 16)153        .accessibilityElement(children: .contain).accessibilityIdentifier("nft.network.\(c.network)")154    }155156    private func fact(_ k: String, _ v: String) -> some View {157        HStack(alignment: .firstTextBaseline, spacing: 10) {158            Text(k).font(.spFootnote).foregroundStyle(Theme.mute)159            Spacer(minLength: 6)160            Text(v).font(.spFootnote.weight(.medium)).foregroundStyle(Theme.ink).multilineTextAlignment(.trailing).fixedSize(horizontal: false, vertical: true)161        }162    }163164    private func providers(_ caps: NFTCapabilities) -> some View {165        VStack(alignment: .leading, spacing: 8) {166            SectionHeader(title: String(localized: "Sources de données"))167            ForEach(caps.providers) { p in168                VStack(alignment: .leading, spacing: 2) {169                    HStack {170                        Text(NFTText.sourceName(p.id)).font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.ink)171                        Spacer()172                        Pill(text: p.on ? String(localized: "activée") : String(localized: "désactivée"), tone: p.on ? .ok : .neutral)173                    }174                    Text(NFTText.sends(p.sends)).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)175                    if let u = p.unlockedBy, !p.on { Text(verbatim: u).font(.system(size: 12, design: .monospaced)).foregroundStyle(Theme.mute) }176                }.padding(.vertical, 4)177            }178            if let max = caps.mediaMaxBytes { Text(String(localized: "Taille maximale d’un média servi par le serveur : \(NFTMediaText.bytes(max)).")).font(.spFootnote).foregroundStyle(Theme.mute) }179        }.spCard(padding: 16)180    }181}182183// MARK: - lookup / manual tracking184185enum NFTLookupForm {186    enum Problem: Error, Equatable { case address, tokenIdRequired, tokenId }187188    /** The reference the owner typed, or what is wrong with it before any request. The server re-validates everything on-chain. */189    static func reference(chain: String, family: String, address: String, tokenId: String) -> Result<NFTReference, Problem> {190        let a = address.trimmingCharacters(in: .whitespacesAndNewlines), t = tokenId.trimmingCharacters(in: .whitespacesAndNewlines)191        guard (26...64).contains(a.count), a.range(of: "^[A-Za-z0-9]+$", options: .regularExpression) != nil else { return .failure(.address) }192        guard family == "evm" else { return .success(NFTReference(chain: chain, address: a)) }193        guard a.range(of: "^0x[0-9a-fA-F]{40}$", options: .regularExpression) != nil else { return .failure(.address) }194        guard !t.isEmpty else { return .failure(.tokenIdRequired) }195        guard t.range(of: "^([0-9]{1,78}|0x[0-9a-fA-F]{1,64})$", options: .regularExpression) != nil else { return .failure(.tokenId) }196        return .success(NFTReference(chain: chain, address: a, tokenId: t))197    }198}199200struct NFTLookupView: View {201    let ctx: NFTContext202    @Environment(AppModel.self) private var model203    let capabilities: NFTCapabilities?204    @State private var chain: String?205    @State private var address = ""206    @State private var tokenId = ""207    @State private var busy = false208    @State private var error: Error?209    @State private var found: NFTAsset?210    @State private var tracked = false211212    private var chains: [NFTChainCapability] { (capabilities?.chains ?? []).filter { $0.lookup || $0.manualAdd } }213    private var cap: NFTChainCapability? { chains.first { $0.network == chain } }214    private var reference: Result<NFTReference, NFTLookupForm.Problem>? {215        guard let c = cap, !address.trimmingCharacters(in: .whitespaces).isEmpty else { return nil }216        return NFTLookupForm.reference(chain: c.network, family: c.family, address: address, tokenId: tokenId)217    }218219    var body: some View {220        ScrollView {221            VStack(alignment: .leading, spacing: Theme.Space.section) {222                NFTFixtureBanner(ctx: ctx)223                FreshnessBanner()224                Text(String(localized: "Ouvre n’importe quel NFT par son identifiant de chaîne, qu’il soit ou non dans ce portefeuille. Les données viennent de la chaîne et de la métadonnée de son créateur ; rien n’est déduit."))225                    .font(.spCallout).foregroundStyle(Theme.mute)226                if chains.isEmpty {227                    Notice(tone: .warn, title: String(localized: "Aucun réseau ne permet l’ouverture par identifiant"), message: capabilities == nil ? String(localized: "L’état des réseaux n’a pas été chargé.") : nil)228                } else { form }229            }230            .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12).frame(maxWidth: 620).frame(maxWidth: .infinity)231        }232        .spPage().navigationTitle(String(localized: "Ouvrir ou suivre un NFT")).navigationBarTitleDisplayMode(.inline)233        .navigationDestination(item: $found) { a in NFTItemView(ctx: ctx, key: a.key, preloaded: a).wallet(model) }234        .onAppear { if chain == nil { chain = chains.first { NFTText.isDiscoveryNotConfigured($0.reason) }?.network ?? chains.first?.network } }235    }236237    @ViewBuilder private var form: some View {238        VStack(alignment: .leading, spacing: 12) {239            Picker(String(localized: "Réseau"), selection: $chain) {240                ForEach(chains) { c in Text(c.name).tag(Optional(c.network)) }241            }.pickerStyle(.menu).accessibilityIdentifier("nft.lookup.chain")242            if let c = cap {243                let evm = c.family == "evm"244                TextField(evm ? String(localized: "Adresse du contrat (0x…)") : String(localized: "Adresse du mint ou de l’actif"), text: $address, axis: .vertical)245                    .font(.spMono).textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.asciiCapable).lineLimit(1...3)246                    .padding(12).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small)).accessibilityIdentifier("nft.lookup.address")247                if evm {248                    TextField(String(localized: "Identifiant du jeton (token ID)"), text: $tokenId)249                        .font(.spMono).textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.asciiCapable)250                        .padding(12).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small)).accessibilityIdentifier("nft.lookup.tokenId")251                }252                Button { if let s = UIPasteboard.general.string { address = s.trimmingCharacters(in: .whitespacesAndNewlines) } } label: { Label(String(localized: "Coller l’adresse"), systemImage: "doc.on.clipboard") }253                    .buttonStyle(.bordered).font(.spCallout.weight(.semibold))254                if case .failure(let p)? = reference {255                    Label(problem(p), systemImage: "exclamationmark.triangle.fill").font(.spFootnote).foregroundStyle(Theme.danger).accessibilityIdentifier("nft.lookup.problem")256                }257            }258        }.spCard()259        if let e = error { NFTErrorNotice(error: e).accessibilityIdentifier("nft.lookup.error") }260        if tracked { Notice(tone: .ok, title: String(localized: "Suivi enregistré par le serveur"), message: String(localized: "La pièce a été vérifiée sur la chaîne avant d’être suivie. Elle apparaît dans la galerie selon ce que dit l’inventaire du serveur.")) }261        let ready: Bool = { if case .success? = reference { return model.canOperate && !busy } else { return false } }()262        Button { Task { await run(track: false) } } label: { HStack { if busy { ProgressView().tint(Theme.onPrimary) }; Text(String(localized: "Ouvrir (lecture seule)")) } }263            .buttonStyle(.spPrimary).disabled(!ready || cap?.lookup != true).accessibilityIdentifier("nft.lookup.open")264        Button { Task { await run(track: true) } } label: { Label(String(localized: "Suivre ce NFT dans la galerie"), systemImage: "plus.circle") }265            .buttonStyle(.spSecondary).disabled(!ready || cap?.manualAdd != true).accessibilityIdentifier("nft.lookup.track")266        Text(String(localized: "« Ouvrir » ne modifie rien. « Suivre » demande au serveur de vérifier la pièce sur la chaîne puis de la suivre : c’est ainsi qu’un NFT entre dans l’inventaire sur un réseau sans découverte automatique."))267            .font(.spFootnote).foregroundStyle(Theme.mute)268        if !model.canOperate { Notice(tone: .warn, title: String(localized: "Indisponible hors ligne"), message: String(localized: "L’ouverture d’un NFT exige le serveur.")) }269    }270271    private func problem(_ p: NFTLookupForm.Problem) -> String {272        switch p {273        case .address: String(localized: "Ce n’est pas un identifiant valide pour ce réseau.")274        case .tokenIdRequired: String(localized: "L’identifiant du jeton est requis sur un réseau EVM.")275        case .tokenId: String(localized: "L’identifiant du jeton est un nombre décimal ou 0x-hexadécimal.")276        }277    }278279    private func run(track: Bool) async {280        guard case .success(let ref)? = reference, !busy else { return }281        busy = true; error = nil; tracked = false282        defer { busy = false }283        do {284            let a = try await (track ? ctx.api.track(ref) : ctx.api.lookup(ref))285            if track { tracked = true; ctx.revision += 1 }286            found = a287        } catch { self.error = error }288    }289}290291// MARK: - receive292293struct NFTReceiveView: View {294    let ctx: NFTContext295    @Environment(AppModel.self) private var model296    @State private var rows = Loaded<[NFTReceiveAddress]>()297    @State private var qr: NFTReceiveAddress?298    @State private var copied: String?299300    var body: some View {301        ScrollView {302            VStack(alignment: .leading, spacing: Theme.Space.section) {303                NFTFixtureBanner(ctx: ctx)304                FreshnessBanner()305                if let list = rows.value {306                    if rows.isCached, let at = rows.savedAt { Notice(tone: .info, title: String(localized: "Adresses enregistrées le \(at.formatted(date: .abbreviated, time: .shortened))"), message: String(localized: "Les adresses du portefeuille ne changent pas."), icon: "clock") }307                    if list.isEmpty { EmptyState(icon: "arrow.down.left", title: String(localized: "Aucune adresse de réception NFT servie par le serveur")) }308                    ForEach(list) { r in row(r) }309                    Text(String(localized: "Un NFT n’apparaît dans la galerie qu’après sa confirmation sur la chaîne et la synchronisation suivante — jamais avant.")).font(.spFootnote).foregroundStyle(Theme.mute)310                } else if let e = rows.error { NFTErrorNotice(error: e) { Task { await load() } } }311                else { ProgressView().frame(maxWidth: .infinity).padding(.vertical, 40) }312            }313            .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12).frame(maxWidth: 620).frame(maxWidth: .infinity)314        }315        .spPage().navigationTitle(String(localized: "Recevoir un NFT")).navigationBarTitleDisplayMode(.inline)316        .task(id: model.canOperate) { await load() }317        .sheet(item: $qr) { r in318            NavigationStack {319                VStack(spacing: 16) {320                    HStack { NetworkIcon(network: r.network, size: 30); Text(r.name).font(.spHeadline) }321                    QRCodeView(content: r.address)322                    Text(verbatim: r.address).font(.spMono).multilineTextAlignment(.center).textSelection(.enabled).padding(.horizontal, 24)323                    Spacer()324                }325                .padding(.top, 24).spPage()326                .toolbar { ToolbarItem(placement: .cancellationAction) { Button(String(localized: "Fermer")) { qr = nil } } }327            }.presentationDetents([.medium, .large]).wallet(model)328        }329    }330331    private func load() async {332        if rows.value == nil, let c = await ctx.cache.load([NFTReceiveAddress].self, key: "nft.receive") { rows.set(cached: c) }333        guard model.canOperate else { return }334        do { let v = try await ctx.api.receiveAddresses(); rows.set(live: v); await ctx.cache.save(v, key: "nft.receive") }335        catch let e as APIError { rows.fail(e) } catch {}336    }337338    private func row(_ r: NFTReceiveAddress) -> some View {339        let det = NFTText.inventory(r.detection)340        return VStack(alignment: .leading, spacing: 10) {341            HStack(spacing: 10) {342                NetworkIcon(network: r.network, size: 30)343                Text(r.name).font(.spHeadline).foregroundStyle(Theme.ink)344                Spacer()345                Pill(text: String(localized: "Détection : \(det.0.lowercased())"), tone: det.1)346            }347            Text(verbatim: r.address).font(.spMono).foregroundStyle(Theme.ink).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)348                .padding(12).frame(maxWidth: .infinity, alignment: .leading).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small))349                .accessibilityIdentifier("nft.receive.address")350            HStack(spacing: 8) {351                Button {352                    UIPasteboard.general.setItems([[UIPasteboard.typeAutomatic: r.address]], options: [.expirationDate: Date().addingTimeInterval(180)])353                    copied = r.network354                } label: { Label(copied == r.network ? String(localized: "Copiée") : String(localized: "Copier"), systemImage: copied == r.network ? "checkmark" : "doc.on.doc") }355                Button { qr = r } label: { Label(String(localized: "Code QR"), systemImage: "qrcode") }356            }.buttonStyle(.bordered).font(.spCallout.weight(.semibold))357            Text(String(localized: "N’envoie à cette adresse que des NFT du réseau \(r.name) et de ces standards : \(r.standards.map { NFTText.standard($0) }.joined(separator: ", ")). Un NFT d’un autre réseau ou d’un standard non lu peut ne jamais apparaître ici."))358                .font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)359            ForEach(r.warnings, id: \.self) { w in360                Label(NFTText.receiveWarning(w), systemImage: "exclamationmark.triangle.fill").font(.spFootnote).foregroundStyle(Theme.warn).fixedSize(horizontal: false, vertical: true)361            }362        }.spCard(padding: 16)363    }364}365
Files main
Menu

Theme