SPB Git

Repository Public

PhraseQuizStep.swift 5.8 KB 140 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Onboarding/PhraseQuizStep.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 QyvoraCrypto44import QyvoraUI4546/// Verification of the written copy: four random positions, each answered by picking the word among four.47/// The checks are done locally against the words of the flow; when all pass, `onPassed` lets the service48/// record the backup as verified.49struct PhraseQuizStep: View {50    struct Question: Identifiable, Equatable {51        let position: Int52        let options: [String]53        var id: Int { position }54    }5556    let words: [String]57    let step: Int58    let stepCount: Int59    let verifying: Bool60    let error: String?61    let onBack: () -> Void62    let onPassed: () -> Void6364    @State private var questions: [Question] = []65    @State private var current = 066    @State private var wrong = 067    @State private var message: String?6869    static let questionCount = 47071    var body: some View {72        OnboardingScaffold(title: "Check your copy", step: step, stepCount: stepCount, onClose: nil) {73            if current < questions.count {74                let question = questions[current]75                Text("Question \(current + 1) of \(questions.count)")76                    .font(QFont.caption).foregroundStyle(QColor.textSecondary)77                Text("Which word is number \(question.position + 1)?")78                    .font(QFont.title).foregroundStyle(QColor.textPrimary)79                VStack(spacing: 10) {80                    ForEach(question.options, id: \.self) { option in81                        Button { answer(option, question) } label: {82                            Text(option).font(.system(.body, design: .monospaced).weight(.medium))83                                .frame(maxWidth: .infinity, minHeight: 28)84                        }85                        .buttonStyle(.qSecondary)86                        .privacySensitive()87                    }88                }89                InlineError(message: message)90            } else if !questions.isEmpty {91                Label("All \(questions.count) words match.", systemImage: "checkmark.circle")92                    .font(QFont.headline).foregroundStyle(QColor.positive)93                if verifying {94                    HStack(spacing: 10) {95                        ProgressView().controlSize(.small)96                        Text("Recording the verification").font(QFont.callout).foregroundStyle(QColor.textSecondary)97                    }98                }99                InlineError(message: error)100                if error != nil {101                    Button("Try again", action: onPassed).buttonStyle(.qSecondary)102                }103            }104        } footer: {105            Button("Show the words again", action: onBack).buttonStyle(.qSecondary).disabled(verifying)106        }107        .sensoryFeedback(.error, trigger: wrong)108        .sensoryFeedback(.success, trigger: current)109        .onAppear {110            if questions.isEmpty { questions = Self.makeQuestions(words: words) }111        }112        .onDisappear { questions = [] }113    }114115    func answer(_ option: String, _ question: Question) {116        guard question.position < words.count else { return }117        if option == words[question.position] {118            message = nil119            current += 1120            if current == questions.count { onPassed() }121        } else {122            wrong += 1123            message = "That is not word number \(question.position + 1). Check your written copy."124        }125    }126127    /// Distinct random positions in ascending order; each with the right word and three other words of the list.128    static func makeQuestions(words: [String]) -> [Question] {129        guard words.count >= questionCount else { return [] }130        let list = BIP39.wordList131        // the engine's generator, like everything else that is drawn at random in the wallet132        let positions = Array(SystemRandom.permutation(of: Array(words.indices)).prefix(questionCount)).sorted()133        return positions.map { position in134            var options: Set<String> = [words[position]]135            while options.count < 4, !list.isEmpty { options.insert(list[SystemRandom.uniform(below: list.count)]) }136            return Question(position: position, options: SystemRandom.permutation(of: options.sorted()))137        }138    }139}140
Files main
Menu

Theme