Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions packages/dashpay-contract/schema/v2/dashpay.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@
"maxItems": 21,
"description": "Platform address in storage form (type byte 0x00 P2PKH / 0x01 P2SH followed by the 20-byte HASH160, i.e. RIPEMD160 of SHA256, of the public key or redeem script) for public payments. The type byte is consensus-enforced by a data trigger.",
"position": 6
},
"shieldedAddress": {
"type": "array",
"byteArray": true,
"minItems": 43,
"maxItems": 43,
"description": "Raw Orchard receiving address: 11-byte diversifier followed by 32-byte diversified transmission key. Clients validate before payment; wallets should use a dedicated tip account.",
"position": 7
}
},
"minProperties": 1,
Expand Down
3 changes: 2 additions & 1 deletion packages/dashpay-contract/src/v2/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use serde_json::Value;

// Document-type name and property constants live in `crate::v1::document_types`;
// v2 does not change any names v1 defined, it only adds the optional
// `corePaymentAddress` / `platformPaymentAddress` properties to `profile`.
// `corePaymentAddress`, `platformPaymentAddress`, and `shieldedAddress`
// properties to `profile`.

pub fn load_documents_schemas() -> Result<Value, Error> {
serde_json::from_str(include_str!("../../schema/v2/dashpay.schema.json"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ data class DashPayProfile(
val displayName: String?,
val publicMessage: String?,
val avatarUrl: String?,
val corePaymentAddress: String? = null,
val platformPaymentAddress: String? = null,
val shieldedAddress: String? = null,
)

/** Parse a `getProfile` / `getContactProfile` JSON object, or null. */
Expand All @@ -32,6 +35,9 @@ fun parseDashPayProfile(json: String?): DashPayProfile? {
displayName = obj.optStringOrNull("displayName"),
publicMessage = obj.optStringOrNull("publicMessage"),
avatarUrl = obj.optStringOrNull("avatarUrl"),
corePaymentAddress = obj.optStringOrNull("corePaymentAddress"),
platformPaymentAddress = obj.optStringOrNull("platformPaymentAddress"),
shieldedAddress = obj.optStringOrNull("shieldedAddress"),
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
Expand Down Expand Up @@ -39,14 +40,20 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import java.math.BigDecimal
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.dashfoundation.dashsdk.tokens.PaymentAddressUpdate
import org.dashfoundation.example.di.LocalAppContainer
import org.dashfoundation.example.ui.components.FormSection
import org.dashfoundation.example.ui.components.LabeledContent
import org.dashfoundation.example.ui.components.SubmitButton
import org.dashfoundation.example.util.Base58
import org.dashfoundation.example.util.DashAddress
import org.dashfoundation.example.util.DashAddressType
import org.dashfoundation.example.util.generateQrBitmap
import org.dashfoundation.example.util.hexToBytes

Expand All @@ -72,7 +79,19 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController
val walletId = identity?.walletId
val wallet = remember(manager, walletId) { walletId?.let { manager?.wallet(forWalletId = it) } }

val tipAccount = remember(manager, identity?.identityIndex) {
identity?.identityIndex?.let { index -> runCatching { manager?.shieldedTipAccountIndex(index) }.getOrNull() }
}
val tipBalance by remember(walletId, tipAccount) {
if (walletId == null || tipAccount == null) flowOf(0L)
else container.database.shieldedDao().observeNotesByWalletAccount(walletId, tipAccount)
.map { notes -> notes.filter { !it.isSpent }.sumOf { it.value } }
}.collectAsStateWithLifecycle(initialValue = 0L)

var profile by remember { mutableStateOf<DashPayProfile?>(null) }
val publishedTipAddress = profile?.shieldedAddress?.let { raw ->
manager?.let { m -> runCatching { DashAddress.encodeOrchard(raw.hexToBytes(), m.network) }.getOrNull() }
}
var profileExists by remember { mutableStateOf(false) }
var qrUri by remember { mutableStateOf<String?>(null) }
var qrError by remember { mutableStateOf<String?>(null) }
Expand All @@ -87,6 +106,7 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController
var displayNameField by remember { mutableStateOf("") }
var publicMessageField by remember { mutableStateOf("") }
var avatarUrlField by remember { mutableStateOf("") }
var shieldedAddressField by remember { mutableStateOf("") }
var isSaving by remember { mutableStateOf(false) }
var saveError by remember { mutableStateOf<String?>(null) }

Expand Down Expand Up @@ -132,6 +152,7 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController
displayNameField = profile?.displayName.orEmpty()
publicMessageField = profile?.publicMessage.orEmpty()
avatarUrlField = profile?.avatarUrl.orEmpty()
shieldedAddressField = publishedTipAddress.orEmpty()
saveError = null
}
isEditing = !isEditing
Expand Down Expand Up @@ -172,6 +193,31 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController
label = { Text("Avatar URL") },
singleLine = true,
)
TextButton(enabled = !isSaving && container.shieldedService.isAvailable, onClick = {
val m = manager ?: return@TextButton
val wid = walletId ?: return@TextButton
isSaving = true
saveError = null
scope.launch {
try {
shieldedAddressField = requireNotNull(DashAddress.encodeOrchard(m.prepareShieldedTipAddress(wid, idBytes), m.network))
} catch (e: Exception) {
saveError = e.message ?: "Could not prepare tip account"
} finally {
isSaving = false
}
}
}, modifier = Modifier.testTag("dashpay.profile.useTipAccount")) {
Text("Use this wallet’s dedicated tip account")
}
Text("The address is published only when you save.", style = MaterialTheme.typography.bodySmall)
OutlinedTextField(
value = shieldedAddressField,
onValueChange = { shieldedAddressField = it },
modifier = Modifier.fillMaxWidth().testTag("dashpay.profile.shieldedAddress"),
label = { Text("Shielded tip address") },
supportingText = { Text("Paste an external receiving address, or leave blank to disable tips. External funds are managed by the receiving wallet.") },
)
saveError?.let {
Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
}
Expand All @@ -194,6 +240,15 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController
avatarUrl = avatarUrlField.trim().ifEmpty { null },
doCreate = !profileExists,
signerHandle = m.signerHandle,
shieldedAddress = when (val address = shieldedAddressField.trim()) {
publishedTipAddress.orEmpty() -> PaymentAddressUpdate.Keep
"" -> PaymentAddressUpdate.Remove
else -> {
val parsed = DashAddress.parse(address, m.network) as? DashAddressType.Orchard
?: throw IllegalArgumentException("Enter a shielded address for this network")
PaymentAddressUpdate.Set(parsed.raw43)
}
},
)
loadProfile()
isEditing = false
Expand Down Expand Up @@ -224,6 +279,19 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController
}
}

