Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Features/NFTs/NFTItemView.swift10// Description : The page of one NFT: its media (through the proxy only),11// what the creator declares — shown as plain, untrusted text12// — and, kept apart, what the chain says: network, standard,13// contract or mint and token id in full, holder, quantity.14// Then the transfer verdict exactly as the server gives it,15// market READ data per source, on-chain events and the16// provenance of every value. No URL of the metadata is ever17// loaded; a link opens in the system browser only after an18// explicit, warned confirmation.19// Module : Features20// Repository : https://git.spboucher.ai/sp-wallet-ios21// Created : 2026-11-1822// Last Modified : 2026-11-1823//24// =============================================================================25// AUTHOR & PROFESSIONAL AFFILIATION26// =============================================================================27//28// Author : Simon-Pierre Boucher29// Position : Professor of Finance30// Institution : Université du Québec en Outaouais (UQO)31// Department : Département des sciences administratives32// Organization : SP Boucher33//34// Website : https://spboucher.ai35// Git : https://git.spboucher.ai36//37// =============================================================================38// OFFICIAL CONTACT DIRECTORY39// =============================================================================40//41// General : info@spboucher.ai42// Professional : contact@spboucher.ai43// Direct : simon@spboucher.ai44// Research : research@spboucher.ai45// Development : dev@spboucher.ai46// Support : support@spboucher.ai47// Security/Admin : admin@spboucher.ai48// Notifications : notifications@spboucher.ai49//50// Preferred Contact: support@spboucher.ai51//52// =============================================================================53// COPYRIGHT & INTELLECTUAL PROPERTY54// =============================================================================55//56// Copyright (c) 202657// Simon-Pierre Boucher58//59// All rights reserved where applicable.60//61// This file is governed by the applicable project license,62// copyright notices, institutional agreements and relevant law.63//64// Unless expressly authorized by the applicable license or65// rights holder, copying, redistribution, sublicensing,66// publication and commercial exploitation are not permitted.67//68// Existing third-party rights and notices remain unaffected.69//70// =============================================================================71// CONFIDENTIALITY & SECURITY72// =============================================================================73//74// Classification : Public75// Distribution : Public repository; use is governed by the project license76// Security Contact : admin@spboucher.ai77//78// Access to this source does not independently grant permission79// to redistribute or disclose confidential materials.80//81// Do not embed credentials, private keys, access tokens,82// certificates or confidential personal information.83//84// =============================================================================85// LICENSE & MAINTENANCE86// =============================================================================87//88// License : None specified (no license file in this repository)89// Maintainer : Simon-Pierre Boucher90// Technical Contact: dev@spboucher.ai91//92// =============================================================================93// END OF SP BOUCHER SOURCE HEADER94// =============================================================================9596import SwiftUI97import SPWalletCore9899/** A card of labelled values; `mono` rows (identifiers) are shown in full and can be copied. */100struct NFTFactCard: View {101 let rows: [(String, String, Bool)]102 var body: some View {103 VStack(alignment: .leading, spacing: 0) {104 ForEach(Array(rows.enumerated()), id: \.offset) { i, r in105 if i > 0 { Divider() }106 FieldRow(label: r.0, value: r.1, mono: r.2, copyable: r.2)107 }108 }.spCard(padding: 16)109 }110}111112/** A label followed by a server-given identifier in monospace (a setting name, a method), on one wrapping line. */113struct NFTInlineMono: View {114 let prefix: String115 let mono: String116 var body: some View {117 VStack(alignment: .leading, spacing: 1) {118 Text(prefix).font(.spFootnote).foregroundStyle(Theme.mute)119 Text(verbatim: mono).font(.system(size: 12, design: .monospaced)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)120 }121 }122}123124/** A link that is never followed by the app: shown as text with its host, opened in the system browser after a confirmation. */125struct NFTExternalLinkRow: View {126 let title: String127 let raw: String?128 let warning: String129 @Environment(\.openURL) private var openURL130 @State private var confirm = false131132 var body: some View {133 if let raw, !raw.isEmpty {134 VStack(alignment: .leading, spacing: 4) {135 Text(title).font(.spFootnote).foregroundStyle(Theme.mute)136 if let url = NFTLinks.safe(raw), let host = url.host {137 Text(verbatim: host).font(.spBody.weight(.semibold)).foregroundStyle(Theme.ink)138 Text(verbatim: raw).font(.system(size: 12, design: .monospaced)).foregroundStyle(Theme.mute).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)139 Button { confirm = true } label: { Label(String(localized: "Ouvrir dans le navigateur…"), systemImage: "arrow.up.right.square") }140 .font(.spCallout.weight(.semibold)).frame(minHeight: 44).accessibilityIdentifier("nft.link.open")141 .confirmationDialog(String(localized: "Ouvrir \(host) hors de SP Wallet ?"), isPresented: $confirm, titleVisibility: .visible) {142 Button(String(localized: "Ouvrir \(host)")) { openURL(url) }143 Button(String(localized: "Annuler"), role: .cancel) {}144 } message: { Text(warning) }145 } else {146 Text(verbatim: raw).font(.system(size: 12, design: .monospaced)).foregroundStyle(Theme.mute).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)147 Label(String(localized: "Ce n’est pas un lien web ordinaire : il n’est pas ouvrable."), systemImage: "hand.raised").font(.spFootnote).foregroundStyle(Theme.warn)148 .accessibilityIdentifier("nft.link.refused")149 }150 }151 .padding(.vertical, 6).frame(maxWidth: .infinity, alignment: .leading)152 }153 }154}155156struct NFTItemView: View {157 let ctx: NFTContext158 @Environment(AppModel.self) private var model159 let key: String160 /** The answer of an explicit lookup, shown as is when the inventory does not hold the asset. */161 var preloaded: NFTAsset?162 /** Shown beside the gallery (iPad): the navigation title stays the section's. */163 var embedded = false164165 @State private var asset: NFTAsset?166 @State private var savedAt: Date?167 @State private var live = false168 @State private var error: Error?169 @State private var verdict: NFTTransferVerdictAnswer?170 @State private var activity: NFTActivity?171 @State private var activityError: Error?172 @State private var market: NFTMarketAnswer?173 @State private var marketError: Error?174 @State private var busy = false175 @State private var actionError: Error?176 @State private var sending = false177 @State private var confirmUntrack = false178 @State private var loadingOlder = false179180 var body: some View {181 ScrollView {182 VStack(alignment: .leading, spacing: Theme.Space.section) {183 NFTFixtureBanner(ctx: ctx)184 FreshnessBanner()185 if let a = asset { page(a) }186 else if let error { NFTErrorNotice(error: error) { Task { await load() } }.accessibilityIdentifier("nft.item.error") }187 else if !model.canOperate { EmptyState(icon: "wifi.slash", title: String(localized: "Fiche non disponible hors ligne"), message: String(localized: "Cette pièce n’a pas été consultée avant la perte de connexion.")) }188 else { ProgressView().frame(maxWidth: .infinity).padding(.vertical, 60) }189 }190 .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12).frame(maxWidth: 760).frame(maxWidth: .infinity)191 }192 .spPage()193 .modifier(NFTItemTitle(title: embedded ? nil : (asset?.displayName ?? String(localized: "NFT"))))194 .task(id: "\(key)|\(model.canOperate)|\(ctx.revision)") { await load() }195 .sheet(isPresented: $sending, onDismiss: { ctx.revision += 1 }) { if let a = asset { NFTTransferFlow(ctx: ctx, item: a).wallet(model) } }196 }197198 // MARK: loading199200 private var cacheKey: String { "nft.item.\(key)" }201202 private func load() async {203 if asset == nil {204 if let c = await ctx.cache.load(NFTAsset.self, key: cacheKey) { asset = c.value; savedAt = c.savedAt; live = false }205 else if let preloaded { asset = preloaded; savedAt = Date(); live = false }206 }207 guard model.canOperate else { live = false; return }208 do {209 let a = try await ctx.api.item(key: key)210 asset = a; live = true; savedAt = Date(); error = nil211 await ctx.cache.save(a, key: cacheKey)212 } catch let e as APIError where e.code == "nft_not_found" && preloaded != nil {213 // an asset opened by lookup is not part of the inventory: the lookup answer stays what is shown214 asset = preloaded; live = true; error = nil215 } catch is CancellationError { return216 } catch { if asset == nil { self.error = error } else { live = false } }217 guard let a = asset else { return }218 async let v = Result.catching { try await ctx.api.transferVerdict(key: a.key) }219 async let act = Result.catching { try await ctx.api.activity(key: a.key) }220 async let m = Result.catching { try await ctx.api.market(key: a.key) }221 let (rv, ra, rm) = await (v, act, m)222 if case .success(let x) = rv { verdict = x } else { verdict = nil }223 switch ra { case .success(let x): activity = x; activityError = nil; case .failure(let e): activityError = e }224 switch rm { case .success(let x): market = x; marketError = nil; case .failure(let e): marketError = e }225 }226227 // MARK: page228229 @ViewBuilder private func page(_ a: NFTAsset) -> some View {230 if !live, let at = savedAt {231 Notice(tone: .info, title: String(localized: "Fiche du \(at.formatted(date: .abbreviated, time: .shortened))"), message: String(localized: "Dernière lecture enregistrée, non actualisée."), icon: "clock")232 }233 media(a)234 title(a)235 verdictCard(a)236 identity(a)237 description(a)238 traits(a)239 NFTMarketSection(ctx: ctx, asset: a, answer: market, error: marketError)240 activitySection(a)241 chainDetails(a)242 sources(a)243 actions(a)244 }245246 @ViewBuilder private func media(_ a: NFTAsset) -> some View {247 let image = a.media.first { $0.role == "image" } ?? a.media.first { NFTMediaGate.kind(of: $0) == .image }248 let video = a.media.first { NFTMediaGate.kind(of: $0) == .video }249 Group {250 if let video { NFTVideoView(ctx: ctx, media: video, poster: image) }251 else if let image { NFTMediaImage(ctx: ctx, id: image.id, mime: image.mime, kind: image.kind, status: image.status, errorCode: image.errorCode, size: .full, fill: false, compact: false) }252 else { NFTMediaTile(icon: "photo", text: String(localized: "Aucun média")) }253 }254 .frame(maxWidth: .infinity).frame(minHeight: 220, maxHeight: 460).aspectRatio(1, contentMode: .fit)255 .background(Theme.elev).clipShape(RoundedRectangle(cornerRadius: Theme.Radius.card, style: .continuous))256 .accessibilityIdentifier("nft.item.media")257 // every other file the metadata names: said, never loaded on its own258 ForEach(a.media.filter { $0.id != image?.id && $0.id != video?.id }) { m in259 let k = NFTMediaGate.kind(of: m)260 let t = NFTMediaText.tile(status: m.status == "not_fetched" && k != .image ? "available" : m.status, errorCode: m.errorCode).flatMap { k == .image ? $0 : nil } ?? NFTMediaText.tile(for: k) ?? ("photo", String(localized: "Image supplémentaire"))261 Label { Text(roleName(m.role) + " : " + t.text).font(.spFootnote).foregroundStyle(Theme.mute) } icon: { Image(systemName: t.icon).foregroundStyle(Theme.mute) }262 .accessibilityIdentifier("nft.item.othermedia")263 }264 if let s = NFTText.metadataStatus(a.metadata.status) {265 Notice(tone: .warn, title: s, message: a.metadata.errorCode.map { NFTText.mediaBlock($0) })266 }267 }268269 private func roleName(_ r: String) -> String {270 switch r { case "animation": String(localized: "Animation"); case "file": String(localized: "Fichier"); case "image": String(localized: "Image"); default: r }271 }272273 @ViewBuilder private func title(_ a: NFTAsset) -> some View {274 let own = NFTText.ownership(a.ownership.state), coll = NFTText.collectionVerification(a.collection?.verifiedOnChain)275 VStack(alignment: .leading, spacing: 8) {276 Text(verbatim: a.displayName ?? String(localized: "Nom non disponible")).font(.spTitle).foregroundStyle(a.displayName == nil ? Theme.mute : Theme.ink)277 .fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("nft.item.name")278 Text(a.metadata.name != nil ? String(localized: "Nom déclaré par le créateur — non vérifié") : a.metadata.onchainName != nil ? String(localized: "Nom inscrit sur la chaîne") : String(localized: "Ni le créateur ni la chaîne ne donnent de nom"))279 .font(.spFootnote).foregroundStyle(Theme.mute)280 VStack(alignment: .leading, spacing: 3) {281 if let c = a.collection {282 Text(verbatim: c.name ?? Money.shortAddress(c.id)).font(.spBody.weight(.semibold)).foregroundStyle(Theme.ink)283 if c.name != nil { Text(String(localized: "Nom de collection déclaré par ses propres métadonnées — non vérifié")).font(.spFootnote).foregroundStyle(Theme.mute) }284 }285 Label(coll.0, systemImage: coll.2).font(.spFootnote.weight(.semibold)).foregroundStyle(coll.1.color).fixedSize(horizontal: false, vertical: true)286 .accessibilityIdentifier("nft.item.collection")287 }288 NFTFlowPills {289 Pill(text: NFTText.standard(a.standard), tone: .info)290 Pill(text: model.network(a.chainId)?.name ?? a.chainId)291 Pill(text: own.0, tone: own.1)292 if a.standard == .erc1155 || a.quantity != "1" { Pill(text: String(localized: "Quantité : \(a.quantity)")) }293 if a.origin == "manual" { Pill(text: String(localized: "Suivi manuel")) }294 if a.origin == "lookup" { Pill(text: String(localized: "Ouvert par identifiant")) }295 }296 if let by = a.spamFlaggedBy {297 Notice(tone: .warn, title: String(localized: "Signalé comme indésirable par \(NFTText.sourceName(by))"),298 message: (a.indexerFlags?.classifications.isEmpty == false ? (a.indexerFlags?.classifications ?? []).joined(separator: ", ") + ". " : "") + String(localized: "C’est l’affirmation de cet indexeur. Ne suis aucun lien de cette pièce."))299 }300 if a.ownership.state == "not_in_wallet" {301 Notice(tone: .info, title: a.origin == "lookup" ? String(localized: "Ce NFT n’est pas dans ce portefeuille. Il est affiché parce que tu l’as ouvert par son identifiant.") : String(localized: "Ce NFT n’est pas (ou plus) détenu par ce portefeuille."))302 }303 if a.ownership.state == "burned" { Notice(tone: .danger, title: String(localized: "Ce NFT est brûlé : il n’existe plus sur la chaîne.")) }304 }305 }306307 // MARK: transfer verdict308309 @ViewBuilder private func verdictCard(_ a: NFTAsset) -> some View {310 let transferable = verdict?.transferable ?? a.transfer?.transferable ?? a.capabilities.transferable311 let blocked = verdict?.blockedBy ?? a.transfer?.blockedBy ?? a.capabilities.transferBlockedBy312 let warnings = verdict?.warnings ?? a.transfer?.warnings ?? a.capabilities.transferWarnings ?? []313 let route = verdict?.route ?? a.transfer?.route314 VStack(alignment: .leading, spacing: 10) {315 SectionHeader(title: String(localized: "Envoi"))316 if transferable, a.standard.transferStandard != nil {317 Label(String(localized: "Transférable selon le serveur"), systemImage: "checkmark.circle.fill").font(.spBody.weight(.semibold)).foregroundStyle(Theme.emerald)318 .accessibilityIdentifier("nft.item.transferable")319 if let route { NFTInlineMono(prefix: String(localized: "Transfert par : "), mono: route) }320 ForEach(warnings, id: \.self) { w in let t = NFTText.transferWarning(w); Notice(tone: t.tone, title: t.title) }321 if let s = verdict?.signer {322 if s.supportsNft == false { Notice(tone: .warn, title: String(localized: "Le signataire ne prend pas encore en charge les envois de NFT.")) }323 if s.halted == true { Notice(tone: .danger, title: String(localized: "Arrêt d’urgence actif : aucun envoi.")) }324 if !s.reachable { Notice(tone: .warn, title: String(localized: "Signataire injoignable")) }325 if s.allowlistOnly == true { Notice(tone: .info, title: String(localized: "Mode liste blanche"), message: String(localized: "Le signataire ne signe un envoi de NFT que vers une destination approuvée (Protections).")) }326 if let n = s.signedToday, let max = s.maxPerDay { Text(String(localized: "Envois de NFT signés aujourd’hui : \(n) sur \(max).")).font(.spFootnote).foregroundStyle(Theme.mute) }327 }328 if verdict?.broadcast == false { Notice(tone: .warn, title: String(localized: "Ce serveur signe mais ne diffuse pas"), message: String(localized: "Un envoi approuvé y finit « signé, non diffusé » : le NFT ne bouge pas.")) }329 Button { sending = true } label: { Label(String(localized: "Envoyer ce NFT"), systemImage: "arrow.up.right") }330 .buttonStyle(.spPrimary).disabled(!model.canOperate || !live || verdict?.signer.supportsNft == false || verdict?.signer.halted == true)331 .accessibilityIdentifier("nft.item.send")332 Text(String(localized: "Ce verdict est un affichage. La détention, le standard et le destinataire sont relus sur la chaîne, et l’envoi simulé, avant toute demande de clé d’accès."))333 .font(.spFootnote).foregroundStyle(Theme.mute)334 } else {335 Label(String(localized: "Non transférable ici"), systemImage: "xmark.octagon.fill").font(.spBody.weight(.semibold)).foregroundStyle(Theme.danger)336 .accessibilityIdentifier("nft.item.blocked")337 let reasons = blocked.isEmpty ? (a.standard.transferStandard == nil ? ["unsupported_standard"] : []) : blocked338 if reasons.isEmpty { Text(String(localized: "Le serveur ne donne pas de motif.")).font(.spFootnote).foregroundStyle(Theme.mute) }339 ForEach(reasons, id: \.self) { r in340 Label(NFTText.transferBlock(r), systemImage: "minus.circle").font(.spCallout).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)341 .accessibilityIdentifier("nft.item.blockReason")342 }343 }344 }.spCard(padding: 16)345 }346347 // MARK: identity (chain facts)348349 @ViewBuilder private func identity(_ a: NFTAsset) -> some View {350 SectionHeader(title: String(localized: "Identifiants on-chain"))351 NFTFactCard(rows: identityRows(a)).accessibilityIdentifier("nft.item.identity")352 }353354 private func identityRows(_ a: NFTAsset) -> [(String, String, Bool)] {355 let evm = a.family == "evm"356 var rows: [(String, String, Bool)] = [357 (String(localized: "Réseau"), model.network(a.chainId)?.name ?? a.chainId, false),358 (String(localized: "Standard"), NFTText.standard(a.standard), false),359 (evm ? String(localized: "Contrat") : String(localized: "Adresse (mint / actif)"), a.assetAddress, true),360 ]361 if let t = a.tokenId { rows.append((String(localized: "Identifiant du jeton"), t, true)) }362 rows.append((String(localized: "Détenteur selon la chaîne"), NFTText.known(a.ownership.owner) { $0 }, a.ownership.owner.isKnown))363 rows.append((String(localized: "Quantité détenue"), a.quantity, false))364 rows.append((String(localized: "Unités existantes"), NFTText.known(a.supply) { $0 }, false))365 if !evm {366 rows.append((String(localized: "Compte de jeton"), NFTText.known(a.ownership.tokenAccount) { $0 }, a.ownership.tokenAccount.isKnown))367 rows.append((String(localized: "Gelé"), NFTText.known(a.ownership.frozen, NFTText.yesNo), false))368 rows.append((String(localized: "État pNFT"), NFTText.known(a.ownership.tokenRecordState) { $0 }, false))369 }370 rows.append((String(localized: "Délégué"), NFTText.known(a.ownership.delegate) { $0 }, a.ownership.delegate.isKnown))371 if let v = a.verifiedAt { rows.append((String(localized: "Dernière vérification de la détention"), v.formatted(date: .abbreviated, time: .standard), false)) }372 if let g = a.goneAt { rows.append((String(localized: "Sorti du portefeuille le"), g.formatted(date: .abbreviated, time: .standard), false)) }373 return rows374 }375376 // MARK: creator content (untrusted)377378 @ViewBuilder private func description(_ a: NFTAsset) -> some View {379 if a.metadata.description?.isEmpty == false || a.metadata.externalUrl?.isEmpty == false {380 SectionHeader(title: String(localized: "Description"))381 VStack(alignment: .leading, spacing: 8) {382 Text(String(localized: "Texte du créateur, non vérifié — affiché tel quel, sans lien ni mise en forme.")).font(.spFootnote).foregroundStyle(Theme.mute)383 if let d = a.metadata.description, !d.isEmpty {384 Text(verbatim: d).font(.spBody).foregroundStyle(Theme.ink).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)385 .accessibilityIdentifier("nft.item.description")386 }387 NFTExternalLinkRow(title: String(localized: "Lien externe déclaré par le créateur, non vérifié"), raw: a.metadata.externalUrl,388 warning: String(localized: "Ce lien vient de la métadonnée du NFT. Il peut mener à un site frauduleux. Ne saisis jamais ta phrase de récupération et ne connecte aucun portefeuille."))389 }.spCard(padding: 16)390 }391 }392393 @ViewBuilder private func traits(_ a: NFTAsset) -> some View {394 SectionHeader(title: String(localized: "Attributs"))395 VStack(alignment: .leading, spacing: 10) {396 if a.metadata.status != "ok" { Text(String(localized: "Attributs non disponibles : la métadonnée n’a pas été chargée.")).font(.spCallout).foregroundStyle(Theme.mute) }397 else if a.metadata.attributes.isEmpty { Text(String(localized: "La métadonnée ne déclare aucun attribut.")).font(.spCallout).foregroundStyle(Theme.mute) }398 else {399 LazyVGrid(columns: [GridItem(.adaptive(minimum: 140), spacing: 8)], alignment: .leading, spacing: 8) {400 ForEach(Array(a.metadata.attributes.enumerated()), id: \.offset) { _, t in401 VStack(alignment: .leading, spacing: 2) {402 Text(verbatim: t.traitType ?? String(localized: "(sans nom)")).font(.system(size: 11.5, weight: .semibold)).foregroundStyle(Theme.mute).lineLimit(2)403 Text(verbatim: t.valueText.isEmpty ? String(localized: "(sans valeur)") : t.valueText + (t.maxValue.map { " / \($0)" } ?? "")).font(.spCallout.weight(.medium)).foregroundStyle(Theme.ink).lineLimit(4)404 if t.malformed { Text(String(localized: "entrée mal formée, conservée telle quelle")).font(.system(size: 11)).foregroundStyle(Theme.warn) }405 }406 .padding(10).frame(maxWidth: .infinity, alignment: .leading).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small))407 }408 }409 Text(String(localized: "Attributs déclarés par le créateur, non vérifiés.")).font(.spFootnote).foregroundStyle(Theme.mute)410 }411 if let s = a.metadata.traitStatistics, !s.computed {412 Text(String(localized: "Fréquence et rareté : non calculées (\(rarityReason(s.reason))).")).font(.spFootnote).foregroundStyle(Theme.mute)413 }414 }.spCard(padding: 16)415 }416417 private func rarityReason(_ r: String) -> String {418 switch r {419 case "no_collection_index": String(localized: "aucun index complet de la collection, dénominateur inconnu")420 case "collection_unverified": String(localized: "la collection n’est pas vérifiée")421 case "compressed": String(localized: "NFT compressé, attributs non vérifiables ici")422 case "mutable_metadata": String(localized: "métadonnée modifiable")423 case "not_built": String(localized: "non pris en charge dans cette version")424 default: r425 }426 }427428 // MARK: on-chain events429430 @ViewBuilder private func activitySection(_ a: NFTAsset) -> some View {431 SectionHeader(title: String(localized: "Activité on-chain"))432 VStack(alignment: .leading, spacing: 10) {433 if let act = activity {434 Text(NFTText.completeness(act.completeness) + (act.note.map { " " + activityNote($0) } ?? "")).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)435 if let e = act.error { Label(String(localized: "Dernière lecture en erreur (\(e)) : événements enregistrés affichés."), systemImage: "exclamationmark.triangle.fill").font(.spFootnote).foregroundStyle(Theme.warn) }436 if act.events.isEmpty { Text(String(localized: "Aucun événement établi par les sources.")).font(.spCallout).foregroundStyle(Theme.mute).accessibilityIdentifier("nft.item.noevents") }437 ForEach(act.events) { e in Divider(); NFTEventRow(event: e) }438 if act.canLoadOlder {439 Button { Task { await loadOlder(a) } } label: { HStack { if loadingOlder { ProgressView() }; Text(String(localized: "Événements plus anciens")) } }440 .buttonStyle(.spSecondary).disabled(loadingOlder || !model.canOperate)441 }442 Text(String(localized: "Un transfert n’est jamais interprété comme une vente ; aucun prix n’en est déduit.")).font(.spFootnote).foregroundStyle(Theme.mute)443 } else if let e = activityError, model.canOperate { Notice(tone: .warn, title: String(localized: "Activité indisponible"), message: NFTText.errorMessage(e).detail) }444 else if !model.canOperate { Text(String(localized: "Activité non disponible hors ligne.")).font(.spCallout).foregroundStyle(Theme.mute) }445 else { ProgressView() }446 }.spCard(padding: 16)447 }448449 private func activityNote(_ n: String) -> String {450 switch n {451 case "history_from_mint_and_current_token_account": String(localized: "Seules les transactions du mint et du compte de jeton actuel sont lues ; des transferts anciens peuvent manquer.")452 case "last_N_blocks": String(localized: "Les points d’accès publics ne donnent que les tout derniers blocs.")453 case "last_N_blocks_and_provider_history": String(localized: "Derniers blocs lus sur les points d’accès publics, plus les transactions nommées par l’indexeur configuré et relues sur la chaîne.")454 case "compressed_history_requires_indexer": String(localized: "L’historique d’un NFT compressé exige un indexeur.")455 case "logs_refused_by_endpoints": String(localized: "Les points d’accès refusent la lecture des journaux.")456 default: "(\(n))"457 }458 }459460 private func loadOlder(_ a: NFTAsset) async {461 loadingOlder = true462 defer { loadingOlder = false }463 do { activity = try await ctx.api.activity(key: a.key, loadOlder: true); activityError = nil } catch { activityError = error }464 }465466 // MARK: chain details, provenance467468 private func chainRows(_ a: NFTAsset) -> [(String, String, Bool)] {469 var rows: [(String, String, Bool)] = [(String(localized: "Clé canonique"), a.key, true)]470 if let p = a.tokenProgram { rows.append((String(localized: "Programme"), p, true)) }471 rows.append((String(localized: "Autorité de mise à jour"), NFTText.known(a.updateAuthority) { $0 }, a.updateAuthority.isKnown))472 rows.append((String(localized: "Métadonnée"), NFTText.known(a.metadata.mutable) { $0 ? String(localized: "modifiable") : String(localized: "immuable") }, false))473 rows.append((String(localized: "Créateurs"), NFTText.known(a.creators) { list in474 list.isEmpty ? String(localized: "aucun") : list.map { "\($0.address) — \($0.verified ? String(localized: "vérifié") : String(localized: "non vérifié")), \($0.share) %" }.joined(separator: "\n")475 }, a.creators.isKnown))476 rows.append((String(localized: "Redevance déclarée"), NFTText.known(a.royaltyBps) { "\(Double($0) / 100) %" }, false))477 rows.append((String(localized: "Jeu de règles"), NFTText.known(a.ruleSet) { $0 }, a.ruleSet.isKnown))478 if !a.extensions.isEmpty { rows.append((String(localized: "Extensions / plugins"), a.extensions.joined(separator: "\n"), true)) }479 if let u = a.metadata.sourceUri { rows.append((String(localized: "Adresse de la métadonnée (texte du créateur, jamais chargée par l’app)"), u, true)) }480 if let u = a.metadata.resolvedUri, u != a.metadata.sourceUri { rows.append((String(localized: "Adresse réellement lue par le serveur"), u, true)) }481 if let h = a.metadata.contentHash { rows.append((String(localized: "Empreinte SHA-256 de la métadonnée"), h, true)) }482 for m in a.media { rows.append((String(localized: "Média déclaré (\(roleName(m.role).lowercased())) — adresse non chargée par l’app"), m.sourceUri.count > 300 ? String(m.sourceUri.prefix(300)) + "…" : m.sourceUri, true)) }483 return rows484 }485486 @ViewBuilder private func chainDetails(_ a: NFTAsset) -> some View {487 SectionHeader(title: String(localized: "Détails blockchain"))488 NFTFactCard(rows: chainRows(a))489 if a.explorerUrl != nil {490 VStack(alignment: .leading, spacing: 0) {491 NFTExternalLinkRow(title: String(localized: "Explorateur de blocs (lien construit par le serveur)"), raw: a.explorerUrl,492 warning: String(localized: "L’explorateur s’ouvre dans le navigateur, hors de SP Wallet."))493 }.spCard(padding: 16)494 }495 }496497 @ViewBuilder private func sources(_ a: NFTAsset) -> some View {498 if !a.sources.isEmpty {499 SectionHeader(title: String(localized: "Sources et fraîcheur"))500 VStack(alignment: .leading, spacing: 10) {501 ForEach(Array(a.sources.enumerated()), id: \.offset) { i, s in502 if i > 0 { Divider() }503 let p = NFTText.provenance(s)504 VStack(alignment: .leading, spacing: 3) {505 HStack { Pill(text: p.0, tone: p.1); if s.isStale { Pill(text: String(localized: "possiblement périmé"), tone: .warn, icon: "clock") }; Spacer() }506 Text("\(NFTText.sourceName(s.source)) · \(s.detail) · \(NFTText.confidence(s.confidence))").font(.spFootnote).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)507 Text(String(localized: "Lu le \(s.fetchedAt.formatted(date: .abbreviated, time: .standard)) — couvre : \(s.covers.joined(separator: ", "))")).font(.spFootnote).foregroundStyle(Theme.mute)508 }509 }510 Text(String(localized: "Chaque valeur de cette page appartient à une seule de ces sources ; aucune n’est présentée comme vérité de la chaîne si elle n’en vient pas.")).font(.spFootnote).foregroundStyle(Theme.mute)511 }.spCard(padding: 16)512 }513 }514515 // MARK: actions on the inventory (no signature)516517 @ViewBuilder private func actions(_ a: NFTAsset) -> some View {518 VStack(alignment: .leading, spacing: 10) {519 if let e = actionError { NFTErrorNotice(error: e) }520 Button { Task { await act { try await ctx.api.refreshMetadata(key: a.key) } } } label: { HStack { if busy { ProgressView() } else { Image(systemName: "arrow.clockwise") }; Text(String(localized: "Actualiser la métadonnée")) } }521 .buttonStyle(.spSecondary).disabled(busy || !model.canOperate).accessibilityIdentifier("nft.item.refresh")522 Text(String(localized: "L’actualisation relit la métadonnée du créateur (une fois par minute au plus). Elle ne change rien à ce que dit la chaîne.")).font(.spFootnote).foregroundStyle(Theme.mute)523 if a.origin == "lookup" {524 Button { Task { await act { try await ctx.api.track(NFTReference(chain: a.chainId, address: a.assetAddress, tokenId: a.family == "evm" ? a.tokenId : nil)) } } } label: { Label(String(localized: "Suivre ce NFT"), systemImage: "plus.circle") }525 .buttonStyle(.spSecondary).disabled(busy || !model.canOperate).accessibilityIdentifier("nft.item.track")526 }527 if a.origin == "manual" {528 Button(role: .destructive) { confirmUntrack = true } label: { Label(String(localized: "Ne plus suivre"), systemImage: "minus.circle") }529 .buttonStyle(.spSecondary).disabled(busy || !model.canOperate).accessibilityIdentifier("nft.item.untrack")530 .confirmationDialog(String(localized: "Ne plus suivre ce NFT ?"), isPresented: $confirmUntrack, titleVisibility: .visible) {531 Button(String(localized: "Ne plus suivre"), role: .destructive) { Task { await untrack(a) } }532 Button(String(localized: "Annuler"), role: .cancel) {}533 } message: { Text(String(localized: "Il sort de la galerie. Rien ne change sur la chaîne : le NFT reste où il est.")) }534 }535 }536 }537538 private func act(_ call: @escaping @Sendable () async throws -> NFTAsset) async {539 busy = true; actionError = nil540 defer { busy = false }541 do { asset = try await call(); live = true; savedAt = Date(); ctx.revision += 1 } catch { actionError = error }542 }543 private func untrack(_ a: NFTAsset) async {544 busy = true; actionError = nil545 defer { busy = false }546 do { _ = try await ctx.api.untrack(key: a.key); ctx.revision += 1 } catch { actionError = error }547 }548}549550private struct NFTItemTitle: ViewModifier {551 let title: String?552 func body(content: Content) -> some View {553 if let title { content.navigationTitle(title).navigationBarTitleDisplayMode(.inline) } else { content }554 }555}556557/** Pills that wrap on several lines. */558struct NFTFlowPills: Layout {559 var spacing: CGFloat = 6560 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {561 let w = proposal.width ?? .infinity562 var x: CGFloat = 0, y: CGFloat = 0, row: CGFloat = 0, maxX: CGFloat = 0563 for s in subviews {564 let d = s.sizeThatFits(.unspecified)565 if x > 0, x + d.width > w { x = 0; y += row + spacing; row = 0 }566 x += d.width + spacing; row = max(row, d.height); maxX = max(maxX, x - spacing)567 }568 return CGSize(width: maxX, height: y + row)569 }570 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {571 var x = bounds.minX, y = bounds.minY, row: CGFloat = 0572 for s in subviews {573 let d = s.sizeThatFits(.unspecified)574 if x > bounds.minX, x + d.width > bounds.maxX { x = bounds.minX; y += row + spacing; row = 0 }575 s.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(d))576 x += d.width + spacing; row = max(row, d.height)577 }578 }579}580581/** One on-chain event: what happened, between whom, how final, according to which source. */582struct NFTEventRow: View {583 let event: NFTEvent584 var body: some View {585 let t = NFTText.event(event.type), f = NFTText.finality(event.finality)586 VStack(alignment: .leading, spacing: 4) {587 HStack(alignment: .firstTextBaseline) {588 Label(t.0, systemImage: t.1).font(.spCallout.weight(.semibold)).foregroundStyle(Theme.ink)589 Spacer()590 Text(event.date.map { $0.formatted(date: .abbreviated, time: .shortened) } ?? String(localized: "date non fournie")).font(.spFootnote).foregroundStyle(Theme.mute)591 }592 if event.from != nil || event.to != nil {593 Text(verbatim: "\(event.from.map(Money.shortAddress) ?? "—") → \(event.to.map(Money.shortAddress) ?? "—")" + (event.quantity != "1" ? " × \(event.quantity)" : ""))594 .font(.system(size: 12.5, design: .monospaced)).foregroundStyle(Theme.mute)595 }596 if let p = event.price {597 Text(String(localized: "Prix lié par \(NFTText.sourceName(event.market?.provider ?? event.source.source)) : \(NFTText.amount(p))")).font(.spFootnote).foregroundStyle(Theme.ink)598 }599 if event.type == "sale", event.source.category == "computed" {600 Text(String(localized: "Vente interprétée à partir de la transaction par SP Wallet — ce n’est pas l’affirmation d’une place de marché.")).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)601 }602 if let mp = event.marketProgram { Text(String(localized: "Programme de place de marché impliqué : \(mp.name) (aucun prix n’en est déduit)")).font(.spFootnote).foregroundStyle(Theme.mute) }603 HStack(spacing: 6) {604 Pill(text: f.0, tone: f.1)605 Pill(text: NFTText.provenance(event.source).0)606 }607 Text(verbatim: event.tx).font(.system(size: 11.5, design: .monospaced)).foregroundStyle(Theme.mute).textSelection(.enabled).lineLimit(2)608 }609 .padding(.vertical, 2)610 .contextMenu { Button { UIPasteboard.general.string = event.tx } label: { Label(String(localized: "Copier l’identifiant de transaction"), systemImage: "doc.on.doc") } }611 }612}613