SPB Git

Repository Public

NFTMarketViews.swift 33.9 KB 477 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Features/NFTs/NFTMarketViews.swift10// Description      : NFT market data, READ only. One block per source with its11//                    state and the time of its answer; asking price, best12//                    offer, last sale and collection floor are separate notions13//                    that are never merged, averaged or turned into a value of14//                    the item. Sources that disagree are named, none is chosen.15//                    Market actions (buy, sell, list, bid…) do not exist on the16//                    server: they are listed as unavailable from the server's17//                    own rows, with no button. The floor-based estimate is18//                    opt-in exactly as the server models it and stays out of19//                    every wallet total.20// Module           : Features21// Repository       : https://git.spboucher.ai/sp-wallet-ios22// Created          : 2026-11-1823// Last Modified    : 2026-11-1824//25// =============================================================================26// AUTHOR & PROFESSIONAL AFFILIATION27// =============================================================================28//29// Author           : Simon-Pierre Boucher30// Position         : Professor of Finance31// Institution      : Université du Québec en Outaouais (UQO)32// Department       : Département des sciences administratives33// Organization     : SP Boucher34//35// Website          : https://spboucher.ai36// Git              : https://git.spboucher.ai37//38// =============================================================================39// OFFICIAL CONTACT DIRECTORY40// =============================================================================41//42// General          : info@spboucher.ai43// Professional     : contact@spboucher.ai44// Direct           : simon@spboucher.ai45// Research         : research@spboucher.ai46// Development      : dev@spboucher.ai47// Support          : support@spboucher.ai48// Security/Admin   : admin@spboucher.ai49// Notifications    : notifications@spboucher.ai50//51// Preferred Contact: support@spboucher.ai52//53// =============================================================================54// COPYRIGHT & INTELLECTUAL PROPERTY55// =============================================================================56//57// Copyright (c) 202658// Simon-Pierre Boucher59//60// All rights reserved where applicable.61//62// This file is governed by the applicable project license,63// copyright notices, institutional agreements and relevant law.64//65// Unless expressly authorized by the applicable license or66// rights holder, copying, redistribution, sublicensing,67// publication and commercial exploitation are not permitted.68//69// Existing third-party rights and notices remain unaffected.70//71// =============================================================================72// CONFIDENTIALITY & SECURITY73// =============================================================================74//75// Classification   : Public76// Distribution     : Public repository; use is governed by the project license77// Security Contact : admin@spboucher.ai78//79// Access to this source does not independently grant permission80// to redistribute or disclose confidential materials.81//82// Do not embed credentials, private keys, access tokens,83// certificates or confidential personal information.84//85// =============================================================================86// LICENSE & MAINTENANCE87// =============================================================================88//89// License          : None specified (no license file in this repository)90// Maintainer       : Simon-Pierre Boucher91// Technical Contact: dev@spboucher.ai92//93// =============================================================================94// END OF SP BOUCHER SOURCE HEADER95// =============================================================================9697import SwiftUI98import SPWalletCore99100enum NFTMarketText {101    /** A `Known` market value: the value, « aucun, selon la source », or « non établi ». */102    static func known<T>(_ k: NFTKnown<T>, _ text: (T) -> String) -> String {103        switch k {104        case .known(let v): text(v)105        case .none: String(localized: "aucun, selon la source")106        case .unknown: String(localized: "non établi par la source")107        case .unsupported: String(localized: "sans objet")108        case .unrecognized(let s): s109        }110    }111    static func price(_ m: NFTMoney) -> String {112        NFTText.money(m) + (m.currency.asset == "native" ? "" : " (\(Money.shortAddress(m.currency.asset)))") + (m.precision == "source_decimal" ? " — " + String(localized: "converti du nombre décimal de la source") : "")113    }114    static func when(_ iso: String?) -> String? { iso.flatMap(ISO8601.parse).map { $0.formatted(date: .abbreviated, time: .shortened) } ?? iso }115    static func stamp(_ s: NFTMarketSourceStatus) -> String? {116        s.fetchedAt.map { String(localized: "réponse du \($0.formatted(date: .abbreviated, time: .standard))") }117    }118}119120/** The state line of one source: its name, whether it answered, when, and why not. */121struct NFTMarketSourceHeader: View {122    let status: NFTMarketSourceStatus123    var body: some View {124        let st = NFTText.marketState(status.state)125        VStack(alignment: .leading, spacing: 3) {126            HStack {127                Text(status.name).font(.spBody.weight(.semibold)).foregroundStyle(Theme.ink)128                Spacer()129                Pill(text: st.0, tone: st.1)130            }131            if let t = NFTMarketText.stamp(status) { Text(String(localized: "Source : \(status.name) — \(t)")).font(.spFootnote).foregroundStyle(Theme.mute) }132            if status.stale {133                Label(String(localized: "La source ne répond plus (\(status.code ?? "?")) : dernière réponse connue, possiblement périmée."), systemImage: "clock.badge.exclamationmark")134                    .font(.spFootnote).foregroundStyle(Theme.warn).fixedSize(horizontal: false, vertical: true)135            } else if !status.isOK, let c = status.code {136                Text(NFTText.marketWhy(c)).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)137            }138            if !status.isOK, let u = status.unlockedBy { NFTInlineMono(prefix: String(localized: "Réglage serveur : "), mono: u) }139        }140    }141}142143/** The market actions as the server lists them: all unavailable, each with its reason. Rows, not buttons. */144struct NFTMarketActionsList: View {145    let actions: [NFTMarketAction]146    var fallbackReason: String?147    var body: some View {148        VStack(alignment: .leading, spacing: 8) {149            Text(String(localized: "Actions de marché dans SP Wallet")).font(.spBody.weight(.semibold)).foregroundStyle(Theme.ink)150            if actions.isEmpty {151                Label(String(localized: "Indisponibles") + (fallbackReason.map { " — " + NFTText.marketWhy($0) } ?? ""), systemImage: "lock").font(.spFootnote).foregroundStyle(Theme.mute)152                    .fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("nft.market.actions.unavailable")153            }154            ForEach(actions) { a in155                HStack(alignment: .firstTextBaseline) {156                    Label(NFTText.marketAction(a.id), systemImage: "lock").font(.spCallout).foregroundStyle(Theme.mute)157                    Spacer()158                    // a server that one day says `available` still finds no flow in this build: said as such, never a button159                    Text(a.available ? String(localized: "non construit dans cette app") : String(localized: "indisponible")).font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.mute)160                }161                .accessibilityElement(children: .combine).accessibilityIdentifier("nft.market.action")162            }163            let reasons = Array(Set(actions.compactMap(\.reason))).sorted()164            ForEach(reasons, id: \.self) { r in Text(NFTText.marketWhy(r)).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }165        }166    }167}168169struct NFTMarketSection: View {170    let ctx: NFTContext171    @Environment(AppModel.self) private var model172    let asset: NFTAsset173    let answer: NFTMarketAnswer?174    let error: Error?175176    var body: some View {177        SectionHeader(title: String(localized: "Marché"))178        VStack(alignment: .leading, spacing: 12) {179            Label(String(localized: "Données de marché lues, pas une valeur. Chaque chiffre est l’affirmation d’une place de marché, avec sa source et sa date."), systemImage: "info.circle")180                .font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("nft.market.readonly")181            if let m = answer {182                Text(String(localized: "Valeur de cet objet : non disponible") + (m.value.map { " (\(NFTText.marketWhy($0.reason)))" } ?? ".")).font(.spCallout.weight(.semibold)).foregroundStyle(Theme.ink)183                    .fixedSize(horizontal: false, vertical: true)184                if m.sources.isEmpty { Text(String(localized: "Aucune source de marché de cette version ne couvre ce réseau.")).font(.spCallout).foregroundStyle(Theme.mute) }185                else if !m.sources.contains(where: { $0.status.isOK }) {186                    Text(String(localized: "Marché indisponible : aucune source n’a répondu pour cet objet. Prix demandé, meilleure offre, dernière vente et prix plancher ne sont pas affichés — rien n’est inventé à leur place."))187                        .font(.spCallout).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("nft.market.none")188                }189                ForEach(Array(m.sources.enumerated()), id: \.offset) { _, s in Divider(); source(s) }190                if !m.contradictions.isEmpty {191                    Divider()192                    VStack(alignment: .leading, spacing: 4) {193                        Label(String(localized: "Les sources divergent — aucune n’est choisie à ta place :"), systemImage: "arrow.triangle.branch").font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.warn)194                        ForEach(Array(m.contradictions.enumerated()), id: \.offset) { _, c in195                            Text("· \(NFTText.marketField(c.field)) — \(c.providers.map(NFTText.sourceName).joined(separator: ", "))").font(.spFootnote).foregroundStyle(Theme.ink)196                        }197                    }.accessibilityIdentifier("nft.market.contradictions")198                }199                if m.sources.contains(where: { $0.status.isOK }) {200                    NavigationLink { NFTMarketDetailView(ctx: ctx, assetKey: asset.key).wallet(model) } label: { Label(String(localized: "Annonces, offres et événements de marché"), systemImage: "list.bullet").font(.spCallout.weight(.semibold)).frame(minHeight: 44) }201                        .accessibilityIdentifier("nft.market.detail")202                }203                Divider()204                NFTMarketActionsList(actions: m.actions, fallbackReason: asset.capabilities.marketBlockedBy)205                if let ext = m.external, !ext.links.isEmpty { Divider(); external(ext.links, notice: ext.notice) }206            } else {207                if let e = error, model.canOperate { Notice(tone: .warn, title: String(localized: "Données de marché indisponibles."), message: NFTText.errorMessage(e).detail) }208                else if !model.canOperate { Text(String(localized: "Données de marché non disponibles hors ligne.")).font(.spCallout).foregroundStyle(Theme.mute) }209                else { ProgressView() }210                if let snap = asset.market { Divider(); snapshot(snap) }211                Divider()212                NFTMarketActionsList(actions: [], fallbackReason: asset.capabilities.marketBlockedBy ?? "market_writes_not_built")213                if let links = asset.externalMarkets, !links.isEmpty { Divider(); external(links, notice: nil) }214            }215        }.spCard(padding: 16)216    }217218    private func line(_ label: String, _ value: String, note: String? = nil) -> some View {219        VStack(alignment: .leading, spacing: 2) {220            Text(label).font(.spFootnote).foregroundStyle(Theme.mute)221            Text(value).font(.spBody.weight(.medium)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)222            if let note { Text(note).font(.system(size: 12)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }223        }.frame(maxWidth: .infinity, alignment: .leading)224    }225226    @ViewBuilder private func source(_ s: NFTItemMarket) -> some View {227        VStack(alignment: .leading, spacing: 8) {228            NFTMarketSourceHeader(status: s.status)229            if s.status.isOK {230                line(String(localized: "En vente"), NFTMarketText.known(s.listed, NFTText.yesNo))231                line(String(localized: "Prix demandé"), NFTMarketText.known(s.ask) { NFTMarketText.price($0.price) + ($0.quantity != "1" ? " " + String(localized: "pour \($0.quantity) unités") : "") },232                     note: s.ask.value.flatMap { a in [a.venue, a.seller.map { String(localized: "vendeur selon la place de marché : \(Money.shortAddress($0))") }].compactMap { $0 }.joined(separator: " · ") })233                line(String(localized: "Meilleure offre"), NFTMarketText.known(s.bestOffer) { NFTMarketText.price($0.price) },234                     note: s.bestOffer.value.flatMap { $0.scope == "collection" ? String(localized: "offre de collection : elle vise n’importe quel objet de la collection") : $0.scope == "trait" ? String(localized: "offre sur un attribut") : nil })235                line(String(localized: "Dernière vente (selon la source)"), NFTMarketText.known(s.lastSale) { NFTMarketText.price($0.price) },236                     note: s.lastSale.value.flatMap { NFTMarketText.when($0.at).map { String(localized: "vente du \($0)") } })237                line(String(localized: "Prix plancher de la collection"), NFTMarketText.known(s.collectionFloor) { NFTMarketText.price($0) },238                     note: String(localized: "Le prix plancher d’une collection n’est pas une estimation de la valeur de cet objet."))239                if let v = s.verification {240                    Label(v.state == "verified" ? String(localized: "Collection vérifiée par \(v.by) — affirmation de cette place de marché, pas une vérification on-chain")241                          : v.state == "not_verified" ? String(localized: "Non vérifiée par \(v.by)") : String(localized: "Vérification par \(v.by) : non établie"),242                          systemImage: v.state == "verified" ? "checkmark.seal" : "questionmark.circle").font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)243                }244                if s.flags?.suspicious.value == true { Label(String(localized: "Signalé comme suspect par \(s.status.name)"), systemImage: "exclamationmark.triangle.fill").font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.warn) }245                if let r = s.rarity?.value { Text(String(localized: "Rang \(r.rank)\(r.outOf.map { " sur \($0)" } ?? "") — méthode \(r.method), selon \(s.status.name)")).font(.spFootnote).foregroundStyle(Theme.mute) }246                if let c = s.collection { Text(String(localized: "Collection selon \(s.status.name) : \(c.name ?? c.slug)")).font(.spFootnote).foregroundStyle(Theme.mute) }247                if let a = s.status.attribution { Text(verbatim: a.text).font(.system(size: 12)).foregroundStyle(Theme.mute) }248            }249        }.accessibilityElement(children: .contain).accessibilityIdentifier("nft.market.source.\(s.status.provider)")250    }251252    /** The single snapshot stored with the item, when the live market answer is not available: dated, from one named source. */253    @ViewBuilder private func snapshot(_ s: NFTMarketSnapshot) -> some View {254        VStack(alignment: .leading, spacing: 8) {255            Text(String(localized: "Instantané enregistré avec la fiche — \(NFTText.sourceName(s.source.source)), \(s.source.fetchedAt.formatted(date: .abbreviated, time: .shortened))")).font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.ink)256            line(String(localized: "En vente"), NFTMarketText.known(s.listed, NFTText.yesNo))257            line(String(localized: "Prix demandé"), NFTMarketText.known(s.listingPrice, NFTText.amount))258            line(String(localized: "Meilleure offre"), NFTMarketText.known(s.bestOffer, NFTText.amount))259            line(String(localized: "Dernière vente (selon la source)"), NFTMarketText.known(s.lastSale, NFTText.amount))260            line(String(localized: "Prix plancher de la collection"), NFTMarketText.known(s.collectionFloor, NFTText.amount), note: String(localized: "Le prix plancher d’une collection n’est pas une estimation de la valeur de cet objet."))261        }262    }263264    @ViewBuilder private func external(_ links: [NFTExternalLink], notice: NFTExternalNotice?) -> some View {265        VStack(alignment: .leading, spacing: 6) {266            Text(String(localized: "Sites externes")).font(.spBody.weight(.semibold)).foregroundStyle(Theme.ink)267            Text(String(localized: "SP Wallet n’a ni WalletConnect ni export de clé : ce portefeuille ne peut pas se connecter à ces sites. Y agir exigerait d’importer la phrase de récupération dans un autre portefeuille, ce que SP Wallet ne fait pas et déconseille."))268                .font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)269            ForEach(Array(links.enumerated()), id: \.offset) { _, l in270                NFTExternalLinkRow(title: l.name, raw: l.url, warning: String(localized: "Ce site s’ouvre dans le navigateur. Toute action s’y déroule hors de SP Wallet, sans ses protections. Ne saisis jamais ta phrase de récupération."))271            }272        }273    }274}275276// MARK: - listings, offers, market events of one item277278struct NFTMarketDetailView: View {279    let ctx: NFTContext280    @Environment(AppModel.self) private var model281    let assetKey: String282    @State private var listings: NFTMarketOrders<NFTMarketListing>?283    @State private var offers: NFTMarketOrders<NFTMarketOffer>?284    @State private var events: NFTMarketEvents?285    @State private var error: Error?286287    var body: some View {288        ScrollView {289            VStack(alignment: .leading, spacing: Theme.Space.section) {290                NFTFixtureBanner(ctx: ctx)291                FreshnessBanner()292                Text(String(localized: "Lecture seule. Chaque source est présentée séparément, avec son état et son heure.")).font(.spCallout).foregroundStyle(Theme.mute)293                if let e = error { NFTErrorNotice(error: e) { Task { await load() } } }294                if let l = listings {295                    SectionHeader(title: String(localized: "Annonces"))296                    ForEach(Array(l.sources.enumerated()), id: \.offset) { _, s in297                        VStack(alignment: .leading, spacing: 8) {298                            NFTMarketSourceHeader(status: s.status)299                            if s.status.isOK, s.items.isEmpty { Text(String(localized: "Aucune annonce pour cet objet selon cette source.")).font(.spFootnote).foregroundStyle(Theme.mute) }300                            ForEach(Array(s.items.enumerated()), id: \.offset) { _, i in301                                Divider()302                                order(NFTMarketText.price(i.price), quantity: i.quantity, who: i.seller.map { String(localized: "vendeur : \($0)") }, venue: i.venue, created: i.createdAt, expires: i.expiresAt, scope: nil, fees: i.fees)303                            }304                        }.spCard(padding: 16)305                    }306                }307                if let o = offers {308                    SectionHeader(title: String(localized: "Offres"))309                    ForEach(Array(o.sources.enumerated()), id: \.offset) { _, s in310                        VStack(alignment: .leading, spacing: 8) {311                            NFTMarketSourceHeader(status: s.status)312                            if s.status.isOK, s.items.isEmpty { Text(String(localized: "Aucune offre sur cet objet selon cette source.")).font(.spFootnote).foregroundStyle(Theme.mute) }313                            ForEach(Array(s.items.enumerated()), id: \.offset) { _, i in314                                Divider()315                                order(NFTMarketText.price(i.price), quantity: i.quantity, who: i.bidder.map { String(localized: "offrant : \($0)") }, venue: i.venue, created: i.createdAt, expires: i.expiresAt, scope: i.scope, fees: i.fees)316                            }317                        }.spCard(padding: 16)318                    }319                }320                if let ev = events {321                    SectionHeader(title: String(localized: "Événements de marché"))322                    Text(String(localized: "Événements rapportés par les places de marché, distincts des transferts lus sur la chaîne. Les annulations ne sont pas fournies par toutes les sources.")).font(.spFootnote).foregroundStyle(Theme.mute)323                    ForEach(Array(ev.sources.enumerated()), id: \.offset) { _, s in324                        VStack(alignment: .leading, spacing: 8) {325                            NFTMarketSourceHeader(status: s.status)326                            if s.status.isOK, s.events.isEmpty { Text(String(localized: "Aucun événement de marché rapporté par cette source.")).font(.spFootnote).foregroundStyle(Theme.mute) }327                            ForEach(Array(s.events.enumerated()), id: \.offset) { _, e in328                                Divider()329                                VStack(alignment: .leading, spacing: 3) {330                                    HStack { Text(NFTText.event(e.type).0).font(.spCallout.weight(.semibold)); Spacer(); Text(NFTMarketText.when(e.at) ?? String(localized: "date non fournie")).font(.spFootnote).foregroundStyle(Theme.mute) }331                                    Text(e.price.map(NFTMarketText.price) ?? String(localized: "sans prix")).font(.spFootnote).foregroundStyle(Theme.ink)332                                    if e.flags?.washTrade.value == true { Label(String(localized: "Signalé comme transaction fictive par \(s.status.name)"), systemImage: "exclamationmark.triangle.fill").font(.spFootnote).foregroundStyle(Theme.warn) }333                                    if let tx = e.tx { Text(verbatim: tx).font(.system(size: 11.5, design: .monospaced)).foregroundStyle(Theme.mute).textSelection(.enabled) }334                                }335                            }336                        }.spCard(padding: 16)337                    }338                }339                if listings == nil, offers == nil, events == nil, error == nil {340                    if model.canOperate { ProgressView().frame(maxWidth: .infinity).padding(.vertical, 40) }341                    else { EmptyState(icon: "wifi.slash", title: String(localized: "Données de marché non disponibles hors ligne")) }342                }343                if let l = listings { NFTMarketActionsList(actions: l.actions).spCard(padding: 16) }344            }345            .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12).frame(maxWidth: 760).frame(maxWidth: .infinity)346        }347        .spPage().navigationTitle(String(localized: "Marché de la pièce")).navigationBarTitleDisplayMode(.inline)348        .task(id: model.canOperate) { await load() }349    }350351    private func load() async {352        guard model.canOperate else { return }353        error = nil354        async let l = Result.catching { [ctx] in try await ctx.api.marketListings(key: assetKey) }355        async let o = Result.catching { [ctx] in try await ctx.api.marketOffers(key: assetKey) }356        async let e = Result.catching { [ctx] in try await ctx.api.marketActivity(key: assetKey) }357        let (rl, ro, re) = await (l, o, e)358        if case .success(let v) = rl { listings = v } else if case .failure(let x) = rl { error = x }359        if case .success(let v) = ro { offers = v } else if case .failure(let x) = ro { error = x }360        if case .success(let v) = re { events = v } else if case .failure(let x) = re { error = x }361    }362363    private func order(_ price: String, quantity: String, who: String?, venue: String?, created: String?, expires: String?, scope: String?, fees: [NFTMarketFee]?) -> some View {364        VStack(alignment: .leading, spacing: 3) {365            Text(price + (quantity != "1" ? " · × \(quantity)" : "")).font(.spBody.weight(.semibold)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)366            if scope == "collection" { Text(String(localized: "offre de collection")).font(.spFootnote).foregroundStyle(Theme.warn) }367            if scope == "trait" { Text(String(localized: "offre sur un attribut")).font(.spFootnote).foregroundStyle(Theme.warn) }368            if let who { Text(verbatim: who).font(.system(size: 12, design: .monospaced)).foregroundStyle(Theme.mute).textSelection(.enabled).fixedSize(horizontal: false, vertical: true) }369            Text([venue, NFTMarketText.when(created).map { String(localized: "créée le \($0)") }, NFTMarketText.when(expires).map { String(localized: "expire le \($0)") }].compactMap { $0 }.joined(separator: " · "))370                .font(.spFootnote).foregroundStyle(Theme.mute)371            ForEach(Array((fees ?? []).enumerated()), id: \.offset) { _, f in372                Text("\(feeKind(f.kind))\(f.bps.map { " : \($0 / 100) %" } ?? "")\(f.required.map { $0 ? " — " + String(localized: "requis") : " — " + String(localized: "facultatif") } ?? "")").font(.spFootnote).foregroundStyle(Theme.mute)373            }374        }375    }376    private func feeKind(_ k: String) -> String {377        switch k { case "marketplace": String(localized: "frais de place de marché"); case "creator_royalty": String(localized: "redevance du créateur"); default: String(localized: "frais (nature non précisée par la source)") }378    }379}380381// MARK: - market sources and the opt-in floor estimate382383struct NFTMarketOverviewView: View {384    let ctx: NFTContext385    @Environment(AppModel.self) private var model386    @State private var providers: NFTMarketProviders?387    @State private var estimate: NFTFloorEstimate?388    @State private var error: Error?389    @State private var busy = false390391    var body: some View {392        ScrollView {393            VStack(alignment: .leading, spacing: Theme.Space.section) {394                NFTFixtureBanner(ctx: ctx)395                FreshnessBanner()396                if let e = error { NFTErrorNotice(error: e) { Task { await load() } } }397                if let p = providers {398                    SectionHeader(title: String(localized: "Sources de marché"))399                    Text(String(localized: "Ce que chaque source apporte, son état, et le réglage serveur qui l’active. Les clés restent sur le serveur.")).font(.spFootnote).foregroundStyle(Theme.mute)400                    ForEach(p.providers) { provider($0) }401                    NFTMarketActionsList(actions: p.actions, fallbackReason: "market_writes_not_built").spCard(padding: 16).accessibilityIdentifier("nft.market.actions")402                }403                if let est = estimate { estimateCard(est) }404                if providers == nil, estimate == nil, error == nil {405                    if model.canOperate { ProgressView().frame(maxWidth: .infinity).padding(.vertical, 40) }406                    else { EmptyState(icon: "wifi.slash", title: String(localized: "Non disponible hors ligne")) }407                }408            }409            .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12).frame(maxWidth: 760).frame(maxWidth: .infinity)410        }411        .spPage().navigationTitle(String(localized: "Marché NFT")).navigationBarTitleDisplayMode(.inline)412        .task(id: model.canOperate) { await load() }413    }414415    private func load() async {416        guard model.canOperate else { return }417        error = nil418        do { providers = try await ctx.api.marketProviders() } catch { self.error = error }419        do { estimate = try await ctx.api.floorEstimate() } catch { self.error = error }420    }421422    private func provider(_ p: NFTMarketProvider) -> some View {423        let st = NFTText.marketState(p.state == "on" ? "on" : p.state)424        return VStack(alignment: .leading, spacing: 5) {425            HStack { Text(p.name).font(.spBody.weight(.semibold)).foregroundStyle(Theme.ink); Spacer(); Pill(text: st.0, tone: st.1) }426            Text(NFTText.sends(p.sends)).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)427            if !p.chains.isEmpty { Text(String(localized: "Réseaux : \(p.chains.map { model.network($0)?.name ?? $0 }.joined(separator: ", "))")).font(.spFootnote).foregroundStyle(Theme.mute) }428            if let u = p.unlockedBy, p.state != "on" { NFTInlineMono(prefix: String(localized: "Réglage serveur : "), mono: u) }429            if let v = p.verification { Text(v == "live" ? String(localized: "adaptateur vérifié en réel") : String(localized: "adaptateur écrit d’après la documentation seulement")).font(.spFootnote).foregroundStyle(Theme.mute) }430            if let b = p.budget { Text(String(localized: "Requêtes : \(b.minute.used)/\(b.minute.limit) cette minute, \(b.day.used)/\(b.day.limit) aujourd’hui") + (b.refused > 0 ? " · " + String(localized: "\(b.refused) refusées") : "")).font(.spFootnote).foregroundStyle(Theme.mute) }431            if let a = p.attribution { Text(verbatim: a.text).font(.system(size: 12)).foregroundStyle(Theme.mute) }432        }.spCard(padding: 16)433    }434435    @ViewBuilder private func estimateCard(_ est: NFTFloorEstimate) -> some View {436        SectionHeader(title: String(localized: "Estimation indicative fondée sur les prix planchers (option)"))437        VStack(alignment: .leading, spacing: 10) {438            Text(String(localized: "Désactivée par défaut. Un prix plancher est le prix demandé le plus bas d’un objet quelconque de la collection : ce n’est pas la valeur de tes objets. Cette vue multiplie le plancher par le nombre d’objets détenus, collection par collection, avec la source et l’âge du plancher."))439                .font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)440            HStack {441                Pill(text: est.enabled ? String(localized: "Option activée") : String(localized: "Option désactivée"), tone: est.enabled ? .info : .neutral)442                Spacer()443                Button(est.enabled ? String(localized: "Masquer l’estimation") : String(localized: "Afficher l’estimation")) { Task { await toggle(!est.enabled) } }444                    .buttonStyle(.bordered).font(.spCallout.weight(.semibold)).disabled(busy || !model.canOperate).accessibilityIdentifier("nft.estimate.toggle")445            }446            if est.enabled, let e = est.estimate {447                Notice(tone: .warn, title: String(localized: "Ce n’est pas une évaluation"), message: String(localized: "Estimation indicative fondée sur les prix planchers — elle n’entre dans aucun total du portefeuille."))448                if e.collections.isEmpty { Text(String(localized: "Aucun objet détenu dans une collection.")).font(.spCallout).foregroundStyle(Theme.mute) }449                ForEach(Array(e.collections.enumerated()), id: \.offset) { _, c in450                    Divider()451                    VStack(alignment: .leading, spacing: 3) {452                        Text(verbatim: c.name ?? (NFTKey(c.collectionKey).map { Money.shortAddress($0.assetId) } ?? c.collectionKey)).font(.spBody.weight(.semibold)).foregroundStyle(Theme.ink)453                        Text(String(localized: "\(c.items) objet(s) détenu(s) · \(model.network(c.chain)?.name ?? c.chain)")).font(.spFootnote).foregroundStyle(Theme.mute)454                        if let u = c.used {455                            Text(String(localized: "plancher \(NFTMarketText.price(u.floor)) — \(NFTText.sourceName(u.provider)), \(u.fetchedAt.map { $0.formatted(date: .abbreviated, time: .shortened) } ?? String(localized: "date non fournie"))") + (u.stale ? " · " + String(localized: "possiblement périmé") : ""))456                                .font(.spFootnote).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)457                            Masked(text: String(localized: "indicatif : \(NFTText.money(u.indicative))")).font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.ink)458                        } else { Text(String(localized: "Non comptée : \(NFTText.marketWhy(c.reason ?? "no_floor_reported"))")).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }459                    }460                }461                Divider()462                if let usd = e.indicativeUsd { Masked(text: String(localized: "Somme indicative : \(Money.exact(usd)) USD sur \(e.collectionsCounted) collection(s).")).font(.spBody.weight(.semibold)).foregroundStyle(Theme.ink).accessibilityIdentifier("nft.estimate.sum") }463                else { Text(String(localized: "Aucune collection n’a pu être comptée : aucune somme.")).font(.spCallout).foregroundStyle(Theme.mute) }464                if e.collectionsWithoutFloor > 0 { Text(String(localized: "\(e.collectionsWithoutFloor) collection(s) sans plancher rapporté ne sont pas comptées.")).font(.spFootnote).foregroundStyle(Theme.mute) }465                if let a = e.asOf { Text(String(localized: "Calculée par le serveur le \(a.formatted(date: .abbreviated, time: .shortened)).")).font(.spFootnote).foregroundStyle(Theme.mute) }466            }467            Text(String(localized: "Exclue du total du portefeuille. La valeur des NFT reste « non disponible ».")).font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.mute)468        }.spCard(padding: 16)469    }470471    private func toggle(_ on: Bool) async {472        busy = true; error = nil473        defer { busy = false }474        do { _ = try await ctx.api.setFloorEstimate(enabled: on); estimate = try await ctx.api.floorEstimate() } catch { self.error = error }475    }476}477
Files main
Menu

Theme