feat(wallet): a screen to open a group's wallet and receive into it (Phase 5)

GroupWalletRoute and GroupWalletScreen, reached from a Group wallet row
on the group's screen. A group that has not opened a wallet gets an
empty state with, for a member who can sign, what opening one asks of
everybody -- including that shares are unencrypted at rest -- and the
button that proposes the statement. An open wallet shows the balance,
confirmed and on the way said apart, the next receive address as a
BIP21 QR code, selectable text and a copy button, the coins, and an
export of the two watch-only descriptors with what they give away.

The wallets are watched on the identity's own Electrum client and made
per PhoenixBusiness in BennuNavHost; a profile with no node sees the
wallet and is told it cannot watch the chain.

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:11:47 +02:00
1 parent 4ab47ba432
commit 24d06d2eee
13 files changed
+913

No files matched your search

@@ -788,4 +788,32 @@
<string name="you_already_have_a_chat_with_s">You already have a chat with %1$s.</string>
<string name="checking_whether_s_can_receive_messages_here">Checking whether %1$s can receive messages here.</string>
<string name="s_hasn_t_set_up_messaging_on_bennu_yet">%1$s hasn't set up messaging on Bennu yet. Try again later, or ask them to open Bennu.</string>
<!-- The group's on-chain wallet. -->
<string name="group_wallet">Group wallet</string>
<string name="open_a_group_wallet">Open a group wallet</string>
<string name="not_opened_yet">Not opened yet</string>
<string name="open_on_s">Open on %1$s</string>
<string name="this_group_has_not_opened_a_wallet">This group has not opened a wallet.</string>
<string name="opening_a_wallet_asks_the_group_to_agree">Opening a wallet asks the group to agree that it keeps coins here. Any quorum of members can then spend them together, and nobody can spend them alone.</string>
<string name="each_member_s_share_is_stored_unencrypted">Each member's share of the group's key is stored unencrypted on their device. Anyone with an unlocked device, or a copy of its data, holds that member's share.</string>
<string name="couldn_t_ask_the_group_to_open_a_wallet">Couldn't ask the group to open a wallet.</string>
<string name="balance">Balance</string>
<string name="s_sats">%1$s sats</string>
<string name="s_sats_on_the_way">%1$s sats on the way</string>
<string name="receive_address">Receive address</string>
<string name="copy_address">Copy address</string>
<string name="address_copied">Address copied</string>
<string name="finding_the_group_s_coins">Finding the group's coins…</string>
<string name="nothing_has_been_sent_to_this_wallet_yet">Nothing has been sent to this wallet yet.</string>
<string name="this_profile_cannot_watch_the_chain">This profile has no wallet of its own to watch the chain with, so the balance and the next address can't be shown here.</string>
<string name="coins">Coins</string>
<string name="change">Change</string>
<string name="received">Received</string>
<string name="waiting_for_a_confirmation">Waiting for a confirmation</string>
<string name="s_confirmations">%1$s confirmations</string>
<string name="s_dot_s">%1$s · %2$s</string>
<string name="balance_not_known_yet">Not known yet</string>
<string name="export_watch_only">Export watch-only</string>
<string name="watch_only_descriptors_copied">Watch-only descriptors copied</string>
<string name="anyone_with_these_can_see_every_address">Anyone with these can see every address of this wallet and its whole balance. They can't spend from it.</string>
</resources>
@@ -0,0 +1,16 @@
package com.machankura.bennu.compose.text
import fr.acinq.bitcoin.Satoshi
/**
* An amount in sats, its thousands grouped: `120,000`.
*
* Sats rather than bitcoin, everywhere the group's wallet shows an amount: a
* signer comparing a fee to an output is comparing two integers, and a decimal
* point eight places in is the easiest digit on the screen to misread.
*/
fun Satoshi.grouped(): String {
val digits = sat.toString().removePrefix("-")
val grouped = digits.reversed().chunked(3).joinToString(",").reversed()
return if (sat < 0) "-$grouped" else grouped
}
@@ -1,5 +1,11 @@
package com.machankura.bennu.compose.ui.composable
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletRoute
import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent
import bennu.composeapp.generated.resources.open_on_s
import bennu.composeapp.generated.resources.not_opened_yet
import bennu.composeapp.generated.resources.group_wallet
import androidx.compose.material.icons.filled.AccountBalanceWallet
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
@@ -515,6 +521,35 @@ fun ChatRoomDetailScreen(
)
}
// The group's coins. After the identity block's
// last signed row and before the paste, because it
// is signed by the same key and read by nobody
// outside the room: the statement opening it never
// leaves the group. Shown to every member, open or
// not -- the screen behind it is where a member who
// can sign asks the group to open one.
item {
SignedWorkRow(
icon = Icons.Default.AccountBalanceWallet,
headline = stringResource(Res.string.group_wallet),
supporting = chatRoomDetailUIState.groupWallet?.let { wallet ->
stringResource(
Res.string.open_on_s,
GroupWalletStatementEvent.chainName(wallet.chain)
)
} ?: stringResource(Res.string.not_opened_yet),
onOpen = {
onNavigateToRoute.invoke(
GroupWalletRoute(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId,
relayHint = relayHint
)
)
}
)
}
// The untyped way into everything above it. Each
// row opens a screen with a form that builds one
// kind of event; this takes any of those kinds as
@@ -0,0 +1,400 @@
package com.machankura.bennu.compose.ui.composable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountBalanceWallet
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.platform.LocalClipboardManager
import androidx.compose.ui.text.buildAnnotatedString
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_copied
import bennu.composeapp.generated.resources.anyone_with_these_can_see_every_address
import bennu.composeapp.generated.resources.balance
import bennu.composeapp.generated.resources.balance_not_known_yet
import bennu.composeapp.generated.resources.change
import bennu.composeapp.generated.resources.coins
import bennu.composeapp.generated.resources.copy_address
import bennu.composeapp.generated.resources.couldn_t_ask_the_group_to_open_a_wallet
import bennu.composeapp.generated.resources.each_member_s_share_is_stored_unencrypted
import bennu.composeapp.generated.resources.export_watch_only
import bennu.composeapp.generated.resources.finding_the_group_s_coins
import bennu.composeapp.generated.resources.group_wallet
import bennu.composeapp.generated.resources.nothing_has_been_sent_to_this_wallet_yet
import bennu.composeapp.generated.resources.open_a_group_wallet
import bennu.composeapp.generated.resources.opening_a_wallet_asks_the_group_to_agree
import bennu.composeapp.generated.resources.receive_address
import bennu.composeapp.generated.resources.received
import bennu.composeapp.generated.resources.s_confirmations
import bennu.composeapp.generated.resources.s_dot_s
import bennu.composeapp.generated.resources.s_sats
import bennu.composeapp.generated.resources.s_sats_on_the_way
import bennu.composeapp.generated.resources.this_group_has_not_opened_a_wallet
import bennu.composeapp.generated.resources.this_profile_cannot_watch_the_chain
import bennu.composeapp.generated.resources.waiting_for_a_confirmation
import bennu.composeapp.generated.resources.watch_only_descriptors_copied
import com.machankura.bennu.compose.managers.GroupWalletDerivation
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.QRCodeView
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.GroupWalletViewModel
import com.machankura.bennu.compose.ui.view.state.GroupWalletUIState
import com.machankura.bennu.compose.wallet.GroupChainWallets
import com.machankura.bennu.compose.wallet.bip21Uri
import com.machankura.bennu.compose.wallet.GroupUtxo
import com.machankura.bennu.compose.wallet.GroupWalletState
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import fr.acinq.bitcoin.Chain
import org.jetbrains.compose.resources.stringResource
/**
* The group's wallet: what it holds, where to pay it, and the coins themselves.
*
* Pushed from its row on the group's screen. A group that has not opened a
* wallet gets an empty state that says so -- and, for a member holding a share,
* the way to ask the group to open one, with what that asks of everybody.
*
* The address is the only thing on the screen a person acts on outside the app,
* so it is shown three ways: as a QR code, as selectable text, and on a copy
* button. Every one of them is derived on this device from the room's key; the
* statement the group signed is what says the wallet exists, never where it is.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GroupWalletScreen(
activeUserPublicKey: HexKey,
chatRoomId: String,
chain: Chain,
initialGroupWalletUIState: GroupWalletUIState = GroupWalletUIState.Loading,
chatRepository: ChatRepository,
frostSigningRepository: FrostSigningRepository,
wallets: GroupChainWallets?,
onNavigateToRoute: (Route) -> Unit,
onNavigateBack: () -> Unit,
) {
val groupWalletViewModel: GroupWalletViewModel = viewModel(
factory = GroupWalletViewModel.factory(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId,
chain = chain,
initialGroupWalletUIState = initialGroupWalletUIState,
chatRepository = chatRepository,
frostSigningRepository = frostSigningRepository,
wallets = wallets,
)
)
LaunchedEffect(true) {
if (initialGroupWalletUIState == GroupWalletUIState.Loading) {
groupWalletViewModel.initiate()
}
}
val notify = rememberNotifier(rememberCoroutineScope())
val couldNotOpen = stringResource(Res.string.couldn_t_ask_the_group_to_open_a_wallet)
Scaffold(
snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
topBar = {
TopAppBar(
title = {
Text(
text = stringResource(Res.string.group_wallet),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
navigationIcon = { NavigateBackButton(onNavigateBack) }
)
}
) { padding ->
ScreenStateTransition(groupWalletViewModel.groupWalletUIState) { uiState ->
when (val state = uiState) {
is GroupWalletUIState.Error -> {
// Nothing to retry: the room came from a navigation argument.
ErrorState(
modifier = Modifier.padding(padding),
message = state.message,
onRetry = null
)
}
GroupWalletUIState.Loading -> {
LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding))
}
is GroupWalletUIState.NotOpened -> {
EmptyState(
modifier = Modifier.padding(padding).readableContent(),
message = stringResource(Res.string.this_group_has_not_opened_a_wallet),
icon = Icons.Default.AccountBalanceWallet,
// Hidden rather than disabled, the way every gated way in
// on the group's screens is: a device with no share cannot
// propose, and a room with no key has nothing to open.
action = if (state.canSign && state.account != null) {
{
OpenWalletAction(
isPending = groupWalletViewModel.isActionPending.value,
onOpen = {
groupWalletViewModel.openWallet(
onSuccess = { sessionId ->
// Onto the session: the wallet does
// not exist until a quorum signs.
onNavigateToRoute(
FrostSigningRoute(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId,
sessionId = sessionId
)
)
},
onFailure = { notify(couldNotOpen) }
)
}
)
}
} else null
)
}
is GroupWalletUIState.Loaded -> {
OpenWallet(
modifier = Modifier.padding(padding),
state = state,
notify = notify,
)
}
}
}
}
}
/**
* What opening a wallet asks of the group, said before the button rather than
* after it: that any quorum can then spend together and nobody alone, and what
* an unencrypted share on a member's device means once there are coins behind it.
*/
@Composable
private fun OpenWalletAction(isPending: Boolean, onOpen: () -> Unit) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)
) {
Text(
text = stringResource(Res.string.opening_a_wallet_asks_the_group_to_agree),
style = MaterialTheme.typography.bodyMedium,
)
Text(
text = stringResource(Res.string.each_member_s_share_is_stored_unencrypted),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Button(onClick = onOpen, enabled = !isPending) {
Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative)
Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
Text(stringResource(Res.string.open_a_group_wallet))
}
}
}
@Composable
private fun OpenWallet(
modifier: Modifier,
state: GroupWalletUIState.Loaded,
notify: (String) -> Unit,
) {
val clipboardManager = LocalClipboardManager.current
val addressCopied = stringResource(Res.string.address_copied)
val descriptorsCopied = stringResource(Res.string.watch_only_descriptors_copied)
val walletState = state.walletState
LazyColumn(
modifier = modifier.readableContent().fillMaxSize()
.padding(MaterialTheme.spacing.screenMargin),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)
) {
item { BalanceCard(walletState) }
when {
!state.canWatch -> item {
Text(
text = stringResource(Res.string.this_profile_cannot_watch_the_chain),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
walletState?.receiveAddress == null -> item {
LoadingDataIndicator(
fillScreen = false,
text = stringResource(Res.string.finding_the_group_s_coins)
)
}
else -> {
val address = walletState.receiveAddress!!
item {
Card(modifier = Modifier.fillMaxWidth()) {
Column(
modifier = Modifier.padding(MaterialTheme.spacing.containerPadding),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)
) {
Text(
text = stringResource(Res.string.receive_address),
style = MaterialTheme.typography.titleMedium,
)
// BIP21, so a scanning wallet knows what the text is.
QRCodeView(bip21Uri(address))
SelectionContainer {
Text(text = address, style = MaterialTheme.typography.bodyMedium)
}
TextButton(
onClick = {
clipboardManager.setText(buildAnnotatedString { append(address) })
notify(addressCopied)
}
) {
Icon(Icons.Default.ContentCopy, contentDescription = Decorative)
Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
Text(stringResource(Res.string.copy_address))
}
}
}
}
item {
Text(
text = stringResource(Res.string.coins),
style = MaterialTheme.typography.titleMedium,
)
}
if (walletState.utxos.isEmpty()) {
item {
EmptyState(message = stringResource(Res.string.nothing_has_been_sent_to_this_wallet_yet))
}
} else {
items(walletState.utxos, key = { it.utxo.outPoint.toString() }) { utxo ->
CoinRow(utxo = utxo, confirmations = walletState.confirmations(utxo))
}
}
}
}
item {
Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) {
TextButton(
onClick = {
val account = state.wallet.account
clipboardManager.setText(
buildAnnotatedString {
append(account.receiveDescriptor)
append("\n")
append(account.changeDescriptor)
}
)
notify(descriptorsCopied)
}
) {
Icon(Icons.Default.Visibility, contentDescription = Decorative)
Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
Text(stringResource(Res.string.export_watch_only))
}
Text(
text = stringResource(Res.string.anyone_with_these_can_see_every_address),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
/** Confirmed and on-the-way said apart: only the first can be spent by a send-all. */
@Composable
private fun BalanceCard(walletState: GroupWalletState?) {
Card(modifier = Modifier.fillMaxWidth()) {
Column(
modifier = Modifier.padding(MaterialTheme.spacing.containerPadding),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)
) {
Text(
text = stringResource(Res.string.balance),
style = MaterialTheme.typography.titleMedium,
)
Text(
text = walletState?.let { stringResource(Res.string.s_sats, it.confirmedBalance.grouped()) }
?: stringResource(Res.string.balance_not_known_yet),
style = MaterialTheme.typography.headlineMedium,
)
walletState?.pendingBalance?.takeIf { it.sat > 0 }?.let { pending ->
Text(
text = stringResource(Res.string.s_sats_on_the_way, pending.grouped()),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
@Composable
private fun CoinRow(utxo: GroupUtxo, confirmations: Int) {
ListItem(
leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) },
headlineContent = { Text(stringResource(Res.string.s_sats, utxo.amount.grouped())) },
supportingContent = {
val branch = stringResource(
if (utxo.derivation.change == GroupWalletDerivation.CHANGE) Res.string.change else Res.string.received
)
val depth = if (confirmations == 0) {
stringResource(Res.string.waiting_for_a_confirmation)
} else {
stringResource(Res.string.s_confirmations, confirmations.toString())
}
Text(text = stringResource(Res.string.s_dot_s, branch, depth), maxLines = 1, overflow = TextOverflow.Ellipsis)
}
)
}
@@ -52,6 +52,7 @@ import com.machankura.bennu.compose.ui.composable.ProposeGroupEventScreen
import com.machankura.bennu.compose.ui.composable.EditGroupRelaysScreen
import com.machankura.bennu.compose.ui.composable.GroupNostrProfileScreen
import com.machankura.bennu.compose.ui.composable.GroupRelaysScreen
import com.machankura.bennu.compose.ui.composable.GroupWalletScreen
import com.machankura.bennu.compose.ui.composable.GroupPostsScreen
import com.machankura.bennu.compose.ui.composable.GroupCuratedSchemasScreen
import com.machankura.bennu.compose.ui.composable.GroupCuratedEntriesScreen
@@ -160,6 +161,9 @@ import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposeGroup
import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupRelaysRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupNostrProfileRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupRelaysRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletRoute
import com.machankura.bennu.compose.wallet.GroupChainWallets
import fr.acinq.phoenix.managers.NodeParamsManager
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupPostsRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupCuratedSchemasRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupCuratedEntriesRoute
@@ -263,6 +267,19 @@ fun BennuNavHost(
)
}
// The group wallets this identity is watching, on its own node's Electrum
// client -- null for an nsec or npub profile, which has no node and so no
// chain to watch. Remade with the node and stopped with it, because a switch
// of profile is a restart and a wallet left subscribing on the last one's
// connection is a wallet nobody can see.
val activeIdentityForWallets by sovereignWalletViewModel.activeIdentity.collectAsState()
val groupChainWallets = remember(activeIdentityForWallets?.business) {
activeIdentityForWallets?.business?.let { GroupChainWallets(it.electrumClient, applicationIOScope) }
}
DisposableEffect(groupChainWallets) {
onDispose { groupChainWallets?.let { wallets -> applicationIOScope.launch { wallets.stop() } } }
}
val navigationViewModel: NavigationViewModel = viewModel (
factory = NavigationViewModel.factory(
activeIdentity = sovereignWalletViewModel.activeIdentity,
@@ -1211,6 +1228,24 @@ fun BennuNavHost(
}
)
}
composable<GroupWalletRoute> { backStackEntry ->
val route = backStackEntry.toRoute<GroupWalletRoute>()
GroupWalletScreen(
activeUserPublicKey = route.activeUserPublicKey,
chatRoomId = route.chatRoomId,
chain = NodeParamsManager.chain,
chatRepository = databaseChatRepository,
frostSigningRepository = databaseFrostSigningRepository,
wallets = groupChainWallets,
onNavigateToRoute = { actionRoute ->
navController.navigate(route = actionRoute)
},
onNavigateBack = {
navController.popBackStack()
}
)
}
composable<GroupPostsRoute> { backStackEntry ->
val route = backStackEntry.toRoute<GroupPostsRoute>()
@@ -0,0 +1,14 @@
package com.machankura.bennu.compose.ui.composable.navigation.routes
import kotlinx.serialization.Serializable
/**
* The group's on-chain wallet: its balance, the address to be paid at, its
* coins, and -- for a group that has not opened one -- the way to ask it to.
*/
@Serializable
data class GroupWalletRoute(
val activeUserPublicKey: String,
val chatRoomId: String,
val relayHint: String?
): Route()
@@ -1,5 +1,6 @@
package com.machankura.bennu.compose.ui.view.model
import fr.acinq.phoenix.managers.NodeParamsManager
import com.machankura.bennu.compose.nostr.MarmotProfile
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
@@ -98,6 +99,7 @@ class ChatRoomDetailViewModel(
groupPosts = chatRepository.groupPosts(chatRoomId),
groupCuratedSchemas = chatRepository.groupCuratedSchemas(chatRoomId),
groupCuratedEntries = chatRepository.groupCuratedEntries(chatRoomId),
groupWallet = chatRepository.groupWallet(chatRoomId, NodeParamsManager.chain),
canEditNostrProfile = canSign,
canAddSubgroup = canSign,
canGovern = canGovern,
@@ -0,0 +1,156 @@
package com.machankura.bennu.compose.ui.view.model
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.nostr.wallet.GroupWalletStatementEvent
import com.machankura.bennu.compose.repository.ChatRepository
import com.machankura.bennu.compose.repository.FrostSigningRepository
import com.machankura.bennu.compose.ui.view.state.GroupWalletUIState
import com.machankura.bennu.compose.wallet.GroupChainWallets
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import fr.acinq.bitcoin.Chain
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* The group's wallet, read once for what the group has signed and then watched
* for what the chain says.
*
* The statement is a read, like every other group-signed thing's screen; the
* coins are a watch, because a payment arriving while the screen is open is the
* one moment somebody is looking at it.
*
* [wallets] is null for a profile with no node of its own -- an nsec or an npub
* -- which can see that the group keeps a wallet, and cannot see the chain.
*/
class GroupWalletViewModel(
val activeUserPublicKey: HexKey,
val chatRoomId: String,
val chain: Chain,
initialGroupWalletUIState: GroupWalletUIState,
val chatRepository: ChatRepository,
val frostSigningRepository: FrostSigningRepository,
private val wallets: GroupChainWallets?,
): ViewModel() {
private val logger = Logger.withTag(TAG)
var groupWalletUIState: GroupWalletUIState by mutableStateOf(initialGroupWalletUIState)
private set
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) {
groupWalletUIState = GroupWalletUIState.Error("Couldn't find the group")
return@launch
}
val canSign = localChatRoom.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId)
val wallet = chatRepository.groupWallet(chatRoomId, chain)
if (wallet == null) {
groupWalletUIState = GroupWalletUIState.NotOpened(
localChatRoom = localChatRoom,
account = chatRepository.groupWalletAccount(chatRoomId, chain),
canSign = canSign,
)
return@launch
}
val loaded = GroupWalletUIState.Loaded(
localChatRoom = localChatRoom,
wallet = wallet,
walletState = null,
canWatch = wallets != null,
canSign = canSign,
)
groupWalletUIState = loaded
val chainWallet = wallets?.walletFor(wallet.account) ?: return@launch
watching?.cancel()
watching = viewModelScope.launch(Dispatchers.IO) {
chainWallet.state.collect { state ->
groupWalletUIState = loaded.copy(walletState = state)
}
}
}
}
/**
* Asks the group to open its wallet: one signing session over one statement.
*
* Never batched with anything, for the reason `GroupWalletStatementEvent`
* gives -- every spend is opened against this, and it should never be as
* available as its worst co-passenger.
*/
fun openWallet(onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) {
val state = groupWalletUIState as? GroupWalletUIState.NotOpened ?: return
val account = state.account ?: return
// A second statement for the same account is harmless -- the same values
// under the same `d` tag -- but it is a second quorum asked for nothing.
if (isActionPending.value) return
isActionPending.value = true
val template = GroupWalletStatementEvent.template(account)
viewModelScope.launch(Dispatchers.IO) {
val session = runCatching {
frostSigningRepository.proposeSigning(
localChatRoom = state.localChatRoom,
userPublicKey = activeUserPublicKey,
kind = template.kind,
tags = template.tags,
content = template.content,
)
}.onFailure { error ->
logger.e("Failed to propose a wallet for $chatRoomId", error)
}.getOrNull()
withContext(Dispatchers.Main) {
if (session != null) onSuccess(session.id) else onFailure()
}
isActionPending.value = false
}
}
companion object {
private const val TAG = "GroupWalletViewModel"
fun factory(
activeUserPublicKey: HexKey,
chatRoomId: String,
chain: Chain,
initialGroupWalletUIState: GroupWalletUIState = GroupWalletUIState.Loading,
chatRepository: ChatRepository,
frostSigningRepository: FrostSigningRepository,
wallets: GroupChainWallets?,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
GroupWalletViewModel(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId,
chain = chain,
initialGroupWalletUIState = initialGroupWalletUIState,
chatRepository = chatRepository,
frostSigningRepository = frostSigningRepository,
wallets = wallets,
)
}
}
}
}
@@ -1,5 +1,6 @@
package com.machankura.bennu.compose.ui.view.state
import com.machankura.bennu.compose.nostr.wallet.GroupWallet
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.machankura.bennu.compose.database.model.GroupKeyState
import com.machankura.bennu.compose.managers.SubgroupManager
@@ -108,6 +109,14 @@ sealed interface ChatRoomDetailUIState {
* nothing, which is every group until a quorum signs an entry.
*/
val groupCuratedEntries: List<GroupCuratedEntry> = emptyList(),
/**
* The wallet this group has opened on the app's network, or null for one
* it has not. Under the identity block because it is not part of the
* group's account of itself on nostr -- nobody outside the room reads it --
* and the row says only whether it is open; the coins are read on
* `GroupWalletScreen`.
*/
val groupWallet: GroupWallet? = null,
/**
* Whether this device could sign an event for the group, which on this
* screen gates the paste at the end of the identity block. Each of the
@@ -0,0 +1,43 @@
package com.machankura.bennu.compose.ui.view.state
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.managers.GroupWalletDerivation
import com.machankura.bennu.compose.nostr.wallet.GroupWallet
import com.machankura.bennu.compose.wallet.GroupWalletState
sealed interface GroupWalletUIState {
/**
* A room whose group has not signed a wallet statement.
*
* [account] is what a statement would carry, or null for a room with no key
* at all -- there is nothing to open then. [canSign] gates the way in, for
* the reason every proposing screen gives: `proposeSigning` throws for a
* device holding no share.
*/
data class NotOpened(
val localChatRoom: LocalChatRoom,
val account: GroupWalletDerivation.Account?,
val canSign: Boolean,
): GroupWalletUIState
/**
* An open wallet.
*
* [walletState] is null in two different situations, told apart by
* [canWatch]: before Electrum's first answer, and for a profile with no node
* to watch the chain with at all.
*/
data class Loaded(
val localChatRoom: LocalChatRoom,
val wallet: GroupWallet,
val walletState: GroupWalletState?,
val canWatch: Boolean,
val canSign: Boolean,
): GroupWalletUIState
data class Error(
val message: String
): GroupWalletUIState
data object Loading: GroupWalletUIState
}
@@ -167,3 +167,6 @@ data class GroupWalletState(
.map { (branch, index) -> GroupWalletDerivation.derive(account, branch, index) }
.firstOrNull { it.pubkeyScript == script }
}
/** A BIP21 URI for [address], so a scanning wallet knows what the text it read is. */
fun bip21Uri(address: String): String = "bitcoin:$address"