Skip to content

feat(platform-wallet)!: top up an identity the wallet does not manage from Platform addresses - #5860

Merged
romchornyi merged 46 commits into
v5.2-devfrom
feat/platform-wallet-external-identity-top-up
Nov 20, 2026
Merged

romchornyi merged 46 commits into
v5.2-devfrom
feat/platform-wallet-external-identity-top-up

Conversation

@romchornyi

@romchornyi romchornyi commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Issue being fixed or feature implemented

A wallet cannot pay credits from its Platform addresses to someone else's identity. IdentityWallet::top_up_from_addresses (and the PlatformWallet composite over it) reads the identity from the wallet's identity manager and returns IdentityNotFound for any identity the wallet does not manage. Dash Wallet iOS needs this for Platform → Identity ID sends in its new Send flow (dashpay/dashwallet-ios#1358); today that pair fails before anything is submitted.

What was done?

  • IdentityWallet::top_up_external_from_addresses — fetches the identity from Platform (Identity::fetch) and runs the same IdentityTopUpFromAddresses transition with the given inputs and address signer. It never adds the identity to the identity manager and persists nothing about it. An identity Platform does not know is IdentityNotFound, with nothing signed or broadcast.
  • PlatformWallet::top_up_external_identity_from_addresses — the composite: reconciles the spent Platform addresses through the same reconcile_address_infos path as the managed top-up.
  • The build / broadcast / error mapping now lives in one private helper used by both the managed and the external path.
  • FFI: platform_wallet_top_up_external_identity_from_addresses_with_signer, the same shape as the managed export; the input marshalling is shared between the two exports.
  • Swift: ManagedPlatformWallet.topUpExternalIdentityFromAddresses(identityId:inputs:addressSigner:) async throws -> UInt64 returns the identity's new balance and writes nothing to SwiftData. The managed and external wrappers share one marshalling helper.
  • docs/sdk/sdk-parity-manifest.json: new capability identity.external_top_up_from_addresses, Kotlin recorded as unsupported (PARITY_SUMMARY.md regenerated).

How Has This Been Tested?

  • cargo test -p platform-wallet -p platform-wallet-ffi — all pass. New Rust tests:
    • an unmanaged identity's transition is built, signed once and broadcast once, and the identity manager's identities are unchanged afterwards (should_submit_a_top_up_for_an_identity_the_wallet_does_not_manage); an unknown identity returns IdentityNotFound with 0 signatures and 0 broadcasts;
    • confirmation binding (nonce_binding_tests): a snapshot behind the submitted nonces, and used nonces without a higher identity balance, are unconfirmed; used nonces with growth stand; growth is measured against Platform's balance, not a stale cache (should_keep_growth_over_platforms_balance_that_a_stale_cache_hides);
    • the managed route reads the identity's balance from Platform before signing (should_read_the_managed_identitys_balance_from_platform_before_signing);
    • empty funding rows are InvalidParameter before any lookup, on both routes (should_report_empty_inputs_as_an_invalid_parameter_on_both_routes);
    • lifecycle: a removed or re-created wallet is refused on both routes; a removal waits only for the send, not for signing, and a removal during signing drops the signed bytes with 0 broadcasts and 0 waits (should_refuse_a_top_up_from_a_wallet_no_longer_current_on_both_routes, should_hold_a_wallets_removal_until_its_top_up_is_sent, should_complete_a_removal_while_the_top_up_signer_is_pending);
    • an oversized top-up is refused as not sent before anything is broadcast, on both routes (should_refuse_an_oversized_top_up_as_not_sent_on_both_routes);
    • a nonce refusal of the first broadcast is not reported as safe to retry (should_not_report_a_nonce_refusal_of_the_first_broadcast_as_safe_to_retry);
    • every dispatch is sent with the caller's settings (should_send_each_dispatch_with_the_callers_settings);
    • a confirmed result reconciles the spent addresses through the top_up_identity_with seam (should_reconcile_the_spent_addresses_of_a_confirmed_top_up).
  • FFI tests: null pointers, zero inputs, a bad address type, not-found through a real handle, the registry released while the host signs.
  • cargo fmt --all -- --check clean; cargo clippy -p platform-wallet-ffi --all-targets -- -D warnings clean. cargo clippy -p platform-wallet --all-targets -- -D warnings reports no lint in this PR's changes; it fails only on dead-code warnings already present on the base in files this PR does not touch (asset_lock/operation.rs, asset_lock/sync/tracking.rs, and dash-sdk's verify_response_metadata_as_of).
  • Swift: ExternalIdentityTopUpTests 6/6 (marshalling, 32-byte id guard, error mapping). The full SwiftDashSDKTests target ran 942 tests with 2 failures in KeychainSignerAdditionalSigningKeysTests (the keychain write returns nil on the simulator); they fail the same way without this change.
  • Not covered: an unconfirmed top-up (20) is shown as pending only while TopUpIdentityView stays open; leaving and re-entering the screen shows the form again. A durable pending state is tracked in Keep an unconfirmed identity top-up from Platform addresses pending across screen re-entry #6000.
  • A wallet removed or re-created between the liveness check and the managed sign step's read is WalletRemovedBeforeSend (98) with nothing signed (should_refuse_the_managed_sign_step_of_a_re_created_wallet_as_not_sent).
  • Not covered: a confirmed result coming from the real SDK. The mock SDK verifies the result proof for real and there are no recorded vectors for this transition, so the SDK-driven tests stop at "built, signed, broadcast once"; the reconciliation of a confirmed result is covered through the top_up_identity_with seam instead. It will be exercised by a testnet send from the wallet.

