SPB Git

Repository Public

BridgeHomeView.swift 10.3 KB 167 lines swift

1// SP Wallet iOS2// File: Features/Bridge/BridgeHomeView.swift3// Description: Root of "Transférer entre réseaux": the operations in progress or resumable (so that leaving a screen never loses4//              one), then two tools — USDC between networks through Circle CCTP, and "Échange entre réseaux" (native THORChain5//              swaps and multi-step plans). A cross-network operation is shown as finished only when its destination is confirmed.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SwiftUI10import SPWalletCore1112enum BridgeLogic {13    /** A cross-network operation the owner can come back to. */14    struct Resumable: Identifiable, Equatable {15        let id: String16        let kind: String17        let network: String18        let amountDisplay: String19        let symbol: String20        let status: String21        let tone: Tone22        /** The owner has something to do (finish, sign a mint again, reclaim a deposit, approve or refuse). */23        let needsAttention: Bool24        let at: Date?25    }2627    private static func bridge(_ b: BridgeSection, pendingApproval: Bool) -> (String, Tone, Bool)? {28        if pendingApproval { return (String(localized: "Préparé, en attente d’approbation"), .warn, true) }29        if b.stage == .mintFailed || b.needsPasskey == true { return (BridgeText.stage(.mintFailed), .danger, true) }30        if b.isInTransit { return (BridgeText.stage(b.stage) + " → " + (b.toNetworkName ?? b.toNetwork), b.canFinish == true ? .warn : .info, b.canFinish == true) }31        if let s = b.sol?.reclaimState, b.sol?.role == "source", s != .done {32            return (String(localized: "Dépôt Solana : \(BridgeText.reclaim(s))"), b.sol?.canReclaim == true ? .warn : .neutral, b.sol?.canReclaim == true)33        }34        return nil35    }3637    private static func xswap(_ x: XSwapSection, pendingApproval: Bool) -> (String, Tone, Bool)? {38        if pendingApproval { return (String(localized: "Préparé, en attente d’approbation"), .warn, true) }39        guard x.done != true, !x.isFailed, x.stage != .review else { return nil }40        return (XSwapText.stage(x.stage), x.hold != nil ? .warn : .info, false)41    }4243    /**44     CCTP transfers and THORChain swaps that are not finished, from the pending proposals and the history. A transfer whose burn45     is final but whose mint is not confirmed IS listed: the source transaction says nothing about the destination.46     */47    static func resumable(pending: [Proposal], activity: [ActivityItem]) -> [Resumable] {48        var out: [Resumable] = [], seen = Set<String>()49        func add(id: String, network: String, amount: String, symbol: String, at: Date?, state: ProposalState?, bridgeJSON: JSONValue?, xswapJSON: JSONValue?) {50            guard !seen.contains(id) else { return }51            let waiting = state == .pendingApproval52            if let j = bridgeJSON, !j.isNull, let b = try? j.decode(BridgeSection.self), let (text, tone, attention) = bridge(b, pendingApproval: waiting) {53                seen.insert(id); out.append(Resumable(id: id, kind: "bridge", network: network, amountDisplay: amount, symbol: symbol, status: text, tone: tone, needsAttention: attention, at: at))54            } else if let j = xswapJSON, !j.isNull, let x = try? j.decode(XSwapSection.self), let (text, tone, attention) = xswap(x, pendingApproval: waiting) {55                seen.insert(id); out.append(Resumable(id: id, kind: "xswap", network: network, amountDisplay: amount, symbol: symbol, status: text, tone: tone, needsAttention: attention, at: at))56            }57        }58        for p in pending { add(id: p.id, network: p.network, amount: p.amountDisplay, symbol: p.symbol, at: p.createdAt, state: p.state, bridgeJSON: p.bridge, xswapJSON: p.xswap) }59        for a in activity where !a.isIncoming {60            add(id: a.id, network: a.network, amount: a.amountDisplay ?? a.amount, symbol: a.symbol, at: a.at, state: a.proposalState, bridgeJSON: a.bridge, xswapJSON: a.xswap)61        }62        return out63    }64}6566struct BridgeHomeView: View {67    enum Tool: String, CaseIterable, Identifiable { case usdc, cross; var id: String { rawValue } }68    @Environment(AppModel.self) private var model69    @Environment(\.horizontalSizeClass) private var sizeClass70    @State private var tool: Tool = .usdc71    @State private var tracking: OperationStart?72    @State private var openPlans: [PlanView] = []73    @State private var planSheet: PlanSheetItem?7475    var body: some View {76        ScrollView {77            VStack(alignment: .leading, spacing: Theme.Space.section) {78                FreshnessBanner()79                if !model.canOperate {80                    Notice(tone: .warn, title: String(localized: "Transferts indisponibles en lecture seule"), message: String(localized: "Un transfert entre réseaux exige une session ouverte, le serveur, le signataire isolé et ta clé d’accès."))81                        .accessibilityIdentifier("bridge.readonly")82                }83                inProgress84                Picker(String(localized: "Outil"), selection: $tool) {85                    Text(String(localized: "USDC (Circle CCTP)")).tag(Tool.usdc)86                    Text(String(localized: "Échange entre réseaux")).tag(Tool.cross)87                }88                .pickerStyle(.segmented).accessibilityIdentifier("bridge.tool")89                switch tool {90                case .usdc: CCTPBridgeView(regular: sizeClass == .regular)91                case .cross: CrossSwapView(regular: sizeClass == .regular, openPlan: { planSheet = PlanSheetItem(id: $0) })92                }93            }94            .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12)95            .frame(maxWidth: sizeClass == .regular ? 1100 : 620).frame(maxWidth: .infinity)96        }97        .scrollDismissesKeyboard(.immediately)98        .spPage()99        .navigationTitle(AppSection.bridge.title).navigationBarTitleDisplayMode(.inline)100        .task(id: model.canOperate) { await loadPlans() }101        #if DEBUG102        .task {103            // interface tests only: present each sheet of this section once, to prove its content resolves its environment104            switch ProcessInfo.processInfo.environment["SPWALLET_UITEST_BRIDGE_SHEET"] {105            case "tracking": tracking = .tracking(proposalId: "00000000-0000-4000-8000-000000000000")106            case "plan": planSheet = PlanSheetItem(id: "00000000-0000-4000-8000-000000000000")107            default: break108            }109        }110        #endif111        .sheet(item: $tracking, onDismiss: { Task { await model.refreshAll() } }) { OperationSheet(start: $0).wallet(model) }112        .sheet(item: $planSheet, onDismiss: { Task { await loadPlans(); await model.refreshAll() } }) { PlanSheet(planId: $0.id).wallet(model) }113    }114115    private func loadPlans() async {116        guard model.canOperate else { return }117        if let p = try? await PlanAPI(model.env.client).list(openOnly: true) { openPlans = p }118    }119120    @ViewBuilder private var inProgress: some View {121        let rows = BridgeLogic.resumable(pending: model.portfolio.value?.pending ?? [], activity: model.activity.value ?? [])122        if !rows.isEmpty || !openPlans.isEmpty {123            VStack(alignment: .leading, spacing: 4) {124                SectionHeader(title: String(localized: "En cours — à suivre ou à reprendre"))125                if model.activity.isCached || model.portfolio.isCached {126                    Text(String(localized: "D’après le dernier instantané synchronisé ; l’état réel peut avoir avancé.")).font(.spFootnote).foregroundStyle(Theme.warn)127                }128                ForEach(openPlans) { p in129                    Button { planSheet = PlanSheetItem(id: p.id) } label: {130                        resumeRow(icon: "list.number", title: String(localized: "Plan \(p.from.symbol) → \(p.to.symbol) · étape \(min(p.current + 1, p.steps)) sur \(p.steps)"),131                                  status: PlanText.next(p.next), tone: p.state == .paused ? .warn : .info, attention: p.next == .prepare || p.next == .approve || p.state == .paused,132                                  amount: Money.brief(p.amountInDisplay) + " " + p.from.symbol)133                    }134                    .buttonStyle(.plain).disabled(!model.canOperate).accessibilityIdentifier("bridge.plan.row")135                    Divider()136                }137                ForEach(rows) { r in138                    Button { tracking = .tracking(proposalId: r.id) } label: {139                        resumeRow(icon: r.kind == "bridge" ? "point.topleft.down.to.point.bottomright.curvepath" : "arrow.triangle.swap",140                                  title: r.kind == "bridge" ? String(localized: "Transfert USDC depuis \(model.network(r.network)?.name ?? r.network)") : String(localized: "Échange natif depuis \(model.network(r.network)?.name ?? r.network)"),141                                  status: r.status, tone: r.tone, attention: r.needsAttention, amount: Money.brief(r.amountDisplay) + " " + r.symbol)142                    }143                    .buttonStyle(.plain).disabled(!model.canOperate).accessibilityIdentifier("bridge.resume.row")144                    if r.id != rows.last?.id { Divider() }145                }146            }147            .spCard().accessibilityIdentifier("bridge.inProgress")148        }149    }150151    private func resumeRow(icon: String, title: String, status: String, tone: Tone, attention: Bool, amount: String) -> some View {152        HStack(spacing: 12) {153            Circle().fill(Theme.elev).frame(width: 40, height: 40).overlay(Image(systemName: icon).font(.system(size: 15, weight: .semibold)).foregroundStyle(Theme.ink))154            VStack(alignment: .leading, spacing: 3) {155                Text(title).font(.system(size: 15, weight: .semibold)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)156                Label(status, systemImage: attention ? "hand.point.up.left.fill" : tone.icon).font(.system(size: 12.5, weight: .medium)).foregroundStyle(tone.color).fixedSize(horizontal: false, vertical: true)157                Masked(text: amount).font(.spFootnote).monospacedDigit().foregroundStyle(Theme.mute)158            }159            Spacer(minLength: 6)160            Image(systemName: "chevron.right").font(.system(size: 13, weight: .semibold)).foregroundStyle(Theme.mute)161        }162        .frame(minHeight: 58).contentShape(Rectangle())163    }164}165166struct PlanSheetItem: Identifiable { let id: String }167
Files main
Menu

Theme