Repository navigation
fix(wallet): restore cached Platform balance before network startup - #1129
Conversation
|
Warning Review limit reachedNext included review available in 10 minutes. View limit detailsLimit 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. Review configuration: ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (15)
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. Comment |
|
🕓 Queued for automated review — 10th in line, estimated start in ~50 min (commit 844c2d4)
|
thepastaclaw
left a comment
There was a problem hiding this comment.
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:
normalbygpt-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); agentphase1-reviewer,muse-spark-1.3-contributor— ffi-engineer (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— security-auditor (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-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; agentastra-verifier - Phase 2 reviewers:
gpt-6-astra— general (completed, effort high); agentphase2-reviewer,gpt-6-astra— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6-astra— security-auditor (completed, effort high); agentphase2-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.
456a978 to
4efc0b9
Compare
thepastaclaw
left a comment
There was a problem hiding this comment.
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:
normalbygpt-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); agentphase1-reviewer,muse-spark-1.3-contributor— security-auditor (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-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; agentastra-verifier - Phase 2 reviewers:
gpt-6-astra— general (completed, effort high); agentphase2-reviewer,gpt-6-astra— security-auditor (completed, effort high); agentphase2-reviewer
4efc0b9 to
3809436
Compare
romchornyi
left a comment
There was a problem hiding this comment.
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—clearLocalStatezeroes every persisted row, thenclearDisplay→platformBalances.clear()resets the scope and state to.unavailablewithout 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 untranslatedlastError, andPlatformSyncStatusScreen.swift:297-309disables Clear only onisClearing— 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 readplatformBalance, nowstate.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
left a comment
There was a problem hiding this comment.
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:
normalbygpt-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); agentphase1-reviewer,muse-spark-1.3-contributor— security-auditor (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-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; agentastra-verifier - Phase 2 reviewers:
gpt-6-astra— general (completed, effort high); agentphase2-reviewer,gpt-6-astra— security-auditor (completed, effort high); agentphase2-reviewer
3809436 to
701fdb4
Compare
|
Rebased onto the updated #1128 and addressed this review round in 701fdb4:
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. |
701fdb4 to
dba0abd
Compare
romchornyi
left a comment
There was a problem hiding this comment.
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
dba0abd to
1e5bec8
Compare
romchornyi
left a comment
There was a problem hiding this comment.
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(withHomeBalanceView.swift:223) —showsBreakdownis nowshowsPlatformBalance || shieldedDuffs != nil, and the Platform row is gated onshowsPlatformBalancealone. In advanced mode that is justviewModel.isAdvancedMode, so on an install where the runtime never starts (hasSDKWallet == false, whererefreshreturns with "no SDK wallet persisted; leaving runtime stopped") both balance states stay.unavailableforever 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 asplatformAccountAvailability == .unavailable, butHomeBalancePresentationhas no input for it, so "no account" and "not read yet" are indistinguishable on screen.PlatformAddressSyncCoordinator.swift:996—clearDisplaygates the balance onpreservingPlatformBalancebut still wipesactiveAddressCountandderivedAddressesunconditionally (1003-1004), andperformStop(deletingPersistedWallet: false)now passespreservingPlatformBalance: true. After Stop — or a failed Core start, which routes through the sameperformStop— 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—canClearLocalStateis the same predicate asclearLocalState'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:canClearLocalStatereads three non-@Publishedstored properties plusplatformBalances' private session; it re-renders today only because every transition also touchesisRunning/isSyncing/isClearing/runningNetwork.)
🤖 Reviewed with Claude Code
1e5bec8 to
41e1868
Compare
|
Addressed the additional review-body points in 41e1868:
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. |
7523946 to
b651975
Compare
|
Final follow-up validation at b651975, based on #1128 head f40e60f: 63 controller, presentation and real-SwiftData tests passed. Signed arm64 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
left a comment
There was a problem hiding this comment.
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—showsBreakdownwent fromplatformSync.isRunning || shieldedDuffs != niltoshowsPlatformBalance || 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.testAdvancedBreakdownIsVisibleBeforeBothLocalReadsonly covers advanced mode, so this case is untested.
🤖 Reviewed with Claude Code
b651975 to
92fe929
Compare
|
Completed this review round at 92fe929 over parent 2da1b5a. The follow-up now has five own commits.
The build copied the rebuilt device archive with SHA256 |
romchornyi
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
92fe929 to
844c2d4
Compare
|
Retargeted to
|
|
Thanks for verifying the availability contract and approving. The remaining simple-mode breakdown recommendation was already fixed in the reviewed The stack is now unstacked: #4709 and #1128 are merged, and #1129 targets |
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
isRunningflag.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?
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
PersistentPlatformAddressesSyncStateis a shared network checkpoint, despite its legacywalletIdfield name; it cannot certify discovery of a particular wallet. This PR does not introduce that additional guarantee.How Has This Been Tested?
844c2d48doverdevelop(5dae044a9): 65 controller, presentation and real SwiftData tests passed, including the shielded regressions.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.dashpaybuild and deep/strict signature verification passed using SDKa68a65d113. The rebuilt device archive SHA256 isd3f5d95829285dbcde3ff05320190389b2cbc9036ff4fc08495f86f06994e84f. This was a generic device build, not a new physical-device smoke test. The simulator scenarios below were performed before this review round.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.Breaking Changes
None. Existing
platformBalance/$platformBalanceconsumers remain supported.Checklist:
For repository code-owners and collaborators only