Breaking Changes

  • platform_wallet_top_up_from_addresses_with_signer and PlatformWallet::top_up_from_addresses no longer saturate when the funding rows naming one address sum past u64::MAX: the sum is refused with PlatformWalletError::InvalidParameter (FFI ErrorInvalidParameter, 2) before anything is signed or sent. Before, the FFI wrapper saturated the sum silently and topped up with u64::MAX credits for that address.

  • An empty list of funding rows still returns FFI ErrorInvalidParameter (2), but the check moved from the FFI wrapper ("inputs_count is zero") into the library (funding_inputs), still before any lookup or network I/O on both routes. Rust callers of top_up_from_addresses now get PlatformWalletError::InvalidParameter where they got InvalidIdentityData before. Kotlin (CreditsNative.topUpFromAddresses) no longer refuses a zero-row blob in JNI with SDK code 1: the call goes to the wallet, which returns its ErrorInvalidParameter (2) after the handle and generation checks, as Swift and C get.

  • The managed top-up (top_up_from_addresses, FFI platform_wallet_top_up_from_addresses_with_signer) now reads the identity's balance from Platform before signing, as the baseline the confirmation must see the balance grow from. This adds one Platform request, and two pre-sign outcomes: a failed read is IdentityLookupFailed (80) and no balance from Platform for the identity is IdentityBalanceUnavailable (58, retryable); nothing is signed or broadcast in either case.

  • The managed top-up now also goes through the wallet's generation lifecycle gate (as the external one does): for a wallet removed or re-created since the handle was taken it returns WalletRemovedBeforeSend (FFI NotFound) before anything is sent.

  • IdentityWallet::top_up_from_addresses (reachable through PlatformWallet::identity()) is now crate-private, like the external route's identity-side method: it skipped the lifecycle gate and the address reconciliation. Rust callers use PlatformWallet::top_up_from_addresses; the FFI already did.

  • New FFI code 80 ErrorIdentityLookupFailed (PlatformWalletError::IdentityLookupFailed, Swift PlatformWalletError.identityLookupFailed, Kotlin DashSdkError.PlatformWallet.IdentityLookupFailed): the new external top-up (platform_wallet_top_up_external_identity_from_addresses_with_signer) reports a failed recipient lookup as this code, and the managed one (platform_wallet_top_up_from_addresses_with_signer) a failed read of the identity's balance before signing, with nothing signed or broadcast, so the call may be retried as it is. On the external route an identity Platform does not know stays ErrorIdentityNotFound (7). On the managed route 7 now only means the identity is not in the wallet's identity manager; since b9433b6 a missing balance from Platform is IdentityBalanceUnavailable (58). Hosts should treat 80 as "not sent", not as a possibly delivered top-up.

  • Both address top-ups (managed and external) now bind the confirmation to this top-up: the result stands only when the proof shows every input address at or past the nonce it was signed with and the identity balance above the balance read before signing. Otherwise it is reported as StateTransitionResultUnconfirmed (FFI 20, do not submit again) with nothing reconciled, where it was reported as success. The affected-state proof cannot rule out a competing transition with the same nonces plus an unrelated credit to the identity; that needs an execution-bound proof (Bind affected-state proofs to transition execution #4270). A failed wait or proof after the broadcast is also 20 now (it was 99). Other SDK errors keep their typed Sdk variant instead of InvalidIdentityData.

  • Both address top-ups no longer return 21 (ErrorAddressNonceMismatch). Any endpoint answer after a possible dispatch is now 20, a CheckTx refusal included. A connection refused while offline is also 20 ("do not resubmit"), where before some of these came back as a typed not-sent error. Hosts that retried on 21, or treat an offline failure as not sent, must treat 20 as possibly delivered and reconcile instead.

  • A wallet removal no longer waits for a top-up's signing to finish: signing runs outside the lifecycle gate, and the generation is rechecked before the send. A removal during signing returns WalletRemovedBeforeSend (FFI NotFound, 98) with nothing sent; a removal after the send starts still waits until it returns. Hosts should treat 58, 80 and 98 from these two calls as not sent.

  • PlatformWallet::top_up_from_addresses takes a new type parameter I (the funding rows, any IntoIterator<Item = (PlatformAddress, Credits)>), as does the new external method. This is a source break for callers that name the type parameters explicitly (turbofish); callers relying on inference are unaffected.

  • A panic inside either export returns 20 instead of unwinding across the C boundary — on unwinding targets only. The iOS profiles (dev-ios, release-ios) build with panic = "abort", so on iOS a panic still aborts the process; that workspace-wide profile is tracked in FFI panic guards cannot catch on iOS: the iOS profiles use panic = abort #5920.

Checklist:

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

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

PR Hygiene · 4549645

  • Bots — thepastaclaw ✓
  • Self-review — posted; again after any push
  • Build running
  • Approvals
    • sdk-parity — you own it
    • kotlin-sdk (packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/credits/TopUpIdentityScreen.kt, packages/kotlin-sdk/PARITY_SUMMARY.md, packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt and 2 more) — approved by HashEngineering
    • rs-platform-wallet-ffi (packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md, packages/rs-platform-wallet-ffi/src/error.rs, packages/rs-platform-wallet-ffi/src/identity_top_up.rs and 3 more) — approved by HashEngineering
    • rs-platform-wallet (packages/rs-platform-wallet/src/broadcast_outcome.rs, packages/rs-platform-wallet/src/error.rs, packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs and 5 more) — approved by HashEngineering
    • swift-sdk — you own it

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

Summary by CodeRabbit

  • New Features
    • Added support for topping up identities not managed by the wallet using address-based funding.
    • Address-based top-ups now accept repeated addresses and combine their amounts.
  • Bug Fixes
    • Identity lookup failures now return a specific, retryable error instead of a generic error.
    • Invalid or overflowing funding inputs are rejected, and failed lookups do not submit a top-up.

romchornyi and others added 2 commits November 11, 2026 13:18
…from Platform addresses

top_up_from_addresses reads the identity from the wallet's identity manager and
returns IdentityNotFound for any other identity, so a wallet could not pay
credits from its Platform addresses to someone else's identity.

- IdentityWallet::top_up_external_from_addresses fetches the identity from
  Platform and runs the same transition; it never adds the identity to the
  manager or persists anything about it. An unknown identity is IdentityNotFound
  with nothing signed or broadcast.
- PlatformWallet::top_up_external_identity_from_addresses reconciles the spent
  addresses through the same path as the managed composite.
- FFI: platform_wallet_top_up_external_identity_from_addresses_with_signer,
  sharing the input marshalling with the managed export.
- The build/broadcast/error mapping is shared by both paths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Swift wrapper over platform_wallet_top_up_external_identity_from_addresses_with_signer:
tops up an identity the wallet does not manage from the wallet's Platform
addresses and returns the identity's new balance. It writes nothing to
SwiftData. The managed and external wrappers share one marshalling helper.
The parity manifest records the capability as unsupported in Kotlin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
Walkthrough

The wallet now supports address-funded top-ups for identities it does not manage. The FFI and Swift SDK expose the operation. Native error code 77 identifies Platform identity lookup failures, with typed error mappings and tests in Swift and Kotlin.

Changes: External identity top-up

Layer / File(s) Summary
Wallet top-up and lifecycle
packages/rs-platform-wallet/src/error.rs, packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs, packages/rs-platform-wallet/src/wallet/platform_wallet.rs, packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs
Managed top-ups now accept funding rows. The wallet aggregates duplicate addresses with checked addition. External top-ups fetch an unmanaged identity, submit the transaction, and reconcile confirmed address information without adding the identity to the manager.
FFI entry point and error mapping
packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md, packages/rs-platform-wallet-ffi/src/error.rs, packages/rs-platform-wallet-ffi/src/identity_top_up.rs, packages/rs-platform-wallet-ffi/src/identity_top_up/*
The FFI adds an external-identity top-up export and maps lookup failures to code 77. Tests cover input validation, missing identities, and registry access while signing is pending.
SDK wrappers, typed errors, and parity
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/*, packages/swift-sdk/SwiftTests/SwiftDashSDKTests/*, packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt, packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt, docs/sdk/sdk-parity-manifest.json, packages/kotlin-sdk/PARITY_SUMMARY.md
Swift adds the external top-up wrapper and a typed lookup error. Kotlin maps code 77 to IdentityLookupFailed. Tests and parity records document the support status.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant IdentityTopUpFFI
  participant PlatformWallet
  participant Platform
  participant AddressSigner
  Caller->>IdentityTopUpFFI: Call external identity top-up
  IdentityTopUpFFI->>PlatformWallet: Pass identity and funding rows
  PlatformWallet->>Platform: Fetch target identity
  Platform-->>PlatformWallet: Return identity or lookup result
  PlatformWallet->>AddressSigner: Sign top-up inputs
  AddressSigner-->>PlatformWallet: Return signature
  PlatformWallet->>Platform: Submit top-up
  Platform-->>PlatformWallet: Return result and address information
  PlatformWallet-->>IdentityTopUpFFI: Return balance or error
  IdentityTopUpFFI-->>Caller: Return FFI result
Loading

Possibly related PRs

  • dashpay/platform#5865: Both PRs use error code 77 in the platform-wallet FFI error mapping. This PR assigns it to IdentityLookupFailed; the related PR assigns it to ShieldedPlanChanged.

Suggested reviewers: quantumexplorer, shumkov

Merge Risk: Moderate · previous review ccf95

Topping up an external identity from Platform addresses may report success when the recipient's balance has not yet changed, so a send could be recorded without crediting the identity. Funding shortfalls also cannot be identified programmatically, and the Kotlin lookup-failure error is not marked retryable. Resolve the success-confirmation concern before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: a new capability to top up an identity that the wallet does not manage, using Platform addresses. The changeset adds the external-identity top-up path in the Rust, FFI…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title names the main change: a new capability to top up an identity that the wallet does not manage, using Platform addresses. The changeset adds the external-identity top-up path in the Rust, FFI, Swift and Kotlin layers, and the PR objectives state the same feature. The conventional-commit scope (platform-wallet) and breaking marker (!) match the breaking changes described in the PR, namely the overflow handling change and the BTreeMap-to-iterator signature change. The title is specific and concise.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions github-actions Bot added this to the v5.1.0 milestone Nov 11, 2026
@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Nov 11, 2026
@thepastaclaw

thepastaclaw commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Final review complete — no blockers (commit 4549645) · triage: critical

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Final validation — Phase 1 + Phase 2

Verified the findings against b1b7129. The external top-up retains the existing proof-verification path, but the new spending route lacks wallet-generation protection, the shared FFI decoder owns funding-amount policy, and the reused Swift helper does not explicitly pin its signer across the FFI call. This was a static review: current Rust workspace, Swift SDK, and Kotlin SDK checks pass; dedicated Rust wallet tests were skipped, and review/hygiene checks remain pending.

🔴 3 blocking | 🟡 3 suggestion(s)

1 finding(s) not shown inline (the lines are not part of this PR's diff)

🔴 Blocking: Pin the address signer across the synchronous FFI call
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:896-907

The shared helper captures addressSigner only through the earlier _ = addressSigner, then invokes Rust using the separately captured raw handle. That discard is not a lifetime fence across the subsequent call in optimized Swift. KeychainSigner registers self with passUnretained, and its deinit destroys the Rust signer handle, so a short-lived signer can leave Rust with a freed handle or callback context while lookup, signing, or confirmation is still running. Other wrappers in this same file explicitly use withExtendedLifetime for this ownership arrangement and explain why a bare discard is insufficient. Wrap the complete synchronous call and its buffer-pinning closures in withExtendedLifetime(addressSigner). This is in scope: the PR moves this implementation into a shared helper and adds the external entry point as another caller, rather than merely sitting beside the existing pattern.

source: gpt-6.1-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.1-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); reviewer 8: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 9: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 10: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 11: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 12: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.1-sol (effort low) — The production changes add a straightforward external-recipient top-up path across Rust, FFI and Swift while reusing existing signing, submission and reconciliation logic, so the substantial test coverage does not make the implementation large or intricate enough for critical.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Second Phase-2 pass: on this first full review every Phase-2 reviewer also ran a second, independent time, and the verifier weighed both sets
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort high); agent phase2-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-platform-wallet/src/wallet/platform_wallet.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/platform_wallet.rs:622-628: Fence external top-ups against wallet removal and recreation
  A retained wallet Arc or FFI handle can execute this spend after remove_wallet completes. Unlike the managed route's initial wallet-manager lookup, top_up_external_from_addresses only fetches the recipient and delegates to the SDK; neither it nor this composite checks the registered generation or participates in its lifecycle gate. Removal can also complete while recipient lookup or signing is suspended, after which the operation can still broadcast and reconcile through stale wallet state. The existing WalletGeneration contract explicitly requires network-publishing operations to exclude teardown, and the FFI removal hook does not invalidate PlatformWallet handles. Apply generation-aware protection in the Rust orchestration, covering submission and reconciliation and protecting the public identity-side route as well. Test retained handles, same-id recreation, and removal during signing; a wallet-id check before an await does not close the race.

In `packages/rs-platform-wallet-ffi/src/identity_top_up.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/identity_top_up.rs:150-161: Move funding-row normalization into the wallet library
  This helper decides that repeated funding rows are additive and that overflowing amounts are silently saturated. Those are funding-amount decisions, not representation conversion: the wallet library receives only the resulting map and cannot own or consistently expose the normalization policy to native callers. The book's “FFI and mobile SDKs hold no business logic” rule explicitly places decisions about how many in the Rust library. This PR extracts that policy and extends it to the external export, so its pre-existence on the managed route does not exempt the new shared boundary. Introduce wallet-owned row normalization used by both routes, leaving the FFI to decode address representations and forward rows. Handle overflow explicitly in that owner and add duplicate-address and overflow tests there; neither branch is currently covered by the top-up FFI tests.

In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift`:
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:896-907: Pin the address signer across the synchronous FFI call
  The shared helper captures addressSigner only through the earlier `_ = addressSigner`, then invokes Rust using the separately captured raw handle. That discard is not a lifetime fence across the subsequent call in optimized Swift. KeychainSigner registers self with passUnretained, and its deinit destroys the Rust signer handle, so a short-lived signer can leave Rust with a freed handle or callback context while lookup, signing, or confirmation is still running. Other wrappers in this same file explicitly use withExtendedLifetime for this ownership arrangement and explain why a bare discard is insufficient. Wrap the complete synchronous call and its buffer-pinning closures in withExtendedLifetime(addressSigner). This is in scope: the PR moves this implementation into a shared helper and adds the external entry point as another caller, rather than merely sitting beside the existing pattern.

In `packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs:281-288: Exercise successful external top-up reconciliation
  The present-identity fixture returns an empty, unverifiable result proof, so submitted top-ups always exit with StateTransitionResultUnconfirmed. This test discards that result and therefore establishes unchanged identity membership only on the unconfirmed path. Removing the new composite's reconciliation call, forwarding an incorrect proof height, or recording the recipient only after confirmation would leave the tests passing. Add a deterministic successful-result fixture or a narrow confirmed-submission test seam at the Rust composite boundary. Assert the returned identity balance, reconciled and persisted funding-address balances/nonces and height pin, and that the external recipient is neither added nor persisted as a managed identity. Existing reconciliation-seam tests do not cover this new route's wiring, and a future testnet send is not an automated regression test.

In `packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift`:
- [SUGGESTION] packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift:90-101: Verify the external wrapper selects the external export
  The parity manifest names this test as verification for identity.external_top_up_from_addresses, but it calls the shared topUpFromAddresses helper with a fake closure, bypassing the public external wrapper and its export selection. The code-7 test does the same. Tests that reach the public external method use malformed arguments or a null wallet handle, which cannot distinguish the managed and external exports. Consequently, changing the external wrapper to select the managed export would still pass this suite. Add a dispatch regression that distinguishes the two exports—for example, invoke the public wrapper with a mock-backed wallet and a recipient present on Platform but absent from its identity manager—and retain these shared-marshalling tests as separate coverage.

In `packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs:159-166: Preserve empty-input failures as invalid parameters
  For an existing recipient, an empty Rust input map is rejected by the SDK's fetch_inputs_with_nonce with a typed TransitionNoInputsError, but this fallback converts it into InvalidIdentityData. The FFI rejects the same caller mistake as ErrorInvalidParameter, and PlatformWalletError::InvalidParameter explicitly documents that distinction. Native callers therefore receive an identity-data failure for a malformed funding argument and lose the typed repair signal. Preserve the SDK's empty-input discriminator as InvalidParameter in this error mapping and add coverage for both top-up routes. Reuse the SDK's validation rather than adding another copy of the empty-input rule.
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.

  • External top-up leaves a managed identity's cached balance stale if called with an owned id — The API is explicitly documented at both Rust entry points as topping up an identity this wallet does not manage, and it deliberately neither reads nor writes the identity manager. Managed recipients already have a separate operation that updates their cached balance. The proposed documentation alternative is already present; using the external API outside that documented recipient contract does not establish a defect.
    • Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.

@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 11, 2026
…funding-row policy

Review fixes for the external identity top-up:
- The external composite takes the wallet generation's payment guard and
  checks the generation is current before fetching the identity, holding it
  through signing, broadcast and reconcile; a removed or recreated wallet gets
  WalletRemovedBeforeSend with nothing signed or sent.
- platform-wallet now takes the funding rows, sums repeated addresses and
  refuses an overflowing sum with InvalidParameter; the FFI only converts row
  types, for both the managed and the external export. The managed export now
  errors on overflow instead of saturating, and its empty-input check moves to
  the library.
- The SDK's TransitionNoInputsError maps to InvalidParameter on both routes.
- Swift: the shared helper pins addressSigner with withExtendedLifetime across
  the synchronous FFI call; the exports are injectable and a test through both
  public wrappers shows each calls its own export.
- A composite seam test covers a confirmed external top-up: balance returned,
  spent address reconciled and persisted at the proof height, identity manager
  unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@romchornyi

Copy link
Copy Markdown
Contributor Author

Re "Pin the address signer across the synchronous FFI call": fixed in 2271e8c — the shared helper pins addressSigner with withExtendedLifetime across the whole synchronous FFI call and its buffer pinning.

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review — Final validation — Phase 1 + Phase 2

On 2271e8c, five prior findings are fixed, with wallet-owned checked funding normalization, signer pinning, and new dispatch/reconciliation coverage. A new blocking registry-lock issue is confirmed in the external FFI export, and one prior finding remains open. Static-only verification: Rust workspace, Swift and Kotlin CI checks pass; dedicated wallet tests are skipped, and review/hygiene checks remain pending.

🔴 2 blocking

1 finding(s) not shown inline (the lines are not part of this PR's diff)

🔴 Blocking: Release the wallet registry before waiting on the host signer
packages/rs-platform-wallet-ffi/src/identity_top_up.rs:185-194

HandleStorage::with_item holds its process-global parking_lot registry read guard throughout this closure, including block_on_worker. Cloning the wallet inside the closure therefore does not release the registry during recipient lookup, foreign signer callbacks, broadcast or proof waiting. ManagedPlatformWallet.deinit synchronously calls platform_wallet_destroy, which needs this registry's write lock, so releasing even an unrelated wallet wrapper on the UI thread blocks it for the network/signing wait.

A queued destroy also prevents subsequent registry readers from proceeding. If host signing completion work reads a wallet balance, it waits behind that writer while the export waits for signing, producing a lock cycle; an asynchronously returning signer only escapes through its timeout. Clone the wallet Arc in a short with_item call, unwrap it, and invoke block_on_worker after that call has returned, as the existing DashPay exports do. Add a regression that holds signing while destroying another wrapper and reading a balance.

source: gpt-6.1-sol (phase2-reviewer: ffi-engineer)

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.1-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.1-sol (effort low) — The change is intricate across Rust, FFI and Swift and directly extends funds movement through IdentityWallet::top_up_external_from_addresses and PlatformWallet::top_up_external_identity_from_addresses, including signing, broadcasting and spent-address reconciliation.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity 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.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — ffi-engineer (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort xhigh); agent phase2-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-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs:151-158: Fence external top-ups against wallet removal and recreation
  The new composite guard protects PlatformWallet and FFI callers, but the separately public IdentityWallet entry point still bypasses it. A native caller can retain wallet.identity().clone(), await manager.remove_wallet(...), then invoke this method: it fetches the recipient and reaches SDK signing and broadcast without checking self.generation or taking its lifecycle gate. Removal can also complete while a direct call is suspended in signing, allowing the spend afterward. Same-ID recreation does not invalidate the retained SDK or external signer.

  This is the new external API, not the pre-existing managed-route gap you left unchanged. The non-reentrant gate prevents simply nesting another acquisition, but does not require leaving a public spending route unprotected. Provide a guarded public identity-side method backed by a separate internal already-guarded implementation, so the composite retains one guard through reconciliation; alternatively, make the unfenced method internal and expose only the guarded composite. Add direct identity-handle regressions for removal, recreation and suspended signing; the current lifecycle tests invoke only the composite.

In `packages/rs-platform-wallet-ffi/src/identity_top_up.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/identity_top_up.rs:185-194: Release the wallet registry before waiting on the host signer
  HandleStorage::with_item holds its process-global parking_lot registry read guard throughout this closure, including block_on_worker. Cloning the wallet inside the closure therefore does not release the registry during recipient lookup, foreign signer callbacks, broadcast or proof waiting. ManagedPlatformWallet.deinit synchronously calls platform_wallet_destroy, which needs this registry's write lock, so releasing even an unrelated wallet wrapper on the UI thread blocks it for the network/signing wait.

  A queued destroy also prevents subsequent registry readers from proceeding. If host signing completion work reads a wallet balance, it waits behind that writer while the export waits for signing, producing a lock cycle; an asynchronously returning signer only escapes through its timeout. Clone the wallet Arc in a short with_item call, unwrap it, and invoke block_on_worker after that call has returned, as the existing DashPay exports do. Add a regression that holds signing while destroying another wrapper and reading a balance.
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.

  • Fence the existing managed address-funded top-up separately — The managed top-up releases its wallet-manager lookup before submission and later updates identity state by wallet ID without lifecycle exclusion or generation comparison. Removal can interleave with submission, and same-ID recreation can receive a stale handle's confirmed balance update. This lifecycle defect exists in the review base and is separate from the newly added external API.
    • Follow-up: Create a follow-up issue or PR adding generation-aware lifecycle protection to the managed identity-side and composite routes, covering submission, identity persistence and address reconciliation.

romchornyi and others added 2 commits November 12, 2026 11:17
…on the signer

Both address top-up exports ran block_on_worker inside
PLATFORM_WALLET_STORAGE.with_item, so the registry read guard stayed held
while the host signed. A wallet handle destroy (write lock) queued behind it,
and any registry read queued behind that destroy, so a signing completion that
reads a balance could never finish.

Clone the wallet Arc in a short with_item and wait on the signer after it
returns. The regression test holds a callback signer pending, then destroys a
second wallet handle and reads a balance; both must finish before the signer
is answered, for both exports.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ted composite

Make IdentityWallet::top_up_external_from_addresses crate-private so the
only public route to topping up someone else's identity is
PlatformWallet::top_up_external_identity_from_addresses, which holds the
wallet lifecycle gate and refuses a removed or re-created wallet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@romchornyi

Copy link
Copy Markdown
Contributor Author

Registry-lock finding from the re-review (identity_top_up.rs:185): fixed in 77c2161. Both address top-up exports take the wallet out of the registry in a short with_item and wait on the signer after it returns; a regression holds a callback signer pending while destroying a second wallet handle and reading a balance, for both exports.

@github-actions

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review — Final validation — Phase 1 + Phase 2

At a982205, one blocking ownership violation remains: the shared Swift top-up helper duplicates empty-funding validation already owned by Rust. The new lifecycle regression also needs a bounded signer rendezvous. This was static verification only; current CI reports passing Rust workspace and Kotlin checks, while Swift build/tests remain pending.

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

Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.

Follow-up candidates (optional) (2)

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: Bound the lifecycle test's signer rendezvous
packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs:470

If recipient lookup or transition preparation returns an error or panics before HeldSigner::sign, the spawned task finishes without notifying this wait. Notify does not report producer termination, and the test does not inspect the top-up JoinHandle until after receiving the notification, so the regression hangs instead of reporting the preparation failure. Add a deadline to this rendezvous, or select between the notification, task completion, and a deadline.

    tokio::time::timeout(Duration::from_secs(60), signer.entered.notified())
        .await
        .expect("the top-up never reached the signer");

source: gpt-6.1-sol (phase2-reviewer: rust-quality)

🟡 Suggestion: Keep empty-funding validation in Rust
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:852-854

The extracted helper extends this Swift-side input-count rule to the new external top-up API. DPP's IdentityTopUpFromAddressesTransitionV0::validate_structure already owns the rule, the SDK's fetch_inputs_with_nonce rejects empty inputs before signing, and the shared wallet submission helper maps that typed refusal to InvalidParameter. Unlike byte-width checks needed to construct fixed-size C values, rejecting an empty collection is semantic validation. This violates the book's explicit prohibition on duplicating DPP count checks in bindings and bypasses Rust's error ordering: an empty call through a removed wallet returns WalletRemovedBeforeSend natively but invalidParameter here. Remove this guard and forward empty funding collections to Rust. Update both FFI exports to accept a null input pointer when the count is zero, and construct an empty collection without calling slice::from_raw_parts on null. Replace the Swift test requiring pre-FFI rejection with coverage that the public wrapper forwards the Rust-emitted refusal.

source: gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality, security-auditor)

Review provenance

Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 5: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); reviewer 7: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 8: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 9: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 10: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 11: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 12: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.1-sol (effort low) — This is a large, intricate change to funds movement, transaction construction, address reconciliation, signing, broadcasting, and FFI/Swift key-handling paths in IdentityWallet::top_up_external_from_addresses and its platform-wallet/FFI wrappers.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity 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 final gate: an independent Phase-2 review ran after iterative findings were reconciled
  • Code unchanged since the last final review (2271e8cd): 1 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 1 not confirmed (now follow-up candidates); 1 new suggestion(s) listed as follow-up candidates, not posted inline
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — ffi-engineer (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — ffi-engineer (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort xhigh); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify the current code and confirm that no unresolved issues remain.

No unresolved findings remain from the prior review on this head.
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.

  • Fence the pre-existing managed top-up route against wallet teardown — IdentityWallet::top_up_from_addresses releases its initial wallet-manager read before signing and submission without holding the generation lifecycle gate. A signature suspended during removal can resume and broadcast after removal completes, and subsequent local reconciliation can report WalletNotFound despite the spend. This race is present in the merge-base; the new external composite protects its own route.
    • Follow-up: Create a separate follow-up PR protecting both public managed address-top-up entry points against removal and same-ID recreation, with a regression that suspends signing during removal.

@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@romchornyi

Copy link
Copy Markdown
Contributor Author

/self-reviewed

@github-actions

Copy link
Copy Markdown
Contributor

Missing human approval. Automatic reviewer requests are paused and this PR is excluded from reviewers' queues. Merge, close, or draft another active PR by this author to free a review slot. Required human review can be satisfied without a slot; once all merge requirements are met, PR Hygiene passes.
Full checklist in the description.

@github-actions github-actions Bot added too-many-open-prs Beyond the author's 5 open PRs; waits for one to merge before a human is asked. and removed waiting-self-review Waiting for the author to post /self-reviewed labels Nov 12, 2026

@HashEngineering HashEngineering left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. Two notes, non-blocking:

  • The managed top_up_from_addresses path changes on edge cases: an overflowing sum of funding rows now returns InvalidParameter instead of saturating, and the empty-inputs error code changed. Worth a line under Breaking Changes in the PR body.
  • On the external path, a failed Identity::fetch surfaces as a generic Sdk error even though nothing was signed or broadcast yet; a dedicated not-sent classification would help hosts that treat unknown errors as "may have gone through".

The Kotlin binding will follow in a separate PR.

romchornyi and others added 2 commits November 13, 2026 08:24
…let-external-identity-top-up

# Conflicts:
#	packages/kotlin-sdk/PARITY_SUMMARY.md
…l top-up as not sent

A failed `Identity::fetch` on the external identity top-up surfaced as a
generic `Sdk` error although nothing had been signed or broadcast, which
a host treating unknown errors as "may have gone through" cannot tell
from a failure after a dispatch. It is now
`PlatformWalletError::IdentityLookupFailed`, mapped to the new FFI code
77 `ErrorIdentityLookupFailed` and mirrored in Swift and Kotlin. A missing
identity keeps `IdentityNotFound` (7). No existing code meant "refused
before anything was sent" for a Platform state transition.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added too-many-open-prs Beyond the author's 5 open PRs; waits for one to merge before a human is asked. and removed waiting-self-review Waiting for the author to post /self-reviewed labels Nov 19, 2026
HashEngineering added a commit that referenced this pull request Nov 19, 2026
…irmed outcomes

#5860 now reports a failed identity read as IdentityLookupFailed (80,
retryable, nothing sent) and an unproved result as
TransactionBroadcastUnconfirmed (20, do not resubmit), alongside
NotFound (7). The KDoc says which is which, and the test pins each
code's mapping, including that 80 is retryable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@HashEngineering HashEngineering left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed the changes since 3548f93552: the managed JNI export now leaves empty inputs to the wallet (code 2), the held-signer test fix, and the v5.2-dev merge with the regenerated parity summary. All fine.

@github-actions github-actions Bot removed the too-many-open-prs Beyond the author's 5 open PRs; waits for one to merge before a human is asked. label Nov 19, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review — Final validation — Phase 1 + Phase 2

On 4549645e68081c17aca86283a4621670b034849f, the JNI empty-input path, merged parity summary, and managed-recipient request counter are corrected. One blocking issue remains: the new wallet path rejects a proof whose input nonce is too low to reflect the submitted top-up, but the shared SDK operation still accepts that same proof as a successful top-up. Rust workspace tests, Kotlin build and tests, and the Swift frozen-schema check passed; the full Swift build and tests, PR Hygiene, and the review check were pending.

🟡 1 suggestion(s)

Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.

Still open from earlier rounds (1)

  • 🟡 Suggestion: Make the send-phase teardown test bounded and deterministic — packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs:702-711 (thread)
Follow-up candidates (optional) (9)

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: Document when Swift callers must not resubmit a top-up
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:863-865

The public external method documents not-found and refers callers to the managed method, but neither method explains the distinction between identityLookupFailed and transactionBroadcastUnconfirmed. The first is a pre-send failure; the second can mean the payment already executed or still will. Document both outcomes on the public APIs: a lookup failure may be retried, but an unconfirmed top-up must not be submitted again, even after a balance refresh. A new call can sign with fresh nonces and pay again.

source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

🟡 Suggestion: Document that the FFI top-up signer supports only P2PKH inputs
packages/rs-platform-wallet-ffi/src/identity_top_up.rs:202-204

The C row format and Swift IdentityAddressInput both represent P2SH, but the builder calls sign_create_witness for each input and VTableSigner rejects P2SH before invoking the callback. A custom callback cannot supply that witness. Document the P2PKH-only limitation on both C exports and their Swift methods without adding a second validation rule in the bindings.

source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

🟡 Suggestion: Apply caller request settings to the new recipient reads
packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs:117-122

Both the managed IdentityBalance::fetch and the external Identity::fetch supply default request settings. A caller requesting zero retries or a short timeout can therefore wait through the SDK-wide retry budget before the signer is called, even though broadcast and the result wait honor the override. Use fetch_with_settings with the caller's PutSettings.request_settings for the two recipient reads. If the funding nonce read is intentionally left on SDK defaults, document that boundary.

source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

🟡 Suggestion: Test which balance the managed sign step records
packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs:645-660

This test supplies both baselines directly to bind_to_submitted_nonces, and the managed fixture only checks failed and absent balance reads. Both would still pass if the real sign step fetched a balance successfully and then stored the cached identity.balance() instead. Set different cached and mocked Platform balances, invoke the real managed sign step, and assert that SignedTopUp.balance_before equals the Platform value. No broadcast or result proof is needed.

source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

🟡 Suggestion: Correct the Rust inference claim in Breaking Changes
packages/rs-platform-wallet/src/wallet/platform_wallet.rs:630-637

The method docs correctly explain that rows.collect() used to infer BTreeMap from the concrete parameter but no longer does. The PR's Breaking Changes section says callers relying on inference are unaffected. Replace that claim with the documented migration: pass rows directly or use collect::<BTreeMap<_, _>>(). This affects call sites without a turbofish on the top-up method too.

source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

🟡 Suggestion: Distinguish the two zero-row C calls in the migration note
packages/rs-platform-wallet-ffi/src/identity_top_up.rs:180-185

The PR says an empty list still returns code 2. The base managed export checked inputs for null before checking the count: (NULL, 0) returned ErrorNullPointer (3), and only a non-null pointer with zero count returned ErrorInvalidParameter (2). With otherwise valid arguments and a live wallet, both forms now reach wallet validation and return 2. Document the 3-to-2 change without changing the new behavior or either code assignment.

source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

🟡 Suggestion: Document the Kotlin code-58 migration for existing operations
packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt:1023

This mapping is shared by all wallet calls. An existing shieldedShieldFromIdentity call that returned native code 58 used to reach Kotlin as PlatformWallet.Generic with isRetryable == false; it now throws IdentityBalanceUnavailable with isRetryable == true. Note in Breaking Changes that existing catch (PlatformWallet.Generic) handlers need to account for the typed case. The native number stays 58.

source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

🟡 Suggestion: Build an address top-up from the recipient ID, not a full identity
packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs:173-183

The external route fetches and proves the recipient's public keys, but the DPP builder uses only identity.id() and the funding addresses supply every witness. An ID-taking constructor would let this route use the proved IdentityBalanceAndRevision lookup for its baseline and recipient existence: it distinguishes an absent identity from an existing one with zero balance without loading the keys. Preserve the current &Identity constructor as a forwarding API; the managed route could then also avoid cloning the full identity just to obtain its ID.

source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

🟡 Suggestion: Reject stale top-up results in the shared SDK operation
packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs:391-398

The wallet refuses to report success if an input signed with nonce 5 still appears at nonce 4 in the proof. But rs-sdk/src/platform/transition/top_up_identity_from_addresses.rs::top_up_result checks only the recipient, address set, and presence of a balance, so the public WASM and direct SDK C top-up APIs can return that same snapshot as a successful payment. The base wallet used the shared SDK operation; this PR replaces it with a second settlement path and puts a check that requires no wallet state above the SDK. Have both paths use an SDK settlement check that rejects input nonces below the submitted values, and test the nonce-4 result at that boundary. Leave lifecycle gating and persistence in the wallet. This check rules out a result that cannot reflect the payment; it does not require or provide the execution receipt tracked in #4270.

source: gpt-6.2-astra (phase2-reviewer: architecture-layering)

Review provenance

Source: reviewer 1: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.2-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.2-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 5: gpt-6.2-astra (agent: phase2-reviewer, role: rust-quality); reviewer 6: gpt-6.2-astra (agent: phase2-reviewer, role: security-auditor); reviewer 7: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 8: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 9: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 10: gpt-6.2-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 11: gpt-6.2-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 12: gpt-6.2-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 13: gpt-6.2-astra (agent: phase2-reviewer, role: rust-quality); reviewer 14: gpt-6.2-astra (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.2-sol (effort low) — The changes in top_up_from_addresses.rs alter a funds-movement path on both managed and external routes, coordinating signing, broadcast, nonce-bound confirmation, and wallet removal.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity 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 final gate: an independent Phase-2 review ran after iterative findings were reconciled
  • Code unchanged since the last final review (3548f935): 1 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 1 not confirmed (now follow-up candidates); 8 new suggestion(s) listed as follow-up candidates, not posted inline
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (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-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs:702-711: Make the send-phase teardown test bounded and deterministic
  (carried; thread: https://github.com/dashpay/platform/pull/5860#discussion_r4622211266)
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.

  • Track and recover the exact top-up after an ambiguous submission — The current checks can rule out some stale snapshots, but a competing spend can consume the submitted nonces while a credit raises the recipient's balance. The proof does not identify which signed payment executed, and code 20 leaves no durable record to recover on re-entry or restart. Track execution-bound settlement and same-operation recovery separately from the shared stale-result check.
    • Follow-up: #4270 for execution-bound settlement and recovery; #6000 for restoring the host's pending indication.

@github-actions github-actions Bot removed the bot-review-skipped A required review bot did not report; it was skipped by the window or by a person. label Nov 20, 2026
@romchornyi

Copy link
Copy Markdown
Contributor Author

ready to merge

@romchornyi
romchornyi merged commit e451c35 into v5.2-dev Nov 20, 2026
33 of 34 checks passed
@romchornyi
romchornyi deleted the feat/platform-wallet-external-identity-top-up branch November 20, 2026 01:05
romchornyi added a commit that referenced this pull request Nov 20, 2026
#5860 landed on v5.2-dev (e451c35) with its own split of the address
top-up's lifecycle gate: signing outside the gate, the generation
rechecked under `generation_payment_guard` before send
(`PlatformWallet::top_up_identity_with`). That supersedes this branch's
`GatedAddressSigner` (taking the gate after the last signature), which is
dropped with the tests that duplicated #5860's.

The top-up of any identity now runs on #5860's sign/send split: one
crate-private sign step (`sign_top_up_from_addresses` with a
`TopUpScope`) fetches the identity from Platform, the composite writes a
managed identity's proved balance back (`record_top_up_balance`) under the
gate and reconciles. The deprecated managed route keeps #5860's errors:
7 for an identity the manager does not hold (read through the handle's
generation), 80 for a failed lookup, 58 when Platform returns no identity.
The sign step still checks the generation after the identity and nonce
reads, before the host is asked to sign.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
romchornyi added a commit that referenced this pull request Nov 20, 2026
Keeps both sides: #5860's caller settings on every broadcast dispatch and
this branch's per-dispatch context check (broadcast_tracking_delivery_checked
takes the settings); error codes 77-79, 80 and 81 side by side in Rust,
the FFI registry, Swift and Kotlin. The parity manifest names the renamed
plan-routing test and the summary is regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
romchornyi added a commit that referenced this pull request Nov 20, 2026
Brings #5860 under this branch's payment classes:
- IdentityLookupFailed (80) is NotSent; it and IdentityBalanceUnavailable
  (58), reads before anything is signed, are retryable by Rust's decision,
  so Kotlin's per-class isRetryable overrides go (the flag is read only).
- The address top-up panic guard carries the panic payment class.
- Swift PlatformWalletError.identityLookupFailed carries its payment.
- The top-up screens show #5860's pending state when Rust classes the
  failure MAYBE_SENT, not on an error type; AddressNonceMismatch docs keep
  both changes (maybe sent; top-ups no longer return it).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
romchornyi added a commit that referenced this pull request Nov 20, 2026
HashEngineering added a commit that referenced this pull request Nov 20, 2026
… 58)

#5863's proved-balance check runs before either identity shield is
signed, and refuses with InsufficientIdentityCredits (39) or
IdentityBalanceUnavailable (58, typed in Kotlin by #5860). List both in
the KDoc of shieldedShieldFromIdentity and
shieldedShieldFromIdentityToRecipient, and widen
InsufficientIdentityCredits' KDoc beyond DPNS purchases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
HashEngineering added a commit that referenced this pull request Nov 20, 2026
…irmed outcomes

#5860 now reports a failed identity read as IdentityLookupFailed (80,
retryable, nothing sent) and an unproved result as
TransactionBroadcastUnconfirmed (20, do not resubmit), alongside
NotFound (7). The KDoc says which is which, and the test pins each
code's mapping, including that 80 is retryable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
romchornyi added a commit to dashpay/dashwallet-ios that referenced this pull request Nov 23, 2026
A Platform -> Identity send whose identity read from Platform failed
(PlatformWalletError.identityLookupFailed, FFI code 80 from
dashpay/platform#5860) fell through to inFlight, so Send showed
"Send in progress" with no Retry although nothing was signed. It is
now notSent(.failed) with Retry.

Code 58 (identityBalanceUnavailable) stays inFlight: the shared map
cannot prove it came before the broadcast on every route.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
HashEngineering added a commit that referenced this pull request Nov 23, 2026
…irmed outcomes

#5860 now reports a failed identity read as IdentityLookupFailed (80,
retryable, nothing sent) and an unproved result as
TransactionBroadcastUnconfirmed (20, do not resubmit), alongside
NotFound (7). The KDoc says which is which, and the test pins each
code's mapping, including that 80 is retryable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
romchornyi added a commit to dashpay/dashwallet-ios that referenced this pull request Nov 24, 2026
A Platform -> Identity send whose identity read from Platform failed
(PlatformWalletError.identityLookupFailed, FFI code 80 from
dashpay/platform#5860) fell through to inFlight, so Send showed
"Send in progress" with no Retry although nothing was signed. It is
now notSent(.failed) with Retry.

Code 58 (identityBalanceUnavailable) stays inFlight: the shared map
cannot prove it came before the broadcast on every route.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
romchornyi added a commit to dashpay/dashwallet-ios that referenced this pull request Nov 24, 2026
It holds the merged SDK changes this layer needs: the external identity
top-up and identityLookupFailed (dashpay/platform#5860),
shieldedShieldFromIdentityToRecipient (#5863) and the address top-up for any
identity (#5929).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
HashEngineering added a commit that referenced this pull request Nov 24, 2026
…kupFailed (80)

#5860 merged the not-sent lookup failure. The external top-up from Core and
the recipient assignment now report a lookup Platform cannot answer as
IdentityLookupFailed (FFI 80) instead of the SDK's error: nothing is built or
assigned, so the call may be retried as it is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
HashEngineering added a commit to dashpay/dash-wallet that referenced this pull request Nov 25, 2026
…tity

int39 adds IdentityCredits.topUpExternalIdentityFromAddresses (a Kotlin
binding of dashpay/platform#5860). Platform -> Identity now uses
topUpFromAddresses for an identity the SDK wallet manages and the external
top-up for any other; an unreadable managed set is NotSent. A missing
identity fails DashSdkError.NotFound before signing, read as NotSent.
Core -> someone else's identity stays unsupported.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
HashEngineering added a commit to dashpay/dash-wallet that referenced this pull request Dec 1, 2026
* feat(payments): External Send from any balance in Advanced mode (MO-1121)

The Advanced payments Send tab gets its own Compose page: send to a
username (Core, as today), to a typed/pasted/scanned destination, or by
scanning a Dash QR. The external send flow detects the destination type
from the whole address (Core, Platform dash1k/dash1s, Shielded dash1z,
identity ID) and rejects wrong-network or malformed input, then reuses
AmountEntryPage with From/To cards, a source picker, a confirm sheet and
PIN before every send.

ExternalSendService routes each source/destination pair to the SDK with
the SdkWriteResult rules (only provably pre-broadcast failures are
retryable, the bound wallet is captured and re-checked before submit).
Supported: Core->Core/Shielded/own Identity, Shielded->all,
Platform->Platform/Identity, Identity->Core/Platform/Identity. The rest
need SDK changes and are shown as not available yet. Basic mode is
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): address pre-review round 1 on External Send

- Core->Shielded locks amount + pool fee so the recipient gets the
  confirmed amount; fee, Max and Total agree.
- Core Max refuses when the balance changed since confirm; the confirm
  sheet shows a Max send as fee-inclusive, like Basic send-all.
- The SDK wallet is captured at confirm and checked before every write.
- An in-flight marker survives process death and restores the terminal
  "may have gone through" state instead of the editable form.
- dash: URIs for Shielded/Platform/Identity amount requests parse.
- The exact amount is pinned across a currency switch.
- AddressUtils/WifKey reject an empty Base58Check payload instead of
  crashing; destination detection never throws.
- Advanced scan keeps BIP70, AnyPay and serialized requests on the
  Basic invoice path.
- Live identity/shielded reads recover after a transient error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): address pre-review round 2 on External Send

- Keep the in-flight marker after a Sent until the user acknowledges it,
  so a process kill before the result is seen warns instead of
  reopening the form.
- Claim an acknowledgement atomically (new Acknowledging state) before
  clearing the marker, so a duplicate acknowledgement cannot clear a
  later send's marker.
- Core→Core: size the fee reserve by UTXO count and turn Max off when
  the balance does not exceed it, so the recipient amount is always
  positive.
- Core→Shielded Max now comes from the confirmed balance an asset lock
  can spend, with the L1 fee reserved up front; the Max retry is gone.

The Core Max drain is still uncapped by the confirmed amount (finding 1);
it is left for device testing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): keep the External Send form disabled once a send has finished

After the user closed the result of a send that went out (or may have),
the executor returned to Idle while the screen was leaving, and the
amount form, still holding the sent amount, became enabled again. A
`finished` flag, set before the executor is released and kept in saved
state, now keeps Continue, the keypad, Max and the source picker inert.
A not-sent result still returns to an editable amount.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(payments): enable External Send from Core to a third-party Platform address

Bump the Kotlin SDK to 5.1.0-int36 (HashEngineering/platform
feat/kotlin-sdk-fund-from-asset-lock-external @ 760d00f559), which binds
fundFromAssetLockExternal, and use it for Core → Platform (P2PKH only).

- The payee gets exactly the amount; the lock carries a 62 000-duff margin
  (the DPP address-funding admission floor) whose remainder, after the
  Platform fee, lands on the wallet's own Platform address.
- Per the SDK contract the recipients are persisted before the call and the
  lock outpoint inside onAssetLockBuilt; once a lock is built a failure is
  "may have gone through", never Not sent.
- A resume sweep (executor start and screen open) completes an interrupted
  funding with exactly the persisted recipients, capped per process.
- A pending record blocks a second Core → Platform send.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(payments): resume an interrupted Core → Platform send at app start

Run the External Send Platform-funding resume sweep from
PlatformSynchronizationService.kickSdkEngines, right after the pending
wallet-shield sweep: every kick (app start and each blockchain-service
start), after the SDK bind pass. A stuck payee is now paid without the
user reopening External Send. The executor is injected as dagger.Lazy so
its service graph is built off the main thread and can't form a cycle.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(platform): start the SDK's Platform-address balance sync

The app never started the Kotlin SDK's Platform-address (BLAST) sync, so
credits other wallets sent to our Platform addresses never appeared: the
wallet only knew balances it wrote itself.

PlatformAddressSyncService starts the SDK loop once the cutover is
committed, the SDK wallet is bound and exactly one SDK wallet is loaded.
PlatformSynchronizationService starts it with the L1 engine (foreground
blockchain-service lifetime, after the bind pass, and on bind heal) and
stops it last in stopSdkEngines (shutdown and wallet wipe). A stop
generation refuses a start decided before a stop. The SDK's 15 s interval
is used; External Send's 15 s Platform balance poll picks up each pass.

Verified on testnet emulators: a 0.05 DASH Core → Platform send from one
wallet appeared on the receiver's Platform address ten seconds later.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): return Home after a finished External Send

Closing a Sent or "may have gone through" result (including the one shown
after a process restart) now pops back to Home instead of only closing
the External Send screen, which left the user on Payments. The back
button, Not sent and leaving mid-send still return to Payments; if Home
is not on the back stack it falls back to the single pop.

Verified on a testnet emulator.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(history): show a Core → Platform send as a send titled "Platform"

A Core → Platform-address External Send is an asset lock the SDK tracks
with funding type 4, which AssetLockKindResolver did not map, so its row
fell back to "Internal" with the internal-transfer icon.

Add AssetLockKind.PLATFORM for funding type 4: the row and detail sheet
read "Platform" with the sent arrow, count under the Sent filter and never
notify as received. The send seeds the kind from onAssetLockBuilt so the
row is right before the SDK's asset_locks row lands. A restored wallet's
own Platform top-up (also type 4) reads the same, since the funding type
cannot tell own from third-party.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(payments): enable Platform → Core and third-party shields in External Send

Adopt Dash SDK 5.1.0-int37, which adds a partial Platform-address
withdrawal and recipient-taking shield calls, and turn on three
Advanced-mode External Send pairs:

- Platform → Core: ManagedPlatformWallet.withdrawCredits with
  wallet-selected inputs (never above an address's balance, at most 16,
  the first-sorting fee payer keeps the fee reserve). Amounts below the
  withdrawal minimum or above the maximum are refused before signing.
- Platform → Shielded: PlatformWalletManager.shieldedShieldToRecipient.
- Identity → Shielded: shieldedShieldFromIdentityToRecipient.

The three pairs show no fee estimate and keep Max off. Results stay
exactly-once (Sent / Not sent / may have gone through, never retried).
The shielded identity-debit-pending error and the own-shielded-recipient
refusal are now classified as NotBroadcast, as Rust builds nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(history): label a received withdrawal "Withdrawal"

A received AssetUnlock this wallet's shielded pool did not author can be
a Platform-address withdrawal (now sendable via Platform → Core), an
identity credit withdrawal or a foreign pool's unshield; the Core
transaction does not say which. "Unshielded Withdrawal" mislabelled the
first two, so the row now reads "Withdrawal". Own-pool unshields keep
"Unshielded"; receive semantics are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): make Max follow a source change in External Send

Switching the source after pressing Max kept the old source's Max as a
plain amount, so a Core Max could be confirmed as a Shielded send. Max
now follows the source: the amount is 0 and Continue disabled until the
new source's Max is read, then it is applied as if Max were pressed. A
source with no Max (unknown fee, empty balance) leaves the amount at 0.
Typing cancels a pending Max, and it survives process death.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(payments): simplify External Send's fee, Max and read plumbing

- estimateFee drops its unused amount; estimateFee and maxSendable take
  the source and destination balance kinds (balanceKindOf, now shared).
- The shielded flag and own-identity flows are deduplicated before
  flatMapLatest, so an unrelated config write no longer restarts the
  balance flows or re-fetches the Identity balance.
- sendFromShielded and nativeWrite return mapWrite's mapping.
- The private retryReadErrors copy is replaced by the common helper.
- PlatformAddressSyncService shares SdkL1SendService's cutover check.
- ExternalSendFragment remembers its actions; the currency codes list is
  remembered per fiat code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): draw the External Send result inside the screen

The result used ModalDialog, a separate window that stayed above the
lock screen and could be closed without the PIN. It is now an in-screen
overlay like the source and confirm sheets, so the lock screen covers it
and it shows again after unlock. Back acknowledges the result as the
dialog did, and is ignored while the lock screen shows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(payments): open the transaction result after a Core-sourced External Send

A Core send that builds a transaction now returns its txid: the payment
itself for Core -> Core, and the asset lock for Core -> Platform,
Core -> Shielded and Core -> own identity. The screen then opens
TransactionResultActivity once, acknowledges the outcome and returns
Home, as the Basic send flow does. It opens only while the screen is
resumed and the wallet is unlocked. Sends without a Core transaction,
and every failure or unknown outcome, keep the in-screen result.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): restore the External Send From/To card colours

The material3 Card import added for the result overlay took precedence
over the screen's private Card, so the From/To cards drew as Material3
cards (lavender, no padding). The private one is now SendCard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): clear a Core -> Platform funding Platform already has

A Core -> Platform send interrupted after its transition was submitted
could never resume: each resume rebuilds the same bytes, Tenderdash
refuses them as already in its cache, and the SDK returns that error
without waiting for the result. The record was kept, so every later
Core -> Platform send was refused as still pending. The resume sweep now
clears the record on the SDK's AlreadyExists error. Platform consumes a
lock once, so nothing can be paid twice.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): pay the confirmed amount on External Send withdrawals

Pre-review findings on #1680:
- Platform, Identity and Shielded -> Core withdrawals now withdraw the
  amount plus the 190-duff Core fee, which Platform takes out of the
  withdrawn amount, so the recipient receives exactly what was
  confirmed. Limits and input selection use the gross amount; a
  Shielded -> Core Max shows the recipient amount net of the fee.
- A Core -> own identity send that only resumed an earlier unfinished
  top-up is now Not sent (EARLIER_TOP_UP_COMPLETED) instead of Sent.
- The confirm sheet's details scroll inside a weighted region, so the
  Cancel/Confirm row keeps its height on short screens or large text.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(history): show a Core -> third-party Shielded payment as a send

A shield to another wallet's Orchard address seeded the same SHIELD
kind as a shield into the wallet's own pool, so history showed it as an
internal transfer although the funds left the wallet. The external path
now seeds SHIELD_EXTERNAL: sent arrow, outgoing amount, titled
"Shielded", as the Core -> Platform send is titled "Platform". Like
PLATFORM, the kind is in-memory only; after a restart the funding-type
fallback reads SHIELD again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): hold the wallet-wipe barrier on External Send submissions

Every non Core -> Core External Send route, and the Core -> Platform
resume sweep, now submits under FundingSelectionLock.withSharedSubmission
with the final bound-wallet check inside the hold, so a Reset Wallet can
neither race a credit payment nor have a stale funding record written
back after it cleared the store.

ExternalSendExecutor now forgets its state on wallet wipe (wipe listener
+ generation counter), so a finished or late-completing send of the
wiped wallet is never shown to, or opened by, the next wallet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): handle int38's unconfirmed outcomes and unproven consumed locks

- Classify every typed *Unconfirmed SDK error (StateTransitionResultUnconfirmed,
  TransactionBroadcastUnconfirmed, shielded/masternode variants) as "may have
  gone through", ahead of any message match, in the credit writes, the
  shielded invite claim and the top-up recovery.
- Core -> Platform resume: the "Object already exists" match is gone (int38
  waits for the proved result itself). An unconfirmed outcome keeps the
  pending record for the next sweep.
- An AssetLockAlreadyConsumed answer is not proof, so, as the iOS wallet
  does, the record is moved to a durable "completion unconfirmed" set: it is
  no longer resumed automatically and no longer blocks new Core -> Platform
  sends, but is kept for a later manual retry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): limit Platform -> Identity to own identity; keep SDK messages out of logs

- The SDK's identityCredits.topUpFromAddresses only finds identities the
  wallet manages, so a Platform -> someone else's identity send failed on
  device with "Identity not found". External Send now offers Platform ->
  Identity only for the wallet's own (SDK-managed) identity, like
  Core -> Identity, and the service refuses the rest before building.
  Someone else's identity needs a Kotlin binding of platform#5860.
- That failure was logged with the SDK message, which named the recipient
  identity. External Send now logs only error class names (and a native
  code) via safeErrorSummary, never an exception message or stack trace.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(payments): pin the Dash SDK to 5.1.0-int39; Platform -> any identity

int39 adds IdentityCredits.topUpExternalIdentityFromAddresses (a Kotlin
binding of dashpay/platform#5860). Platform -> Identity now uses
topUpFromAddresses for an identity the SDK wallet manages and the external
top-up for any other; an unreadable managed set is NotSent. A missing
identity fails DashSdkError.NotFound before signing, read as NotSent.
Core -> someone else's identity stays unsupported.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): cap Platform -> Core at what the withdrawal can take

maxSendable returned null for a Platform source, so the Amount page fell
back to the raw balance and allowed amounts the send then refused as
INSUFFICIENT_FUNDS (MO-1121 QA). The cap now mirrors the withdrawal's own
input selection: the first-sorting input keeps the SDK preflight's fee
reserve and the 190-duff Core fee comes out of the gross. An unknown cap
blocks Continue instead of falling back to the balance.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): match the External Send confirm notes to Figma

Drop the identity-balance note (not in the design), use Figma's
info-rect-small and system_message-public icons for the two Shielded
notes, and keep the sheet clear of the system bars like the app's other
bottom sheets. Adds 320dp previews of the Shielded confirm sheet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): keep a fee reserve on Platform -> Identity top-ups

IdentityTopUpFromAddresses pays its fee from the first-sorting input's
remainder (DeductFromInput(0)), but the inputs were picked to spend exactly
the amount, so a top-up that emptied that address could not pay its fee.
Select with the withdrawal selector and a fixed reserve (the SDK's
withdrawal reserve at 16 inputs), refuse amounts below the identity
funding minimum, and cap the Amount page at the same Max for both the
managed and the external top-up.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): address pre-review findings on External Send

- Retry a failed Max read for Platform -> Core / Identity while the
  balance is unchanged, so Continue can't stay blocked
- Show the recipient amount as unknown while a Max drain fee is unknown
- Advanced scan: use the shared DashConnectUri.isConnectUri predicate
  (dashpay://connect was rejected)
- Shielded external routes: log safeErrorSummary, not the throwable
- Core asset-lock Max: cap the confirmed balance at the SDK max-sendable
- Executor: don't clear a marker after a wipe; it may be the new wallet's
- Docs: drain amount check is best-effort; accepted-risk note for a
  failed outpoint write followed by process death

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(payments): estimate the Core -> Identity network fee

The confirm sheet showed "---" for the fee and total. Core -> Identity now
estimates the L1 asset-lock reserve (assetLockMaxFeeReserve over the
spendable UTXO count, an upper bound paid on top; null when the count is
unknown), shown as "~" like Core -> Platform. Platform's top-up fee comes
out of the locked amount and is not included.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): refuse a Core -> own identity top-up below Platform's minimum

A new top-up lock below 50,500 duffs (identity_topup_base_cost +
required_asset_lock_duff_balance_for_processing_start_for_identity_top_up)
was built and broadcast, then rejected by Platform, ending Ambiguous.
Refuse it before it is built (Not sent). Resuming an earlier lock is not
gated. PerformTopUpWorker's floor now uses the shared constant. MO-1121.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): show a Platform -> Shielded capacity refusal as not sent

The SDK's PlatformShieldCapacityExceeded (native code 41) is raised while
fetching the shield's input nonces, before anything is built: the Platform
addresses cannot cover the amount plus input 0's fee reserve. It fell
through classifyBroadcastFailure to Ambiguous, so the user saw "Payment
status unknown, do not send again" for a transfer that never left. It is
now NotBroadcast (after the unconfirmed arm, which still wins) and maps to
INSUFFICIENT_FUNDS, so the user can enter a smaller amount.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): scan Shielded and Platform addresses from Home in Advanced mode

The Home Scan QR shortcut used only the legacy Core parser, so a Shielded
or Platform address (bare or dash:<addr>?amount=) failed with "invalid
Dash address". In Advanced mode, classify the scan the same way as the
Advanced Send page's Scan Dash QR: destinations open External Send
prefilled, a wrong-network address shows that error, and DashConnect,
BIP70, keys and raw transactions keep the legacy path. With Advanced mode
off nothing changes. MO-1121.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): classify three pre-broadcast SDK refusals as not sent

classifyBroadcastFailure sent these to Ambiguous ("may have gone
through") although nothing was signed or broadcast:

- "Insufficient address balance" (dpp AddressNotEnoughFundsError): the
  rs-sdk address-input pre-check refuses a Platform -> Core / Platform /
  Identity send when the cached address balance is stale. A refusal that
  may have been accepted still arrives as StateTransitionResultUnconfirmed
  and stays Ambiguous.
- DashSdkError.PlatformWallet.InsufficientIdentityCredits (code 39): a
  local pre-flight or a definite CheckTx refusal on the identity paths.
- "fetch identity nonce": the identity shield's nonce lookup, before it
  builds, records or broadcasts anything.

Reasons stay static; the SDK messages carry addresses and identity ids.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): bound External Send address input before decoding

- Reject Base58 text longer than any real encoding before decoding it:
  35 chars for a Core address (25 bytes), 44 for an identity id
  (32 bytes). The Base58 decode is quadratic, so a huge pasted token
  could stall the UI thread. Bech32m decoding is linear and is left
  unbounded.
- Show clipboard: bound the text (4096 chars) and the number of tokens
  (64) before validating them, and read only an item's literal text.
  coerceToText could block on another app's content provider for a
  URI-only clip.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(platform): keep identities and usernames out of query timeout labels

boundedSdkPlatformQuery logs its label when a query times out and again
when the abandoned native call settles. Several labels interpolated an
identity id, a username or search text (the DPNS username lookup that
External Send runs before confirmation, among them). Use static
operation names instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): pay a Core -> Core Max as an exact-amount payment

The Max went through the SDK send-all, whose amount is only a floor:
coin selection runs again at build time, so an output that became
spendable after the Max re-check was swept to the recipient on top of
the confirmed balance (#1774).

A Core -> Core Max is now an ordinary payment of exactly what the
confirm sheet showed the recipient: the confirmed amount minus the fee
the sheet showed. That fee travels with the request
(ExternalSendRequest.coreMaxFee). A Confirm tapped before the fee
arrived is refused and must be tapped again, and the service refuses a
Max whose fee is missing or out of range. A deposit that arrives in
between comes back as change; a build that comes up short is refused
before broadcast as Not sent. The fee reserve is always at least the
real fee, so an unchanged Max still funds (a remainder at or below dust
goes to the fee).

The send-all refused to spend app-locked (CrowdNode) outputs; the
payment keeps that guard and refuses the Max, failing closed, when the
check can't be read. External Send no longer calls the send-all at all.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* build(sdk): move External Send to Kotlin SDK 5.2.0-int01

5.2.0-int01 is v5.2-dev plus the int42/int43 carry. v5.2-dev already has
the bindings External Send needs (#5860, #5873, #5896), so the int39 pin
is no longer needed. Its dash-sdk.db is Room 21, so an int42 database
(17) migrates instead of failing to open.

#5860 merged the external top-up as topUpIdentityFromAddresses, so the
call is renamed. The InsufficientIdentityCredits comment now lists the
sources at v5.2-dev.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(payments): resume interrupted shields to their recorded payee; classify int01 shielded refusals

With SDK 5.2.0-int01 the asset-lock row records the Orchard recipient
before dispatch, and resume refuses any other recipient
(AssetLockRecipientMismatch). walletShieldLocks dropped that field, so the
sweep and the user retry resumed an interrupted Core -> third-party
Shielded payment to the sender's default address and were refused,
leaving the funds locked. PendingWalletShieldLock now carries
shieldedRecipientRaw43 (kept out of toString), and the sweep resumes to
it. The default address is used only for legacy rows with no recorded
recipient. Only locks that paid this wallet's own pool are announced as
"shielded balance updated". InterruptedFundsReturnToShielded is renamed
InterruptedCompletesAutomatically, and its copy now says the payment
finishes on its own.

classifyBroadcastFailure maps three typed int01 refusals that are raised
only before submission to NotBroadcast, after the unconfirmed-outcome
check: ShieldedWithdrawalAmountOutOfRange, ShieldedSpendTooManyNotes and
ShieldedMerkleWitnessUnavailable. A below-minimum Shielded -> Core send
now shows "not sent" with the form still editable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants