Skip to content

fix(wallet): restore cached Platform balance before network startup - #1129

Merged
llbartekll merged 5 commits into
developfrom
codex/platform-balance-early-restore
Sep 14, 2026
Merged

llbartekll merged 5 commits into
developfrom
codex/platform-balance-early-restore

Conversation

@llbartekll

@llbartekll llbartekll commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

Issue being fixed or feature implemented

On an offline launch, transparent and shielded balances appear from local storage while Platform remains hidden until identity discovery finishes its retries (about 11.3 seconds in the reported logs). Platform's cached balance was restored after that wait, and Home gated the row on the sync coordinator's isRunning flag.

Follow-up to merged #1128, now based on develop (5dae044a9). Only the five follow-up commits were rebased; parent commits were not replayed. SDK dependency #4709 is also merged.

What was done?

  • Restore Platform balance from SwiftData before pre-SPV identity discovery; also support direct Platform startup. The shared throwing reader distinguishes unavailable data and failed reads from a known zero.
  • Publish explicit balance availability separately from sync readiness, preserving the existing numeric publisher for compatibility. Send and internal transfer also observe availability, show unknown amounts explicitly, and guard Confirm/Max. Offline errors and manager retries retain the selected wallet's last known amount; switching wallets/networks invalidates it. A successful Clear invalidates the old session and immediately re-reads the cleared local zero; a failed Clear retains the displayed amount. Session tokens reject queued updates from the previous manager or scope; scope/manager validation happens before detaching subscriptions.
  • Show the advanced-mode Platform row immediately, using a placeholder until its local read completes. The total includes known components and labels partial amounts. Simple mode still excludes Platform.
  • Record local-read outcome, duration and completion timestamp in diagnostic exports without wallet identifiers or amounts. No SDK source or database schema changes.

Availability contract

Here, available means the selected wallet/account's local rows were successfully read; it does not mean their amount has been verified by a completed network discovery. A present Platform account with empty or zero-valued rows therefore yields available zero, including after an explicit successful Clear. A missing wallet/account remains unavailable. This is the agreed scope of this follow-up: restore the local snapshot before networking and keep balance availability separate from sync readiness.

Consequently, a freshly restored wallet can initially show its local zero before discovery finds remote funds. Distinguishing that case from a previously verified zero would require wallet/account-specific persisted provenance and an explicit policy for Clear and legacy caches. The existing PersistentPlatformAddressesSyncState is a shared network checkpoint, despite its legacy walletId field name; it cannot certify discovery of a particular wallet. This PR does not introduce that additional guarantee.

How Has This Been Tested?

  • Latest validation after retarget at 844c2d48d over develop (5dae044a9): 65 controller, presentation and real SwiftData tests passed, including the shielded regressions.
  • Earlier validation: 55 tests passed via python3 scripts/test_shielded_state.py --sdk-path ../platform/packages/swift-sdk: 11 Platform state tests, 8 real SwiftData reader tests, 6 Home presentation tests, and 30 shielded regressions. New coverage includes cleared local zero, wallet-material invalidation, incomplete account discovery and network repair after a snapshot read failure.
  • Latest signed arm64 iPhone dashpay build and deep/strict signature verification passed using SDK a68a65d113. The rebuilt device archive SHA256 is d3f5d95829285dbcde3ff05320190389b2cbc9036ff4fc08495f86f06994e84f. This was a generic device build, not a new physical-device smoke test. The simulator scenarios below were performed before this review round.
  • Signed iPhone 17 simulator build (iOS 26.3) passed. Verified cold launch, offline restart, restoration of connections, and Testnet → Mainnet → Testnet with the existing local wallets. The Platform row retained a known zero while discovery retried; sync resumed after connections were restored.
  • Exported app/SDK logs confirm local publication before wallet_startup_started: first launch 17:51:46.031 vs 17:51:46.216 UTC (4 ms local read); restart 17:56:33.393 vs 17:56:33.525 UTC (3 ms local read). Discovery still took approximately 11.3 seconds, without delaying balance availability.
  • Simulator network failures were injected into this app's non-loopback socket connections using a temporary, uncommitted transport shim; Mac networking was unchanged. This validates connection failure/recovery, not a physical NWPathMonitor airplane-mode transition. Fault injection was removed after testing. Nonzero amounts and stale-session isolation are covered by automated tests; the simulator wallets had cached zero Platform balances.
  • Full Xcode test-target execution remains limited by the locally missing watchOS SDK; the registered controller/presentation/SwiftData tests ran through the standalone runner above.

