Merge remote-tracking branch 'origin/bennu' into claude/satoshi-amount-group-wallet-a12572

# Conflicts:
#	composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallet.kt
#	composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWalletJvmTest.kt
#	docs/README.md
This commit is contained in:
Kgothatso Ngako committed 2026-10-23 12:51:52 +02:00
commit 409be6db28
14 files changed
+1424 -69

No files matched your search

@@ -622,6 +622,17 @@
<string name="receive_address">Receive address</string>
<string name="copy_address">Copy address</string>
<string name="address_copied">Address copied</string>
<string name="all_addresses">All addresses</string>
<string name="addresses">Addresses</string>
<string name="addresses_explainer">Each payment should go to a new address. If someone else in the group is already sharing the current one, share one of the ones after it.</string>
<string name="being_handed_out_now">Being handed out now</string>
<string name="not_used_yet">Not used yet</string>
<string name="paid_s_sats">Paid · %1$s sats</string>
<string name="paid_spent_since">Paid · spent since</string>
<string name="copy_address_s">Copy address %1$s</string>
<string name="address_s">Address %1$s</string>
<string name="show_as_a_qr_code">Show as a QR code</string>
<string name="address_s_was_just_paid">Address %1$s was just paid</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>
@@ -0,0 +1,368 @@
package com.machankura.bennu.compose.ui.composable
import androidx.compose.foundation.clickable
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.ContentCopy
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.minimumInteractiveComponentSize
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.font.FontFamily
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.address_s
import bennu.composeapp.generated.resources.address_s_was_just_paid
import bennu.composeapp.generated.resources.addresses
import bennu.composeapp.generated.resources.addresses_explainer
import bennu.composeapp.generated.resources.being_handed_out_now
import bennu.composeapp.generated.resources.change
import bennu.composeapp.generated.resources.copy_address
import bennu.composeapp.generated.resources.copy_address_s
import bennu.composeapp.generated.resources.finding_the_group_s_coins
import bennu.composeapp.generated.resources.not_used_yet
import bennu.composeapp.generated.resources.paid_s_sats
import bennu.composeapp.generated.resources.paid_spent_since
import bennu.composeapp.generated.resources.show_as_a_qr_code
import bennu.composeapp.generated.resources.this_profile_cannot_watch_the_chain
import com.machankura.bennu.compose.repository.ChatRepository
import com.machankura.bennu.compose.text.grouped
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.dialogs.ModalBottomSheet
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.GroupWalletAddressesViewModel
import com.machankura.bennu.compose.ui.view.state.GroupWalletAddressesUIState
import com.machankura.bennu.compose.wallet.GroupAddress
import com.machankura.bennu.compose.wallet.GroupOnchainWallets
import com.machankura.bennu.compose.wallet.bip21Uri
import fr.acinq.bitcoin.Chain
import fr.acinq.bitcoin.Satoshi
import org.jetbrains.compose.resources.stringResource
/**
* The group wallet's receive addresses, newest first: every one paid, the one
* the wallet screen is handing out, and the few after it.
*
* Modelled on Phoenix's swap-in address list, with the look-ahead cut to what is
* worth handing out. The addresses after the current one are there so that two
* members sharing the wallet at once can each give a payer a different one;
* the sentence above the list says so, or nobody would use anything but the top.
* Tapping an unused one opens it as a QR code, in a sheet that closes itself if
* the address is paid while it is open.
*
* No block explorer: a tap that sends every address of the group's wallet to a
* third party's server is the leak the watch-only export warns about, made
* without asking.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GroupWalletAddressesScreen(
chatRoomId: String,
chain: Chain,
initialUIState: GroupWalletAddressesUIState = GroupWalletAddressesUIState.Loading,
chatRepository: ChatRepository,
wallets: GroupOnchainWallets?,
onNavigateBack: () -> Unit,
) {
val addressesViewModel: GroupWalletAddressesViewModel = viewModel(
factory = GroupWalletAddressesViewModel.factory(
chatRoomId = chatRoomId,
chain = chain,
initialUIState = initialUIState,
chatRepository = chatRepository,
wallets = wallets,
)
)
LaunchedEffect(true) {
if (initialUIState == GroupWalletAddressesUIState.Loading) {
addressesViewModel.initiate()
}
}
val notify = rememberNotifier(rememberCoroutineScope())
Scaffold(
snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
topBar = {
TopAppBar(
title = {
Text(
text = stringResource(Res.string.addresses),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
navigationIcon = { NavigateBackButton(onNavigateBack) }
)
}
) { padding ->
ScreenStateTransition(addressesViewModel.uiState) { uiState ->
when (val state = uiState) {
is GroupWalletAddressesUIState.Error -> {
// Nothing to retry: the room came from a navigation argument.
ErrorState(
modifier = Modifier.padding(padding),
message = state.message,
onRetry = null
)
}
GroupWalletAddressesUIState.Loading -> {
LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding))
}
GroupWalletAddressesUIState.CannotWatch -> {
EmptyState(
modifier = Modifier.padding(padding).readableContent(),
message = stringResource(Res.string.this_profile_cannot_watch_the_chain),
icon = Icons.Default.Visibility,
)
}
is GroupWalletAddressesUIState.Loaded -> {
val receive = state.receive
if (receive == null) {
LoadingDataIndicator(
modifier = Modifier.fillMaxWidth().padding(padding),
text = stringResource(Res.string.finding_the_group_s_coins)
)
} else {
AddressList(
modifier = Modifier.padding(padding),
receive = receive,
change = state.change,
notify = notify,
onShow = { index, paid -> addressesViewModel.show(index) { notify(paid) } },
)
val shown = addressesViewModel.shown?.let { index -> receive.firstOrNull { it.derivation.index == index } }
if (shown != null) {
AddressSheet(
address = shown,
notify = notify,
onDismiss = addressesViewModel::dismiss,
)
}
}
}
}
}
}
}
@Composable
private fun AddressList(
modifier: Modifier,
receive: List<GroupAddress>,
change: List<GroupAddress>,
notify: (String) -> Unit,
onShow: (index: Long, paidMessage: String) -> Unit,
) {
val clipboardManager = LocalClipboardManager.current
val addressCopied = stringResource(Res.string.address_copied)
val copy = { address: GroupAddress ->
clipboardManager.setText(buildAnnotatedString { append(address.address) })
notify(addressCopied)
}
// Both branches start at index 0, so the index alone is not a row's identity.
val key = { address: GroupAddress -> "${address.derivation.change}/${address.derivation.index}" }
LazyColumn(
modifier = modifier.readableContent().fillMaxSize()
.padding(MaterialTheme.spacing.screenMargin),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)
) {
item {
Text(
text = stringResource(Res.string.addresses_explainer),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
items(receive, key = key) { address ->
// Read here rather than in the click: the index is the row's, and a
// click handler is not composable.
val paid = stringResource(Res.string.address_s_was_just_paid, address.derivation.index.toString())
AddressRow(
address = address,
onCopy = { copy(address) },
// A used address is never offered for scanning: copying it is for
// checking, a QR code is for being paid.
onShow = if (address.status != GroupAddress.Status.USED) {
{ onShow(address.derivation.index, paid) }
} else null,
)
}
// The group's money too, and what a watch-only import will show beside
// the receive addresses -- but chosen by a spend, so never offered here.
if (change.isNotEmpty()) {
item {
Text(
text = stringResource(Res.string.change),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(top = MaterialTheme.spacing.sectionGap),
)
}
items(change, key = key) { address ->
AddressRow(address = address, onCopy = { copy(address) }, onShow = null)
}
}
}
}
/**
* One unused address, ready to be paid: what the wallet screen's receive card
* shows for the current address, for whichever one this member is handing out.
*
* The title carries the index so a member reading it to a payer can say which
* one they gave.
*/
@Composable
private fun AddressSheet(
address: GroupAddress,
notify: (String) -> Unit,
onDismiss: () -> Unit,
) {
val clipboardManager = LocalClipboardManager.current
val addressCopied = stringResource(Res.string.address_copied)
ModalBottomSheet(
onDismiss = onDismiss,
skipPartiallyExpanded = true,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)
) {
Text(
text = stringResource(Res.string.address_s, address.derivation.index.toString()),
style = MaterialTheme.typography.titleMedium,
)
Text(
text = address.status.label(address.balance),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
// BIP21, so a scanning wallet knows what the text is.
QRCodeView(bip21Uri(address.address))
SelectionContainer {
Text(text = address.address, style = MaterialTheme.typography.bodyMedium)
}
TextButton(
onClick = {
clipboardManager.setText(buildAnnotatedString { append(address.address) })
notify(addressCopied)
}
) {
Icon(Icons.Default.ContentCopy, contentDescription = Decorative)
Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
Text(stringResource(Res.string.copy_address))
}
}
}
}
/**
* One address: its index, the address itself, and what it has been used for.
*
* The current address takes the secondary container rather than Phoenix's
* leading bar, so the emphasis is a colour pairing the theme has already
* measured in all six schemes.
*/
@Composable
private fun AddressRow(address: GroupAddress, onCopy: () -> Unit, onShow: (() -> Unit)?) {
val showLabel = stringResource(Res.string.show_as_a_qr_code)
val colors = if (address.status == GroupAddress.Status.CURRENT) {
val onContainer = MaterialTheme.colorScheme.onSecondaryContainer
ListItemDefaults.colors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
headlineColor = onContainer,
supportingColor = onContainer,
leadingIconColor = onContainer,
trailingIconColor = onContainer,
)
} else {
ListItemDefaults.colors()
}
ListItem(
modifier = if (onShow != null) {
Modifier.clickable(onClickLabel = showLabel, onClick = onShow).minimumInteractiveComponentSize()
} else Modifier,
colors = colors,
leadingContent = {
Text(
text = address.derivation.index.toString(),
style = MaterialTheme.typography.labelLarge,
)
},
headlineContent = {
Text(
text = address.address,
style = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace),
maxLines = 1,
overflow = TextOverflow.MiddleEllipsis,
)
},
supportingContent = { Text(address.status.label(address.balance)) },
trailingContent = {
IconButton(onClick = onCopy) {
Icon(
Icons.Default.ContentCopy,
contentDescription = stringResource(Res.string.copy_address_s, address.derivation.index.toString())
)
}
},
)
}
@Composable
private fun GroupAddress.Status.label(balance: Satoshi): String = when (this) {
GroupAddress.Status.CURRENT -> stringResource(Res.string.being_handed_out_now)
GroupAddress.Status.NEXT -> stringResource(Res.string.not_used_yet)
GroupAddress.Status.USED -> if (balance > Satoshi(0)) {
stringResource(Res.string.paid_s_sats, balance.grouped())
} else {
stringResource(Res.string.paid_spent_since)
}
}
@@ -19,6 +19,7 @@ import bennu.composeapp.generated.resources.couldn_t_bump_the_fee
import androidx.compose.material.icons.filled.Send
import bennu.composeapp.generated.resources.send
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupSendRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletAddressesRoute
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
@@ -32,6 +33,7 @@ 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.FormatListNumbered
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material3.Button
import androidx.compose.material3.Card
@@ -56,6 +58,7 @@ 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.all_addresses
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
@@ -242,6 +245,14 @@ fun GroupWalletScreen(
)
}
} else null,
onOpenAddresses = {
onNavigateToRoute(
GroupWalletAddressesRoute(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId
)
)
},
onOpenSpend = toSession,
onSendAgain = if (watcher != null) {
{ sessionId -> groupWalletViewModel.sendAgain(sessionId) { notify(sentAgain) } }
@@ -292,6 +303,7 @@ private fun OpenWallet(
state: GroupWalletUIState.Loaded,
notify: (String) -> Unit,
onSend: (() -> Unit)?,
onOpenAddresses: () -> Unit,
onOpenSpend: (sessionId: String) -> Unit,
onSendAgain: ((sessionId: String) -> Unit)?,
onBump: ((sessionId: String) -> Unit)?,
@@ -362,6 +374,14 @@ private fun OpenWallet(
Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
Text(stringResource(Res.string.copy_address))
}
// In the card because it answers the question the card
// raises: which address to give, when somebody else in
// the group may be giving this one.
TextButton(onClick = onOpenAddresses) {
Icon(Icons.Default.FormatListNumbered, contentDescription = Decorative)
Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
Text(stringResource(Res.string.all_addresses))
}
}
}
}
@@ -51,6 +51,7 @@ 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.GroupWalletAddressesScreen
import com.machankura.bennu.compose.ui.composable.GroupPostsScreen
import com.machankura.bennu.compose.ui.composable.HomeScreen
import com.machankura.bennu.compose.ui.composable.ImplementationPendingScreen
@@ -154,6 +155,7 @@ import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupRel
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.ui.composable.navigation.routes.GroupWalletAddressesRoute
import com.machankura.bennu.compose.wallet.GroupOnchainWallets
import com.machankura.bennu.compose.wallet.GroupTransactionWatcher
import fr.acinq.phoenix.managers.NodeParamsManager
@@ -1250,6 +1252,19 @@ fun BennuNavHost(
}
)
}
composable<GroupWalletAddressesRoute> { backStackEntry ->
val route = backStackEntry.toRoute<GroupWalletAddressesRoute>()
GroupWalletAddressesScreen(
chatRoomId = route.chatRoomId,
chain = NodeParamsManager.chain,
chatRepository = databaseChatRepository,
wallets = groupOnchainWallets,
onNavigateBack = {
navController.popBackStack()
}
)
}
composable<GroupSendRoute> { backStackEntry ->
val route = backStackEntry.toRoute<GroupSendRoute>()
@@ -0,0 +1,13 @@
package com.machankura.bennu.compose.ui.composable.navigation.routes
import kotlinx.serialization.Serializable
/**
* The group wallet's receive addresses: every one paid, the one being handed
* out, and the next few -- pushed from the wallet screen's receive card.
*/
@Serializable
data class GroupWalletAddressesRoute(
val activeUserPublicKey: String,
val chatRoomId: String,
): Route()
@@ -0,0 +1,107 @@
package com.machankura.bennu.compose.ui.view.model
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 com.machankura.bennu.compose.repository.ChatRepository
import com.machankura.bennu.compose.ui.view.state.GroupWalletAddressesUIState
import com.machankura.bennu.compose.wallet.GroupAddress
import com.machankura.bennu.compose.wallet.GroupOnchainWallets
import fr.acinq.bitcoin.Chain
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* The group wallet's addresses, watched for as long as the screen is open.
*
* [wallets] hands back the wallet the wallet screen is already watching, so the
* list costs no subscriptions of its own and agrees with that screen about which
* address is current.
*/
class GroupWalletAddressesViewModel(
val chatRoomId: String,
val chain: Chain,
initialUIState: GroupWalletAddressesUIState,
val chatRepository: ChatRepository,
private val wallets: GroupOnchainWallets?,
): ViewModel() {
var uiState: GroupWalletAddressesUIState by mutableStateOf(initialUIState)
private set
/** The index of the address the sheet is showing as a QR code, or null when it is closed. */
var shown: Long? by mutableStateOf(null)
private set
private var onShownPaid: (() -> Unit)? = null
/**
* Opens the sheet on the receive address at [index]. [onPaid] runs once if
* that address is paid while the sheet is open, as the sheet closes: whoever
* is scanning it then has already paid, and nobody else should.
*/
fun show(index: Long, onPaid: () -> Unit) {
shown = index
onShownPaid = onPaid
}
fun dismiss() {
shown = null
onShownPaid = null
}
fun initiate() {
viewModelScope.launch(Dispatchers.IO) {
val wallet = chatRepository.groupWallet(chatRoomId, chain)
if (wallet == null) {
uiState = GroupWalletAddressesUIState.Error("This group has not opened a wallet")
return@launch
}
if (wallets == null) {
uiState = GroupWalletAddressesUIState.CannotWatch
return@launch
}
uiState = GroupWalletAddressesUIState.Loaded(receive = null)
wallets.walletFor(wallet.account).state.collect { state ->
val receive = state.receiveAddresses
uiState = GroupWalletAddressesUIState.Loaded(receive = receive, change = state.changeAddresses.orEmpty())
val index = shown ?: return@collect
val status = receive?.firstOrNull { it.derivation.index == index }?.status ?: return@collect
if (status == GroupAddress.Status.USED) {
val paid = onShownPaid
withContext(Dispatchers.Main) {
dismiss()
paid?.invoke()
}
}
}
}
}
companion object {
fun factory(
chatRoomId: String,
chain: Chain,
initialUIState: GroupWalletAddressesUIState = GroupWalletAddressesUIState.Loading,
chatRepository: ChatRepository,
wallets: GroupOnchainWallets?,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
GroupWalletAddressesViewModel(
chatRoomId = chatRoomId,
chain = chain,
initialUIState = initialUIState,
chatRepository = chatRepository,
wallets = wallets,
)
}
}
}
}
@@ -0,0 +1,30 @@
package com.machankura.bennu.compose.ui.view.state
import com.machankura.bennu.compose.wallet.GroupAddress
sealed interface GroupWalletAddressesUIState {
/**
* The wallet's addresses as the chain last said.
*
* [receive] is null until Electrum has said which are used: before that every
* address reads as unused, and a list that called `/0/0` current would be
* wrong about a group paid there before.
*/
data class Loaded(
val receive: List<GroupAddress>?,
/** The change addresses that have been used, newest first: empty for a wallet that has never sent. */
val change: List<GroupAddress> = emptyList(),
): GroupWalletAddressesUIState
/**
* A profile with no node of its own -- an nsec or an npub -- which knows the
* group keeps a wallet and cannot see which of its addresses are used.
*/
data object CannotWatch: GroupWalletAddressesUIState
data class Error(
val message: String
): GroupWalletAddressesUIState
data object Loading: GroupWalletAddressesUIState
}
@@ -94,6 +94,37 @@ class GroupOnchainWallet(
* have at once before the next is told to wait.
*/
const val CHANGE_LOOKAHEAD: UInt = 10u
/**
* Unused receive addresses the address list offers past the current one,
* so several members can each hand out a different one. Every one of them
* has to be watched already, or a payment to it would go unseen.
*/
const val ADDRESSES_AHEAD: Int = 2
init {
require(ADDRESSES_AHEAD < RECEIVE_LOOKAHEAD.toInt()) { "the address list would offer addresses the wallet does not watch" }
}
}
}
/** One of the wallet's addresses as the address list shows it. */
data class GroupAddress(
val derivation: GroupWalletDerivation.Derived,
val address: String,
val status: Status,
/** What it holds now: zero for an address never paid, and for one paid and spent. */
val balance: Satoshi,
) {
enum class Status {
/** The address the wallet screen is handing out. */
CURRENT,
/** Not paid yet, and past the current one. */
NEXT,
/** Paid at least once, whether or not the coins have moved since. */
USED,
}
}
@@ -145,6 +176,60 @@ data class GroupWalletState(
*/
val receiveAddress: String? get() = receive.firstUnusedDerivedAddress?.first
/**
* The receive addresses worth listing, newest first: every one paid, the one
* being handed out, and [GroupOnchainWallet.ADDRESSES_AHEAD] after it -- or
* null until Electrum has said which are used, for the reason
* [receiveAddress] is.
*
* The list reaches the highest paid address even past the current one plus
* the addresses ahead: the current address is the *lowest* unused one, so a
* watch-only wallet paid further up leaves it where it was.
*/
val receiveAddresses: List<GroupAddress>? by lazy {
val current = receive.firstUnusedDerivedAddress?.second?.index ?: return@lazy null
listed(GroupWalletDerivation.RECEIVE, receive, current)
}
/**
* The change addresses that have been used, newest first, or null until
* Electrum has answered. Never a current or a next one: change is chosen by
* a spend, and is not handed out to be paid.
*/
val changeAddresses: List<GroupAddress>? by lazy {
change.firstUnusedDerivedAddress ?: return@lazy null
listed(GroupWalletDerivation.CHANGE, change, current = null)
}
/**
* [branch]'s addresses up to the highest used one, and -- given the branch's
* [current] index -- up to [GroupOnchainWallet.ADDRESSES_AHEAD] past that.
* Without a current index, only the used ones.
*/
private fun listed(branch: Long, state: WalletState, current: Int?): List<GroupAddress> {
val derived = state.addresses.mapNotNull { (address, addressState) ->
(addressState.meta as? WalletState.AddressMeta.Derived)?.let { Triple(address, it.index, addressState) }
}
val highestUsed = derived.filter { it.third.alreadyUsed }.maxOfOrNull { it.second } ?: -1
val last = current?.let { maxOf(it + GroupOnchainWallet.ADDRESSES_AHEAD, highestUsed) } ?: highestUsed
return derived
.filter { (_, index, addressState) -> index <= last && (current != null || addressState.alreadyUsed) }
.sortedByDescending { (_, index, _) -> index }
.map { (address, index, addressState) ->
GroupAddress(
derivation = GroupWalletDerivation.derive(account, branch, index.toLong()),
address = address,
status = when {
addressState.alreadyUsed -> GroupAddress.Status.USED
index == current -> GroupAddress.Status.CURRENT
else -> GroupAddress.Status.NEXT
},
balance = addressState.utxos.map { it.amount }.sum(),
)
}
}
/** Whether Electrum has answered for any change address yet: before it has, there is no next one to name. */
val changeKnown: Boolean get() = change.addresses.values.any { !it.alreadyUsed }