Repository navigation
fix(platform-wallet)!: carry Rust's handback class on every paid output a binding cannot hand back - #6464
fix(platform-wallet)!: carry Rust's handback class on every paid output a binding cannot hand back#6464romchornyi wants to merge 72 commits into
Conversation
…the wallet Every wallet error now carries a payment class set once in Rust: `NotSent` (nothing left the wallet, retryable as Rust decides), `MaybeSent` (a dispatch happened; do not retry), or `LockHeld` (an asset lock exists and names the outpoint its resume can finish). This first part of the split of #5928 holds the class itself (`PaymentDelivery`, `PlatformWalletError::payment_class`/`is_retryable`), the funded-lock seam (`with_funded_lock`) that names a held lock on every failure after it exists, and the flows built on that seam: identity registration, invitation create and claim (with the SDK's `InvitationError` now saying whether a claim was broadcast), the Platform address and shielded fundings from an asset lock, and the external identity top-up from addresses. The FFI only adapts to the new variant shapes here; carrying the class to the hosts follows in the next PR. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-class wrapper Until the FFI carries the payment class (next PR of the stack), the blanket conversion and every result mapper read the error a RefusedBeforeDispatch or PaymentAlreadyDispatched wraps, so its own code, JSON detail and consensus code still reach the host. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… never sent The drain records NotSent for a refusal before any lock exists; its error now says NotSent too (before_dispatch) instead of MaybeSent. A RefusedBeforeDispatch is never retryable, and its docs say so: its source is a variant that also ends dispatched payments, so running the call again is the user's decision. Co-Authored-By: Claude Opus 5.5 <[email protected]>
refuses_resume read only the outer variant with matches!, so a new variant took the false arm silently. It now reads through the payment-class wrappers and names every PlatformWalletError variant. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lback fails The InstantSend claim before the fallback may have been sent, so any fallback failure, a local one before its own broadcast included, now arrives as StateTransitionResultUnconfirmed rather than a never-sent error. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The ChainLock fallback's error is wrapped as unconfirmed, which hid Platform's consumed-outpoint verdict from the adoption check, so a claim whose InstantSend primary had landed reported a failure instead of its identity. The check now reads the verdict through the wrapper and keeps the wrapper when nothing is adopted. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ror to the hosts Second part of the split of #5928, on top of the payment class itself. The remaining wallet paths now set their class (DPNS and the marketplace, contact requests, credit and token shielded spends and plans, shielded tips, the shielded seed batch and the wallet drain, masternode withdrawals), and every FFI result carries Rust's class: `payment_delivery`, `retryable` and the held asset lock's outpoint on `PlatformWalletFFIResult`, set from the wallet error by the blanket conversion and every result mapper, never inferred from the code. A panic in a payment export is classed as possibly sent. ERROR_CODE_REGISTRY.md documents the class per code. Swift and Kotlin read it in the next two PRs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ever sent The mainnet gate, the wallet id check, the starting notes count, the recipient and the first batch's fee and amount refuse the run before any lock is built, so they are NotSent (before_dispatch); after an earlier batch dispatched they stay the run's MaybeSent failure. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…esults PlatformWalletFFIResult gains payment_delivery, held_asset_lock and retryable in this PR, so Swift's init(code:message:) fills them with Rust's own defaults and the test that builds a result field by field names them; Swift reads them in the next PR. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…assified A null pointer, an invalid handle, a different or removed wallet generation and an unrepresentable txid are refused by the FFI, not by a wallet error; they crossed with a class stamped from a wallet error made up for the call. They now cross as Unknown, as the result's contract says. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Third part of the split of #5928. `PlatformWalletError` carries the FFI result's `PlatformPaymentClass` (delivery, retry, and the held asset lock under `LockHeld`) on every case, read from the result and never derived from the code; texts and recovery suggestions follow it, and a guard that throws after a successful FFI call carries a class too. SwiftExampleApp presents a payment failure by its class: it holds a payment's slot unless nothing was sent, names a held voucher or lock, and releases a hold only once the user reconciled it. BREAKING CHANGE: `PlatformWalletError` cases gain a `payment:` field. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`PlatformWalletError.invalidParameter` now carries `payment:`, so the single-binding catch pattern bound a tuple and the test target did not compile. No other single-binding pattern over a `PlatformWalletError` case remains in the Swift SDK, its tests or the example app. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every guard that throws after Rust reported a paid write as done now carries `payment: .maybeSent`, including an output that does not decode: the DPNS give-up result, the contract fee claim (missing JSON and its decode), and every signed moderation call (missing JSON and its decode, through `moderationCall`). The moderation offer read still carries no class. `PlatformWalletError.readingPaidOutput` reclasses a decode refusal of such an output. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nd name the lock its Resume resumes A drain failure carries Rust's class, and the drain's own Resume names the outpoint it resumes: - `WalletDrainAttemptError` carries the class of the outcome's error (`attemptError`), `.notSent` for a not-sent outcome whose error has none, and keeps the class when a resume finds no tracked lock (`resumeError`). `PaymentFailure.paymentClass(of:)` reads it, so a not-sent drain releases its slot instead of holding it as unconfirmed. - `run` passes `resuming:` to `startFunding`: `nil` for a start, the resumed outpoint from `resume`, so a failure that holds that lock lets the drain's Resume run. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e voucher outpoint claim The submit docs of the shielded and address funding controllers and the identity registration controller said a slot restarts only after a retryable failure; any `.notSent` failure releases it. The invitation create comment said `out_outpoint` names the held voucher lock, but nothing reads it: a success without a URI throws `.maybeSent`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…duled A slot that holds a failed Max refuses a new one by re-presenting the failure without running its body. `start` now removes the id it just stored in that case too, as it does for a start blocked by another funding, so a refused start leaves no marker behind. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…aybe sent Token transfer, burn and mint read the balances Rust returns through `tokenReadingBalancesJSON` after the write succeeded; a map that does not parse now throws `.deserialization` with `payment: .maybeSent`, like the other guards after a paid write. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The SDK marshals Rust's payment class (delivery, isRetryable, the held lock) and no longer turns it into a recovery, a title or user-facing text. `PlatformPaymentRecovery` and `ErrorRecovery.suggestion(for: PlatformPaymentClass?)` are removed; the example app's `PaymentFailure` now owns the same mapping as `PaymentFailure.Recovery`, with its suggestion and invitation-voucher texts. `ErrorCategorizer` / `ErrorFormatter` show a wallet error as its own text, titled by its category, with Rust's retry and no suggestion. The `.transactionBroadcastUnconfirmed` text and title are back to the base branch's. BREAKING CHANGE: `PlatformPaymentRecovery` and `ErrorRecovery.suggestion(for: PlatformPaymentClass?)` are gone; a host decides retry, wait or resume from `PlatformWalletError.payment`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Last part of the split of #5928. The JNI bridge carries the FFI result's payment class into `DashSDKException`, including the error beside a wallet drain's packed outcome, and `DashSdkError.PlatformWallet` exposes `delivery`, `isRetryable` and `heldAssetLock` from it; `PaymentRecovery` reads it for hosts, and texts follow it. KotlinExampleApp's payment screens follow the class: a payment's slot is held unless nothing was sent, a held invitation voucher is reclaimed and named, and a reconciled hold is released only after confirmation. The SDK parity manifest gets the `errors.payment_class` capability (Swift and Kotlin). BREAKING CHANGE: `DashSDKException` gains the payment class fields. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`ErrorCategorizer` had started presenting every `SDKError.networkError` and `.timeout` as not retryable with no suggestion. That is a decision the SDK does not own, and it also hit read-only queries. The base branch's category-based answer is back; a payment screen decides from Rust's class in the app. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nd refuse starts without running them A start the hold refuses now reports its body as not scheduled (bodyScheduled = false, as Swift's `.started(existing, bodyScheduled: false)`), so WalletDrainCoordinator undoes its running count and a refused Max removes the operation id it stored. A drain failure carries Rust's class: WalletDrainAttemptException keeps the outcome error's recovery (NOT_SENT for a not-sent outcome without an error, unclassified otherwise), including the not-tracked resume error, and PaymentFailure reads it. The drain's Resume names the outpoint it resumes, so a LOCK_HELD drain resumes its own lock. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ed payment `PaymentFailure.ofPayment` returned nil for a `PlatformWalletError` without a class, so the screen showed it as a plain refusal and let a new payment go. The FFI's `Unknown` delivery also decodes to no class, so a paid call can come back that way. As in Kotlin's `PaymentFailure.ofPayment`, every SDK error is now a payment failure; a classless one is unconfirmed and holds its slot until the user releases it after checking the history. Only an error that is not an SDK error (the screen's own input check) shows as its own message. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…stored hold Both identity top-up screens assigned PaymentFailure.ofPayment(e) unconditionally, so a later throwable that is not an SDK error replaced a held failure (for example the LOCK_HELD lock a resume is bound to) with null and re-enabled a new lock. PaymentFailure.keptAfter keeps the previous failure in that case; Send already only assigns a non-null failure. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…r an unresolved failure Every example-app screen that starts a payment now keeps its last `PaymentFailure` and, while it holds its slot (`.maybeSent`, `.lockHeld` or no class), refuses a fresh payment from that screen: the control is disabled and the action itself checks `PaymentFailure.permitsFreshPayment`. The failure clears only on a success, a later `.notSent` result, or the user's confirmed release (`ReleasePaymentHoldButton`, offered when `releasableAfterReconciliation`). `PaymentFailure.keptAfter` keeps a hold across an error that is not an SDK error (← Kotlin). Applied at: - CreateInvitationSheet: create is refused while a voucher lock is held (its text sends the user to reclaim it under Sent invitations) or the create may have gone through. - DpnsMarketplaceView: one screen-level trade failure gates list, delist, transfer and purchase (menu items and the sheet's confirm); search, sync and history stay available. - TopUpAddressFromAssetLockViewModel / AddressQueriesView: the top-up button and `executeTopUp` are refused; a form reset keeps the hold. - CreateIdentityView: the Platform-payment registration's failure is kept and gates submit before any key is persisted. - SendViewModel: a rejected Core broadcast is read by its payment class like an unknown one, so a holding class keeps the form refused. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…h screens read the class Comments said a fresh start or a new lock was allowed only after a retryable failure; PaymentFailure.permitsRestart allows it after any NOT_SENT. The errors.payment_class parity reasons now list the screens each example app presents by the payment class. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The SDK marshals Rust's payment class (delivery, isRetryable, heldAssetLock) and no longer maps it to a recovery action or user-facing text. PaymentRecovery, its suggestion texts and the invitation-voucher rule move into KotlinExampleApp's util package next to PaymentFailure, their one presenter. The SDK keeps its own test of userMessage and isRetryable in DashSdkErrorTest. BREAKING CHANGE: org.dashfoundation.dashsdk.errors.PaymentRecovery is removed; hosts map DashSdkError.delivery/isRetryable/heldAssetLock to their own recovery. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…er an unresolved failure Every screen that starts a payment keeps its last PaymentFailure and, while that failure holds its slot (MAYBE_SENT, LOCK_HELD, no class), refuses a fresh payment in both the control and the action. The hold clears on success, a later NOT_SENT failure, or the confirmed release after checking the history; a non-SDK throwable keeps it (keptAfter). - CreateInvitationSheet: keeps the failure as an invitation voucher (reclaim under Sent invitations), gates Create, offers the release. - DpnsMarketplaceScreen: gates purchase, set price, delist and transfer plus the confirmation; search, sync and history stay available. - TopUpIdentityScreen: the hold now gates the shielded source too, and the submit action checks it. All gates read PaymentFailure.permitsFreshPayment (sendPermittedAfter included); PaymentHoldGateTest checks each site's gate. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… not decode A LOCK_HELD failure without an outpoint read as Reconcile and offered the release after checking history, which re-enabled a fresh payment while the lock stayed held. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… without its outpoint WalletDrainAttemptException kept only the recovery, so a drain Rust classed LOCK_HELD whose outpoint did not decode reached PaymentFailure as a plain Reconcile and offered the release. It now carries the LOCK_HELD bit. 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
Changes requested: 1 blocker
- A completed Android payment loses its no-retry signal when the JVM cannot allocate the replacement error —
packages/rs-unified-sdk-jni/src/support.rs:378-385(thread, carried)
Impact: An Android user whose Core send broadcasts under sustained heap pressure can receive an unclassified throwable and submit the same payment again.
New on this head: This head extends Rust-owned payment handback classification across the platform-wallet FFI, JNI, Swift decoding, profile conversion, and address changeset paths, with additional Kotlin tests and documentation updates. The supplied Kotlin SDK build and emulator tests passed; policy and title checks passed, while the review check remains queued.
🔴 1 blocking | 🟡 3 suggestion(s)
Still open from earlier rounds (2)
- 🔴 Blocking: A completed Android payment loses its no-retry signal when the JVM cannot allocate the replacement error —
packages/rs-unified-sdk-jni/src/support.rs:378-385(thread) - 🟡 Suggestion: Swift accepts missing or unreadable token balances as a successful result —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/Tokens/TokenActions.swift:1052-1054(thread)
Review provenance
Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.2-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.2-astra (agent: phase2-reviewer, role: rust-quality); reviewer 7: 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) — This is a large, intricate cross-language change across FFI and JNI payment-handling paths that directly governs failure and retry semantics for broadcasts, transfers, withdrawals, funding, and wallet operations, a critical funds-movement surface. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (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— rust-quality (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/rs-unified-sdk-jni/src/support.rs`:
- [SUGGESTION] packages/rs-unified-sdk-jni/src/support.rs:134-138: A failed read-only wallet call can be reported as a payment handback failure under heap pressure
Impact: An Android caller reading a cached profile can receive `MAYBE_SENT` when the read fails and the JVM cannot allocate its diagnostic exception, even though no payment was possible.
`throw_pwffi_result` uses the prepared handback exception for every delivery other than `NotSent`. Ordinary read failures from platform-wallet FFI results use the `Unknown` delivery class; for example, the newly fallible profile conversion returns `ErrorUtf8Conversion` from `getContactProfile`. If building that read error fails under heap pressure, this branch replaces it with the prepared `MaybeSent` exception, causing Kotlin to report that the call succeeded but its result was not handed back. Preserve `Unknown` with a prebuilt unclassified fallback, and reserve the handback fallback for `MaybeSent` and `LockHeld` results.
- [BLOCKING] packages/rs-unified-sdk-jni/src/support.rs:378-385: A completed Android payment loses its no-retry signal when the JVM cannot allocate the replacement error
(carried; thread: https://github.com/dashpay/platform/pull/6464#discussion_r4786565336)
In `packages/rs-platform-wallet-ffi/src/dashpay_profile.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/dashpay_profile.rs:362-366: A contact profile containing a NUL can crash the Android example app when profile previews load
Impact: A user opening the DashPay send sheet or adding a contact whose synced public message contains a NUL can have the example app's coroutine fail before the screen is usable.
The new `from_profile` conversion intentionally returns `ErrorUtf8Conversion` instead of dropping a NUL-containing field, and the schema permits such a string. That error is appropriate at the FFI boundary, but the Kotlin example app now reaches it from unguarded `LaunchedEffect` calls: `SendDashPayPaymentSheet.kt:71` directly calls `getContactProfile`, and `AddContactScreen.kt:272` does the same before `parseDashPayProfile`. Neither site catches the SDK error, so a peer-controlled cached profile can abort the coroutine and prevent the preview/send flow from opening. Catch the profile-read failure at both display sites, rethrow `CancellationException`, and show an unavailable-profile state or continue without the optional profile.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/Tokens/TokenActions.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/Tokens/TokenActions.swift:1052-1054: Swift accepts missing or unreadable token balances as a successful result
(carried; thread: https://github.com/dashpay/platform/pull/6464#discussion_r4786565427)
| let fallback = if result.payment_delivery == PlatformWalletFFIPaymentDelivery::NotSent { | ||
| Fallback::Runtime | ||
| } else { | ||
| Fallback::HandbackPrepared | ||
| }; |
There was a problem hiding this comment.
✅ Resolved at
223452aa; see the replies below.
🟡 Suggestion: A failed read-only wallet call can be reported as a payment handback failure under heap pressure
Impact: An Android caller reading a cached profile can receive MAYBE_SENT when the read fails and the JVM cannot allocate its diagnostic exception, even though no payment was possible.
throw_pwffi_result uses the prepared handback exception for every delivery other than NotSent. Ordinary read failures from platform-wallet FFI results use the Unknown delivery class; for example, the newly fallible profile conversion returns ErrorUtf8Conversion from getContactProfile. If building that read error fails under heap pressure, this branch replaces it with the prepared MaybeSent exception, causing Kotlin to report that the call succeeded but its result was not handed back. Preserve Unknown with a prebuilt unclassified fallback, and reserve the handback fallback for MaybeSent and LockHeld results.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality, security-auditor)
There was a problem hiding this comment.
Fixed in 3aeb3c1: the fallback is now chosen per class (fallback_for, an exhaustive match). MaybeSent and LockHeld keep the prepared handback failure. Unknown gets its own unclassified exception (ErrorUnknown, Unknown, not retryable), prepared in JNI_OnLoad next to it, so a failed read never reads as a payment. NotSent stays a RuntimeException. Test: should_fall_back_to_the_prepared_exception_of_the_result_class.
There was a problem hiding this comment.
Resolved (re-reviewed at 223452aa): I verified that your Unknown branch selects the separately prepared unclassified exception, whose delivery Kotlin decodes as null. A read failure no longer selects the prepared payment exception.
| Err(message) => { | ||
| return PlatformWalletFFIResult::err( | ||
| PlatformWalletFFIResultCode::ErrorUtf8Conversion, | ||
| message, | ||
| ) |
There was a problem hiding this comment.
✅ Resolved at
223452aa; see the replies below.
🟡 Suggestion: A contact profile containing a NUL can crash the Android example app when profile previews load
Impact: A user opening the DashPay send sheet or adding a contact whose synced public message contains a NUL can have the example app's coroutine fail before the screen is usable.
The new from_profile conversion intentionally returns ErrorUtf8Conversion instead of dropping a NUL-containing field, and the schema permits such a string. That error is appropriate at the FFI boundary, but the Kotlin example app now reaches it from unguarded LaunchedEffect calls: SendDashPayPaymentSheet.kt:71 directly calls getContactProfile, and AddContactScreen.kt:272 does the same before parseDashPayProfile. Neither site catches the SDK error, so a peer-controlled cached profile can abort the coroutine and prevent the preview/send flow from opening. Catch the profile-read failure at both display sites, rethrow CancellationException, and show an unavailable-profile state or continue without the optional profile.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality, security-auditor)
There was a problem hiding this comment.
Fixed in 223452a: every profile read on a display path now survives a profile the wallet cannot convert, and CancellationException is still rethrown. SendDashPayPaymentSheet and the AddContactScreen preview carry on without the profile. The third reader, Your Profile's OwnProfileChecker, treats an unreadable own profile as unknown, never as "no profile", because "no profile" would offer a second, paid create; it keeps polling. The save path's re-read was already inside its try. Test: OwnProfileCheckGateTest.shouldKeepPollingWhenTheCachedProfileCannotBeRead.
There was a problem hiding this comment.
Resolved (re-reviewed at 223452aa): Your two contact previews now continue without the optional profile and rethrow cancellation. The own-profile checker also keeps a failed read unchecked, so it cannot authorize another paid create.
…ailure A drain that returned Pending with no error fails unclassified: its failure holds the slot and names no lock, so the Resume a later status read offers for that operation's lock was re-presented without running. The controller now decides once (permitsStart, read by startFunding and submit): a resume under the failed operation's own id goes on with that payment, unless the failure names another lock. A fresh start stays refused. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ibly sent A timeout or network error carries no native class: no verdict was reached. shieldedOperationMayHaveGoneThrough read it as a refusal, so an identity shield or a shielded top-up that timed out showed a failure and released its slot, and a second payment could follow. Like rs-sdk-ffi's unconfirmed transition it is now unresolved on every shielded path (identity shield and top-up, tip, private document, token pool and purchase); typed refusals keep their wording. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ps a payment hold The Core and Platform-address top-up screens and Seed Pool kept a failure that may have left the wallet with no lock held, and offered no way out but leaving the screen. Each now shows ReleasePaymentHoldButton for such a failure, clearing it only after the user confirms. Held locks stay on their resume path; NOT_SENT failures never held the form. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ts error cannot be allocated The JNI layer keeps the class when it cannot build the exception, but DashSdkError.fromNative then allocates the public error. Every conversion (mapNativeErrors, the paid-output handback, the drain outcome) goes through it, so it now falls back to a MAYBE_SENT, non-retryable error built at class load when the mapping runs out of memory for a MAYBE_SENT or LOCK_HELD failure. Any other class has no payment to protect and lets the OutOfMemoryError through. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…der heap pressure throw_pwffi_result fell back to the prepared handback failure (MaybeSent) for every class but NotSent, so a failed read the JVM could not report reached Kotlin as a payment that may have gone through. The fallback is now picked per class: MaybeSent and LockHeld keep the prepared handback failure, Unknown gets its own prepared unclassified exception, NotSent stays a RuntimeException. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… bytes Base58 decodes any width, so a one-byte key passed for a token id. The balances a paid token write returns are decoded by decodeTokenBalances, which now requires 32 bytes and throws with the handback class, like an unreadable amount; tests cover both and the empty result. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…llet cannot read A cached profile with a NUL now fails to convert. The send sheet and the add-contact preview read it in an unguarded LaunchedEffect, so the screen broke; both now go on without the profile (cancellation still propagates). Your Profile's checker treats an unreadable own profile as unknown, never as "no profile", so it keeps polling instead of offering a second, paid create. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A top-up from Platform addresses leaves no record of the attempt, and the balance history shows balance changes, not that top-up's outcome, so the release that asks the user to check it in the history could only invite a second payment. The screen holds a possibly sent top-up until the user leaves it, as Swift's TopUpIdentityView does. The Core top-up and Seed Pool keep their release: their asset lock transaction is in the history. 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
Changes requested: 2 blockers
- Kotlin substitutes its own payment classification when error mapping runs out of memory —
packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt:1157-1168(new)
Impact: Android callers who receive the low-memory fallback get a Kotlin-authored broadcast-unconfirmed error instead of the wallet's handback error. - A completed Android payment loses its no-retry signal when the JVM cannot allocate the replacement error —
packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt:1132-1145(carried)
Impact: An Android user whose Core send broadcasts under heap pressure can get an ordinary form error and submit a second payment.
New on this head: This round adds a Kotlin low-memory error fallback, gives unclassified JNI errors their own fallback, checks Swift token-balance identifier widths, and keeps Android DashPay screens open when cached profiles cannot be read. The Kotlin SDK build and tests passed on the x86_64 emulator at this head; the PastaClaw review check is pending.
🔴 2 blocking | 🟡 1 suggestion(s)
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: The shared Android fallback can carry a decode error from an earlier payment
Impact: A Kotlin caller who receives the low-memory fallback can see suppressed diagnostics from another operation in the same process.
packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/PaidOutput.kt:42-49
handbackFailure appends the current decode exception to the result of DashSdkError.fromNative. Since 46b753d40d, that result can be a process-wide singleton rather than a fresh exception. A successful addSuppressed retains the decode error on the singleton and exposes it on later throws; the append can also allocate immediately after mapping failed to allocate. Attach per-call diagnostics only to fresh errors and leave the prepared fallback untouched.
source: gpt-6.2-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality, security-auditor)
Review provenance
Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.2-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.2-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
normalbygpt-6.2-sol(effort low) — The diff is cross-cutting and affects whether callers treat a payment as safe to retry, but it changes output handling after execution rather than funds movement, coin selection, or another critical surface. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (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) - New since the last final review (
650c9c61): 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-sol— general (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— rust-quality (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— 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/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt`:
- [BLOCKING] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt:1132-1145: A completed Android payment loses its no-retry signal when the JVM cannot allocate the replacement error
Impact: An Android user whose Core send broadcasts under heap pressure can get an ordinary form error and submit a second payment.
The send form can still allow a second payment even when JNI successfully throws its prepared `MaybeSent` exception. `sendToAddresses` broadcasts before JNI allocates the Java txid (`wallet_manager.rs:1361–1384`). On a process's first mapped error, `mapNativeErrors` accesses `DashSdkError.Companion`, which allocates the public fallback before `classedOrPrepared` enters its `try`. Neither `NativeLoader.ensureLoaded` nor the successful path to broadcast initializes that fallback. If initialization runs out of memory, `PaymentFailure.ofPayment` does not recognize the resulting `OutOfMemoryError`; `SendTransactionScreen` clears `isSending` without setting a hold, and a fresh send can spend other available inputs. The injected builder test exercises only the already-initialized case. Even then, reading `delivery` or `isRetryable` still allocates through the `generateSequence` cause walk. Prepare the public fallback before paid work can dispatch and make its payment metadata readable without allocating.
- [BLOCKING] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt:1157-1168: Kotlin substitutes its own payment classification when error mapping runs out of memory
Impact: Android callers who receive the low-memory fallback get a Kotlin-authored broadcast-unconfirmed error instead of the wallet's handback error.
Kotlin becomes a second authority on payment recovery in this branch. `PREPARED_HANDBACK_FAILURE` constructs a synthetic `DashSDKException` with code `1020`, `MAYBE_SENT`, and `retryable = false`. JNI's prepared handback instead uses `ErrorSerialization` and gets its delivery and retry values from `rs-platform-wallet::error::handback_failure_payment_class` via `PlatformWalletFFIResult::handback_failure`. The delivery and retry values agree today, but the book's “FFI and mobile SDKs hold no business logic” rule requires Kotlin to carry that decision, not duplicate it. Build the public fallback from the Rust-classified exception during SDK initialization.
_Confirmed by an independent pass: The book’s “FFI and mobile SDKs hold no business logic” rule requires Kotlin to carry Rust’s payment-recovery decision, not make its own. If JNI reports a possibly sent payment and Kotlin runs out of memory while mapping that error, the new fallback substitutes a Kotlin-created exception with hard-coded `MAYBE_SENT` and `retryable = false` instead of using a Rust-classified fallback._
In `packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt`:
- [SUGGESTION] packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt:540-547: Your Profile keeps asking users to wait for sync when the cached profile is unreadable
Impact: An Android example-app user whose published profile contains an embedded NUL can see a sync message and be unable to edit the profile even after sync succeeds.
Waiting for another sync does not resolve this error while the published profile is unchanged. The DashPay schema allows an embedded NUL in `publicMessage`, and sync preserves that text, but `DashPayProfileFFI::from_profile` rejects it on every cached read. The new catch returns `Answer(null, checked = false)`, so the screen polls every two seconds, keeps Edit disabled, and says it is waiting for sync. Keep creation disabled for an unreadable profile, but report the read failure separately from a sync that has not finished.
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.
- The DashPay example send sheet re-enables Send after an uncertain payment — The existing
performDashPaySendcatch passes only the error message to the sheet and clearsisSending. It does not retain the delivery class, so a user can submit again after a broadcast whose result could not be returned.- Follow-up: Use #6009 to wire the DashPay sheet into the existing payment-hold flow for uncertain delivery.
| fun fromNative(e: DashSDKException): DashSdkError = classedOrPrepared(e, ::mapNative) | ||
|
|
||
| /** [fromNative] over [build]; tests replace it to raise the OOM. */ | ||
| internal fun classedOrPrepared( | ||
| e: DashSDKException, | ||
| build: (DashSDKException) -> DashSdkError, | ||
| ): DashSdkError = | ||
| try { | ||
| build(e) | ||
| } catch (oom: OutOfMemoryError) { | ||
| when (e.paymentDelivery) { | ||
| PaymentDelivery.MAYBE_SENT, PaymentDelivery.LOCK_HELD -> PREPARED_HANDBACK_FAILURE | ||
| PaymentDelivery.NOT_SENT, null -> throw oom | ||
| } |
There was a problem hiding this comment.
✅ Resolved at
1ca9633b; see the replies below.
🔴 Blocking: A completed Android payment loses its no-retry signal when the JVM cannot allocate the replacement error
Impact: An Android user whose Core send broadcasts under heap pressure can get an ordinary form error and submit a second payment.
The send form can still allow a second payment even when JNI successfully throws its prepared MaybeSent exception. sendToAddresses broadcasts before JNI allocates the Java txid (wallet_manager.rs:1361–1384). On a process's first mapped error, mapNativeErrors accesses DashSdkError.Companion, which allocates the public fallback before classedOrPrepared enters its try. Neither NativeLoader.ensureLoaded nor the successful path to broadcast initializes that fallback. If initialization runs out of memory, PaymentFailure.ofPayment does not recognize the resulting OutOfMemoryError; SendTransactionScreen clears isSending without setting a hold, and a fresh send can spend other available inputs. The injected builder test exercises only the already-initialized case. Even then, reading delivery or isRetryable still allocates through the generateSequence cause walk. Prepare the public fallback before paid work can dispatch and make its payment metadata readable without allocating.
source: gpt-6.2-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality)
There was a problem hiding this comment.
Fixed in 84a61a7: after a paid call may have dispatched, mapping its failure never needs an allocation. The fallback is prepared while the native library loads, before any paid call, and its class reads without allocating. Applied at NativeLoader.ensureLoaded (maps Rust's prepared exceptions via DashSdkError.prepareFallbacks), DashSdkError.classedOrPrepared (inline, so nothing is allocated before the try; the fallback is a table lookup), DashSdkError.native (an allocation-free loop behind delivery, heldAssetLock, consensusError and isRetryable), readingPaidOutput (catches OutOfMemoryError) and handbackFailure (falls back to the prepared handback failure and never adds suppressed errors to a shared prepared one). Tests: DashSdkErrorTest.shouldReadTheClassOfAFailedPaymentWithoutAllocating (fails on the old walk), PaidOutputTest.shouldClassAnOutOfMemoryErrorWhileReadingAPaidOutput, FfiSmokeTest.loadingMapsRustsPreparedFallbacks.
There was a problem hiding this comment.
Resolved (re-reviewed at 1ca9633b): ensureLoaded now prepares the public mapping before it publishes loaded. The mapping catch reuses that object, and the bounded cause walk reads delivery and retryability without allocating.
| internal val PREPARED_HANDBACK_FAILURE: DashSdkError = | ||
| PlatformWallet.TransactionBroadcastUnconfirmed( | ||
| PREPARED_HANDBACK_MESSAGE, | ||
| DashSDKException( | ||
| PLATFORM_WALLET_CODE_OFFSET + 20, | ||
| PREPARED_HANDBACK_MESSAGE, | ||
| null, | ||
| PaymentDelivery.MAYBE_SENT, | ||
| null, | ||
| false, | ||
| ), | ||
| ) |
There was a problem hiding this comment.
✅ Resolved at
1ca9633b; see the replies below.
🔴 Blocking: Kotlin substitutes its own payment classification when error mapping runs out of memory
Impact: Android callers who receive the low-memory fallback get a Kotlin-authored broadcast-unconfirmed error instead of the wallet's handback error.
Kotlin becomes a second authority on payment recovery in this branch. PREPARED_HANDBACK_FAILURE constructs a synthetic DashSDKException with code 1020, MAYBE_SENT, and retryable = false. JNI's prepared handback instead uses ErrorSerialization and gets its delivery and retry values from rs-platform-wallet::error::handback_failure_payment_class via PlatformWalletFFIResult::handback_failure. The delivery and retry values agree today, but the book's “FFI and mobile SDKs hold no business logic” rule requires Kotlin to carry that decision, not duplicate it. Build the public fallback from the Rust-classified exception during SDK initialization.
Confirmed by an independent pass: The book’s “FFI and mobile SDKs hold no business logic” rule requires Kotlin to carry Rust’s payment-recovery decision, not make its own. If JNI reports a possibly sent payment and Kotlin runs out of memory while mapping that error, the new fallback substitutes a Kotlin-created exception with hard-coded MAYBE_SENT and retryable = false instead of using a Rust-classified fallback.
source: gpt-6.2-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality, security-auditor)
There was a problem hiding this comment.
Fixed in 84a61a7: Kotlin holds no payment classification for the low-memory fallback. The fallback is Rust's prepared exception, and which class falls back to which is Rust's support::fallback_for, handed to Kotlin as a table indexed by the class discriminant. Applied at DashSdkError (the Kotlin-built code-1020 fallback and the when over PaymentDelivery are removed), rs-unified-sdk-jni handback.rs (NativeLoader.preparedHandbackFailure / preparedFallbacks), support.rs (the table, with a compile-time check that every class has its slot) and DashSDKException.nativeDelivery. DashSdkErrorTest now checks Rust's table instead of a Kotlin class.
There was a problem hiding this comment.
Resolved (re-reviewed at 1ca9633b): Your loader now maps Rust’s prepared exceptions, and the OOM lookup uses the raw Rust discriminant. The Kotlin-authored code-1020 fallback and its hard-coded classification are gone.
| suspend fun read(): Answer { | ||
| val raw = readProfile() | ||
| val raw = try { | ||
| readProfile() | ||
| } catch (e: CancellationException) { | ||
| throw e | ||
| } catch (e: Exception) { | ||
| return Answer(null, checked = false) | ||
| } |
There was a problem hiding this comment.
✅ Resolved at
1ca9633b; see the replies below.
🟡 Suggestion: Your Profile keeps asking users to wait for sync when the cached profile is unreadable
Impact: An Android example-app user whose published profile contains an embedded NUL can see a sync message and be unable to edit the profile even after sync succeeds.
Waiting for another sync does not resolve this error while the published profile is unchanged. The DashPay schema allows an embedded NUL in publicMessage, and sync preserves that text, but DashPayProfileFFI::from_profile rejects it on every cached read. The new catch returns Answer(null, checked = false), so the screen polls every two seconds, keeps Edit disabled, and says it is waiting for sync. Keep creation disabled for an unreadable profile, but report the read failure separately from a sync that has not finished.
source: gpt-6.2-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality, security-auditor)
There was a problem hiding this comment.
Fixed in 235acd6: a failed read of the cached own profile is reported as a read failure, separate from a pending sync, and Edit and Create stay off. Applied at OwnProfileChecker.read (the poll and the reload after a write) and the read before a create, which now stops the create with the same text instead of the raw native message. The Swift example app copies (DashPayTabView.swift, IdentityDetailView.swift) are outside this PR and left for a follow-up.
There was a problem hiding this comment.
Resolved (re-reviewed at 1ca9633b): Your new unreadable answer takes precedence over the sync message and leaves Edit disabled. The pre-create check now shows a read failure and returns before submitting.
| let fallback = if result.payment_delivery == PlatformWalletFFIPaymentDelivery::NotSent { | ||
| Fallback::Runtime | ||
| } else { | ||
| Fallback::HandbackPrepared | ||
| }; |
There was a problem hiding this comment.
Resolved (re-reviewed at 223452aa): I verified that your Unknown branch selects the separately prepared unclassified exception, whose delivery Kotlin decodes as null. A read failure no longer selects the prepared payment exception.
| Err(message) => { | ||
| return PlatformWalletFFIResult::err( | ||
| PlatformWalletFFIResultCode::ErrorUtf8Conversion, | ||
| message, | ||
| ) |
There was a problem hiding this comment.
Resolved (re-reviewed at 223452aa): Your two contact previews now continue without the optional profile and rethrow cancellation. The own-profile checker also keeps a failed read unchecked, so it cannot authorize another paid create.
The Platform-address top-up showed its pending warning only for a MAYBE_SENT failure. A failure with no delivery class holds the slot too, so after the user dismissed its alert the Top Up button stayed disabled for both sources with nothing saying why. The warning now shows whenever the kept failure holds its slot (topUpPendingAfter, the inverse of topUpPermittedAfter), still without a release. The other payment screens already explain such a hold: Send closes the form, and DPNS, invitations and Seed Pool show the release button for it. The Swift comparison in the comment now says that TopUpIdentityView's held-failure section does offer a release for a classless failure. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… pending sync Your Profile in the example app showed "waiting for sync" for a cached profile the wallet cannot read (an embedded NUL in a published field), which no sync resolves. Every own-profile read now reports such a failure as a read failure: OwnProfileChecker.read (the poll and the reload after a write) answers unreadable, and the read before a create stops the create with the same text instead of the raw native message. Edit and Create stay off while the profile is unreadable. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…, when error mapping runs out of memory Kotlin built its own low-memory fallback (code 1020, MAYBE_SENT, not retryable) in a companion initializer that ran on the first mapped error, after a paid call may have dispatched, and picked which classes fall back to it itself. Reading delivery or isRetryable then walked the cause chain through an allocating sequence. The fallback is now Rust's: NativeLoader.ensureLoaded takes the exceptions JNI prepared at load (preparedHandbackFailure, and preparedFallbacks, the exception support::fallback_for picks per payment class, indexed by the class discriminant) and maps each into DashSdkError once, before any paid call can dispatch. fromNative falls back through that table by the raw class JNI passed, so the choice (LOCK_HELD to the handback failure, Unknown to the unclassified one, none for NotSent) stays Rust's and the fallback path allocates nothing and loads no class. The cause walk behind delivery, heldAssetLock, consensusError and isRetryable is a plain loop. readingPaidOutput classes an OutOfMemoryError like any read failure, handbackFailure falls back to the prepared handback failure when it cannot allocate, and a prepared error is never given a suppressed exception. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ivery-kotlin' into feat/platform-wallet-handback-class
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
Changes requested: 2 blockers
- Android can lose the no-retry signal after a DashPay payment or voucher is funded —
packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/PaidOutput.kt:20-35(new)
Impact: Under Android heap pressure, a sender can lose the transaction ID and no-retry error after broadcast, while an inviter can be offered a second funded voucher instead of being told to reclaim the first. - Android can offer a second token purchase when it runs out of memory reporting the first —
packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt:1149-1153(new)
Impact: A buyer whose identity-funded purchase executes without confirmation can dismiss a generic error and spend credits on the same purchase again.
New on this head: This round maps Rust’s prepared payment errors during Android SDK initialization, removes allocations from reading their payment metadata, and distinguishes an unreadable DashPay profile from a pending sync. The Kotlin SDK build and tests passed on the x86_64 emulator at this head; no code checks failed, and the review check is still pending.
A pattern across this PR's review rounds
This is review round 4, and the PR has drawn 6 blocking findings so far. 5 of them share 2 underlying causes. They are listed with the other findings as usual; fixing the cause is likely to be cheaper than fixing each case.
1. The no-retry signal can be lost between layers (2 new in this round, 3 earlier finding(s))
Rust decides whether a payment may have been sent, but Android has no single path that preserves that decision from dispatch through result decoding to the screen’s decision to allow another payment. Preparing the JNI exception exposed another allocation in DashSdkError mapping; Kotlin briefly supplied its own classification before switching to Rust’s prepared error. That still leaves decoder allocation outside readingPaidOutput’s guard, and identityPurchaseMayHaveGoneThrough checks exception subtypes rather than the delivery class the fallback preserves.
Already tracked: #6009
In this round: Android can lose the no-retry signal after a DashPay payment or voucher is funded; Android can offer a second token purchase when it runs out of memory reporting the first
2. An unreadable profile has no reliable recovery path (1 new in this round, 2 earlier finding(s))
DashPayProfileFFI::from_profile can now reject a cached profile that Platform accepts, but the Android screens were built without a separate, recoverable state for an unreadable profile. After catches kept failed reads from breaking screens, OwnProfileChecker initially treated the failure as pending sync; the new profileUnreadable flag distinguishes it and blocks Create, but DashPayProfileScreen still discards fresh read answers while editing.
In this round: Create stays disabled after an unreadable profile becomes readable again
Suggested decision (redesign the component): Redesign Android paid-call handback as one path from native dispatch to the decision to allow another payment. For the payment flows covered by this PR, a failure after dispatch must preserve Rust’s no-retry decision through output decoding and error mapping without requiring another allocation, and the screen must honor that decision even when the original error subtype is unavailable. Keep the existing #6009 deferrals out of this redesign.
🔴 2 blocking | 🟡 2 suggestion(s)
Review provenance
Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.2-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
normalbygpt-6.2-sol(effort low) — The patch is large and cross-language, but it changes how bindings report failures after paid operations return, not how funds move or how any other critical surface behaves. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (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) - New since the last final review (
223452aa): 2 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 2 confirmed - Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-sol— general (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— rust-quality (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
Several findings on this PR share an underlying cause (the review's "pattern" section): The no-retry signal can be lost between layers; An unreadable profile has no reliable recovery path. When you fix the findings below, fix the cause, not only the reported case. The review suggests (redesign the component): Redesign Android paid-call handback as one path from native dispatch to the decision to allow another payment. For the payment flows covered by this PR, a failure after dispatch must preserve Rust’s no-retry decision through output decoding and error mapping without requiring another allocation, and the screen must honor that decision even when the original error subtype is unavailable. Keep the existing #6009 deferrals out of this redesign. If that decision is not yours to make, say so to the PR's author or maintainer.
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/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/PaidOutput.kt`:
- [BLOCKING] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/PaidOutput.kt:20-35: Android can lose the no-retry signal after a DashPay payment or voucher is funded
Impact: Under Android heap pressure, a sender can lose the transaction ID and no-retry error after broadcast, while an inviter can be offered a second funded voucher instead of being told to reclaim the first.
A successful paid JNI call can still escape the new OOM handler as a bare `OutOfMemoryError`. `Dashpay.sendPayment` receives the packed transaction ID and fee after broadcast, and `Dashpay.createInvitation` receives the link after Rust broadcasts and records the voucher. Both then pass a capturing decoder to the non-inline `readingPaidOutput`. If allocating that decoder fails on the unoptimized Android path, the helper’s `try` has not started, and `mapNativeErrors` only catches `DashSDKException`. The send sheet catches `Exception`, so the bare OOM can abort its coroutine without a receipt. The invitation sheet catches `Throwable`, but `PaymentFailure.keptAfter` installs no hold for a raw OOM; when the user taps Create again and has sufficient funds, Rust funds a separate voucher. Identity resume, reclaim, and invitation claim also allocate a `ManagedIdentityResultHandle` before the guard, so OOM there can strand the native result handle. Start the guard immediately after native success, inline the decoder to avoid allocating its closure, and ensure the raw handle is released even if constructing its Kotlin owner fails. Keep pre-dispatch failures outside this guard.
_Confirmed by an independent pass: On a memory-constrained Android device, a user can tap Create Invitation, have Rust broadcast and record the voucher, and then hit an OutOfMemoryError while Kotlin allocates the decoder before entering readingPaidOutput. The sheet catches the raw error but installs no payment hold, so another tap with enough spendable DASH funds a second voucher and incurs another transaction fee._
In `packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt`:
- [BLOCKING] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt:1149-1153: Android can offer a second token purchase when it runs out of memory reporting the first
Impact: A buyer whose identity-funded purchase executes without confirmation can dismiss a generic error and spend credits on the same purchase again.
Direct Purchase leaves the form open for another payment even though the fallback still says `MAYBE_SENT`. If the token purchase broadcasts but confirmation fails, the wallet FFI maps the SDK outcome to `ErrorTransactionBroadcastUnconfirmed`. When Kotlin then runs out of memory creating its public error, `84a61a79c2` returns the Rust-prepared `ErrorSerialization`, which maps to `PlatformWallet.Generic`; the previous Kotlin fallback, when available, was a `TransactionBroadcastUnconfirmed`. `identityPurchaseMayHaveGoneThrough` in `TokenActionScreens.kt:1006–1008` only accepts that type or `StateTransitionResultUnconfirmed`, so the generic error skips the do-not-resubmit notice. `TokenActionScaffold.kt:112–123` displays an ordinary failure and clears `isSubmitting`. If the first purchase executed and the buyer has credits left, another tap signs a new transition with the next identity-contract nonce. Keep Rust’s prepared fallback and have the purchase form read `delivery` first, retaining the typed check for classless SDK errors.
_Confirmed by an independent pass: A user can tap Buy with identity credits, have the purchase execute on Platform, and miss its confirmation because the response times out. If JNI constructs the unconfirmed exception but Kotlin runs out of memory mapping it, Direct Purchase shows an ordinary failure and re-enables Buy without the do-not-resubmit notice. With sufficient credits and tokens still available at the quoted price, a second tap signs with the next identity-contract nonce and charges the buyer again._
In `packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt`:
- [SUGGESTION] packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt:370-377: Create stays disabled after an unreadable profile becomes readable again
Impact: An example-app user whose pre-create read fails once may have to reopen Your Profile even after the wallet has synced a readable copy.
The editor cannot recover from a failed pre-create read while it is open. The catch sets `profileUnreadable`, which disables Create, but the refresh effect and polling callback at lines 191–200 skip applying answers during editing. For example, another device can publish an unreadable profile while the Create form is open, then correct it; if sync sees the correction while the editor is still open, the screen ignores it. Cancel does not itself trigger a read because `isEditing` is not an effect key, and the initial poll may already have ended with the checked cache miss that opened the editor. Keep creation blocked while the result is unknown, but offer a read-only recheck or explicitly reload on Cancel.
In `packages/rs-unified-sdk-jni/src/support.rs`:
- [SUGGESTION] packages/rs-unified-sdk-jni/src/support.rs:275-305: A new payment class can compile without a Kotlin fallback slot
Impact: If a future payment class needs a no-retry fallback but is left out of the table, Android callers can get a bare `OutOfMemoryError` even though JNI knows which prepared error to use.
The compile-time check verifies the slots that exist, not that every class has a slot. Adding a new class and handling it in the exhaustive `delivery_slot` and `fallback_for` matches still compiles if `DELIVERIES` is left unchanged: the const loop only visits the existing entries. JNI can then select a fallback for the new discriminant, while Kotlin’s `preparedFallback` has no entry for it. Generate the table and the exhaustive coverage check from the same variant list so handling a new class cannot leave its slot out.
| internal fun <T> readingPaidOutput( | ||
| what: String, | ||
| failure: (String, Throwable) -> DashSdkError = ::handbackFailure, | ||
| read: () -> T, | ||
| ): T = | ||
| try { | ||
| read() | ||
| } catch (e: CancellationException) { | ||
| throw e | ||
| } catch (e: DashSdkError) { | ||
| if (e.native != null) throw e | ||
| throw failure(what, e) | ||
| } catch (e: Exception) { | ||
| throw failure(what, e) | ||
| } catch (e: OutOfMemoryError) { | ||
| throw failure(what, e) |
There was a problem hiding this comment.
🔴 Blocking: Android can lose the no-retry signal after a DashPay payment or voucher is funded
Impact: Under Android heap pressure, a sender can lose the transaction ID and no-retry error after broadcast, while an inviter can be offered a second funded voucher instead of being told to reclaim the first.
A successful paid JNI call can still escape the new OOM handler as a bare OutOfMemoryError. Dashpay.sendPayment receives the packed transaction ID and fee after broadcast, and Dashpay.createInvitation receives the link after Rust broadcasts and records the voucher. Both then pass a capturing decoder to the non-inline readingPaidOutput. If allocating that decoder fails on the unoptimized Android path, the helper’s try has not started, and mapNativeErrors only catches DashSDKException. The send sheet catches Exception, so the bare OOM can abort its coroutine without a receipt. The invitation sheet catches Throwable, but PaymentFailure.keptAfter installs no hold for a raw OOM; when the user taps Create again and has sufficient funds, Rust funds a separate voucher. Identity resume, reclaim, and invitation claim also allocate a ManagedIdentityResultHandle before the guard, so OOM there can strand the native result handle. Start the guard immediately after native success, inline the decoder to avoid allocating its closure, and ensure the raw handle is released even if constructing its Kotlin owner fails. Keep pre-dispatch failures outside this guard.
Confirmed by an independent pass: On a memory-constrained Android device, a user can tap Create Invitation, have Rust broadcast and record the voucher, and then hit an OutOfMemoryError while Kotlin allocates the decoder before entering readingPaidOutput. The sheet catches the raw error but installs no payment hold, so another tap with enough spendable DASH funds a second voucher and incurs another transaction fee.
source: gpt-6.2-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality)
There was a problem hiding this comment.
Fixed in b413be6: from the moment a paid native call returns success, every Kotlin step up to the returned value runs inside the handback guard without allocating first, and a raw handle is released when its owner cannot be built. readingPaidOutput is inline. Applied at Dashpay.sendPayment/createInvitation, DpnsMarketplace giveUp/trade, Tokens.updateConfig, decodeChangeset, shieldedIdentityCreateFromPool, the private document entry, DecisionProposals.create, MultipleChoiceProposals.create/enterChoice, DocumentTransactions.eraseAndObserve and the wallet drain outcome. The new owningPaidHandle covers the six contact request/accept calls in Dashpay and PlatformWalletManager. IdentityRegistration resume/reclaim/claim release the raw handle in a finally around the guard, with no owner object. opReturningCompletedResult no longer allocates a wrapper after success. Boxing a Long result through the generic gate and the coroutine resume are outside what Kotlin can guard.
There was a problem hiding this comment.
Still applies (re-reviewed at 2c8824a5): Inlining fixes the DashPay payment and invitation decoders, and the registration paths no longer allocate an owner before reading the result. The remaining allocation is not the generic teardown gate: the new registration finally boxes the handle for destroyManagedIdentity, which can mask the prepared error before JNI gets to release the handle.
| try { | ||
| build(e) | ||
| } catch (oom: OutOfMemoryError) { | ||
| preparedFallback(e) ?: throw oom | ||
| } |
There was a problem hiding this comment.
✅ Resolved at
2c8824a5; see the replies below.
🔴 Blocking: Android can offer a second token purchase when it runs out of memory reporting the first
Impact: A buyer whose identity-funded purchase executes without confirmation can dismiss a generic error and spend credits on the same purchase again.
Direct Purchase leaves the form open for another payment even though the fallback still says MAYBE_SENT. If the token purchase broadcasts but confirmation fails, the wallet FFI maps the SDK outcome to ErrorTransactionBroadcastUnconfirmed. When Kotlin then runs out of memory creating its public error, 84a61a79c2 returns the Rust-prepared ErrorSerialization, which maps to PlatformWallet.Generic; the previous Kotlin fallback, when available, was a TransactionBroadcastUnconfirmed. identityPurchaseMayHaveGoneThrough in TokenActionScreens.kt:1006–1008 only accepts that type or StateTransitionResultUnconfirmed, so the generic error skips the do-not-resubmit notice. TokenActionScaffold.kt:112–123 displays an ordinary failure and clears isSubmitting. If the first purchase executed and the buyer has credits left, another tap signs a new transition with the next identity-contract nonce. Keep Rust’s prepared fallback and have the purchase form read delivery first, retaining the typed check for classless SDK errors.
Confirmed by an independent pass: A user can tap Buy with identity credits, have the purchase execute on Platform, and miss its confirmation because the response times out. If JNI constructs the unconfirmed exception but Kotlin runs out of memory mapping it, Direct Purchase shows an ordinary failure and re-enables Buy without the do-not-resubmit notice. With sufficient credits and tokens still available at the quoted price, a second tap signs with the next identity-contract nonce and charges the buyer again.
source: gpt-6.2-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality)
There was a problem hiding this comment.
Fixed in f030458: every example-app screen that decides whether to allow another payment reads Rust's delivery first and keeps typed checks only for errors with no class. Rust's prepared fallback is unchanged. One helper, paymentMayHaveGoneThrough, is applied at Direct Purchase (identityPurchaseNotice), Update Key Limits, Create Decision Proposal, Give Up Name submit, Update Contract, and the shared catches of document transactions (including erase), token actions and the DashPay send sheet, which now hold the form. The shielded flows already used it. Tests feed the prepared fallback (Generic, MAYBE_SENT) through the helper and each routed form. Screens that read no class at all and sit outside this diff (transfers, withdrawals, name registration, proposal details) are left for a follow-up.
There was a problem hiding this comment.
Resolved (re-reviewed at 2c8824a5): Direct Purchase now reads delivery before checking the error type, so Rust’s prepared generic MAYBE_SENT error produces the unconfirmed-purchase notice instead of re-enabling Buy.
| } catch (e: Exception) { | ||
| // Unknown whether a profile exists: | ||
| // never create over it. | ||
| profileUnreadable = true | ||
| profileChecked = false | ||
| saveError = PROFILE_UNREADABLE_MESSAGE + | ||
| " Your profile was not created." | ||
| return@launch |
There was a problem hiding this comment.
✅ Resolved at
2c8824a5; see the replies below.
🟡 Suggestion: Create stays disabled after an unreadable profile becomes readable again
Impact: An example-app user whose pre-create read fails once may have to reopen Your Profile even after the wallet has synced a readable copy.
The editor cannot recover from a failed pre-create read while it is open. The catch sets profileUnreadable, which disables Create, but the refresh effect and polling callback at lines 191–200 skip applying answers during editing. For example, another device can publish an unreadable profile while the Create form is open, then correct it; if sync sees the correction while the editor is still open, the screen ignores it. Cancel does not itself trigger a read because isEditing is not an effect key, and the initial poll may already have ended with the checked cache miss that opened the editor. Keep creation blocked while the result is unknown, but offer a read-only recheck or explicitly reload on Cancel.
source: gpt-6.2-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality)
There was a problem hiding this comment.
Fixed in 7049249: an unknown own-profile answer keeps creation blocked, and Cancel reads the wallet again (read only), so a profile that became readable, or was found, is applied. No recheck is applied inside an open create draft, so a profile found mid-draft cannot turn the create into an update.
There was a problem hiding this comment.
Resolved (re-reviewed at 2c8824a5): Cancel now performs the read needed to recover from a failed pre-create check without leaving Your Profile. The read can still finish after Edit is reopened on a previously checked miss; that is a separate race in the new reload.
| /// Every payment-delivery class at the index of its discriminant, the order | ||
| /// of the table [`prepared_fallbacks`] hands to Kotlin. | ||
| const DELIVERIES: [PlatformWalletFFIPaymentDelivery; 5] = [ | ||
| PlatformWalletFFIPaymentDelivery::None, | ||
| PlatformWalletFFIPaymentDelivery::NotSent, | ||
| PlatformWalletFFIPaymentDelivery::MaybeSent, | ||
| PlatformWalletFFIPaymentDelivery::LockHeld, | ||
| PlatformWalletFFIPaymentDelivery::Unknown, | ||
| ]; | ||
|
|
||
| /// The slot of `delivery` in [`DELIVERIES`]. Exhaustive, so a class added to | ||
| /// the FFI fails the build here until it has a slot in the table. | ||
| const fn delivery_slot(delivery: PlatformWalletFFIPaymentDelivery) -> usize { | ||
| match delivery { | ||
| PlatformWalletFFIPaymentDelivery::None => 0, | ||
| PlatformWalletFFIPaymentDelivery::NotSent => 1, | ||
| PlatformWalletFFIPaymentDelivery::MaybeSent => 2, | ||
| PlatformWalletFFIPaymentDelivery::LockHeld => 3, | ||
| PlatformWalletFFIPaymentDelivery::Unknown => 4, | ||
| } | ||
| } | ||
|
|
||
| // Each class sits at its slot and its discriminant, the index Kotlin reads. | ||
| const _: () = { | ||
| let mut index = 0; | ||
| while index < DELIVERIES.len() { | ||
| assert!(delivery_slot(DELIVERIES[index]) == index); | ||
| assert!(DELIVERIES[index] as usize == index); | ||
| index += 1; | ||
| } | ||
| }; |
There was a problem hiding this comment.
✅ Resolved at
2c8824a5; see the replies below.
🟡 Suggestion: A new payment class can compile without a Kotlin fallback slot
Impact: If a future payment class needs a no-retry fallback but is left out of the table, Android callers can get a bare OutOfMemoryError even though JNI knows which prepared error to use.
The compile-time check verifies the slots that exist, not that every class has a slot. Adding a new class and handling it in the exhaustive delivery_slot and fallback_for matches still compiles if DELIVERIES is left unchanged: the const loop only visits the existing entries. JNI can then select a fallback for the new discriminant, while Kotlin’s preparedFallback has no entry for it. Generate the table and the exhaustive coverage check from the same variant list so handling a new class cannot leave its slot out.
source: gpt-6.2-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality)
There was a problem hiding this comment.
Fixed in a507e33: the fallback table and its coverage check come from one list. delivery_table! generates a match that must name every payment class and asserts each class sits at its discriminant, so a new class cannot compile without a slot. Kotlin's preparedFallback returns null for a class with no slot (tested), and FfiSmokeTest checks slot 0 and the table size.
There was a problem hiding this comment.
Resolved (re-reviewed at 2c8824a5): Your macro now builds the table and an exhaustive match from the same variant list, and the const assertion checks each index against its discriminant. Adding a class without a slot now fails compilation.
| fun fromNative(e: DashSDKException): DashSdkError = classedOrPrepared(e, ::mapNative) | ||
|
|
||
| /** [fromNative] over [build]; tests replace it to raise the OOM. */ | ||
| internal fun classedOrPrepared( | ||
| e: DashSDKException, | ||
| build: (DashSDKException) -> DashSdkError, | ||
| ): DashSdkError = | ||
| try { | ||
| build(e) | ||
| } catch (oom: OutOfMemoryError) { | ||
| when (e.paymentDelivery) { | ||
| PaymentDelivery.MAYBE_SENT, PaymentDelivery.LOCK_HELD -> PREPARED_HANDBACK_FAILURE | ||
| PaymentDelivery.NOT_SENT, null -> throw oom | ||
| } |
There was a problem hiding this comment.
Resolved (re-reviewed at 1ca9633b): ensureLoaded now prepares the public mapping before it publishes loaded. The mapping catch reuses that object, and the bounded cause walk reads delivery and retryability without allocating.
| internal val PREPARED_HANDBACK_FAILURE: DashSdkError = | ||
| PlatformWallet.TransactionBroadcastUnconfirmed( | ||
| PREPARED_HANDBACK_MESSAGE, | ||
| DashSDKException( | ||
| PLATFORM_WALLET_CODE_OFFSET + 20, | ||
| PREPARED_HANDBACK_MESSAGE, | ||
| null, | ||
| PaymentDelivery.MAYBE_SENT, | ||
| null, | ||
| false, | ||
| ), | ||
| ) |
There was a problem hiding this comment.
Resolved (re-reviewed at 1ca9633b): Your loader now maps Rust’s prepared exceptions, and the OOM lookup uses the raw Rust discriminant. The Kotlin-authored code-1020 fallback and its hard-coded classification are gone.
| suspend fun read(): Answer { | ||
| val raw = readProfile() | ||
| val raw = try { | ||
| readProfile() | ||
| } catch (e: CancellationException) { | ||
| throw e | ||
| } catch (e: Exception) { | ||
| return Answer(null, checked = false) | ||
| } |
There was a problem hiding this comment.
Resolved (re-reviewed at 1ca9633b): Your new unreadable answer takes precedence over the sync message and leaves Edit disabled. The pre-create check now shows a read failure and returns before submitting.
… class list The compile-time check walked only the classes already in DELIVERIES, so a payment class added to the FFI compiled without a slot and Kotlin found no fallback for it. A macro now declares the table from one list and checks it: a match over the list must name every class, and each class must sit at the index of its discriminant. On the Kotlin side a class with no slot finds no fallback (tested), the LOCK_HELD fallback (the handback failure, MAYBE_SENT without its lock) is documented, and FfiSmokeTest checks slot 0 and the table size. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…locating nothing first The decoder passed to the non-inline readingPaidOutput was allocated before its try, so an OutOfMemoryError right after a paid call (a DashPay payment, an invitation) escaped with no class. Registration results built a ManagedIdentityResultHandle before the guard, and the contact-request calls built their handle owners with no guard, so the raw handle could leak. readingPaidOutput is now inline, and every step from a paid call's return to its result runs inside it: the existing sites, the proposal create and choice results, the erase outcome and the wallet drain outcome. owningPaidHandle builds the owner of a raw handle a paid call returned inside the guard and releases the handle when that fails; it covers the public and private contact request and accept calls. Registration releases its handle in a finally around the guard, with no owner object. opReturningCompletedResult holds the completed result without allocating a wrapper. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A pre-create read that failed left the open editor without a way back: answers are not applied while editing, and the poll may have ended. Cancel now reads the wallet again (read only), so a profile that became readable, or was found, is applied; creation stays blocked while the answer is unknown. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ss on every payment screen Rust's prepared low-memory fallback maps to PlatformWallet.Generic with MAYBE_SENT, and screens that accepted only the broadcast-unconfirmed types re-enabled the form after it. One helper, paymentMayHaveGoneThrough (util), reads delivery first and keeps typed checks only for errors with no class. It replaces the shielded helper and the typed checks in token purchase, decision proposal create, give-up, contract update, document erase and key limits, and the shared catches of document transactions, token actions and the DashPay send sheet now hold the form through it instead of offering a second submit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them. |
|
Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them. |
|
Your move: thepastaclaw left review threads unresolved; resolve them. |
…let-handback-class # Conflicts: # packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt # packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/util/PaymentRecovery.kt # packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ContactRequestOutcomesTest.kt # packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt # packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/DashSDKException.kt # packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt # packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManagerWalletDrain.kt # packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt # packages/rs-unified-sdk-jni/src/dashpay.rs # packages/rs-unified-sdk-jni/src/support.rs # packages/rs-unified-sdk-jni/src/wallet_drain.rs
|
Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them. |
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 2 only (queue backlog)
Changes requested: 2 blockers
- A funded Android drain can still return a bare out-of-memory error —
packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManagerWalletDrain.kt:117-131(new; not shown inline, see below)
Impact: A caller running Max drain on a supported network can lose both the outcome and Rust’s no-retry signal if Android runs out of heap after the wallet funds its asset lock. - Android can lose the no-retry signal after a DashPay payment or voucher is funded —
packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/identity/IdentityRegistration.kt:334-339(carried)
Impact: An Android caller claiming a funded invitation, reclaiming a voucher, or resuming registration under heap pressure can receive a bareOutOfMemoryErrorafter registration succeeds, leaving the native result handle in the registry.
New on this head: This revision makes the JNI fallback table exhaustive, moves Kotlin paid-output decoding into inline guards, and updates several Android example-app forms to use Rust’s payment delivery class. Rust workspace tests, the Swift SDK build and tests, and the Kotlin emulator build and tests passed on 2c8824a54a; PastaClaw review and PR Hygiene are pending.
A pattern across this PR's review rounds
This is review round 5, and the PR has drawn 7 blocking findings so far. 6 of them share 3 underlying causes. They are listed with the other findings as usual; fixing the cause is likely to be cheaper than fixing each case.
1. The no-retry signal can still be lost after the guard (1 new in this round, 5 earlier finding(s))
Android now prepares Rust’s fallback in NativeLoader, protects decoding with readingPaidOutput, and reads the delivery class in paymentMayHaveGoneThrough, but no single path owns the result from dispatch through cleanup to the caller’s retry decision. The funded drain shows why the fixes keep moving the problem: the guard recovers the prepared error, then WalletDrainOutcome.unresolved and WalletDrainActiveCalls.leave can allocate again before the caller receives it.
Already tracked: #6009
In this round: A funded Android drain can still return a bare out-of-memory error
2. Profile refreshes and drafts share the same state (1 new in this round, 2 earlier finding(s))
OwnProfileChecker now distinguishes an unreadable profile from a pending sync, but DashPayProfileScreen still uses the live profileExists flag to choose Create or Save while using editSnapshot to decide what the draft changed. Suppressing refresh answers while editing left the screen stuck on stale state; adding a reload on Cancel lets a late answer change the mode of a newly opened draft.
In this round: A late Cancel reload can turn a reopened profile draft into an update
3. A successful native return does not prove submission (1 new in this round, 1 earlier finding(s))
eraseAndObserve can return NotSubmitted, and acceptContactRequestReplyingInKind can adopt an existing reply without sending one. The Kotlin guards treat both successful returns as proof of payment, but the erase’s submission tag is inside the payload being decoded and the contact handle carries no such tag.
In this round: Accepting a contact can report a possible payment when no reply was sent
Suggested decision (redesign the component): Finish the Android paid-call handback redesign as one path from Rust’s submission outcome to the caller’s retry decision, rather than adding another guard around an individual decoder. Reuse the prepared Rust error and the shared retry check, but make sure decoding, failure return, and cleanup cannot replace that error with a classless one under heap pressure. If a flow cannot use that path in this PR, leave its new handback guarantee out and track it in #6009 without reopening the existing deferrals.
🔴 2 blocking | 🟡 4 suggestion(s)
1 finding(s) not shown inline (the lines are not part of this PR's diff)
🔴 Blocking: A funded Android drain can still return a bare out-of-memory error
Impact: A caller running Max drain on a supported network can lose both the outcome and Rust’s no-retry signal if Android runs out of heap after the wallet funds its asset lock.
packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManagerWalletDrain.kt:117-131
The SDK can throw an unclassified OutOfMemoryError even after recovering Rust’s prepared error. A caller with spendable funds and a stored operation ID can complete native funding and receive the packed result, then run out of heap when WalletDrainOutcome.decode allocates the buffer, outpoint, or result. The new guard converts that failure to a classified DashSdkError, but the catch immediately allocates another WalletDrainOutcome through unresolved(e). The finally also rebuilds the active-call key with joinToString and per-byte formatting; if that allocation fails, it overrides the outcome and leaves the active entry behind. The durable status read still works once memory is available, but it does not preserve the immediate no-retry signal. Prepare a pending outcome carrying Rust’s fallback before dispatch and retain an allocation-free cleanup token. This is separate from preserving the outpoint when JNI cannot allocate the initial result array.
Confirmed by an independent pass: An Android caller with spendable funds can call shieldedFundFromWalletDrain with a saved operation ID and receive the packed JNI result after funding succeeds, then hit the app’s heap limit while Kotlin constructs the outcome. Even when the new guard recovers Rust’s prepared MaybeSent error, the catch allocates a fresh WalletDrainOutcome and can throw a bare OutOfMemoryError instead, leaving the caller without the immediate no-retry signal. The finally can also run out of memory while rebuilding the active-call key, overriding the return and leaving the entry behind.
source: gpt-6.2-sol (phase2-reviewer: architecture-layering)
Review provenance
Source: reviewer 1: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 5: grok-4.7 (standing in for gpt-6.2-sol) (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
normalbygpt-6.2-sol(effort low) — The diff is broad and changes how bindings report and recover from paid-output failures, but it does not change how funds are selected, signed, or moved. - Phase 1 reviewers: not run (skipped for throughput: 17 PRs queued, above the 10 limit)
- New since the last final review (
1ca9633b): 1 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 1 confirmed - Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-sol— general (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— rust-quality (completed, effort high); agentphase2-reviewer,grok-4.7(standing in forgpt-6.2-sol) — security-auditor (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
Several findings on this PR share an underlying cause (the review's "pattern" section): The no-retry signal can still be lost after the guard; Profile refreshes and drafts share the same state; A successful native return does not prove submission. When you fix the findings below, fix the cause, not only the reported case. The review suggests (redesign the component): Finish the Android paid-call handback redesign as one path from Rust’s submission outcome to the caller’s retry decision, rather than adding another guard around an individual decoder. Reuse the prepared Rust error and the shared retry check, but make sure decoding, failure return, and cleanup cannot replace that error with a classless one under heap pressure. If a flow cannot use that path in this PR, leave its new handback guarantee out and track it in #6009 without reopening the existing deferrals. If that decision is not yours to make, say so to the PR's author or maintainer.
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/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/identity/IdentityRegistration.kt`:
- [BLOCKING] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/identity/IdentityRegistration.kt:334-339: Android can lose the no-retry signal after a DashPay payment or voucher is funded
Impact: An Android caller claiming a funded invitation, reclaiming a voucher, or resuming registration under heap pressure can receive a bare `OutOfMemoryError` after registration succeeds, leaving the native result handle in the registry.
The caller can lose both the registered identity ID and Rust’s no-retry signal. The inline decoder fixes the earlier pre-guard allocation, but the new `finally` can replace the prepared error after the guard selects it. On a valid invitation claim, JNI registers the identity, returns a result with a temporary managed-identity handle, and disarms its own cleanup guard. If Kotlin’s `identityId.copyOf()` fails, `readingPaidOutput` can throw the prepared `MAYBE_SENT` error. The `finally` then calls the stored `(Long) -> Unit` destructor, which boxes the handle for `Function1.invoke`. The shared registry counter advances across ordinary wallet operations, so the handle can be outside the boxed `Long` cache. If boxing fails on the same exhausted heap, that error replaces the classified one and JNI never removes the handle. Resume and reclaim use the same helper. Call the primitive JNI destructor directly or use a test seam whose method takes a primitive `Long`.
In `packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManagerWalletDrain.kt`:
- [BLOCKING] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManagerWalletDrain.kt:117-131: A funded Android drain can still return a bare out-of-memory error
Impact: A caller running Max drain on a supported network can lose both the outcome and Rust’s no-retry signal if Android runs out of heap after the wallet funds its asset lock.
The SDK can throw an unclassified `OutOfMemoryError` even after recovering Rust’s prepared error. A caller with spendable funds and a stored operation ID can complete native funding and receive the packed result, then run out of heap when `WalletDrainOutcome.decode` allocates the buffer, outpoint, or result. The new guard converts that failure to a classified `DashSdkError`, but the catch immediately allocates another `WalletDrainOutcome` through `unresolved(e)`. The `finally` also rebuilds the active-call key with `joinToString` and per-byte formatting; if that allocation fails, it overrides the outcome and leaves the active entry behind. The durable status read still works once memory is available, but it does not preserve the immediate no-retry signal. Prepare a pending outcome carrying Rust’s fallback before dispatch and retain an allocation-free cleanup token. This is separate from preserving the outpoint when JNI cannot allocate the initial result array.
_Confirmed by an independent pass: An Android caller with spendable funds can call `shieldedFundFromWalletDrain` with a saved operation ID and receive the packed JNI result after funding succeeds, then hit the app’s heap limit while Kotlin constructs the outcome. Even when the new guard recovers Rust’s prepared `MaybeSent` error, the catch allocates a fresh `WalletDrainOutcome` and can throw a bare `OutOfMemoryError` instead, leaving the caller without the immediate no-retry signal. The `finally` can also run out of memory while rebuilding the active-call key, overriding the return and leaving the entry behind._
In `packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/documents/DocumentTransactions.kt`:
- [SUGGESTION] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/documents/DocumentTransactions.kt:235-237: An erase declined before submission can be reported as possibly sent
Impact: An Android caller whose erase stops at preflight can receive a non-retryable `MAYBE_SENT` error if Kotlin runs out of memory decoding the refusal.
An erase that never reached submission can leave the caller waiting to reconcile it. JNI still handles string allocation correctly: it checks Rust’s `NotSubmitted` tag and uses an ordinary error if it cannot hand back that string. But if the string does arrive, the new guard treats both outcomes as paid. For example, Rust returns `NotSubmitted` when the history read is unavailable, and `fromJson` allocates its parse tree before reading the tag. An OOM there becomes `MAYBE_SENT`. The same guard also translates `DocumentEraseResultUnreadableException` rather than letting it escape the public call as described in the PR. Carry Rust’s submission verdict separately from the fallible payload decode, and preserve the dedicated exception if it remains part of the public contract.
In `packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt`:
- [SUGGESTION] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt:3704-3710: Accepting a contact can report a possible payment when no reply was sent
Impact: An Android caller accepting a contact with an existing reciprocal request can receive `MAYBE_SENT` if Kotlin cannot allocate the contact wrapper, even though this accept sent no transition and paid no fee.
An unreadable result can make an unpaid contact adoption look like a possible payment. In `accept_contact_request_replying_with`, Rust skips sending when the reciprocal request already exists and adopts it instead. The C and JNI accept functions return the same kind of established-contact handle for both paths, so the new `owningPaidHandle` call requests the paid handback class whenever wrapper construction fails. Keep cleanup on both paths, but carry Rust’s sent-versus-adopted outcome with the handle so Kotlin can report the output failure without inferring that a reply went out.
In `packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentWithPriceScreen.kt`:
- [SUGGESTION] packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentWithPriceScreen.kt:369-377: An unconfirmed document transaction leaves the form spinning and disables Back
Impact: An example-app user whose document purchase, price update, or erase cannot be confirmed sees a loading state that never clears and cannot leave using the toolbar Back button.
After the warning is dismissed, the form still looks as if the transaction is running even though the submit coroutine has finished. The new `held` branch skips `end()`, so both document screens keep `isSubmitting = true`. That flag controls the spinner, toolbar Back, and document ID field; on Document Actions it also disables the other write controls. Keep the no-resubmit hold separate from the in-flight flag, as the token scaffold does, so completion stops the spinner and restores navigation while submissions remain held.
In `packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt`:
- [SUGGESTION] packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt:247-253: A late Cancel reload can turn a reopened profile draft into an update
Impact: An example-app user who cancels and immediately reopens a create draft can end up paying to update a newly synced profile without first seeing its existing values.
A draft opened against a checked cache miss can silently change from Create to Save. The new Cancel reload suspends while reading the wallet, but Edit remains available on the previous checked answer. If the user reopens the editor before the read returns, the draft starts with `editSnapshot == null`. A profile synced from another device can then arrive in the Cancel read, and `loadProfile()` applies it unconditionally. That sets `profileExists` without refreshing the draft, so Save skips the pre-create reread that would show the newly found profile and ask the user to reapply their edits. Keep the Cancel reload, but apply its answer only if the editor has not reopened, or disable reopening while the read is pending.
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.
- Some example-app payment forms still allow resubmission after an unconfirmed payment — Credit transfer, withdrawal, and name registration still show a generic error and re-enable submission without checking the wallet’s delivery class. If the first transition landed but its confirmation was lost, a user can submit another paid transition. These form handlers are unchanged by this PR.
- Follow-up: Use a follow-up PR under #6009 to route the remaining payment forms through the shared delivery-class check and keep a hold after an uncertain submission.
| private inline fun <T> readingRegisteredIdentity(handle: Long, read: () -> T): T = | ||
| try { | ||
| readingPaidOutput("the registered identity", handbackFailure, read) | ||
| } finally { | ||
| if (handle != 0L) destroyManagedIdentity(handle) | ||
| } |
There was a problem hiding this comment.
🔴 Blocking: Android can lose the no-retry signal after a DashPay payment or voucher is funded
Impact: An Android caller claiming a funded invitation, reclaiming a voucher, or resuming registration under heap pressure can receive a bare OutOfMemoryError after registration succeeds, leaving the native result handle in the registry.
The caller can lose both the registered identity ID and Rust’s no-retry signal. The inline decoder fixes the earlier pre-guard allocation, but the new finally can replace the prepared error after the guard selects it. On a valid invitation claim, JNI registers the identity, returns a result with a temporary managed-identity handle, and disarms its own cleanup guard. If Kotlin’s identityId.copyOf() fails, readingPaidOutput can throw the prepared MAYBE_SENT error. The finally then calls the stored (Long) -> Unit destructor, which boxes the handle for Function1.invoke. The shared registry counter advances across ordinary wallet operations, so the handle can be outside the boxed Long cache. If boxing fails on the same exhausted heap, that error replaces the classified one and JNI never removes the handle. Resume and reclaim use the same helper. Call the primitive JNI destructor directly or use a test seam whose method takes a primitive Long.
source: gpt-6.2-sol (phase2-reviewer: rust-quality)
| // The erase already went through: an outcome Kotlin cannot read | ||
| // carries Rust's handback class. | ||
| readingPaidOutput("the erase outcome") { DocumentEraseOutcome.fromJson(json) } |
There was a problem hiding this comment.
🟡 Suggestion: An erase declined before submission can be reported as possibly sent
Impact: An Android caller whose erase stops at preflight can receive a non-retryable MAYBE_SENT error if Kotlin runs out of memory decoding the refusal.
An erase that never reached submission can leave the caller waiting to reconcile it. JNI still handles string allocation correctly: it checks Rust’s NotSubmitted tag and uses an ordinary error if it cannot hand back that string. But if the string does arrive, the new guard treats both outcomes as paid. For example, Rust returns NotSubmitted when the history read is unavailable, and fromJson allocates its parse tree before reading the tag. An OOM there becomes MAYBE_SENT. The same guard also translates DocumentEraseResultUnreadableException rather than letting it escape the public call as described in the PR. Carry Rust’s submission verdict separately from the fallible payload decode, and preserve the dedicated exception if it remains part of the public contract.
source: gpt-6.2-sol (phase2-reviewer: general, ffi-engineer, rust-quality)
| // The reply already went out: an owner Kotlin cannot build releases | ||
| // the handle and carries Rust's handback class. | ||
| owningPaidHandle( | ||
| "the established contact", | ||
| handle, | ||
| TokensNative::establishedContactDestroy, | ||
| own = ::EstablishedContactRef, |
There was a problem hiding this comment.
🟡 Suggestion: Accepting a contact can report a possible payment when no reply was sent
Impact: An Android caller accepting a contact with an existing reciprocal request can receive MAYBE_SENT if Kotlin cannot allocate the contact wrapper, even though this accept sent no transition and paid no fee.
An unreadable result can make an unpaid contact adoption look like a possible payment. In accept_contact_request_replying_with, Rust skips sending when the reciprocal request already exists and adopts it instead. The C and JNI accept functions return the same kind of established-contact handle for both paths, so the new owningPaidHandle call requests the paid handback class whenever wrapper construction fails. Keep cleanup on both paths, but carry Rust’s sent-versus-adopted outcome with the handle so Kotlin can report the output failure without inferring that a reply went out.
source: gpt-6.2-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality); grok-4.7 (phase2-reviewer: security-auditor)
| } catch (e: Exception) { | ||
| fail(e.message ?: "Transaction failed") | ||
| if (paymentMayHaveGoneThrough(e)) { | ||
| held = true | ||
| fail(mayHaveGoneThroughMessage(e)) | ||
| } else { | ||
| fail(e.message ?: "Transaction failed") | ||
| } | ||
| } finally { | ||
| end() | ||
| if (!held) end() |
There was a problem hiding this comment.
🟡 Suggestion: An unconfirmed document transaction leaves the form spinning and disables Back
Impact: An example-app user whose document purchase, price update, or erase cannot be confirmed sees a loading state that never clears and cannot leave using the toolbar Back button.
After the warning is dismissed, the form still looks as if the transaction is running even though the submit coroutine has finished. The new held branch skips end(), so both document screens keep isSubmitting = true. That flag controls the spinner, toolbar Back, and document ID field; on Document Actions it also disables the other write controls. Keep the no-resubmit hold separate from the in-flight flag, as the token scaffold does, so completion stops the spinner and restores navigation while submissions remain held.
source: gpt-6.2-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality); grok-4.7 (phase2-reviewer: security-auditor)
| // Answers are not applied while editing, so | ||
| // read the wallet again now: a profile that | ||
| // could not be read before a create may be | ||
| // readable, or found, since. Read only. | ||
| scope.launch { loadProfile() } | ||
| } | ||
| isEditing = !isEditing |
There was a problem hiding this comment.
🟡 Suggestion: A late Cancel reload can turn a reopened profile draft into an update
Impact: An example-app user who cancels and immediately reopens a create draft can end up paying to update a newly synced profile without first seeing its existing values.
A draft opened against a checked cache miss can silently change from Create to Save. The new Cancel reload suspends while reading the wallet, but Edit remains available on the previous checked answer. If the user reopens the editor before the read returns, the draft starts with editSnapshot == null. A profile synced from another device can then arrive in the Cancel read, and loadProfile() applies it unconditionally. That sets profileExists without refreshing the draft, so Save skips the pre-create reread that would show the newly found profile and ask the user to reapply their edits. Keep the Cancel reload, but apply its answer only if the editor has not reopened, or disable reopening while the read is pending.
source: gpt-6.2-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality); grok-4.7 (phase2-reviewer: security-auditor)
| internal fun <T> readingPaidOutput( | ||
| what: String, | ||
| failure: (String, Throwable) -> DashSdkError = ::handbackFailure, | ||
| read: () -> T, | ||
| ): T = | ||
| try { | ||
| read() | ||
| } catch (e: CancellationException) { | ||
| throw e | ||
| } catch (e: DashSdkError) { | ||
| if (e.native != null) throw e | ||
| throw failure(what, e) | ||
| } catch (e: Exception) { | ||
| throw failure(what, e) | ||
| } catch (e: OutOfMemoryError) { | ||
| throw failure(what, e) |
There was a problem hiding this comment.
Still applies (re-reviewed at 2c8824a5): Inlining fixes the DashPay payment and invitation decoders, and the registration paths no longer allocate an owner before reading the result. The remaining allocation is not the generic teardown gate: the new registration finally boxes the handle for destroyManagedIdentity, which can mask the prepared error before JNI gets to release the handle.
| try { | ||
| build(e) | ||
| } catch (oom: OutOfMemoryError) { | ||
| preparedFallback(e) ?: throw oom | ||
| } |
There was a problem hiding this comment.
Resolved (re-reviewed at 2c8824a5): Direct Purchase now reads delivery before checking the error type, so Rust’s prepared generic MAYBE_SENT error produces the unconfirmed-purchase notice instead of re-enabling Buy.
| } catch (e: Exception) { | ||
| // Unknown whether a profile exists: | ||
| // never create over it. | ||
| profileUnreadable = true | ||
| profileChecked = false | ||
| saveError = PROFILE_UNREADABLE_MESSAGE + | ||
| " Your profile was not created." | ||
| return@launch |
There was a problem hiding this comment.
Resolved (re-reviewed at 2c8824a5): Cancel now performs the read needed to recover from a failed pre-create check without leaving Your Profile. The read can still finish after Edit is reopened on a previously checked miss; that is a separate race in the new reload.
| /// Every payment-delivery class at the index of its discriminant, the order | ||
| /// of the table [`prepared_fallbacks`] hands to Kotlin. | ||
| const DELIVERIES: [PlatformWalletFFIPaymentDelivery; 5] = [ | ||
| PlatformWalletFFIPaymentDelivery::None, | ||
| PlatformWalletFFIPaymentDelivery::NotSent, | ||
| PlatformWalletFFIPaymentDelivery::MaybeSent, | ||
| PlatformWalletFFIPaymentDelivery::LockHeld, | ||
| PlatformWalletFFIPaymentDelivery::Unknown, | ||
| ]; | ||
|
|
||
| /// The slot of `delivery` in [`DELIVERIES`]. Exhaustive, so a class added to | ||
| /// the FFI fails the build here until it has a slot in the table. | ||
| const fn delivery_slot(delivery: PlatformWalletFFIPaymentDelivery) -> usize { | ||
| match delivery { | ||
| PlatformWalletFFIPaymentDelivery::None => 0, | ||
| PlatformWalletFFIPaymentDelivery::NotSent => 1, | ||
| PlatformWalletFFIPaymentDelivery::MaybeSent => 2, | ||
| PlatformWalletFFIPaymentDelivery::LockHeld => 3, | ||
| PlatformWalletFFIPaymentDelivery::Unknown => 4, | ||
| } | ||
| } | ||
|
|
||
| // Each class sits at its slot and its discriminant, the index Kotlin reads. | ||
| const _: () = { | ||
| let mut index = 0; | ||
| while index < DELIVERIES.len() { | ||
| assert!(delivery_slot(DELIVERIES[index]) == index); | ||
| assert!(DELIVERIES[index] as usize == index); | ||
| index += 1; | ||
| } | ||
| }; |
There was a problem hiding this comment.
Resolved (re-reviewed at 2c8824a5): Your macro now builds the table and an exhaustive match from the same variant list, and the const assertion checks each index against its discriminant. Adding a class without a slot now fails compilation.
Issue being fixed or feature implemented
Part of #6009. After a paid call succeeds (a state transition or Core transaction was broadcast or applied), a failure to hand its output back to the host — encoding its JSON, an interior NUL, a JVM allocation, a NULL output pointer, an output the host cannot decode — must carry Rust's handback class (
MaybeSent, not retryable). Before this PR, such failures came back unclassified from the FFI and JNI exports, so they read as a refusal before any payment. The Swift and Kotlin SDKs also assigned the class themselves in their own guards (readingPaidOutput,payment: .maybeSent). thepastaclaw raised this on #6380 (#6380 (comment)).Stacked on #6381 (Kotlin), which is stacked on #6380 (Swift).
What was done?
The rule this PR applies: every failure after a paid call succeeded carries the class from
handback_failure_payment_class, on every layer, and no host chooses it.platform-wallet-ffi
paid_output/paid_output_c_stringmark such a failure throughPlatformWalletFFIResult::handback_failure. Applied at:platform_wallet_ffi_handback_failure(message): a host builds the error for an output it finds missing or unreadable here, so it carries Rust's class. The code is fixed (ErrorDeserialization): a host-chosen code could beSuccessor a value outside the enum.asset_lock_build_transactionconverts the derivation path before it writes any out-param, so an error no longer leaks the transaction bytes.Swift SDK
PlatformPaymentClass.handbackFailurereads the class from that export.readingPaidOutputand the 31 guards that assigned.maybeSentafter a reported success now use it.PlatformPaymentClass.maybeSentstays as a value that describes the class.unified-sdk-jni
throw_handback_failure,paid_jstringandpaid_byte_arrayreplace the plain code-99 exceptions, bare JVM allocation errors and silentnulls that followed a paid call. Applied at:HandbackNative.throwFailure(message).Kotlin SDK
readingPaidOutput(← Swift) re-classes a failure that Kotlin raises itself while reading a paid output. It callsHandbackNative, and an error mapped from a native result keeps its own class. Applied at:Second round (thepastaclaw on
89db6ab812, fixed in2e402893fe):JNI_OnLoadand rethrown when a fresh exception cannot be built for a result whose class is notNotSent(throw_pwffi_result), instead of a classlessRuntimeException; a failed prepare is logged.NotSubmittedoutcome the JVM cannot hold is an ordinary output error.take_unpaid_wallet_json(no payment class).paid_changesetrefuses a count with no rows; Kotlin reads only a blob holding exactly its declared rows.Third round (thepastaclaw on
223452aa42, fixed in84a61a79c2and235acd6654). The low-memory fallback is Rust's, not Kotlin's:NativeLoader.preparedHandbackFailure,preparedFallbacks: a table indexed by the payment class, filled fromsupport::fallback_for).NativeLoader.ensureLoadedmaps them intoDashSdkErrorbefore any paid call can dispatch.MAYBE_SENT) is removed. When mapping a native error runs out of memory,classedOrPreparedreturns Rust's prepared error for the class (DashSDKException.nativeDelivery).delivery,heldAssetLock,consensusErrorandisRetryablewalk the cause chain without allocating. A shared prepared error is never given suppressed errors.readingPaidOutputalso catchesOutOfMemoryError.Fourth round (thepastaclaw on
1ca9633bb4, fixed ina507e334be,b413be62b2,7049249c53andf03045853b):readingPaidOutputisinline.owningPaidHandlebuilds the Kotlin owner of a paid handle inside the guard and releases the raw handle if that fails. It is used by the six DashPay contact request and accept calls.finallyaround the guard.opReturningCompletedResultno longer allocates a wrapper after success.delivery_table!builds the fallback table and its coverage check from one list, so a new payment class does not compile without a slot.paymentMayHaveGoneThrough, reads Rust'sdeliveryfirst and keeps typed checks only for errors with no class. It is used by Direct Purchase, Update Key Limits, Create Decision Proposal, Give Up Name, Update Contract, and the shared submit paths of document transactions (erase included), token actions and the DashPay send sheet, which now hold the form after a possible send.Longresult through the generic teardown gate, and the coroutine resume afterwithContext.Left as is, on purpose:
DocumentEraseResultUnreadable(Swift) andDocumentEraseResultUnreadableException(Kotlin) remain their own public error types. They tell the caller to read history before retrying. Giving them a class means changing those types, which is follow-up work tracked in #6009.How Has This Been Tested?
f03045853b(fourth round)::sdk:testDebugUnitTest :app:testDebugUnitTest :app:assembleDebug :sdk:compileDebugAndroidTestKotlinbuild and pass;cargo test -p rs-unified-sdk-jni --lib160 passed, fmt and clippy clean. New tests:PaidOutputTest.shouldAllocateNothingToReadAPaidOutputandshouldReleaseAPaidHandleWhoseOwnerCannotBeBuiltPaymentMayHaveGoneThroughTest(the prepared fallback blocks a resubmit, class before type, Direct Purchase, document submit, token actions), plus the prepared fallback in the existing decision proposal, give up name, key limits and DashPay send testsOwnProfileCheckGateTest: a readable answer after an unreadable oneFfiSmokeTest: slot 0 and the table size (instrumented; runs in CI)1ca9633bb4(third round): the same Kotlin and Rust gates passed, and CI ran the instrumented tests on the x86_64 emulator,FfiSmokeTest.loadingMapsRustsPreparedFallbacksincluded. New tests:DashSdkErrorTest.shouldFallBackToRustsPreparedErrorForTheClassWhenTheMappedOneCannotBeAllocatedandshouldReadTheClassOfAFailedPaymentWithoutAllocating,PaidOutputTest.shouldClassAnOutOfMemoryErrorWhileReadingAPaidOutput.2e402893fe(with feat(kotlin-sdk)!: read Rust's payment class on every wallet error #6381 merged in):cargo test -p platform-wallet-ffi -p rs-unified-sdk-jni1053 passed, clippy clean;swift test1341 passed; SwiftExampleApp 726 passed, 0 failed, 15 skipped;:sdk:testDebugUnitTest984 passed (newAddressChangesetDecodingTest);:app:compileDebugKotlinbuilds. New Rust test:should_refuse_a_profile_text_field_holding_a_nul_instead_of_dropping_it.cargo test -p platform-wallet-ffi --all-features: 846 passed. New tests:paid_outputandpaid_output_c_stringwrite_document_jsonin both proposal modulescargo test -p rs-unified-sdk-jni --all-features: 158 passed. clippy is clean on both crates.swift test: 1324 passed. New test:testShouldReadTheHandbackClassFromRust.:sdk:testDebugUnitTest: 979 passed. New tests:PaidOutputTest:app:compileDebugKotlinbuilds.FfiSmokeTest.handbackFailureCarriesTheWalletsClasswas added. It is instrumented and was not run locally.Breaking Changes
C:
platform_wallet_ffi_handback_failuretakes onlymessage; thecodeparameter is gone and the result's code is alwaysErrorDeserialization(Swift updated).C and Swift:
managed_identity_get_dashpay_profile,platform_wallet_get_dashpay_profileandplatform_wallet_get_contact_profilereturnErrorUtf8Conversionfor a profile whose text field holds a NUL, where they used to hand that field over as absent.Kotlin: when identity resume, invitation reclaim or claim, the DashPay payment, the invitation link, DPNS trade or give up, the token config update, the shielded identity create or the private document entry return an output that Kotlin cannot read, they now throw a
DashSdkErrorcarryingdelivery == MAYBE_SENT. They used to throw anIllegalStateException, a JSON exception or a classlessSerializationError. The JNI exports listed above throw aDashSDKExceptionwith the handback class where they used to returnnullor throw code 99.Kotlin: when mapping a payment error runs out of memory, the fallback is Rust's prepared handback failure (
ErrorSerialization, aPlatformWallet.Genericwithdelivery == MAYBE_SENT), not a Kotlin-builtTransactionBroadcastUnconfirmed. Readdelivery, not the error type. Decision and multiple choice proposal create, entering a choice, document erase and the wallet drain outcome now throw aDashSdkErrorwith the handback class when their output cannot be read, where they used to throw an unclassified exception.Checklist:
structure.rs, regeneratedgrovedb-structure.json, and checked the structure viewer link posted on this pull request🤖 Generated with Claude Code
PR Hygiene ·
2c8824a/self-reviewedkotlin-sdk(packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentActionsScreen.kt,packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentWithPriceScreen.kt,packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/PrivateDocumentEntryCreateScreen.ktand 61 more) — HashEngineeringrs-platform-wallet-ffi(packages/rs-platform-wallet-ffi/src/asset_lock/build.rs,packages/rs-platform-wallet-ffi/src/contract_fee_claim.rs,packages/rs-platform-wallet-ffi/src/contract_user_moderation.rsand 9 more) — HashEngineering or ZocoLini or llbartekllswift-sdk— you own itWhen every merge requirement is met, the
PR Hygienecheck passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.