Skip to content

fix(wallet): show a placeholder until transparent balance loads - #1130

Merged
llbartekll merged 2 commits into
developfrom
codex/transparent-balance-loading
Sep 14, 2026
Merged

llbartekll merged 2 commits into
developfrom
codex/transparent-balance-loading

Conversation

@llbartekll

@llbartekll llbartekll commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Issue being fixed or feature implemented

Home showed an unread transparent balance as zero on cold launch and after wallet state was cleared. #1118 publishes the persisted Core snapshot early, but BalanceModel still converted nil to zero and deferred delivery through the main run loop. A restored Platform or shielded zero must also not make the headline look empty before Core has been read.

What was done?

  • Preserve transparent balance availability through the model and Home presentation. The transparent row uses the same — and “Balance unavailable” treatment as Platform; a successful zero remains a valid amount.
  • Consume the emitted wallet snapshot synchronously, avoiding both the extra run-loop delay and rereading the old value during @Published delivery.
  • Keep the main amount unavailable until the transparent balance specifically is known, including when Platform/shielded amounts restore first or survive a runtime restart. Their individual rows retain known values. Once Core is available, sum known visible components and retain the existing “Known balance” label for partial totals.
  • Preserve balance hiding and per-wallet backup/shortcut flags across clears and reseeds.

Targets develop after #1129 merged. The two transparent-balance commits were rebased onto 8e1664540; the diff contains only this follow-up. Both commits retained identical patches through the rebase. The 73 standalone tests and signed device build were rerun successfully on this base.

How Has This Been Tested?

  • python3 scripts/test_shielded_state.py --sdk-path ../platform/packages/swift-sdk: 73 XCTest cases passed, including 15 Home presentation tests.
  • Verified the review regression fails before the fix and passes afterward. Cases cover restored Platform/shielded zeros while Core is unread, retained zero/nonzero components across clear/reseed, both display modes, known component rows, and genuine transparent zero.
  • Signed arm64 dashpay device build passed after the fix and rebase (Debug, generic iOS destination, COMPILER_INDEX_STORE_ENABLE=NO).
  • Strengthened PassiveWalletStateUITailTests to check immediate publication before the main actor yields, placeholder formatting, clears/reseeds, and a genuine zero. Retried the targeted Xcode test on September 14; it remains blocked before compilation because the dashwallet host embeds a Watch app and Xcode requires watchOS 26.5. This integration test has not executed, and the standalone tests do not compile BalanceModel.
  • No funded-device cold-launch smoke test was performed. The review suggestion for that validation remains open.
  • git diff --check passed.

Breaking Changes

None. No additional SDK API or persistence changes beyond the parent PR's dependencies.

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

@coderabbitai

coderabbitai Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 69f6f221-26e3-489f-b42b-083879f86b68

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@thepastaclaw

thepastaclaw commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

🔍 Review in progress — actively reviewing now (commit 87224a5) · triage: normal

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Final validation — Phase 1 + Phase 2

The transparent-balance placeholder implementation is correct at the reviewed head: unavailable state remains distinct from a genuine zero, wallet snapshots are consumed synchronously, and partial-balance presentation behavior is covered by the standalone tests. One integration regression test remains unexecuted because the targeted Xcode test run was blocked by the missing watchOS 26.5 installation; this is a validation gap rather than a blocking implementation defect.

