Skip to content

feat(swift-example-app): shield the whole Core balance (Max) and recover it after a restart - #6050

Merged
QuantumExplorer merged 16 commits into
v5.1-devfrom
feat/swift-example-shielded-wallet-drain
Nov 22, 2026
Merged

QuantumExplorer merged 16 commits into
v5.1-devfrom
feat/swift-example-shielded-wallet-drain

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Basic explanation

What this does: The example iOS app can now move everything held at one Core (L1) account index into the wallet's own shielded balance in one step, called "Max". Before it runs, the screen shows the wallet's estimate of what will be swept, the fees, and what arrives in the shielded balance. If the app is killed mid-transfer, the next launch finds the unfinished transfer and offers to finish that same asset lock instead of losing track of it.

Value: The Swift SDK already supported this (preview, execute, status by a durable operation id), but no app screen used it, so it could not be tested by hand or shown to integrators. It also gives the Kotlin port a reference screen with fixed accessibility ids.

Risks: Low. No Rust or FFI changes and no consensus effect. One SDK wrapper, shieldedResumeFundFromAssetLock, now waits inside the manager's operation admission (see Public interface changes). Otherwise the change is app-only, and the existing fixed-amount shield path is unchanged unless the new toggle is turned on. Max only pays the wallet's own shielded address, because the drain sweeps whatever is eligible when it runs, which can exceed the estimate, and new Max transfers are not offered on mainnet until a drain's completion is proof-backed (#5580). Resume can only finish an existing asset lock, never build a new one. What could go wrong is in the app itself: a stored operation id that is never cleared would keep a stale row on the wallet screen, and Rust refuses a new Max while one is unfinished, so the user must resume it first. The flow has not yet been run on a funded testnet wallet or through a process kill (see testing).

Issue being fixed or feature implemented

docs/sdk/sdk-parity-manifest.json listed shielded.core_wallet_drain as supported in the Swift SDK and unsupported in SwiftExampleApp: shieldedWalletDrainPreview, shieldedFundFromWalletDrain and shieldedWalletDrainStatus had no caller in the app.

No open PR or issue covered the app side. Related SDK work: #5528, #5788; issues #5607, #5737, #5478, #5580.

What was done?

  • Max toggle on the Core to shielded screen (ShieldedFundFromAssetLockView, Core Balance source). When it is on, the amount field is replaced by the preview from shieldedWalletDrainPreview for the selected account index, and the button reads "Shield Max". The preview carries the wallet and account index it was read for; submit requires a match and uses the quoted index. Max pays the wallet's own shielded address, read at submit, with no override field, until the SDK can cap the swept amount (Wallet drain: let the host cap the swept balance at what the user confirmed #5607). The drain runs through the existing ShieldedFundFromAssetLockCoordinator, so it shares the per-wallet single-flight rule and the five-step progress UI with the fixed-amount shield.
  • Durable operation id. WalletDrainOperationStore writes the operation UUID, wallet, network, account index and recipient to a JSON file (.atomic) before the FFI call, as the SDK contract requires. It is a file rather than UserDefaults because it must be on disk before the call starts, and rather than a SwiftData model to avoid changing the shared model graph for an app-only marker. A corrupt file throws instead of reading as empty, so an unfinished transfer cannot be hidden.
  • Recovery. WalletDrainCoordinator.reconcile reads shieldedWalletDrainStatus for every stored id at launch, when the wallet screen opens, and after each attempt. A stored id is forgotten when Rust reports completed, or notSent with no attempt overlapping the read. A pending result or a failed read keeps it. Unfinished transfers are listed on the wallet screen under "Unfinished Max Transfers". Resume is offered only when a status read named the asset lock's outpoint, and calls shieldedResumeFundFromAssetLock with that exact outpoint and the stored recipient, which can never build a new lock; Rust writes the drain's completion receipt when it lands. A row without an outpoint offers only Check again, which re-reads the status. Progress follows the operation's own lock (by drain id or resumed outpoint), not the wallet's newest shielded lock. Deleting a wallet removes its stored ids.
  • No double listing. An asset lock whose operationId has a stored marker is not also offered in "Pending Platform Top Ups". A drain lock without a marker stays there, since resuming by exact outpoint is the fallback Rust supports.
  • Rust decides every amount, fee and input. The app shows only the preview's own figures.
  • No new Max on mainnet. Blocked at the toggle and at submit until a drain's completion is proof-backed (Wallet drain completes on an unauthenticated "already consumed" report; add a proof-backed asset-lock outpoint query #5580). Recovering an existing Max transfer works on every network.
  • Markerless drain checkpoints are recoverable. A drain lock stored as Built with no marker is offered in "Pending Platform Top Ups"; ordinary Built rows stay hidden.
  • No SDK rebuild while a funding is in flight. The shared rebuild (network switch, Docker toggle, devnet edits) now refuses before stopping SPV while a shield, Platform address top-up or identity registration is in flight, with a new SdkRebuildOutcome.fundingInFlight; Max and Resume refuse to start while a rebuild runs. Otherwise a rebuild could wait forever for a funding that needs a ChainLock from the SPV client it had just stopped.
  • SDK: exact-outpoint resume holds manager admission. shieldedResumeFundFromAssetLock now runs inside the manager's native-operation admission, so deleteWallet and shutdown() wait for it.
  • Generic resume uses the recorded recipient. A shielded asset lock resumed from "Pending Platform Top Ups" that recorded its recipient pays that recipient, shown read-only.
  • Not included: the CoinJoin drain (shieldedFundFromCoinJoinDrain), because the app shows CoinJoin balances only read-only and has no flow that starts from one; and a Max option in the send flow's Core to Shielded pair.
  • Docs: TEST_PLAN.md rows SH-18 (Max), SH-19 (restart), SH-20 (second Max refused while one is unfinished) and a restart tag. The manifest entry now says partial for the Swift example app, and PARITY_SUMMARY.md is regenerated.

