Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/EndpointsEditorView.swift8// Module : Sources9// 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// =============================================================================40import SwiftUI41import QyvoraCore42import QyvoraNetworking43import QyvoraSolana44import QyvoraTron45import QyvoraWallet46import QyvoraUI4748// MARK: - Keys4950/// The endpoint lists of a network, from the registry's descriptors.51enum SecEndpointKeys {52 /// The endpoint lists of one network, in the order they are shown. The key of the network in its table is the53 /// registry's (`ChainDescriptor.endpointKey`).54 static func lists(for chain: ChainDescriptor) -> [EndpointListID] {55 let kinds: [EndpointListID.Kind]56 switch chain.family {57 case .utxo: kinds = [.esplora, .blockbook, .bitcore]58 case .evm: kinds = [.ethereumRPC, .ethereumIndexer]59 case .solana: kinds = [.solanaRPC]60 case .tron: kinds = [.tronFullNode, .tronHistory]61 }62 return kinds.map { EndpointListID(kind: $0, network: chain.endpointKey, chain: chain.id) }63 }6465 /// A main chain with its test networks, main network first.66 static func networks(of main: ChainDescriptor) -> [ChainDescriptor] {67 [main] + main.testCounterparts.compactMap { ChainRegistry.descriptor($0) }68 }69}7071// MARK: - One list7273/// One editable list of `ChainEndpoints`.74struct EndpointListID: Hashable, Sendable, Identifiable {75 enum Kind: String, Hashable, Sendable {76 case esplora, blockbook, bitcore, ethereumRPC, ethereumIndexer, solanaRPC, tronFullNode, tronHistory, priceAPI, priceCheckAPI77 }7879 let kind: Kind80 /// The key of the network in its table (raw value of the module's network type); empty for the price API.81 let network: String82 /// The registry identifier of the network; nil for the price API.83 let chain: ChainID?8485 var id: String { "\(kind.rawValue)|\(network)" }8687 static let price = EndpointListID(kind: .priceAPI, network: "", chain: nil)88 /// The second, independent price source: it cross-checks the first when a dollar limit is verified (QYV-SVC-087).89 static let priceCheck = EndpointListID(kind: .priceCheckAPI, network: "", chain: nil)9091 private var isMarket: Bool { kind == .priceAPI || kind == .priceCheckAPI }9293 var descriptor: ChainDescriptor? { chain.flatMap(ChainRegistry.descriptor) }94 var isMainnet: Bool { descriptor.map { !$0.isTest } ?? false }95 var networkName: String { descriptor?.displayName ?? (kind == .priceCheckAPI ? "Second price source" : "Price API") }9697 /// The role of the list, without the network ("Esplora indexer", "JSON-RPC").98 var roleName: String {99 switch kind {100 case .esplora: return "Esplora indexer"101 case .blockbook: return "Blockbook indexer"102 case .bitcore: return "Bitcore indexer"103 case .ethereumRPC: return "JSON-RPC"104 case .ethereumIndexer: return "History indexer"105 case .solanaRPC: return "JSON-RPC"106 case .tronFullNode: return "Full nodes"107 case .tronHistory: return "History index"108 case .priceAPI: return "Price API"109 case .priceCheckAPI: return "Second price source"110 }111 }112113 var title: String { isMarket ? roleName : "\(networkName) · \(roleName)" }114115 var protocolName: String {116 switch kind {117 case .esplora: return "Esplora-compatible REST API (mempool.space, Blockstream)"118 case .blockbook: return "Blockbook REST API v2 (a base ending in /api/v2)"119 case .bitcore: return "Bitcore REST API (a base ending in /api/<COIN>/<network>)"120 case .ethereumRPC: return "Ethereum JSON-RPC"121 case .ethereumIndexer: return "Blockscout-compatible API"122 case .solanaRPC: return "Solana JSON-RPC"123 case .tronFullNode: return "java-tron full-node HTTP API (/wallet, /walletsolidity)"124 case .tronHistory: return "TronGrid-compatible index (/v1/accounts)"125 case .priceAPI: return "CoinGecko-compatible API"126 case .priceCheckAPI: return "Kraken-compatible public market API (a base answering /Ticker?pair=…)"127 }128 }129130 /// What each list is used for, in a few words.131 var purpose: String {132 switch kind {133 case .esplora, .blockbook, .bitcore: return "Addresses, coins, history, fee estimates and broadcast."134 case .ethereumRPC: return "Balance, nonce, gas, contract calls and broadcast."135 case .ethereumIndexer: return "Transaction history and token discovery. Optional."136 case .solanaRPC: return "Balance, token accounts, history, simulation and broadcast."137 case .tronFullNode: return "Account, resources, transaction building and broadcast."138 case .tronHistory: return "Transaction and TRC-20 history. Optional."139 case .priceAPI: return "Prices and price history. Optional."140 case .priceCheckAPI: return "Cross-checks the price API when a limit in dollars is verified on a main network. It must be another host."141 }142 }143144 /// The price API is a single URL; the other lists are ordered fallbacks.145 var limit: Int? { isMarket ? 1 : nil }146147 /// True when the wallet can work on the network without this list.148 var isOptional: Bool { kind == .ethereumIndexer || kind == .tronHistory || isMarket }149150 /// What the operator of the endpoint can observe. Kept factual: requests carry no cookie and no identifier of the151 /// application, but the operator always sees the IP address and the content of the queries.152 var disclosure: String {153 switch kind {154 case .esplora, .blockbook, .bitcore:155 return "The operator sees your IP address and every address and transaction the app asks about, so it can tell that these addresses belong to one wallet. It also sees the transactions you broadcast. It never receives keys."156 case .ethereumRPC:157 return "The operator sees your IP address, the account whose balance and nonce are requested, the contracts queried and the transactions you broadcast. It never receives keys."158 case .ethereumIndexer:159 return "The operator sees your IP address and the account whose history and tokens are requested. It never receives keys."160 case .solanaRPC:161 return "The operator sees your IP address, the account whose balance, token accounts and history are requested, and the transactions you simulate and broadcast. It never receives keys."162 case .tronFullNode:163 return "The operator sees your IP address, the account whose balance and resources are requested and the transactions you build and broadcast. A TronGrid host also receives your API key when one is set, which links your requests together. It never receives wallet keys."164 case .tronHistory:165 return "The operator sees your IP address and the account whose history is requested. A TronGrid host also receives your API key when one is set, which links your requests together. It never receives wallet keys."166 case .priceAPI:167 return "The operator sees your IP address and which assets and currency are requested. It receives no address and no balance."168 case .priceCheckAPI:169 return "The operator sees your IP address and the one asset whose price is asked, at the moment a payment limited in dollars is prepared or signed on a main network. It receives no address, no amount and no balance."170 }171 }172173 var emptyConsequence: String {174 switch kind {175 case .esplora, .blockbook, .bitcore:176 return "No endpoint of this protocol. The network works as long as one of its indexer lists has an endpoint; with none, balances and history cannot be loaded and nothing can be broadcast."177 case .ethereumRPC, .solanaRPC: return "Without an endpoint, balances of this network cannot be loaded and nothing can be broadcast."178 case .ethereumIndexer: return "Without an indexer, history and token discovery are disabled for this network. Balances still work through the RPC."179 case .tronFullNode: return "Without a full node, balances of this network cannot be loaded and nothing can be broadcast."180 case .tronHistory: return "Without a history index, history is disabled for this network. Balances still work through the full nodes."181 case .priceAPI: return "Without a price API, market data is disabled: amounts are shown without fiat values and without charts."182 case .priceCheckAPI:183 return "Without a second price source, a limit in dollars cannot be verified: on a main network this build refuses payments of every coin and token whose limit is in dollars, except dollar-pegged tokens."184 }185 }186187 func urls(in endpoints: ChainEndpoints) -> [String] {188 switch kind {189 case .esplora: return endpoints.core.esplora[network] ?? []190 case .blockbook: return endpoints.core.blockbook[network] ?? []191 case .bitcore: return endpoints.core.bitcore[network] ?? []192 case .ethereumRPC: return endpoints.core.ethereumRPC[network] ?? []193 case .ethereumIndexer: return endpoints.core.ethereumIndexer[network] ?? []194 case .solanaRPC: return endpoints.solana.rpc[network] ?? []195 case .tronFullNode: return endpoints.tron.fullNodes[network] ?? []196 case .tronHistory: return endpoints.tron.history[network] ?? []197 case .priceAPI: return endpoints.core.priceAPI.isEmpty ? [] : [endpoints.core.priceAPI]198 case .priceCheckAPI: return endpoints.core.priceCheckAPI.isEmpty ? [] : [endpoints.core.priceCheckAPI]199 }200 }201202 func set(_ urls: [String], in endpoints: inout ChainEndpoints) {203 switch kind {204 case .esplora: endpoints.core.esplora[network] = urls205 case .blockbook: endpoints.core.blockbook[network] = urls206 case .bitcore: endpoints.core.bitcore[network] = urls207 case .ethereumRPC: endpoints.core.ethereumRPC[network] = urls208 case .ethereumIndexer: endpoints.core.ethereumIndexer[network] = urls209 case .solanaRPC: endpoints.solana.rpc[network] = urls210 case .tronFullNode: endpoints.tron.fullNodes[network] = urls211 case .tronHistory: endpoints.tron.history[network] = urls212 case .priceAPI: endpoints.core.priceAPI = urls.first ?? ""213 case .priceCheckAPI: endpoints.core.priceCheckAPI = urls.first ?? ""214 }215 }216217 /// "mempool.space + 1", "None", or nil for an empty optional protocol list that has no default either.218 func summary(in endpoints: ChainEndpoints) -> String {219 let urls = urls(in: endpoints)220 guard let first = urls.first else { return isOptional ? "Disabled" : "None" }221 return EndpointRules.host(first) + (urls.count > 1 ? " + \(urls.count - 1)" : "")222 }223}224225extension EndpointListID {226 /// A list named by its kind and network key alone (launch arguments, deep links): the registry identifier is found227 /// from the tables.228 init(kind: Kind, network: String) {229 let chain = ChainRegistry.all.first { descriptor in230 SecEndpointKeys.lists(for: descriptor).contains { $0.kind == kind && $0.network == network }231 }?.id232 self.init(kind: kind, network: network, chain: kind == .priceAPI || kind == .priceCheckAPI ? nil : chain)233 }234}235236/// One list opened directly (`SettingsRoute.endpointList`), with its own copy of the configuration.237struct SecEndpointListStandalone: View {238 let id: EndpointListID239 @Environment(WalletStore.self) private var store240 @State private var model = SecEndpointsModel()241242 var body: some View {243 SecEndpointListEditor(id: id, model: model, level: 0)244 .task { await model.load(store) }245 }246}247248/// Rules of the endpoint editor (pure).249enum EndpointRules {250 enum Problem: Equatable {251 case empty252 case notAcceptable253 case duplicate254255 var message: String? {256 switch self {257 case .empty: return nil258 case .notAcceptable:259 return "Use an https:// address. Plain http:// is accepted only for localhost, .local and .onion hosts and for private network addresses (10.x, 172.16–31.x, 192.168.x, 127.x). Addresses with a user name or password are refused."260 case .duplicate: return "This endpoint is already in the list."261 }262 }263 }264265 /// Trims spaces and trailing slashes so that the same server is not listed twice.266 static func normalize(_ text: String) -> String {267 var s = text.trimmingCharacters(in: .whitespacesAndNewlines)268 while s.hasSuffix("/") { s.removeLast() }269 return s270 }271272 static func problem(_ text: String, existing: [String], replacing original: String?) -> Problem? {273 let candidate = normalize(text)274 if candidate.isEmpty { return .empty }275 if !EndpointConfiguration.isAcceptable(candidate) { return .notAcceptable }276 let others = existing.filter { $0 != original }.map { normalize($0).lowercased() }277 if others.contains(candidate.lowercased()) { return .duplicate }278 return nil279 }280281 static func host(_ url: String) -> String { URL(string: url)?.host ?? url }282283 /// True when a network cannot work with the given configuration: no acceptable endpoint in any of its required lists.284 static func isUnserved(_ chain: ChainDescriptor, in endpoints: ChainEndpoints) -> Bool {285 let lists = SecEndpointKeys.lists(for: chain).filter { !$0.isOptional }286 func usable(_ list: EndpointListID) -> Bool { list.urls(in: endpoints).contains(where: EndpointConfiguration.isAcceptable) }287 // UTXO: any one indexer protocol is enough; elsewhere there is a single required list288 return !lists.contains(where: usable)289 }290}291292// MARK: - Model293294/// The endpoint configuration being edited: the service's copy, saved through the service on every change.295/// With a full wallet the service wants a credential verified in the last two minutes (QYV-APP-002): when it says so,296/// the screen on top shows the re-authentication sheet and the save is repeated after it.297@MainActor298@Observable299final class SecEndpointsModel {300 private(set) var endpoints: ChainEndpoints?301 private(set) var saveError: String?302 private(set) var isSaving = false303 /// The change waiting for a credential, with the screen (navigation depth) that asked for it.304 private(set) var awaitingAuthentication: (endpoints: ChainEndpoints?, level: Int)?305 private(set) var saves = 0306307 var needsAuthenticationLevel: Int? { awaitingAuthentication?.level }308309 func load(_ store: WalletStore) async {310 guard let service = store.service else { return }311 endpoints = await service.chainEndpoints()312 }313314 /// Saves `new` (nil restores the built-in endpoints of every chain).315 func save(_ new: ChainEndpoints?, store: WalletStore, level: Int, promptOnDemand: Bool = true) {316 let previous = endpoints317 endpoints = new ?? .default318 saveError = nil319 isSaving = true320 Task {321 do {322 try await store.run { service in323 if let new { try await service.setChainEndpoints(new) } else { try await service.resetEndpoints() }324 }325 await store.refresh()326 saves += 1327 } catch WalletError.authenticationRequired where promptOnDemand {328 endpoints = previous329 // a sheet of the editor that made the change may still be closing330 try? await Task.sleep(for: .milliseconds(700))331 awaitingAuthentication = (new, level)332 } catch {333 saveError = SecurityError.text(error)334 endpoints = previous335 }336 isSaving = false337 }338 }339340 func update(_ list: EndpointListID, urls: [String], store: WalletStore, level: Int) {341 guard var next = endpoints else { return }342 list.set(urls, in: &next)343 save(next, store: store, level: level)344 }345346 func authenticationSucceeded(store: WalletStore, level: Int) {347 guard let pending = awaitingAuthentication else { return }348 awaitingAuthentication = nil349 save(pending.endpoints, store: store, level: level, promptOnDemand: false)350 }351352 func authenticationDismissed() { awaitingAuthentication = nil }353}354355/// Presents the re-authentication sheet on the screen that asked for a save.356private struct SecEndpointsAuthentication: ViewModifier {357 let model: SecEndpointsModel358 let level: Int359 @Environment(WalletStore.self) private var store360 @State private var presented = false361362 func body(content: Content) -> some View {363 content364 .requiresReauthentication(isPresented: $presented, reason: "Change the network endpoints") {365 model.authenticationSucceeded(store: store, level: level)366 }367 .onChange(of: model.needsAuthenticationLevel) { _, new in368 if new == level { presented = true }369 }370 .onChange(of: presented) { _, shown in371 // closed without a credential: the change is dropped, the stored configuration stays372 if !shown { Task { try? await Task.sleep(for: .milliseconds(400)); model.authenticationDismissed() } }373 }374 .qHaptic(.selection, trigger: model.saves)375 }376}377378// MARK: - Overview379380/// Endpoints of every chain: one row per chain, the price API, the TronGrid key and the reset. Self-contained: it381/// reads and saves through the wallet service (`chainEndpoints`, `setChainEndpoints`, `resetEndpoints`).382struct EndpointsEditorView: View {383 @Environment(WalletStore.self) private var store384 @State private var model = SecEndpointsModel()385 @State private var openChain: ChainID?386 @State private var openList: EndpointListID?387 @State private var confirmReset = false388 @State private var showTronKey = false389390 var body: some View {391 SecurityScroll {392 VStack(alignment: .leading, spacing: QSpace.s) {393 Explanation("QYVORA has no server. To read balances and broadcast transactions it queries the endpoints below in the order shown: the first is preferred, the others serve as fallbacks or cross-checks.")394 Explanation("Requests carry no cookie, no account and no identifier. The operator of an endpoint still sees your IP address and what is asked. Pointing the app to your own node removes that third party.")395 }396 if let saveError = model.saveError {397 WarningBanner(.critical, title: "Not saved", message: saveError)398 }399 if let endpoints = model.endpoints {400 let enabled = store.snapshot?.profile.enabledChains ?? ChainRegistry.defaultEnabled401 ForEach(ChainRegistry.groups) { group in402 QListSection(group.title) {403 ForEach(group.chains) { main in404 chainRow(main, endpoints, enabled: enabled.contains(main.id))405 }406 }407 .id("endpoints-\(group.id)")408 }409 QListSection("Market data", footnote: "The price API gives prices and price history. The second source is asked only when a limit in dollars is verified on a main network: the two must agree within \(Int(MainnetPolicy.priceAgreementTolerance * 100)) %, and the higher price is used.") {410 SecActionRow(title: "Price API", subtitle: EndpointListID.price.summary(in: endpoints), systemImage: "chart.line.uptrend.xyaxis") {411 openList = .price412 }413 SecActionRow(title: "Second price source", subtitle: EndpointListID.priceCheck.summary(in: endpoints), systemImage: "checkmark.shield") {414 openList = .priceCheck415 }416 }417 .id("price")418 tronKeySection.id("tron-key")419 QListSection(footnote: (endpoints == .default ? "The default endpoints are in use." : "The configuration differs from the defaults.")420 + " Changes are saved in the wallet profile and take effect at the next request; the chain served by an endpoint is checked again before it is used.") {421 SecActionRow(title: "Reset all endpoints to defaults", systemImage: "arrow.counterclockwise",422 tint: endpoints == .default ? QColor.textTertiary : QColor.negative, chevron: false) { confirmReset = true }423 .disabled(endpoints == .default)424 }425 .id("reset")426 } else {427 SecSkeletonSection(title: ChainRegistry.groups.first?.title, rows: 4)428 SecSkeletonSection(rows: 3)429 }430 }431 .navigationTitle("Network endpoints")432 .navigationBarTitleDisplayMode(.inline)433 .task { await model.load(store) }434 .navigationDestination(item: $openChain) { id in435 if let main = ChainRegistry.descriptor(id) { SecEndpointsChainView(main: main, model: model) }436 }437 .navigationDestination(item: $openList) { SecEndpointListEditor(id: $0, model: model, level: 1) }438 .sheet(isPresented: $showTronKey) { SecTronKeySheet().qSheetChrome(detents: QDetents.half) }439 .confirmationDialog("Reset all endpoints?", isPresented: $confirmReset, titleVisibility: .visible) {440 Button("Reset to defaults", role: .destructive) { model.save(nil, store: store, level: 0) }441 Button("Cancel", role: .cancel) {}442 } message: {443 Text("Every list of every chain returns to the public endpoints shipped with QYVORA. Your own endpoints are removed.")444 }445 .modifier(SecEndpointsAuthentication(model: model, level: 0))446 #if DEBUG447 .task {448 switch SecurityDebug.action {449 case "endpoints-chain": openChain = ChainID(SecurityDebug.defaults.string(forKey: "QYSecEndpointChain") ?? "bitcoin")450 case "endpoints-list": openList = SecEndpointKeys.lists(for: ChainRegistry.descriptor(.bitcoinSignet) ?? ChainRegistry.all[0]).first451 case "endpoints-tron-key": showTronKey = true452 default: break453 }454 }455 #endif456 }457458 private func chainRow(_ main: ChainDescriptor, _ endpoints: ChainEndpoints, enabled: Bool) -> some View {459 let networks = SecEndpointKeys.networks(of: main)460 let lists = networks.flatMap(SecEndpointKeys.lists)461 let custom = lists.contains { $0.urls(in: endpoints) != $0.urls(in: .default) }462 let detail = [networks.count == 1 ? "1 network" : "\(networks.count) networks", custom ? "customised" : "defaults", enabled ? nil : "chain not enabled"]463 .compactMap { $0 }.joined(separator: " · ")464 return Button { openChain = main.id } label: {465 HStack(spacing: QSpace.m) {466 ChainGlyph(main.qNetwork)467 VStack(alignment: .leading, spacing: 3) {468 Text(main.displayName).font(QFont.headline).foregroundStyle(QColor.textPrimary)469 Text(detail).font(QFont.caption).foregroundStyle(QColor.textSecondary)470 }471 .fixedSize(horizontal: false, vertical: true)472 Spacer(minLength: QSpace.s)473 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(QColor.textTertiary).accessibilityHidden(true)474 }475 .padding(.vertical, QSpace.s)476 .frame(minHeight: QMetric.rowMinHeight)477 }478 .buttonStyle(.qRow)479 .accessibilityElement(children: .combine)480 .accessibilityLabel("\(main.displayName), \(detail)")481 }482483 private var tronKeySection: some View {484 let profile = store.snapshot?.profile485 let hasKey = profile?.hasTronAPIKey == true486 let watchOnly = profile?.kind == .watchOnly487 return QListSection("TRON access", footnote: watchOnly488 ? "A watch-only wallet has no vault to keep an API key in: TronGrid is used without a key."489 : "Optional. TronGrid limits requests without a key. The key is stored in the vault, sent to TronGrid hosts over https only, and never shown again after it is saved.") {490 SecActionRow(title: "TronGrid API key", subtitle: hasKey ? "A key is stored in the vault" : "Not set: keyless access", systemImage: "key.horizontal",491 trailing: hasKey ? "Set" : nil) { showTronKey = true }492 .disabled(watchOnly)493 }494 }495}496497// MARK: - One chain498499/// The endpoint lists of one chain: its main network and its test networks.500struct SecEndpointsChainView: View {501 let main: ChainDescriptor502 let model: SecEndpointsModel503 @Environment(WalletStore.self) private var store504 @State private var openList: EndpointListID?505506 var body: some View {507 SecurityScroll {508 if let saveError = model.saveError {509 WarningBanner(.critical, title: "Not saved", message: saveError)510 }511 if let endpoints = model.endpoints {512 ForEach(SecEndpointKeys.networks(of: main)) { network in513 networkSection(network, endpoints)514 }515 }516 }517 .navigationTitle(main.displayName)518 .navigationBarTitleDisplayMode(.inline)519 .navigationDestination(item: $openList) { SecEndpointListEditor(id: $0, model: model, level: 2) }520 .modifier(SecEndpointsAuthentication(model: model, level: 1))521 }522523 private func isActive(_ network: ChainDescriptor) -> Bool {524 store.snapshot?.chain(network.id) != nil525 }526527 private func footnote(_ network: ChainDescriptor, _ endpoints: ChainEndpoints) -> String? {528 if EndpointRules.isUnserved(network, in: endpoints) {529 return network.capabilities.historyAvailable || network.family != .utxo530 ? "No usable endpoint: this network cannot be read and nothing can be broadcast on it."531 : "No keyless public indexer is known for this network. It works only with an endpoint of your own."532 }533 if !network.isTest, !MainnetPolicy.mainnetEnabled { return MainnetWording.endpointNote }534 return nil535 }536537 private func networkSection(_ network: ChainDescriptor, _ endpoints: ChainEndpoints) -> some View {538 QListSection(footnote: footnote(network, endpoints), separatorInset: QMetric.padding) {539 SecChainHeader(network: network.qNetwork, detail: isActive(network) ? "In use now" : (network.isTest ? "Test network" : "Main network"))540 ForEach(SecEndpointKeys.lists(for: network)) { list in541 let urls = list.urls(in: endpoints)542 let invalid = urls.contains { !EndpointConfiguration.isAcceptable($0) }543 SecActionRow(title: list.roleName, subtitle: list.summary(in: endpoints),544 systemImage: invalid ? "exclamationmark.triangle" : nil, tint: QColor.warning,545 trailing: urls.isEmpty ? nil : (urls == list.urls(in: .default) ? "Default" : "Custom")) { openList = list }546 }547 }548 .id(network.id.rawValue)549 }550}551552// MARK: - One list553554/// Editor of one list: add, edit, remove, reorder, validate, reset.555struct SecEndpointListEditor: View {556 let id: EndpointListID557 let model: SecEndpointsModel558 /// Navigation depth of this screen, for the re-authentication sheet.559 let level: Int560 @Environment(WalletStore.self) private var store561 @State private var editing: Draft?562 @State private var confirmReset = false563564 struct Draft: Identifiable {565 let id = UUID()566 /// The URL being replaced; nil for a new endpoint.567 let original: String?568 }569570 private var urls: [String] { model.endpoints.map { id.urls(in: $0) } ?? [] }571 private var defaults: [String] { id.urls(in: .default) }572 private var canAdd: Bool { id.limit.map { urls.count < $0 } ?? true }573574 private func commit(_ updated: [String]) { model.update(id, urls: updated, store: store, level: level) }575576 var body: some View {577 SecurityScroll {578 QListSection("What this endpoint learns", footnote: id.protocolName, separatorInset: QMetric.padding) {579 SecTextRow(text: id.disclosure, tone: .info)580 }581 if id.isMainnet, !MainnetPolicy.mainnetEnabled {582 WarningBanner(.info, message: MainnetWording.endpointNote)583 }584 if let saveError = model.saveError {585 WarningBanner(.critical, title: "Not saved", message: saveError)586 }587 QListSection(id.limit == 1 ? "Endpoint" : "Endpoints, in order of use", footnote: listFootnote, separatorInset: QMetric.padding) {588 if urls.isEmpty {589 SecTextRow(text: id.emptyConsequence, systemImage: id.isOptional ? "minus.circle" : "exclamationmark.triangle", tone: id.isOptional ? .neutral : .warning)590 }591 ForEach(Array(urls.enumerated()), id: \.element) { index, url in592 endpointRow(index: index, url: url)593 }594 if canAdd {595 Button { editing = Draft(original: nil) } label: {596 Label(id.limit == 1 ? "Set endpoint" : "Add endpoint", systemImage: "plus")597 .font(QFont.headline)598 .foregroundStyle(QColor.violet)599 .padding(.vertical, QSpace.m)600 .frame(minHeight: QMetric.rowMinHeight)601 }602 .buttonStyle(.qRow)603 }604 }605 .qAnimation(value: urls)606 .id("list")607 QListSection(footnote: defaults.isEmpty ? "This list has no default endpoint." : "Defaults: " + defaults.map(EndpointRules.host).joined(separator: ", ")) {608 SecActionRow(title: "Reset this list to defaults", systemImage: "arrow.counterclockwise",609 tint: urls == defaults ? QColor.textTertiary : QColor.violet, chevron: false) { confirmReset = true }610 .disabled(urls == defaults)611 }612 }613 .navigationTitle(id.title)614 .navigationBarTitleDisplayMode(.inline)615 .sheet(item: $editing) { draft in616 EndpointEditSheet(listTitle: id.title, original: draft.original, existing: urls) { value in617 var updated = urls618 if let original = draft.original, let i = updated.firstIndex(of: original) {619 updated[i] = value620 } else {621 updated.append(value)622 }623 commit(updated)624 }625 .qSheetChrome(detents: QDetents.half)626 }627 .confirmationDialog("Reset this list?", isPresented: $confirmReset, titleVisibility: .visible) {628 Button("Reset to defaults", role: .destructive) { commit(defaults) }629 Button("Cancel", role: .cancel) {}630 }631 .modifier(SecEndpointsAuthentication(model: model, level: level))632 #if DEBUG633 .task { if SecurityDebug.sheet == "endpoint-add" { editing = Draft(original: nil) } }634 #endif635 }636637 private var listFootnote: String? {638 if urls.count > 1 { return "The first endpoint is tried first. Use the menu of a row to edit it, move it or remove it." }639 if urls.count == 1, id.limit == nil { return "With a single endpoint there is no fallback if it does not answer. " + singleEndpointMeaning }640 return nil641 }642643 /// What one endpoint alone decides, by kind: nothing cross-checks its answers.644 private var singleEndpointMeaning: String {645 switch id.kind {646 case .solanaRPC:647 return "Its answers are not cross-checked: it alone decides the balance shown, whether a broadcast happened and whether a transaction is declared expired. A second endpoint of another operator is recommended."648 case .tronFullNode:649 return "Its answers are not cross-checked: the reference block of a payment, the balance, the resources and the decimals of a token added by its address are its word alone. A second node of another operator is recommended."650 case .esplora, .blockbook, .bitcore:651 return "When it is the only indexer source of the network, balances, history and confirmations are its word alone; sources of different protocols are compared with each other."652 case .ethereumRPC:653 return "The nonce and the chain identity are compared between endpoints when there are several."654 case .ethereumIndexer, .tronHistory, .priceAPI, .priceCheckAPI:655 return ""656 }657 }658659 private func move(_ index: Int, to target: Int) {660 var updated = urls661 guard updated.indices.contains(index), updated.indices.contains(target) else { return }662 updated.insert(updated.remove(at: index), at: target)663 commit(updated)664 }665666 private func endpointRow(index: Int, url: String) -> some View {667 let acceptable = EndpointConfiguration.isAcceptable(url)668 let isLocal = url.lowercased().hasPrefix("http://")669 return HStack(alignment: .center, spacing: QSpace.m) {670 Text("\(index + 1)")671 .font(Font.system(.footnote, design: .monospaced).weight(.semibold))672 .foregroundStyle(QColor.textTertiary)673 .frame(minWidth: 16)674 .accessibilityHidden(true)675 VStack(alignment: .leading, spacing: 4) {676 Text(EndpointRules.host(url)).font(QFont.headline).foregroundStyle(QColor.textPrimary).lineLimit(1).truncationMode(.middle)677 Text(SecurityFormat.breakingLongTokens(url, longerThan: 12)).font(QFont.mono).foregroundStyle(QColor.textSecondary)678 .fixedSize(horizontal: false, vertical: true)679 HStack(spacing: 6) {680 if !acceptable {681 QBadge("Not accepted, ignored", systemImage: "exclamationmark.triangle", tone: .warning)682 } else {683 if id.limit == nil {684 QBadge(index == 0 ? "Primary" : "Fallback", systemImage: index == 0 ? "1.circle" : "arrow.turn.down.right", tone: .neutral)685 }686 if isLocal { QBadge("Local, unencrypted", systemImage: "house", tone: .neutral) }687 }688 }689 }690 Spacer(minLength: QSpace.xs)691 Menu {692 Button { editing = Draft(original: url) } label: { Label("Edit", systemImage: "pencil") }693 if index > 0 {694 Button { move(index, to: 0) } label: { Label("Make primary", systemImage: "arrow.up.to.line") }695 Button { move(index, to: index - 1) } label: { Label("Move up", systemImage: "arrow.up") }696 }697 if index < urls.count - 1 {698 Button { move(index, to: index + 1) } label: { Label("Move down", systemImage: "arrow.down") }699 }700 Button(role: .destructive) { commit(urls.filter { $0 != url }) } label: { Label("Remove", systemImage: "trash") }701 } label: {702 Image(systemName: "ellipsis.circle")703 .font(.title3)704 .foregroundStyle(QColor.violet)705 .frame(minWidth: QMetric.minTap, minHeight: QMetric.minTap)706 .contentShape(Rectangle())707 }708 .accessibilityLabel("Actions for endpoint \(index + 1)")709 }710 .padding(.vertical, QSpace.m)711 .accessibilityElement(children: .contain)712 .accessibilityLabel("Endpoint \(index + 1): \(url)\(acceptable ? "" : ", not accepted")")713 }714}715716/// Sheet that adds or edits one URL with live validation.717struct EndpointEditSheet: View {718 let listTitle: String719 let original: String?720 let existing: [String]721 let onSave: (String) -> Void722 @State private var text: String723 @FocusState private var focused: Bool724 @Environment(\.dismiss) private var dismiss725726 init(listTitle: String, original: String?, existing: [String], onSave: @escaping (String) -> Void) {727 self.listTitle = listTitle728 self.original = original729 self.existing = existing730 self.onSave = onSave731 _text = State(initialValue: original ?? "")732 }733734 var problem: EndpointRules.Problem? { EndpointRules.problem(text, existing: existing, replacing: original) }735736 var body: some View {737 QSheetScaffold(original == nil ? "Add endpoint" : "Edit endpoint", subtitle: listTitle, onClose: { dismiss() }) {738 VStack(alignment: .leading, spacing: QSpace.s) {739 TextField("https://", text: $text, axis: .vertical)740 .font(QFont.mono)741 .foregroundStyle(QColor.textPrimary)742 .lineLimit(1...4)743 .keyboardType(.URL)744 .textInputAutocapitalization(.never)745 .autocorrectionDisabled()746 .focused($focused)747 .padding(14)748 .frame(minHeight: QMetric.controlHeight)749 .background(QColor.surface, in: RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous))750 .overlay(RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous)751 .strokeBorder(borderColor, lineWidth: focused ? 1.5 : 1))752 .accessibilityLabel("Endpoint address")753 status754 }755 } footer: {756 Button(original == nil ? "Add" : "Save") {757 onSave(EndpointRules.normalize(text))758 dismiss()759 }760 .buttonStyle(.qPrimary)761 .disabled(problem != nil)762 }763 .onAppear { focused = true }764 }765766 var borderColor: Color {767 switch problem {768 case .none: return QColor.positive769 case .empty: return focused ? QColor.violet : QColor.stroke770 default: return QColor.negative771 }772 }773774 @ViewBuilder var status: some View {775 switch problem {776 case .none:777 Label(EndpointRules.normalize(text).lowercased().hasPrefix("http://") ? "Accepted: local or private host, not encrypted" : "Accepted", systemImage: "checkmark.circle")778 .font(QFont.caption)779 .foregroundStyle(QColor.positive)780 case .empty:781 Text("The address of the API, starting with https://")782 .font(QFont.caption)783 .foregroundStyle(QColor.textSecondary)784 case .some(let p):785 Label(p.message ?? "", systemImage: "exclamationmark.circle")786 .font(QFont.caption)787 .foregroundStyle(QColor.negative)788 .fixedSize(horizontal: false, vertical: true)789 }790 }791}792793// MARK: - TronGrid key794795/// Entry of the TronGrid API key. The key is typed into a local state, handed to the service (which stores it in the796/// vault) and forgotten; it is never read back.797struct SecTronKeySheet: View {798 @Environment(WalletStore.self) private var store799 @Environment(\.dismiss) private var dismiss800 @State private var key = ""801 @State private var error: String?802 @State private var busy = false803 @State private var reauthenticate = false804 @State private var pendingRemoval = false805 @State private var done = 0806 @FocusState private var focused: Bool807808 private var hasKey: Bool { store.snapshot?.profile.hasTronAPIKey == true }809810 var body: some View {811 QSheetScaffold("TronGrid API key", subtitle: hasKey ? "A key is stored in the vault" : "Not set", onClose: { dismiss() }) {812 Explanation("TronGrid serves TRON's full nodes and history. Without a key its public access is rate limited; a key from trongrid.io raises the limit. The key identifies you to TronGrid across requests.")813 VStack(alignment: .leading, spacing: QSpace.s) {814 SecureField(hasKey ? "New key (replaces the stored one)" : "API key", text: $key)815 .font(QFont.mono)816 .textInputAutocapitalization(.never)817 .autocorrectionDisabled()818 .textContentType(.password)819 .focused($focused)820 .padding(14)821 .frame(minHeight: QMetric.controlHeight)822 .background(QColor.surface, in: RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous))823 .overlay(RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous).strokeBorder(focused ? QColor.violet : QColor.stroke, lineWidth: focused ? 1.5 : 1))824 .accessibilityLabel("TronGrid API key")825 Text("Stored in the vault only: never in the profile, never in a log, and never displayed again. To change it, enter a new one.")826 .font(QFont.caption).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)827 }828 SecInlineError(error)829 } footer: {830 LoadingButton("Save in the vault", loadingTitle: "Saving", state: busy ? .loading : .idle) { submit(removing: false) }831 .disabled(key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || busy)832 if hasKey {833 Button("Remove the stored key", role: .destructive) { submit(removing: true) }834 .buttonStyle(.qSecondary)835 .disabled(busy)836 }837 }838 .requiresReauthentication(isPresented: $reauthenticate, reason: "Change the TronGrid API key") { submit(removing: pendingRemoval, promptOnDemand: false) }839 .qHaptic(.toggled, trigger: done)840 // what was typed and not saved does not outlive the sheet841 .onDisappear { key = "" }842 }843844 private func submit(removing: Bool, promptOnDemand: Bool = true) {845 let value: String? = removing ? nil : key846 pendingRemoval = removing847 error = nil848 busy = true849 Task {850 do {851 try await store.run { try await $0.setTronAPIKey(value) }852 await store.refresh()853 key = ""854 done += 1855 dismiss()856 } catch WalletError.authenticationRequired where promptOnDemand {857 reauthenticate = true858 } catch {859 self.error = SecurityError.text(error)860 }861 busy = false862 }863 }864}865