Repository navigation
feat(wallet): harden the DashPay invitation claim flow - #927
Conversation
Claiming an Android-issued invitation on iOS ran into four separate gaps, all of which surfaced only on device: - AppsFlyer wraps OneLinks on several hosts, but the normalizer allowed exactly two, so a valid link read as "not an invitation". Match any onelink.me / appsflyersdk.com / appsflyer.com host instead of an allowlist of two. - The "Have an invitation?" entry point was conditional and effectively never visible; it is now always offered from the JoinDashPay screen. - A voucher that had already funded an identity was only discovered at the very end of registration, as a raw SDK "asset lock ... already completely used". The Continue button now asks Platform for an identity by the voucher's public key hash and stops there with a readable message. An inconclusive answer proceeds — a network hiccup must not block a good invitation. - The contact request to the inviter was sent against a stale identity snapshot taken seconds earlier; refresh from the SDK and reconcile the recovered identity first. Also fixes a priority inversion: NetworkReachability's queue ran at .utility while user-interactive callers waited on it.
…ntity The first attempt asked Platform for an identity under the hash of the voucher's public key. That was wrong: an invitee registers an identity with their OWN keys — the voucher key only signs the asset-lock proof and never becomes an identity key. The lookup therefore missed on a demonstrably spent voucher (notFound "No data returned"), the check passed, and registration still died on "asset lock ... already completely used". Platform derives a created identity's id from the asset-lock outpoint, so the id an invitation would produce is knowable before the claim. Ask the SDK for it (new platform_wallet_invitation_prospective_identity_id, which refetches the funding tx to locate the credit output the voucher controls) and fetch the identity under that id — an existing identity is exactly the "already used" signal. Unchanged: any failure is undetermined and proceeds. An unclaimed invitation is expected to miss, and a miss is indistinguishable from a transport error at this layer.
The screen had no way back: it is pushed as a bare UIHostingController, and the app carries a retroactive `UIHostingController: NavigationBarDisplayable` conformance that reports both the navigation bar and its back button as hidden. So a pushed SwiftUI screen gets neither unless it draws its own — which the sibling DashPay screens do. Draw the same circular chevron `JoinDashPayReadinessScreen` uses for its close button, wired to popViewController.
…creen Replaces the hand-rolled circular chevron with `NavigationBar(leading: NavigationBarElement.back.button)`, so the screen picks up the shared 64pt bar, press animation and dark-mode icon instead of a one-off copy. Body split into the bar plus a `content` view so the bar keeps its own 20pt inset rather than inheriting the content padding.
It was a bare SwiftUI Button with footnote-sized blue text, so an entry point that bypasses the whole funding checklist read as a caption. Use the shared DashButton in its tintedBlue style: still visibly secondary to the filled Continue, but a real button with the app's sizing, hit area and pressed state.
The check logged only its failure path, so a positive verdict left no trace: the screen says "already used" and the log says nothing, making the verdict unauditable from a bug report. Log the verdict together with the prospective identity id, which is the whole basis for it.
The sheet drew a hardcoded blue circle with the username's first letter and never looked at the profile's avatar at all — there was no image path in it to fail, so a user with a picture set still saw initials. It now uses `ContactAvatarView`, the app's single avatar path: the remote image when the profile has one, otherwise the deterministic placeholder whose colour matches Android. The owner's own profile therefore renders the same here as it does in contacts and notifications. Visible side effect for users with no picture: the placeholder is no longer always blue, it takes the per-letter colour the rest of the app already uses.
…validation Two regressions from the earlier QA-fix batch, both on the typing path. `checkBalance()` called `feeAwareMaxSendable()`, whose reserve estimate walks the account's entire UTXO set over the FFI on the main actor — and validation runs on every throttled keystroke. That is what made the field feel unresponsive: it was never disabled, the main actor was just busy. The value is now cached and recomputed from the balance publisher, the only moment it can actually change. The locked-contest check was chained after the availability check, so "Validating username…" waited for the sum of two DAPI round trips on every contested-eligible name — which is most of them. They answer independent questions about the same label, so they now run concurrently and the wait is the slower of the two. Neither changes what the form decides; the remaining latency is DAPI's own.
|
Warning Review limit reached
Next review available in: 36 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThe change expands invitation link recognition, adds voucher claim checks, updates DashPay entry points, caches username-validation balances, renders identity avatars, changes reachability startup behavior, and scopes contested-name bookmarks by wallet. ChangesInvitation redemption flow
Username setup
Identity profile
Reachability startup
Contested-name bookmark storage
Estimated code review effort: 3 (Moderate) | ~30 minutes Sequence Diagram(s)sequenceDiagram
participant User
participant ClaimInvitationScreen
participant DWInvitationService
participant DashSDK
User->>ClaimInvitationScreen: Tap Continue
ClaimInvitationScreen->>DWInvitationService: Check voucher claim status
DWInvitationService->>DashSDK: Query prospective identity
DashSDK-->>DWInvitationService: Return identity result
DWInvitationService-->>ClaimInvitationScreen: Return claim status
ClaimInvitationScreen-->>User: Show feedback or continue to username setup
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
DashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swift (1)
19-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the redundant state initializers flagged by SwiftLint.
Use implicit
nilinitialization foravatarURLand infer the type ofidentitySeed.Proposed cleanup
- `@State` private var avatarURL: String? = nil + `@State` private var avatarURL: String? ... - `@State` private var identitySeed: Data = Data() + `@State` private var identitySeed = Data()🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@DashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swift` around lines 19 - 24, Remove the explicit nil initializer from the avatarURL state declaration and let its optional type provide the default value. Update identitySeed to use type inference with its empty Data default while preserving the existing state behavior.Source: Linters/SAST tools
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@DashWallet/Sources/Infrastructure/Networking/NetworkReachability.swift`:
- Around line 28-35: Update the startup flow using NetworkReachability’s
startMonitoring so the main-thread caller does not synchronously wait for the
initial path update; dispatch monitoring startup asynchronously or perform it
off the main thread. Keep the reachability queue at the minimum QoS needed for
path updates rather than raising it to mask the wait.
In `@DashWallet/Sources/UI/DashPay/Invitations/ClaimInvitationScreen.swift`:
- Around line 127-135: Update continueIfUnclaimed to run the claim check in an
owning cancellable task tied to the active screen, cancelling it when input
changes, Back is selected, or the screen disappears. After await
service.isVoucherAlreadyClaimed, guard that the task is still active and
normalizedURI still equals the captured uri before mutating state or calling
proceed.
In
`@DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift`:
- Around line 122-130: Update the CreateUsernameViewModel flow so
coreSpendableDuffs is recalculated from the current UTXO state before
Core-funded eligibility checks and registration submission, not only during
initialization or balance updates. Ensure UTXO reservation, release, and
same-value set changes invalidate the cached value while preserving the existing
fee-aware calculation.
---
Nitpick comments:
In `@DashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swift`:
- Around line 19-24: Remove the explicit nil initializer from the avatarURL
state declaration and let its optional type provide the default value. Update
identitySeed to use type inference with its empty Data default while preserving
the existing state behavior.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 1a1006a8-697c-4b34-a144-d4bf22d54d18
📒 Files selected for processing (9)
DashWallet/Sources/Infrastructure/Networking/NetworkReachability.swiftDashWallet/Sources/Infrastructure/SwiftDashSDK/Invitations/DWInvitationLinkNormalizer.swiftDashWallet/Sources/Infrastructure/SwiftDashSDK/Invitations/DWInvitationService.swiftDashWallet/Sources/UI/DashPay/Invitations/ClaimInvitationScreen.swiftDashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swiftDashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swiftDashWallet/Sources/UI/DashPay/Setup/CreateUsername/JoinDashPayReadinessScreen.swiftDashWallet/Sources/UI/Home/HomeViewController+Shortcuts.swiftDashWallet/Sources/UI/Menu/Main/MainMenuViewController.swift
| /// `.userInitiated`, not `.utility`, because `startMonitoring` blocks its | ||
| /// caller on the first path update delivered here. That caller is the main | ||
| /// thread at launch (`SyncingActivityMonitor`), so a lower-QoS queue makes | ||
| /// a user-interactive thread wait on utility work — the priority inversion | ||
| /// the Thread Performance Checker flags. Matching the QoS to the highest | ||
| /// waiter removes it; the ongoing updates this queue also serves are cheap | ||
| /// enough that the higher class costs nothing. | ||
| private let queue = DispatchQueue(label: "org.dash.reachability", qos: .userInitiated) |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 8 \
'startNetworkMonitoring|`@objc` func startMonitoring|firstUpdate\.wait|org\.dash\.reachability' \
'DashWallet/Sources/Application/Syncyng Activity Monitor/SyncingActivityMonitor.swift' \
'DashWallet/Sources/Infrastructure/Networking/NetworkReachability.swift'Repository: dashpay/dashwallet-ios
Length of output: 10297
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- NetworkReachability structure and implementation ---'
ast-grep outline 'DashWallet/Sources/Infrastructure/Networking/NetworkReachability.swift'
sed -n '1,115p' 'DashWallet/Sources/Infrastructure/Networking/NetworkReachability.swift'
printf '%s\n' '--- All monitoring entry points and callers ---'
rg -n -C 10 \
'startNetworkMonitoring|startMonitoring\(\)|NetworkReachability|SyncingActivityMonitor\.(shared|init)|initializeReachibility' \
'DashWallet/Sources'Repository: dashpay/dashwallet-ios
Length of output: 50379
🌐 Web query:
Apple NWPathMonitor start queue DispatchQueue QoS pathUpdateHandler semaphore priority inversion Thread Performance Checker
💡 Result:
When using NWPathMonitor, you must provide a DispatchQueue to the start(queue:) method [1][2]. The pathUpdateHandler will execute on that specific queue, not the main thread [3]. To avoid Thread Performance Checker warnings and potential priority inversion: 1. Maintain Separation of Concerns: The queue provided to start(queue:) should be a dedicated background queue [1][2]. Do not use the main queue directly for path monitoring unless your application's architecture specifically requires it, as network monitoring work should generally remain off the main thread [3]. 2. Offload Main Thread Work: If the pathUpdateHandler needs to update UI or state held on the @MainActor, you must explicitly hop to the main queue or use Swift Concurrency (e.g., Task { @MainActor in... }) [3]. Updating UI directly from the background monitor queue will trigger warnings and potential threading issues [3]. 3. Understand Priority Inversion: The Thread Performance Checker warns when high-priority threads (like the main thread) wait on lower-priority threads [4][5]. Priority inversion often occurs when using synchronous primitives (like dispatch_semaphore_wait) [5]. Since NWPathMonitor's pathUpdateHandler is asynchronous, avoid introducing synchronous blocking inside this handler [4][5]. If you must perform blocking operations, ensure the threads involved have compatible QoS levels, or ideally, refactor to remove the synchronous wait entirely [4][5]. 4. Proper Lifecycle Management: NWPathMonitor is not automatically cleaned up if it goes out of scope [2]. Ensure you call monitor.cancel in your deinit or when monitoring is no longer required to prevent memory leaks and dangling handlers [3]. 5. Usage Warning: Apple recommends using NWPathMonitor in an advisory capacity only [6]. Do not use it to preflight or block user operations, as it can report false positives (claiming connectivity when none exists) or false negatives [6]. For modern Swift applications, NWPathMonitor also conforms to AsyncSequence in newer OS versions, allowing you to iterate over network paths using for await path in monitor, which handles much of the threading boilerplate automatically [7].
Citations:
- 1: https://useyourloaf.com/blog/network-path-monitoring/
- 2: https://www.hackingwithswift.com/example-code/networking/how-to-check-for-internet-connectivity-using-nwpathmonitor
- 3: https://rorklab.net/en/articles/app-dev/rork-max-nwpathmonitor-offline-detection-reconnect-retry-design
- 4: https://forums.swift.org/t/xcode-14-beta-thread-performance-checker/57883
- 5: https://apple-docs.everest.mt/docs/xcode/diagnosing-performance-issues-early/
- 6: https://developer.apple.com/forums/thread/784268
- 7: https://stackoverflow.com/questions/74221389/use-nwpathmonitor-with-swift-modern-concurrency-asyncstream-vs-gcd-dispatchqu
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- Reachability protocol and startNetworkMonitoring implementation ---'
rg -n -C 12 \
'protocol NetworkReachabilityHandling|extension NetworkReachabilityHandling|func startNetworkMonitoring|func stopNetworkMonitoring|reachabilityObserver' \
'DashWallet/Sources'
printf '%s\n' '--- Direct SyncingActivityMonitor singleton references ---'
rg -n -C 5 \
'SyncingActivityMonitor\.shared|SyncingActivityMonitor\(' \
'DashWallet/Sources'
printf '%s\n' '--- Direct NetworkReachability start calls ---'
rg -n -C 5 \
'NetworkReachability\.shared\.startMonitoring|reachability\.startMonitoring\(\)|\.startMonitoring\(\)' \
'DashWallet/Sources' \
-g '*.swift' | head -n 240Repository: dashpay/dashwallet-ios
Length of output: 50378
Remove the synchronous startup wait from the main-thread path.
startMonitoring() can block its caller for 200 ms. .userInitiated remains below the main thread’s .userInteractive QoS, so a main-thread caller can still wait on lower-QoS monitoring work. Start monitoring asynchronously, or move the synchronous wait off the main thread. Keep the monitor queue at the minimum QoS required for path updates.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@DashWallet/Sources/Infrastructure/Networking/NetworkReachability.swift`
around lines 28 - 35, Update the startup flow using NetworkReachability’s
startMonitoring so the main-thread caller does not synchronously wait for the
initial path update; dispatch monitoring startup asynchronously or perform it
off the main thread. Keep the reachability queue at the minimum QoS needed for
path updates rather than raising it to mask the wait.
… device Submit a contested username, reset the wallet mid-vote, create a new one — and the new wallet still reported the previous wallet's name as being in voting. Two causes, both device-scoped state outliving the wallet that produced it: - The bookmark's UserDefaults keys were scoped by network only, so any wallet on that network read whatever the last one wrote. They now carry the active wallet id, the same scoping primitive `DWGlobalOptions` already uses for its per-wallet flags. With no active wallet the read answers nil: no wallet, no submission to report. - Nothing cleared the bookmark on wipe. `DWContestedNameStatusService` was the one UserDefaults-backed store missing from the wiper's `resetForWipe()` list; it now drops every contested key it holds, scoped and legacy, across networks. An install that updates mid-vote keeps its bookmark: the first scoped read for a wallet adopts the pre-scoping value and deletes it. `clearPending` drops the legacy keys too, so a resolved contest cannot leave one behind for a later read to adopt.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWContestedNameStatusService.swift`:
- Around line 276-280: Update recordSubmission(label:network:) and the
voting-end/pending-state write paths to capture the active wallet ID when each
operation begins, then pass that value through the pending-contest APIs. Change
scope() and key generation to use the captured wallet ID rather than resolving
WalletEnvironment.activeWalletIdHex at write time, preserving the captured
network behavior.
- Around line 304-335: Serialize migrateLegacyBookmarkIfNeeded(for:) and
resetForWipe() through the same actor or lock so all bookmark reads, writes, and
removals cannot interleave; update
DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWContestedNameStatusService.swift:304-335
accordingly. If actor isolation is used, invoke resetForWipe() within the
existing main-queue cleanup block in
DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift:169-177.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: f3baa3c9-48ab-4b89-83ea-fd8c608abdbd
📒 Files selected for processing (2)
DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWContestedNameStatusService.swiftDashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift
| private nonisolated static func scope() -> String? { | ||
| guard let hex = WalletEnvironment.activeWalletIdHex as String?, !hex.isEmpty else { | ||
| return nil | ||
| } | ||
| return hex |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Capture the wallet ID when the operation starts.
recordSubmission(label:network:) preserves the network before asynchronous FFI, but scope() resolves the wallet only when it writes. If wallet A starts registration and wallet B becomes active before completion, the submission is stored under wallet B. The same late lookup affects voting-end writes and pending-state clearing.
Pass the captured wallet ID through the pending-contest APIs and use it for key generation.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWContestedNameStatusService.swift`
around lines 276 - 280, Update recordSubmission(label:network:) and the
voting-end/pending-state write paths to capture the active wallet ID when each
operation begins, then pass that value through the pending-contest APIs. Change
scope() and key generation to use the captured wallet ID rather than resolving
WalletEnvironment.activeWalletIdHex at write time, preserving the captured
network behavior.
| private nonisolated static func migrateLegacyBookmarkIfNeeded(for network: Network) { | ||
| guard let labelKey = pendingLabelKey(for: network), | ||
| let endTimeKey = pendingVotingEndTimeKey(for: network) | ||
| else { return } | ||
|
|
||
| let defaults = UserDefaults.standard | ||
| let legacyLabelKey = legacyPendingLabelKey(for: network) | ||
| guard defaults.object(forKey: labelKey) == nil, | ||
| let legacyLabel = defaults.string(forKey: legacyLabelKey) | ||
| else { return } | ||
|
|
||
| defaults.set(legacyLabel, forKey: labelKey) | ||
| let legacyEndTimeKey = legacyPendingVotingEndTimeKey(for: network) | ||
| let legacyEnd = defaults.double(forKey: legacyEndTimeKey) | ||
| if legacyEnd > 0 { | ||
| defaults.set(legacyEnd, forKey: endTimeKey) | ||
| } | ||
| defaults.removeObject(forKey: legacyLabelKey) | ||
| defaults.removeObject(forKey: legacyEndTimeKey) | ||
| logger.info( | ||
| "🪪 CONTEST-SVC :: adopted legacy bookmark for \(networkKey(network), privacy: .public)") | ||
| } | ||
|
|
||
| /// Drop every contested bookmark this device holds — both wallet-scoped and | ||
| /// legacy, across networks. Called from the wallet wiper alongside the other | ||
| /// UserDefaults-backed stores. | ||
| nonisolated static func resetForWipe() { | ||
| let defaults = UserDefaults.standard | ||
| for key in defaults.dictionaryRepresentation().keys | ||
| where key.hasPrefix(pendingLabelKeyPrefix) || key.hasPrefix(pendingVotingEndTimeKeyPrefix) { | ||
| defaults.removeObject(forKey: key) | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Serialize bookmark migration and wipe reset.
resetForWipe() runs on the background wipe queue while migrateLegacyBookmarkIfNeeded(for:) can run on the main actor. If migration reads a legacy value before reset removes it, then writes its scoped value after reset enumerates keys, the wipe completes with a recreated bookmark.
DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWContestedNameStatusService.swift#L304-L335: Use the same actor or lock for migration, reads, writes, and reset.DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift#L169-L177: Invoke the reset inside the existing main-queue cleanup block if actor isolation is used.
📍 Affects 2 files
DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWContestedNameStatusService.swift#L304-L335(this comment)DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift#L169-L177
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWContestedNameStatusService.swift`
around lines 304 - 335, Serialize migrateLegacyBookmarkIfNeeded(for:) and
resetForWipe() through the same actor or lock so all bookmark reads, writes, and
removals cannot interleave; update
DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWContestedNameStatusService.swift:304-335
accordingly. If actor isolation is used, invoke resetForWipe() within the
existing main-queue cleanup block in
DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift:169-177.
Reachability: `startMonitoring` blocked its caller for up to 200 ms waiting on the first `NWPathMonitor` update, which is delivered on a background queue. At launch that caller is the main thread, so a user-interactive thread waited on lower-QoS work. Raising the queue to `.userInitiated` only narrowed the window — it still sits below `.userInteractive`. The queue goes back to `.utility` and the wait is skipped on the main thread instead; every caller already observes `didChangeNotification`, which carries the first real path moments later. Background callers keep the synchronous contract. Invitation claim check: the Continue-time round trip ran in an unowned task, so its result could land after the user had edited the link, gone Back, or left the screen — marking an unrelated link as claimed, or pushing the claim flow for a URI already replaced. The task is now owned by the view model, cancelled on input change, Back and disappear, and its continuation re-checks that the URI it started from is still the current one. Username submission re-derives the cached spendable ceiling from the live UTXO set. The cache tracks the balance publisher, which is right for per-keystroke validation, but a submission spends real UTXOs and the fee reserve follows the UTXO count, which can move while the balance does not. One FFI walk on an explicit user action costs nothing. Also dropped two redundant `@State` initializers flagged by SwiftLint.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@DashWallet/Sources/Infrastructure/Networking/NetworkReachability.swift`:
- Around line 74-85: Update startMonitoring() and its reachability state to
represent the initial status as unknown rather than defaulting to offline.
Ensure NetworkReachabilityMonitor, TransferAmountViewModel, and
startNetworkMonitoring() defer reachability-dependent decisions until
handlePathUpdate(_:) supplies the first path, while preserving the existing
monitoring and notification flow.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: ed110f83-2da4-47d8-92fd-e10c67625459
📒 Files selected for processing (4)
DashWallet/Sources/Infrastructure/Networking/NetworkReachability.swiftDashWallet/Sources/UI/DashPay/Invitations/ClaimInvitationScreen.swiftDashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swiftDashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift
🚧 Files skipped from review as they are similar to previous changes (3)
- DashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swift
- DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift
- DashWallet/Sources/UI/DashPay/Invitations/ClaimInvitationScreen.swift
|
|
||
| // Off the main thread, keep the synchronous contract the old | ||
| // `SCNetworkReachability`-based manager offered: wait briefly so the | ||
| // caller observes real state on return. | ||
| // | ||
| // On the main thread, never wait. `NWPathMonitor` delivers on a | ||
| // background queue, so the wait made a user-interactive thread block on | ||
| // lower-QoS work for up to 200 ms at launch — the priority inversion | ||
| // the Thread Performance Checker flags. Every caller already observes | ||
| // `didChangeNotification`, which carries the first real path a few | ||
| // milliseconds later. | ||
| guard !Thread.isMainThread else { return } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- startMonitoring callers ---'
rg -n -C 10 '\bstartMonitoring\(\)' 'DashWallet/Sources' -g '*.swift' || true
printf '%s\n' '--- immediate state reads and notification observers ---'
rg -n -C 10 \
'reachability\.networkStatus|\.isReachable\b|didChangeNotification|org\.dash\.networking\.reachability\.change' \
'DashWallet/Sources' -g '*.swift' || trueRepository: dashpay/dashwallet-ios
Length of output: 35609
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- NetworkReachability implementation ---'
cat -n 'DashWallet/Sources/Infrastructure/Networking/NetworkReachability.swift' | sed -n '20,125p'
printf '%s\n' '--- NetworkUnavailableStateView implementation ---'
cat -n 'DashWallet/Sources/UI/SwiftUI Components/NetworkUnavailableStateView.swift' | sed -n '20,75p'
printf '%s\n' '--- BaseViewController reachability helpers and callers ---'
cat -n 'DashWallet/Sources/UI/Views/BaseController/BaseViewController+NetworkReachability.swift' | sed -n '20,100p'
rg -n -C 8 '\bstartNetworkMonitoring\(\)|NetworkReachabilityMonitor\(' 'DashWallet/Sources' -g '*.swift' || true
printf '%s\n' '--- All reachability state reads and monitoring entry points ---'
rg -n -C 5 '\b(startMonitoring|startNetworkMonitoring|networkStatus|isReachable|isReachableViaWiFi|didChangeNotification)\b' 'DashWallet/Sources' -g '*.swift' || trueRepository: dashpay/dashwallet-ios
Length of output: 50379
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
import re
roots = [Path("DashWallet/Sources")]
patterns = {
"direct_start": re.compile(r"\bstartMonitoring\s*\(\s*\)"),
"wrapper_start": re.compile(r"\bstartNetworkMonitoring\s*\(\s*\)"),
"status_read": re.compile(r"\b(?:networkStatus|isReachable|isReachableViaWiFi)\b"),
}
for path in sorted(p for root in roots for p in root.rglob("*.swift")):
lines = path.read_text(errors="replace").splitlines()
hits = []
for i, line in enumerate(lines):
if patterns["direct_start"].search(line) or patterns["wrapper_start"].search(line):
window = "\n".join(
f"{j + 1}: {lines[j]}" for j in range(i, min(i + 8, len(lines)))
)
hits.append((i + 1, window))
if hits:
print(f"\n{path}")
for line_no, window in hits:
print(f"--- start at line {line_no} ---")
print(window)
print("\n--- direct state reads within the first 12 lines after a monitoring start ---")
for path in sorted(p for root in roots for p in root.rglob("*.swift")):
lines = path.read_text(errors="replace").splitlines()
for i, line in enumerate(lines):
if patterns["direct_start"].search(line) or patterns["wrapper_start"].search(line):
following = lines[i + 1:min(i + 12, len(lines))]
reads = [
(i + 2 + offset, text.strip())
for offset, text in enumerate(following)
if patterns["status_read"].search(text)
]
if reads:
print(f"{path}:{i + 1}")
for line_no, text in reads:
print(f" {line_no}: {text}")
PY
printf '%s\n' '--- definitions of NetworkStatus and networkStatus ---'
rg -n -C 6 \
'enum NetworkStatus|typealias NetworkStatus|var networkStatus\b|isReachable\b' \
'DashWallet/Sources' -g '*.swift' | head -n 240Repository: dashpay/dashwallet-ios
Length of output: 20202
Defer reachability decisions until the first path update.
startMonitoring() can return before _isReachable is updated. Main-thread consumers then treat the default false value as .offline, including NetworkReachabilityMonitor, TransferAmountViewModel, and startNetworkMonitoring(). Represent the initial state as unknown and defer these decisions until handlePathUpdate(_:) runs.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@DashWallet/Sources/Infrastructure/Networking/NetworkReachability.swift`
around lines 74 - 85, Update startMonitoring() and its reachability state to
represent the initial status as unknown rather than defaulting to offline.
Ensure NetworkReachabilityMonitor, TransferAmountViewModel, and
startNetworkMonitoring() defer reachability-dependent decisions until
handlePathUpdate(_:) supplies the first path, while preserving the existing
monitoring and notification flow.
…ng it The wallet-scoping fix still showed the previous wallet's contest on a freshly created one. The cause was the legacy migration I added alongside it: on the first scoped read it copied the old wallet-agnostic bookmark onto whichever wallet happened to read first. A value with no wallet in its key cannot be attributed to a wallet, so "be kind to an install that updates mid-vote" turned into exactly the leak the scoping was meant to close. The legacy keys are now deleted on first access, never adopted. Nothing is lost: a wallet that really has a contest in flight rebuilds the bookmark from Platform on the next runtime start — the same-seed recovery pipeline refreshes contested names for every identity it finds and calls `recordSubmission` for the one it owns.
Removing the main-thread wait from `startMonitoring` left a window before the first `NWPathMonitor` path arrives, and `isReachable` reports `false` there. That `false` is a placeholder, not an answer, and callers read it as "offline". `NetworkStatus` gains `.unknown`, and `networkStatus` returns it until a real path has been reported; `hasDeterminedReachability` exposes the same fact to Obj-C callers. `SyncingActivityMonitor` — the launch-time consumer, and the one the removed wait put at risk — already branches on `== .offline`, so it now stays quiet during the window instead of announcing a connection failure. Sites that gate on `== .online` are unchanged by design: an unknown path is not a licence to act. What is still outstanding is presentation — screens that hide content on `!isOnline` (Coinbase, CrowdNode, Buy & Sell, Swap) treat unknown as offline and can briefly show the unavailable state. Moving those to `networkStatus == .offline` is mechanical but touches payment screens, so it belongs in its own change rather than riding along here.
Issue being fixed or feature implemented
QA could not redeem a DashPay invitation on iOS, and the surfaces around the
claim flow had a set of smaller defects found while reproducing it.
used, and had no way back out of the redeem screen.
hardcoded circle with the username's first letter, so a user with a picture
set still saw initials.
What was done?
Invitation claim flow. Hardened the claim path: an already-used invitation
is now detected by its prospective identity instead of being accepted and
failing later, the redeem screen gained a back button, and the screen was moved
onto the shared
NavigationBarandDashButtonso it matches the rest of theapp. Added a log line recording which identity the claimed-check matched, since
that was previously invisible when diagnosing a failed claim.
Profile picture on the identity sheet. The sheet now uses
ContactAvatarView, the app's single avatar path: the remote image when theprofile has one, otherwise the deterministic placeholder whose colour matches
Android. The owner's own profile therefore renders the same here as it does in
contacts and notifications. Visible side effect for users with no picture: the
placeholder is no longer always blue, it takes the per-letter colour the rest
of the app already uses.
Username validation performance. Two problems on the typing path, both
introduced by the earlier QA-fix batch:
checkBalance()calledfeeAwareMaxSendable(), whose reserve estimate walksthe account's entire UTXO set over the FFI on the main actor — and validation
runs on every throttled keystroke. That is what made the field feel
unresponsive: it was never disabled, the main actor was just busy. The value
is now cached and recomputed from the balance publisher, the only moment it
can actually change.
"Validating username…" waited for the sum of two DAPI round trips on every
contested-eligible name — which is most of them. They answer independent
questions about the same label, so they now run concurrently and the wait is
the slower of the two.
Neither changes what the form decides; the remaining latency is DAPI's own.
How Has This Been Tested?
Clean
dashpaybuild (xcodebuild -workspace DashWallet.xcworkspace -scheme dashpay -sdk iphonesimulator ARCHS=arm64), the standing bar on this branchwhile the unit-test target is broken.
Testnet smoke on device and simulator:
already-used invitation, and backing out of the redeem screen;
validating spinner clears in roughly one DAPI round trip rather than two.
Not verified end to end: a profile picture actually appearing on the sheet.
Avatar upload is currently refused by Imgur (
These actions are forbidden.)for the app's Client-ID, so no picture can be set from the device to render.
The placeholder path and the pending-vote states were exercised instead.
Breaking Changes
None.
Checklist:
For repository code-owners and collaborators only
Summary by CodeRabbit
New Features
Improvements