SPB Git

Repository Public

ActivityItem.swift 12.3 KB 297 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Activity/ActivityItem.swift8// Module           : Activity9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0513//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI42import QyvoraCore43import QyvoraWallet44import QyvoraUI4546/// One line of history of any chain, with what the list and the detail screen say about it. It only rewords the47/// service's `ActivityEntry`: nothing is guessed (an entry the wallet cannot decode is shown as such).48struct ActivityItem: Identifiable, Equatable {49    let entry: ActivityEntry50    let chain: ChainDescriptor5152    var id: String { chain.id.rawValue + "|" + entry.id }53    var route: WalletRoute { .transaction(chain: chain.id, id: entry.id) }54    var network: QNetwork { chain.qNetwork }5556    /// Newest first across the active chains: pending entries, then by block time; entries without a time last.57    static func all(_ snapshot: WalletSnapshot) -> [ActivityItem] {58        sorted(snapshot.chains.flatMap { of($0) })59    }6061    static func of(_ chain: ChainSnapshot) -> [ActivityItem] {62        (chain.data.value?.history.value ?? []).map { ActivityItem(entry: $0, chain: chain.chain) }63    }6465    static func sorted(_ items: [ActivityItem]) -> [ActivityItem] {66        items.enumerated().sorted { a, b in67            let x = a.element.sortDate, y = b.element.sortDate68            return x != y ? x > y : a.offset < b.offset69        }.map(\.element)70    }7172    var sortDate: Date { entry.time ?? (isPending ? .distantFuture : .distantPast) }7374    var isPending: Bool { entry.status == .pending }75    var isFailed: Bool { entry.status == .failed }7677    var isTransfer: Bool {78        switch entry.kind {79        case .native, .token: return entry.direction != .none80        default: return false81        }82    }8384    /// What happened, in two or three words.85    var title: String {86        switch entry.kind {87        case .approval: return "Token approval"88        case .contract(let method): return method.map { "Contract call · \($0)" } ?? "Contract call"89        case .unknown: return "Not decoded"90        case .native, .token:91            switch entry.direction {92            case .received: return "Received"93            case .sent: return "Sent"94            case .selfTransfer: return "Internal transfer"95            case .none: return isFailed ? "Failed transaction" : "No balance change"96            }97        }98    }99100    /// The other side when it is known, otherwise what the entry is about.101    var subtitle: String? {102        if let counterparty = entry.counterparty, !counterparty.isEmpty {103            let short = MiddleTruncation.truncate(counterparty, head: 6, tail: 4)104            switch entry.direction {105            case .received: return "From \(short)"106            case .sent: return "To \(short)"107            default: return short108            }109        }110        switch entry.kind {111        case .approval(let token): return "Token \(MiddleTruncation.truncate(token, head: 6, tail: 4))"112        case .unknown(let description): return description113        case .token(_, _, _, let verified) where !verified: return "Token details from the indexer, not verified"114        default: return nil115        }116    }117118    var symbol: String { entry.symbol ?? (entry.isToken ? "units" : chain.nativeSymbol) }119120    /// False for a token whose decimals are unknown: the amount is then raw base units and is labelled so.121    var amountIsScaled: Bool { entry.decimals != nil }122123    var sign: AmountText.Sign {124        guard isTransfer, !isFailed else { return .none }125        switch entry.direction {126        case .received: return .incoming127        case .sent: return .outgoing128        default: return .none129        }130    }131132    /// True when the row shows an amount (a movement of a coin or a token).133    var showsAmount: Bool { isTransfer && !(entry.amount.isZero && entry.direction == .selfTransfer) }134135    /// The status in the chain's own words: confirmations on UTXO and EVM chains, finality on Solana and TRON.136    var statusText: String {137        switch entry.status {138        case .pending: return "Pending"139        case .failed: return "Failed"140        case .finalized:141            switch chain.family {142            case .solana: return "Finalized"143            case .tron: return "Irreversible"144            case .evm, .utxo: return "Final"145            }146        case .confirmed(let confirmations):147            guard let confirmations else { return "Confirmed" }148            return confirmations == 1 ? "1 confirmation" : "\(confirmations) confirmations"149        }150    }151152    /// One sentence on what the status means on this chain.153    var statusExplanation: String {154        switch entry.status {155        case .pending:156            return chain.family == .utxo ? "Seen by the network, not in a block yet. It can still be replaced or dropped."157                                         : "Seen by the network, not in a block yet."158        case .failed: return "Included in a block and failed: the fee was paid and nothing else moved."159        case .confirmed(let confirmations):160            switch chain.family {161            case .utxo: return "In a block" + (confirmations.map { ", \($0) deep" } ?? "") + ". Each further block makes a reorganisation less likely; there is no moment of absolute finality."162            case .evm: return "In a block, below the depth this wallet treats as final on \(chain.displayName)."163            case .solana: return "Confirmed by the cluster, not finalized yet."164            case .tron: return "In a block that is not irreversible yet."165            }166        case .finalized:167            switch chain.family {168            case .utxo: return "Deep enough that a reorganisation is not expected."169            case .evm: return "Deeper than the depth this wallet treats as final on \(chain.displayName)."170            case .solana: return "Finalized by the cluster: it cannot be rolled back."171            case .tron: return "In an irreversible block."172            }173        }174    }175176    var statusTone: QBadge.Tone {177        switch entry.status {178        case .pending: return .warning179        case .failed: return .negative180        case .confirmed: return .neutral181        case .finalized: return .positive182        }183    }184185    var statusImage: String {186        switch entry.status {187        case .pending: return "clock"188        case .failed: return "xmark"189        case .confirmed: return "checkmark"190        case .finalized: return "checkmark.seal"191        }192    }193194    var directionImage: String {195        switch entry.kind {196        case .approval: return "checkmark.shield"197        case .contract: return "doc.text"198        case .unknown: return "questionmark"199        case .native, .token:200            switch entry.direction {201            case .received: return "arrow.down.left"202            case .sent: return "arrow.up.right"203            case .selfTransfer: return "arrow.triangle.2.circlepath"204            case .none: return "minus"205            }206        }207    }208209    var spoken: String {210        var parts = [title, network.spokenName]211        if showsAmount { parts.append(WalletChainFormat.amount(entry.amount, decimals: entry.decimals ?? 0, symbol: symbol, maxFractionDigits: 8)) }212        if let subtitle { parts.append(subtitle) }213        parts.append(statusText)214        if let time = entry.time { parts.append(RelativeTime.spoken(for: time)) }215        return parts.joined(separator: ", ")216    }217}218219/// One row of history: the glyph of the chain (or of the token, with its network sub-badge) carrying a direction220/// mark, what happened and with whom, the amount, and the status or the time.221struct ActivityRow: View {222    let item: ActivityItem223    let hidden: Bool224    /// True where the rows are not grouped by day: the date is shown with the time.225    var showsDate = false226    @Environment(\.dynamicTypeSize) private var typeSize227228    var body: some View {229        Group {230            if typeSize.isAccessibilitySize {231                VStack(alignment: .leading, spacing: QSpace.s) {232                    HStack(spacing: QSpace.m) { glyph; titles }233                    trailing(alignment: .leading)234                }235            } else {236                HStack(spacing: QSpace.m) {237                    glyph238                    titles239                    Spacer(minLength: QSpace.s)240                    trailing(alignment: .trailing)241                }242            }243        }244        .padding(.vertical, QSpace.m)245        .frame(minHeight: QMetric.rowMinHeight)246        .contentShape(Rectangle())247        .accessibilityElement(children: .ignore)248        .accessibilityLabel(hidden ? [item.title, item.network.spokenName, item.statusText, "amount hidden"].joined(separator: ", ") : item.spoken)249    }250251    var glyph: some View {252        ZStack(alignment: .bottomLeading) {253            if case .token(_, let symbol, _, _) = item.entry.kind, let symbol {254                TokenGlyph(symbol: symbol, network: item.network)255            } else {256                ChainGlyph(item.network)257            }258            Image(systemName: item.directionImage)259                .font(.system(size: 9, weight: .bold))260                .foregroundStyle(QColor.textPrimary)261                .frame(width: 18, height: 18)262                .background(Circle().fill(QColor.surfaceRaised))263                .overlay(Circle().strokeBorder(QColor.stroke, lineWidth: 1))264                .offset(x: -4, y: 4)265                .accessibilityHidden(true)266        }267    }268269    var titles: some View {270        VStack(alignment: .leading, spacing: 2) {271            Text(item.title).font(QFont.body).foregroundStyle(QColor.textPrimary).lineLimit(typeSize.isAccessibilitySize ? 3 : 1)272            Text(item.subtitle ?? item.network.fullName)273                .font(QFont.caption).foregroundStyle(QColor.textSecondary).lineLimit(typeSize.isAccessibilitySize ? 3 : 1)274                .privacySensitive(item.entry.counterparty != nil)275        }276    }277278    func trailing(alignment: HorizontalAlignment) -> some View {279        VStack(alignment: alignment, spacing: 3) {280            if item.showsAmount {281                AmountText(units: item.entry.amount, decimals: item.entry.decimals ?? 0, symbol: item.amountIsScaled ? item.symbol : "base units",282                           maxFractionDigits: AssetPrecision.fractionDigits(units: item.entry.amount.description, decimals: item.entry.decimals ?? 0),283                           style: .row, sign: item.sign, hidden: hidden)284                    .privacySensitive()285            }286            if item.isPending || item.isFailed {287                QBadge(item.statusText, systemImage: item.statusImage, tone: item.statusTone)288            } else if let time = item.entry.time {289                Text(showsDate ? time.formatted(.dateTime.day().month(.abbreviated).hour().minute()) : time.formatted(date: .omitted, time: .shortened))290                    .font(QFont.caption).foregroundStyle(QColor.textSecondary)291            } else {292                Text(item.statusText).font(QFont.caption).foregroundStyle(QColor.textSecondary)293            }294        }295    }296}297
Files main
Menu

Theme