Repository navigation
feat(swift-sdk): top up someone else's identity from the Core balance - #6139
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the
|
|
✅ Final review complete — no blockers (commit 0c8c807) · triage: critical |
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — Phase 2 only (queue backlog)
Changes requested: 2 blockers
- Retrying an unconfirmed top-up after
assetLockNotTrackedcan pay twice —packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5729-5732(new)
Impact: An iOS app following this guidance can fund a replacement from other coins while the original lock remains recoverable and can still pay the same identity. - A managed top-up resume can report a cached balance as the payment's proved balance —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5700-5704(new)
Impact: An iOS app recording a successful top-up to a managed identity can record a different balance from the one proved for that payment if a concurrent refresh has already advanced the wallet cache.
This adds Swift APIs to fund and resume external identity top-ups and stores their recipients in the unreleased SwiftData V5 schema. The SwiftData explorer check passed, but no Swift build or test check is recorded for this head; the author reports a passing local Swift test suite. The Kotlin emulator job was cancelled after Gradle reported BUILD SUCCESSFUL, with no code failure shown in the job log.
🔴 2 blocking | 🟡 8 suggestion(s)
Review provenance
Source: reviewer 1: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.2-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.2-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 5: gpt-6.2-astra (agent: phase2-reviewer, role: security-auditor); reviewer 6: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 7: gpt-6.2-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 8: gpt-6.2-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 9: gpt-6.2-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 10: gpt-6.2-astra (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.2-sol(effort low) — ManagedPlatformWallet.swift adds a funds-movement flow whose recovery depends on PlatformWalletPersistenceHandler.swift preserving the intended recipient across failed calls, later writes, and restarts. - Phase 1 reviewers: not run (skipped for throughput: 14 PRs queued, above the 10 limit)
- Second Phase-2 pass: on this first full review every Phase-2 reviewer also ran a second, independent time, and the verifier weighed both sets
- Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-astra— general (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— security-auditor (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— general (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— security-auditor (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift`:
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5729-5732: Retrying an unconfirmed top-up after `assetLockNotTracked` can pay twice
Impact: An iOS app following this guidance can fund a replacement from other coins while the original lock remains recoverable and can still pay the same identity.
A same-session lookup miss does not establish that the first payment is gone. When Core rejects a broadcast, `wallet/asset_lock/build.rs` untracks the lock before attempting durable deletion. If the SwiftData removal round fails, Rust returns `transactionBroadcastUnconfirmed` (20), keeps the inputs reserved, and leaves the outpoint absent from the in-memory map that resume reads. The original `Built` row can reappear on restore and be resumed even after a replacement has paid. Give code 20 its own branch, as the native export does, and require a definitive not-sent outcome before funding another lock.
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5700-5704: A managed top-up resume can report a cached balance as the payment's proved balance
Impact: An iOS app recording a successful top-up to a managed identity can record a different balance from the one proved for that payment if a concurrent refresh has already advanced the wallet cache.
The new Swift result promises the balance proved by the resumed transition, but the native paths return different values. In `wallet/identity/network/registration.rs`, a bound lock or an unbound lock paying a managed identity goes through `top_up_identity_with_funding`, which replaces the proved value with the result of `record_top_up_balance`. `persist_confirmed_balance` returns the value kept locally, so a newer cached snapshot wins even when its balance differs. The external route already returns the proved value separately. Keep the cache freshness check and have the Rust recorded-recipient operation return the transition's proved balance on both routes; test the returned balance separately from the retained balance.
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5776-5779: A process kill can leave a recoverable lock unlinked from its payment request
Impact: An app that starts two equal payments to the same identity can recover the lock rows but cannot reliably match them to its own requests if it dies before the native calls return.
SwiftData keeps the recipient, but the app cannot durably associate its request with the outpoint until this callback runs, after the native proof wait and submission. The Rust wallet already invokes `on_built` before persisting or broadcasting the lock, but the current export only saves that outpoint for its return value. An additive callback-capable export could forward the existing observer, as other Swift funding APIs do, so the app can record the association before the lock becomes recoverable.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:773-779: A conflicting consumed snapshot can make a live top-up look completed
Impact: If SwiftData receives a consumed snapshot for a different recipient than the one on a live row, the next wallet restore sees the original row as consumed and cannot offer it for recovery.
The persistence adapter can commit a status and recipient that came from different snapshots. For a stored `Broadcast/A` and an incoming `Consumed/B`, the native bridge first sends the legacy row without B, so `persistAssetLocks` stages `statusRaw = 4`. The sidecar callback then checks that newly staged status, accepts the conflict as stale, and lets `endChangeset` save `Consumed/A`. SQLite checks the pre-update row: it rejects the conflict if the row was live and skips the entire incoming row if it was already consumed. Apply both callbacks as one update against the pre-round row and add a production-order regression test that checks both status and recipient. The adapter mismatch is reproducible at the callback boundary; the ordinary single-wallet resume and assignment paths already guard against replacing a recorded recipient.
In `packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift:224-237: Editing a saved asset-lock recipient can change who gets paid after restart
Impact: An SDK consumer that edits and saves a fetched SwiftData lock can change the destination of a pending payment without calling the wallet's assignment API.
The public setter exposes a write that the SDK documents as immutable after assignment. An app using its supplied `ModelContainer` can save another valid 32-byte identity directly; the sidecar loader checks the length and restores the edited value to Rust as the recorded recipient. This bypasses Rust's one-time assignment checks, although it requires the app to write the store directly. Expose a public getter with nonpublic mutation, keep recipient-bearing construction internal, and direct clients to `assignTopUpRecipient`. This protects the SDK API from accidental edits, not from an app that controls the underlying store.
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift:254-255: References to the previous asset-lock initializer no longer resolve
Impact: A Swift caller using the base revision's `PersistentAssetLock.init` as a factory function cannot rebuild unchanged, even though ordinary constructor calls still work.
A default for `identityRecipient` lets callers omit it in a constructor call, but does not preserve the initializer's old full name or function arity. Keep the previous public initializer and let the persistence adapter set the optional field internally, or forward to an internal overload with an explicit `identityRecipient:` parameter. Neither option needs a schema version change.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift:690-697: Code 81 tells apps to assign a recipient even when a seed-restored lock cannot accept one
Impact: A recovery UI following these docs can show a recipient picker for a chain-restored lock only for assignment to fail with code 24.
A missing recipient is not proof that assignment is allowed. Rust can return code 81 for a recipient-less `RecoveredFromChain` lock, but leaves `identityRecipientUnassigned` false and refuses assignment because Platform consumption is unknown. State in the Swift error, raw result-code, and resume docs that code 81 means this resume submitted nothing because there is no recorded recipient. Offer assignment only when the Rust-provided flag is true.
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift:327-331: Existing exhaustive wallet-error switches become non-exhaustive on rebuild
Impact: Swift apps that enumerate every previous case of `PlatformWalletResultCode` or `PlatformWalletError` without a default must update their switches even if they do not call the new API.
The new cases preserve the native numeric mapping but change Swift source compatibility. `SwiftDashSDK` is built from source without library evolution, and both public enums gain a case. Document `errorAssetLockRecipientUnknown` and `assetLockRecipientUnknown` in the PR's Breaking Changes section. No protocol bump or `!` in the title is needed: the coding conventions reserve that marker for consensus breaks.
In `packages/swift-sdk/SwiftTests/SwiftDashSDKTests/IdentityTopUpRecipientTests.swift`:
- [SUGGESTION] packages/swift-sdk/SwiftTests/SwiftDashSDKTests/IdentityTopUpRecipientTests.swift:31-40: The code-81 test passes a libc string to Rust's `CString` deallocator
Impact: Running the test violates the native result's allocation contract and can crash if the allocators are incompatible.
`strdup` produces a libc-owned pointer, but `ffi.check()` takes ownership through `PlatformWalletResult`, whose deinitializer calls `platform_wallet_ffi_result_free`. That function uses `CString::from_raw`, which requires a pointer produced by `CString::into_raw`. The preceding assertions already cover the native code mapping. Use the existing Swift initializer to verify the error case and detail without transferring a foreign allocation.
- [SUGGESTION] packages/swift-sdk/SwiftTests/SwiftDashSDKTests/IdentityTopUpRecipientTests.swift:113-126: The Swift tests would miss a lost recovery outpoint on a post-build error
Impact: A regression that drops the outpoint after a failed top-up would leave apps without the identifier they need to resume it while the Swift wrapper tests still pass.
The null-handle test proves the callback stays silent when nothing is built, and the decoder test proves a nonzero outpoint can be parsed. Neither verifies delivery when the native result contains both a built outpoint and an error. Moving `outcome.get()` ahead of the callback would pass both tests. Stub the native result or factor the delivery step, then assert that a nonzero outpoint is delivered exactly once before the error reaches the caller.
| /// - any other error: resume that outpoint with | ||
| /// `resumeTopUpToRecordedRecipient`, after the next launch if it is not | ||
| /// tracked now. A resume answering `assetLockNotTracked` means the lock | ||
| /// was removed before it was sent, so a new call is safe. |
There was a problem hiding this comment.
✅ Resolved at
a242c339; see the replies below.
🔴 Blocking: Retrying an unconfirmed top-up after assetLockNotTracked can pay twice
Impact: An iOS app following this guidance can fund a replacement from other coins while the original lock remains recoverable and can still pay the same identity.
A same-session lookup miss does not establish that the first payment is gone. When Core rejects a broadcast, wallet/asset_lock/build.rs untracks the lock before attempting durable deletion. If the SwiftData removal round fails, Rust returns transactionBroadcastUnconfirmed (20), keeps the inputs reserved, and leaves the outpoint absent from the in-memory map that resume reads. The original Built row can reappear on restore and be resumed even after a replacement has paid. Give code 20 its own branch, as the native export does, and require a definitive not-sent outcome before funding another lock.
| /// - any other error: resume that outpoint with | |
| /// `resumeTopUpToRecordedRecipient`, after the next launch if it is not | |
| /// tracked now. A resume answering `assetLockNotTracked` means the lock | |
| /// was removed before it was sent, so a new call is safe. | |
| /// - `transactionBroadcastUnconfirmed`: keep the reported outpoint and | |
| /// reconcile it after wallet restore if it is not tracked now. Do not | |
| /// build a new lock: `assetLockNotTracked` is only an in-memory lookup | |
| /// result, not proof that the original lock is gone. | |
| /// - any other error: resume the reported outpoint with | |
| /// `resumeTopUpToRecordedRecipient`. Build a new lock only when the | |
| /// original is known not to have been sent and cannot still be resumed. |
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, security-auditor)
There was a problem hiding this comment.
Fixed in fd00f37: every retry instruction after onAssetLockBuilt allows a new lock only after a definite not-sent outcome; transactionBroadcastUnconfirmed never does. Applied at the topUpExternalIdentityWithFunding doc (own branch for code 20, mirroring the FFI doc in identity_top_up.rs; the assetLockNotTracked licence is limited to the other errors). The resume doc does not give retry advice.
There was a problem hiding this comment.
Resolved (re-reviewed at fd00f374): The separate code-20 branch now says not to fund a replacement even if same-session resume returns assetLockNotTracked. That covers the failed durable-removal case described in the thread.
There was a problem hiding this comment.
Still applies (re-reviewed at 721bf990): Judged fixed at fd00f374; raised again and confirmed by an independent pass: If a user deletes the wallet while topUpExternalIdentityWithFunding is in flight, Core can accept the lock before teardown removes the wallet, and the call can return WalletNotFound rather than code 20 while still reporting the built outpoint. After reimporting the seed, an app that calls resumeTopUpToRecordedRecipient before the rescan finds that outpoint gets assetLockNotTracked and, following the Swift docs, can fund a replacement from other available UTXOs. Once the rescan recovers the original lock, the app can assign it to the same identity and resume it, spending two locks for one intended top-up.
The separate code-20 branch fixes the failed-deletion case you addressed. The narrower exception still fails after a different error: Core can accept the first lock before wallet removal causes the status update to fail, and code 23 after reimport says nothing about that accepted transaction.
There was a problem hiding this comment.
Fixed in a242c33: once the outpoint is reported, no answer but transactionBroadcastRejected licenses a new lock. assetLockNotTracked now means only "not tracked now" (the lock may still be on the network or reappear on restore), and code 20 keeps its own branch: resume that outpoint, never build again. Applied at the topUpExternalIdentityWithFunding docs and the resume docs (resumeTopUpToRecordedRecipient); the outpoint goes through deliverTopUpOutcome.
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): The funding docs now say a lookup miss after removal and reimport does not establish that the first lock was never sent. After an outpoint is reported, only definitive broadcast rejection is documented as safe for fresh funding.
| /// Outcome of `resumeTopUpToRecordedRecipient`: the identity the lock | ||
| /// paid (32 bytes; in this wallet or not) and its proved new balance. | ||
| public struct IdentityTopUpResult: Equatable, Sendable { | ||
| public let identityId: Data | ||
| public let newBalance: UInt64 |
There was a problem hiding this comment.
✅ Resolved at
a242c339; see the replies below.
🔴 Blocking: A managed top-up resume can report a cached balance as the payment's proved balance
Impact: An iOS app recording a successful top-up to a managed identity can record a different balance from the one proved for that payment if a concurrent refresh has already advanced the wallet cache.
The new Swift result promises the balance proved by the resumed transition, but the native paths return different values. In wallet/identity/network/registration.rs, a bound lock or an unbound lock paying a managed identity goes through top_up_identity_with_funding, which replaces the proved value with the result of record_top_up_balance. persist_confirmed_balance returns the value kept locally, so a newer cached snapshot wins even when its balance differs. The external route already returns the proved value separately. Keep the cache freshness check and have the Rust recorded-recipient operation return the transition's proved balance on both routes; test the returned balance separately from the retained balance.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, security-auditor)
There was a problem hiding this comment.
Fixed in fd00f37 (doc): IdentityTopUpResult.newBalance now says a managed identity may return a newer verified balance the wallet already holds rather than this payment's proved one. Returning the proved value on the managed route needs a change to top_up_identity_with_funding in the base (#5931), so I leave that to it; the base's topUpIdentityWithFunding behaves the same way.
There was a problem hiding this comment.
Still applies (re-reviewed at fd00f374): The new wording accounts for a newer published balance, but a newer refresh can advance the pending watermark without publishing its balance; if the write retry fails, Swift receives the old published value instead. You do not need to change #5931 to fix the Swift contract: describe the managed result as locally retained, with no guarantee that it reflects the payment.
There was a problem hiding this comment.
Still applies (re-reviewed at 721bf990): Your documentation change covers a newer balance that the wallet actually published, and the underlying fix does belong in #5931. A newer proof whose store fails is only queued; if it suppresses the delayed payment proof and its write still fails, Swift can receive the pre-payment balance, which the revised contract does not allow.
There was a problem hiding this comment.
Fixed in a242c33 by the contract, not by a new value: IdentityTopUpResult.newBalance is the proved balance for an identity this wallet does not manage, and for one it manages the balance the wallet retains after recording the top-up, documented as not necessarily this payment's (concurrent refresh, failed store). Returning the proved value there would need a native change in #5931's top_up_identity_with_funding; I left Rust unchanged in this Swift port.
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): Your revised contract describes the managed result as the locally retained balance and explicitly allows an older value after a failed store. That matches the native return without presenting it as proof of this payment.
| guard let record = try modelFetcher.fetch(descriptor, in: backgroundContext).first else { | ||
| throw AssetLockPersistenceError.missingRecord | ||
| } | ||
| if let previous = record.identityRecipient, previous != identityId { | ||
| if Self.isTerminalAssetLockStatus(record.statusRaw) { return } | ||
| throw AssetLockPersistenceError.conflictingIdentityRecipient | ||
| } |
There was a problem hiding this comment.
✅ Resolved at
a242c339; see the replies below.
🟡 Suggestion: A conflicting consumed snapshot can make a live top-up look completed
Impact: If SwiftData receives a consumed snapshot for a different recipient than the one on a live row, the next wallet restore sees the original row as consumed and cannot offer it for recovery.
The persistence adapter can commit a status and recipient that came from different snapshots. For a stored Broadcast/A and an incoming Consumed/B, the native bridge first sends the legacy row without B, so persistAssetLocks stages statusRaw = 4. The sidecar callback then checks that newly staged status, accepts the conflict as stale, and lets endChangeset save Consumed/A. SQLite checks the pre-update row: it rejects the conflict if the row was live and skips the entire incoming row if it was already consumed. Apply both callbacks as one update against the pre-round row and add a production-order regression test that checks both status and recipient. The adapter mismatch is reproducible at the callback boundary; the ordinary single-wallet resume and assignment paths already guard against replacing a recorded recipient.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, security-auditor)
There was a problem hiding this comment.
Fixed in a242c33: the sidecar and the upsert check a conflicting recipient against the lock's status before the round (assetLockStatusBeforeRound), as SQLite does, so Consumed/B over a live Broadcast/A is refused instead of committing Consumed/A. Test: testShouldRefuseAConflictingRecipientInTheRoundThatConsumesALiveRow.
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): Your pre-round status check now refuses Consumed/B over a live Broadcast/A row. The regression test follows native callback order and verifies that rollback preserves both Broadcast and recipient A.
| /// 32-byte identity an unbound identity top-up (`fundingTypeRaw == 2`) | ||
| /// was built or assigned to pay, which may be an identity this wallet | ||
| /// does not manage. Written by Rust with the row before the lock is | ||
| /// dispatched (or when the user assigns one to a lock that records | ||
| /// none) and immutable afterwards: a resume pays this identity and | ||
| /// refuses another (`assetLockRecipientMismatch`). `nil` for other | ||
| /// funding types and for unbound locks that record no identity, such as | ||
| /// one rebuilt from the chain; a resume of those is refused | ||
| /// (`assetLockRecipientUnknown`) until one is assigned. | ||
| /// | ||
| /// Default `nil` on the column keeps SwiftData's lightweight migration | ||
| /// safe for rows that pre-date this field. Lands in the live, not yet | ||
| /// published, V5 schema. | ||
| public var identityRecipient: Data? |
There was a problem hiding this comment.
✅ Resolved at
a242c339; see the replies below.
🟡 Suggestion: Editing a saved asset-lock recipient can change who gets paid after restart
Impact: An SDK consumer that edits and saves a fetched SwiftData lock can change the destination of a pending payment without calling the wallet's assignment API.
The public setter exposes a write that the SDK documents as immutable after assignment. An app using its supplied ModelContainer can save another valid 32-byte identity directly; the sidecar loader checks the length and restores the edited value to Rust as the recorded recipient. This bypasses Rust's one-time assignment checks, although it requires the app to write the store directly. Expose a public getter with nonpublic mutation, keep recipient-bearing construction internal, and direct clients to assignTopUpRecipient. This protects the SDK API from accidental edits, not from an app that controls the underlying store.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, security-auditor)
There was a problem hiding this comment.
Fixed in fd00f37: identityRecipient is public internal(set); only the SDK writes it (at build and in assignTopUpRecipient). The schema check is unchanged.
There was a problem hiding this comment.
Still applies (re-reviewed at fd00f374): public internal(set) closes direct edits on a fetched row, but callers can still set the field through public init(..., identityRecipient:). Saving a replacement for the same unique outPointHex can update the value the loader restores without calling the assignment API.
There was a problem hiding this comment.
Fixed in a242c33: identityRecipient is public internal(set), and the initializer that sets it is internal; clients assign through assignTopUpRecipient.
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): Your internal initializer closes the construction path left open by the earlier setter change. Clients can read the recipient but cannot supply a different one through the public model API.
| /// Code 81: an unbound identity top-up lock records no identity to pay — | ||
| /// it was rebuilt from the chain, for example after a restore from the | ||
| /// seed — so no resume pays it; it may have been meant for someone | ||
| /// else's identity. Nothing was submitted or paid. Not retryable as is: | ||
| /// assign the lock a recipient the user chooses | ||
| /// (`ManagedPlatformWallet.assignTopUpRecipient`), then resume it. Such a | ||
| /// lock is flagged `identityRecipientUnassigned` on the tracked-lock | ||
| /// lists. |
There was a problem hiding this comment.
✅ No longer applies at
721bf990; see the replies below.
🟡 Suggestion: Code 81 tells apps to assign a recipient even when a seed-restored lock cannot accept one
Impact: A recovery UI following these docs can show a recipient picker for a chain-restored lock only for assignment to fail with code 24.
A missing recipient is not proof that assignment is allowed. Rust can return code 81 for a recipient-less RecoveredFromChain lock, but leaves identityRecipientUnassigned false and refuses assignment because Platform consumption is unknown. State in the Swift error, raw result-code, and resume docs that code 81 means this resume submitted nothing because there is no recorded recipient. Offer assignment only when the Rust-provided flag is true.
| /// Code 81: an unbound identity top-up lock records no identity to pay — | |
| /// it was rebuilt from the chain, for example after a restore from the | |
| /// seed — so no resume pays it; it may have been meant for someone | |
| /// else's identity. Nothing was submitted or paid. Not retryable as is: | |
| /// assign the lock a recipient the user chooses | |
| /// (`ManagedPlatformWallet.assignTopUpRecipient`), then resume it. Such a | |
| /// lock is flagged `identityRecipientUnassigned` on the tracked-lock | |
| /// lists. | |
| /// Code 81: an unbound identity top-up lock has no recorded recipient. | |
| /// This resume submitted nothing. Offer `assignTopUpRecipient` only if | |
| /// the tracked lock has `identityRecipientUnassigned == true`. | |
| /// A recipient-less `RecoveredFromChain` lock also returns this error, | |
| /// but its Platform consumption is unknown, so it is not flagged and | |
| /// assignment returns `assetLockAlreadyConsumed`. |
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, security-auditor)
There was a problem hiding this comment.
Fixed in fd00f37: code 81 and the resume doc no longer promise that a lock rebuilt from the chain can be assigned. Only a lock flagged identityRecipientUnassigned can; a RecoveredFromChain lock is refused with assetLockConsumptionUnknown and stays unpaid.
There was a problem hiding this comment.
Still applies (re-reviewed at fd00f374): You corrected the assignment gate in the typed comment and excluded chain-restored locks in the resume docs, but the separate raw code-81 comment still instructs callers to assign one. The Swift refusal is .assetLockAlreadyConsumed (24), and it means prior consumption is unknown, not that the lock stayed unpaid.
There was a problem hiding this comment.
No longer applies (re-reviewed at 721bf990): The typed code-81 docs now explain the distinction you called out, with the rebased behavior: a seed-restored lock is refused by default with code 82, but explicit acknowledgement can make assignment possible. The original unconditional-refusal premise no longer applies.
| if let built { | ||
| onAssetLockBuilt(built) | ||
| } | ||
| return try outcome.get() |
There was a problem hiding this comment.
⏭️ Deferred (maintainer decision; not blocking) at
a242c339; see the replies below.
🟡 Suggestion: A process kill can leave a recoverable lock unlinked from its payment request
Impact: An app that starts two equal payments to the same identity can recover the lock rows but cannot reliably match them to its own requests if it dies before the native calls return.
SwiftData keeps the recipient, but the app cannot durably associate its request with the outpoint until this callback runs, after the native proof wait and submission. The Rust wallet already invokes on_built before persisting or broadcasting the lock, but the current export only saves that outpoint for its return value. An additive callback-capable export could forward the existing observer, as other Swift funding APIs do, so the app can record the association before the lock becomes recoverable.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, security-auditor)
There was a problem hiding this comment.
Deferred (re-reviewed at a242c339): The current export still returns the outpoint only when the native operation finishes, so Swift cannot forward Rust's earlier build notification through this signature. Your linked issue covers both the callback-capable export and Swift forwarding.
| let ffi = PlatformWalletFFIResult( | ||
| code: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_ASSET_LOCK_RECIPIENT_UNKNOWN, | ||
| message: strdup("no recorded recipient")) | ||
| XCTAssertThrowsError(try ffi.check()) { error in | ||
| guard case PlatformWalletError.assetLockRecipientUnknown(let detail) = error else { | ||
| return XCTFail("expected assetLockRecipientUnknown, got \(error)") | ||
| } | ||
| XCTAssertEqual(detail, "no recorded recipient") | ||
| XCTAssertEqual(error.localizedDescription, "no recorded recipient") | ||
| } |
There was a problem hiding this comment.
✅ Resolved at
a242c339; see the replies below.
🟡 Suggestion: The code-81 test passes a libc string to Rust's CString deallocator
Impact: Running the test violates the native result's allocation contract and can crash if the allocators are incompatible.
strdup produces a libc-owned pointer, but ffi.check() takes ownership through PlatformWalletResult, whose deinitializer calls platform_wallet_ffi_result_free. That function uses CString::from_raw, which requires a pointer produced by CString::into_raw. The preceding assertions already cover the native code mapping. Use the existing Swift initializer to verify the error case and detail without transferring a foreign allocation.
| let ffi = PlatformWalletFFIResult( | |
| code: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_ASSET_LOCK_RECIPIENT_UNKNOWN, | |
| message: strdup("no recorded recipient")) | |
| XCTAssertThrowsError(try ffi.check()) { error in | |
| guard case PlatformWalletError.assetLockRecipientUnknown(let detail) = error else { | |
| return XCTFail("expected assetLockRecipientUnknown, got \(error)") | |
| } | |
| XCTAssertEqual(detail, "no recorded recipient") | |
| XCTAssertEqual(error.localizedDescription, "no recorded recipient") | |
| } | |
| let error = PlatformWalletError(code: .errorAssetLockRecipientUnknown, message: "no recorded recipient") | |
| guard case .assetLockRecipientUnknown(let detail) = error else { | |
| return XCTFail("expected assetLockRecipientUnknown, got \(error)") | |
| } | |
| XCTAssertEqual(detail, "no recorded recipient") | |
| XCTAssertEqual(error.localizedDescription, "no recorded recipient") |
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, security-auditor)
There was a problem hiding this comment.
Still applies (re-reviewed at 721bf990): The new code-82 test repeats the code-81 fixture's strdup ownership mismatch. Testing the detail through the Swift error initializer avoids transferring either allocation to Rust.
There was a problem hiding this comment.
Fixed in a242c33: both code tests (89, 90) use PlatformWalletError(code:message:); no strdup left.
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): Both tests now verify the native constant mapping separately and use PlatformWalletError(code:message:) for the message assertions. Neither transfers a libc allocation to Rust.
| /// An unknown wallet handle fails before any lock is built: the error | ||
| /// reaches the caller and no outpoint is reported, so a new call is safe. | ||
| func testShouldReportNoOutPointWhenNothingWasBuilt() async { | ||
| let reported = Reported() | ||
| do { | ||
| _ = try await wallet.topUpExternalIdentityWithFunding( | ||
| identityId: identityId, amountDuffs: 50_500, accountIndex: 0, | ||
| onAssetLockBuilt: { reported.append($0) }) | ||
| XCTFail("expected notFound") | ||
| } catch PlatformWalletError.notFound { | ||
| } catch { | ||
| XCTFail("expected notFound, got \(error)") | ||
| } | ||
| XCTAssertTrue(reported.all.isEmpty) |
There was a problem hiding this comment.
✅ Resolved at
a242c339; see the replies below.
🟡 Suggestion: The Swift tests would miss a lost recovery outpoint on a post-build error
Impact: A regression that drops the outpoint after a failed top-up would leave apps without the identifier they need to resume it while the Swift wrapper tests still pass.
The null-handle test proves the callback stays silent when nothing is built, and the decoder test proves a nonzero outpoint can be parsed. Neither verifies delivery when the native result contains both a built outpoint and an error. Moving outcome.get() ahead of the callback would pass both tests. Stub the native result or factor the delivery step, then assert that a nonzero outpoint is delivered exactly once before the error reaches the caller.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, security-auditor)
There was a problem hiding this comment.
Fixed in a242c33: delivery is factored into deliverTopUpOutcome; testShouldDeliverTheBuiltOutPointOnceBeforeTheError asserts the outpoint is reported exactly once before the error is thrown.
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): The production wrapper now calls your deliverTopUpOutcome helper, and the test checks exactly one delivery inside the thrown-error assertion. Moving outcome.get() ahead of the callback would fail that assertion.
| /// An unbound identity top-up lock records no identity to pay (it was | ||
| /// rebuilt from the chain, for example after a restore from the seed), | ||
| /// so no resume pays it. Nothing was submitted or paid. Not retryable as | ||
| /// is: assign it a recipient the user chooses, then resume it. | ||
| case errorAssetLockRecipientUnknown = 81 |
There was a problem hiding this comment.
✅ Resolved at
a242c339; see the replies below.
🟡 Suggestion: Existing exhaustive wallet-error switches become non-exhaustive on rebuild
Impact: Swift apps that enumerate every previous case of PlatformWalletResultCode or PlatformWalletError without a default must update their switches even if they do not call the new API.
The new cases preserve the native numeric mapping but change Swift source compatibility. SwiftDashSDK is built from source without library evolution, and both public enums gain a case. Document errorAssetLockRecipientUnknown and assetLockRecipientUnknown in the PR's Breaking Changes section. No protocol bump or ! in the title is needed: the coding conventions reserve that marker for consensus breaks.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, security-auditor)
There was a problem hiding this comment.
Still applies (re-reviewed at 721bf990): This revision adds code 82 alongside 81 to both Swift enums. The new cases correctly mirror Rust, but clients rebuilding exhaustive switches now need migration guidance for both.
There was a problem hiding this comment.
Done: the PR's Breaking Changes section now lists the new PlatformWalletResultCode / PlatformWalletError cases (codes 89 and 90).
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): Your Breaking Changes section lists both new cases on each public enum, gives the verified values 89 and 90, and tells callers how to update exhaustive switches.
| shieldedRecipientRaw43: Data? = nil, | ||
| identityRecipient: Data? = nil |
There was a problem hiding this comment.
✅ Resolved at
a242c339; see the replies below.
🟡 Suggestion: References to the previous asset-lock initializer no longer resolve
Impact: A Swift caller using the base revision's PersistentAssetLock.init as a factory function cannot rebuild unchanged, even though ordinary constructor calls still work.
A default for identityRecipient lets callers omit it in a constructor call, but does not preserve the initializer's old full name or function arity. Keep the previous public initializer and let the persistence adapter set the optional field internally, or forward to an internal overload with an explicit identityRecipient: parameter. Neither option needs a schema version change.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, security-auditor)
There was a problem hiding this comment.
Fixed in a242c33: the public initializer keeps its previous signature; the identityRecipient: overload is internal.
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): Your public initializer now has the same labels and arity as the base version. The overload with identityRecipient: is internal, so existing public initializer references still resolve.
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 2 only (queue backlog)
Changes requested: 1 blocker
- A managed top-up resume can report a cached balance as the payment's proved balance —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5700-5703(thread, carried)
Impact: An iOS app that resumes a managed identity’s top-up while a balance refresh cannot save its result can receive success with the pre-payment balance innewBalance.
New on this head: This revision clarifies Swift’s external top-up retry and recipient-assignment guidance, restricts direct writes to the stored recipient, and revises the managed-resume balance documentation. The SwiftData model-coverage check and Kotlin SDK build and tests passed; no Swift test check is reported for this head, and the review check is pending.
🔴 1 blocking | 🟡 8 suggestion(s)
Still open from earlier rounds (9)
- 🔴 Blocking: A managed top-up resume can report a cached balance as the payment's proved balance —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5700-5703(thread) - 🟡 Suggestion: Code 81 tells apps to assign a recipient even when a seed-restored lock cannot accept one —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift:690-700(thread) - 🟡 Suggestion: Editing a saved asset-lock recipient can change who gets paid after restart —
packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift:254-258(thread) - 🟡 Suggestion: A conflicting consumed snapshot can make a live top-up look completed —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:773-779(thread) - 🟡 Suggestion: A process kill can leave a recoverable lock unlinked from its payment request —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5781-5785(thread) - 🟡 Suggestion: References to the previous asset-lock initializer no longer resolve —
packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift:254-257(thread) - 🟡 Suggestion: Existing exhaustive wallet-error switches become non-exhaustive on rebuild —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift:327-331(thread) - 🟡 Suggestion: The Swift tests would miss a lost recovery outpoint on a post-build error —
packages/swift-sdk/SwiftTests/SwiftDashSDKTests/IdentityTopUpRecipientTests.swift:113-126(thread) - 🟡 Suggestion: The code-81 test passes a libc string to Rust's
CStringdeallocator —packages/swift-sdk/SwiftTests/SwiftDashSDKTests/IdentityTopUpRecipientTests.swift:31-40(thread)
Review provenance
Source: reviewer 1: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.2-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.2-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 5: gpt-6.2-astra (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.2-sol(effort low) — ManagedPlatformWallet.swift and PlatformWalletPersistenceHandler.swift coordinate funding, outpoint recovery, and durable recipient binding across FFI and app restarts, where a mistake could fund a second lock or credit the wrong identity. - Phase 1 reviewers: not run (skipped for throughput: 16 PRs queued, above the 10 limit)
- Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-astra— general (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— security-auditor (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift`:
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5700-5703: A managed top-up resume can report a cached balance as the payment's proved balance
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078524)
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5781-5785: A process kill can leave a recoverable lock unlinked from its payment request
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078585)
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift:690-700: Code 81 tells apps to assign a recipient even when a seed-restored lock cannot accept one
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078560)
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift:327-331: Existing exhaustive wallet-error switches become non-exhaustive on rebuild
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078632)
In `packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift:254-258: Editing a saved asset-lock recipient can change who gets paid after restart
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078547)
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift:254-257: References to the previous asset-lock initializer no longer resolve
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078647)
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:773-779: A conflicting consumed snapshot can make a live top-up look completed
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078536)
In `packages/swift-sdk/SwiftTests/SwiftDashSDKTests/IdentityTopUpRecipientTests.swift`:
- [SUGGESTION] packages/swift-sdk/SwiftTests/SwiftDashSDKTests/IdentityTopUpRecipientTests.swift:113-126: The Swift tests would miss a lost recovery outpoint on a post-build error
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078618)
- [SUGGESTION] packages/swift-sdk/SwiftTests/SwiftDashSDKTests/IdentityTopUpRecipientTests.swift:31-40: The code-81 test passes a libc string to Rust's `CString` deallocator
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078596)
| /// - any other error: resume that outpoint with | ||
| /// `resumeTopUpToRecordedRecipient`, after the next launch if it is not | ||
| /// tracked now. A resume answering `assetLockNotTracked` means the lock | ||
| /// was removed before it was sent, so a new call is safe. |
There was a problem hiding this comment.
Resolved (re-reviewed at fd00f374): The separate code-20 branch now says not to fund a replacement even if same-session resume returns assetLockNotTracked. That covers the failed durable-removal case described in the thread.
| /// Outcome of `resumeTopUpToRecordedRecipient`: the identity the lock | ||
| /// paid (32 bytes; in this wallet or not) and its proved new balance. | ||
| public struct IdentityTopUpResult: Equatable, Sendable { | ||
| public let identityId: Data | ||
| public let newBalance: UInt64 |
There was a problem hiding this comment.
Still applies (re-reviewed at fd00f374): The new wording accounts for a newer published balance, but a newer refresh can advance the pending watermark without publishing its balance; if the write retry fails, Swift receives the old published value instead. You do not need to change #5931 to fix the Swift contract: describe the managed result as locally retained, with no guarantee that it reflects the payment.
| /// 32-byte identity an unbound identity top-up (`fundingTypeRaw == 2`) | ||
| /// was built or assigned to pay, which may be an identity this wallet | ||
| /// does not manage. Written by Rust with the row before the lock is | ||
| /// dispatched (or when the user assigns one to a lock that records | ||
| /// none) and immutable afterwards: a resume pays this identity and | ||
| /// refuses another (`assetLockRecipientMismatch`). `nil` for other | ||
| /// funding types and for unbound locks that record no identity, such as | ||
| /// one rebuilt from the chain; a resume of those is refused | ||
| /// (`assetLockRecipientUnknown`) until one is assigned. | ||
| /// | ||
| /// Default `nil` on the column keeps SwiftData's lightweight migration | ||
| /// safe for rows that pre-date this field. Lands in the live, not yet | ||
| /// published, V5 schema. | ||
| public var identityRecipient: Data? |
There was a problem hiding this comment.
Still applies (re-reviewed at fd00f374): public internal(set) closes direct edits on a fetched row, but callers can still set the field through public init(..., identityRecipient:). Saving a replacement for the same unique outPointHex can update the value the loader restores without calling the assignment API.
| /// Code 81: an unbound identity top-up lock records no identity to pay — | ||
| /// it was rebuilt from the chain, for example after a restore from the | ||
| /// seed — so no resume pays it; it may have been meant for someone | ||
| /// else's identity. Nothing was submitted or paid. Not retryable as is: | ||
| /// assign the lock a recipient the user chooses | ||
| /// (`ManagedPlatformWallet.assignTopUpRecipient`), then resume it. Such a | ||
| /// lock is flagged `identityRecipientUnassigned` on the tracked-lock | ||
| /// lists. |
There was a problem hiding this comment.
Still applies (re-reviewed at fd00f374): You corrected the assignment gate in the typed comment and excluded chain-restored locks in the resume docs, but the separate raw code-81 comment still instructs callers to assign one. The Swift refusal is .assetLockAlreadyConsumed (24), and it means prior consumption is unknown, not that the lock stayed unpaid.
…lock PersistentAssetLock gains identityRecipient (32 bytes, nullable column in the live, unpublished V5 schema). The persistence handler wires on_persist/on_load_asset_lock_identity_recipient_fn: a repeat of the recorded identity is accepted, a different one fails the round, a conflicting value on a consumed row is dropped (as the SQLite store does), upserts never replace a recorded value, and a missing row or a malformed value fails the load. The handler now declares ASSET_LOCK_IDENTITY_RECIPIENTS (bit 17). Part of #5924 (PR C). Co-Authored-By: Claude Opus 5.5 <[email protected]>
ManagedPlatformWallet binds the three exports from #5931: - topUpExternalIdentityWithFunding wraps platform_wallet_top_up_external_identity_with_funding_signer and hands the built lock's outpoint to onAssetLockBuilt after the native call, on failure as well as success; it is not called when nothing was built. - resumeTopUpToRecordedRecipient wraps platform_wallet_resume_identity_top_up_to_recorded_recipient_signer and returns the identity paid and its new balance. - assignTopUpRecipient wraps platform_wallet_assign_identity_top_up_recipient. Error code 81 maps to PlatformWalletError.assetLockRecipientUnknown, and the docs of code 61 cover identity recipients. Both tracked-lock lists carry identityRecipient and identityRecipientUnassigned. Part of #5924 (PR C). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Adds identity.top_up_any_identity_from_core (Swift SDK partial, Swift example app and Kotlin unsupported on this base), declares asset_lock_identity_recipients and lists the three new exports. PARITY_SUMMARY.md regenerated. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…top-up The retry guidance of `topUpExternalIdentityWithFunding` sent `transactionBroadcastUnconfirmed` (20) to "any other error", where a resume answering `assetLockNotTracked` licensed a new lock. After 20 the lock may be on the network, or its row may come back after a restart with its inputs still reserved, so a new lock could pay the identity twice. Code 20 now has its own branch, as in the FFI doc: resume that outpoint, never build a new lock. Also: - `IdentityTopUpResult.newBalance` says what a managed identity returns: the proved balance or a newer verified one the wallet already holds. - Code 81 and the resume doc no longer promise that a lock rebuilt from the chain can be assigned; assignment refuses it (`assetLockConsumptionUnknown`). - `PersistentAssetLock.identityRecipient` is `public internal(set)`: only the SDK writes it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…knowledged unknown consumption #5931 gave platform_wallet_assign_identity_top_up_recipient an acknowledge_unknown_consumption flag and a new code 82 (ErrorAssetLockConsumptionUnknown). assignTopUpRecipient takes acknowledgeUnknownConsumption (default false) and passes it through, and code 82 maps to PlatformWalletError.assetLockConsumptionUnknown, as #5933 does on Kotlin. Co-Authored-By: Claude Opus 5.5 <[email protected]>
fd00f37 to
721bf99
Compare
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 2 only (queue backlog)
Changes requested: 2 blockers
- Retrying an unconfirmed top-up after
assetLockNotTrackedcan pay twice —packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5881-5883(thread, carried)
Impact: An iOS app following the recovery instructions after a wallet reimport can fund a second lock while the first Core transaction is still recoverable and can pay the same identity. - A managed top-up resume can report a cached balance as the payment's proved balance —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5845-5848(thread, carried)
Impact: An iOS app resuming a payment to a managed identity can receive success with the pre-payment balance if a concurrent balance refresh gets a newer proof that the store cannot save.
New on this head: This revision exposes the rebased Rust wallet’s acknowledged assignment path for chain-restored top-up locks, defaults the acknowledgement to false, and maps native error code 82 in Swift. The Kotlin emulator build and tests and the SwiftData model-coverage check passed; the review check is pending, and CI shows no Swift build or test result for this head. Three additional verified suggestions were omitted to stay within the comment limit.
🔴 2 blocking | 🟡 7 suggestion(s)
Still open from earlier rounds (9)
- 🔴 Blocking: Retrying an unconfirmed top-up after
assetLockNotTrackedcan pay twice —packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5881-5883(thread) - 🔴 Blocking: A managed top-up resume can report a cached balance as the payment's proved balance —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5845-5848(thread) - 🟡 Suggestion: A conflicting consumed snapshot can make a live top-up look completed —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:773-779(thread) - 🟡 Suggestion: A process kill can leave a recoverable lock unlinked from its payment request —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5926-5930(thread) - 🟡 Suggestion: Editing a saved asset-lock recipient can change who gets paid after restart —
packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift:254-257(thread) - 🟡 Suggestion: The code-81 test passes a libc string to Rust's
CStringdeallocator —packages/swift-sdk/SwiftTests/SwiftDashSDKTests/IdentityTopUpRecipientTests.swift:31-40(thread) - 🟡 Suggestion: The Swift tests would miss a lost recovery outpoint on a post-build error —
packages/swift-sdk/SwiftTests/SwiftDashSDKTests/IdentityTopUpRecipientTests.swift:132-145(thread) - 🟡 Suggestion: References to the previous asset-lock initializer no longer resolve —
packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift:254-257(thread) - 🟡 Suggestion: Existing exhaustive wallet-error switches become non-exhaustive on rebuild —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift:333-342(thread)
Follow-up candidates (optional) (1)
New non-blocking observations on code unchanged since the last full review. No inline threads are opened for them and later reviews do not repeat them: fix forward or track separately if they are worth it.
🟡 Suggestion: A standalone assignment can succeed without recording the requested identity
Impact: If Rust's tracked state lags a consumed SwiftData row, assignment can acknowledge a recipient the store did not record or add a recipient to a lock that is already consumed.
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:776-780
The rebased Rust assignment relies on success meaning that the requested identity was committed. It invokes this callback in a recipient-only round, with no base upsert. On a consumed row recording A, a request for B returns success without writing B; on a consumed row with no recipient, it writes B. SQLite's conditional assignment rejects both cases, and Rust's later in-memory check cannot undo a committed write. Distinguish standalone assignment from snapshot persistence and test both consumed-row cases through the recipient callback.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, security-auditor)
Review provenance
Source: reviewer 1: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.2-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.2-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 5: gpt-6.2-astra (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.2-sol(effort low) — ManagedPlatformWallet.swift adds a funds-movement flow whose funding, recipient assignment, and crash recovery depend on coordinating native outpoints with persisted recipients to avoid misdirected payments or duplicate funding. - Phase 1 reviewers: not run (skipped for throughput: 15 PRs queued, above the 10 limit)
- New since the last final review (
fd00f374): 1 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 1 confirmed; 1 suggestion(s) on unchanged code listed as follow-up candidates - Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-astra— general (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— security-auditor (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift`:
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5881-5883: Retrying an unconfirmed top-up after `assetLockNotTracked` can pay twice
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078467)
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5845-5848: A managed top-up resume can report a cached balance as the payment's proved balance
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078524)
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:5926-5930: A process kill can leave a recoverable lock unlinked from its payment request
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078585)
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:773-779: A conflicting consumed snapshot can make a live top-up look completed
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078536)
In `packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift:254-257: Editing a saved asset-lock recipient can change who gets paid after restart
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078547)
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift:254-257: References to the previous asset-lock initializer no longer resolve
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078647)
In `packages/swift-sdk/SwiftTests/SwiftDashSDKTests/IdentityTopUpRecipientTests.swift`:
- [SUGGESTION] packages/swift-sdk/SwiftTests/SwiftDashSDKTests/IdentityTopUpRecipientTests.swift:31-40: The code-81 test passes a libc string to Rust's `CString` deallocator
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078596)
- [SUGGESTION] packages/swift-sdk/SwiftTests/SwiftDashSDKTests/IdentityTopUpRecipientTests.swift:132-145: The Swift tests would miss a lost recovery outpoint on a post-build error
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078618)
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift:333-342: Existing exhaustive wallet-error switches become non-exhaustive on rebuild
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4669078632)
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.
- A recovery lookup miss can authorize a second payment after Core accepted the first lock — Already covered by b0e182762330 on this head: the same unsafe code-23 retry rule survives for failures outside the fixed code-20 branch.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
| /// - any other error: resume that outpoint with | ||
| /// `resumeTopUpToRecordedRecipient`, after the next launch if it is not | ||
| /// tracked now. A resume answering `assetLockNotTracked` means the lock | ||
| /// was removed before it was sent, so a new call is safe. |
There was a problem hiding this comment.
Still applies (re-reviewed at 721bf990): Judged fixed at fd00f374; raised again and confirmed by an independent pass: If a user deletes the wallet while topUpExternalIdentityWithFunding is in flight, Core can accept the lock before teardown removes the wallet, and the call can return WalletNotFound rather than code 20 while still reporting the built outpoint. After reimporting the seed, an app that calls resumeTopUpToRecordedRecipient before the rescan finds that outpoint gets assetLockNotTracked and, following the Swift docs, can fund a replacement from other available UTXOs. Once the rescan recovers the original lock, the app can assign it to the same identity and resume it, spending two locks for one intended top-up.
The separate code-20 branch fixes the failed-deletion case you addressed. The narrower exception still fails after a different error: Core can accept the first lock before wallet removal causes the status update to fail, and code 23 after reimport says nothing about that accepted transaction.
| /// Outcome of `resumeTopUpToRecordedRecipient`: the identity the lock | ||
| /// paid (32 bytes; in this wallet or not) and its proved new balance. | ||
| public struct IdentityTopUpResult: Equatable, Sendable { | ||
| public let identityId: Data | ||
| public let newBalance: UInt64 |
There was a problem hiding this comment.
Still applies (re-reviewed at 721bf990): Your documentation change covers a newer balance that the wallet actually published, and the underlying fix does belong in #5931. A newer proof whose store fails is only queued; if it suppresses the delayed payment proof and its write still fails, Swift can receive the pre-payment balance, which the revised contract does not allow.
| /// Code 81: an unbound identity top-up lock records no identity to pay — | ||
| /// it was rebuilt from the chain, for example after a restore from the | ||
| /// seed — so no resume pays it; it may have been meant for someone | ||
| /// else's identity. Nothing was submitted or paid. Not retryable as is: | ||
| /// assign the lock a recipient the user chooses | ||
| /// (`ManagedPlatformWallet.assignTopUpRecipient`), then resume it. Such a | ||
| /// lock is flagged `identityRecipientUnassigned` on the tracked-lock | ||
| /// lists. |
There was a problem hiding this comment.
No longer applies (re-reviewed at 721bf990): The typed code-81 docs now explain the distinction you called out, with the rebased behavior: a seed-restored lock is refused by default with code 82, but explicit acknowledgement can make assignment possible. The original unconditional-refusal premise no longer applies.
| let ffi = PlatformWalletFFIResult( | ||
| code: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_ASSET_LOCK_RECIPIENT_UNKNOWN, | ||
| message: strdup("no recorded recipient")) | ||
| XCTAssertThrowsError(try ffi.check()) { error in | ||
| guard case PlatformWalletError.assetLockRecipientUnknown(let detail) = error else { | ||
| return XCTFail("expected assetLockRecipientUnknown, got \(error)") | ||
| } | ||
| XCTAssertEqual(detail, "no recorded recipient") | ||
| XCTAssertEqual(error.localizedDescription, "no recorded recipient") | ||
| } |
There was a problem hiding this comment.
Still applies (re-reviewed at 721bf990): The new code-82 test repeats the code-81 fixture's strdup ownership mismatch. Testing the detail through the Swift error initializer avoids transferring either allocation to Rust.
| /// An unbound identity top-up lock records no identity to pay (it was | ||
| /// rebuilt from the chain, for example after a restore from the seed), | ||
| /// so no resume pays it. Nothing was submitted or paid. Not retryable as | ||
| /// is: assign it a recipient the user chooses, then resume it. | ||
| case errorAssetLockRecipientUnknown = 81 |
There was a problem hiding this comment.
Still applies (re-reviewed at 721bf990): This revision adds code 82 alongside 81 to both Swift enums. The new cases correctly mirror Rust, but clients rebuilding exhaustive switches now need migration guidance for both.
…ntity-fr (d7d22a9) The base renumbered the identity-recipient codes to 89 (recipient unknown) and 90 (consumption unknown), since 81 and 82 belong to #5865 and #5647: Swift's raw values, their docs and the pin tests follow. Both sides' result codes and errors are kept, the schema doc lists both sides' additions, and the parity summary is regenerated from the merged manifest. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nce, recipient conflicts, initializer - topUpExternalIdentityWithFunding: once the outpoint is reported, only transactionBroadcastRejected allows a new lock. assetLockNotTracked means only that this wallet does not track the outpoint now; the lock may still be on the network (a wallet removed after Core accepted it, found again only after a reimport's rescan). The built outpoint goes through deliverTopUpOutcome, tested to report it once before the error. - IdentityTopUpResult.newBalance is the proved balance for an identity this wallet does not manage, and the locally retained one for an identity it manages, which need not reflect the payment. - The identity-recipient sidecar and the upsert check a conflicting recipient against the lock's status before the round, as SQLite does: a round whose upsert consumes a live row no longer drops the conflicting recipient as stale and commits Consumed with the old one. - PersistentAssetLock's public initializer keeps its previous signature; the one that sets identityRecipient is internal, so a client cannot save a replacement row with another identity. - The code 89/90 tests use the Swift error seam instead of handing a strdup string to Rust's CString deallocator. Co-Authored-By: Claude Opus 5.5 <[email protected]>
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
New on this head: This revision aligns Swift with native result codes 89 and 90, clarifies recovery and balance reporting, and adds regression coverage for outpoint delivery and live-row recipient conflicts. The Kotlin build and tests and the SwiftData model coverage check passed; the review check is pending, and no Swift SDK test result was reported for this head.
🟡 1 suggestion(s)
Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.
Follow-up candidates (optional) (1)
New non-blocking observations on code unchanged since the last full review. No inline threads are opened for them and later reviews do not repeat them: fix forward or track separately if they are worth it.
🟡 Suggestion: Recipient assignment can throw after the write commits
Impact: An iOS recovery screen following these docs can offer another recipient after an error even though the first assignment committed or the lock is no longer assignable.
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:6408-6409
A thrown error is not evidence that the lock is unassigned. In wallet/asset_lock/sync/tracking.rs, Rust commits the recipient before reacquiring the wallet-manager lock to publish it in memory. That step can find the lock swept or consumed, and b636eb17818 adds a recipient-mismatch error if the row was replaced. None of those error paths rolls back the write, and the merged native export now documents that distinction. Tell Swift callers to re-read the tracked outpoint before offering another recipient rather than treating the error as permission to choose again.
/// `identityLookupFailed`. A refused backend write does not apply the
/// assignment. Other errors can occur after the write commits; re-read
/// the tracked outpoint before offering another recipient.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, security-auditor)
Review provenance
Source: reviewer 1: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.2-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 5: gpt-6.2-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 6: gpt-6.2-astra (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.2-sol(effort low) — ManagedPlatformWallet.swift adds a funds-moving top-up, resume, and recipient-assignment flow whose correctness depends on durable recipient binding and on distinguishing a safe retry from resuming an already-built asset lock. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
- New since the last final review (
721bf990): 1 suggestion(s) on unchanged code listed as follow-up candidates - Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-astra— general (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— security-auditor (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:791-796: SwiftData accepts assignments on consumed locks and partially applies conflicting snapshots
Impact: If a recipient callback encounters an already-consumed row, an iOS wallet can record an assignment it should have refused, report success without storing the requested recipient, or keep snapshot fields that came with a different recipient.
The consumed-row exception applies to both kinds of callback round, but they have different contracts. The merged `d7d22a95fcc` FFI contract requires a standalone assignment to refuse a consumed row; `FFIPersister::assign_asset_lock_identity_recipient` sends begin → recipient → end without an upsert. On `Consumed/nil`, Swift falls through and stores the requested recipient; on `Consumed/A`, a request for B returns success without storing B. Rust's earlier eligibility check reads the in-memory row, not the row SwiftData is committing. For a snapshot round, the new pre-round status check correctly rejects a conflict on a previously live row, but `Consumed/A` followed by a `Consumed/B` snapshot still commits base fields such as `proofBytes` that were staged before the sidecar returned. SQLite skips the entire conflicting snapshot in that case. Distinguish recipient-only rounds from snapshot rounds for the same outpoint, and test that a refused assignment leaves the recipient unchanged and a skipped snapshot leaves both the recipient and proof unchanged.
| if let previous = record.identityRecipient, previous != identityId { | ||
| let statusBefore = assetLockStatusBeforeRound[hex] ?? record.statusRaw | ||
| if Self.isTerminalAssetLockStatus(statusBefore) { return } | ||
| throw AssetLockPersistenceError.conflictingIdentityRecipient | ||
| } | ||
| record.identityRecipient = identityId |
There was a problem hiding this comment.
🟡 Suggestion: SwiftData accepts assignments on consumed locks and partially applies conflicting snapshots
Impact: If a recipient callback encounters an already-consumed row, an iOS wallet can record an assignment it should have refused, report success without storing the requested recipient, or keep snapshot fields that came with a different recipient.
The consumed-row exception applies to both kinds of callback round, but they have different contracts. The merged d7d22a95fcc FFI contract requires a standalone assignment to refuse a consumed row; FFIPersister::assign_asset_lock_identity_recipient sends begin → recipient → end without an upsert. On Consumed/nil, Swift falls through and stores the requested recipient; on Consumed/A, a request for B returns success without storing B. Rust's earlier eligibility check reads the in-memory row, not the row SwiftData is committing. For a snapshot round, the new pre-round status check correctly rejects a conflict on a previously live row, but Consumed/A followed by a Consumed/B snapshot still commits base fields such as proofBytes that were staged before the sidecar returned. SQLite skips the entire conflicting snapshot in that case. Distinguish recipient-only rounds from snapshot rounds for the same outpoint, and test that a refused assignment leaves the recipient unchanged and a skipped snapshot leaves both the recipient and proof unchanged.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, security-auditor)
There was a problem hiding this comment.
Still applies (re-reviewed at 0c8c8078): The round bookkeeping now handles standalone assignments and stale upserts, but it does not discard fields from a same-status consumed snapshot after the sidecar rejects its recipient. A Consumed/B snapshot can still commit its proof and metadata over Consumed/A, so the whole per-outpoint update remains non-atomic.
| /// - any other error: resume that outpoint with | ||
| /// `resumeTopUpToRecordedRecipient`, after the next launch if it is not | ||
| /// tracked now. A resume answering `assetLockNotTracked` means the lock | ||
| /// was removed before it was sent, so a new call is safe. |
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): The funding docs now say a lookup miss after removal and reimport does not establish that the first lock was never sent. After an outpoint is reported, only definitive broadcast rejection is documented as safe for fresh funding.
| /// Outcome of `resumeTopUpToRecordedRecipient`: the identity the lock | ||
| /// paid (32 bytes; in this wallet or not) and its proved new balance. | ||
| public struct IdentityTopUpResult: Equatable, Sendable { | ||
| public let identityId: Data | ||
| public let newBalance: UInt64 |
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): Your revised contract describes the managed result as the locally retained balance and explicitly allows an older value after a failed store. That matches the native return without presenting it as proof of this payment.
| guard let record = try modelFetcher.fetch(descriptor, in: backgroundContext).first else { | ||
| throw AssetLockPersistenceError.missingRecord | ||
| } | ||
| if let previous = record.identityRecipient, previous != identityId { | ||
| if Self.isTerminalAssetLockStatus(record.statusRaw) { return } | ||
| throw AssetLockPersistenceError.conflictingIdentityRecipient | ||
| } |
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): Your pre-round status check now refuses Consumed/B over a live Broadcast/A row. The regression test follows native callback order and verifies that rollback preserves both Broadcast and recipient A.
| /// 32-byte identity an unbound identity top-up (`fundingTypeRaw == 2`) | ||
| /// was built or assigned to pay, which may be an identity this wallet | ||
| /// does not manage. Written by Rust with the row before the lock is | ||
| /// dispatched (or when the user assigns one to a lock that records | ||
| /// none) and immutable afterwards: a resume pays this identity and | ||
| /// refuses another (`assetLockRecipientMismatch`). `nil` for other | ||
| /// funding types and for unbound locks that record no identity, such as | ||
| /// one rebuilt from the chain; a resume of those is refused | ||
| /// (`assetLockRecipientUnknown`) until one is assigned. | ||
| /// | ||
| /// Default `nil` on the column keeps SwiftData's lightweight migration | ||
| /// safe for rows that pre-date this field. Lands in the live, not yet | ||
| /// published, V5 schema. | ||
| public var identityRecipient: Data? |
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): Your internal initializer closes the construction path left open by the earlier setter change. Clients can read the recipient but cannot supply a different one through the public model API.
| if let built { | ||
| onAssetLockBuilt(built) | ||
| } | ||
| return try outcome.get() |
There was a problem hiding this comment.
Deferred (re-reviewed at a242c339): The current export still returns the outpoint only when the native operation finishes, so Swift cannot forward Rust's earlier build notification through this signature. Your linked issue covers both the callback-capable export and Swift forwarding.
| let ffi = PlatformWalletFFIResult( | ||
| code: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_ASSET_LOCK_RECIPIENT_UNKNOWN, | ||
| message: strdup("no recorded recipient")) | ||
| XCTAssertThrowsError(try ffi.check()) { error in | ||
| guard case PlatformWalletError.assetLockRecipientUnknown(let detail) = error else { | ||
| return XCTFail("expected assetLockRecipientUnknown, got \(error)") | ||
| } | ||
| XCTAssertEqual(detail, "no recorded recipient") | ||
| XCTAssertEqual(error.localizedDescription, "no recorded recipient") | ||
| } |
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): Both tests now verify the native constant mapping separately and use PlatformWalletError(code:message:) for the message assertions. Neither transfers a libc allocation to Rust.
| /// An unknown wallet handle fails before any lock is built: the error | ||
| /// reaches the caller and no outpoint is reported, so a new call is safe. | ||
| func testShouldReportNoOutPointWhenNothingWasBuilt() async { | ||
| let reported = Reported() | ||
| do { | ||
| _ = try await wallet.topUpExternalIdentityWithFunding( | ||
| identityId: identityId, amountDuffs: 50_500, accountIndex: 0, | ||
| onAssetLockBuilt: { reported.append($0) }) | ||
| XCTFail("expected notFound") | ||
| } catch PlatformWalletError.notFound { | ||
| } catch { | ||
| XCTFail("expected notFound, got \(error)") | ||
| } | ||
| XCTAssertTrue(reported.all.isEmpty) |
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): The production wrapper now calls your deliverTopUpOutcome helper, and the test checks exactly one delivery inside the thrown-error assertion. Moving outcome.get() ahead of the callback would fail that assertion.
| /// An unbound identity top-up lock records no identity to pay (it was | ||
| /// rebuilt from the chain, for example after a restore from the seed), | ||
| /// so no resume pays it. Nothing was submitted or paid. Not retryable as | ||
| /// is: assign it a recipient the user chooses, then resume it. | ||
| case errorAssetLockRecipientUnknown = 81 |
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): Your Breaking Changes section lists both new cases on each public enum, gives the verified values 89 and 90, and tells callers how to update exhaustive switches.
| shieldedRecipientRaw43: Data? = nil, | ||
| identityRecipient: Data? = nil |
There was a problem hiding this comment.
Resolved (re-reviewed at a242c339): Your public initializer now has the same labels and arity as the base version. The overload with identityRecipient: is internal, so existing public initializer references still resolve.
…up outcomes honest - A resume through a manager of a replaced wallet generation is refused (WalletNotFound) under the guard it authorizes and claims under, as a build already is, so it cannot send a lock the replacement's cleanup called safe to rebuild. - An abandoned build's generation check and fence verdict run in a task that owns the pin, so a cancelled caller cannot leave the fence pending. - A status write that finds no wallet or row after the network accepted the lock reports the unknown outcome, not "not found". - The top-up ChainLock fallback re-checks the recorded recipient. - The managed resume returns the balance Platform proved. - FFI: runtime-reentry guard on the managed top-up, inputs copied before outputs are cleared, conditional panic guidance, status-5 docs, and a boundary test for withdrawing the outpoint. - Storage: an out-of-range funding index is tolerated under Recovery, the funding-pool load error stays typed, and two tests are tightened. - Registry: rule-5 exception for codes 89/90 (Kotlin #5933, Swift #6139). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ntity-fr (182cc6b) Co-Authored-By: Claude Opus 5.5 <[email protected]>
… state the acknowledgement and retry rules as the FFI does Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ntity-fr (7d6b704) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
New on this head: This head adds SwiftData handling for identity-recipient persistence and assignment, updates the Swift top-up/resume API documentation, and adds coverage for live and terminal asset-lock states. Available CI checks are successful, including Kotlin build/tests, SwiftData model verification, policy, title, and release checks; no code check is failing, while the review check remains queued.
🟡 3 suggestion(s)
Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.
Still open from earlier rounds (1)
- 🟡 Suggestion: SwiftData accepts assignments on consumed locks and partially applies conflicting snapshots —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:839-843(thread)
Review provenance
Source: reviewer 1: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.2-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.2-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 5: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 6: gpt-6.2-astra (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.2-sol(effort low) — ManagedPlatformWallet.swift adds a path that spends Core funds, and PlatformWalletPersistenceHandler.swift implements intricate rules for preserving the intended payee across restarts, stale snapshots, and consumed locks. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
- Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-astra— general (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— security-auditor (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:6412-6416: A refused recipient write can leave the original assignment, but the docs say another identity is safe
Impact: A recovery UI following this documentation can offer a different recipient after a persistence error even though the stored lock still has its permanent original recipient.
The documentation says that a store refusal leaves no assignment and that any identity may be assigned again. That is too strong: a failed persistence operation means this call did not change the durable row, and a later error can occur after the assignment was staged or committed; neither case proves that the lock is unassigned. The following paragraph already correctly says that other errors do not establish an unassigned lock. Tell callers to reread the tracked lock after every assignment error before offering another recipient.
In `packages/swift-sdk/SwiftTests/SwiftDashSDKTests/AssetLockIdentityRecipientPersistenceTests.swift`:
- [SUGGESTION] packages/swift-sdk/SwiftTests/SwiftDashSDKTests/AssetLockIdentityRecipientPersistenceTests.swift:137-150: The assignment test never starts with a recipient-less recovered lock
Impact: A regression that rejects first assignment for a `RecoveredFromChain` lock while allowing repeated assignment would pass the current SwiftData test.
The loop reuses one handler and outpoint. Status 0 receives the first assignment, and every later iteration—including status 5—already has the recipient, so those iterations only test idempotent repetition. Use a fresh in-memory container and handler for each status, seed the row without a recipient, then perform the first assignment and the repeat. This directly exercises the ordinary assignment path for every live status, including `RecoveredFromChain`.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:839-843: SwiftData accepts assignments on consumed locks and partially applies conflicting snapshots
(carried; thread: https://github.com/dashpay/platform/pull/6139#discussion_r4712495957)
| /// `identityLookupFailed`. A store that refused the write leaves no | ||
| /// assignment, and any identity may be assigned again. Other errors do not | ||
| /// establish that the lock is unassigned (the store may have committed | ||
| /// before the lock was found swept, consumed or recording another | ||
| /// identity): read the tracked lock before offering another recipient. |
There was a problem hiding this comment.
🟡 Suggestion: A refused recipient write can leave the original assignment, but the docs say another identity is safe
Impact: A recovery UI following this documentation can offer a different recipient after a persistence error even though the stored lock still has its permanent original recipient.
The documentation says that a store refusal leaves no assignment and that any identity may be assigned again. That is too strong: a failed persistence operation means this call did not change the durable row, and a later error can occur after the assignment was staged or committed; neither case proves that the lock is unassigned. The following paragraph already correctly says that other errors do not establish an unassigned lock. Tell callers to reread the tracked lock after every assignment error before offering another recipient.
| /// `identityLookupFailed`. A store that refused the write leaves no | |
| /// assignment, and any identity may be assigned again. Other errors do not | |
| /// establish that the lock is unassigned (the store may have committed | |
| /// before the lock was found swept, consumed or recording another | |
| /// identity): read the tracked lock before offering another recipient. | |
| /// A refused write leaves the stored row unchanged. A later error can occur | |
| /// after the assignment committed. In either case, read the tracked lock | |
| /// before offering another recipient. |
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, security-auditor)
| let container = try DashModelContainer.createInMemory() | ||
| let handler = PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet) | ||
| for status in [0, 1, 2, 3, 5] { | ||
| try round(handler, status: status) | ||
| for _ in 0..<2 { | ||
| handler.beginChangeset(walletId: walletId) | ||
| try handler.persistAssetLockIdentityRecipient( | ||
| walletId: walletId, outPoint: rawOutPoint, identityId: recipient) | ||
| XCTAssertTrue(handler.endChangeset(walletId: walletId, success: true)) | ||
| } | ||
| let row = try handler.loadCachedAssetLocks(walletId: walletId).first | ||
| XCTAssertEqual(row?.identityRecipient, recipient) | ||
| XCTAssertEqual(row?.statusRaw, status) | ||
| } |
There was a problem hiding this comment.
🟡 Suggestion: The assignment test never starts with a recipient-less recovered lock
Impact: A regression that rejects first assignment for a RecoveredFromChain lock while allowing repeated assignment would pass the current SwiftData test.
The loop reuses one handler and outpoint. Status 0 receives the first assignment, and every later iteration—including status 5—already has the recipient, so those iterations only test idempotent repetition. Use a fresh in-memory container and handler for each status, seed the row without a recipient, then perform the first assignment and the repeat. This directly exercises the ordinary assignment path for every live status, including RecoveredFromChain.
| let container = try DashModelContainer.createInMemory() | |
| let handler = PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet) | |
| for status in [0, 1, 2, 3, 5] { | |
| try round(handler, status: status) | |
| for _ in 0..<2 { | |
| handler.beginChangeset(walletId: walletId) | |
| try handler.persistAssetLockIdentityRecipient( | |
| walletId: walletId, outPoint: rawOutPoint, identityId: recipient) | |
| XCTAssertTrue(handler.endChangeset(walletId: walletId, success: true)) | |
| } | |
| let row = try handler.loadCachedAssetLocks(walletId: walletId).first | |
| XCTAssertEqual(row?.identityRecipient, recipient) | |
| XCTAssertEqual(row?.statusRaw, status) | |
| } | |
| for status in [0, 1, 2, 3, 5] { | |
| let container = try DashModelContainer.createInMemory() | |
| let handler = PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet) | |
| try round(handler, status: status) | |
| for _ in 0..<2 { | |
| handler.beginChangeset(walletId: walletId) | |
| try handler.persistAssetLockIdentityRecipient( | |
| walletId: walletId, outPoint: rawOutPoint, identityId: recipient) | |
| XCTAssertTrue(handler.endChangeset(walletId: walletId, success: true)) | |
| } | |
| let row = try handler.loadCachedAssetLocks(walletId: walletId).first | |
| XCTAssertEqual(row?.identityRecipient, recipient) | |
| XCTAssertEqual(row?.statusRaw, status) | |
| } |
source: gpt-6.2-astra (phase2-reviewer: general)
| if let previous = record.identityRecipient, previous != identityId { | ||
| let statusBefore = assetLockStatusBeforeRound[hex] ?? record.statusRaw | ||
| if Self.isTerminalAssetLockStatus(statusBefore) { return } | ||
| throw AssetLockPersistenceError.conflictingIdentityRecipient | ||
| } | ||
| record.identityRecipient = identityId |
There was a problem hiding this comment.
Still applies (re-reviewed at 0c8c8078): The round bookkeeping now handles standalone assignments and stale upserts, but it does not discard fields from a same-status consumed snapshot after the sidecar rejects its recipient. A Consumed/B snapshot can still commit its proof and metadata over Consumed/A, so the whole per-outpoint update remains non-atomic.
Basic explanation
What this does: Lets an iOS app using the Swift SDK pay Dash from its Core balance into an identity it does not own, recover such a payment if the app dies halfway, and assign an identity to a lock that has none. Who each payment is for is stored in SwiftData, so a restart pays the right identity.
Value: iOS gets the same "top up someone else's identity" flow as the Rust wallet in #5931 and Android in #5933. This unblocks Core → any identity in dashwallet-ios (dashpay/dashwallet-ios#1406–#1409).
Risks: Low. One nullable attribute in the unreleased V5 SwiftData schema and new API only. Declaring bit 17 lets Rust build unbound top-up locks for this store. No consensus impact.
Issue being fixed or feature implemented
Swift part of #5924 (PR C), and the last of the three to merge, so it closes it: Closes #5924. Stacked on #5931 (PR A, Rust + FFI): this PR targets #5931's branch, so the diff shows only the Swift changes. Retarget to
v5.2-devonce #5931 merges. Kotlin is #5933 (PR B). #5931 asks for A, B and C in the same SDK release.What was done?
Persistence (SwiftData)
PersistentAssetLock.identityRecipient(32 bytes, nullable) in the live, unpublished V5 schema. Operation ids and shielded recipients were already stored.PlatformWalletPersistenceHandlerwireson_persist_asset_lock_identity_recipient_fn/on_load_asset_lock_identity_recipient_fn:ASSET_LOCK_IDENTITY_RECIPIENTS(bit 17).SDK API
ManagedPlatformWallet.topUpExternalIdentityWithFunding(identityId:amountDuffs:accountIndex:onAssetLockBuilt:):onAssetLockBuiltreceives the built lock's outpoint (fromout_asset_lock_outpoint) once the native call returns, on failure too, and is not called when nothing was built. After it is called, the caller resumes that outpoint instead of retrying with a new lock.resumeTopUpToRecordedRecipient(outPointTxid:outPointVout:)returns the identity paid and its new balance.assignTopUpRecipient(outPointTxid:outPointVout:identityId:acknowledgeUnknownConsumption:). The acknowledgement has no default: assigning any lock that records no recipient needs an explicit decision.withExtendedLifetimeacross the FFI call (swift-sdk: keep the signer alive withwithExtendedLifetimein every wrapper that passes its handle to the FFI #5939).PlatformWalletError.assetLockRecipientUnknownand code 90 toassetLockConsumptionUnknown; the docs of code 61 cover identity recipients.TrackedAssetLockandTrackedAssetLockSnapshotcarryidentityRecipientandidentityRecipientUnassigned.PARITY_SUMMARY.mdupdated.Not in this PR
Notes for the stack
identity.top_up_any_identity_from_coreconflicts with feat(kotlin-sdk): top up someone else's identity from the Core balance #5933's: whichever merges second sets both hosts topartialand re-runs--write-summary.How Has This Been Tested?
AssetLockIdentityRecipientPersistenceTests(12): an assignment on a consumed row is refused; a stale snapshot writes no recipient; survives later snapshots and a store reopen; same value accepted, different refused; an upsert cannot replace it; a consumed row drops a conflicting value; fail-closed without a row, outside a changeset, or with a malformed value; round trip through the C callback shims; bit 17 equals the header constant. Removing the conflict refusal and the malformed-load check fails 3 of them.IdentityTopUpRecipientTests(9): code 89 and 90 mapping, built-outpoint decoding, argument checks, no outpoint reported when nothing was built.swift test: 1320 tests, 1 skipped, 0 failures, on28f82dc630; the merge of feat(platform-wallet): top up someone else's identity from the Core balance #5931's7d6b70435cafter it changes no Swift file. One earlier run had a single failure intestCaptureReleaseSchemathat did not recur alone or in the second full run; its cause is not established.Breaking Changes
Swift source compatibility only:
PlatformWalletResultCodegainserrorAssetLockRecipientUnknown(89) anderrorAssetLockConsumptionUnknown(90), andPlatformWalletErrorgainsassetLockRecipientUnknownandassetLockConsumptionUnknown. An app that switches over either enum without adefaultmust add the new cases. No protocol or consensus change: the schema change is additive in the unreleased V5, and the rest of the API is new.Checklist:
structure.rs, regeneratedgrovedb-structure.json, and checked the structure viewer link posted on this pull requestFor repository code-owners and collaborators only
🤖 Generated with Claude Code