Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraWallet/ChainTypes.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 QyvoraMath43import QyvoraCore44import QyvoraBitcoin45import QyvoraEthereum46import QyvoraSolana47import QyvoraTron4849// The uniform state of a chain, as the interface reads it. Every amount is an integer of base units next to its50// decimals; nothing here is ever a placeholder: what was not read is `.notLoaded` or `.unavailable(reason:)`.5152// MARK: - Tokens and assets5354/// A token on any chain: an ERC-20 contract, an SPL mint or a TRC-20 contract. A token is identified by its chain and55/// its address only; symbol and name are what the contract claims (built-in entries were checked by hand).56public struct ChainToken: Equatable, Hashable, Sendable, Identifiable, Codable {57 public enum Standard: String, Codable, Sendable {58 case erc20 = "ERC-20"59 case spl = "SPL"60 case splToken2022 = "SPL Token-2022"61 case trc20 = "TRC-20"62 }6364 public let chain: ChainID65 /// Contract address (EVM: EIP-55 form; TRON: Base58Check) or mint address (Solana: base58).66 public let address: String67 public let symbol: String68 public let name: String69 public let decimals: Int70 public let standard: Standard71 /// CoinGecko identifier, when the token has a known price. A token without one cannot be sent on mainnet by an72 /// unaudited build (its value cannot be checked against the limit).73 public let priceID: String?74 /// True for a token added by the user, false for the built-in list.75 public let isCustom: Bool76 /// A fact the user should know before relying on the token, when there is one.77 public let note: String?7879 public var id: String { "\(chain.rawValue):\(address)" }8081 public init(chain: ChainID, address: String, symbol: String, name: String, decimals: Int, standard: Standard, priceID: String? = nil,82 isCustom: Bool = false, note: String? = nil) {83 self.chain = chain84 self.address = address85 self.symbol = symbol86 self.name = name87 self.decimals = decimals88 self.standard = standard89 self.priceID = priceID90 self.isCustom = isCustom91 self.note = note92 }93}9495/// What a payment sends: the coin of the chain, or one of its tokens.96public enum ChainAsset: Equatable, Hashable, Sendable {97 case native98 case token(ChainToken)99}100101public struct ChainTokenBalance: Equatable, Sendable, Identifiable {102 public let token: ChainToken103 /// Base units, read on chain.104 public let balance: Availability<UInt256>105 /// Something about this holding the user must see (a frozen token account, a Token-2022 extension the wallet106 /// refuses to transfer, decimals that differ from the token list…).107 public let warning: String?108 public var id: String { token.id }109}110111/// Balance of the native coin in base units.112public struct ChainNativeBalance: Equatable, Sendable {113 /// What the chain has confirmed.114 public let confirmed: UInt256115 /// Unconfirmed incoming value. Only UTXO chains report one; zero elsewhere (an account chain shows the balance of116 /// its latest block, there is no separate pending amount).117 public let pending: UInt256118 public let decimals: Int119 public let symbol: String120 public var total: UInt256 { confirmed.addingReportingOverflow(pending).0 }121}122123// MARK: - Activity124125/// One line of history, the same shape on every chain.126public struct ActivityEntry: Equatable, Sendable, Identifiable, Codable {127 public enum Direction: String, Sendable, Codable {128 case received, sent, selfTransfer129 /// The account took part without a balance movement the wallet can attribute (a failed call, an approval).130 case none131 }132133 public enum Kind: Equatable, Sendable, Codable {134 /// A movement of the native coin.135 case native136 /// A token movement. `verified` is true when symbol and decimals come from the wallet's own token list or137 /// from the chain; false when they are the indexer's word.138 case token(address: String, symbol: String?, decimals: Int?, verified: Bool)139 /// An allowance granted (or revoked) by the account.140 case approval(token: String)141 /// A call to a contract or a program that is not a plain transfer.142 case contract(method: String?)143 /// Something the wallet does not decode. Shown as such, never guessed.144 case unknown(description: String?)145 }146147 public enum Status: Equatable, Sendable, Codable {148 /// Seen, not in a block yet.149 case pending150 /// In a block. `confirmations` is nil when the source does not give a depth.151 case confirmed(confirmations: UInt64?)152 /// Final by the chain's own rule (Solana "finalized", TRON irreversible, EVM beyond the finality depth).153 case finalized154 /// Included and failed: the fee was paid, nothing else moved.155 case failed156 }157158 public let chain: ChainID159 /// Unique among the entries of the chain (a transaction with several token movements gives several entries).160 public let id: String161 /// Transaction identifier: txid, 0x hash, Solana signature or TRON transaction id.162 public let hash: String163 public let direction: Direction164 /// The other side, where it is known: recipient of a send, sender of a receipt on account chains, the paid165 /// addresses on UTXO chains (payers cannot be known reliably there). nil when unknown.166 public let counterparty: String?167 /// Base units of the native coin or of the token named by `kind`.168 public let amount: UInt256169 /// Decimals of `amount`; nil for a token whose decimals are not known.170 public let decimals: Int?171 public let symbol: String?172 /// Fee in base units of the native coin, when this account paid it and the source reports it.173 public let fee: UInt256?174 public let status: Status175 /// Block time; nil while pending or when the source does not give it.176 public let time: Date?177 /// Block height or slot.178 public let blockHeight: UInt64?179 public let kind: Kind180181 /// Explorer page of the transaction (a link for the user; QYVORA does not query it).182 public var explorerURL: URL? { ChainRegistry.descriptor(chain)?.explorerTransactionURL(hash) }183 public var isToken: Bool {184 if case .token = kind { return true }185 return false186 }187}188189// MARK: - Receiving190191public struct ChainReceive: Equatable, Sendable {192 public enum Rule: String, Sendable {193 /// UTXO chains: a new address for every payment (never reuse one).194 case freshAddressPerPayment195 /// Account chains: the account has one address.196 case fixedAddress197 }198199 public let address: String200 /// Full derivation path of this address.201 public let derivationPath: String?202 public let rule: Rule203 /// Sentences to show next to the address ("This address is the same on every EVM network…").204 public let notes: [String]205}206207// MARK: - Exposure (Quantum Shield)208209/// Whether the public key of the account of this chain is public. A statement about this wallet's history.210public struct ChainExposure: Equatable, Sendable {211 public enum Evidence: String, Sendable {212 /// UTXO chains: per-coin analysis of the scripts spent from (see the `BitcoinSnapshot` in the extras).213 case spendHistory214 /// EVM: the account nonce at "latest".215 case nonce216 /// History of the account (TRON, and EVM where an indexer exists).217 case history218 /// Solana: the address is the public key.219 case addressIsPublicKey220 case notMeasured221 }222223 /// true: the key is public. false: only a hash of it is. nil: not measured.224 public let publicKeyExposed: Bool?225 public let evidence: Evidence226 /// Transactions sent by the account, where the chain counts them (EVM nonce); nil elsewhere or when unknown.227 public let outgoingTransactionCount: UInt64?228 /// One sentence, ready to display.229 public let statement: String230}231232// MARK: - Family extras233234public struct SolanaExtras: Equatable, Sendable, Codable {235 /// False when no account exists at the address yet (never funded): it is created by the first payment received.236 public let accountExists: Bool237 /// Rent-exempt minimum of a wallet account, in lamports, read on chain. An account must hold at least this much238 /// or nothing at all; a first payment below it is rejected by the cluster.239 public let systemAccountRent: UInt64240 /// Lamports locked in a token account of the legacy Token program (paid by whoever creates it; when this wallet241 /// sends a token to someone who has none, this wallet pays it).242 public let tokenAccountRent: UInt64243 /// The same for a Token-2022 account.244 public let token2022AccountRent: UInt64245 /// Token accounts found for the owner, both programs together.246 public let tokenAccountCount: Int247}248249public struct TronExtras: Equatable, Sendable {250 /// False for an address the chain has never seen: it holds nothing and cannot send; the first TRX payment it251 /// receives creates it (the sender pays the activation fee).252 public let isActivated: Bool253 public let resources: TronResources254 /// Free bandwidth left today (bytes). A TRX transfer needs about 270; beyond the allowance bytes are paid in TRX.255 public var freeBandwidth: UInt64 { resources.freeBandwidth }256 /// Bandwidth from staking.257 public var stakedBandwidth: UInt64 { resources.stakedBandwidth }258 /// Energy from staking. Without energy a token transfer burns TRX instead.259 public var energy: UInt64 { resources.energy }260 /// Fee parameters of the chain, read on chain.261 public let parameters: TronChainParameters262}263264/// What only one family has.265public enum ChainExtras: Equatable, Sendable {266 /// Coins, addresses, coin control and per-coin exposure.267 case utxo(BitcoinSnapshot)268 /// Nonces, pending transaction, approvals.269 case evm(EthereumSnapshot)270 case solana(SolanaExtras)271 case tron(TronExtras)272}273274// MARK: - Snapshot275276public struct ChainSyncProgress: Equatable, Sendable {277 public let stage: String278 /// Real counts, never an estimate. `total` is nil while unknown.279 public let completed: Int280 public let total: Int?281}282283/// What was read on one chain at one moment.284public struct ChainData: Equatable, Sendable {285 public let synchronizedAt: Date286 /// True when restored from the last synchronization of a previous launch: the last known state as of287 /// `synchronizedAt`, not a fresh reading. Payments are never built from it.288 public let isFromPreviousSession: Bool289 /// Block height (UTXO, EVM, TRON) or slot (Solana) the data was read at.290 public let height: UInt64291 public let native: ChainNativeBalance292 /// Tokens of the wallet's list (built-in and custom, hidden ones removed).293 public let tokens: [ChainTokenBalance]294 /// Tokens found on the account that the user has not accepted: kept apart, never valued, never mixed with `tokens`.295 public let detectedTokens: [ChainTokenBalance]296 /// Newest first. `.unavailable` where no history source exists: nothing is shown in its place.297 public let history: Availability<[ActivityEntry]>298 public let exposure: ChainExposure299 public let extras: ChainExtras300 /// Non-fatal remarks of the synchronization.301 public let notes: [String]302303 /// Why there is no history, when there is none (seven EVM networks have no keyless indexer).304 public var historyUnavailableReason: String? {305 if case .unavailable(let reason) = history { return reason }306 return nil307 }308}309310/// Ceilings of an unaudited build on a main network, as sentences. nil on a test network.311public struct ChainLimits: Equatable, Sendable {312 /// "At most 0.002 BTC per transaction." / "At most 150 USD of SOL per transaction, checked with a fresh price."313 public let native: String314 /// nil on a chain without tokens.315 public let tokens: String?316 public let fee: String317 public var lines: [String] { [native] + (tokens.map { [$0] } ?? []) + [fee] }318}319320/// One enabled chain in the dashboard.321public struct ChainSnapshot: Equatable, Sendable, Identifiable {322 public let chain: ChainDescriptor323 public var id: ChainID { chain.id }324 /// True for the two chains the 1.0 screens show (`WalletSnapshot.bitcoin` / `.ethereum`).325 public let isPrimary: Bool326 /// The account address on an account chain; nil on a UTXO chain (see `receive`) and when the wallet has no327 /// account of this family.328 public let accountAddress: String?329 /// `.notLoaded` before the first synchronization, `.unavailable` when it failed and nothing older is known (or330 /// when the wallet has no account of this family).331 public let data: Availability<ChainData>332 public let isSynchronizing: Bool333 public let progress: ChainSyncProgress?334 /// Error of the last failed synchronization, ready to display; nil after a success. Set whether or not older335 /// data is still shown.336 public let syncError: String?337 /// Where to be paid. Available offline and while the vault is locked.338 public let receive: ChainReceive?339 /// Per-transaction ceilings that apply now; nil unless this is a main network on an unaudited build.340 public let limits: ChainLimits?341}342343// MARK: - Addresses344345/// Why a text is not an address the wallet can pay on a chain. Each case gives a precise sentence (`message`).346public enum AddressRefusal: Error, Equatable, Sendable {347 case empty348 /// Not an address of any kind the wallet recognises.349 case malformed(chain: String, expected: String)350 /// A valid address of another chain family (an Ethereum address pasted on TRON, a Bitcoin address on Solana…).351 case wrongFamily(chain: String, found: String)352 /// The right coin on another of its networks (a test address on the main network, or the reverse).353 case wrongNetwork(chain: String, found: String)354 /// The form is right and the checksum is not: a character is wrong.355 case invalidChecksum(chain: String)356 /// A Bitcoin Cash address given without its "bitcoincash:" prefix cannot be told from other formats.357 case missingPrefix(chain: String, prefix: String)358 /// The all-zero address: funds sent there are lost.359 case zeroAddress360 /// The address form exists on the chain and the wallet does not pay it; the text says why.361 case unsupported(String)362}363364/// A recipient that passed validation, with what the user should know about it.365public struct AddressCheck: Equatable, Sendable {366 public let chain: ChainID367 /// The address in the canonical form of the chain (EIP-55 for EVM, Base58Check for TRON…).368 public let canonical: String369 /// True when the address is this wallet's own.370 public let isOwnAddress: Bool371 /// Sentences to show under the field (no checksum, off-curve Solana address, legacy format accepted…).372 public let notes: [String]373}374