Before / after

Shield from Core screen, Core Balance source:

Before: Core account picker, recipient, Amount [0.001] DASH, [Shield]
After:  Core account picker, [Max (everything at this account index)] toggle,
        recipient (own shielded address, read-only), with Max on:
          Swept from Core (est.)      0.31200000 DASH, 4 inputs
          Core network fee (est.)     0.00000985 DASH
          Shielded pool fee (est.)    0.00100000 DASH (credits)
          You receive, shielded (est.) 0.31099015 DASH (credits)
          Ready
        [Shield Max]

App killed after the asset lock was broadcast, then relaunched:

Before: no UI calls the drain, so nothing to recover in the app
After:  Wallet screen: "Unfinished Max Transfers (1)"
          Max to 3f9a1c2e...b07d44e1   Asset lock 8c41d0e2...:0   [Resume]
        Resume -> exact-outpoint resume of 8c41d0e2...:0, same recipient
        A row whose status read failed shows [Check again] instead

The figures above illustrate the layout; they are not from a run.

Public interface changes

No pub item in any Rust crate and no FFI symbol changed. In SwiftDashSDK no public signature changed; one public method's runtime behaviour did:

  • PlatformWalletManager.shieldedResumeFundFromAssetLock(walletId:outPointTxid:outPointVout:recipients:surplusOutput:) now runs inside the manager's native-operation admission, as the wallet-drain wrappers already did. While it runs, deleteWallet(walletId:) throws ("an async native operation is in flight") and shutdown() waits for it. During a shutdown it is rejected with PlatformWalletError.invalidHandle instead of calling into Rust. Existing callers compile unchanged.
  • Internal only: the drain helper withWalletDrainNativeOperation is renamed withAdmittedNativeOperation and moved to PlatformWalletManager.swift.

App side: All new types (WalletDrainOperationStore, WalletDrainOperationRecord, WalletDrainCoordinator, the two views) are internal to the SwiftExampleApp target. New accessibility ids, for the Kotlin app to reuse verbatim: shieldFromCore.maxToggle, shieldFromCore.maxPreview.{swept,l1Fee,poolFee,receive,status,refreshButton}, shieldFromCore.fixedRecipient, shieldFromCore.submitButton, walletDetail.unfinishedMaxTransfers, walletDetail.unfinishedMaxTransfer.resumeButton, walletDetail.unfinishedMaxTransfer.checkAgainButton.

How Has This Been Tested?

  • build_ios.sh --target sim --profile dev (framework), then the SwiftExampleApp target built with -warnings-as-errors: BUILD SUCCEEDED.
  • xcodebuild test -only-testing:SwiftExampleAppTests/WalletDrainRecoveryTests plus PendingPlatformTopUpResumeTests and WalletBalanceCardStateTests on an iPhone 17 simulator (iOS 27.2): plus WalletDeletionTests, SdkRebuildSequenceTests and AppStateSdkRebuildTests: all 64 passed. SDK: PlatformWalletShutdownTests and WalletDrainTests, 21 of 21 passed, including the new testShouldRefuseDeleteWalletWhileAnAdmittedOperationIsInFlight. The new tests cover the store surviving a reopen, removing only the named record or wallet, a corrupt file and an unwritable directory throwing, the rule for forgetting a stored id (including a notSent read overlapped by an attempt), a completed outcome that carries an error counting as done, the row action (In progress / Resume by outpoint / Check again), the progress lock matching, the progress steps for a failed attempt with no lock, the mainnet rule, the resumable-list decision including Built drain checkpoints, progress for recovered and completed locks, the resume message when a lock was never stored, and the rebuild refusal while a funding is in flight.
  • python3 scripts/check_sdk_parity_manifest.py --write-summary: OK.

Not run yet: SH-18, SH-19 and SH-20 on a funded testnet wallet, including the process-death run of SH-19. The new screens have compiled but have not been driven in the simulator. For that reason the manifest keeps the Swift example app at partial; the host-wide restart: tested rests on the existing SDK tests.

Separately, building the test target with -warnings-as-errors fails in StateTransitionTests.swift, which this PR does not touch; the tests above ran without that flag.

Breaking Changes

None.

Checklist:

  • I have performed a self-review of my own code
  • My Rust, FFI, WASM, Swift or Kotlin changes follow the coding conventions
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have added "!" to the title and described breaking changes in the corresponding section if my code contains any
  • I have made corresponding changes to the documentation if needed
  • If I added or changed GroveDB structure, I described it in the area's structure.rs, regenerated grovedb-structure.json, and checked the structure viewer link posted on this pull request
  • If I added or changed a system contract's document schemas, I checked the contract viewer link posted on this pull request

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

PR Hygiene · 7226e6b

  • Bots — thepastaclaw 2 threads unresolved — resolve them
  • Self-review — post /self-reviewed
  • Reviewer requests paused — your 5 review slots are occupied; this PR is excluded from reviewers' queues. Required approvals still count without a slot.
  • Build running
  • Approvals
    • sdk-parity — you own it
    • kotlin-sdk (packages/kotlin-sdk/PARITY_SUMMARY.md) — HashEngineering
    • swift-sdk (packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift, packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedFunding.swift, packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerWalletDrain.swift and 24 more) — llbartekll or romchornyi

When every merge requirement is met, the PR Hygiene check passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Client Only waiting-self-review Waiting for the author to post /self-reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants