SPB Git

Repository Public

NFTItemView.swift 40.0 KB 661 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet for macOS9// File             : Features/NFTs/NFTItemView.swift10// Description      : The page of one NFT: its media (through the server's proxy11//                    only; images downsampled by ImageIO, MP4 / audio played by12//                    AVKit, everything else shown as a neutral "not13//                    displayable" tile), its identity as the chain gives it14//                    (network, standard, token id, full contract / mint,15//                    quantity), ownership, the creator's metadata as plain16//                    untrusted text, provenance stamps, on-chain history, this17//                    wallet's own transfers, the transfer verdict and the entry18//                    to the transfer flow, and the market READ section. Flags19//                    (indexer spam signal, unverified collection, stale20//                    ownership) are shown at the top, never hidden.21// Module           : Features22// Repository       : https://git.spboucher.ai/sp-wallet-macos23// Created          : 2026-11-1824// Last Modified    : 2026-11-1825//26// =============================================================================27// AUTHOR & PROFESSIONAL AFFILIATION28// =============================================================================29//30// Author           : Simon-Pierre Boucher31// Position         : Professor of Finance32// Institution      : Université du Québec en Outaouais (UQO)33// Department       : Département des sciences administratives34// Organization     : SP Boucher35//36// Website          : https://spboucher.ai37// Git              : https://git.spboucher.ai38//39// =============================================================================40// OFFICIAL CONTACT DIRECTORY41// =============================================================================42//43// General          : info@spboucher.ai44// Professional     : contact@spboucher.ai45// Direct           : simon@spboucher.ai46// Research         : research@spboucher.ai47// Development      : dev@spboucher.ai48// Support          : support@spboucher.ai49// Security/Admin   : admin@spboucher.ai50// Notifications    : notifications@spboucher.ai51//52// Preferred Contact: support@spboucher.ai53//54// =============================================================================55// COPYRIGHT & INTELLECTUAL PROPERTY56// =============================================================================57//58// Copyright (c) 202659// Simon-Pierre Boucher60//61// All rights reserved where applicable.62//63// This file is governed by the applicable project license,64// copyright notices, institutional agreements and relevant law.65//66// Unless expressly authorized by the applicable license or67// rights holder, copying, redistribution, sublicensing,68// publication and commercial exploitation are not permitted.69//70// Existing third-party rights and notices remain unaffected.71//72// =============================================================================73// CONFIDENTIALITY & SECURITY74// =============================================================================75//76// Classification   : Public77// Distribution     : Public repository; use is governed by the project license78// Security Contact : admin@spboucher.ai79//80// Access to this source does not independently grant permission81// to redistribute or disclose confidential materials.82//83// Do not embed credentials, private keys, access tokens,84// certificates or confidential personal information.85//86// =============================================================================87// LICENSE & MAINTENANCE88// =============================================================================89//90// License          : None specified (no license file in this repository)91// Maintainer       : Simon-Pierre Boucher92// Technical Contact: dev@spboucher.ai93//94// =============================================================================95// END OF SP BOUCHER SOURCE HEADER96// =============================================================================9798import SwiftUI99import AVKit100import CryptoKit101import SPWalletCore102103@MainActor @Observable final class NFTItemModel {104    let model: AppModel105    let api: NFTAPI106    let key: String107108    private(set) var asset: NFTAsset?109    private(set) var assetAt: Date?110    private(set) var fromCache = false111    private(set) var loading = false112    private(set) var missing = false113    var error: String?114115    private(set) var verdict: NFTTransferVerdictAnswer?116    private(set) var verdictError: String?117    private(set) var events: [NFTEvent] = []118    private(set) var activity: NFTActivity?119    private(set) var activityLoading = false120    private(set) var activityError: String?121    private(set) var transfers: [NFTTransfer] = []122    private(set) var working = false123    var actionError: String?124    var actionNote: String?125126    init(model: AppModel, key: String) { self.model = model; self.key = key; api = NFTAPI(model.client) }127128    private var snapshotKey: String { "nft-item-" + SHA256.hash(data: Data(key.utf8)).prefix(16).map { String(format: "%02x", $0) }.joined() }129130    func load() async {131        if asset == nil, let s: Snapshot<NFTAsset> = await SnapshotStore.shared.load(snapshotKey), s.value.key == key {132            asset = s.value; assetAt = s.savedAt; fromCache = true133        }134        guard model.phase == .signedIn, !loading else { return }135        loading = true; defer { loading = false }136        do {137            let a = try await api.item(key: key)138            guard a.key == key else { throw APIError(status: 0, code: "nft_key_mismatch", message: "le serveur a répondu un autre actif que celui demandé") }139            asset = a; assetAt = Date(); fromCache = false; error = nil; missing = false140            await SnapshotStore.shared.save(a, as: snapshotKey)141        } catch let e as APIError where e.code == "nft_not_found" {142            missing = true; error = "Cet NFT n’est pas (ou plus) dans l’inventaire du serveur. Utilisez « Rechercher ou suivre » pour l’ouvrir par son identifiant."143        } catch {144            self.error = model.describe(error)145            if asset != nil { fromCache = true }146            return147        }148        guard !missing else { return }149        async let v: Void = loadVerdict()150        async let a: Void = loadActivity(reset: true)151        async let t: Void = loadTransfers()152        _ = await (v, a, t)153    }154155    func loadVerdict() async {156        do { verdict = try await api.transferVerdict(key: key); verdictError = nil } catch { verdictError = model.describe(error) }157    }158    func loadTransfers() async { if let t = try? await api.transfers(key: key, limit: 20) { transfers = t } }159160    /// `reset`: the first page of the stored events. `older`: ask the server to continue its chain scan. Otherwise: the next stored page.161    func loadActivity(reset: Bool = false, older: Bool = false) async {162        guard !activityLoading else { return }163        activityLoading = true; defer { activityLoading = false }164        do {165            let page = try await api.activity(key: key, cursor: reset || older ? nil : activity?.cursor, limit: 20, loadOlder: older)166            if reset || older { events = page.events } else { let known = Set(events.map(\.id)); events += page.events.filter { !known.contains($0.id) } }167            activity = page; activityError = nil168        } catch { activityError = model.describe(error) }169    }170171    func refreshMetadata() async {172        guard model.canOperate, !working else { return }173        working = true; actionError = nil; actionNote = nil; defer { working = false }174        do {175            let a = try await api.refreshMetadata(key: key)176            guard a.key == key else { return }177            // the refresh answer carries no transfer verdict: read the item again so the page stays whole178            await NFTMediaStore.shared.forgetFailures()179            actionNote = "Métadonnées relues auprès de la source du créateur le \(Fmt.date(Date())). La propriété et l’identité restent celles de la chaîne."180            await load()181        } catch { actionError = model.describe(error) }182    }183184    /// Stops tracking a hand-tracked asset. Returns true when the server removed it.185    func untrack() async -> Bool {186        guard model.canOperate, !working else { return false }187        working = true; actionError = nil; defer { working = false }188        do { return try await api.untrack(key: key).removed } catch { actionError = model.describe(error); return false }189    }190}191192struct NFTItemPage: View {193    let model: AppModel194    let gallery: NFTGallery195    let key: String196    let open: (NFTRoute) -> Void197    let back: () -> Void198    @State private var item: NFTItemModel?199    @State private var sending = false200201    var body: some View {202        Page(title, subtitle: subtitle) {203            NFTBackBar(title: "Galerie", back: back)204            if let item {205                if let e = item.error { Banner(item.asset == nil ? .danger : .warning, e) }206                if let a = item.asset {207                    if item.fromCache { Banner(.warning, "Lecture seule — fiche telle que lue le \(Fmt.date(item.assetAt)). Elle peut ne plus refléter la chaîne ; le transfert est désactivé.") }208                    NFTItemFlags(asset: a)209                    HStack(alignment: .top, spacing: 16) {210                        NFTItemMedia(model: model, gallery: gallery, asset: a).frame(width: 430)211                        NFTIdentityCard(model: model, gallery: gallery, asset: a, open: open)212                    }213                    NFTTransferCard(model: model, gallery: gallery, item: item, asset: a, send: { sending = true })214                    NFTMetadataCard(asset: a)215                    NFTOwnershipCard(asset: a)216                    NFTHistoryCard(model: model, item: item)217                    NFTMarketSection(model: model, gallery: gallery, asset: a, offline: item.fromCache || !model.canOperate)218                    NFTProvenanceCard(asset: a)219                    actions(item, a)220                } else if item.loading { HStack { ProgressView().controlSize(.small); Text("Lecture de l’actif et vérification de sa propriété sur la chaîne…").foregroundStyle(.secondary) } }221                else if let s = gallery.summary(key) {222                    Banner(.info, "La fiche complète de cet NFT n’a pas été synchronisée sur ce Mac. Voici ce que l’inventaire en dit.")223                    Card { Field(label: "Réseau", value: gallery.networkName(s.chain)); Field(label: "Standard", value: NFTText.standard(s.standard)); Field(label: "Identifiant", value: s.assetId, mono: true); Field(label: "Quantité", value: s.quantity) }224                } else if item.error == nil {225                    EmptyState(symbol: "icloud.slash", title: "Fiche indisponible hors connexion", detail: "Cet NFT n’a pas été ouvert sur ce Mac avant la perte de connexion : aucune donnée locale à afficher.")226                }227            } else { ProgressView() }228        }229        .task {230            if item == nil { item = NFTItemModel(model: model, key: key) }231            await item?.load()232        }233        .sheet(isPresented: $sending) {234            if let item, let a = item.asset {235                NFTTransferSheet(model: model, gallery: gallery, asset: a, verdict: item.verdict, close: { changed in236                    sending = false237                    if changed { Task { await item.load(); await gallery.load() } }238                })239            }240        }241    }242243    private var title: String {244        if let a = item?.asset { return NFTClean.line(a.displayName, max: 100) ?? "NFT sans nom" }245        return NFTClean.line(gallery.summary(key)?.displayName, max: 100) ?? "NFT"246    }247    private var subtitle: String? {248        guard let a = item?.asset else { return nil }249        return "\(NFTClean.line(a.collection?.name) ?? "Sans collection") · \(gallery.networkName(a.chainId)) · nom et collection déclarés par le créateur, non vérifiés"250    }251252    @ViewBuilder private func actions(_ item: NFTItemModel, _ a: NFTAsset) -> some View {253        Card("Actions de lecture") {254            if let e = item.actionError { Banner(.danger, e) }255            if let n = item.actionNote { Banner(.ok, n) }256            HStack {257                Button { Task { await item.load() } } label: { Label("Relire la fiche", systemImage: "arrow.clockwise") }.disabled(model.phase != .signedIn || item.loading)258                Button { Task { await item.refreshMetadata() } } label: { Label("Relire les métadonnées du créateur", systemImage: "doc.text.magnifyingglass") }259                    .disabled(!model.canOperate || item.working).help("Le serveur relit l’URI de métadonnées (une fois par minute au plus par actif).")260                if a.origin == "manual" {261                    Button("Ne plus suivre", role: .destructive) { Task { if await item.untrack() { await gallery.load(); back() } } }.disabled(!model.canOperate || item.working)262                        .help("Retire cet actif suivi à la main de l’inventaire du serveur. Rien n’est modifié sur la chaîne.")263                }264                if item.loading || item.working { ProgressView().controlSize(.small) }265                Spacer()266            }267        }268    }269}270271// MARK: - Flags272273private struct NFTItemFlags: View {274    let asset: NFTAsset275    var body: some View {276        VStack(alignment: .leading, spacing: 8) {277            if let f = asset.indexerFlags, f.spam {278                Banner(.danger, "Signalé comme INDÉSIRABLE (spam) par \(NFTText.sourceName(f.by))\(f.classifications.isEmpty ? "" : " — classifications : \(f.classifications.joined(separator: ", "))"). C’est la déclaration de cet indexeur. N’ouvrez aucun lien de ses métadonnées et ne signez rien qu’il vous demanderait ailleurs.")279            } else if let f = asset.indexerFlags, !f.classifications.isEmpty {280                Banner(.warning, "Classifications rapportées par \(NFTText.sourceName(f.by)) : \(f.classifications.joined(separator: ", ")).")281            }282            if asset.ownership.state != "in_wallet" {283                Banner(asset.ownership.state == "unknown" ? .warning : .info, "\(NFTText.ownership(asset.ownership.state))\(asset.goneAt.map { " — constaté le \(Fmt.date($0))" } ?? "").")284            }285            if let c = asset.collection {286                switch c.verifiedOnChain {287                case .known(false): Banner(.warning, "Collection NON vérifiée sur la chaîne : l’appartenance à cette collection est une simple déclaration de l’actif. Une contrefaçon se présente ainsi.")288                case .unknown: Banner(.warning, "La vérification on-chain de la collection n’a pas pu être établie.")289                default: EmptyView()290                }291            }292            if asset.ownership.source.isStale { Banner(.warning, "La propriété n’a pas été relue récemment sur la chaîne (dernière lecture \(Fmt.relative(asset.ownership.source.fetchedAt))).") }293            if asset.origin == "lookup" { Banner(.info, "Actif ouvert par recherche explicite : il ne fait pas partie de l’inventaire de ce portefeuille.") }294        }295    }296}297298// MARK: - Media299300private struct NFTItemMedia: View {301    let model: AppModel302    let gallery: NFTGallery303    let asset: NFTAsset304    @State private var selected = ""305    @State private var state: Shown = .loading306    @State private var player: AVPlayer?307    @State private var file: NFTPlayableFile?308    @State private var info: NFTMediaInfo?309310    enum Shown { case loading, image(CGImage), playable(isAudio: Bool), message(symbol: String, title: String, detail: String) }311312    private var media: NFTMedia? { asset.media.first { $0.id == selected } }313    private var api: NFTAPI? { gallery.mediaAPI }314315    var body: some View {316        VStack(alignment: .leading, spacing: 8) {317            ZStack {318                RoundedRectangle(cornerRadius: Theme.corner).fill(Color.secondary.opacity(0.10))319                switch state {320                case .loading: ProgressView()321                case .image(let image): Image(decorative: image, scale: 1).resizable().interpolation(.high).aspectRatio(contentMode: .fit).clipShape(RoundedRectangle(cornerRadius: Theme.corner))322                case .playable(let isAudio):323                    if let player { VideoPlayer(player: player).clipShape(RoundedRectangle(cornerRadius: Theme.corner)).padding(isAudio ? 24 : 0) }324                case .message(let symbol, let title, let detail):325                    VStack(spacing: 8) {326                        Image(systemName: symbol).font(.system(size: 34)).foregroundStyle(.tertiary)327                        Text(title).font(.headline)328                        NFTPlain(detail).font(.callout).foregroundStyle(.secondary).multilineTextAlignment(.center).textSelection(.enabled)329                    }.padding(20)330                }331            }332            .aspectRatio(1, contentMode: .fit)333            if asset.media.count > 1 {334                Picker("Média", selection: $selected) {335                    ForEach(asset.media) { m in NFTPlain("\(role(m.role)) — \(m.mime ?? m.declaredMime ?? m.kind)").tag(m.id) }336                }.labelsHidden()337            }338            if let m = media {339                VStack(alignment: .leading, spacing: 2) {340                    NFTPlain("Servi par le proxy du serveur — jamais chargé depuis l’URI du créateur. État : \(NFTText.mediaStatus(info?.status ?? m.status))\((info?.code ?? m.errorCode).map { " (\($0))" } ?? "").")341                    NFTPlain("Type établi par le serveur d’après les octets : \(info?.mime ?? m.mime ?? "non établi")\(m.declaredMime.map { " · type annoncé par le créateur : \($0)" } ?? "")\((info?.bytes.map(String.init) ?? m.bytes).map { " · \($0) octets" } ?? "")")342                    if (info?.mime ?? m.mime) == "image/gif" { Text("GIF : seule la première image est affichée.") }343                    NFTPlain("URI du créateur (texte, non ouverte) : \(NFTClean.line(m.sourceUri, max: 300) ?? "—")").lineLimit(2).textSelection(.enabled)344                }.font(.caption).foregroundStyle(.secondary)345            }346        }347        .task(id: "\(selected)|\(api == nil)") { await show() }348        .onAppear { if selected.isEmpty { selected = (asset.media.first { $0.role == "image" } ?? asset.media.first)?.id ?? "" } }349        .onDisappear { release() }350    }351352    private func role(_ r: String) -> String { switch r { case "image": "Image"; case "animation": "Animation"; case "file": "Fichier"; default: r } }353354    private func release() {355        player?.pause(); player = nil356        if let f = file { file = nil; Task { await NFTMediaStore.shared.discard(f) } }357    }358359    private func show() async {360        release(); info = nil361        guard let m = media else { state = .message(symbol: "photo", title: "Aucun média déclaré", detail: "Les métadonnées de cet NFT ne nomment aucun fichier (\(NFTText.metadataStatus(asset.metadata.status)))."); return }362        state = .loading363        let limit = gallery.mediaLimit364        guard let api else {365            // offline: only the grid thumbnail already on this Mac can be shown366            if case .image(let image) = await NFTMediaStore.shared.thumbnail(id: m.id, pixels: NFTMediaStore.gridPixels, api: nil, maxBytes: limit) { state = .image(image) }367            else { state = .message(symbol: "icloud.slash", title: "Média indisponible hors connexion", detail: "Ce fichier n’avait pas été téléchargé sur ce Mac.") }368            return369        }370        do {371            let i = try await api.mediaInfo(id: m.id)372            if Task.isCancelled { return }373            info = i374            guard i.isAvailable, let mime = i.mime else {375                state = .message(symbol: "icloud.slash", title: "Média indisponible", detail: "Le proxy du serveur ne sert pas ce fichier : \(NFTText.mediaStatus(i.status))\(i.code.map { " (\($0))" } ?? "").")376                return377            }378            if mime == "image/svg+xml" || mime == "text/html" || i.kind == "html" {379                state = .message(symbol: "eye.slash", title: "Média non affichable", detail: "Type \(mime) : un document qui peut contenir du script. Cette app n’exécute ni ne rend jamais de HTML ou de SVG provenant d’un NFT, et le serveur ne le convertit pas en image.")380            } else if i.kind == "image" {381                switch await NFTMediaStore.shared.thumbnail(id: m.id, pixels: NFTMediaStore.detailPixels, api: api, maxBytes: limit) {382                case .image(let image): if !Task.isCancelled { state = .image(image) }383                case .notDisplayable(let why): state = .message(symbol: "eye.slash", title: "Média non affichable", detail: why)384                case .unavailable(let why): state = .message(symbol: "icloud.slash", title: "Média indisponible", detail: why)385                }386            } else if NFTMediaStore.playableTypes[mime] != nil {387                if let bytes = i.bytes, bytes > limit {388                    state = .message(symbol: "eye.slash", title: "Média non chargé", detail: "Fichier de \(bytes) octets, au-delà de la limite de téléchargement de cette app (\(limit) octets).")389                    return390                }391                let f = try await NFTMediaStore.shared.playable(id: m.id, api: api, maxBytes: limit)392                if Task.isCancelled { await NFTMediaStore.shared.discard(f); return }393                file = f; player = AVPlayer(url: f.url); state = .playable(isAudio: f.isAudio)394            } else {395                state = .message(symbol: "eye.slash", title: "Média non affichable", detail: "Type \(mime) (\(i.kind ?? "inconnu")) : macOS ne le lit pas nativement, et cette app ne confie aucun contenu de NFT à un moteur web.")396            }397        } catch is CancellationError {398        } catch { if !Task.isCancelled { state = .message(symbol: "icloud.slash", title: "Média indisponible", detail: NFTMediaStore.text(error)) } }399    }400}401402// MARK: - Identity403404private struct NFTIdentityCard: View {405    let model: AppModel406    let gallery: NFTGallery407    let asset: NFTAsset408    let open: (NFTRoute) -> Void409410    var body: some View {411        let a = asset412        Card("Identité sur la chaîne", trailing: AnyView(ProvenanceTag(p: a.ownership.source.isChainVerified ? .verified : .stale, text: a.ownership.source.isChainVerified ? "Propriété vérifiée sur la chaîne" : NFTText.confidence(a.ownership.source.confidence)))) {413            Field(label: "Réseau", value: "\(gallery.networkName(a.chainId))  (\(a.chainId))")414            Field(label: "Standard", value: NFTText.standard(a.standard), emphasis: true)415            if let t = a.tokenId { Field(label: "Identifiant du jeton", value: t, mono: true) }416            if let c = a.contractAddress { Field(label: "Contrat", value: c, mono: true) }417            if let m = a.mintAddress { Field(label: a.standard == .metaplexCore ? "Adresse de l’actif" : "Mint", value: m, mono: true) }418            if a.contractAddress == nil, a.mintAddress == nil { Field(label: "Identifiant de l’actif", value: a.assetId, mono: true) }419            Field(label: a.standard == .erc1155 ? "Quantité détenue (ERC-1155)" : "Quantité détenue", value: Fmt.amount(a.quantity), emphasis: a.standard == .erc1155 || a.quantity != "1")420            Field(label: "Offre totale", value: NFTText.known(a.supply) { Fmt.amount($0) })421            if let c = a.collection {422                Field(label: "Collection", value: "\(NFTClean.line(c.name) ?? "sans nom déclaré") — vérifiée sur la chaîne : \(NFTText.knownBool(c.verifiedOnChain))")423                Field(label: "Identifiant de collection", value: c.id, mono: true)424                HStack { Spacer().frame(width: 182); Button("Page de la collection") { open(.collection(c.key)) }.buttonStyle(.link) }425            } else { Field(label: "Collection", value: "Aucune") }426            if let p = a.tokenProgram { Field(label: "Programme de jetons", value: p, mono: true) }427            if !a.extensions.isEmpty { Field(label: "Extensions / plugins", value: a.extensions.joined(separator: ", ")) }428            Field(label: "Redevance du créateur", value: NFTText.known(a.royaltyBps) { "\($0) points de base (\(Double($0) / 100) %)" })429            Field(label: "Jeu de règles (pNFT)", value: NFTText.known(a.ruleSet) { $0 }, mono: a.ruleSet.isKnown)430            Field(label: "Autorité de mise à jour", value: NFTText.known(a.updateAuthority) { $0 }, mono: a.updateAuthority.isKnown)431            if case .known(let creators) = a.creators, !creators.isEmpty {432                Field(label: "Créateurs", value: creators.map { "\($0.address) — \($0.verified ? "vérifié" : "NON vérifié"), part \($0.share) %" }.joined(separator: "\n"), mono: true)433            }434            Field(label: "Entrée dans l’inventaire", value: NFTText.origin(a.origin))435            Field(label: "Vu pour la première fois", value: Fmt.date(a.firstSeen))436            Field(label: "Propriété relue le", value: Fmt.date(a.verifiedAt))437            HStack(spacing: 14) {438                NFTExternalLinkView(title: "Explorateur de blocs", raw: a.explorerUrl)439                Button("Copier l’adresse") { copyToPasteboard(a.assetAddress) }.buttonStyle(.link)440            }441        }442    }443}444445private struct NFTOwnershipCard: View {446    let asset: NFTAsset447    var body: some View {448        let o = asset.ownership449        Card("Propriété") {450            Field(label: "État", value: NFTText.ownership(o.state), emphasis: true)451            Field(label: "Détenteur selon la chaîne", value: NFTText.known(o.owner) { $0 }, mono: o.owner.isKnown)452            if let w = asset.ownerAddress { Field(label: "Adresse de ce portefeuille", value: w, mono: true) }453            Field(label: "Compte de jetons", value: NFTText.known(o.tokenAccount) { $0 }, mono: o.tokenAccount.isKnown)454            Field(label: "Gelé", value: NFTText.knownBool(o.frozen))455            Field(label: "Délégué", value: NFTText.known(o.delegate) { $0 }, mono: o.delegate.isKnown)456            Field(label: "État du token record", value: NFTText.known(o.tokenRecordState) { $0 })457            NFTPlain(NFTText.stamp(o.source)).font(.caption).foregroundStyle(.secondary)458        }459    }460}461462// MARK: - Creator metadata (untrusted, plain text)463464private struct NFTMetadataCard: View {465    let asset: NFTAsset466    @State private var showRaw = false467468    private var onchainName: String {469        let parts = [NFTClean.line(asset.metadata.onchainName), NFTClean.line(asset.metadata.onchainSymbol).map { "(\($0))" }].compactMap { $0 }470        return parts.isEmpty ? "—" : parts.joined(separator: " ")471    }472473    var body: some View {474        let m = asset.metadata475        Card("Métadonnées déclarées par le créateur", trailing: AnyView(NFTFlag(text: "Non vérifié — texte brut", color: .secondary))) {476            Text("Tout ce qui suit est du contenu distant non fiable, affiché comme simple texte : aucun lien n’y est suivi, aucun balisage n’y est interprété.").font(.caption).foregroundStyle(.secondary)477            Field(label: "État de lecture", value: NFTText.metadataStatus(m.status) + (m.errorCode.map { " (\($0))" } ?? ""))478            Field(label: "Nom (créateur)", value: NFTClean.line(m.name, max: 300) ?? "—")479            Field(label: "Nom sur la chaîne", value: onchainName)480            if let d = NFTClean.text(m.description, max: 4_000) { Field(label: "Description", value: d) }481            Field(label: "Modifiables", value: NFTText.knownBool(m.mutable))482            if let u = m.externalUrl, !u.isEmpty {483                HStack(alignment: .firstTextBaseline, spacing: 12) {484                    Text("Lien du créateur").foregroundStyle(.secondary).frame(width: 170, alignment: .leading)485                    VStack(alignment: .leading, spacing: 2) {486                        NFTExternalLinkView(title: "Ouvrir dans le navigateur", raw: u)487                        Text("Lien choisi par le créateur de l’NFT : SP Wallet ne le cautionne pas. Ne connectez ce portefeuille à aucun site.").font(.caption).foregroundStyle(Theme.warning)488                    }489                }490            }491            if let u = m.sourceUri { Field(label: "URI des métadonnées", value: NFTClean.line(u, max: 400) ?? "—", mono: true) }492            if let h = m.contentHash { Field(label: "SHA-256 du document", value: h, mono: true) }493            if let s = m.source { NFTPlain(NFTText.stamp(s)).font(.caption).foregroundStyle(.secondary) }494            if !m.attributes.isEmpty {495                Divider()496                Text("Attributs (\(m.attributes.count))").font(.subheadline.weight(.medium))497                LazyVGrid(columns: [GridItem(.adaptive(minimum: 220), spacing: 8, alignment: .top)], alignment: .leading, spacing: 8) {498                    ForEach(Array(m.attributes.prefix(200).enumerated()), id: \.offset) { _, t in499                        VStack(alignment: .leading, spacing: 2) {500                            NFTPlain(NFTClean.line(t.traitType, max: 80) ?? "(sans type)").font(.caption).foregroundStyle(.secondary)501                            NFTPlain(NFTClean.line(t.valueText, max: 160) ?? "—").textSelection(.enabled)502                            if let d = t.displayType { NFTPlain("affichage : \(NFTClean.line(d, max: 40) ?? "")\(t.maxValue.map { " · max \($0)" } ?? "")").font(.caption2).foregroundStyle(.secondary) }503                            if t.malformed { NFTFlag(text: "Entrée malformée") }504                        }505                        .padding(8).frame(maxWidth: .infinity, alignment: .leading).background(Color.secondary.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))506                    }507                }508                if m.attributes.count > 200 { Text("\(m.attributes.count - 200) attribut(s) supplémentaire(s) non affiché(s).").font(.caption).foregroundStyle(.secondary) }509                if let s = m.traitStatistics, !s.computed { NFTPlain("Aucune rareté n’est calculée par le serveur (\(s.reason)). Voir « Fréquence des traits » dans les données de marché.").font(.caption).foregroundStyle(.secondary) }510            }511            if let raw = m.raw {512                DisclosureGroup("Document JSON tel que lu par le serveur (texte inerte)", isExpanded: $showRaw) {513                    ScrollView { NFTPlain(NFTClean.text(raw.displayText, max: 20_000) ?? "").font(.system(.caption, design: .monospaced)).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) }.frame(maxHeight: 260)514                }.font(.callout)515            }516        }517    }518}519520private struct NFTProvenanceCard: View {521    let asset: NFTAsset522    var body: some View {523        Card("Provenance des données") {524            Text("Chaque valeur de cette fiche vient d’une seule de ces sources ; elles ne sont jamais fusionnées.").font(.caption).foregroundStyle(.secondary)525            ForEach(Array(asset.sources.enumerated()), id: \.offset) { _, s in526                VStack(alignment: .leading, spacing: 1) {527                    NFTPlain(NFTText.stamp(s)).font(.callout)528                    if !s.covers.isEmpty { NFTPlain("couvre : \(s.covers.joined(separator: ", "))").font(.caption).foregroundStyle(.secondary) }529                }530            }531            if let b = asset.blockRef { NFTPlain("Référence de bloc : \([b.number.map { "n° \($0)" }, b.slot.map { "slot \($0)" }, b.commitment, b.hash].compactMap { $0 }.joined(separator: " · "))").font(.caption).foregroundStyle(.secondary).textSelection(.enabled) }532        }533    }534}535536// MARK: - History537538private struct NFTHistoryCard: View {539    let model: AppModel540    let item: NFTItemModel541542    var body: some View {543        Card("Historique sur la chaîne", trailing: item.activityLoading ? AnyView(ProgressView().controlSize(.small)) : nil) {544            if let e = item.activityError { Banner(.warning, e) }545            if let a = item.activity {546                NFTPlain("\(NFTText.completeness(a.completeness))\(a.note.map { " — \($0)" } ?? "")\(a.scannedAt.map { " · lu le \(Fmt.date($0))" } ?? "")").font(.caption).foregroundStyle(a.completeness == "full" ? Color.secondary : Theme.warning)547                if let code = a.error { Banner(.warning, "La relecture de l’historique a échoué (\(code)) : les événements ci-dessous sont ceux déjà stockés.") }548            }549            if item.events.isEmpty, item.activity != nil { Text("Aucun événement connu pour cet actif.").foregroundStyle(.secondary) }550            ForEach(item.events) { e in551                NFTEventRow(event: e)552                Divider()553            }554            HStack {555                if item.activity?.cursor != nil { Button("Événements suivants") { Task { await item.loadActivity() } }.disabled(item.activityLoading || model.phase != .signedIn) }556                if item.activity?.canLoadOlder == true { Button("Remonter plus loin dans la chaîne") { Task { await item.loadActivity(older: true) } }.disabled(item.activityLoading || !model.canOperate) }557                Spacer()558            }559            if !item.transfers.isEmpty {560                Text("Transferts préparés depuis ce portefeuille").font(.subheadline.weight(.medium)).padding(.top, 4)561                ForEach(item.transfers) { t in562                    VStack(alignment: .leading, spacing: 2) {563                        HStack(spacing: 8) {564                            StatusPill(raw: t.state == .unknown ? "unknown" : t.state.rawValue)565                            NFTPlain("\(Fmt.date(t.proposal.createdAt)) · quantité \(t.proposal.amount)").font(.callout)566                            Spacer()567                            if let ex = NFTText.httpsURL(t.proposal.explorer) { Link("Explorateur", destination: ex).font(.callout) }568                        }569                        if let to = t.proposal.to { NFTPlain("vers \(to)").font(Theme.monoSmall).textSelection(.enabled) }570                        if let tx = t.proposal.txid { NFTPlain("transaction \(tx)").font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary).textSelection(.enabled) }571                        if let err = t.proposal.error { NFTPlain(err).font(.caption).foregroundStyle(Theme.negative) }572                    }573                }574            }575        }576    }577}578579private struct NFTEventRow: View {580    let event: NFTEvent581    var body: some View {582        let e = event583        VStack(alignment: .leading, spacing: 2) {584            HStack(spacing: 8) {585                Text(NFTText.eventType(e.type)).fontWeight(.medium)586                NFTFlag(text: NFTText.finality(e.finality), color: e.isFinal ? Theme.positive : Theme.warning)587                if e.quantity != "1" { NFTPlain("× \(e.quantity)").monospacedDigit() }588                Spacer()589                NFTPlain(NFTText.sourceTime(e.at)).font(.callout).foregroundStyle(.secondary)590            }591            if let f = e.from { NFTPlain("de   \(f)").font(.system(.caption, design: .monospaced)).textSelection(.enabled) }592            if let t = e.to { NFTPlain("vers \(t)").font(.system(.caption, design: .monospaced)).textSelection(.enabled) }593            NFTPlain("tx \(e.tx)").font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary).textSelection(.enabled)594            if let p = e.price { NFTPlain("Prix lié par une source de marché (déclaration, pas une lecture de chaîne) : \(NFTText.amount(p))").font(.caption).foregroundStyle(.secondary) }595            if let m = e.market { NFTPlain("Marché : \(NFTText.sourceName(m.provider))\(m.venue.map { " · \($0)" } ?? "")\(m.washTrade.map { " · vente fictive selon la source : \(NFTText.knownBool($0))" } ?? "")").font(.caption).foregroundStyle(.secondary) }596            NFTPlain("\(NFTText.sourceName(e.source.source)) — \(NFTText.confidence(e.source.confidence))\(e.interpretation.map { " · interprété par \($0.by)" } ?? "")\(e.marketProgram.map { " · programme \($0.name)" } ?? "")").font(.caption2).foregroundStyle(.secondary)597        }598    }599}600601// MARK: - Transfer verdict602603private struct NFTTransferCard: View {604    let model: AppModel605    let gallery: NFTGallery606    let item: NFTItemModel607    let asset: NFTAsset608    let send: () -> Void609610    private var chainCap: NFTChainCapability? { gallery.capabilities?.chain(asset.chainId) }611    private var blockedBy: [String] { item.verdict?.blockedBy ?? asset.transfer?.blockedBy ?? asset.capabilities.transferBlockedBy }612    private var warnings: [String] { item.verdict?.warnings ?? asset.transfer?.warnings ?? asset.capabilities.transferWarnings ?? [] }613    private var transferable: Bool { item.verdict?.transferable ?? asset.transfer?.transferable ?? false }614615    /// Why the button is disabled, in order. Empty = the transfer can be prepared (the server and the signer still decide).616    private var obstacles: [String] {617        var out: [String] = []618        if item.fromCache || !model.canOperate { out.append("Hors connexion ou session indisponible : aucun transfert ne peut être préparé.") }619        if asset.standard.transferStandard == nil { out.append("Aucun transfert n’est construit pour le standard \(NFTText.standard(asset.standard)).") }620        if let c = chainCap, !c.canPrepareTransfer(of: asset.standard) { out.append("Le serveur ne prépare pas de transfert de ce standard sur \(c.name)\(c.transferReason.map { " (\(NFTText.blockReason($0)))" } ?? "").") }621        out += blockedBy.map(NFTText.blockReason)622        if let s = item.verdict?.signer {623            if !s.reachable { out.append("Le signataire isolé est injoignable.") }624            if s.halted == true { out.append("L’arrêt d’urgence du signataire est actif.") }625            if s.supportsNft == false { out.append("La version du signataire ne prend pas en charge les transferts de NFT.") }626            if let n = s.signedToday, let m = s.maxPerDay, n >= m { out.append("Plafond quotidien du signataire atteint : \(n) transfert(s) de NFT signé(s) aujourd’hui sur \(m).") }627        } else if item.verdict == nil, !item.fromCache { out.append(item.verdictError ?? "Le verdict de transfert du serveur n’a pas encore été lu.") }628        return out629    }630631    private func policy(_ s: NFTTransferVerdictAnswer.Signer) -> String {632        let parts: [String?] = [633            s.signedToday.flatMap { n in s.maxPerDay.map { "\(n) / \($0) transfert(s) signé(s) aujourd’hui" } },634            s.allowlistOnly.map { $0 ? "destinations limitées à la liste autorisée" : "toute destination valide (liste non imposée)" },635            asset.standard == .erc1155 ? s.maxErc1155Quantity.map { "au plus \($0) unité(s) ERC-1155 par transfert" } : nil,636        ]637        let known = parts.compactMap { $0 }638        return known.isEmpty ? "non lue" : known.joined(separator: " · ")639    }640641    var body: some View {642        Card("Transfert", trailing: AnyView(NFTFlag(text: transferable && obstacles.isEmpty ? "Préparable" : "Non disponible", color: transferable && obstacles.isEmpty ? Theme.positive : .secondary))) {643            if let v = item.verdict {644                if let r = v.route { Field(label: "Appel utilisé", value: r, mono: true) }645                Field(label: "Politique NFT du signataire", value: policy(v.signer))646                if v.broadcast == false { Banner(.warning, "SERVEUR DE TEST — il signe mais ne diffuse pas : un transfert approuvé se terminera « signé, NON diffusé ». Rien ne quittera le portefeuille.") }647            }648            ForEach(warnings, id: \.self) { w in Banner(.warning, NFTText.warning(w)) }649            ForEach(obstacles, id: \.self) { o in650                HStack(alignment: .firstTextBaseline, spacing: 6) { Image(systemName: "nosign").foregroundStyle(.secondary); NFTPlain(o).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }651            }652            HStack {653                Text("Ce verdict est un affichage, pas une autorisation : à la préparation, le serveur relit la chaîne sur chaque point d’accès et simule le transfert ; le signataire applique ensuite sa propre politique.").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)654                Spacer()655                Button { send() } label: { Label("Envoyer cet NFT…", systemImage: "paperplane") }.buttonStyle(.borderedProminent).controlSize(.large)656                    .disabled(!transferable || !obstacles.isEmpty)657            }658        }659    }660}661
Files main
Menu

Theme