SPB Git

Repository Public

CreateWalletFlow.swift 10.8 KB 246 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Onboarding/CreateWalletFlow.swift8// Module           : Onboarding9// 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// =============================================================================4041import SwiftUI42import QyvoraCore43import QyvoraWallet44import QyvoraUI4546/// Creation of a new wallet: explanation, master password, the 24 words shown once, a verification quiz,47/// optional quick unlock. The words live in this view's state only between creation and verification.48struct CreateWalletFlow: View {49    enum Step: Int { case explain, password, phrase, quiz, protect, chains, done }5051    let onClose: () -> Void5253    @Environment(WalletStore.self) private var wallet54    @Environment(\.isSceneCaptured) private var isCaptured55    @State private var step: Step = .explain56    @State private var password = ""57    @State private var confirmation = ""58    @State private var passphrase = ""59    @State private var words: [String] = []60    @State private var creating = false61    @State private var error: String?62    @State private var verifying = false63    @State private var screenshotTaken = false64    @State private var debugStartsWithPIN = false65    @State private var debugStarted = false6667    private let stepCount = 76869    var body: some View {70        // One container view, not a Group: a Group would hand `onDisappear` to each step, clearing the words71        // at every step change instead of when the flow goes away.72        ZStack {73            switch step {74            case .explain: explain75            case .password: passwordStep76            case .phrase: phraseStep77            case .quiz:78                PhraseQuizStep(words: words, step: step.rawValue, stepCount: stepCount, verifying: verifying, error: error,79                               onBack: { step = .phrase }, onPassed: verifyBackup)80            case .protect:81                ProtectStep(step: step.rawValue, stepCount: stepCount, startWithPIN: debugStartsWithPIN) { step = .chains }82            case .chains:83                OnboardingChainsStep(step: step.rawValue, stepCount: stepCount) { step = .done }84            case .done:85                OnboardingDoneStep(title: "Your wallet is ready", lines: [86                    "It starts on test networks: coins there have no value and are meant for trying things out.",87                    "More networks can be enabled at any time from the wallet (Manage networks); the same phrase covers them all.",88                    "The recovery phrase is the only way to restore this wallet. QYVORA cannot recover it for you.",89                ], step: step.rawValue, stepCount: stepCount, onFinish: onClose)90            }91        }92        .onDisappear(perform: clearSecrets)93        .warnsAboutScreenshots(of: step == .phrase && !words.isEmpty, taken: $screenshotTaken)94        #if DEBUG95        .task { await debugFastForward() }96        #endif97    }9899    // MARK: Steps100101    var explain: some View {102        OnboardingScaffold(title: "Create a new wallet", step: 0, stepCount: stepCount, onClose: onClose) {103            OnboardingPoint(systemImage: "key.horizontal", title: "A master password",104                            text: "It encrypts the vault that holds your keys on this device. It is asked when quick unlock is not available, and it cannot be reset.")105            OnboardingPoint(systemImage: "list.number", title: "A 24-word recovery phrase",106                            text: "Generated on this device and shown once. Written on paper, it restores the wallet anywhere. Anyone who reads it controls the funds.")107            OnboardingPoint(systemImage: "point.3.connected.trianglepath.dotted", title: "One phrase for every network",108                            text: OnboardingChains.onePhrase + " Covered: " + OnboardingChains.names + ".")109            OnboardingPoint(systemImage: "checklist", title: "A short verification",110                            text: "You confirm a few words so that a copying mistake is caught now, not on the day you need the phrase.")111            WarningBanner(.info, message: "Prepare paper and a pen, and make sure nobody and no camera can see this screen.")112        } footer: {113            Button("Continue") { step = .password }.buttonStyle(.qPrimary)114        }115    }116117    var passwordStep: some View {118        OnboardingScaffold(title: "Master password", step: 1, stepCount: stepCount, onClose: creating ? nil : onClose) {119            Text("Choose a password you do not use anywhere else. A sentence of several unrelated words is both strong and memorable.")120                .font(QFont.callout).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)121            NewPasswordForm(password: $password, confirmation: $confirmation)122            PassphraseDisclosure(passphrase: $passphrase, isImport: false)123            InlineError(message: error)124        } footer: {125            LoadingButton("Create the wallet", loadingTitle: "Creating the vault", state: creating ? .loading : .idle) { create() }126                .disabled(!passwordAccepted || creating)127        }128    }129130    var phraseStep: some View {131        OnboardingScaffold(title: "Write down these 24 words", step: 2, stepCount: stepCount, onClose: nil) {132            Text("In this order, on paper. Do not photograph them, do not store them in a file, a note or a message.")133                .font(QFont.callout).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)134            CompromisedDeviceNotice()135            if screenshotTaken {136                WarningBanner(.critical, title: ScreenshotWarning.title, message: ScreenshotWarning.message)137            }138            if isCaptured {139                WarningBanner(.critical, title: "The screen is being recorded or mirrored",140                              message: "The words are hidden. Stop the recording, screen sharing or AirPlay to display them.")141            } else {142                SeedPhraseGrid(words: words, protected: true)143            }144            WarningBanner(.warning, message: "Screenshots and screen recordings of this page would contain your keys. The words cannot be copied and are not shown again here.")145        } footer: {146            Button("I wrote them down") { step = .quiz }147                .buttonStyle(.qPrimary)148                .disabled(isCaptured || words.isEmpty)149        }150    }151152    // MARK: Actions153154    var passwordAccepted: Bool {155        NewPasswordForm.problem(password: password, confirmation: confirmation,156                                estimate: password.isEmpty ? nil : wallet.service?.passwordQuality(password)) == nil157    }158159    func create() {160        guard passwordAccepted, !creating else { return }161        creating = true162        error = nil163        let chosen = password, extra = passphrase.isEmpty ? nil : passphrase164        Task {165            defer { creating = false }166            do {167                let generated = try await wallet.run { try await $0.createWallet(password: chosen, passphrase: extra) }168                password = ""169                confirmation = ""170                passphrase = ""171                words = generated172                step = .phrase173            } catch {174                self.error = WalletStore.message(for: error)175            }176        }177    }178179    /// The quiz was answered from the words shown: the service records the backup as verified.180    func verifyBackup() {181        guard !verifying else { return }182        verifying = true183        error = nil184        let confirmed = words185        Task {186            defer { verifying = false }187            do {188                let matches = try await wallet.run { try await $0.verifyPhraseBackup(words: confirmed) }189                guard matches else {190                    error = "The words do not match the stored phrase."191                    return192                }193                words = []194                step = .protect195            } catch {196                self.error = WalletStore.message(for: error)197            }198        }199    }200201    func clearSecrets() {202        password = ""203        confirmation = ""204        passphrase = ""205        words = []206    }207208    #if DEBUG209    /// `-QYStep <name>`: reaches a step through the same service calls as the buttons (screenshots).210    func debugFastForward() async {211        guard let target = DebugLaunch.onboardingStep, step == .explain, !debugStarted else { return }212        debugStarted = true213        await DebugNavigator.shared.waitUntilWalletPrepared()214        switch target {215        case "password":216            password = DebugLaunch.throwawayPassword217            step = .password218        case "password-weak":219            password = "abc12345"220            step = .password221        case "phrase", "quiz", "protect", "pin", "chains", "done":222            let generated: [String]223            do {224                generated = try await wallet.run { try await $0.createWallet(password: DebugLaunch.throwawayPassword) }225            } catch {226                self.error = WalletStore.message(for: error)227                step = .password228                return229            }230            words = generated231            switch target {232            case "phrase": step = .phrase233            case "quiz": step = .quiz234            case "done": words = []; step = .done235            case "chains": words = []; step = .chains236            default:237                words = []238                debugStartsWithPIN = target == "pin"239                step = .protect240            }241        default: break242        }243    }244    #endif245}246
Files main
Menu

Theme