SPB Git

Repository Public

NFTTransferFlow.swift 32.0 KB 467 lines swift

1// SP Wallet iOS2// File: Features/NFTs/NFTTransferFlow.swift3// Description: Sending one NFT, step by step: destination (typed, pasted, scanned or from the address book — checked) and, for4//              ERC-1155, the quantity; then the server's preparation (chain re-read, simulation, limits) and the review of the5//              exact NFT intent SPWalletCore verified against the request and bound to the passkey challenge — every on-chain6//              identifier in full; then the passkey; then the follow-up of the proposal until the chain finalizes it. What the7//              creator declares (name, image) is shown small and labelled unverified: it is never what is approved. The piece8//              leaves the gallery only when the server's inventory says so.9//10// Author: Simon-Pierre Boucher11// Contact: contact@spboucher.ai12import SwiftUI13import SPWalletCore1415@MainActor @Observable16final class NFTTransferModel {17    enum Step: Equatable { case form, review, tracking }18    enum QuantityProblem: Equatable { case notAWholeNumber, zero, aboveHeld }1920    let item: NFTAsset21    var step: Step = .form22    var to = ""23    var quantity = "1"24    var busy = false25    var error: Error?26    var approval: NFTTransferApproval?27    var submitted: NFTTransfer?28    /** The owner ticked « I checked the full destination address » on this review. */29    var acknowledged = false30    /** One key per distinct request: retrying the same request after a lost answer returns the same proposal instead of a second one. */31    private var idempotency: (key: String, request: NFTTransferRequest)?3233    init(item: NFTAsset) { self.item = item }3435    /** Only ERC-1155 carries a quantity; every other standard moves exactly one unit. */36    var isMulti: Bool { item.standard == .erc1155 }37    var effectiveQuantity: String { isMulti ? quantity.trimmingCharacters(in: .whitespaces) : "1" }3839    /** What is wrong with a typed quantity, before any request. */40    static func quantityProblem(_ text: String, held: String, multi: Bool) -> QuantityProblem? {41        guard multi else { return nil }42        let t = text.trimmingCharacters(in: .whitespaces)43        guard t.range(of: "^[0-9]{1,78}$", options: .regularExpression) != nil else { return .notAWholeNumber }44        // the server takes a canonical positive integer: no zero, no leading zero45        if t.hasPrefix("0") { return .zero }46        guard let v = try? BaseUnits(t) else { return .notAWholeNumber }47        guard let h = try? BaseUnits(held) else { return nil } // unreadable holding: the server decides48        return v > h ? .aboveHeld : nil49    }50    var quantityProblem: QuantityProblem? { Self.quantityProblem(quantity, held: item.quantity, multi: isMulti) }5152    /** The request for what is typed; throws when no transfer exists for this standard. nil while the destination is empty. */53    func request() throws -> NFTTransferRequest? {54        let dest = to.trimmingCharacters(in: .whitespacesAndNewlines)55        guard !dest.isEmpty, quantityProblem == nil else { return nil }56        return try NFTTransferRequest(item: item, to: dest, quantity: effectiveQuantity)57    }5859    private func key(for r: NFTTransferRequest) -> String {60        if let i = idempotency, i.request == r { return i.key }61        let k = APIClient.newIdempotencyKey()62        idempotency = (k, r)63        return k64    }6566    /** Server preparation, then the Core's checks (intent == request, review == intent, challenge == hash of the intent). */67    func prepare(_ api: NFTAPI) async {68        guard !busy else { return }69        busy = true; error = nil70        defer { busy = false }71        do {72            guard let r = try request() else { return }73            approval = try await api.prepareTransfer(r, idempotencyKey: key(for: r))74            acknowledged = false75            step = .review76        } catch let e as APIError where e.isOffline {77            error = e // the answer may have been lost: the same key is kept so that a retry returns the same proposal78        } catch {79            idempotency = nil // a refusal or an expired replay: the next attempt is a new preparation80            self.error = error81        }82    }8384    /** The approval window is short: after it, a new preparation re-reads the chain and issues a new challenge. */85    func prepareAgain(_ api: NFTAPI) async {86        idempotency = nil87        await prepare(api)88    }8990    func approve(_ api: NFTAPI, passkeys: any PasskeyAuthenticator) async {91        guard let a = approval, acknowledged, !busy else { return }92        busy = true; error = nil93        defer { busy = false }94        do {95            submitted = try await api.approveTransfer(a, with: passkeys)96            step = .tracking97        } catch PasskeyError.cancelled {98            // sheet dismissed: nothing signed, the proposal stays pending and can be approved or refused99        } catch let e as APIError where e.isOffline {100            // the answer was lost AFTER the assertion left: never sign again — read the real state instead101            if let t = try? await api.transfer(id: a.transfer.id), t.state != .pendingApproval { submitted = t; step = .tracking } else { error = e }102        } catch { self.error = error }103    }104105    func reject(_ api: NFTAPI) async {106        if let a = approval { _ = try? await api.rejectTransfer(id: a.transfer.id) }107        approval = nil; idempotency = nil; acknowledged = false; step = .form108    }109110    /** One read of the proposal's real state. Returns true when it is terminal. */111    func refreshStatus(_ api: NFTAPI) async -> Bool {112        guard let id = submitted?.id else { return true }113        if let t = try? await api.transfer(id: id) { submitted = t }114        return submitted?.state.isTerminal ?? false115    }116}117118struct NFTTransferFlow: View {119    let ctx: NFTContext120    @Environment(AppModel.self) private var model121    @Environment(\.dismiss) private var dismiss122    @State private var send: NFTTransferModel123    @State private var scanning = false124    @State private var showBook = false125    @State private var scanNotice: String?126    @State private var confirmCancel = false127    @FocusState private var typing: Bool128129    init(ctx: NFTContext, item: NFTAsset) { self.ctx = ctx; _send = State(initialValue: NFTTransferModel(item: item)) }130131    private var item: NFTAsset { send.item }132    private var network: Network? { model.network(item.chainId) }133134    var body: some View {135        NavigationStack {136            ScrollView {137                VStack(alignment: .leading, spacing: Theme.Space.section) {138                    NFTFixtureBanner(ctx: ctx)139                    if !model.canOperate { Notice(tone: .warn, title: String(localized: "Envoi indisponible hors ligne"), message: String(localized: "Un envoi exige le serveur, le signataire isolé et ta clé d’accès.")) }140                    switch send.step {141                    case .form: form142                    case .review: review143                    case .tracking: tracking144                    }145                }146                .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12).frame(maxWidth: 620).frame(maxWidth: .infinity)147            }148            .spPage().scrollDismissesKeyboard(.interactively)149            .navigationTitle(title).navigationBarTitleDisplayMode(.inline)150            .toolbar {151                ToolbarItem(placement: .cancellationAction) {152                    Button(send.step == .tracking ? String(localized: "Fermer") : String(localized: "Annuler")) { if send.step == .review { confirmCancel = true } else { dismiss() } }153                        .accessibilityIdentifier("nft.send.close")154                }155                ToolbarItemGroup(placement: .keyboard) { Spacer(); Button(String(localized: "Terminé")) { typing = false }.accessibilityIdentifier("nft.send.keyboardDone") }156            }157            .confirmationDialog(String(localized: "Refuser cet envoi ?"), isPresented: $confirmCancel, titleVisibility: .visible) {158                Button(String(localized: "Refuser et fermer"), role: .destructive) { Task { await send.reject(ctx.api); dismiss() } }159                Button(String(localized: "Continuer la revue"), role: .cancel) {}160            } message: { Text(String(localized: "Rien n’a été signé. La proposition sera marquée refusée.")) }161            .sheet(isPresented: $scanning) { QRScannerSheet { handleScan($0, source: String(localized: "code QR")) }.wallet(model) }162            .sheet(isPresented: $showBook) { AddressBookPicker(network: item.chainId) { send.to = $0.address; showBook = false }.wallet(model) }163        }164        // an approval is never dismissed by an accidental swipe165        .interactiveDismissDisabled(send.step == .review || send.busy)166        .presentationSizing(.page)167    }168169    private var title: String {170        switch send.step { case .form: String(localized: "Envoyer ce NFT"); case .review: String(localized: "Vérifier et approuver"); case .tracking: String(localized: "Suivi de l’envoi du NFT") }171    }172173    // MARK: form174175    private var addressCheck: AddressVerdict? {176        let t = send.to.trimmingCharacters(in: .whitespacesAndNewlines)177        guard !t.isEmpty else { return nil }178        guard let n = network else { return .unverifiable }179        return AddressChecks.check(t, network: n, own: model.account(n.id)?.address ?? item.ownerAddress)180    }181    private var canPrepare: Bool {182        guard model.canOperate, !send.busy, send.quantityProblem == nil, item.standard.transferStandard != nil, let c = addressCheck else { return false }183        if case .invalid = c { return false }184        return true185    }186187    @ViewBuilder private var form: some View {188        let evm = item.family == "evm"189        Text(String(localized: "Tu envoies — identifiants on-chain")).spEyebrow()190        NFTFactCard(rows: [191            (String(localized: "Réseau"), network?.name ?? item.chainId, false),192            (String(localized: "Standard"), NFTText.standard(item.standard), false),193            (evm ? String(localized: "Contrat") : String(localized: "Mint / adresse de l’actif"), item.assetAddress, true),194        ] + (item.tokenId.map { [(String(localized: "Identifiant du jeton"), $0, true)] } ?? []) + [195            (String(localized: "Unités détenues"), item.quantity, false),196            (String(localized: "Transfert par"), item.transfer?.route ?? item.standard.transferStandard?.method ?? String(localized: "non établi"), false),197        ]).accessibilityIdentifier("nft.send.identity")198        NFTCreatorNote(ctx: ctx, name: item.displayName, collection: item.collection?.name, imageId: (item.media.first { $0.role == "image" } ?? item.media.first)?.id)199        ForEach(item.transfer?.warnings ?? item.capabilities.transferWarnings ?? [], id: \.self) { w in let t = NFTText.transferWarning(w); Notice(tone: t.tone, title: t.title) }200201        VStack(alignment: .leading, spacing: 10) {202            Text(String(localized: "Destinataire")).font(.spHeadline)203            TextField(String(localized: "Adresse \(network?.name ?? item.chainId)"), text: $send.to, axis: .vertical)204                .font(.spMono).textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.asciiCapable).lineLimit(1...4)205                .padding(12).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small)).focused($typing).accessibilityIdentifier("nft.send.to")206            HStack(spacing: 8) {207                Button { if let s = UIPasteboard.general.string { handleScan(s, source: String(localized: "presse-papiers")) } } label: { Label(String(localized: "Coller"), systemImage: "doc.on.clipboard") }.buttonStyle(.bordered)208                Button { scanning = true } label: { Label(String(localized: "Scanner"), systemImage: "qrcode.viewfinder") }.buttonStyle(.bordered).accessibilityIdentifier("nft.send.scan")209                Button { showBook = true } label: { Label(String(localized: "Carnet"), systemImage: "book.closed") }.buttonStyle(.bordered).disabled(!model.canOperate)210            }.font(.spCallout.weight(.semibold))211            if let s = scanNotice { Notice(tone: .info, title: s) }212            if let c = addressCheck {213                switch c {214                case .valid: Label(String(localized: "Format d’adresse valide pour \(network?.name ?? item.chainId) (le serveur la revalide)"), systemImage: "checkmark.circle.fill").font(.spFootnote).foregroundStyle(Theme.emerald)215                case .invalid(let why): Label(why, systemImage: "xmark.octagon.fill").font(.spFootnote).foregroundStyle(Theme.danger).accessibilityIdentifier("nft.send.addressError")216                case .unverifiable: Label(String(localized: "Le format sera validé par le serveur à l’étape suivante"), systemImage: "info.circle").font(.spFootnote).foregroundStyle(Theme.mute)217                }218            }219            Text(String(localized: "Vérifie l’adresse en entier : un NFT envoyé à une mauvaise adresse est perdu.")).font(.spFootnote).foregroundStyle(Theme.mute)220        }.spCard()221222        if send.isMulti {223            VStack(alignment: .leading, spacing: 10) {224                Text(String(localized: "Quantité")).font(.spHeadline)225                TextField("1", text: $send.quantity).keyboardType(.numberPad).font(.system(size: 28, weight: .semibold)).monospacedDigit().focused($typing).accessibilityIdentifier("nft.send.quantity")226                Text(String(localized: "Unités détenues : \(item.quantity)")).font(.spFootnote).foregroundStyle(Theme.mute)227                if let p = send.quantityProblem {228                    Label(p == .aboveHeld ? String(localized: "Quantité supérieure à ce que ce portefeuille détient.") : String(localized: "Entre un nombre entier entre 1 et \(item.quantity)."), systemImage: "exclamationmark.triangle.fill")229                        .font(.spFootnote).foregroundStyle(Theme.danger).accessibilityIdentifier("nft.send.quantityProblem")230                }231            }.spCard()232        }233234        if let e = send.error { NFTErrorNotice(error: e).accessibilityIdentifier("nft.send.error") }235        Button { Task { await send.prepare(ctx.api) } } label: { HStack { if send.busy { ProgressView().tint(Theme.onPrimary) }; Text(send.busy ? String(localized: "Vérification on-chain et simulation…") : String(localized: "Préparer et vérifier")) } }236            .buttonStyle(.spPrimary).disabled(!canPrepare).accessibilityIdentifier("nft.send.prepare")237        Text(String(localized: "La détention, le standard et le destinataire sont relus sur la chaîne, puis le transfert est simulé, avant toute demande de clé d’accès. Rien n’est signé à cette étape."))238            .font(.spFootnote).foregroundStyle(Theme.mute)239    }240241    /** Text from a QR code or the clipboard: parsed and validated, used only to fill the destination. An amount in the code is ignored. */242    private func handleScan(_ raw: String, source: String) {243        switch ScannedPayment.parse(raw, networks: model.networks.value ?? [], current: item.chainId) {244        case .failure(let why): scanNotice = why245        case .success(let p):246            if let n = p.network, n != item.chainId {247                scanNotice = String(localized: "Ce code vise le réseau \(model.network(n)?.name ?? n), pas \(network?.name ?? item.chainId). Rien n’a été rempli."); return248            }249            send.to = p.address250            scanNotice = String(localized: "Adresse remplie depuis le \(source). Vérifie-la en entier : rien n’est envoyé automatiquement.")251        }252    }253254    // MARK: review (every figure is read from the verified intent)255256    @ViewBuilder private var review: some View {257        if let a = send.approval {258            let i = a.intent, r = a.review, evm = i.standard.isEVM259            Text(String(localized: "Envoi d’un NFT")).spEyebrow()260            Text(String(localized: "\(i.quantity) unité(s) — \(NFTText.standard(i.standard.rawValue))")).font(.system(size: 26, weight: .semibold)).tracking(-0.5).foregroundStyle(Theme.ink)261                .fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("nft.review.headline")262            VStack(alignment: .leading, spacing: 0) {263                FieldRow(label: String(localized: "Réseau"), value: (model.network(i.network)?.name ?? i.network) + " (\(i.chainRef))")264                Divider()265                FieldRow(label: String(localized: "Standard"), value: NFTText.standard(i.standard.rawValue))266                Divider()267                FieldRow(label: evm ? String(localized: "Contrat") : String(localized: "Mint / adresse de l’actif"), value: i.asset, mono: true, copyable: true).accessibilityIdentifier("nft.review.asset")268                if let t = i.tokenId { Divider(); FieldRow(label: String(localized: "Identifiant du jeton"), value: t, mono: true, copyable: true).accessibilityIdentifier("nft.review.tokenId") }269                Divider()270                FieldRow(label: String(localized: "Quantité"), value: i.quantity, mono: true).accessibilityIdentifier("nft.review.quantity")271                Divider()272                FieldRow(label: evm ? String(localized: "Contrat appelé") : String(localized: "Programme appelé"), value: i.program, mono: true, copyable: true)273                Divider()274                FieldRow(label: String(localized: "Appel"), value: i.standard.method)275                Divider()276                FieldRow(label: String(localized: "De (ce portefeuille)"), value: i.from, mono: true, copyable: true)277                Divider()278                FieldRow(label: String(localized: "Destinataire"), value: i.to, mono: true, copyable: true).accessibilityIdentifier("nft.review.to")279                Divider()280                FieldRow(label: String(localized: "Frais de réseau, plafond"), value: feeText(i.maxFee, intent: i, review: r)).accessibilityIdentifier("nft.review.maxFee")281                ForEach(Array(chainRows(i).enumerated()), id: \.offset) { _, row in Divider(); FieldRow(label: row.0, value: row.1, mono: row.2, copyable: row.2) }282            }.spCard(padding: 16)283284            if let r { serverReview(r, intent: i) }285            else { Notice(tone: .danger, title: String(localized: "Le serveur n’a pas fourni sa fiche de vérification"), message: String(localized: "Sans le verdict de simulation, l’app n’offre pas l’approbation.")) }286287            let warnings = Array(Set((r?.warnings ?? []) + (a.transfer.proposal.warnings ?? []))).sorted()288            ForEach(warnings, id: \.self) { w in let t = NFTText.transferWarning(w); Notice(tone: t.tone, title: t.title).accessibilityIdentifier("nft.review.warning") }289            Notice(tone: .danger, title: String(localized: "Un transfert de NFT est irréversible"), message: String(localized: "Personne ne peut l’annuler ni le récupérer. La clé d’accès signe exactement les identifiants ci-dessus."))290291            VStack(alignment: .leading, spacing: 0) {292                TimelineView(.periodic(from: .now, by: 1)) { c in293                    let left = Int(i.expiry.timeIntervalSince(c.date))294                    FieldRow(label: String(localized: "Fenêtre d’approbation"), value: left > 0 ? String(localized: "expire dans \(left) s") : String(localized: "expirée"), tone: left > 15 ? nil : .danger)295                }296                Divider()297                FieldRow(label: String(localized: "Empreinte de l’intention (défi signé par la clé d’accès)"), value: a.approval.digest.hex, mono: true, copyable: true).accessibilityIdentifier("nft.review.digest")298                Divider()299                FieldRow(label: String(localized: "Proposition"), value: i.proposalId, mono: true)300                Divider()301                FieldRow(label: String(localized: "Clé du signataire · politique · politique NFT"), value: "\(i.keyId) · v\(i.policyVersion) · v\(i.nftPolicyVersion)", mono: true)302            }.spCard(padding: 16)303            Label(String(localized: "L’app a recalculé cette empreinte à partir des champs affichés, vérifié qu’elle est le défi demandé à ta clé d’accès et que l’intention est bien l’envoi demandé. Le signataire isolé la revérifie avant de signer."), systemImage: "checkmark.shield.fill")304                .font(.spFootnote).foregroundStyle(Theme.mute)305            if a.replayed { Text(String(localized: "Cette préparation avait déjà été faite : la même proposition et le même défi ont été resservis.")).font(.spFootnote).foregroundStyle(Theme.mute) }306            if let c = r?.creatorMetadata { NFTCreatorNote(ctx: ctx, name: c.name, collection: c.collectionName, imageId: c.imageId) }307308            Toggle(isOn: $send.acknowledged) { Text(String(localized: "J’ai vérifié l’adresse du destinataire en entier.")).font(.spCallout.weight(.semibold)) }309                .padding(14).background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.Radius.control)).accessibilityIdentifier("nft.review.ack")310            if let e = send.error { NFTErrorNotice(error: e).accessibilityIdentifier("nft.send.error") }311            TimelineView(.periodic(from: .now, by: 1)) { c in312                let expired = i.expiry <= c.date313                VStack(spacing: 10) {314                    if expired {315                        Button { Task { await send.prepareAgain(ctx.api) } } label: { Label(String(localized: "Fenêtre expirée : préparer de nouveau"), systemImage: "arrow.clockwise") }316                            .buttonStyle(.spPrimary).disabled(send.busy || !model.canOperate).accessibilityIdentifier("nft.send.refresh")317                    } else {318                        Button { Task { await send.approve(ctx.api, passkeys: model.env.passkeys) } } label: { HStack { if send.busy { ProgressView().tint(Theme.onPrimary) } else { Image(systemName: "person.badge.key.fill") }; Text(String(localized: "Approuver avec la clé d’accès")) } }319                            .buttonStyle(.spPrimary).disabled(send.busy || !model.canOperate || !send.acknowledged || r == nil || r?.simulation.ok == false).accessibilityIdentifier("nft.send.approve")320                    }321                    Button(String(localized: "Refuser")) { Task { await send.reject(ctx.api) } }.buttonStyle(.spSecondary).disabled(send.busy).accessibilityIdentifier("nft.send.reject")322                }323            }324        }325    }326327    /** The fee ceiling of the intent in the network's coin; in base units when the app does not know that coin for certain. */328    private func feeText(_ units: String, intent i: NFTIntent, review r: NFTReview?) -> String {329        let native = model.network(i.network)?.native330        let decimals = native?.decimals ?? r?.fee.decimals, symbol = native?.symbol ?? r?.fee.symbol331        if let native, let r, native.decimals != r.fee.decimals { return units + " " + String(localized: "(unités de base)") }332        guard let decimals, let symbol, let u = try? BaseUnits(units) else { return units + " " + String(localized: "(unités de base)") }333        return Money.exact(u.formatted(decimals: decimals)) + " " + symbol334    }335336    /** The chain section of the intent, shown raw: nothing signed is hidden. */337    private func chainRows(_ i: NFTIntent) -> [(String, String, Bool)] {338        var rows: [(String, String, Bool)] = []339        if let e = i.evm {340            rows += [(String(localized: "Nonce"), String(e.nonce), true), (String(localized: "Limite de gaz"), e.gasLimit, true),341                     (String(localized: "Frais max par gaz (wei)"), e.maxFeePerGas, true), (String(localized: "Pourboire max par gaz (wei)"), e.maxPriorityFeePerGas, true)]342        }343        if let s = i.sol {344            rows += [(String(localized: "Blockhash récent"), s.recentBlockhash, true), (String(localized: "Dernière hauteur de bloc valide"), String(s.lastValidBlockHeight), true),345                     (String(localized: "Limite d’unités de calcul"), String(s.computeUnitLimit), true), (String(localized: "Prix de l’unité de calcul (micro-lamports)"), s.computeUnitPrice, true)]346            if let p = s.tokenProgram { rows.append((String(localized: "Programme de jetons"), p, true)) }347            if let c = s.createAta { rows.append((String(localized: "Crée le compte de jeton du destinataire"), NFTText.yesNo(c), false)) }348            if let x = s.ruleSet { rows.append((String(localized: "Jeu de règles"), x, true)) }349            if let x = s.collection { rows.append((String(localized: "Collection"), x, true)) }350        }351        return rows352    }353354    @ViewBuilder private func serverReview(_ r: NFTReview, intent i: NFTIntent) -> some View {355        let kind = NFTText.toKind(r.toKind)356        VStack(alignment: .leading, spacing: 10) {357            Text(String(localized: "Vérification et simulation du serveur")).font(.spHeadline).foregroundStyle(Theme.ink)358            if r.simulation.ok {359                Label(String(localized: "Simulation réussie"), systemImage: "checkmark.circle.fill").font(.spBody.weight(.semibold)).foregroundStyle(Theme.emerald).accessibilityIdentifier("nft.review.simulation")360            } else {361                Label(String(localized: "Simulation en échec : l’envoi n’est pas approuvable"), systemImage: "xmark.octagon.fill").font(.spBody.weight(.semibold)).foregroundStyle(Theme.danger).accessibilityIdentifier("nft.review.simulation")362            }363            Text(verbatim: r.simulation.detail + (r.simulation.used.map { " · " + String(localized: "consommé : \($0)") } ?? "")).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)364            ForEach(Array(r.simulation.changes.enumerated()), id: \.offset) { _, c in365                let t = NFTText.simulationChange(c)366                VStack(alignment: .leading, spacing: 2) {367                    Text(t.what).font(.spFootnote).foregroundStyle(Theme.mute)368                    Text(verbatim: "\(t.before) → \(t.after)").font(.system(size: 12.5, design: .monospaced)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)369                }370            }371            Divider()372            HStack { Text(String(localized: "Nature du destinataire")).font(.spFootnote).foregroundStyle(Theme.mute); Spacer(); Pill(text: kind.0, tone: kind.1) }373            FieldRow(label: String(localized: "Frais estimés"), value: "≈ " + feeText(r.fee.estimate, intent: i, review: r))374            if let rent = r.fee.rent, rent != "0" { FieldRow(label: String(localized: "Dépôt de loyer des comptes créés (pas un frais)"), value: feeText(rent, intent: i, review: r)) }375            Text(String(localized: "Relu sur \(r.verified.endpoints) point(s) d’accès concordant(s) : \(r.verified.standard) ; \(r.verified.ownership).")).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)376            if !r.accounts.isEmpty {377                Divider()378                Text(String(localized: "Comptes de l’instruction (\(r.accounts.count))")).font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.ink)379                ForEach(Array(r.accounts.enumerated()), id: \.offset) { _, acc in380                    FieldRow(label: "\(acc.role) (\(NFTText.accountDerivation(acc.derived)))", value: acc.address, mono: true, copyable: true)381                }382            }383        }.spCard(padding: 16)384    }385386    // MARK: tracking387388    @ViewBuilder private var tracking: some View {389        if let t = send.submitted {390            let i = send.approval?.intent391            VStack(alignment: .leading, spacing: 4) {392                Text(String(localized: "Envoi du NFT")).spEyebrow()393                Text(verbatim: (i?.asset ?? t.proposal.asset) + (i?.tokenId.map { " · #\($0)" } ?? "")).font(.spMono).foregroundStyle(Theme.ink).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)394                Text(String(localized: "Quantité : \(t.proposal.amount)")).font(.spFootnote).foregroundStyle(Theme.mute)395                if let to = t.proposal.to { Text(verbatim: "→ " + to).font(.spMono).foregroundStyle(Theme.mute).textSelection(.enabled).fixedSize(horizontal: false, vertical: true) }396            }397            NFTTransferTracker(transfer: t)398            Button(String(localized: "Terminer")) { dismiss() }.buttonStyle(.spSecondary).accessibilityIdentifier("nft.send.done")399                .task(id: t.id) {400                    while !Task.isCancelled {401                        if await send.refreshStatus(ctx.api) {402                            // the chain decided: the wallet's balances (fees) and the server's NFT inventory are re-read403                            ctx.revision += 1404                            await model.refreshAll()405                            break406                        }407                        try? await Task.sleep(for: .seconds(ctx.isFixture ? 1 : 4))408                    }409                }410        }411    }412}413414/** The state of an NFT transfer as the server reports it. Only `finalized` is a success. */415struct NFTTransferTracker: View {416    let transfer: NFTTransfer417    var body: some View {418        let p = transfer.proposal, s = transfer.state419        VStack(alignment: .leading, spacing: 14) {420            HStack(spacing: 10) {421                if s.isInFlight { ProgressView() } else { Image(systemName: s.symbol).font(.system(size: 22)).foregroundStyle(s.tone.color) }422                Text(s.label).font(.spHeadline).foregroundStyle(Theme.ink)423            }424            .accessibilityElement(children: .combine).accessibilityIdentifier("nft.tracker.state")425            if s == .finalized {426                Notice(tone: .ok, title: String(localized: "Confirmé à la finalité de la chaîne"), message: String(localized: "La galerie suit l’inventaire du serveur : la pièce en sort dès qu’il constate le transfert."))427            } else if s == .notBroadcast {428                Notice(tone: .warn, title: String(localized: "Signé mais NON diffusé"), message: String(localized: "La diffusion est désactivée sur ce serveur. Le NFT n’a pas bougé."))429            } else if s.isInFlight || s == .pendingApproval {430                Notice(tone: .info, title: String(localized: "Pas encore confirmé par le réseau"), message: String(localized: "Le NFT n’est considéré comme envoyé qu’à la finalité de la chaîne. Une transaction diffusée peut encore échouer ou être remplacée."))431            } else if s == .unknown {432                Notice(tone: .warn, title: String(localized: "État que cette version ne connaît pas"), message: String(localized: "L’app ne le traite ni comme un succès ni comme un échec."))433            }434            VStack(alignment: .leading, spacing: 0) {435                if let c = p.confirmations { FieldRow(label: String(localized: "Confirmations"), value: String(c)); Divider() }436                if let t = p.txid { FieldRow(label: String(localized: "Identifiant de transaction"), value: t, mono: true, copyable: true) }437                else { FieldRow(label: String(localized: "Identifiant de transaction"), value: String(localized: "pas encore de transaction")) }438                if let e = p.error { Divider(); FieldRow(label: String(localized: "Erreur"), value: e + (p.errorCode.map { " (\($0))" } ?? ""), tone: .danger) }439            }.spCard(padding: 16)440            if p.explorer != nil, s != .notBroadcast {441                NFTExternalLinkRow(title: String(localized: "Explorateur de blocs (lien construit par le serveur)"), raw: p.explorer, warning: String(localized: "L’explorateur s’ouvre dans le navigateur, hors de SP Wallet."))442            }443        }444    }445}446447/** What the creator declares: small, secondary, labelled unverified. Never the title of what is approved. */448struct NFTCreatorNote: View {449    let ctx: NFTContext450    let name: String?451    let collection: String?452    let imageId: String?453    var body: some View {454        HStack(spacing: 12) {455            NFTMediaImage(ctx: ctx, id: imageId, kind: "image").frame(width: 46, height: 46).clipShape(RoundedRectangle(cornerRadius: 9)).opacity(0.85)456            VStack(alignment: .leading, spacing: 2) {457                Text(String(localized: "Métadonnée du créateur, non vérifiée")).spEyebrow()458                Text(verbatim: (name ?? String(localized: "Nom non disponible")) + (collection.map { " · \($0)" } ?? "")).font(.spFootnote).foregroundStyle(Theme.mute).lineLimit(2)459            }460            Spacer(minLength: 0)461        }462        .padding(12)463        .overlay(RoundedRectangle(cornerRadius: Theme.Radius.control, style: .continuous).strokeBorder(Theme.hairline, style: StrokeStyle(lineWidth: 1, dash: [4, 3])))464        .accessibilityElement(children: .combine).accessibilityIdentifier("nft.creatorNote")465    }466}467
Files main
Menu

Theme