Skip to content

feat(wallet): harden the DashPay invitation claim flow - #927

Merged
romchornyi merged 12 commits into
developfrom
feat/dashpay-invitations-claim
Aug 7, 2026
Merged

romchornyi merged 12 commits into
developfrom
feat/dashpay-invitations-claim

Conversation

@romchornyi

@romchornyi romchornyi commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

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.

  • The invitation claim flow could accept an invitation that had already been
    used, and had no way back out of the redeem screen.
  • The identity profile sheet never rendered a profile picture — it drew a
    hardcoded circle with the username's first letter, so a user with a picture
    set still saw initials.
  • Username validation blocked typing and took far longer than it needed to.

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 NavigationBar and DashButton so it matches the rest of the
app. 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 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.

Username validation performance. Two problems on the typing path, both
introduced by the earlier QA-fix batch:

  • 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.

How Has This Been Tested?

Clean dashpay build (xcodebuild -workspace DashWallet.xcworkspace -scheme dashpay -sdk iphonesimulator ARCHS=arm64), the standing bar on this branch
while the unit-test target is broken.

Testnet smoke on device and simulator:

  • redeeming an invitation link, including a second attempt with an
    already-used invitation, and backing out of the redeem screen;
  • the identity profile sheet with and without a pending contested name;
  • typing into the username field — the field stays responsive, and the
    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:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have made corresponding changes to the documentation

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

Summary by CodeRabbit

  • New Features

    • Added an “Have an invitation?” option during DashPay setup, available regardless of funding readiness.
    • Added invitation claim checks with loading feedback and an already-claimed message.
    • Expanded invitation link support for AppsFlyer OneLink domains.
    • Profile sheets now display the user’s avatar and identity information.
  • Improvements

    • Improved username availability checks and balance handling.
    • Enhanced invitation redemption navigation and validation.
    • Improved startup network responsiveness.
    • Scoped contested-name bookmarks to the active wallet and removed them during wallet cleanup.

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.
@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@romchornyi, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 36 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 4ccb254c-219f-4810-9386-8b0c2e68bdcc

📥 Commits

Reviewing files that changed from the base of the PR and between 84d0fee and 95fcb5c.

📒 Files selected for processing (2)
  • DashWallet/Sources/Application/Types.swift
  • DashWallet/Sources/Infrastructure/Networking/NetworkReachability.swift
📝 Walkthrough

Walkthrough

The 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.

Changes

Invitation redemption flow

Layer / File(s) Summary
Invitation recognition and claim lookup
DashWallet/Sources/Infrastructure/SwiftDashSDK/Invitations/*
OneLink matching accepts approved domain suffixes. The service checks prospective identity claims and refreshes identity data before contact requests.
Redemption validation and feedback
DashWallet/Sources/UI/DashPay/Invitations/ClaimInvitationScreen.swift
The screen checks voucher status asynchronously, prevents duplicate checks, supports custom back navigation, and displays already-claimed feedback.
Readiness screen entry points
DashWallet/Sources/UI/DashPay/Setup/CreateUsername/JoinDashPayReadinessScreen.swift, DashWallet/Sources/UI/Home/HomeViewController+Shortcuts.swift, DashWallet/Sources/UI/Menu/Main/MainMenuViewController.swift
Readiness UI now opens invitation redemption from an always-available invitation action.

Username setup

Layer / File(s) Summary
Cached balance and concurrent validation
DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift
Username validation and balance display use a cached Core spendable balance. Availability and contested-lock checks run concurrently when required.

Identity profile

Layer / File(s) Summary
Identity avatar loading and rendering
DashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swift
The profile sheet loads avatar and identity seed data and renders them through ContactAvatarView.

Reachability startup

Layer / File(s) Summary
Main-thread startup behavior
DashWallet/Sources/Infrastructure/Networking/NetworkReachability.swift
The monitoring queue remains at .utility QoS. Main-thread startup no longer waits for the first path update, while background callers retain the synchronous wait.

Contested-name bookmark storage

Layer / File(s) Summary
Wallet-scoped bookmark persistence
DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWContestedNameStatusService.swift
Contested-name bookmarks use wallet-scoped keys, discard legacy values, and safely handle missing wallet IDs.
Wallet wipe integration
DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift
Wallet cleanup resets contested-name status.

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
Loading

Possibly related PRs

Suggested reviewers: jeanpierreroma, llbartekll

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main changes to strengthen the DashPay invitation claim flow.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/dashpay-invitations-claim

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
DashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swift (1)

19-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the redundant state initializers flagged by SwiftLint.

Use implicit nil initialization for avatarURL and infer the type of identitySeed.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 642e114 and 00fb040.

📒 Files selected for processing (9)
  • DashWallet/Sources/Infrastructure/Networking/NetworkReachability.swift
  • DashWallet/Sources/Infrastructure/SwiftDashSDK/Invitations/DWInvitationLinkNormalizer.swift
  • DashWallet/Sources/Infrastructure/SwiftDashSDK/Invitations/DWInvitationService.swift
  • DashWallet/Sources/UI/DashPay/Invitations/ClaimInvitationScreen.swift
  • DashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swift
  • DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift
  • DashWallet/Sources/UI/DashPay/Setup/CreateUsername/JoinDashPayReadinessScreen.swift
  • DashWallet/Sources/UI/Home/HomeViewController+Shortcuts.swift
  • DashWallet/Sources/UI/Menu/Main/MainMenuViewController.swift

Comment on lines +28 to +35
/// `.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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 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:


🏁 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 240

Repository: 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 00fb040 and e449c43.

📒 Files selected for processing (2)
  • DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWContestedNameStatusService.swift
  • DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift

Comment on lines +276 to +280
private nonisolated static func scope() -> String? {
guard let hex = WalletEnvironment.activeWalletIdHex as String?, !hex.isEmpty else {
return nil
}
return hex

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

Comment on lines +304 to +335
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)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between e449c43 and ca0a524.

📒 Files selected for processing (4)
  • DashWallet/Sources/Infrastructure/Networking/NetworkReachability.swift
  • DashWallet/Sources/UI/DashPay/Invitations/ClaimInvitationScreen.swift
  • DashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swift
  • DashWallet/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

Comment on lines +74 to +85

// 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 }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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' || true

Repository: 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' || true

Repository: 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 240

Repository: 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants