Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraWallet/ChainPersistence.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 QyvoraEthereum45import QyvoraNetworking46import QyvoraStorage47import QyvoraSolana48import QyvoraTron4950// What the last synchronization of a Solana or TRON network read, in the form that is also stored between launches51// (public chain data only, as for Bitcoin and Ethereum: see SyncPersistence.swift). One file per network. A file with52// another identity (account, network, endpoints), another format version or values out of range is ignored and removed.5354/// A transaction signed in this session on Solana or TRON.55struct SentTransaction: Sendable {56 enum Outcome: Sendable { case unknown, rejected }57 let kind: ChainKind58 let id: String59 /// Recipient, asset and amount: two transactions with the same key are the same payment.60 let paymentKey: String61 /// The signed bytes, so that a retry re-sends them instead of signing again.62 let signed: Bytes63 /// Solana: block height after which the transaction can no longer be executed.64 let lastValidBlockHeight: UInt64?65 /// TRON: expiration, milliseconds since 1970.66 let expirationMilliseconds: UInt64?67 /// `.rejected` once every endpoint refused it: it was never broadcast.68 var outcome: Outcome = .unknown69 /// True once tracking saw it confirmed, failed or expired: it no longer blocks a new payment.70 var settled = false71}7273/// A token holding as read on chain.74struct ChainHolding: Codable, Equatable, Sendable {75 var token: ChainToken76 /// Base units; nil when the balance could not be read (`reason` says why).77 var amount: UInt256?78 var reason: String?79 var warning: String?80 /// True for a token of the wallet's list, false for one found on the account and not accepted.81 var listed: Bool8283 var balance: ChainTokenBalance {84 ChainTokenBalance(token: token, balance: amount.map { .available($0) } ?? .unavailable(reason: reason ?? "Not read at the last synchronization."),85 warning: warning)86 }87}8889struct SolanaChainRecord: Codable, Equatable, Sendable {90 static let currentVersion = 191 static let maximumBytes = 4 << 2092 static func fileName(_ network: SolanaNetwork) -> String { "solana-sync-\(network.rawValue).json" }9394 var version = currentVersion95 /// `WalletService.solanaIdentity`: network, account and endpoint list this data was read for.96 var identity: String97 var network: SolanaNetwork98 var address: String99 var synchronizedAt: Date100 var slot: UInt64101 var lamports: UInt64102 var extras: SolanaExtras103 var holdings: [ChainHolding]104 /// nil when the history could not be read (`historyReason` says why).105 var history: [ActivityEntry]?106 var historyReason: String?107 /// True when the history shows a transaction this account initiated; nil when the history is not known.108 var hasOutgoing: Bool?109 var notes: [String]110 var isFromPreviousSession: Bool?111112 /// The record as restored from disk, or nil when a value is out of the ranges the service accepts.113 func validated(identity expected: String, address expectedAddress: String) -> SolanaChainRecord? {114 guard version >= 1, version <= Self.currentVersion, identity == expected, address == expectedAddress,115 SolanaPublicKey(base58: address) != nil, holdings.count <= 1_200, (history?.count ?? 0) <= 500, notes.count <= 50,116 holdings.allSatisfy({ $0.token.decimals >= 0 && $0.token.decimals <= 255 && $0.token.chain == ChainRegistry.id(network) }),117 (history ?? []).allSatisfy({ $0.chain == ChainRegistry.id(network) }) else { return nil }118 var copy = self119 copy.isFromPreviousSession = true120 return copy121 }122}123124struct TronChainRecord: Codable, Equatable, Sendable {125 static let currentVersion = 1126 static let maximumBytes = 4 << 20127 static func fileName(_ network: TronNetwork) -> String { "tron-sync-\(network.rawValue).json" }128129 struct Resources: Codable, Equatable, Sendable {130 var freeNetLimit: UInt64, freeNetUsed: UInt64, netLimit: UInt64, netUsed: UInt64, energyLimit: UInt64, energyUsed: UInt64131132 init(_ r: TronResources) {133 freeNetLimit = r.freeNetLimit134 freeNetUsed = r.freeNetUsed135 netLimit = r.netLimit136 netUsed = r.netUsed137 energyLimit = r.energyLimit138 energyUsed = r.energyUsed139 }140141 var value: TronResources {142 TronResources(freeNetLimit: freeNetLimit, freeNetUsed: freeNetUsed, netLimit: netLimit, netUsed: netUsed, energyLimit: energyLimit, energyUsed: energyUsed)143 }144 }145146 struct Parameters: Codable, Equatable, Sendable {147 var bandwidthPriceSun: UInt64, energyPriceSun: UInt64, accountActivationFeeSun: UInt64, createAccountFeeSun: UInt64148 var createAccountBandwidthRate: UInt64, maximumFeeLimitSun: UInt64, memoFeeSun: UInt64149150 init(_ p: TronChainParameters) {151 bandwidthPriceSun = p.bandwidthPriceSun152 energyPriceSun = p.energyPriceSun153 accountActivationFeeSun = p.accountActivationFeeSun154 createAccountFeeSun = p.createAccountFeeSun155 createAccountBandwidthRate = p.createAccountBandwidthRate156 maximumFeeLimitSun = p.maximumFeeLimitSun157 memoFeeSun = p.memoFeeSun158 }159160 var value: TronChainParameters {161 TronChainParameters(bandwidthPriceSun: bandwidthPriceSun, energyPriceSun: energyPriceSun, accountActivationFeeSun: accountActivationFeeSun,162 createAccountFeeSun: createAccountFeeSun, createAccountBandwidthRate: createAccountBandwidthRate,163 maximumFeeLimitSun: maximumFeeLimitSun, memoFeeSun: memoFeeSun)164 }165 }166167 var version = currentVersion168 var identity: String169 var network: TronNetwork170 var address: String171 var synchronizedAt: Date172 var blockNumber: UInt64173 var balanceSun: UInt64174 var isActivated: Bool175 var resources: Resources176 var parameters: Parameters177 var holdings: [ChainHolding]178 var history: [ActivityEntry]?179 var historyReason: String?180 /// True when the account is known to have sent a transaction; false when it is known not to; nil when not measured.181 var hasOutgoing: Bool?182 var notes: [String]183 var isFromPreviousSession: Bool?184185 func validated(identity expected: String, address expectedAddress: String) -> TronChainRecord? {186 guard version >= 1, version <= Self.currentVersion, identity == expected, address == expectedAddress, TronAddress(address) != nil,187 balanceSun <= UInt64(Int64.max), holdings.count <= 200, (history ?? []).count <= 500, notes.count <= 50,188 holdings.allSatisfy({ $0.token.decimals >= 0 && $0.token.decimals <= 77 && $0.token.chain == ChainRegistry.id(network) }),189 (history ?? []).allSatisfy({ $0.chain == ChainRegistry.id(network) }) else { return nil }190 var copy = self191 copy.isFromPreviousSession = true192 return copy193 }194}195196extension EthereumSnapshotRecord {197 /// One file per EVM chain (a main network and its test network are never active together). Ethereum and Sepolia198 /// keep the file name of QYVORA 1.0, so that its last snapshot is still read after the upgrade.199 static func fileName(for network: EthereumNetwork) -> String {200 network.family == .ethereum ? fileName : "evm-sync-\(network.family.rawValue).json"201 }202}203204extension WalletService {205 // MARK: Identities206207 /// What a persisted EVM snapshot belongs to: the network, the account and both endpoint lists.208 static func ethereumIdentity(_ profile: WalletProfile, network: EthereumNetwork) -> String? {209 guard profile.kind != nil, let address = profile.ethereumAddress else { return nil }210 let name = network.rawValue211 let rpc = (profile.endpoints.ethereumRPC[name] ?? []).joined(separator: ","), indexer = (profile.endpoints.ethereumIndexer[name] ?? []).joined(separator: ",")212 return "eth|v\(EthereumSnapshotRecord.currentVersion)|\(name)|\(address.checksummed)|\(rpc)|\(indexer)"213 }214215 static func solanaIdentity(_ profile: WalletProfile, network: SolanaNetwork) -> String? {216 guard profile.kind != nil, let address = profile.solanaAddress else { return nil }217 return "sol|v\(SolanaChainRecord.currentVersion)|\(network.rawValue)|\(address)|" + (profile.solanaEndpoints.rpc[network.rawValue] ?? []).joined(separator: ",")218 }219220 static func tronIdentity(_ profile: WalletProfile, network: TronNetwork) -> String? {221 guard profile.kind != nil, let address = profile.tronAddress else { return nil }222 let nodes = (profile.tronEndpoints.fullNodes[network.rawValue] ?? []).joined(separator: ","), history = (profile.tronEndpoints.history[network.rawValue] ?? []).joined(separator: ",")223 return "trx|v\(TronChainRecord.currentVersion)|\(network.rawValue)|\(address)|\(nodes)|\(history)"224 }225226 // MARK: Restoring227228 /// A file written by a version that kept the snapshot of the primary EVM network, whatever it was, under the 1.0229 /// name: when it holds another chain than Ethereum it is moved to that chain's file.230 static func migrateLegacyEVMFile(fileStore: FileStore) {231 let legacy = EthereumSnapshotRecord.fileName232 guard fileStore.exists(legacy),233 let record = SyncStore.load(EthereumSnapshotRecord.self, from: fileStore, name: legacy, maximumBytes: EthereumSnapshotRecord.maximumBytes),234 record.network.family != .ethereum else { return }235 let target = EthereumSnapshotRecord.fileName(for: record.network)236 if !fileStore.exists(target) { SyncStore.save(record, to: fileStore, name: target, maximumBytes: EthereumSnapshotRecord.maximumBytes) }237 SyncStore.remove(from: fileStore, name: legacy)238 }239240 static func restoredEthereum(fileStore: FileStore, profile: WalletProfile, network: EthereumNetwork) -> EthereumSnapshot? {241 let name = EthereumSnapshotRecord.fileName(for: network)242 guard fileStore.exists(name) else { return nil }243 guard let identity = ethereumIdentity(profile, network: network),244 let record = SyncStore.load(EthereumSnapshotRecord.self, from: fileStore, name: name, maximumBytes: EthereumSnapshotRecord.maximumBytes),245 record.identity == identity, record.network == network, record.address == profile.ethereumAddress,246 MainnetPolicy.mainnetEnabled || record.network.isTest, let snapshot = record.snapshot() else {247 SyncStore.remove(from: fileStore, name: name)248 return nil249 }250 return snapshot251 }252253 static func restoredSolana(fileStore: FileStore, profile: WalletProfile, network: SolanaNetwork) -> SolanaChainRecord? {254 let name = SolanaChainRecord.fileName(network)255 guard fileStore.exists(name) else { return nil }256 guard let identity = solanaIdentity(profile, network: network), let address = profile.solanaAddress, MainnetPolicy.mainnetEnabled || network.isTest,257 let record = SyncStore.load(SolanaChainRecord.self, from: fileStore, name: name, maximumBytes: SolanaChainRecord.maximumBytes),258 record.network == network, let valid = record.validated(identity: identity, address: address) else {259 SyncStore.remove(from: fileStore, name: name)260 return nil261 }262 return valid263 }264265 static func restoredTron(fileStore: FileStore, profile: WalletProfile, network: TronNetwork) -> TronChainRecord? {266 let name = TronChainRecord.fileName(network)267 guard fileStore.exists(name) else { return nil }268 guard let identity = tronIdentity(profile, network: network), let address = profile.tronAddress, MainnetPolicy.mainnetEnabled || network.isTest,269 let record = SyncStore.load(TronChainRecord.self, from: fileStore, name: name, maximumBytes: TronChainRecord.maximumBytes),270 record.network == network, let valid = record.validated(identity: identity, address: address) else {271 SyncStore.remove(from: fileStore, name: name)272 return nil273 }274 return valid275 }276277 // MARK: Storing and forgetting278279 /// Stores the snapshot of an EVM network for the next launch. Called after every change of that snapshot.280 func persistEVMSnapshot(_ network: EthereumNetwork) {281 guard let snapshot = evmSnapshots[network], let identity = Self.ethereumIdentity(profile, network: network), usesEVM(network) else { return }282 SyncStore.save(EthereumSnapshotRecord(snapshot, identity: identity), to: fileStore, name: EthereumSnapshotRecord.fileName(for: network),283 maximumBytes: EthereumSnapshotRecord.maximumBytes)284 }285286 func persistSolana(_ network: SolanaNetwork) {287 guard let record = solanaRecords[network] else { return }288 var stored = record289 stored.isFromPreviousSession = nil290 SyncStore.save(stored, to: fileStore, name: SolanaChainRecord.fileName(network), maximumBytes: SolanaChainRecord.maximumBytes)291 }292293 func persistTron(_ network: TronNetwork) {294 guard let record = tronRecords[network] else { return }295 var stored = record296 stored.isFromPreviousSession = nil297 SyncStore.save(stored, to: fileStore, name: TronChainRecord.fileName(network), maximumBytes: TronChainRecord.maximumBytes)298 }299300 func forgetEVMSynchronization(_ network: EthereumNetwork) {301 SyncStore.remove(from: fileStore, name: EthereumSnapshotRecord.fileName(for: network))302 }303304 /// Removes every persisted snapshot of the account chains (another wallet, or none).305 func forgetAllChainSynchronization() {306 for family in EVMFamily.allCases { SyncStore.remove(from: fileStore, name: EthereumSnapshotRecord.fileName(for: EthereumNetwork.networks(of: family).main)) }307 for network in SolanaNetwork.allCases { SyncStore.remove(from: fileStore, name: SolanaChainRecord.fileName(network)) }308 for network in TronNetwork.allCases { SyncStore.remove(from: fileStore, name: TronChainRecord.fileName(network)) }309 for network in BitcoinNetwork.allCases where !Self.isPrimaryUTXO(network) { forgetUTXOCoinSynchronization(network) }310 }311312 /// Brings the in-memory and persisted state in line with the active chains, after the enabled list, the network313 /// mode or a primary network changed: what belongs to a network that is no longer active is dropped (and its file314 /// removed when the other network of the same chain took its place), and a network that became active gets back315 /// what was persisted for it, when that is still exactly its state.316 func reconcileChainState() {317 let active = Set(Self.activeKinds(profile) + [.evm(profile.ethereumNetwork)])318 for network in Array(evmSnapshots.keys) where !active.contains(.evm(network)) {319 evmSnapshots[network] = nil320 evmErrors[network] = nil321 }322 for network in Array(utxoCoinStates.keys) where !active.contains(.utxo(network)) { utxoCoinStates[network] = nil }323 for network in Array(solanaRecords.keys) where !active.contains(.solana(network)) { solanaRecords[network] = nil }324 for network in Array(tronRecords.keys) where !active.contains(.tron(network)) { tronRecords[network] = nil }325 for id in Array(chainErrors.keys) where !(ChainRegistry.kind(id).map { active.contains($0) } ?? false) { chainErrors[id] = nil }326 for id in Array(chainProgress.keys) where !(ChainRegistry.kind(id).map { active.contains($0) } ?? false) { chainProgress[id] = nil }327 for kind in active {328 switch kind {329 case .utxo(let network):330 if !Self.isPrimaryUTXO(network), utxoCoinStates[network] == nil {331 utxoCoinStates[network] = Self.restoredUTXOCoin(fileStore: fileStore, profile: profile, network: network)332 }333 case .evm(let network):334 if evmSnapshots[network] == nil { evmSnapshots[network] = Self.restoredEthereum(fileStore: fileStore, profile: profile, network: network) }335 case .solana(let network):336 if solanaRecords[network] == nil { solanaRecords[network] = Self.restoredSolana(fileStore: fileStore, profile: profile, network: network) }337 case .tron(let network):338 if tronRecords[network] == nil { tronRecords[network] = Self.restoredTron(fileStore: fileStore, profile: profile, network: network) }339 }340 }341 }342}343