feat(wallet): a form to propose a spend from the group's wallet (Phase 8, part 2)

GroupSendRoute and GroupSendScreen, behind a Send button on the wallet
screen for a member who holds a share and has a node to see the coins
with. Address, amount or send everything, and a feerate prefilled from
Electrum's six-block estimate. The preview is GroupSpendBuilder over the
same inputs the proposal is built from -- what leaves, the fee, what
comes back as change, or why it cannot be built -- and proposing moves
onto the signing session, replacing the form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-10-23 08:38:19 +02:00
1 parent 6d066e19c0
commit b1d5963b53
10 files changed
+682

No files matched your search

@@ -822,4 +822,20 @@
<string name="fee_s_sats_at_s_sats_per_byte">Fee: %1$s sats, at %2$s sats per byte</string>
<string name="spends_s_of_the_group_s_coins">Spends %1$s of the group's coins</string>
<string name="signed_by_the_group_any_member_can_send_it">Signed by the group, not by you. Once enough members sign, any member's device can send it to the network.</string>
<string name="send">Send</string>
<string name="send_from_the_group_s_wallet">Send from the group's wallet</string>
<string name="address">Address</string>
<string name="amount_in_sats">Amount in sats</string>
<string name="send_everything">Send everything</string>
<string name="feerate_in_sats_per_byte">Fee rate in sats per byte</string>
<string name="ask_the_group_to_send">Ask the group to send</string>
<string name="sends_s_sats_with_a_fee_of_s_sats">Sends %1$s sats, with a fee of %2$s sats.</string>
<string name="s_sats_come_back_to_the_group_as_change">%1$s sats come back to the group as change.</string>
<string name="that_isn_t_an_address_on_s">That isn't an address on %1$s.</string>
<string name="the_group_has_nothing_confirmed_to_spend">The group has nothing confirmed to spend yet.</string>
<string name="the_group_doesn_t_have_that_much_confirmed">The group doesn't have that much confirmed, after the fee.</string>
<string name="that_is_too_little_to_send">That is too little to send: the network won't relay an output that small.</string>
<string name="couldn_t_ask_the_group_to_send">Couldn't ask the group to send.</string>
<string name="sending_needs_a_share_and_a_node">Sending needs a share of the group's key, and a wallet of your own on this profile to see the group's coins with.</string>
<string name="nothing_leaves_until_a_quorum_signs">Nothing leaves the wallet until a quorum of members has seen this spend and signed it.</string>
</resources>
@@ -0,0 +1,264 @@
package com.machankura.bennu.compose.ui.composable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.input.TextFieldLineLimits
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountBalanceWallet
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.lifecycle.viewmodel.compose.viewModel
import bennu.composeapp.generated.resources.Res
import bennu.composeapp.generated.resources.address
import bennu.composeapp.generated.resources.amount_in_sats
import bennu.composeapp.generated.resources.ask_the_group_to_send
import bennu.composeapp.generated.resources.couldn_t_ask_the_group_to_send
import bennu.composeapp.generated.resources.feerate_in_sats_per_byte
import bennu.composeapp.generated.resources.finding_the_group_s_coins
import bennu.composeapp.generated.resources.nothing_leaves_until_a_quorum_signs
import bennu.composeapp.generated.resources.s_sats_come_back_to_the_group_as_change
import bennu.composeapp.generated.resources.send_everything
import bennu.composeapp.generated.resources.send_from_the_group_s_wallet
import bennu.composeapp.generated.resources.sending_needs_a_share_and_a_node
import bennu.composeapp.generated.resources.sends_s_sats_with_a_fee_of_s_sats
import bennu.composeapp.generated.resources.that_is_too_little_to_send
import bennu.composeapp.generated.resources.that_isn_t_an_address_on_s
import bennu.composeapp.generated.resources.the_group_doesn_t_have_that_much_confirmed
import bennu.composeapp.generated.resources.the_group_has_nothing_confirmed_to_spend
import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent
import com.machankura.bennu.compose.repository.ChatRepository
import com.machankura.bennu.compose.repository.FrostSigningRepository
import com.machankura.bennu.compose.text.grouped
import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.Route
import com.machankura.bennu.compose.ui.composable.widgets.Decorative
import com.machankura.bennu.compose.ui.composable.widgets.EmptyState
import com.machankura.bennu.compose.ui.composable.widgets.ErrorState
import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator
import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState
import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton
import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition
import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier
import com.machankura.bennu.compose.ui.theme.readableContent
import com.machankura.bennu.compose.ui.theme.spacing
import com.machankura.bennu.compose.ui.view.model.GroupSendViewModel
import com.machankura.bennu.compose.ui.view.state.GroupSendUIState
import com.machankura.bennu.compose.wallet.GroupChainWallets
import com.machankura.bennu.compose.wallet.GroupSpendBuilder
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import fr.acinq.bitcoin.Chain
import org.jetbrains.compose.resources.stringResource
/**
* A spend from the group's wallet, proposed.
*
* The form says what it would build as it is filled in -- what leaves, the fee,
* what comes back as change -- from the same build the proposal is made of, so
* nothing a member reads here is an estimate of something else. Proposing it
* moves onto the signing session: nothing has left the wallet, and nothing will
* until a quorum has seen it and signed.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GroupSendScreen(
activeUserPublicKey: HexKey,
chatRoomId: String,
chain: Chain,
initialGroupSendUIState: GroupSendUIState = GroupSendUIState.Loading,
chatRepository: ChatRepository,
frostSigningRepository: FrostSigningRepository,
wallets: GroupChainWallets?,
onNavigateToRouteAndPopUpInclusive: (Route) -> Unit,
onNavigateBack: () -> Unit,
) {
val groupSendViewModel: GroupSendViewModel = viewModel(
factory = GroupSendViewModel.factory(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId,
chain = chain,
initialGroupSendUIState = initialGroupSendUIState,
chatRepository = chatRepository,
frostSigningRepository = frostSigningRepository,
wallets = wallets,
)
)
LaunchedEffect(true) {
if (initialGroupSendUIState == GroupSendUIState.Loading) groupSendViewModel.initiate()
}
val notify = rememberNotifier(rememberCoroutineScope())
val couldNotSend = stringResource(Res.string.couldn_t_ask_the_group_to_send)
Scaffold(
snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
topBar = {
TopAppBar(
title = {
Text(
text = stringResource(Res.string.send_from_the_group_s_wallet),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
navigationIcon = { NavigateBackButton(onNavigateBack) }
)
}
) { padding ->
ScreenStateTransition(groupSendViewModel.groupSendUIState) { uiState ->
when (val state = uiState) {
is GroupSendUIState.Error -> ErrorState(
modifier = Modifier.padding(padding),
message = state.message,
onRetry = null
)
GroupSendUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding))
GroupSendUIState.Unavailable -> EmptyState(
modifier = Modifier.padding(padding).readableContent(),
message = stringResource(Res.string.sending_needs_a_share_and_a_node),
icon = Icons.Default.AccountBalanceWallet,
)
is GroupSendUIState.Ready -> Column(
modifier = Modifier.padding(padding).readableContent().fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(MaterialTheme.spacing.screenMargin),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)
) {
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
state = groupSendViewModel.addressField,
lineLimits = TextFieldLineLimits.SingleLine,
label = { Text(stringResource(Res.string.address)) },
)
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(stringResource(Res.string.send_everything))
Switch(
checked = groupSendViewModel.sendEverything.value,
onCheckedChange = { groupSendViewModel.sendEverything.value = it },
)
}
if (!groupSendViewModel.sendEverything.value) {
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
state = groupSendViewModel.amountField,
lineLimits = TextFieldLineLimits.SingleLine,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
label = { Text(stringResource(Res.string.amount_in_sats)) },
)
}
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
state = groupSendViewModel.feerateField,
lineLimits = TextFieldLineLimits.SingleLine,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
label = { Text(stringResource(Res.string.feerate_in_sats_per_byte)) },
)
if (state.walletState == null) {
LoadingDataIndicator(fillScreen = false, text = stringResource(Res.string.finding_the_group_s_coins))
}
val preview = groupSendViewModel.preview()
preview?.let { SendPreview(it, chain) }
Text(
text = stringResource(Res.string.nothing_leaves_until_a_quorum_signs),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Button(
enabled = preview is GroupSpendBuilder.Result.Built && !groupSendViewModel.isActionPending.value,
onClick = {
groupSendViewModel.propose(
onSuccess = { sessionId ->
// Onto the session: the spend exists once it is
// signed, and this form has done its part.
onNavigateToRouteAndPopUpInclusive(
FrostSigningRoute(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId,
sessionId = sessionId,
)
)
},
onFailure = { notify(couldNotSend) },
)
}
) {
Icon(Icons.Default.Send, contentDescription = Decorative)
Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
Text(stringResource(Res.string.ask_the_group_to_send))
}
}
}
}
}
}
/** What the form would build, or why it cannot. */
@Composable
private fun SendPreview(result: GroupSpendBuilder.Result, chain: Chain) {
when (result) {
is GroupSpendBuilder.Result.Built -> Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) {
Text(
text = stringResource(Res.string.sends_s_sats_with_a_fee_of_s_sats, result.amount.grouped(), result.fee.grouped()),
style = MaterialTheme.typography.bodyLarge,
)
result.change?.let { change ->
Text(
text = stringResource(Res.string.s_sats_come_back_to_the_group_as_change, change.grouped()),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
else -> Text(
text = when (result) {
GroupSpendBuilder.Result.NotAnAddress ->
stringResource(Res.string.that_isn_t_an_address_on_s, GroupWalletStatementEvent.chainName(chain))
GroupSpendBuilder.Result.NothingToSpend -> stringResource(Res.string.the_group_has_nothing_confirmed_to_spend)
GroupSpendBuilder.Result.NotEnough -> stringResource(Res.string.the_group_doesn_t_have_that_much_confirmed)
else -> stringResource(Res.string.that_is_too_little_to_send)
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.error,
)
}
}
@@ -1,5 +1,8 @@
package com.machankura.bennu.compose.ui.composable
import androidx.compose.material.icons.filled.Send
import bennu.composeapp.generated.resources.send
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupSendRoute
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
@@ -203,6 +206,19 @@ fun GroupWalletScreen(
modifier = Modifier.padding(padding),
state = state,
notify = notify,
// Behind both gates: a share to propose with, and a node to
// see the coins with -- a spend built blind is not one.
onSend = if (state.canSign && state.canWatch) {
{
onNavigateToRoute(
GroupSendRoute(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId,
relayHint = null
)
)
}
} else null,
)
}
}
@@ -243,6 +259,7 @@ private fun OpenWallet(
modifier: Modifier,
state: GroupWalletUIState.Loaded,
notify: (String) -> Unit,
onSend: (() -> Unit)?,
) {
val clipboardManager = LocalClipboardManager.current
val addressCopied = stringResource(Res.string.address_copied)
@@ -256,6 +273,16 @@ private fun OpenWallet(
) {
item { BalanceCard(walletState) }
onSend?.let { send ->
item {
Button(onClick = send) {
Icon(Icons.Default.Send, contentDescription = Decorative)
Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
Text(stringResource(Res.string.send))
}
}
}
when {
!state.canWatch -> item {
Text(
@@ -1,5 +1,7 @@
package com.machankura.bennu.compose.ui.composable.navigation
import com.machankura.bennu.compose.ui.composable.GroupSendScreen
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupSendRoute
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.material3.MaterialTheme
@@ -1246,6 +1248,28 @@ fun BennuNavHost(
}
)
}
composable<GroupSendRoute> { backStackEntry ->
val route = backStackEntry.toRoute<GroupSendRoute>()
GroupSendScreen(
activeUserPublicKey = route.activeUserPublicKey,
chatRoomId = route.chatRoomId,
chain = NodeParamsManager.chain,
chatRepository = databaseChatRepository,
frostSigningRepository = databaseFrostSigningRepository,
wallets = groupChainWallets,
onNavigateToRouteAndPopUpInclusive = { signingRoute ->
// Replace the form so back returns to the wallet rather
// than to a spend that has already been proposed.
navController.navigate(route = signingRoute) {
popUpTo<GroupSendRoute> { inclusive = true }
}
},
onNavigateBack = {
navController.popBackStack()
}
)
}
composable<GroupPostsRoute> { backStackEntry ->
val route = backStackEntry.toRoute<GroupPostsRoute>()
@@ -0,0 +1,11 @@
package com.machankura.bennu.compose.ui.composable.navigation.routes
import kotlinx.serialization.Serializable
/** The form a member proposes a spend from the group's wallet with. */
@Serializable
data class GroupSendRoute(
val activeUserPublicKey: String,
val chatRoomId: String,
val relayHint: String?
): Route()
@@ -0,0 +1,157 @@
package com.machankura.bennu.compose.ui.view.model
import androidx.compose.foundation.text.input.TextFieldState
import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import co.touchlab.kermit.Logger
import com.machankura.bennu.compose.repository.ChatRepository
import com.machankura.bennu.compose.repository.FrostSigningRepository
import com.machankura.bennu.compose.ui.view.state.GroupSendUIState
import com.machankura.bennu.compose.wallet.GroupChainWallets
import com.machankura.bennu.compose.wallet.GroupSpendBuilder
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import fr.acinq.bitcoin.Chain
import fr.acinq.bitcoin.Satoshi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* A spend from the group's wallet, built as the member types and proposed when
* they ask.
*
* The preview the screen shows is [preview] over the same inputs the proposal is
* built from, so the fee a member reads before pressing the button is the fee
* the group is then asked to sign -- there is no second build.
*/
class GroupSendViewModel(
val activeUserPublicKey: HexKey,
val chatRoomId: String,
val chain: Chain,
initialGroupSendUIState: GroupSendUIState,
val chatRepository: ChatRepository,
val frostSigningRepository: FrostSigningRepository,
private val wallets: GroupChainWallets?,
): ViewModel() {
private val logger = Logger.withTag(TAG)
var groupSendUIState: GroupSendUIState by mutableStateOf(initialGroupSendUIState)
private set
val addressField = TextFieldState()
val amountField = TextFieldState()
val feerateField = TextFieldState()
val sendEverything: MutableState<Boolean> = mutableStateOf(false)
val isActionPending: MutableState<Boolean> = mutableStateOf(false)
private var watching: Job? = null
fun initiate() {
viewModelScope.launch(Dispatchers.IO) {
val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId)
if (localChatRoom == null) {
groupSendUIState = GroupSendUIState.Error("Couldn't find the group")
return@launch
}
val wallet = chatRepository.groupWallet(chatRoomId, chain)
val canSign = localChatRoom.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId)
if (wallet == null || !canSign || wallets == null) {
groupSendUIState = GroupSendUIState.Unavailable
return@launch
}
val ready = GroupSendUIState.Ready(
localChatRoom = localChatRoom,
wallet = wallet,
walletState = null,
reserved = frostSigningRepository.reservedOutPoints(chatRoomId),
)
groupSendUIState = ready
wallets.suggestedFeeratePerVbyte()?.let { suggested ->
withContext(Dispatchers.Main) {
if (feerateField.text.isEmpty()) feerateField.setTextAndPlaceCursorAtEnd(suggested.toString())
}
}
val chainWallet = wallets.walletFor(wallet.account)
watching?.cancel()
watching = viewModelScope.launch(Dispatchers.IO) {
chainWallet.state.collect { state -> groupSendUIState = ready.copy(walletState = state) }
}
}
}
/**
* The spend the form describes right now, or null while it is incomplete --
* no wallet state yet, no feerate, no amount.
*/
fun preview(): GroupSpendBuilder.Result? {
val state = groupSendUIState as? GroupSendUIState.Ready ?: return null
val walletState = state.walletState ?: return null
val feerate = feerateField.text.toString().trim().toLongOrNull()?.takeIf { it > 0 } ?: return null
val address = addressField.text.toString().trim().takeIf { it.isNotEmpty() } ?: return null
return if (sendEverything.value) {
GroupSpendBuilder.sendAll(walletState, address, feerate, state.reserved)
} else {
val amount = amountField.text.toString().filter { it.isDigit() }.toLongOrNull() ?: return null
GroupSpendBuilder.send(walletState, address, Satoshi(amount), feerate, state.reserved)
}
}
fun propose(onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) {
val state = groupSendUIState as? GroupSendUIState.Ready ?: return
val built = preview() as? GroupSpendBuilder.Result.Built ?: return
if (isActionPending.value) return
isActionPending.value = true
viewModelScope.launch(Dispatchers.IO) {
val session = runCatching {
frostSigningRepository.proposeSpend(
localChatRoom = state.localChatRoom,
userPublicKey = activeUserPublicKey,
psbt = built.psbt,
chain = chain,
)
}.onFailure { logger.e("Failed to propose a spend from $chatRoomId", it) }.getOrNull()
withContext(Dispatchers.Main) {
if (session != null) onSuccess(session.id) else onFailure()
}
isActionPending.value = false
}
}
companion object {
private const val TAG = "GroupSendViewModel"
fun factory(
activeUserPublicKey: HexKey,
chatRoomId: String,
chain: Chain,
initialGroupSendUIState: GroupSendUIState = GroupSendUIState.Loading,
chatRepository: ChatRepository,
frostSigningRepository: FrostSigningRepository,
wallets: GroupChainWallets?,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
GroupSendViewModel(
activeUserPublicKey, chatRoomId, chain, initialGroupSendUIState,
chatRepository, frostSigningRepository, wallets,
)
}
}
}
}
@@ -0,0 +1,27 @@
package com.machankura.bennu.compose.ui.view.state
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.nostr.wallet.GroupWallet
import com.machankura.bennu.compose.wallet.GroupWalletState
import fr.acinq.bitcoin.OutPoint
sealed interface GroupSendUIState {
/**
* A wallet this device can propose a spend from: it holds a share, and it has
* a node to see the coins with. [walletState] is null until Electrum answers.
*/
data class Ready(
val localChatRoom: LocalChatRoom,
val wallet: GroupWallet,
val walletState: GroupWalletState?,
/** The coins open spends already hold, which a new one leaves alone. */
val reserved: Set<OutPoint>,
): GroupSendUIState
/** A room this device cannot propose from -- no wallet, no share, or no node. */
data object Unavailable: GroupSendUIState
data class Error(val message: String): GroupSendUIState
data object Loading: GroupSendUIState
}
@@ -2,6 +2,7 @@ package com.machankura.bennu.compose.wallet
import com.machankura.bennu.compose.managers.GroupWalletDerivation
import fr.acinq.lightning.blockchain.electrum.IElectrumClient
import fr.acinq.lightning.blockchain.fee.FeeratePerByte
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
@@ -28,6 +29,14 @@ class GroupChainWallets(
wallets.getOrPut(account.xpub) { GroupChainWallet(account, electrum, scope) }
}
/**
* A feerate to start the send form at, in sats per virtual byte: Electrum's
* estimate for six blocks, or null when it has none. A suggestion the member
* edits, never a value a spend is built on without them seeing it.
*/
suspend fun suggestedFeeratePerVbyte(): Long? =
electrum.estimateFees(6)?.let { FeeratePerByte(it).feerate.sat }?.coerceAtLeast(1)
suspend fun stop() = mutex.withLock {
wallets.values.forEach { it.stop() }
wallets.clear()