Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/Wallet/ChainTokensSection.swift8// Module : Wallet9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0512// 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/// The tokens of one chain: the wallet's list, the tokens found on the account and not accepted yet (kept apart,47/// never valued), and the form that adds a token by its contract or mint address.48struct ChainTokensSection: View {49 let chain: ChainSnapshot50 let snapshot: WalletSnapshot51 let hidden: Bool5253 @Environment(WalletStore.self) private var wallet54 @State private var adding = false55 @State private var error: String?56 @State private var busy: String?57 @State private var showsAllDetected = false58 /// The tokens hidden on this chain, as the service lists them (they are in no snapshot).59 @State private var hiddenTokens: [HiddenToken] = []6061 var body: some View {62 VStack(alignment: .leading, spacing: QSpace.l) {63 listed64 detected65 hiddenList66 InlineError(message: error)67 Button { adding = true } label: {68 Label("Add a token by address", systemImage: "plus").frame(maxWidth: .infinity)69 }70 .buttonStyle(.qSecondary)71 .disabled(snapshot.profile.coldMode)72 if snapshot.profile.coldMode {73 WalletNoteLine(text: "Cold mode is on: a token cannot be read on chain, so none can be added.")74 }75 }76 .sheet(isPresented: $adding) {77 WalletAddTokenSheet(chain: chain.chain).presentedPrivacyCover().qSheetChrome(detents: QDetents.full)78 }79 .qHaptic(trigger: error) { $0 == nil ? nil : .failed }80 .task(id: HiddenKey(chain: chain.id, hidden: snapshot.profile.hiddenTokens)) {81 hiddenTokens = await wallet.service?.hiddenTokens(chain: chain.id) ?? []82 }83 #if DEBUG84 .task(id: DebugNavigator.shared.serial) {85 adding = false86 if DebugLaunch.screen == "chain-add-token" {87 try? await Task.sleep(for: .milliseconds(600))88 adding = true89 }90 }91 #endif92 }9394 struct HiddenKey: Equatable {95 let chain: ChainID96 let hidden: [String]97 }9899 /// The hidden tokens, each with the action that shows it again. A token hidden from the detected list is known100 /// by its address only: no name is invented for it.101 @ViewBuilder var hiddenList: some View {102 if !hiddenTokens.isEmpty {103 QListSection("Hidden tokens", footnote: "A hidden token is neither read nor shown; it stays on chain. One that was hidden before being accepted comes back among the detected tokens at the next synchronization.") {104 ForEach(hiddenTokens) { item in105 HStack(spacing: QSpace.m) {106 VStack(alignment: .leading, spacing: 3) {107 Text(item.token.map { $0.symbol == $0.name ? $0.symbol : "\($0.symbol) · \($0.name)" } ?? "Unlisted \(chain.chain.tokenStandardName)")108 .font(QFont.headline).foregroundStyle(QColor.textPrimary).lineLimit(1)109 Text(MiddleTruncation.truncate(item.address, head: 8, tail: 6)).font(QFont.mono).foregroundStyle(QColor.textSecondary)110 .accessibilityLabel("Address \(item.address)")111 }112 Spacer(minLength: QSpace.s)113 if busy == item.id { ProgressView().controlSize(.small) }114 Button("Show again") { show(item) }115 .buttonStyle(.bordered).tint(QColor.violet)116 .accessibilityLabel("Show \(item.token?.symbol ?? "this token") again")117 .disabled(busy != nil)118 }119 .padding(.vertical, QSpace.m)120 }121 }122 }123 }124125 func show(_ item: HiddenToken) {126 guard busy == nil else { return }127 busy = item.id128 error = nil129 Task {130 defer { busy = nil }131 do {132 try await wallet.run { try await $0.showHiddenToken(item) }133 await wallet.refresh()134 } catch {135 self.error = WalletStore.message(for: error)136 }137 }138 }139140 @ViewBuilder var listed: some View {141 let tokens = chain.tokens142 if chain.data.value == nil {143 QListSection("Tokens") { ForEach(0..<2, id: \.self) { _ in QSkeletonRow() } }144 } else if tokens.isEmpty {145 VStack(alignment: .leading, spacing: QSpace.s) {146 QEyebrow("Tokens")147 WalletNoteLine(text: "No \(chain.chain.tokenStandardName) is in this wallet's list for \(chain.chain.displayName).", systemImage: "tray")148 }149 } else {150 QListSection("Tokens") {151 ForEach(tokens) { held in152 NavigationLink(value: WalletRoute.token(chain: chain.id, address: held.token.address)) { row(held) }153 .buttonStyle(.qRow)154 }155 }156 }157 }158159 @ViewBuilder160 func row(_ held: ChainTokenBalance) -> some View {161 switch held.balance {162 case .available(let balance):163 AssetRow(asset: .token(symbol: held.token.symbol, network: chain.network), name: held.token.name,164 note: held.warning ?? held.token.standard.rawValue + (held.token.isCustom ? " · added by you" : ""),165 units: balance.description, decimals: held.token.decimals, symbol: held.token.symbol,166 fiat: WalletChainFormat.fiat(snapshot.tokenLine(held.token), currency: snapshot.currency),167 change: balance.isZero ? nil : WalletChainFormat.change(snapshot.quote(of: held.token)), hidden: hidden)168 case .unavailable(let reason):169 unread(held, reason)170 case .notLoaded:171 unread(held, "Not read yet")172 }173 }174175 /// A token whose balance could not be read: named, with the reason, and no figure.176 func unread(_ held: ChainTokenBalance, _ reason: String) -> some View {177 HStack(spacing: QSpace.m) {178 TokenGlyph(symbol: held.token.symbol, network: chain.network)179 VStack(alignment: .leading, spacing: 2) {180 Text(held.token.name).font(QFont.body).foregroundStyle(QColor.textPrimary)181 Text(reason).font(QFont.caption).foregroundStyle(QColor.warning).fixedSize(horizontal: false, vertical: true)182 }183 Spacer(minLength: QSpace.s)184 Text("—").font(QFont.amount).foregroundStyle(QColor.textTertiary)185 }186 .frame(minHeight: QMetric.rowMinHeight)187 .accessibilityElement(children: .ignore)188 .accessibilityLabel("\(held.token.name): balance not known. \(reason)")189 }190191 @ViewBuilder var detected: some View {192 let tokens = chain.detectedTokens193 if !tokens.isEmpty {194 QListSection("Detected, not accepted",195 footnote: "Found on this account by the synchronization. Anyone can send a token to an address, and a token can copy the name of another: check the address before accepting. Detected tokens are not counted in the total.") {196 ForEach(showsAllDetected ? tokens : Array(tokens.prefix(3))) { held in197 VStack(alignment: .leading, spacing: QSpace.m) {198 HStack(spacing: QSpace.m) {199 TokenGlyph(symbol: held.token.symbol, network: chain.network)200 VStack(alignment: .leading, spacing: 2) {201 Text(held.token.name.isEmpty ? held.token.symbol : held.token.name).font(QFont.body).foregroundStyle(QColor.textPrimary).lineLimit(2)202 Text(MiddleTruncation.truncate(held.token.address, head: 8, tail: 6)).font(QFont.mono).foregroundStyle(QColor.textSecondary)203 }204 Spacer(minLength: 0)205 }206 if let warning = held.warning { WalletNoteLine(text: warning, systemImage: "exclamationmark.triangle", tone: QColor.warning) }207 ViewThatFits(in: .horizontal) {208 HStack(spacing: QSpace.m) {209 detectedActions(held)210 Spacer(minLength: QSpace.s)211 detectedAmount(held)212 }213 VStack(alignment: .leading, spacing: QSpace.s) {214 detectedAmount(held)215 HStack(spacing: QSpace.m) { detectedActions(held) }216 }217 }218 }219 .padding(.vertical, QSpace.m)220 }221 if tokens.count > 3 {222 Button { showsAllDetected.toggle() } label: {223 HStack {224 Text(showsAllDetected ? "Show fewer" : "Show all \(tokens.count)").font(QFont.callout.weight(.medium)).foregroundStyle(QColor.violet)225 Spacer()226 Image(systemName: "chevron.down").font(.footnote.weight(.semibold)).foregroundStyle(QColor.textTertiary)227 .rotationEffect(.degrees(showsAllDetected ? 180 : 0)).accessibilityHidden(true)228 }229 .frame(minHeight: QMetric.minTap + 6)230 .contentShape(Rectangle())231 }232 .buttonStyle(.qRow)233 }234 }235 .qAnimation(value: showsAllDetected)236 }237 }238239 @ViewBuilder240 func detectedActions(_ held: ChainTokenBalance) -> some View {241 Button("Accept") { act(held.token, id: held.id) { token in { try await $0.acceptDetectedToken(token) } } }242 .buttonStyle(.bordered).tint(QColor.violet)243 .accessibilityLabel("Accept \(held.token.symbol)")244 .disabled(busy != nil)245 Button("Hide") { act(held.token, id: held.id) { token in { try await $0.setTokenHidden(true, token: token) } } }246 .buttonStyle(.bordered).tint(QColor.textSecondary)247 .accessibilityLabel("Hide \(held.token.symbol)")248 .disabled(busy != nil)249 if busy == held.id { ProgressView().controlSize(.small) }250 }251252 @ViewBuilder253 func detectedAmount(_ held: ChainTokenBalance) -> some View {254 if let balance = held.balance.value {255 Text(hidden ? "••••" : WalletChainFormat.short(balance, decimals: held.token.decimals) + " " + String(held.token.symbol.prefix(10)))256 .font(QFont.figure).foregroundStyle(QColor.textSecondary).lineLimit(1)257 .privacySensitive()258 .accessibilityLabel(hidden ? "Amount hidden" : "Balance \(WalletChainFormat.short(balance, decimals: held.token.decimals)) \(held.token.symbol)")259 }260 }261262 func act(_ token: ChainToken, id: String, _ operation: (ChainToken) -> @Sendable (WalletService) async throws -> Void) {263 guard busy == nil else { return }264 busy = id265 error = nil266 let work = operation(token)267 Task {268 defer { busy = nil }269 do {270 try await wallet.run(work)271 await wallet.refresh()272 } catch {273 self.error = WalletStore.message(for: error)274 }275 }276 }277}278279/// Adds a token by contract or mint address. The token is read on chain by the service; what it claims (symbol,280/// name) is shown as a claim.281struct WalletAddTokenSheet: View {282 let chain: ChainDescriptor283284 @Environment(WalletStore.self) private var wallet285 @Environment(\.dismiss) private var dismiss286 @State private var address = ""287 @State private var label = ""288 @State private var scanning = false289 @State private var busy = false290 @State private var error: String?291 @State private var added: ChainToken?292293 var trimmed: String { address.trimmingCharacters(in: .whitespacesAndNewlines) }294295 var body: some View {296 QSheetScaffold("Add a token", subtitle: chain.qNetwork.fullName, onClose: { dismiss() }) {297 if let added {298 ResultView(status: .sent, title: "\(added.symbol) added", message: "\(added.name) is now in this wallet's list for \(chain.displayName).",299 identifierLabel: chain.tokenAddressNoun.capitalized, identifier: added.address, network: chain.qNetwork)300 if let note = added.note { WalletNoteLine(text: note, systemImage: "exclamationmark.triangle", tone: QColor.warning) }301 } else {302 NetworkBadge(chain.qNetwork)303 RecipientCard(text: $address, title: chain.tokenAddressNoun.capitalized, placeholder: placeholder, validity: trimmed.isEmpty ? .empty : .valid(nil),304 network: chain.qNetwork, onScan: { scanning = true })305 if chain.family == .solana {306 VStack(alignment: .leading, spacing: QSpace.s) {307 QEyebrow("Your name for it")308 TextField("For example: USDC", text: $label)309 .textInputAutocapitalization(.characters)310 .autocorrectionDisabled()311 .padding(14)312 .background(QColor.surface, in: RoundedRectangle(cornerRadius: QMetric.radiusSmall))313 .overlay(RoundedRectangle(cornerRadius: QMetric.radiusSmall).strokeBorder(QColor.stroke))314 Text("A Solana mint carries no symbol on chain: this label is yours and proves nothing about the token.")315 .font(QFont.caption).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)316 }317 }318 InlineError(message: error)319 VStack(alignment: .leading, spacing: QSpace.s) {320 ForEach(rules, id: \.self) { WalletNoteLine(text: $0) }321 }322 }323 } footer: {324 if added != nil {325 Button("Done") { dismiss() }.buttonStyle(.qPrimary)326 } else {327 LoadingButton("Read and add the token", loadingTitle: "Reading the token on chain", state: busy ? .loading : .idle) { add() }328 .disabled(trimmed.isEmpty || busy)329 }330 }331 .sheet(isPresented: $scanning) {332 VStack(spacing: QSpace.l) {333 SheetHeader("Scan the token address") { scanning = false }334 QRScannerView { text in335 address = text.trimmingCharacters(in: .whitespacesAndNewlines)336 scanning = false337 }338 }339 .padding(QMetric.screenPadding)340 .qScreen()341 .presentedPrivacyCover()342 }343 .qHaptic(.sent, trigger: added)344 }345346 var placeholder: String {347 switch chain.family {348 case .evm: return "0x…"349 case .solana: return "Mint address"350 case .tron: return "T…"351 case .utxo: return ""352 }353 }354355 var rules: [String] {356 var out: [String]357 switch chain.family {358 case .evm:359 out = ["The contract must hold code on \(chain.displayName) and answer as an ERC-20 token. The same token has another address on every EVM network."]360 case .solana:361 out = ["The mint must exist on \(chain.displayName). Tokens of the Token and Token-2022 programs are read; some Token-2022 extensions cannot be transferred by QYVORA and are flagged."]362 case .tron:363 out = ["The contract must exist on \(chain.displayName) and answer as a TRC-20 token."]364 case .utxo:365 out = []366 }367 out.append("Symbol and name are what the token claims about itself. Take the address from the issuer, never from a message.")368 if !chain.isTest { out.append("On this unaudited build a token without a known price cannot be sent on a main network.") }369 return out370 }371372 func add() {373 guard !busy else { return }374 busy = true375 error = nil376 let id = chain.id, text = trimmed377 let name = label.trimmingCharacters(in: .whitespaces)378 Task {379 defer { busy = false }380 do {381 added = try await wallet.run { try await $0.addCustomToken(chain: id, address: text, label: name.isEmpty ? nil : name) }382 await wallet.refresh()383 } catch {384 self.error = WalletStore.message(for: error)385 }386 }387 }388}389390/// One token: balance, where it lives, its contract or mint in full, price, activity, and the actions on it.391struct WalletTokenDetailScreen: View {392 let chainID: ChainID393 let address: String394395 @Environment(WalletStore.self) private var wallet396 @Environment(\.dismiss) private var dismiss397 @HideAmounts private var hideAmounts398 @State private var sheet: WalletSheet?399 @State private var error: String?400 @State private var busy = false401 @State private var confirmRemoval = false402403 var chain: ChainSnapshot? { wallet.snapshot?.activeChain(chainID) }404 var held: ChainTokenBalance? { chain.flatMap { c in c.tokens.first { $0.token.address == address } ?? c.detectedTokens.first { $0.token.address == address } } }405 var isDetected: Bool { chain?.detectedTokens.contains { $0.token.address == address } ?? false }406407 var body: some View {408 Group {409 if let snapshot = wallet.snapshot, let chain, let held {410 content(held, chain, snapshot)411 } else {412 UnavailableDataView(reason: "This token is no longer in the list of this network (hidden, removed, or the network is not active).", title: "Token not listed")413 .padding(QSpace.xl).frame(maxWidth: .infinity, maxHeight: .infinity)414 }415 }416 .qScreen()417 .navigationTitle(held?.token.symbol ?? "Token")418 .navigationBarTitleDisplayMode(.inline)419 .walletSheet($sheet)420 .confirmationDialog("Remove this token from the list?", isPresented: $confirmRemoval, titleVisibility: .visible) {421 Button("Remove", role: .destructive) { change { token in { try await $0.removeCustomToken(token) } } }422 } message: {423 Text("The tokens stay on chain at your address. Add the token again by its address to see them.")424 }425 }426427 func content(_ held: ChainTokenBalance, _ chain: ChainSnapshot, _ snapshot: WalletSnapshot) -> some View {428 let token = held.token429 let items = ActivityItem.of(chain).filter { item in430 switch item.entry.kind {431 case .token(let contract, _, _, _): return contract.caseInsensitiveCompare(token.address) == .orderedSame432 case .approval(let contract): return contract.caseInsensitiveCompare(token.address) == .orderedSame433 default: return false434 }435 }436 return ScrollView {437 VStack(alignment: .leading, spacing: QMetric.sectionSpacing) {438 VStack(alignment: .leading, spacing: QSpace.xl) {439 VStack(alignment: .leading, spacing: QSpace.m) {440 HStack(spacing: QSpace.m) {441 TokenGlyph(symbol: token.symbol, network: chain.network, size: .large)442 VStack(alignment: .leading, spacing: QSpace.xs) {443 Text(token.name).font(QFont.headline).foregroundStyle(QColor.textPrimary).fixedSize(horizontal: false, vertical: true)444 NetworkBadge(chain.network, style: .plain)445 }446 }447 switch held.balance {448 case .available(let balance):449 AmountText(units: balance, decimals: token.decimals, symbol: token.symbol,450 fiat: WalletChainFormat.fiat(snapshot.tokenLine(token), currency: snapshot.currency), style: .balance, hidden: hideAmounts)451 .privacySensitive()452 case .unavailable(let reason):453 UnavailableDataView(reason: reason, title: "Balance not read", compact: true)454 case .notLoaded:455 Text("—").font(QFont.display).foregroundStyle(QColor.textTertiary).accessibilityLabel("Balance not known")456 }457 if isDetected {458 WarningBanner(.warning, title: "Detected, not accepted",459 message: "This token was found on your account and is not in your list. It is not counted in the total. Accept it only if you know where it comes from.",460 actionTitle: "Accept", action: { change(leaves: false) { token in { try await $0.acceptDetectedToken(token) } } })461 }462 if let warning = held.warning { WarningBanner(.warning, message: warning) }463 if let note = token.note { WalletNoteLine(text: note) }464 }465 QuickActionBar([466 .send(isEnabled: held.balance.value.map { !$0.isZero } ?? false) { sheet = .send(SendPrefill(chain: chain.id, tokenAddress: token.address)) },467 .receive(isEnabled: chain.receive != nil) { sheet = .receive(chain.id) },468 ])469 }470 ReviewSection("Token", footnote: "A token is identified by its network and this address only. The same symbol exists on other networks, and other tokens can copy it.") {471 ReviewRow("Network", value: chain.network.fullName)472 ReviewRow("Standard", value: token.standard.rawValue)473 ReviewRow(chain.chain.tokenAddressNoun.capitalized, value: token.address, emphasis: .address, copyValue: token.address)474 ReviewRow("Decimals", value: String(token.decimals))475 ReviewRow("Listed", value: isDetected ? "Not yet (detected)" : (token.isCustom ? "Added by you" : "Built-in list"))476 }477 if let url = chain.chain.explorerAddressURL(token.address) {478 WalletExplorerLink(title: "View the token on a block explorer", url: url)479 }480 PriceChartSection(assetID: token.priceID, currency: snapshot.currency, isTestNetwork: chain.chain.isTest)481 activity(items, chain)482 VStack(alignment: .leading, spacing: QSpace.m) {483 InlineError(message: error)484 Button { change { token in { try await $0.setTokenHidden(true, token: token) } } } label: {485 Label("Hide this token", systemImage: "eye.slash").frame(maxWidth: .infinity)486 }487 .buttonStyle(.qSecondary)488 .disabled(busy)489 if token.isCustom, !isDetected {490 Button(role: .destructive) { confirmRemoval = true } label: {491 Label("Remove from the list", systemImage: "trash").frame(maxWidth: .infinity)492 }493 .buttonStyle(.qSecondary)494 .disabled(busy)495 }496 WalletNoteLine(text: "A hidden token is neither read nor shown; it stays on chain. The network's screen lists the hidden tokens and shows them again.")497 }498 }499 .padding(.horizontal, QMetric.screenPadding)500 .padding(.top, QSpace.l)501 .padding(.bottom, QSpace.xl)502 .frame(maxWidth: 640)503 .frame(maxWidth: .infinity)504 }505 .refreshable { await wallet.synchronize(chains: [chain.id]) }506 }507508 @ViewBuilder509 func activity(_ items: [ActivityItem], _ chain: ChainSnapshot) -> some View {510 if let reason = chain.data.value?.historyUnavailableReason {511 VStack(alignment: .leading, spacing: QSpace.s) {512 QEyebrow("Activity")513 UnavailableDataView(reason: reason, title: "History is not available on \(chain.chain.displayName)", compact: true)514 }515 } else if items.isEmpty {516 VStack(alignment: .leading, spacing: QSpace.s) {517 QEyebrow("Activity")518 WalletNoteLine(text: "No movement of this token appears in the history that was read.", systemImage: "tray")519 }520 } else {521 QListSection("Activity") {522 ForEach(items.prefix(20)) { item in523 NavigationLink(value: item.route) { ActivityRow(item: item, hidden: hideAmounts, showsDate: true) }.buttonStyle(.qRow)524 }525 }526 }527 }528529 /// Runs a change of the token list; the screen closes when the token leaves the list.530 func change(leaves: Bool = true, _ operation: (ChainToken) -> @Sendable (WalletService) async throws -> Void) {531 guard !busy, let token = held?.token else { return }532 busy = true533 error = nil534 let work = operation(token)535 Task {536 defer { busy = false }537 do {538 try await wallet.run(work)539 await wallet.refresh()540 if leaves { dismiss() }541 } catch {542 self.error = WalletStore.message(for: error)543 }544 }545 }546}547