SPB Git

Repository Public

NFTTransfer.swift 29.6 KB 494 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/NFTTransfer.swift10// Description      : Sending one NFT: form (destination checked with the11//                    backend's own address rules, quantity for ERC-1155) →12//                    server preparation (chain re-read on every endpoint,13//                    simulation, policy pre-check) → the Core verifies that the14//                    passkey challenge is the SHA-256 of the NFT intent and15//                    that the intent is the transfer that was asked → a review16//                    sheet that renders the fields OF THAT VERIFIED INTENT in17//                    full, with what the server says it checked shown apart →18//                    passkey → isolated signer → tracking until a terminal19//                    state. The client decides nothing about success, and a20//                    lost answer is followed, never signed twice.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 SPWalletCore100101@MainActor @Observable final class NFTTransferFlow {102    enum Step: Equatable { case form, preparing, review, approving, tracking }103104    let model: AppModel105    let api: NFTAPI106    let asset: NFTAsset107    let verdict: NFTTransferVerdictAnswer?108109    var to = ""110    var quantity = "1"111112    private(set) var step: Step = .form113    private(set) var approval: NFTTransferApproval?114    private(set) var tracked: NFTTransfer?115    private(set) var history: [(Date, ProposalState)] = []116    /// True once something was approved: the item and the inventory must be read again.117    private(set) var changed = false118    var error: String?119    /// Kept while the form does not change, so a retried preparation answers the same proposal instead of creating a second one.120    private var idempotency: (key: String, fingerprint: String)?121    private var trackTask: Task<Void, Never>?122123    init(model: AppModel, asset: NFTAsset, verdict: NFTTransferVerdictAnswer?) {124        self.model = model; self.asset = asset; self.verdict = verdict; api = NFTAPI(model.client)125    }126127    var net: SPWalletCore.Network? { model.network(asset.chainId) }128    var isMultiUnit: Bool { asset.standard == .erc1155 }129    var trimmedTo: String { to.trimmingCharacters(in: .whitespacesAndNewlines) }130    var addressCheck: AddressCheck? { guard let n = net, !trimmedTo.isEmpty else { return nil }; return AddressValidator.check(trimmedTo, network: n) }131    var otherNetworks: [SPWalletCore.Network] {132        guard let all = model.networks?.value, addressCheck?.isValid == false else { return [] }133        return AddressValidator.plausibleNetworks(for: trimmedTo, among: all).filter { $0.id != asset.chainId }134    }135    private func same(_ a: String, _ b: String?) -> Bool {136        guard let b else { return false }137        return a.hasPrefix("0x") && b.hasPrefix("0x") ? a.lowercased() == b.lowercased() : a == b138    }139    var isOwnAddress: Bool {140        guard let n = addressCheck?.normalized else { return false }141        return same(n, model.address(on: asset.chainId)) || same(n, asset.ownerAddress)142    }143    var isAssetItself: Bool { guard let n = addressCheck?.normalized else { return false }; return same(n, asset.assetAddress) }144    var quantityUnits: BaseUnits? {145        let q = quantity.trimmingCharacters(in: .whitespaces)146        guard q.range(of: "^[1-9][0-9]{0,77}$", options: .regularExpression) != nil else { return nil }147        return try? BaseUnits(q)148    }149150    var formProblem: String? {151        guard net != nil else { return "Le réseau de cet NFT n’est pas dans le registre lu par l’app." }152        switch addressCheck {153        case nil: return "Entrez l’adresse du destinataire."154        case .invalid(let r): return SendFlow.text(r)155        case .unverifiable, .valid: break156        }157        if isOwnAddress { return "La destination est l’adresse de ce portefeuille." }158        if isAssetItself { return "La destination est le contrat (ou le mint) de l’NFT lui-même : il serait perdu." }159        if isMultiUnit {160            guard let q = quantityUnits else { return "Quantité invalide : un entier d’au moins 1." }161            if let held = asset.quantityUnits, q > held { return "Quantité supérieure aux \(asset.quantity) unité(s) détenue(s)." }162            if let max = verdict?.signer.maxErc1155Quantity, let m = try? BaseUnits(max), q > m { return "La politique du signataire limite un transfert ERC-1155 à \(max) unité(s)." }163        }164        return nil165    }166167    func prepare() async {168        guard formProblem == nil, model.canOperate, step == .form else { return }169        error = nil; step = .preparing170        let destination = addressCheck?.normalized ?? trimmedTo171        let units = isMultiUnit ? (quantityUnits?.description ?? "1") : "1"172        let fingerprint = "\(asset.key)|\(destination)|\(units)"173        if idempotency?.fingerprint != fingerprint { idempotency = (APIClient.newIdempotencyKey(), fingerprint) }174        do {175            let request = try NFTTransferRequest(item: asset, to: destination, quantity: units)176            // the Core compares the intent with this request field by field and binds it to the challenge before anything is returned177            let a = try await api.prepareTransfer(request, idempotencyKey: idempotency!.key)178            guard a.transfer.state == .pendingApproval || a.transfer.state == .draft else {179                idempotency = nil180                throw APIError(status: 409, code: "bad_state", message: "Cette demande a déjà été traitée (\(ErrorText.state(a.transfer.state))). Préparez-la de nouveau.")181            }182            approval = a; step = .review183        } catch {184            if case ApprovalError.expired = error { idempotency = nil }185            self.error = model.describe(error); step = .form186        }187    }188189    func approve() async {190        guard let a = approval, step == .review else { return }191        error = nil; step = .approving192        do {193            let t = try await api.approveTransfer(a, with: model.authenticator)194            idempotency = nil195            begin(tracking: t)196        } catch PasskeyError.cancelled { step = .review }197        catch let e as APIError where e.isOffline {198            // the answer was lost: the approval may have reached the signer — never sign twice, read the proposal instead199            self.error = "Réponse perdue pendant l’approbation. Lecture de l’état réel du transfert…"200            await recover(a)201        }202        catch {203            self.error = model.describe(error)204            await recover(a)205        }206    }207208    private func recover(_ a: NFTTransferApproval) async {209        if let t = try? await api.transfer(id: a.transfer.id), t.state != .pendingApproval, t.state != .draft { idempotency = nil; begin(tracking: t) }210        else { step = .review }211    }212213    func reject() async {214        guard let a = approval, step == .review else { return }215        do { _ = try await api.rejectTransfer(id: a.transfer.id) } catch { self.error = model.describe(error) }216        idempotency = nil; approval = nil; step = .form217    }218219    private func begin(tracking t: NFTTransfer) {220        tracked = t; history = [(Date(), t.state)]; step = .tracking; changed = true221        Task { await model.refreshActivity() }222        if t.state.isTerminal { Notifier.proposal(t.proposal); return }223        trackTask?.cancel()224        trackTask = Task { [weak self] in225            while !Task.isCancelled {226                guard let self, let current = self.tracked, !current.state.isTerminal else { return }227                try? await Task.sleep(for: .seconds(current.state == .broadcast || current.state == .confirming ? 5 : 2))228                guard !Task.isCancelled, AppActivity.isActive else { continue }229                guard let t = try? await self.api.transfer(id: current.id) else { continue }230                if t.state != self.tracked?.state {231                    self.history.append((Date(), t.state))232                    if t.state.isTerminal { Notifier.proposal(t.proposal); await self.model.refreshAll() }233                }234                self.tracked = t235            }236        }237    }238239    func stop() { trackTask?.cancel(); trackTask = nil }240}241242// MARK: - Review of the verified intent243244enum NFTIntentReview {245    /// Every field of the verified NFT intent, in reading order. Nothing is abbreviated and nothing comes from the server's summary.246    static func lines(_ i: NFTIntent, network n: SPWalletCore.Network?) -> [ReviewLine] {247        var out: [ReviewLine] = []248        let feeSymbol = n?.native.symbol ?? "(monnaie native)"249        let fee: String = n.map { Fmt.amount(i.maxFeeUnits.formatted(decimals: $0.native.decimals)) } ?? "\(i.maxFee) unités de base"250        out.append(.init(label: "Type d’opération", value: "Transfert d’un NFT (\(i.kind), version \(i.v))", style: .strong))251        out.append(.init(label: "Réseau", value: "\(n?.name ?? i.network)  (\(i.network), \(i.chainRef))"))252        out.append(.init(label: "Standard", value: NFTText.standard(NFTStandard(rawValue: i.standard.rawValue)), style: .strong))253        out.append(.init(label: "Appel effectué", value: i.standard.method))254        out.append(.init(label: i.standard.isEVM ? "Contrat du jeton" : i.standard == .metaplexCore ? "Adresse de l’actif" : "Mint", value: i.asset, style: .address))255        if let t = i.tokenId { out.append(.init(label: "Identifiant du jeton", value: t, style: .address)) }256        else { out.append(.init(label: "Identifiant du jeton", value: "Sans objet : sur Solana l’adresse ci-dessus est l’identité de l’NFT.")) }257        out.append(.init(label: "Quantité envoyée", value: i.standard == .erc1155 ? "\(Fmt.amount(i.quantity)) unité(s) de cet identifiant ERC-1155" : i.quantity, style: .strong))258        out.append(.init(label: i.standard.isEVM ? "Contrat appelé" : "Programme appelé", value: i.program, style: .address))259        out.append(.init(label: "Depuis", value: i.from, style: .address))260        out.append(.init(label: "Destinataire", value: i.to, style: .address))261        out.append(.init(label: "Frais de réseau maximum", value: "\(fee) \(feeSymbol)", style: .strong))262        out.append(.init(label: "Expiration de l’approbation", value: Fmt.dateSeconds(i.expiry)))263        if let e = i.evm { out.append(.init(label: "Paramètres EVM", value: "nonce \(e.nonce) · gaz \(e.gasLimit) · max \(e.maxFeePerGas) wei/gaz · priorité \(e.maxPriorityFeePerGas)")) }264        if let s = i.sol {265            out.append(.init(label: "Paramètres Solana", value: "blockhash \(s.recentBlockhash) · valide jusqu’au bloc \(s.lastValidBlockHeight) · \(s.computeUnitLimit) CU à \(s.computeUnitPrice) µlamports" + (s.tokenProgram.map { " · programme de jetons : \($0)" } ?? "")))266            if s.createAta == true { out.append(.init(label: "Compte créé", value: "La transaction crée d’abord le compte de jetons associé du destinataire : un loyer (rent) y est immobilisé, à vos frais.", style: .warning)) }267            if let r = s.ruleSet { out.append(.init(label: "Jeu de règles (pNFT)", value: r, style: .address)) }268            if let c = s.collection { out.append(.init(label: "Collection (Core)", value: c, style: .address)) }269        }270        out.append(.init(label: "Clé du portefeuille", value: i.keyId))271        out.append(.init(label: "Politique du signataire", value: "version \(i.policyVersion) · politique NFT version \(i.nftPolicyVersion)"))272        return out273    }274275    static func toKind(_ k: String) -> String {276        switch k { case "account": "un compte ordinaire"; case "contract": "un CONTRAT"; case "new_account": "un compte qui n’existe pas encore sur ce réseau"; default: k }277    }278}279280// MARK: - Sheet281282struct NFTTransferSheet: View {283    let model: AppModel284    let gallery: NFTGallery285    let asset: NFTAsset286    let verdict: NFTTransferVerdictAnswer?287    /// `true` when something was approved (the caller reads the item again).288    let close: (Bool) -> Void289    @State private var flow: NFTTransferFlow?290291    var body: some View {292        VStack(alignment: .leading, spacing: 0) {293            if let flow {294                switch flow.step {295                case .form, .preparing: form(flow)296                case .review, .approving: if let a = flow.approval { review(flow, a) }297                case .tracking: tracking(flow)298                }299            } else { ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) }300        }301        .frame(width: 760, height: 800)302        .interactiveDismissDisabled()303        .task { if flow == nil { flow = NFTTransferFlow(model: model, asset: asset, verdict: verdict) } }304        .onDisappear { flow?.stop() }305    }306307    private func header(_ title: String) -> some View {308        VStack(alignment: .leading, spacing: 0) {309            HStack(spacing: 12) {310                NFTThumbView(mediaId: (asset.media.first { $0.role == "image" } ?? asset.media.first)?.id, kind: (asset.media.first { $0.role == "image" } ?? asset.media.first)?.kind,311                             pixels: NFTMediaStore.gridPixels, api: gallery.mediaAPI, maxBytes: gallery.mediaLimit).frame(width: 56, height: 56)312                VStack(alignment: .leading, spacing: 2) {313                    Text(title).font(.title2.weight(.semibold))314                    NFTPlain("\(NFTClean.line(asset.displayName, max: 80) ?? "NFT sans nom") · \(gallery.networkName(asset.chainId)) — nom et image déclarés par le créateur, non vérifiés").font(.callout).foregroundStyle(.secondary).lineLimit(2)315                }316            }.padding(20)317            Divider()318        }319    }320321    // MARK: form322323    private func form(_ flow: NFTTransferFlow) -> some View {324        @Bindable var flow = flow325        return VStack(alignment: .leading, spacing: 0) {326            header("Envoyer cet NFT")327            ScrollView {328                VStack(alignment: .leading, spacing: 14) {329                    if !model.canOperate { Banner(.warning, "Envoi impossible pour l’instant : session ou portefeuille indisponible.") }330                    if verdict?.broadcast == false { Banner(.warning, "SERVEUR DE TEST — il signe mais ne diffuse pas : rien ne quittera le portefeuille.") }331                    Card("Ce qui sera envoyé") {332                        Field(label: "Standard", value: NFTText.standard(asset.standard))333                        if let c = asset.contractAddress { Field(label: "Contrat", value: c, mono: true) }334                        if let m = asset.mintAddress { Field(label: "Mint / actif", value: m, mono: true) }335                        if let t = asset.tokenId { Field(label: "Identifiant du jeton", value: t, mono: true) }336                        Field(label: "Quantité détenue", value: Fmt.amount(asset.quantity))337                    }338                    Card("Destination") {339                        Form {340                            TextField("Destinataire", text: $flow.to, prompt: Text(verbatim: "Adresse sur \(flow.net?.name ?? asset.chainId)"), axis: .vertical).font(Theme.monoSmall).lineLimit(1...3)341                            addressFeedback(flow)342                            if flow.isMultiUnit {343                                TextField("Quantité (unités de cet identifiant ERC-1155)", text: $flow.quantity)344                                LabeledContent("") { Button("Tout (\(asset.quantity))") { flow.quantity = asset.quantity }.buttonStyle(.link) }345                            } else {346                                LabeledContent("Quantité") { Text("1 — ce standard s’envoie à l’unité") }347                            }348                        }.formStyle(.grouped).scrollDisabled(true).disabled(flow.step != .form)349                        if verdict?.signer.allowlistOnly == true {350                            Banner(.info, "La politique du signataire ne signe les transferts de NFT que vers les destinations de sa liste autorisée (« Contrôles du signataire »). Une autre destination sera refusée.")351                        }352                    }353                    ForEach(verdict?.warnings ?? asset.capabilities.transferWarnings ?? [], id: \.self) { w in Banner(.warning, NFTText.warning(w)) }354                    Text("Préparer ne signe rien et n’envoie rien : le serveur relit la propriété et le standard sur chaque point d’accès, simule le transfert, calcule les frais et vérifie la politique du signataire. L’envoi n’a lieu qu’après votre approbation par passkey sur l’écran suivant. Un NFT envoyé ne peut pas être récupéré.")355                        .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)356                }.padding(20)357            }358            Divider()359            VStack(alignment: .leading, spacing: 8) {360                if let e = flow.error { Banner(.danger, e) }361                HStack {362                    Button("Annuler") { close(flow.changed) }.disabled(flow.step == .preparing)363                    if let p = flow.formProblem, !flow.to.isEmpty { Text(p).foregroundStyle(.secondary).font(.callout).lineLimit(2) }364                    Spacer()365                    if flow.step == .preparing { ProgressView().controlSize(.small); Text("Relecture de la chaîne, simulation, frais…").font(.callout).foregroundStyle(.secondary) }366                    Button("Préparer et vérifier…") { Task { await flow.prepare() } }.buttonStyle(.borderedProminent).controlSize(.large)367                        .disabled(flow.formProblem != nil || !model.canOperate || flow.step != .form)368                }369            }.padding(16)370        }371    }372373    @ViewBuilder private func addressFeedback(_ flow: NFTTransferFlow) -> some View {374        switch flow.addressCheck {375        case .valid(let n):376            let bad = flow.isOwnAddress || flow.isAssetItself377            LabeledContent("") {378                Label { NFTPlain(flow.isOwnAddress ? "C’est l’adresse de ce portefeuille" : flow.isAssetItself ? "C’est le contrat de l’NFT lui-même" : n == flow.trimmedTo ? "Adresse valide pour ce réseau" : "Valide — forme normalisée : \(n)") } icon: { Image(systemName: bad ? "xmark.circle" : "checkmark.circle") }379                    .foregroundStyle(bad ? Theme.negative : Theme.positive).font(.callout)380            }381        case .invalid(let r):382            LabeledContent("") {383                VStack(alignment: .leading) {384                    Label(SendFlow.text(r), systemImage: "xmark.circle").foregroundStyle(Theme.negative).font(.callout)385                    if !flow.otherNetworks.isEmpty { NFTPlain("Cette adresse est valide sur : \(flow.otherNetworks.map(\.name).joined(separator: ", ")). Un NFT n’existe que sur son réseau.").font(.caption).foregroundStyle(Theme.warning) }386                }387            }388        case .unverifiable: LabeledContent("") { Label("Format non vérifiable par cette version de l’app : le serveur validera l’adresse.", systemImage: "questionmark.circle").foregroundStyle(Theme.warning).font(.callout) }389        case nil: EmptyView()390        }391    }392393    // MARK: review394395    private func review(_ flow: NFTTransferFlow, _ a: NFTTransferApproval) -> some View {396        let i = a.intent397        return VStack(alignment: .leading, spacing: 0) {398            header("Vérifier et approuver l’envoi de l’NFT")399            ScrollView {400                VStack(alignment: .leading, spacing: 14) {401                    if verdict?.broadcast == false { Banner(.warning, "SERVEUR DE TEST — la transaction sera signée mais NON diffusée.") }402                    if a.replayed { Banner(.info, "Cette préparation avait déjà été faite : le serveur a répondu la même proposition et le même défi.") }403                    ForEach(a.transfer.proposal.warnings ?? a.review?.warnings ?? [], id: \.self) { w in Banner(w == "address_poisoning_suspected" ? .danger : .warning, NFTText.warning(w)) }404                    Text("Ce que votre passkey va signer").font(.headline)405                    ReviewLines(lines: NFTIntentReview.lines(i, network: model.network(i.network)))406                    VStack(alignment: .leading, spacing: 4) {407                        Text("Adresse du destinataire, par groupes de 4 caractères").font(.caption).foregroundStyle(.secondary)408                        NFTPlain(Fmt.chunked(i.to)).font(.system(.title3, design: .monospaced)).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)409                    }410                    .padding(10).frame(maxWidth: .infinity, alignment: .leading).background(Color.secondary.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))411                    if let r = a.review { serverChecks(r) }412                    Banner(.warning, "Un NFT envoyé est irréversible : une adresse erronée, un mauvais réseau ou un contrat qui ne sait pas le restituer signifient sa perte définitive.")413                    Text("Le signataire isolé reconstruit la transaction à partir des seuls champs ci-dessus et applique sa politique NFT (réseau et standard autorisés, plafond quotidien, liste de destinations, plafond de frais). Il ne lit pas la chaîne : il ne vérifie ni que ce portefeuille détient l’NFT, ni le standard du contrat. Ces deux points ont été établis par le serveur, comme indiqué ci-dessus, et la chaîne refusera un transfert que ce portefeuille ne peut pas faire.")414                        .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)415                    BindingProof(digest: a.approval.digest, expiry: i.expiry)416                }.padding(20)417            }418            Divider()419            VStack(alignment: .leading, spacing: 8) {420                if let e = flow.error { Banner(.danger, e) }421                HStack {422                    Button("Rejeter", role: .destructive) { Task { await flow.reject() } }.disabled(flow.step == .approving)423                    Spacer()424                    if flow.step == .approving { ProgressView().controlSize(.small); Text("Passkey, puis signature isolée…").foregroundStyle(.secondary) }425                    Button { Task { await flow.approve() } } label: { Label("Approuver avec la passkey", systemImage: "touchid") }426                        .buttonStyle(.borderedProminent).controlSize(.large).disabled(flow.step == .approving)427                }428            }.padding(16)429        }430    }431432    /// The server's own account of what it read and simulated. Shown apart: it is not what the passkey signs.433    private func serverChecks(_ r: NFTReview) -> some View {434        VStack(alignment: .leading, spacing: 8) {435            Text("Ce que le serveur déclare avoir vérifié et simulé (non signé)").font(.headline)436            Field(label: "Standard établi", value: r.verified.standard)437            Field(label: "Propriété établie", value: r.verified.ownership)438            Field(label: "Points d’accès concordants", value: "\(r.verified.endpoints)\(r.verified.at.map { " — le \(Fmt.dateSeconds($0))" } ?? "")")439            Field(label: "Nature de la destination", value: NFTIntentReview.toKind(r.toKind), emphasis: r.toKind != "account")440            Field(label: "Simulation", value: "\(r.simulation.ok ? "réussie" : "ÉCHEC") — \(r.simulation.detail)\(r.simulation.used.map { " (consommé : \($0))" } ?? "")", emphasis: !r.simulation.ok)441            ForEach(Array(r.simulation.changes.enumerated()), id: \.offset) { _, c in442                Field(label: "Effet simulé", value: "\(c.what) : \(c.before) → \(c.after)")443            }444            Field(label: "Frais estimés", value: "\(r.fee.estimateDisplay.map { Fmt.amount($0) } ?? r.fee.estimate) \(r.fee.symbol) (estimation ; le plafond signé est plus haut)")445            if let rent = r.fee.rent, rent != "0" {446                Field(label: "Loyer immobilisé", value: "\((try? BaseUnits(rent))?.formatted(decimals: r.fee.decimals) ?? rent) \(r.fee.symbol) — placé dans le compte créé pour le destinataire, pas un frais de réseau", emphasis: true)447            }448            if !r.accounts.isEmpty {449                Field(label: "Comptes de l’instruction", value: r.accounts.map { "\($0.role) : \($0.address) (\($0.derived))" }.joined(separator: "\n"), mono: true)450            }451            if let c = r.creatorMetadata, c.name != nil || c.collectionName != nil {452                NFTPlain("Déclaré par le créateur, NON vérifié, sans effet sur la transaction : \(NFTClean.line(c.name, max: 80) ?? "sans nom")\(NFTClean.line(c.collectionName, max: 80).map { " · collection « \($0) »" } ?? "")").font(.caption).foregroundStyle(.secondary)453            }454        }455        .padding(12).frame(maxWidth: .infinity, alignment: .leading).background(Color.secondary.opacity(0.06), in: RoundedRectangle(cornerRadius: 8))456    }457458    // MARK: tracking459460    private func tracking(_ flow: NFTTransferFlow) -> some View {461        VStack(alignment: .leading, spacing: 0) {462            header("Suivi du transfert")463            ScrollView {464                VStack(alignment: .leading, spacing: 14) {465                    if let e = flow.error { Banner(.warning, e) }466                    if let t = flow.tracked {467                        Card {468                            ProposalStatusView(proposal: t.proposal)469                            if let r = t.review {470                                Field(label: r.standard.isEVMStandard ? "Contrat" : "Mint / actif", value: r.asset, mono: true)471                                if let id = r.tokenId { Field(label: "Identifiant du jeton", value: id, mono: true) }472                            }473                            Divider()474                            VStack(alignment: .leading, spacing: 4) {475                                Text("Historique des états").font(.caption).foregroundStyle(.secondary)476                                ForEach(Array(flow.history.enumerated()), id: \.offset) { _, h in477                                    HStack { Text(Fmt.dateSeconds(h.0)).monospacedDigit().foregroundStyle(.secondary); Text(ErrorText.state(h.1)) }.font(.callout)478                                }479                            }480                        }481                        if !t.state.isTerminal { Text("Le transfert n’est acquis qu’à l’état « Finalisée ». Vous pouvez fermer cette fenêtre : le serveur poursuit le suivi, visible dans l’historique de la fiche et dans Activité.").font(.caption).foregroundStyle(.secondary) }482                    }483                }.padding(20)484            }485            Divider()486            HStack { Spacer(); Button("Fermer") { close(flow.changed) }.keyboardShortcut(.defaultAction) }.padding(16)487        }488    }489}490491private extension NFTStandard {492    var isEVMStandard: Bool { rawValue == "erc721" || rawValue == "erc1155" || rawValue == "evm-nonstandard" }493}494
Files main
Menu

Theme