From 9b9bccc3e8a48dd6f03cffe4fe1e09ee9d4a37f5 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Thu, 12 Nov 2026 21:05:21 -0800 Subject: [PATCH 1/4] feat(kotlin-sdk): topUpExternalIdentityFromAddresses Bridge platform_wallet_top_up_external_identity_from_addresses_with_signer to Kotlin: a JNI export in rs-unified-sdk-jni, CreditsNative, and IdentityCredits.topUpExternalIdentityFromAddresses. It tops up an identity the wallet does not manage from the wallet's Platform-address inputs; Rust fetches the identity from Platform and never adds it to the wallet. The JNI layer does not refuse empty inputs: the library owns that rule. An unknown identity maps to DashSdkError.NotFound. Parity: identity.external_top_up_from_addresses is now supported for the Kotlin SDK, verified by ExternalIdentityTopUpTest. Co-Authored-By: Claude Opus 5.5 --- docs/sdk/sdk-parity-manifest.json | 12 +++- packages/kotlin-sdk/PARITY_SUMMARY.md | 4 +- .../dashsdk/credits/IdentityCredits.kt | 41 +++++++++++ .../dashsdk/ffi/CreditsNative.kt | 16 +++++ .../credits/ExternalIdentityTopUpTest.kt | 71 +++++++++++++++++++ packages/rs-unified-sdk-jni/src/credits.rs | 48 +++++++++++++ 6 files changed, 188 insertions(+), 4 deletions(-) create mode 100644 packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt diff --git a/docs/sdk/sdk-parity-manifest.json b/docs/sdk/sdk-parity-manifest.json index a59a25072e7..07b97adcf6c 100644 --- a/docs/sdk/sdk-parity-manifest.json +++ b/docs/sdk/sdk-parity-manifest.json @@ -1485,10 +1485,10 @@ "reason": "ManagedPlatformWallet.topUpExternalIdentityFromAddresses bridges the export; the example app has no screen that pays to someone else's identity." }, "kotlin": { - "sdk": "unsupported", + "sdk": "supported", "example_app": "unsupported", "restart": "not_applicable", - "reason": "No JNI bridge or Kotlin wrapper for the external identity top-up yet." + "reason": "IdentityCredits.topUpExternalIdentityFromAddresses bridges the export through CreditsNative; the example app has no screen that pays to someone else's identity." } }, "verification": [ @@ -1499,6 +1499,14 @@ "id": "testMarshalsArgumentsAndReturnsTheBalanceTheExportWrites", "command": "cd packages/swift-sdk && xcodebuild test -scheme SwiftDashSDK -destination 'platform=iOS Simulator,name=iPhone 17 Pro' -only-testing:SwiftDashSDKTests/ExternalIdentityTopUpTests", "covers_restart": false + }, + { + "host": "kotlin", + "kind": "unit", + "file": "packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt", + "id": "should pass the handles, id and encoded inputs to the external export and return its balance", + "command": "cd packages/kotlin-sdk && ./gradlew :sdk:testDebugUnitTest --tests 'org.dashfoundation.dashsdk.credits.ExternalIdentityTopUpTest'", + "covers_restart": false } ] }, diff --git a/packages/kotlin-sdk/PARITY_SUMMARY.md b/packages/kotlin-sdk/PARITY_SUMMARY.md index a62b3e0e164..ca40353d7a2 100644 --- a/packages/kotlin-sdk/PARITY_SUMMARY.md +++ b/packages/kotlin-sdk/PARITY_SUMMARY.md @@ -10,7 +10,7 @@ Capabilities tracked: **31** | --- | --- | ---: | ---: | ---: | ---: | | Swift | SDK | 18 | 11 | 1 | 1 | | Swift | Example app | 5 | 14 | 3 | 9 | -| Kotlin | SDK | 14 | 14 | 2 | 1 | +| Kotlin | SDK | 15 | 14 | 1 | 1 | | Kotlin | Example app | 6 | 13 | 2 | 10 | ## Restart coverage @@ -42,7 +42,7 @@ Capabilities tracked: **31** | `persistence.dashpay_payment_history` | partial / not-applicable / required | not-applicable / not-applicable / not_applicable | | `network.masternode_discovery` | partial / not-applicable / not_applicable | partial / not-applicable / not_applicable | | `identity.platform_address_auto_funding` | partial / partial / not_applicable | partial / partial / not_applicable | -| `identity.external_top_up_from_addresses` | supported / unsupported / not_applicable | unsupported / unsupported / not_applicable | +| `identity.external_top_up_from_addresses` | supported / unsupported / not_applicable | supported / unsupported / not_applicable | | `tokens.authorization_decisions` | partial / partial / not_applicable | partial / partial / not_applicable | | `tokens.direct_purchase_quote` | partial / partial / not_applicable | partial / partial / not_applicable | | `protocol.address_validation` | supported / supported / not_applicable | partial / partial / not_applicable | diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt index d03f3de82c8..c7e4f9a3932 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt @@ -19,6 +19,15 @@ internal fun interface ResumeTopUpNativeCall { ): Long } +internal fun interface AddressTopUpNativeCall { + fun call( + walletHandle: Long, + identityId: ByteArray, + inputsBlob: ByteArray, + signerHandle: Long, + ): Long +} + /** * One Platform-address funding input for an identity top-up — port of the * `IdentityAddressInput` tuple the Swift `TopUpIdentityView` packs. Encodes @@ -81,6 +90,8 @@ class IdentityCredits internal constructor( private val gate: org.dashfoundation.dashsdk.wallet.TeardownGate? = null, private val resumeTopUpNative: ResumeTopUpNativeCall = ResumeTopUpNativeCall(CreditsNative::topUpIdentityWithExistingAssetLock), + private val externalTopUpNative: AddressTopUpNativeCall = + AddressTopUpNativeCall(CreditsNative::topUpExternalIdentityFromAddresses), ) { /** @@ -231,6 +242,36 @@ class IdentityCredits internal constructor( } } + /** + * Top up [identityId] (32 bytes), an identity this wallet does **not** + * manage (someone else's), from the wallet's Platform-address [inputs], + * signed via [signerHandle]. Returns the identity's post-transition + * balance. ← Swift `ManagedPlatformWallet.topUpExternalIdentityFromAddresses` + * (packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift). + * + * Rust fetches the identity from Platform and never adds it to the + * wallet; the spent addresses' balances are reconciled as for + * [topUpFromAddresses]. An identity that does not exist on Platform + * fails with [org.dashfoundation.dashsdk.errors.DashSdkError.NotFound] + * before anything is signed or broadcast. Rust also owns the input + * rules (empty or overflowing inputs are refused there). + */ + suspend fun topUpExternalIdentityFromAddresses( + walletHandle: Long, + identityId: ByteArray, + inputs: List, + signerHandle: Long, + ): Long = gate.op { + mapNativeErrors { + externalTopUpNative.call( + walletHandle, + identityId, + FundingInput.encode(inputs), + signerHandle, + ) + } + } + /** * Transfer credits from [fromIdentityId] (32 bytes) to one or more * Platform-address recipients ([outputs]), signed by the identity's diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt index 395cf3ddd21..f4e36f1083b 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt @@ -84,6 +84,22 @@ internal object CreditsNative { signerHandle: Long, ): Long + /** + * Top up [identityId] (32 bytes), an identity this wallet does **not** + * manage, from the wallet's Platform-address inputs, signed per-address + * via [signerHandle]. The identity is fetched from Platform and never + * added to the wallet. Returns the identity's post-transition credit + * balance. ← Swift `ManagedPlatformWallet.topUpExternalIdentityFromAddresses`. + * + * @param inputsBlob same layout as [topUpFromAddresses]. + */ + external fun topUpExternalIdentityFromAddresses( + walletHandle: Long, + identityId: ByteArray, + inputsBlob: ByteArray, + signerHandle: Long, + ): Long + /** * Transfer credits from [fromIdentityId] (32 bytes) to one or more * Platform-address recipients, signed by the identity's transfer key diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt new file mode 100644 index 00000000000..2b3697cc099 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt @@ -0,0 +1,71 @@ +package org.dashfoundation.dashsdk.credits + +import kotlinx.coroutines.test.runTest +import org.dashfoundation.dashsdk.errors.DashSdkError +import org.dashfoundation.dashsdk.ffi.DashSDKException +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class ExternalIdentityTopUpTest { + + private val identityId = ByteArray(32) { 7 } + private val inputs = listOf( + FundingInput(addressType = 0, hash = ByteArray(20) { 1 }, credits = 50_000L), + FundingInput(addressType = 1, hash = ByteArray(20) { 2 }, credits = 25_000L), + ) + + @Test + fun `should pass the handles, id and encoded inputs to the external export and return its balance`() = runTest { + var seen: List? = null + val credits = IdentityCredits( + externalTopUpNative = AddressTopUpNativeCall { wallet, id, blob, signer -> + seen = listOf(wallet, id, blob, signer) + 9_000L + }, + ) + + val balance = credits.topUpExternalIdentityFromAddresses(11L, identityId, inputs, 22L) + + assertEquals(9_000L, balance) + val call = checkNotNull(seen) + assertEquals(11L, call[0]) + assertArrayEquals(identityId, call[1] as ByteArray) + assertArrayEquals(FundingInput.encode(inputs), call[2] as ByteArray) + assertEquals(22L, call[3]) + } + + @Test + fun `should map an unknown identity to NotFound`() = runTest { + val credits = IdentityCredits( + externalTopUpNative = AddressTopUpNativeCall { _, _, _, _ -> + throw DashSDKException( + DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 7, // ErrorIdentityNotFound + "identity not found", + ) + }, + ) + + val failure = runCatching { + credits.topUpExternalIdentityFromAddresses(1L, identityId, inputs, 2L) + }.exceptionOrNull() + + assertTrue("expected NotFound, got $failure", failure is DashSdkError.NotFound) + } + + @Test + fun `should leave empty inputs to Rust rather than refusing them in Kotlin`() = runTest { + var blob: ByteArray? = null + val credits = IdentityCredits( + externalTopUpNative = AddressTopUpNativeCall { _, _, b, _ -> + blob = b + 0L + }, + ) + + credits.topUpExternalIdentityFromAddresses(1L, identityId, emptyList(), 2L) + + assertArrayEquals(FundingInput.encode(emptyList()), blob) + } +} diff --git a/packages/rs-unified-sdk-jni/src/credits.rs b/packages/rs-unified-sdk-jni/src/credits.rs index 5d7831254d9..82c361f38a7 100644 --- a/packages/rs-unified-sdk-jni/src/credits.rs +++ b/packages/rs-unified-sdk-jni/src/credits.rs @@ -12,6 +12,8 @@ //! - [`platform_wallet_withdraw_credits_with_signer`] — identity → L1 address. //! - [`platform_wallet_top_up_from_addresses_with_signer`] — top up an //! existing identity from Platform-address inputs (ID-06). +//! - [`platform_wallet_top_up_external_identity_from_addresses_with_signer`] +//! — the same, for an identity the wallet does not manage. //! - [`platform_wallet_top_up_identity_with_funding_signer`] — top up an //! existing identity from a **new Core asset lock** (ID-05); this one //! takes a `MnemonicResolverHandle` (the Core asset-lock signer) rather @@ -212,6 +214,52 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_CreditsNative_topUpFr }) } +/// Top up an identity this wallet does **not** manage (someone else's) +/// from one or more of the wallet's Platform-address inputs, signed +/// per-address via `signerHandle`. Returns the identity's post-transition +/// credit balance. The identity is fetched from Platform and never added +/// to the wallet. +/// +/// `inputsBlob` has the same layout as `topUpFromAddresses`. An empty +/// input list is not checked here: the library owns that rule (an empty +/// `Vec`'s pointer is non-null, so it reaches the library). +/// +/// Wraps `platform_wallet_top_up_external_identity_from_addresses_with_signer`. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_CreditsNative_topUpExternalIdentityFromAddresses( + mut env: JNIEnv, + _class: JClass, + wallet_handle: jlong, + identity_id: JByteArray, + inputs_blob: JByteArray, + signer_handle: jlong, +) -> jlong { + guard(&mut env, 0i64, |env| { + let Some(id) = read_id32(env, &identity_id, "identityId") else { + return 0; + }; + let Some(inputs) = decode_inputs_blob(env, &inputs_blob) else { + return 0; + }; + + let mut out_balance: u64 = 0; + let result = unsafe { + platform_wallet_ffi::platform_wallet_top_up_external_identity_from_addresses_with_signer( + wallet_handle as Handle, + &id as *const [u8; 32], + inputs.as_ptr(), + inputs.len(), + signer_handle as *mut SignerHandle, + &mut out_balance as *mut u64, + ) + }; + if take_pwffi_error(env, result) { + return 0; + } + out_balance as i64 + }) +} + // ── Transfer (identity → Platform addresses) ─────────────────────────── /// Transfer credits from `fromIdentityId` (32 bytes) to one or more From 9d72936fcfb8eb6b599f1f55ae42412d31de5c71 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Thu, 12 Nov 2026 21:40:41 -0800 Subject: [PATCH 2/4] test(kotlin-sdk): smoke-test the external identity top-up JNI symbol The JVM tests inject the native call, so a wrong symbol name or descriptor would only fail on device. FfiSmokeTest now calls the real CreditsNative.topUpExternalIdentityFromAddresses with a 31-byte id and expects the JNI argument check's code 1. Co-Authored-By: Claude Opus 5.5 --- .../dashfoundation/dashsdk/FfiSmokeTest.kt | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt index 419de77c636..1fe99638156 100644 --- a/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt +++ b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt @@ -3,6 +3,8 @@ package org.dashfoundation.dashsdk import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import kotlinx.coroutines.Dispatchers +import org.dashfoundation.dashsdk.credits.FundingInput +import org.dashfoundation.dashsdk.ffi.CreditsNative import org.dashfoundation.dashsdk.ffi.DashSDKException import org.dashfoundation.dashsdk.ffi.DashpayNative import org.dashfoundation.dashsdk.ffi.NativePersistenceBridge @@ -161,6 +163,27 @@ class FfiSmokeTest { } } + /** + * The external identity top-up's `CreditsNative` symbol binds with the + * descriptor Kotlin declares, and reaches its own export: a 31-byte + * identity id is refused by the JNI argument check (code 1) before any + * handle is read or anything is signed. The top-up itself is covered by + * the platform-wallet and platform-wallet-ffi external-identity tests. + */ + @Test + fun externalIdentityTopUpSymbolBindsAndRejectsInvalidInput() { + NativeLoader.ensureLoaded() + val error = assertThrows(DashSDKException::class.java) { + CreditsNative.topUpExternalIdentityFromAddresses( + 0L, + ByteArray(31), + FundingInput.encode(emptyList()), + 0L, + ) + } + assertEquals(1, error.code) + } + /** * The private contact request scan state needs every override it * depends on, and atomic changesets: JNI wires its slots only for a From 2ed6fb49544534c0ec0451cc3b4cb11927ab49be Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Sun, 15 Nov 2026 23:25:53 -0800 Subject: [PATCH 3/4] docs(kotlin-sdk): name the external top-up's lookup-failed and unconfirmed 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 --- .../dashsdk/credits/IdentityCredits.kt | 16 ++++++--- .../credits/ExternalIdentityTopUpTest.kt | 36 +++++++++++++++---- 2 files changed, 42 insertions(+), 10 deletions(-) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt index c7e4f9a3932..c9a63f1f5f3 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt @@ -251,10 +251,18 @@ class IdentityCredits internal constructor( * * Rust fetches the identity from Platform and never adds it to the * wallet; the spent addresses' balances are reconciled as for - * [topUpFromAddresses]. An identity that does not exist on Platform - * fails with [org.dashfoundation.dashsdk.errors.DashSdkError.NotFound] - * before anything is signed or broadcast. Rust also owns the input - * rules (empty or overflowing inputs are refused there). + * [topUpFromAddresses]. Rust also owns the input rules (empty or + * overflowing inputs are refused there). + * + * Outcomes the caller must tell apart: + * - [org.dashfoundation.dashsdk.errors.DashSdkError.NotFound]: Platform + * does not know the identity; nothing was signed or sent. + * - [org.dashfoundation.dashsdk.errors.DashSdkError.PlatformWallet.IdentityLookupFailed]: + * the identity could not be read from Platform; nothing was signed or + * sent, and the call can be retried. + * - [org.dashfoundation.dashsdk.errors.DashSdkError.PlatformWallet.TransactionBroadcastUnconfirmed]: + * the top-up may have executed or may still execute; do not submit it + * again, the next sync settles it. */ suspend fun topUpExternalIdentityFromAddresses( walletHandle: Long, diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt index 2b3697cc099..94a608dd5c4 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt @@ -38,20 +38,44 @@ class ExternalIdentityTopUpTest { @Test fun `should map an unknown identity to NotFound`() = runTest { + val failure = failureFor(7) // ErrorIdentityNotFound + + assertTrue("expected NotFound, got $failure", failure is DashSdkError.NotFound) + } + + @Test + fun `should map a failed identity lookup to a retryable IdentityLookupFailed`() = runTest { + val failure = failureFor(80) // ErrorIdentityLookupFailed + + assertTrue( + "expected IdentityLookupFailed, got $failure", + failure is DashSdkError.PlatformWallet.IdentityLookupFailed, + ) + assertTrue((failure as DashSdkError).isRetryable) + } + + @Test + fun `should map an unproved result to TransactionBroadcastUnconfirmed`() = runTest { + val failure = failureFor(20) // ErrorTransactionBroadcastUnconfirmed + + assertTrue( + "expected TransactionBroadcastUnconfirmed, got $failure", + failure is DashSdkError.PlatformWallet.TransactionBroadcastUnconfirmed, + ) + } + + private suspend fun failureFor(platformWalletCode: Int): Throwable? { val credits = IdentityCredits( externalTopUpNative = AddressTopUpNativeCall { _, _, _, _ -> throw DashSDKException( - DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 7, // ErrorIdentityNotFound - "identity not found", + DashSdkError.PLATFORM_WALLET_CODE_OFFSET + platformWalletCode, + "native failure $platformWalletCode", ) }, ) - - val failure = runCatching { + return runCatching { credits.topUpExternalIdentityFromAddresses(1L, identityId, inputs, 2L) }.exceptionOrNull() - - assertTrue("expected NotFound, got $failure", failure is DashSdkError.NotFound) } @Test From 1a2d6bfd7b173192f7b82bcbfc062228c027602e Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Sun, 15 Nov 2026 23:29:47 -0800 Subject: [PATCH 4/4] fix(kotlin-sdk): return an external top-up that completes after cancellation The native top-up cannot observe coroutine cancellation, so it can pay the identity after the caller was cancelled. gate.op's withContext then threw CancellationException and dropped the balance, and a retry would fetch fresh nonces and pay again. Use opReturningCompletedResult, as the platform-address transfers and withdrawals do. The regression test cancels the caller while the injected native call is blocked; it fails with gate.op. Co-Authored-By: Claude Opus 5.5 --- .../dashsdk/credits/IdentityCredits.kt | 8 +++- .../credits/ExternalIdentityTopUpTest.kt | 41 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt index c9a63f1f5f3..c6f1871af8e 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt @@ -1,6 +1,7 @@ package org.dashfoundation.dashsdk.credits import org.dashfoundation.dashsdk.wallet.op +import org.dashfoundation.dashsdk.wallet.opReturningCompletedResult import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @@ -263,13 +264,18 @@ class IdentityCredits internal constructor( * - [org.dashfoundation.dashsdk.errors.DashSdkError.PlatformWallet.TransactionBroadcastUnconfirmed]: * the top-up may have executed or may still execute; do not submit it * again, the next sync settles it. + * + * The native call cannot observe coroutine cancellation, so a top-up can + * finish after the caller was cancelled; its balance is then returned + * rather than thrown away ([opReturningCompletedResult]), so a completed + * payment is never hidden and retried. */ suspend fun topUpExternalIdentityFromAddresses( walletHandle: Long, identityId: ByteArray, inputs: List, signerHandle: Long, - ): Long = gate.op { + ): Long = gate.opReturningCompletedResult { mapNativeErrors { externalTopUpNative.call( walletHandle, diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt index 94a608dd5c4..d57df9e8df6 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt @@ -1,8 +1,16 @@ package org.dashfoundation.dashsdk.credits +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withTimeout import org.dashfoundation.dashsdk.errors.DashSdkError import org.dashfoundation.dashsdk.ffi.DashSDKException +import org.dashfoundation.dashsdk.wallet.TeardownGate +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue @@ -64,6 +72,39 @@ class ExternalIdentityTopUpTest { ) } + @Test + fun `should return a top-up that completes after the caller was cancelled`() = runBlocking { + for (gate in listOf(TeardownGate(), null)) { + val entered = CountDownLatch(1) + val release = CountDownLatch(1) + val received = CompletableDeferred() + val credits = IdentityCredits( + gate = gate, + externalTopUpNative = AddressTopUpNativeCall { _, _, _, _ -> + entered.countDown() + // The native top-up does not observe cancellation; it pays + // the identity only after the caller has been cancelled. + release.await() + 9_000L + }, + ) + + val call = launch(Dispatchers.Default) { + received.complete( + credits.topUpExternalIdentityFromAddresses(1L, identityId, inputs, 2L), + ) + } + assertTrue("native top-up never started", entered.await(5, TimeUnit.SECONDS)) + call.cancel() + release.countDown() + withTimeout(5_000) { call.join() } + + assertTrue("completed top-up was dropped", received.isCompleted) + assertEquals(9_000L, received.await()) + gate?.let { withTimeout(5_000) { it.closeAndAwait() } } + } + } + private suspend fun failureFor(platformWalletCode: Int): Throwable? { val credits = IdentityCredits( externalTopUpNative = AddressTopUpNativeCall { _, _, _, _ ->