Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/Wallet/DebugWalletLaunch.swift8// Module : Wallet9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//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// =============================================================================4041#if DEBUG42import SwiftUI43import QyvoraNetworking44import QyvoraCore45import QyvoraWallet4647/// DEBUG-only launch arguments of the wallet screens (screenshots, UI review). Not compiled in Release.48/// Everything here drives the real wallet service: no balance, price or transaction is made up.49///50/// -QYDebugWallet <a,b,…> performed in order before the first screen:51/// reset deletes the wallet of this installation52/// create creates a wallet with a throwaway password (if none exists)53/// import restores the public BIP-39 test vector "abandon … about" (if none exists)54/// watch watch-only wallet of public test accounts (if none exists): that vector's BIP-8455/// test account (Signet), 0xf39F…2266 (every EVM test network), the Solana devnet56/// faucet account and a public TRON Nile address;57/// -QYDebugXpub / -QYDebugEth / -QYDebugSol / -QYDebugTron override the values58/// ("none" leaves a family out)59/// chains:<id+id+…> enables exactly these chains (main identifiers: bitcoin, litecoin,60/// dogecoin, bitcoin-cash, ethereum, base, arbitrum, optimism, polygon, bsc,61/// avalanche, solana, tron) ; allchains enables the thirteen62/// unlock unlocks with the throwaway password63/// pin enables the PIN 730915 (vault must be unlocked)64/// lock locks the vault65/// cold / online switches cold mode on / off66/// unreachable / reachable points the endpoints at a domain that cannot resolve (the67/// synchronization really fails) / restores the built-in endpoints68/// -QYScrollTo <id> wallet: sync | assets | bottom ; chain: price | tokens | family | activity | exposure | account69/// -QYScreen <name> wallet | networks | more | scan | import-signed | receive | send | activity | tx-detail70/// | chain | chain-add-token | chain-activity | token | coins | addresses | auth71/// | onboarding-create | onboarding-import | onboarding-watch | onboarding-restore | locked | startup-error72/// -QYChain <chain id> chain, chain-*, token, coins, addresses, receive, send, tx-detail: the chain, by its73/// identifier ("ethereum-sepolia") or by its main identifier ("ethereum": the network of the74/// current mode). Without it receive and send open their pickers.75/// -QYToken <address> token: the token shown ; send: the token sent76/// -QYListing <networks|assets> dashboard listing77/// -QYScanText <text> scan: resolves this text as if it had been scanned78/// -QYStep <name> onboarding-create: password | password-weak | phrase | quiz | protect | pin | chains | done79/// onboarding-watch: filled | package (the comparison step of a scanned watch-only package,80/// for a package of public test accounts) | package-typed (the same with the last group81/// typed and the comparison ticked, as a user would)82/// onboarding-import: filled | password | run (performs the import) ; onboarding-watch: filled83/// onboarding-restore: backup | transfer (opens that restore screen)84/// -QYSendTo <address> -QYSendAmount <decimal> -QYSendMax YES -QYSendTier <slow|normal|fast> -QYSendMemo <text>85/// -QYSendReview YES -QYSendExport YES86/// send: fills the form, then builds the review with the service (and the export)87/// -QYUnlockWith <pin|wrong-pin|password|wrong-password> locked: submits that credential88/// -QYFilter <All|Tokens|Pending|Failed|chain id> activity filter89/// -wallet.hideAmounts YES privacy toggle90/// -QYDebugTour YES keeps one launch (and its synchronization) for several screens: the app polls91/// Documents/qy-debug-command.txt in its data container; each line is `key=value` with the92/// keys above without the dash (QYScreen=chain). A changed file re-opens that screen.93/// A key given as a launch argument wins over the file: launch a tour without -QYScreen.94/// QYAction=sync | sync-chain (with QYChain) runs a real synchronization first.95extension DebugLaunch {96 /// Protects nothing of value: wallets created with it exist only on a development simulator.97 static let throwawayPassword = "debug-only throwaway passphrase 2026"98 static let throwawayPIN = "730915"99 /// Why the last debug action failed, for the debugger (nothing is written to the console or to a file).100 nonisolated(unsafe) static var lastFailure: String?101 /// BIP-39 test vector (all-zero entropy). Public knowledge: never holds funds that stay.102 static let testVectorWords = Array(repeating: "abandon", count: 11) + ["about"]103 /// Account key of that vector at m/84'/1'/0' (BIP-84 test vector, SLIP-132 "vpub" form).104 static let testVectorAccountKey = "vpub5Y6cjg78GGuNLsaPhmYsiw4gYX3HoQiRBiSwDaBXKUafCt9bNwWQiitDk5VZ5BVxYnQdwoTyXSs2JHRPAgjAvtbBrf8ZhDYe2jWAqvZVnsc"105 static let testVectorFingerprint = "73c5da0a"106 /// First account of the public "test test … junk" development mnemonic.107 static let testVectorEthereumAddress = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"108 /// The faucet account of Solana devnet: a public system account with a balance and a history.109 static let publicSolanaAddress = "9B5XszUGdMaxCZ7uSQhPzdks5ZQSmWxrmzCSvtJ6Ns6g"110 /// A public address of the TRON Nile test network.111 static let publicTronAddress = "TKHuVq1oKVruCGLvqVexFs6dawKv6fQgFs"112 /// A watch-only package of those three public accounts, as a cold device would write it (`-QYStep package`):113 /// the comparison screen of the watch-only flow is then shown for it, exactly as after a scan.114 static var publicWatchOnlyPackage: String {115 "{\"format\":\"qyvora-watch-only\",\"version\":2,\"ethereumAddress\":\"\(testVectorEthereumAddress)\",\"solanaAddress\":\"\(publicSolanaAddress)\",\"tronAddress\":\"\(publicTronAddress)\"}"116 }117118 static var onboardingPath: OnboardingPath? {119 switch screen {120 case "onboarding-create": return .create121 case "onboarding-import": return .importPhrase122 case "onboarding-watch": return .watchOnly123 case "onboarding-restore": return .restore124 default: return nil125 }126 }127128 static var onboardingStep: String? { defaults.string(forKey: "QYStep") }129130 static let walletScreens: Set<String> = ["wallet", "networks", "more", "scan", "import-signed", "receive", "send", "activity", "tx-detail", "chain",131 "chain-add-token", "chain-activity", "token", "coins", "addresses", "auth", "locked", "startup-error",132 "boot", "selftest-failed", "privacy-cover", "shield"]133134 /// Screens that exist without a wallet keep their fixed route; wallet screens follow the real wallet state.135 static var forcedRoute: AppRoute? {136 guard let screen else { return nil }137 if screen.hasPrefix("onboarding") { return .onboarding }138 return walletScreens.contains(screen) ? nil : .main139 }140141 /// `-QYChain`, as given. The screens resolve a main identifier to the network of the current mode.142 static var chain: ChainID? { defaults.string(forKey: "QYChain").map { ChainID($0) } }143 static var tokenAddress: String? { defaults.string(forKey: "QYToken") }144145 static var initialWalletPath: NavigationPath {146 var path = NavigationPath()147 guard let chain else { return path }148 switch screen {149 case "chain", "chain-add-token": path.append(WalletRoute.chain(chain))150 case "token":151 path.append(WalletRoute.chain(chain))152 if let tokenAddress { path.append(WalletRoute.token(chain: chain, address: tokenAddress)) }153 case "coins":154 path.append(WalletRoute.chain(chain))155 path.append(WalletRoute.coins(chain))156 case "addresses":157 path.append(WalletRoute.chain(chain))158 path.append(WalletRoute.addresses(chain))159 case "chain-activity":160 path.append(WalletRoute.chain(chain))161 path.append(WalletRoute.activity(chain))162 default: break163 }164 return path165 }166167 static var initialWalletSheet: WalletSheet? {168 switch screen {169 case "receive": return .receive(chain)170 case "send": return .send(SendPrefill(chain: chain, tokenAddress: tokenAddress))171 case "scan": return .scan172 case "networks": return .networks173 case "more": return .more174 case "import-signed": return .importSigned175 default: return nil176 }177 }178179 static var sendRecipient: String? { defaults.string(forKey: "QYSendTo") }180 static var sendAmount: String? { defaults.string(forKey: "QYSendAmount") }181 static var sendMax: Bool { defaults.bool(forKey: "QYSendMax") }182 static var sendReview: Bool { defaults.bool(forKey: "QYSendReview") }183 static var sendExport: Bool { defaults.bool(forKey: "QYSendExport") }184185 /// Applies `-QYDebugWallet` through the real service. Failures are printed (they never contain a secret).186 @MainActor187 static func prepareWallet(_ store: WalletStore) async {188 DebugNavigator.shared.start()189 defer { DebugNavigator.shared.walletPrepared = true }190 guard let actions = defaults.string(forKey: "QYDebugWallet"), let service = store.service else { return }191 for action in actions.split(separator: ",").map(String.init) {192 do {193 let exists = await service.currentProfile().kind != nil194 switch action {195 case "reset": if exists { try await service.deleteWallet() }196 case "create": if !exists { _ = try await service.createWallet(password: throwawayPassword) }197 case "import": if !exists { try await service.importWallet(words: testVectorWords, password: throwawayPassword) }198 case "watch":199 if !exists {200 func value(_ key: String, _ fallback: String) -> String? {201 let given = defaults.string(forKey: key)202 return given == "none" ? nil : (given ?? fallback)203 }204 let fingerprint = defaults.string(forKey: "QYDebugXpub") == nil ? testVectorFingerprint : nil205 try await service.importWatchOnly(bitcoinExtendedPublicKey: value("QYDebugXpub", testVectorAccountKey),206 ethereumAddress: value("QYDebugEth", testVectorEthereumAddress), masterFingerprint: fingerprint,207 solanaAddress: value("QYDebugSol", publicSolanaAddress), tronAddress: value("QYDebugTron", publicTronAddress))208 }209 case "allchains": try await service.setEnabledChains(ChainRegistry.mainChains.map(\.id))210 case let list where list.hasPrefix("chains:"):211 try await service.setEnabledChains(list.dropFirst(7).split(separator: "+").map { ChainID(String($0)) })212 case "unlock": try await service.unlock(password: throwawayPassword)213 case "pin": try await service.enablePIN(throwawayPIN)214 case "lock": await service.lock()215 case "cold": try await service.setColdMode(true)216 case "online": try await service.setColdMode(false)217 case "unreachable":218 // endpoints on the reserved .invalid domain: every synchronization really fails (failure states)219 try await service.setEndpoints(EndpointConfiguration(220 esplora: ["signet": ["https://esplora.qyvora.invalid/api"]], ethereumRPC: ["sepolia": ["https://rpc.qyvora.invalid"]],221 ethereumIndexer: [:], priceAPI: ""))222 case "reachable": try await service.resetEndpoints()223 default: lastFailure = "unknown action \(action)"224 }225 } catch {226 lastFailure = "\(action): \(WalletStore.message(for: error))"227 }228 }229 await store.refresh()230 }231}232233/// `-QYDebugTour YES`: applies the commands written to Documents/qy-debug-command.txt (see `DebugLaunch`).234@MainActor235@Observable236final class DebugNavigator {237 static let shared = DebugNavigator()238 /// Incremented each time a new command was applied to the defaults; screens observe it and re-open.239 private(set) var serial = 0240 /// True once `-QYDebugWallet` has been applied: flows that fast-forward wait for it.241 var walletPrepared = false242 private var last: String?243 private var task: Task<Void, Never>?244245 nonisolated static let keys = ["QYAction", "QYScreen", "QYStep", "QYSendTo", "QYSendAmount", "QYSendMax", "QYSendReview", "QYSendExport", "QYSendTier", "QYSendMemo",246 "QYChain", "QYToken", "QYListing", "QYScanText", "QYFilter", "QYScrollTo", WalletPreference.hideAmounts]247248 /// Removes command values a previous tour left in the persistent defaults, then starts polling when asked to.249 func waitUntilWalletPrepared() async {250 while !walletPrepared { try? await Task.sleep(for: .milliseconds(100)) }251 }252253 /// Removes the command values a previous tour left in the persistent defaults (launch arguments are untouched:254 /// they live in another domain). Called before the first screen is chosen, so that no route, tab or path of a255 /// launch is ever computed from the commands of the previous one.256 nonisolated static func clearStaleCommands() {257 let defaults = UserDefaults.standard258 for key in keys where key != WalletPreference.hideAmounts { defaults.removeObject(forKey: key) }259 }260261 func start() {262 let defaults = UserDefaults.standard263 Self.clearStaleCommands()264 guard defaults.bool(forKey: "QYDebugTour"), task == nil,265 let file = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appending(path: "qy-debug-command.txt") else { return }266 task = Task {267 while !Task.isCancelled {268 if let text = try? String(contentsOf: file, encoding: .utf8), text != last {269 last = text270 for key in Self.keys { defaults.removeObject(forKey: key) }271 for line in text.split(whereSeparator: \.isNewline) {272 let parts = line.split(separator: "=", maxSplits: 1).map(String.init)273 if parts.count == 2, Self.keys.contains(parts[0]) { defaults.set(parts[1], forKey: parts[0]) }274 }275 serial += 1276 }277 try? await Task.sleep(for: .milliseconds(400))278 }279 }280 }281}282283/// `-QYScreen tx-detail`: pushes the first transaction of the synchronized history on the Activity stack.284struct DebugOpenFirstTransaction: ViewModifier {285 @Binding var path: NavigationPath286 @Environment(WalletStore.self) private var wallet287288 func body(content: Content) -> some View {289 content.task(id: DebugNavigator.shared.serial) {290 path = NavigationPath()291 guard DebugLaunch.screen == "tx-detail" else { return }292 let chain = DebugLaunch.defaults.string(forKey: "QYChain")293 for _ in 0..<240 {294 if let snapshot = wallet.snapshot,295 let item = ActivityItem.all(snapshot).first(where: { chain == nil || $0.chain.id.rawValue == chain || $0.chain.mainCounterpart.rawValue == chain }) {296 path.append(item.route)297 return298 }299 try? await Task.sleep(for: .milliseconds(500))300 }301 }302 }303}304305extension View {306 func debugOpenFirstTransaction(path: Binding<NavigationPath>) -> some View { modifier(DebugOpenFirstTransaction(path: path)) }307}308#endif309