Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraWallet/Chains.swift8// Module : Qyvora 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 Foundation42import QyvoraBitcoin43import QyvoraCore44import QyvoraNetworking45import QyvoraSolana46import QyvoraTron4748// The uniform chain model. One recovery phrase gives one account per family; each family has several networks.49// The interface never needs to know which Swift module serves a network: it reads `ChainDescriptor` values from50// `ChainRegistry` and addresses every call of the service with a `ChainID`.5152/// Stable identifier of one network of one chain ("bitcoin", "bitcoin-signet", "base-sepolia", "solana-devnet"…).53/// The raw value is what the profile stores; it never changes between versions.54public struct ChainID: RawRepresentable, Hashable, Codable, Sendable, Comparable, CustomStringConvertible {55 public let rawValue: String56 public init(rawValue: String) { self.rawValue = rawValue }57 public init(_ rawValue: String) { self.rawValue = rawValue }58 public var description: String { rawValue }59 public static func < (a: ChainID, b: ChainID) -> Bool { a.rawValue < b.rawValue }6061 public init(from decoder: any Decoder) throws { rawValue = try decoder.singleValueContainer().decode(String.self) }62 public func encode(to encoder: any Encoder) throws {63 var c = encoder.singleValueContainer()64 try c.encode(rawValue)65 }6667 public static let bitcoin = ChainID("bitcoin")68 public static let bitcoinSignet = ChainID("bitcoin-signet")69 public static let bitcoinTestnet = ChainID("bitcoin-testnet")70 public static let litecoin = ChainID("litecoin")71 public static let litecoinTestnet = ChainID("litecoin-testnet")72 public static let dogecoin = ChainID("dogecoin")73 public static let dogecoinTestnet = ChainID("dogecoin-testnet")74 public static let bitcoinCash = ChainID("bitcoin-cash")75 public static let bitcoinCashTestnet = ChainID("bitcoin-cash-testnet")76 public static let ethereum = ChainID("ethereum")77 public static let ethereumSepolia = ChainID("ethereum-sepolia")78 public static let base = ChainID("base")79 public static let baseSepolia = ChainID("base-sepolia")80 public static let arbitrum = ChainID("arbitrum")81 public static let arbitrumSepolia = ChainID("arbitrum-sepolia")82 public static let optimism = ChainID("optimism")83 public static let optimismSepolia = ChainID("optimism-sepolia")84 public static let polygon = ChainID("polygon")85 public static let polygonAmoy = ChainID("polygon-amoy")86 public static let bsc = ChainID("bsc")87 public static let bscTestnet = ChainID("bsc-testnet")88 public static let avalanche = ChainID("avalanche")89 public static let avalancheFuji = ChainID("avalanche-fuji")90 public static let solana = ChainID("solana")91 public static let solanaDevnet = ChainID("solana-devnet")92 public static let solanaTestnet = ChainID("solana-testnet")93 public static let tron = ChainID("tron")94 public static let tronNile = ChainID("tron-nile")95 public static let tronShasta = ChainID("tron-shasta")96}9798/// The four families of chains. One family = one kind of account and one way of signing.99public enum ChainFamily: String, Codable, Sendable, CaseIterable {100 /// Bitcoin and the coins that share its transaction format: a tree of addresses under an extended public key.101 case utxo102 /// Ethereum and the EVM networks: one secp256k1 account shared by all of them.103 case evm104 /// Solana: one Ed25519 account; the address is the public key.105 case solana106 /// TRON: one secp256k1 account.107 case tron108}109110/// Test networks (the default) or main networks, for every chain at once.111public enum NetworkMode: String, Codable, Sendable, CaseIterable {112 case test113 /// Real funds. Only when `MainnetPolicy.mainnetEnabled`.114 case main115}116117/// What the wallet can do on a chain. The interface hides what is false.118public struct ChainCapabilities: Equatable, Sendable {119 /// Tokens exist on the chain and the wallet reads and sends them (ERC-20, SPL, TRC-20).120 public let tokens: Bool121 /// A history source exists with the built-in endpoints. When false the snapshot says why122 /// (`ChainData.historyUnavailableReason`) and nothing is shown in its place.123 public let historyAvailable: Bool124 /// Unsigned transactions can be exported to a cold device and signed there.125 public let coldSigning: Bool126 /// The user can choose which coins a payment spends.127 public let coinControl: Bool128 /// Slow / normal / fast fee choices exist.129 public let feeTiers: Bool130 /// A public note can be attached to a payment of the native coin.131 public let memo: Bool132}133134/// The internal form of a chain identifier: which module serves it, with that module's own network value.135enum ChainKind: Hashable, Sendable {136 case utxo(BitcoinNetwork)137 case evm(EthereumNetwork)138 case solana(SolanaNetwork)139 case tron(TronNetwork)140141 var family: ChainFamily {142 switch self {143 case .utxo: return .utxo144 case .evm: return .evm145 case .solana: return .solana146 case .tron: return .tron147 }148 }149150 var isTest: Bool {151 switch self {152 case .utxo(let n): return n.isTest153 case .evm(let n): return n.isTest154 case .solana(let n): return n.isTest155 case .tron(let n): return n.isTest156 }157 }158}159160/// Everything the interface needs to know about one network of one chain. Values come from `ChainRegistry` only.161public struct ChainDescriptor: Equatable, Sendable, Identifiable {162 public let id: ChainID163 public let family: ChainFamily164 /// "Ethereum Sepolia", "Solana Devnet"…165 public let displayName: String166 /// Short label for lists and badges ("Sepolia", "Devnet").167 public let shortName: String168 /// Ticker of the coin that pays the fees ("BTC", "ETH", "POL", "SOL", "TRX"). The same on a test network: the169 /// interface marks test coins with `isTest`, never with another ticker.170 public let nativeSymbol: String171 public let nativeName: String172 /// Decimals of the native coin: 8 (UTXO coins), 18 (EVM), 9 (SOL), 6 (TRX).173 public let nativeDecimals: Int174 public let isTest: Bool175 /// The main network of the same chain (itself for a main network). This is the identifier the user enables:176 /// `WalletProfile.enabledChains` holds main identifiers only.177 public let mainCounterpart: ChainID178 /// The test networks of the same chain, default first. Several exist for Bitcoin (Signet, Testnet), Solana179 /// (devnet, testnet) and TRON (Nile, Shasta): `WalletService.setTestNetwork` chooses among them.180 public let testCounterparts: [ChainID]181 /// CoinGecko identifier of the native coin. A test network names the coin of its main network: test coins have no182 /// value, and the valuation reports them as a reference value only.183 public let priceID: String184 /// The signature algorithm QYVORA signs with on the network ("secp256k1 ECDSA", "Ed25519"). None resists a quantum185 /// computer. A network may validate more than this: Bitcoin also validates Schnorr signatures (Taproot), which the186 /// engine implements and the wallet does not use for spending. What a network validates is section 3 of the187 /// Shield (`NetworkResistance.ChainStatus.signatureSchemes`), which states this scheme next to it (`walletSignatureScheme`).188 public let signatureScheme: String189 /// Derivation path of the account from the recovery phrase ("m/84'/1'/0'", "m/44'/60'/0'/0/0", "m/44'/501'/0'/0'").190 public let derivationPath: String191 public let capabilities: ChainCapabilities192 /// EIP-155 chain identifier of an EVM network; nil elsewhere.193 public let evmChainID: UInt64?194195 let kind: ChainKind196197 /// Web page of a transaction on a public explorer, for a link the user opens. nil when `id` is not a transaction198 /// identifier of this chain. QYVORA never queries the explorer itself.199 public func explorerTransactionURL(_ id: String) -> URL? {200 switch kind {201 case .utxo(let n):202 // the network knows its explorer and the path that explorer uses; none (Dogecoin Testnet) gives no link (QYV-FUZ-080)203 return n.explorerTransactionURL(txid: id).flatMap { URL(string: $0) }204 case .evm(let n): return n.explorerTransactionURL(hash: id)205 case .solana(let n):206 guard SolanaRPC.isSignature(id) else { return nil }207 return URL(string: "https://explorer.solana.com/tx/" + id + Self.solanaCluster(n))208 case .tron(let n):209 guard id.utf8.count == 64, id.utf8.allSatisfy(Self.isLowerHex) else { return nil }210 return URL(string: Self.tronExplorer(n) + "/#/transaction/" + id)211 }212 }213214 /// Web page of an address on a public explorer; nil when `address` is not an address of this chain's family.215 public func explorerAddressURL(_ address: String) -> URL? {216 switch kind {217 case .utxo(let n):218 // an address of this network, and a network that has an explorer: otherwise no link (QYV-FUZ-080)219 guard let base = n.explorerBaseURL, (14...90).contains(address.utf8.count), address.utf8.allSatisfy({ Self.isAlphanumeric($0) || $0 == 0x3a }),220 (try? BitcoinAddress(address, network: n)) != nil else { return nil }221 return URL(string: base + "/address/" + address)222 case .evm(let n): return n.explorerAddressURL(address: address)223 case .solana(let n):224 guard SolanaPublicKey(base58: address) != nil else { return nil }225 return URL(string: "https://explorer.solana.com/address/" + address + Self.solanaCluster(n))226 case .tron(let n):227 guard TronAddress(address) != nil else { return nil }228 return URL(string: Self.tronExplorer(n) + "/#/address/" + address)229 }230 }231232 private static func isLowerHex(_ c: UInt8) -> Bool { (c >= 0x30 && c <= 0x39) || (c >= 0x61 && c <= 0x66) }233 private static func isAlphanumeric(_ c: UInt8) -> Bool { (c >= 0x30 && c <= 0x39) || (c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a) }234235 private static func bitcoinExplorer(_ n: BitcoinNetwork) -> String {236 ChainRegistry.utxoExplorerBase(n)237 }238239 private static func solanaCluster(_ n: SolanaNetwork) -> String {240 switch n {241 case .mainnetBeta: return ""242 case .devnet: return "?cluster=devnet"243 case .testnet: return "?cluster=testnet"244 }245 }246247 private static func tronExplorer(_ n: TronNetwork) -> String {248 switch n {249 case .mainnet: return "https://tronscan.org"250 case .nile: return "https://nile.tronscan.org"251 case .shasta: return "https://shasta.tronscan.org"252 }253 }254}255256/// The chains of one family, for a list with section headers.257public struct ChainGroup: Equatable, Sendable, Identifiable {258 public let family: ChainFamily259 /// "Bitcoin and UTXO coins", "Ethereum and EVM networks", "Solana", "TRON".260 public let title: String261 /// One sentence about the account of the family, ready to display.262 public let accountNote: String263 /// Main networks of the family, in display order. Each one names its test networks (`testCounterparts`).264 public let chains: [ChainDescriptor]265 public var id: String { family.rawValue }266}267268/// Every chain QYVORA supports. Static data: nothing here depends on the wallet or on the network.269public enum ChainRegistry {270 // MARK: Identifier mapping271272 static let utxoNetworks: [(ChainID, BitcoinNetwork)] = UTXOChains.table273 static let evmNetworks: [(ChainID, EthereumNetwork)] = [274 (.ethereum, .mainnet), (.ethereumSepolia, .sepolia), (.base, .base), (.baseSepolia, .baseSepolia),275 (.arbitrum, .arbitrum), (.arbitrumSepolia, .arbitrumSepolia), (.optimism, .optimism), (.optimismSepolia, .optimismSepolia),276 (.polygon, .polygon), (.polygonAmoy, .polygonAmoy), (.bsc, .bsc), (.bscTestnet, .bscTestnet),277 (.avalanche, .avalanche), (.avalancheFuji, .avalancheFuji),278 ]279 static let solanaNetworks: [(ChainID, SolanaNetwork)] = [(.solana, .mainnetBeta), (.solanaDevnet, .devnet), (.solanaTestnet, .testnet)]280 static let tronNetworks: [(ChainID, TronNetwork)] = [(.tron, .mainnet), (.tronNile, .nile), (.tronShasta, .shasta)]281282 static func id(_ network: BitcoinNetwork) -> ChainID { utxoNetworks.first { $0.1 == network }?.0 ?? ChainID("utxo-" + network.rawValue) }283 static func id(_ network: EthereumNetwork) -> ChainID { evmNetworks.first { $0.1 == network }?.0 ?? ChainID("evm-" + network.rawValue) }284 static func id(_ network: SolanaNetwork) -> ChainID { solanaNetworks.first { $0.1 == network }?.0 ?? .solana }285 static func id(_ network: TronNetwork) -> ChainID { tronNetworks.first { $0.1 == network }?.0 ?? .tron }286287 static func kind(_ id: ChainID) -> ChainKind? {288 if let n = utxoNetworks.first(where: { $0.0 == id }) { return .utxo(n.1) }289 if let n = evmNetworks.first(where: { $0.0 == id }) { return .evm(n.1) }290 if let n = solanaNetworks.first(where: { $0.0 == id }) { return .solana(n.1) }291 if let n = tronNetworks.first(where: { $0.0 == id }) { return .tron(n.1) }292 return nil293 }294295 static func id(_ kind: ChainKind) -> ChainID {296 switch kind {297 case .utxo(let n): return id(n)298 case .evm(let n): return id(n)299 case .solana(let n): return id(n)300 case .tron(let n): return id(n)301 }302 }303304 // MARK: Descriptors305306 /// Every network, main networks first inside each family, in display order.307 public static let all: [ChainDescriptor] = {308 var out = [ChainDescriptor]()309 for (id, n) in utxoNetworks { out.append(UTXOChains.descriptor(id, n)) }310 for (id, n) in evmNetworks {311 out.append(ChainDescriptor(312 id: id, family: .evm, displayName: n.displayName, shortName: n.shortName, nativeSymbol: n.nativeSymbol, nativeName: n.nativeName,313 nativeDecimals: n.nativeDecimals, isTest: n.isTest, mainCounterpart: Self.id(n.mainCounterpart), testCounterparts: [Self.id(n.testCounterpart)],314 priceID: n.priceID, signatureScheme: "secp256k1 ECDSA", derivationPath: StandardPaths.ethereum().description,315 capabilities: ChainCapabilities(tokens: true, historyAvailable: EVMEndpointDefaults.hasDefaultIndexer(n), coldSigning: true,316 coinControl: false, feeTiers: true, memo: false),317 evmChainID: n.chainID, kind: .evm(n)))318 }319 for (id, n) in solanaNetworks {320 out.append(ChainDescriptor(321 id: id, family: .solana, displayName: n.displayName, shortName: n == .mainnetBeta ? "Solana" : (n == .devnet ? "Devnet" : "Testnet"),322 nativeSymbol: SolanaNetwork.symbol, nativeName: "Solana", nativeDecimals: SolanaNetwork.decimals, isTest: n.isTest,323 mainCounterpart: .solana, testCounterparts: [.solanaDevnet, .solanaTestnet], priceID: "solana", signatureScheme: "Ed25519",324 derivationPath: SolanaKeys.derivationPath().description,325 capabilities: ChainCapabilities(tokens: true, historyAvailable: true, coldSigning: true, coinControl: false, feeTiers: true, memo: true),326 evmChainID: nil, kind: .solana(n)))327 }328 for (id, n) in tronNetworks {329 out.append(ChainDescriptor(330 id: id, family: .tron, displayName: n.displayName, shortName: n == .mainnet ? "TRON" : (n == .nile ? "Nile" : "Shasta"),331 nativeSymbol: n.symbol, nativeName: "TRON", nativeDecimals: TronUnits.decimals, isTest: n.isTest,332 mainCounterpart: .tron, testCounterparts: [.tronNile, .tronShasta], priceID: "tron", signatureScheme: "secp256k1 ECDSA",333 derivationPath: TronPaths.account().description,334 capabilities: ChainCapabilities(tokens: true, historyAvailable: true, coldSigning: true, coinControl: false, feeTiers: false, memo: true),335 evmChainID: nil, kind: .tron(n)))336 }337 return out338 }()339340 private static let byID: [ChainID: ChainDescriptor] = Dictionary(uniqueKeysWithValues: all.map { ($0.id, $0) })341342 /// The descriptor of an identifier; nil for an identifier QYVORA does not know.343 public static func descriptor(_ id: ChainID) -> ChainDescriptor? { byID[id] }344345 static func descriptor(_ kind: ChainKind) -> ChainDescriptor {346 // every kind built from the tables above has a descriptor347 byID[id(kind)] ?? all[0]348 }349350 /// Main networks only, in display order: what the user can enable.351 public static let mainChains: [ChainDescriptor] = all.filter { !$0.isTest }352353 /// The chains enabled in a wallet that never chose: Bitcoin and Ethereum, as QYVORA 1.0.354 public static let defaultEnabled: [ChainID] = [.bitcoin, .ethereum]355356 /// Main networks grouped by family, for the "chains" screen.357 public static let groups: [ChainGroup] = [358 ChainGroup(family: .utxo, title: "Bitcoin and UTXO coins",359 accountNote: "Each coin has its own account and gives a new address for every payment.",360 chains: mainChains.filter { $0.family == .utxo }),361 ChainGroup(family: .evm, title: "Ethereum and EVM networks",362 accountNote: "One address (m/44'/60'/0'/0/0) is shared by every EVM network.",363 chains: mainChains.filter { $0.family == .evm }),364 ChainGroup(family: .solana, title: "Solana",365 accountNote: "One address (m/44'/501'/0'/0'). A Solana address is the Ed25519 public key itself.",366 chains: mainChains.filter { $0.family == .solana }),367 ChainGroup(family: .tron, title: "TRON",368 accountNote: "One address (m/44'/195'/0'/0/0).",369 chains: mainChains.filter { $0.family == .tron }),370 ]371372 /// The test network each main network uses by default in test mode:373 /// Bitcoin → Signet, every EVM network → its Sepolia / Amoy / Fuji / BNB testnet, Solana → devnet, TRON → Nile.374 public static func defaultTestNetwork(of main: ChainID) -> ChainID? { descriptor(main)?.testCounterparts.first }375376 static func utxoExplorerBase(_ n: BitcoinNetwork) -> String { UTXOChains.explorerBase(n) }377}378379/// The UTXO part of the registry: every value comes from the properties of `BitcoinNetwork`.380enum UTXOChains {381 /// The UTXO networks the wallet service drives. Bitcoin's three networks; a coin is added here once the service382 /// synchronizes, limits and signs it.383 static let table: [(ChainID, BitcoinNetwork)] = [384 (.bitcoin, .mainnet), (.bitcoinSignet, .signet), (.bitcoinTestnet, .testnet),385 (.litecoin, .litecoin), (.litecoinTestnet, .litecoinTestnet), (.dogecoin, .dogecoin), (.dogecoinTestnet, .dogecoinTestnet),386 (.bitcoinCash, .bitcoinCash), (.bitcoinCashTestnet, .bitcoinCashTestnet),387 ]388389 static func explorerBase(_ n: BitcoinNetwork) -> String { n.explorerBaseURL ?? "" }390391 static func descriptor(_ id: ChainID, _ n: BitcoinNetwork) -> ChainDescriptor {392 let main = n.mainCounterpart393 // test networks of the coin, the default one first394 var tests = [main.testCounterpart]395 for t in BitcoinNetwork.networks(of: n.coin) where t.isTest && !tests.contains(t) { tests.append(t) }396 return ChainDescriptor(397 id: id, family: .utxo, displayName: n.displayName, shortName: n.shortName, nativeSymbol: n.ticker, nativeName: main.displayName,398 nativeDecimals: n.decimals, isTest: n.isTest, mainCounterpart: ChainRegistry.id(main), testCounterparts: tests.map { ChainRegistry.id($0) },399 priceID: main.priceID ?? "bitcoin", signatureScheme: "secp256k1 ECDSA",400 derivationPath: StandardPaths.account(n.defaultPurpose, n).description,401 // cold signing (PSBT) is wired for Bitcoin's own networks only402 capabilities: ChainCapabilities(tokens: false, historyAvailable: n.indexerAvailable, coldSigning: n.coin == .bitcoin, coinControl: true,403 feeTiers: true, memo: false),404 evmChainID: nil, kind: .utxo(n))405 }406}407