🟡 1 suggestion(s)

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: gpt-6-astra (agent: phase2-reviewer, role: general); final verifier: gpt-6-astra (agent: astra-verifier, role: final-verifier)

  • Triage: normal by gpt-6-astra (effort low) — This is a contained but behaviorally meaningful UI/state-model change spanning balance availability propagation, synchronous published-state handling, placeholder and partial-total presentation, and regression tests, without modifying funds movement, cryptography, storage, or other critical surfaces.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity below 15% reserve: weekly 11% left, 5h 100% left), glm-5.3-flash (zai below 15% reserve: 5h 100% left, weekly 13% left)
  • Fresh verifier: gpt-6-astra — final-verifier; agent astra-verifier
  • Phase 2 reviewers: gpt-6-astra — general (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `DashWalletTests/PassiveWalletStateUITailTests.swift`:
- [SUGGESTION] DashWalletTests/PassiveWalletStateUITailTests.swift:67-126: Run the strengthened BalanceModel regression when the test host is available
  The key integration regression in `testBalanceModelDistinguishesUnavailableFromZeroAcrossClearsAndReseeds` has not executed. It directly verifies the synchronous `applyBalanceOnMainActor` publication before the main actor yields, preservation of `nil` through clear/reseed, placeholder formatting, persistence of the per-wallet flags, and distinction between an unavailable balance and a genuine zero. The standalone presentation harness does not compile `BalanceModel` or this test file, so it cannot validate those assertions. Run this test once the required watchOS 26.5 runtime is installed, and perform the documented cold-launch smoke to confirm that `—` is shown before the first transparent balance publication.

Comment on lines 67 to 126
@@ -86,14 +86,23 @@ final class PassiveWalletStateUITailTests: XCTestCase {

let model = BalanceModel()
XCTAssertTrue(model.isBalanceHidden)

await applyBalance(9_000, expecting: 9_000, in: model)
XCTAssertNil(model.value)
XCTAssertEqual(model.mainAmountString, "—")
XCTAssertEqual(model.fiatAmountString(), "—")

// The early restore publish must reach Home before the main actor
// yields. This also catches rereading @Published's old stored value.
SwiftDashSDKWalletState.shared.applyBalanceOnMainActor(WalletBalance(confirmed: 9_000))
XCTAssertEqual(model.value, 9_000)
XCTAssertTrue(options.userHasBalance)
XCTAssertNotNil(options.balanceChangedDate)
XCTAssertTrue(model.isBalanceHidden)

let backupReminderDate = options.balanceChangedDate
await clearBalance(expecting: model)
XCTAssertNil(model.value)
XCTAssertEqual(model.mainAmountString, "—")
XCTAssertEqual(model.fiatAmountString(), "—")
// `userHasBalance` deliberately survives a cleared balance. `nil` means
// "not known yet" — Core SPV stopped, or no wallet bound to the host —
// never "this wallet is empty", and the flag is persisted per wallet and
@@ -109,6 +118,11 @@ final class PassiveWalletStateUITailTests: XCTestCase {
XCTAssertEqual(model.value, 4_000)
XCTAssertTrue(options.userHasBalance)
XCTAssertTrue(model.isBalanceHidden)

await applyBalance(0, expecting: 0, in: model)
XCTAssertEqual(model.value, 0)
XCTAssertNotEqual(model.mainAmountString, "—")
XCTAssertFalse(options.userHasBalance)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Suggestion: Run the strengthened BalanceModel regression when the test host is available

The key integration regression in testBalanceModelDistinguishesUnavailableFromZeroAcrossClearsAndReseeds has not executed. It directly verifies the synchronous applyBalanceOnMainActor publication before the main actor yields, preservation of nil through clear/reseed, placeholder formatting, persistence of the per-wallet flags, and distinction between an unavailable balance and a genuine zero. The standalone presentation harness does not compile BalanceModel or this test file, so it cannot validate those assertions. Run this test once the required watchOS 26.5 runtime is installed, and perform the documented cold-launch smoke to confirm that — is shown before the first transparent balance publication.

source: muse-spark-1.3-contributor (phase1-reviewer: general)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Retried the exact BalanceModel regression on September 14 after rebasing. Xcode still exits before compilation: “This scheme builds an embedded Apple Watch app. watchOS 26.5 must be installed in order to test the scheme.” The 73 passing standalone tests and signed dashpay device build do not close this integration gap. No funded-device cold-launch smoke was performed. Keeping this thread open and retaining the limitation explicitly in the PR description.

@llbartekll
llbartekll force-pushed the codex/platform-balance-early-restore branch 7 times, most recently from 7523946 to b651975 Compare September 14, 2026 11:28

@romchornyi romchornyi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed at head 7a04a662, weighting this PR's own commit — GitHub's diff also carries two stale copies of #1129's commits, since the base branch was rebased under it.

The core change is sound: BalanceModel.value becoming UInt64? breaks no callers (BalanceViewDataSource conformance is unreferenced and dashAmountStringWithFont has none), and dropping .receive(on: RunLoop.main) is thread-safe, because every writer of SwiftDashSDKWalletState.balance — applyBalance, applyBalanceOnMainActor, clearBalance, clearAllState — is already main-queue-bound, and passing the snapshot correctly sidesteps the willSet stale read. The new defer { isClearing = false } covers the mid-function guard.

One inline blocker: the placeholder does not cover the case the PR is named for.

Worth knowing for the stack: the merge base does not have HomeBalancePresentation.swift in project.pbxproj at all — this PR is what adds it to both app targets. If #1129 merges first it needs the same entry, or it will not build.

Non-blocking, and all in the inherited #1129 commits rather than this PR — flagging them here only so they are not lost if this lands first: PlatformAddressSyncCoordinator.swift:849, where clearLocalState's guard makes the Clear button inert after any detachPlatformSubscriptions() and writes a UI instruction into lastError that the status screen renders as a red sync-failure card; :1587, where the loadCachedBalances seed was dropped, so nothing restores platformBalance / activeAddressCount when modelContainer is nil — a case prepareLocalPlatformState explicitly logs as result=no-container; and :1531, where refreshBalanceSnapshot() is now dead after handleSyncEvent switched to calling refreshDerivedAddresses() directly.

🤖 Reviewed with Claude Code

@romchornyi romchornyi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed at head 7a04a662, weighting this PR's own commit — GitHub's diff also carries two stale copies of #1129's commits, since the base branch was rebased under it.

The core change is sound: BalanceModel.value becoming UInt64? breaks no callers (BalanceViewDataSource conformance is unreferenced and dashAmountStringWithFont has none), and dropping .receive(on: RunLoop.main) is thread-safe, because every writer of SwiftDashSDKWalletState.balance — applyBalance, applyBalanceOnMainActor, clearBalance, clearAllState — is already main-queue-bound, and passing the snapshot correctly sidesteps the willSet stale read. The new defer { isClearing = false } covers the mid-function guard.

One inline blocker: the placeholder does not cover the case the PR is named for.

Worth knowing for the stack: the merge base does not have HomeBalancePresentation.swift in project.pbxproj at all — this PR is what adds it to both app targets. If #1129 merges first it needs the same entry, or it will not build.

Non-blocking, and all in the inherited #1129 commits rather than this PR — flagging them here only so they are not lost if this lands first: PlatformAddressSyncCoordinator.swift:849, where clearLocalState's guard makes the Clear button inert after any detachPlatformSubscriptions() and writes a UI instruction into lastError that the status screen renders as a red sync-failure card; :1587, where the loadCachedBalances seed was dropped, so nothing restores platformBalance / activeAddressCount when modelContainer is nil — a case prepareLocalPlatformState explicitly logs as result=no-container; and :1531, where refreshBalanceSnapshot() is now dead after handleSyncEvent switched to calling refreshDerivedAddresses() directly.

🤖 Reviewed with Claude Code

@llbartekll
llbartekll force-pushed the codex/platform-balance-early-restore branch from b651975 to 92fe929 Compare September 14, 2026 13:00
@llbartekll
llbartekll force-pushed the codex/transparent-balance-loading branch from 7a04a66 to 87224a5 Compare September 14, 2026 13:43
@llbartekll
llbartekll force-pushed the codex/platform-balance-early-restore branch from 92fe929 to 844c2d4 Compare September 14, 2026 13:51

@romchornyi romchornyi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving at head 87224a50. The blocker is closed, and closed exactly right — I read the file rather than the commit message:

var totalDuffs: UInt64? {
    guard let transparentDuffs else { return nil }
    ...
}

The total now waits for Core specifically instead of for any known component, so both cases I described — a restored Platform zero, and a runtime restart where clearBalance() nils Core while performStop(preservingPlatformBalance:) keeps Platform — produce the placeholder rather than a confident 0.00 DASH. The doc comment above it now describes what the code does.

Verified this pass: dropping .receive(on: RunLoop.main) is safe, because every writer of SwiftDashSDKWalletState.balance is main-queue-bound (publishBalance is @MainActor; applyBalance and clearBalance hop via DispatchQueue.main.async; clearAllState uses Thread.isMainThread ? … : main.sync) and balance is private(set). The stale-read reasoning in the new comment is right — @Published emits from willSet, so the old reloadBalance() re-read was only saved by the run-loop hop, and consuming the snapshot is the correct fix. @Published private(set) var value: UInt64? does default to nil. Operator precedence in both rewritten if let conditions is correct, and the coin-sound and balanceChangedDate semantics are unchanged for every nil/zero path. BalanceViewDataSource's new "—" returns are inert, since nothing assigns BalanceModel as a BalanceView.dataSource, and "—" through attributedAmountStringWithDashSymbol keeps its range math valid.

Non-blocking recommendations:

  • HomeBalanceView.swift:130 — in advanced mode the hero copy can contradict the rows beneath it: launch with Platform credits restored from persistence and Core not yet read renders — / "Balance unavailable" directly above a breakdown showing "Dash Platform 10.0". Not summing a Platform-only total is the right call — it would understate — but the string asserts the whole balance is unavailable to a user who can see part of it listed. Naming what is loading ("Dash balance loading") would match what the card already shows.
  • BalanceModel.swift:56 — the removed .receive(on: RunLoop.main) was what kept the main-thread requirement local to this file. The sink now runs synchronously inside balance's willSet, on whatever thread mutates it, and applyBalance reaches UIApplication.shared.applicationState, dw_playCoinSound(), DWGlobalOptions and a SwiftUI-observed @Published. Correct today, but the invariant now lives in another file with nothing asserting it; a dispatchPrecondition(condition: .onQueue(.main)) at the top of applyBalance(_:) pins it where it is relied on and costs nothing.
  • HomeBalancePresentation.swift:11 — the new transparentDuffs == nil clause in isPartial is unreachable at the only call site, since isPartial is read exclusively inside if let totalDuffs = … and totalDuffs is non-nil only when transparentDuffs is. Harmless now; a future caller driving the caption off isPartial alone would show it with no total to qualify.

On the verification gap you kept open — I agree it should stay open, and I could not close it either. The standalone harness (scripts/test_shielded_state.py) builds only four sources, of which HomeBalancePresentation.swift is the sole file from this PR; BalanceModel.swift and PassiveWalletStateUITailTests are Xcode-target-only, that target is blocked before compilation by the watchOS host requirement, and this repo has no build check in CI. I would normally build it locally, but the branch needs the unmerged dashpay/platform#4709 SDK, so the same dependency blocks me. Net: the optional value, the dropped receive(on:) and the re-guarded coin-sound / balanceChangedDate writes are reasoned-through but not compiled. Worth one local build once #4709 lands, before this merges.

🤖 Reviewed with Claude Code

@llbartekll
llbartekll force-pushed the codex/transparent-balance-loading branch from 87224a5 to 6393bbe Compare September 14, 2026 14:25
@llbartekll
llbartekll changed the base branch from codex/platform-balance-early-restore to develop September 14, 2026 14:25
@llbartekll
llbartekll merged commit a54dbf9 into develop Sep 14, 2026
5 checks passed
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.

3 participants