Breaking Changes

None. Existing platformBalance / $platformBalance consumers remain supported.

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 13, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 10 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 0edeb6ad-76fe-4dba-9c17-0769af127572

📥 Commits

Reviewing files that changed from the base of the PR and between 5dae044 and 844c2d4.

📒 Files selected for processing (15)
  • DashWallet.xcodeproj/project.pbxproj
  • DashWallet/Sources/Infrastructure/SwiftDashSDK/HomeBalancePresentation.swift
  • DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift
  • DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformBalanceController.swift
  • DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformBalanceReader.swift
  • DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift
  • DashWallet/Sources/UI/Home/Views/Home Balance View/HomeBalanceView.swift
  • DashWallet/Sources/UI/Menu/SyncInfo/PlatformSyncStatusScreen.swift
  • DashWallet/Sources/UI/Payments/InternalTransfer/InternalTransferViewModel.swift
  • DashWallet/Sources/UI/Payments/Pay/SendViewModel.swift
  • DashWallet/en.lproj/Localizable.strings
  • DashWalletTests/HomeBalancePresentationTests.swift
  • DashWalletTests/PlatformBalanceControllerTests.swift
  • DashWalletTests/PlatformBalanceReaderTests.swift
  • scripts/test_shielded_state.py

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 13, 2026 •

Copy link
Copy Markdown
Contributor

🕓 Queued for automated review — 10th in line, estimated start in ~50 min (commit 844c2d4)
Estimated review time once started: ~10 min (two-phase automated review; median of recent runs).

  • Request priority review — tick this box and the review moves to the front of the queue.

@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 PR improves Platform balance restoration and correctly separates balance availability from sync readiness, but the new SwiftData reader does not constrain address rows to the selected network. Because wallet IDs can be reused across networks, the restored balance and derived addresses can include data from the wrong chain. The diagnostic no-container path also omits the completion timestamp promised by the PR description.