if (!isEditing) {
FormSection(title = "Shielded tips") {
Text("This wallet’s tip balance: ${BigDecimal.valueOf(tipBalance, 11).stripTrailingZeros().toPlainString()} DASH")
val address = publishedTipAddress
if (address == null) {
Text("Tips are not enabled.")
} else {
SelectionContainer { Text(address, style = MaterialTheme.typography.bodySmall) }
Text("This receiving address is public and associated with your username. Removing it does not revoke previously shared copies.", style = MaterialTheme.typography.bodySmall)
}
}
}

FormSection(title = "Identity") {
Text(
Base58.encode(idBytes),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ fun DashPayTabScreen(navController: NavHostController) {
val appUiState = container.appUiState
var claimSheetUri by remember { mutableStateOf<String?>(null) }
var showClaimSheet by remember { mutableStateOf(false) }
var showTipSheet by remember { mutableStateOf(false) }
val pendingInvite by appUiState.pendingInviteUri.collectAsStateWithLifecycle()
val claimInFlight by appUiState.invitationClaimInFlight.collectAsStateWithLifecycle()
// The parked URI is NOT cleared at seeding: it stays in AppUiState (the
Expand Down Expand Up @@ -320,7 +321,31 @@ fun DashPayTabScreen(navController: NavHostController) {
onError = { unlockError = it },
)

val tipManager = manager
val tipWalletId = identity.walletId
val tipAccountResult = remember(tipManager, identity.identityIndex) {
runCatching { requireNotNull(tipManager).shieldedTipAccountIndex(identity.identityIndex) }
}
val tipAccount = tipAccountResult.getOrNull()
if (showTipSheet && managed != null && tipManager != null && tipWalletId != null && tipAccount != null) {
ModalBottomSheet(onDismissRequest = { showTipSheet = false }) {
ShieldedTipSheet(tipManager, managed, tipWalletId, tipAccount)
}
Comment on lines +330 to +333

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.

🟡 Suggestion: Preserve the submission guard when dismissing an in-flight tip

ModalBottomSheet can be dismissed while a tip is being sent, and its dismissal removes ShieldedTipSheet from composition. That discards the remember-backed submitted flag and cancels the sheet's coroutine scope. PlatformWalletManager.sendShieldedTip runs the blocking JNI call through TeardownGate on Dispatchers.IO; cancellation does not stop an already-running native call from proving and broadcasting. Reopening the sheet therefore creates submitted=false and allows another payment without knowing the first payment's outcome. Note reservations prevent reuse of the same inputs, not a second payment funded by other available notes. Hoist the in-flight and uncertain-outcome state outside the dismissible composable, and prevent dismissal during the native send, including gesture-driven sheet hiding.

source: ['claude']

}
FormSection(title = "DashPay") {
if (container.shieldedService.isAvailable) {
EntityRow(
icon = Icons.AutoMirrored.Filled.Send,
title = "Send shielded tip",
onClick = {
tipAccountResult.fold(
onSuccess = { showTipSheet = true },
onFailure = { unlockError = it.message ?: "Could not open shielded tips" },
)
},
modifier = Modifier.testTag("dashpay.sendShieldedTip"),
)
}
EntityRow(
icon = Icons.Default.Group,
title = "Contacts",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package org.dashfoundation.example.ui.dashpay

import org.dashfoundation.dashsdk.errors.DashSdkError

/**
* Permit a fresh user review only for failures known not to have executed a tip.
* On the tip path, Rust maps selection/build/recipient-check failures to
* WalletOperation. Broadcast ambiguity maps to ShieldedSpendUnconfirmed, and
* successful post-broadcast bookkeeping is best-effort (never WalletOperation).
* Unknown exceptions, including JNI failures and cancellation, remain locked.
*/
internal fun canReviewShieldedTipAfterFailure(error: Exception): Boolean = when (error) {
is IllegalArgumentException,
is DashSdkError.InvalidParameter,
is DashSdkError.PlatformWallet.InvalidHandle,
is DashSdkError.PlatformWallet.NotFound,
is DashSdkError.PlatformWallet.SigningKeyUnavailable,
is DashSdkError.PlatformWallet.WalletOperation,
is DashSdkError.PlatformWallet.ShieldedNoRecordedAnchor,
is DashSdkError.PlatformWallet.ShieldedBroadcastFailed -> true
// ErrorInvalidParameter is a preflight-only FFI failure on this call path.
is DashSdkError.PlatformWallet.Generic -> error.nativeCode == 2
else -> false
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package org.dashfoundation.example.ui.dashpay

import android.content.Context
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Checkbox
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import java.math.BigDecimal
import kotlinx.coroutines.launch
import org.dashfoundation.dashsdk.tokens.ShieldedTipRecipient
import org.dashfoundation.dashsdk.tokens.ShieldedTipRecipientHistory
import org.dashfoundation.dashsdk.wallet.ManagedPlatformWallet
import org.dashfoundation.dashsdk.wallet.PlatformWalletManager
import org.dashfoundation.example.ui.components.SubmitButton
import org.dashfoundation.example.util.Base58
import org.dashfoundation.example.util.DashAddress

/** Username tipping uses the same verified recipient and confirmation boundary as Swift. */
@Composable
fun ShieldedTipSheet(manager: PlatformWalletManager, wallet: ManagedPlatformWallet, walletId: ByteArray, tipAccount: Int) {
val scope = rememberCoroutineScope()
val context = LocalContext.current
val history = remember(context) {
ShieldedTipRecipientHistory(context.getSharedPreferences("dashpay.tipRecipients", Context.MODE_PRIVATE))
}
var changedRecipient by remember { mutableStateOf<ShieldedTipRecipient?>(null) }
var username by remember { mutableStateOf("") }
var amount by remember { mutableStateOf("") }
var recipient by remember { mutableStateOf<ShieldedTipRecipient?>(null) }
var confirmedAmount by remember { mutableStateOf<Long?>(null) }
var busy by remember { mutableStateOf(false) }
var submitted by remember { mutableStateOf(false) }
var spendTips by remember { mutableStateOf(false) }
var message by remember { mutableStateOf<String?>(null) }

changedRecipient?.let { changed ->
AlertDialog(
onDismissRequest = { changedRecipient = null },
title = { Text("Tip recipient changed") },
text = { Text("The identity or shielded address for this username differs from your previous confirmation. Verify the change with the recipient before continuing.") },
confirmButton = {
TextButton(onClick = { recipient = changed; changedRecipient = null }) { Text("Review new recipient") }
},
dismissButton = {
TextButton(onClick = { changedRecipient = null }) { Text("Cancel") }
},
)
}

Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text("Send a shielded tip")
OutlinedTextField(username, { username = it; recipient = null }, label = { Text("Username") }, enabled = !busy && !submitted)
OutlinedTextField(amount, { amount = it; recipient = null }, label = { Text("Amount (DASH)") }, enabled = !busy && !submitted)
Row {
Checkbox(checked = spendTips, enabled = !busy && !submitted,
onCheckedChange = { spendTips = it; recipient = null })
Text("Spend from my dedicated tip account")
}
recipient?.let {
Text("Recipient: ${Base58.encode(it.identityId)}")
DashAddress.encodeOrchard(it.address, manager.network)?.let { address ->
SelectionContainer { Text(address) }
}
Text("Send $amount DASH from your ${if (spendTips) "tip" else "main shielded"} account to $username?")
}
message?.let { Text(it) }
SubmitButton(
text = if (recipient == null) "Review tip" else "Confirm and send",
isLoading = busy, enabled = !busy && !submitted && changedRecipient == null, modifier = Modifier.fillMaxWidth(),
) {
busy = true
message = null
scope.launch {
try {
val selected = recipient
if (selected == null) {
val credits = BigDecimal(amount.trim()).movePointRight(11).longValueExact()
require(credits > 0) { "Enter a positive amount" }
confirmedAmount = credits
val resolved = wallet.dashpay.resolveShieldedTip(username.trim())
if (history.hasChanged(manager.network, walletId, username, resolved)) {
changedRecipient = resolved
} else {
recipient = resolved
}
} else {
// Ambiguous or unclassified outcomes remain locked; definitive failures permit a fresh review.
history.confirm(manager.network, walletId, username, selected)
submitted = true
Comment thread
coderabbitai[bot] marked this conversation as resolved.
manager.sendShieldedTip(walletId, username.trim(), selected, requireNotNull(confirmedAmount), account = if (spendTips) tipAccount else 0)
message = "Shielded tip sent."
}
} catch (e: Exception) {
message = e.message ?: "Unable to send tip"
if (canReviewShieldedTipAfterFailure(e)) submitted = false
recipient = null
} finally { busy = false }
}
}
}
}
Loading
Loading