🔴 1 blocking | 🟡 1 suggestion(s) | 💬 1 nitpick(s)

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: ffi-engineer); reviewer 3: muse-spark-1.3-contributor (agent: phase1-reviewer, role: security-auditor); reviewer 4: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 5: gpt-6-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6-astra (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6-astra (agent: astra-verifier, role: final-verifier)

  • Triage: normal by gpt-6-astra (effort low) — This is a substantial cross-cutting change to Platform balance restoration, wallet/session state management, SwiftData reads, diagnostics, UI presentation, tests, and project configuration, but it does not itself modify funds movement, cryptography, key handling, consensus, network deserialization, or storage migrations.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — ffi-engineer (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — security-auditor (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, gpt-6-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6-astra — security-auditor (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 `DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformBalanceReader.swift`:
- [BLOCKING] DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformBalanceReader.swift:29-31: Filter restored address rows to the selected network
  The wallet lookup correctly checks both walletId and networkRaw, but the subsequent address fetch uses only PersistentPlatformAddress.predicate(walletId: walletId). Platform address rows do not carry their own network discriminator, so when the same wallet ID is present for both networks, this read can aggregate the other network's persisted credits and return its addresses as part of the selected wallet. That can display and publish a balance from the wrong chain and populate derivedAddresses with cross-network data. Scope the address query through the selected wallet/account relationship or otherwise enforce the selected network before aggregating the rows.
- [NITPICK] DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformBalanceReader.swift:5-6: Remove the unverifiable loadCachedBalances reference
  The new doc comment contrasts this reader with loadCachedBalances(), but no such symbol exists in the repository outside this comment. That makes the documented distinction unverifiable and conflicts with the project's requirement that comments describe behavior backed by executable symbols. Describe the reader's actual throwing and unavailable-data behavior instead.

In `DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift`:
- [SUGGESTION] DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift:259-260: Include completion timestamp for the no-container read outcome
  The normal local-read path logs result, duration_ms, and completed_unix_ms, but the modelContainer == nil early return logs only result and duration_ms=0. The PR description explicitly promises outcome, duration, and completion timestamp in diagnostic exports. Add completed_unix_ms to this branch so consumers can record every local-read outcome consistently.
Out-of-scope follow-up suggestions (1)

These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.

  • Sync Info renders unknown Platform balance as zero — OUTDATED: PlatformSyncStatusScreen.swift is not changed by this PR, and its unconditional numeric rendering of coordinator.platformBalance existed before the new platformBalanceState was introduced. The PR's stated UI change is in HomeBalanceView.swift; changing this pre-existing Sync Info presentation is outside the reviewed diff.
    • Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.

@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 reviewed head correctly restores cached Platform balances before network startup, preserves wallet and network isolation, separates balance availability from sync readiness, and fences stale session updates. The previously reported documentation, diagnostic timestamp, and cross-network aggregation concerns are fixed or refuted by the network-specific persistence contract and regression coverage; no new in-scope issues remain.

Review provenance

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

  • Triage: normal by gpt-6-astra (effort low) — This is a substantial cross-cutting change to wallet balance state, persistence reads, sync-session isolation, diagnostics, UI presentation, tests, and project configuration, but it does not modify funds movement, key handling, cryptography, consensus, network deserialization, or storage migrations.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — security-auditor (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, gpt-6-astra — security-auditor (completed, effort high); agent phase2-reviewer

@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 this stack on top of #1128. The design is sound — a session-fenced controller mirroring ShieldedBalanceController, with the local SwiftData read happening before identity discovery — and I checked the parts most likely to go wrong: the isSelectedWalletScope rename is a pure widening; devnet is unreachable here because WalletEnvironment.network is nil there; switchWallet calls prepareForNetworkSwitch() first, so the preserved balance cannot leak across wallets; and all three new files are in both app targets plus the test target in the pbxproj.

Two inline comments below.

One thing I considered and rejected, so it does not come back as a review note: the $0.networkRaw == networkRaw filter in the reader is redundant, since the container is already per-network, and PersistentWallet.networkRaw is a documented-nullable UInt32? — but every app-side creation path goes through ensureWalletRecord with a non-nil network, so I could not construct a live failure.

Non-blocking recommendations:

  • PlatformAddressSyncCoordinator.swift:896 — clearLocalState zeroes every persisted row, then clearDisplay → platformBalances.clear() resets the scope and state to .unavailable without re-reading. Offline, a user who taps Clear is left with an indefinitely "unknown" Platform balance instead of the zero that was just written to disk.
  • PlatformAddressSyncCoordinator.swift:842 — the new refusal path sets an untranslated lastError, and PlatformSyncStatusScreen.swift:297-309 disables Clear only on isClearing — so the button is dead in exactly the state where it previously reset the display.
  • InternalTransferViewModel.swift:586 — the new availability state is wired into Home only; send and internal transfer still read platformBalance, now state.credits ?? 0. So an unknown Platform balance is still indistinguishable from empty at the transfer entry points, which is the same shape as the bug this PR fixes on Home.
  • PlatformAddressSyncCoordinator.swift:1531 — refreshBalanceSnapshot() has no callers left.

Merge ordering: this sits on #1128, which sits on dashpay/platform#4709, and both still have open blockers.

🤖 Reviewed with Claude Code

@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 reviewed head restores cached Platform balances with explicit availability, preserves selected-wallet state across retries, and keeps network stores isolated. The prior documentation and diagnostic gaps are fixed, and the previous cross-network concern is refuted by the network-specific SwiftData container contract and regression coverage; no new in-scope issues remain.

Review provenance

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

  • Triage: normal by gpt-6-astra (effort low) — This is a substantial, cross-cutting change to wallet runtime state, Platform balance restoration, sync/session handling, UI presentation, diagnostics, project configuration, and tests, but it does not directly modify funds movement, key handling, cryptography, consensus, network deserialization, or storage migrations.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — security-auditor (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, gpt-6-astra — security-auditor (completed, effort high); agent phase2-reviewer

@llbartekll
llbartekll force-pushed the codex/platform-balance-early-restore branch from 3809436 to 701fdb4 Compare September 14, 2026 09:26
@llbartekll

Copy link
Copy Markdown
Collaborator Author

Rebased onto the updated #1128 and addressed this review round in 701fdb4:

  • Validate the manager and selected scope before subscription teardown; inherited startup-generation checks also reject obsolete continuations.
  • After a successful Clear, re-read the cleared local rows immediately and publish known zero without waiting for networking. Failed clears retain the last displayed amount. Clear is disabled when its required manager/session/container is unavailable, and its refusal message is localized.
  • Send and internal transfer now observe Platform availability: an unknown amount shows a placeholder, reports Balance unavailable after amount entry, and disables Confirm/Max. Available zero remains distinct.
  • Removed the unused refreshBalanceSnapshot wrapper and added immediate Platform snapshot invalidation on a changed wallet-material selection.

The missing-account suggestion is answered in its thread: a local account not yet persisted is insufficient evidence for a zero on an imported seed. The agreed unavailable/known-zero contract is preserved and now has an additional real SwiftData regression.

Validation: 55 tests pass (30 shielded regressions, 11 Platform controller, 8 real SwiftData reader, 6 Home presentation), plus the integrated signed arm64 iPhone dashpay build. This remains a three-commit follow-up above #1128; the base is still codex/shielded-balance-reconnect until its merge.

@llbartekll
llbartekll force-pushed the codex/platform-balance-early-restore branch from 701fdb4 to dba0abd Compare September 14, 2026 09:39

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

Re-reviewed at head dba0abdb. Both findings from my last pass are addressed — the detach now sits below the scope guard, and the cached Platform balance is restored before network startup.

Two blockers below. Nothing else in this pass blocks the merge.

🤖 Reviewed with Claude Code

@llbartekll
llbartekll force-pushed the codex/platform-balance-early-restore branch from dba0abd to 1e5bec8 Compare September 14, 2026 10:21

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

Re-reviewed at head 1e5bec8b. Both blockers from my last pass are closed — the Clear re-subscribe no longer replays the pre-clear event over the zeroed counters, and the type-14 case no longer reports .unavailable for a knowably-zero balance.

I also walked the PlatformBalanceController begin / detach / clear / invalidateUnless state machine against the stop, network-switch, wallet-material-change and clear paths, and could not find a way to publish a foreign wallet's amount. The session fencing holds.

Two inline blockers below.

Non-blocking recommendations:

  • HomeBalancePresentation.swift:10 (with HomeBalanceView.swift:223) — showsBreakdown is now showsPlatformBalance || shieldedDuffs != nil, and the Platform row is gated on showsPlatformBalance alone. In advanced mode that is just viewModel.isAdvancedMode, so on an install where the runtime never starts (hasSDKWallet == false, where refresh returns with "no SDK wallet persisted; leaving runtime stopped") both balance states stay .unavailable forever and the breakdown card renders permanently with two "Balance unavailable" rows under a "Known balance" total — where it used to be hidden entirely. The coordinator already models the no-account case as platformAccountAvailability == .unavailable, but HomeBalancePresentation has no input for it, so "no account" and "not read yet" are indistinguishable on screen.
  • PlatformAddressSyncCoordinator.swift:996 — clearDisplay gates the balance on preservingPlatformBalance but still wipes activeAddressCount and derivedAddresses unconditionally (1003-1004), and performStop(deletingPersistedWallet: false) now passes preservingPlatformBalance: true. After Stop — or a failed Core start, which routes through the same performStop — the screen shows a non-zero "Platform Balance" next to "Active Addresses: 0" and an empty address list. The balance snapshot and the address snapshot want to be preserved or dropped together.
  • PlatformSyncStatusScreen.swift:311 — canClearLocalState is the same predicate as clearLocalState's entry guard, so the new "Start Platform sync before clearing its local state" string is unreachable: the user gets a silently greyed-out button instead. Either surface it as help text under the disabled button or drop the string. (Related: canClearLocalState reads three non-@Published stored properties plus platformBalances' private session; it re-renders today only because every transition also touches isRunning / isSyncing / isClearing / runningNetwork.)

🤖 Reviewed with Claude Code

@llbartekll
llbartekll force-pushed the codex/platform-balance-early-restore branch from 1e5bec8 to 41e1868 Compare September 14, 2026 11:10
@llbartekll

Copy link
Copy Markdown
Collaborator Author

Addressed the additional review-body points in 41e1868:

  • Stopping/rebuilding the same runtime now preserves derivedAddresses and activeAddressCount together with the cached Platform amount. Actual clear/wipe/selection invalidation still removes the snapshot.
  • The disabled Clear button now has visible help text when no bound runtime is available; it is no longer explained only by an unreachable button action.
  • The advanced-mode unavailable rows remain intentional: the accepted plan requires Platform to stay visible and missing wallet/account data to remain unavailable, rather than claiming a zero or hiding the row. Simple mode still omits Platform. A present type-14 account with an empty address pool is known zero; a missing account is not proof that an imported wallet has no Platform funds.

Both inline findings were also addressed. Validation: 61 controller, presentation and real-SwiftData tests passed, including nil network metadata, explicit wrong-network rejection, and isolation of two network containers holding the same wallet ID.

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

Copy link
Copy Markdown
Collaborator Author

Final follow-up validation at b651975, based on #1128 head f40e60f: 63 controller, presentation and real-SwiftData tests passed. Signed arm64 dashpay build and deep/strict signature verification passed using the newly rebuilt SDK cd093ac52d device archive. Framework copy SHA256: c9f00dc2e727baf31030f0642c8d30701c2b5ec207cd17a77896b0a7aea0496d.

The follow-up still contains exactly four own commits over #1128. Effective route-source validation from the last CodeRabbit review is preserved for both Shielded and Platform. The iPhone was disconnected; this validates the generic iOS device build, not a new device smoke test.

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

Re-reviewed at head b6519758. Both blockers from my last pass are closed — the re-subscribe skip no longer starts the loop without a subscriber, and the networkRaw term is gone from the wallet lookup.

Two inline blockers below.

Verified clean this pass: PlatformBalanceController's session/generation fencing across begin / detach / read / invalidateUnless (the stale-delivery and manager-restart paths behave as the tests claim, and read really does preserve the last known amount on a throw); clearLocalState's post-await re-validation and the detach → clearDisplay → re-subscribe → re-read ordering; the reader's overflow guard and its consistency with the widened clearLocalState predicate; pbxproj membership for all three new sources and all three test files; no dangling references to the removed seedFromPersistedState / refreshBalanceSnapshot / shieldedBalanceObservers; and every SDK API the new tests use exists.

Non-blocking recommendation:

  • HomeBalancePresentation.swift:10 — showsBreakdown went from platformSync.isRunning || shieldedDuffs != nil to showsPlatformBalance || shieldedDuffs != nil. In simple mode (showsPlatformBalance == false) with the shielded balance not yet restored, both disjuncts are false, so the whole breakdown card — including the Core row that was previously visible — disappears until restoration completes and then pops back in. HomeBalancePresentationTests.testAdvancedBreakdownIsVisibleBeforeBothLocalReads only covers advanced mode, so this case is untested.

🤖 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

Copy link
Copy Markdown
Collaborator Author

Completed this review round at 92fe929 over parent 2da1b5a. The follow-up now has five own commits.

  • Wallet/network selection changes invalidate the receive-address snapshot before replacement startup, while same-scope Stop/retry retains it.
  • The Home breakdown remains visible while local balances are unavailable, including simple mode; its total still excludes Platform in simple mode.
  • 65 controller, presentation and real-SwiftData tests passed. Signed arm64 dashpay build and deep/strict signature verification passed with SDK a68a65d113.

The build copied the rebuilt device archive with SHA256 d3f5d95829285dbcde3ff05320190389b2cbc9036ff4fc08495f86f06994e84f. This was a generic iOS device build, not a new device smoke test.

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

Re-reviewed at head 92fe9293. The receive-address blocker is closed — invalidating the addresses with the selected balance scope is the right fix, and it removes the cross-wallet window I described.

Two inline blockers, both in PlatformBalanceReader, and they are mirror images of each other: one turns an unknown into a confident zero, the other turns a knowable zero into a permanent unknown.

Verified clean this pass, so it does not get re-raised: the session/generation fencing in PlatformBalanceController has no session-token collision across the detach / begin / clear paths; clearLocalState's re-subscribe does not replay a stale sync event, because the SDK's resetPlatformAddressSyncState calls resetPlatformAddressPublishedMirror() first; clearDisplay(preservingPlatformBalance:) retention is guarded on every wallet and network switch path (prepareForNetworkSwitch in switchWallet and the network observer, invalidateBalancesIfSelectionChanged in handleWalletMaterialChanged, deletingPersistedWallet on wipe); the stranded-runtime elide hazard is closed by RuntimeReadinessPolicy's subscriptionsDetached term; refreshDerivedAddresses's session.scope.walletId cannot diverge from wallet?.walletId; and pbxproj has all three sources in both app targets and all three tests in the test target.

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

Approving at head 92fe9293. I checked both of your replies against the code rather than taking them at face value, and you are right on both — with one of my two findings resting on a false premise.

PlatformBalanceReader:41 — my proposed fix does not work, and I should have checked before suggesting it. I pointed at PersistentPlatformAddressesSyncState as the "never synced" signal. Its own doc says otherwise: "Kept as walletId for schema compatibility, but the persisted value is now a network-scoped key (one row per network) rather than a concrete wallet id." So it cannot distinguish "this wallet has never synced" from "some wallet on this network has" — exactly as you said. The limitation I described is real, but separating a genuine zero from an unsynced zero needs per-wallet provenance that does not exist yet, which is a larger change than this PR. Modelling local balance availability and documenting the boundary in the PR description is a reasonable line to draw.

PlatformBalanceReader:36 — withdrawing it, and your argument is the better one. I was asking you to turn the absence of a local Platform account into a numeric zero. That is fabricating a plausible default from missing data, which is precisely what this repo's third architecture guardrail forbids — "Model unknown data as unknown (nil / .unknown case) — never fabricate plausible defaults". resolvePlatformAccountAvailability establishes that this runtime has no local Platform Payment account; it says nothing about funds an imported seed may hold. Blocking a send from an account that does not exist locally is the honest outcome, not a defect.

Everything else I raised across the earlier rounds is closed: the re-subscribe no longer replays a stale event over the cleared counters, the networkRaw term is gone from the wallet lookup, the detach/scope-guard ordering no longer strands the loop without a subscriber, and receive addresses are now invalidated with the selected balance scope, which removes the cross-wallet window where the previous wallet's Platform address was still being published as the Receive QR.

Verified clean: the session and generation fencing in PlatformBalanceController has no token collision across detach / begin / clear; clearDisplay(preservingPlatformBalance:) retention is guarded on every wallet and network switch path; the stranded-runtime elide hazard is closed by RuntimeReadinessPolicy's subscriptionsDetached term; refreshDerivedAddresses's session.scope.walletId cannot diverge from wallet?.walletId; and pbxproj has all three sources in both app targets with all three tests in the test target.

Non-blocking, carried from the last round: HomeBalancePresentation.swift:10 — in simple mode with the shielded balance unrestored, both disjuncts of showsBreakdown are false, so the whole breakdown card including the Core row disappears until restoration completes and then pops back in. HomeBalancePresentationTests.testAdvancedBreakdownIsVisibleBeforeBothLocalReads covers only advanced mode.

Merge ordering: this sits on #1128 (approved) and ultimately on dashpay/platform#4709 (approved), so the stack is clear to land in that order.

🤖 Reviewed with Claude Code

@llbartekll
llbartekll force-pushed the codex/platform-balance-early-restore branch from 92fe929 to 844c2d4 Compare September 14, 2026 13:51
@llbartekll
llbartekll changed the base branch from codex/shielded-balance-reconnect to develop September 14, 2026 13:51
@llbartekll

Copy link
Copy Markdown
Collaborator Author

Retargeted to develop after #1128 merged. Current head: 844c2d48d, base: 5dae044a9.

  • Rebased exactly the five follow-up commits. git range-diff reports all five unchanged; no parent commits were replayed and there were no conflicts.
  • All 65 controller, presentation and real SwiftData tests passed after rebase. The initial link ran out of disk space; the rerun passed after removing only generated worktree build artifacts.
  • Signed arm64 dashpay build and deep/strict signature verification passed. The device archive still matches merged SDK #4709 (a68a65d113), SHA256 d3f5d95829285dbcde3ff05320190389b2cbc9036ff4fc08495f86f06994e84f.
  • This validates the generic iPhone build; no new physical-device smoke test was performed. The availability contract explained in the latest review replies is unchanged.

@llbartekll

Copy link
Copy Markdown
Collaborator Author

Thanks for verifying the availability contract and approving.

The remaining simple-mode breakdown recommendation was already fixed in the reviewed 92fe9293 tree and is preserved at rebased head 844c2d48d: HomeBalancePresentation no longer has a showsBreakdown property. Home renders the breakdown whenever the balance is not hidden, independent of whether Shielded restoration finished. testSimpleModeKeepsKnownCoreWhileShieldedIsUnavailable covers the partial Core total with unknown Shielded and Platform excluded; the older advanced-only test name cited in this review was also replaced.

The stack is now unstacked: #4709 and #1128 are merged, and #1129 targets develop with exactly its five own commits. All 65 tests and the signed generic iPhone build passed after that rebase, as reported above. No further code changes were needed for this review.

@llbartekll
llbartekll merged commit 8e16645 into develop Sep 14, 2026
7 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