diff --git a/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/35.json b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/35.json
index ce75472c..553fc4ca 100644
--- a/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/35.json
+++ b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/35.json
@@ -2,7 +2,7 @@
"formatVersion": 1,
"database": {
"version": 35,
- "identityHash": "96c5c9b771985195100cd1e3bde04d60",
+ "identityHash": "29067a5a909c975b5c9689f8964c63c4",
"entities": [
{
"tableName": "BroadcastNostrEventReceipt",
@@ -1793,7 +1793,7 @@
},
{
"tableName": "GroupLightningPaymentRow",
- "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `id` TEXT NOT NULL, `incoming` INTEGER NOT NULL, `amountMsat` INTEGER NOT NULL, `feesMsat` INTEGER NOT NULL, `paymentHash` TEXT, `description` TEXT, `completedAt` INTEGER, `succeeded` INTEGER NOT NULL, PRIMARY KEY(`wallet`, `id`))",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `id` TEXT NOT NULL, `incoming` INTEGER NOT NULL, `amountMsat` INTEGER NOT NULL, `feesMsat` INTEGER NOT NULL, `paymentHash` TEXT, `description` TEXT, `completedAt` INTEGER, `succeeded` INTEGER NOT NULL, `liquiditySat` INTEGER, PRIMARY KEY(`wallet`, `id`))",
"fields": [
{
"fieldPath": "wallet",
@@ -1845,6 +1845,11 @@
"columnName": "succeeded",
"affinity": "INTEGER",
"notNull": true
+ },
+ {
+ "fieldPath": "liquiditySat",
+ "columnName": "liquiditySat",
+ "affinity": "INTEGER"
}
],
"primaryKey": {
@@ -5488,7 +5493,7 @@
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
- "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '96c5c9b771985195100cd1e3bde04d60')"
+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '29067a5a909c975b5c9689f8964c63c4')"
]
}
}
\ No newline at end of file
diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index ad5fe7d9..cccb40f5 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -753,6 +753,33 @@
Wallets already guarded keep the delay they were guarded at.
Members whose app is older than this one can only be guarded at 12 blocks, and don't know this group can close.
Ask the group
+ Add liquidity
+ Plan ahead your liquidity
+ The LSP adds this much to the channel, so the group can be paid that much more without the LSP splicing it first.
+ Current liquidity: %1$s sats
+ Liquidity to add: %1$s sats
+ The channel grows from %1$s to %2$s sats.
+ Miner fee
+ Service fee
+ Duration
+ 1 year
+ Total
+ After a year, the LSP may reclaim the liquidity that is still unused.
+ The fee is a quarter of the amount or more.
+ The fee is more than the group's balance.
+ Priced on your device at %1$s sat/vbyte, the feerate the operator reported in term %2$s. The miner fee may rise before the node buys.
+ Buying liquidity asks the group to sign. The operator's node buys it once enough members have, and every member's device checks the splice before it signs.
+ Review the purchase
+ This is an initial amount of inbound liquidity. It is used up as the group is paid, and after a year the LSP may reclaim what is unused. The fee comes out of the group's balance.
+ I understand
+ Receive a payment first: it opens the channel.
+ The channel holds the most a channel may on this network for now.
+ The operator hasn't reported what the LSP sells yet.
+ The LSP sells none of the amounts this app offers.
+ Adding %1$s sats of inbound liquidity
+ Waiting for the channel's last splice before adding %1$s sats
+ Couldn't add liquidity: %1$s
+ Inbound liquidity added: %1$s sats, for %2$s sats in fees
Stop guarding new wallets
Stop guarding new members' wallets?
Wallets already guarded stay guarded, and this group can still take their coins after their delay.
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt
index 125ccbfb..e986c6d0 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt
@@ -615,6 +615,9 @@ data class ChatMessage(
const val TYPE_LIGHTNING_PAYMENT_RECEIVED = "lightningPaymentReceived"
const val TYPE_LIGHTNING_PAYMENT_SENT = "lightningPaymentSent"
const val TYPE_LIGHTNING_PAYMENT_FAILED = "lightningPaymentFailed"
+ /** A liquidity purchase locked or failed (docs/group-lightning-liquidity.md, Phase 7). Keyed on the authorisation's id. */
+ const val TYPE_LIGHTNING_LIQUIDITY_ADDED = "lightningLiquidityAdded"
+ const val TYPE_LIGHTNING_LIQUIDITY_FAILED = "lightningLiquidityFailed"
/**
* This device's co-signer refused what the operator's node asked it to sign, and why --
@@ -642,6 +645,8 @@ data class ChatMessage(
TYPE_LIGHTNING_PAYMENT_RECEIVED,
TYPE_LIGHTNING_PAYMENT_SENT,
TYPE_LIGHTNING_PAYMENT_FAILED,
+ TYPE_LIGHTNING_LIQUIDITY_ADDED,
+ TYPE_LIGHTNING_LIQUIDITY_FAILED,
TYPE_LIGHTNING_REFUSED,
TYPE_LIGHTNING_EQUIVOCATION,
)
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupLightningRecords.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupLightningRecords.kt
index 7f600059..42b3370e 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupLightningRecords.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupLightningRecords.kt
@@ -33,6 +33,8 @@ data class GroupLightningPaymentRow(
val description: String?,
val completedAt: Instant?,
val succeeded: Boolean,
+ /** For inbound liquidity bought, how much: then [amountMsat] is what it cost (docs/group-lightning-liquidity.md, Phase 7). */
+ val liquiditySat: Long? = null,
)
/** An invoice the operator made for a member's request. */
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt
index d792c3df..65f4dd85 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt
@@ -77,6 +77,9 @@ class DatabaseGroupLightningRepository(private val database: BennuDatabase) : Gr
override suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession =
GroupLightningAuthorisations.propose(database, localChatRoom, userPublicKey, pay)
+ override suspend fun proposeLiquidity(localChatRoom: LocalChatRoom, userPublicKey: HexKey, buy: GroupLightningAuthorisationEvent.BuyLiquidity): FrostSigningSession =
+ GroupLightningAuthorisations.proposeBuyLiquidity(database, localChatRoom, userPublicKey, buy)
+
override suspend fun proposeClose(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession =
GroupLightningAuthorisations.proposeChannelAction(database, localChatRoom, userPublicKey, wallet, channelId, force)
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt
index 028dcc6e..639ba0c2 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt
@@ -7,6 +7,7 @@ import com.machankura.bennu.compose.nostr.lightning.GroupLightningAuthorisationE
import com.machankura.bennu.compose.nostr.lightning.GroupLightningEvents
import com.machankura.bennu.compose.nostr.lightning.GroupLightningWalletStatementEvent
import com.machankura.bennu.compose.wallet.GroupChainClients
+import com.machankura.bennu.compose.wallet.GroupLightningRollout
import com.machankura.bennu.compose.wallet.lightning.GroupNodeKeyManager
import com.machankura.bennu.compose.wallet.lightning.GroupSweep
import com.machankura.bennu.compose.wallet.lightning.WalletWire
@@ -417,7 +418,7 @@ class GroupLightningNode(
runCatching { answerInvoiceRequests() }.onFailure { logger.e("Could not answer an invoice request", it) }
runCatching { payAuthorised() }.onFailure { logger.e("Could not make an authorised payment", it) }
runCatching { closeAuthorised() }.onFailure { logger.e("Could not close an authorised channel", it) }
- runCatching { buyAuthorised() }.onFailure { logger.e("Could not buy authorised liquidity", it) }
+ if (GroupLightningRollout.LIQUIDITY_ENABLED) runCatching { buyAuthorised() }.onFailure { logger.e("Could not buy authorised liquidity", it) }
}
/**
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningReports.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningReports.kt
index 838da650..84420bb1 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningReports.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningReports.kt
@@ -108,7 +108,7 @@ object GroupLightningReports {
}
// Payments are kept whatever the snapshot's age: a list of what happened only grows.
snapshot.payments.forEach { p ->
- dao.upsertPayment(GroupLightningPaymentRow(snapshot.wallet, p.id, p.incoming, p.amountMsat, p.feesMsat, p.paymentHash, p.description, p.completedAt?.let(Instant::fromEpochMilliseconds), p.succeeded))
+ dao.upsertPayment(GroupLightningPaymentRow(snapshot.wallet, p.id, p.incoming, p.amountMsat, p.feesMsat, p.paymentHash, p.description, p.completedAt?.let(Instant::fromEpochMilliseconds), p.succeeded, p.liquiditySat))
}
sayWhatHappened(database, chatRoomId, sentBy, snapshot, previous.takeIf { newer })
}
@@ -161,6 +161,8 @@ object GroupLightningReports {
// Lightning payment has one. The channel's closed line already says it, and a second line
// would read as the group having paid the money away. Found by the regtest run.
if (isChannelClose(payment.incoming, payment.paymentHash)) return@forEach
+ // A purchase of liquidity is said by its own line, below, as it locks or fails: it is not money sent.
+ if (payment.kind == WalletWire.LIQUIDITY) return@forEach
val (type, content) = when {
payment.incoming && payment.succeeded -> ChatMessage.TYPE_LIGHTNING_PAYMENT_RECEIVED to buildString {
append("The group's Lightning wallet received ${sats(payment.amountMsat)}")
@@ -180,6 +182,23 @@ object GroupLightningReports {
}
GroupLightningLines.writeFact(database, chatRoomId, type, payment.id, sentBy, content, completedAt)
}
+
+ // A liquidity purchase, once it has an outcome: the channel is on the splice's output, or it failed.
+ snapshot.purchases.forEach { purchase ->
+ when (purchase.state) {
+ WalletWire.LOCKED -> GroupLightningLines.writeFact(
+ database, chatRoomId, ChatMessage.TYPE_LIGHTNING_LIQUIDITY_ADDED, purchase.id, sentBy,
+ "The group's Lightning wallet can receive ${Satoshi(purchase.amountSat).grouped()} sats more" +
+ (purchase.feeSat?.let { ", for ${Satoshi(it).grouped()} sats in fees." } ?: "."),
+ sentAt,
+ )
+ WalletWire.FAILED -> GroupLightningLines.writeFact(
+ database, chatRoomId, ChatMessage.TYPE_LIGHTNING_LIQUIDITY_FAILED, purchase.id, sentBy,
+ "Adding ${Satoshi(purchase.amountSat).grouped()} sats of inbound liquidity failed" + (purchase.reason?.let { ": $it." } ?: ". Nothing left the wallet."),
+ sentAt,
+ )
+ }
+ }
}
/** A snapshot, with each of its channels checked against this device's own ledger. */
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt
index 93ea9832..ff2b2922 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt
@@ -94,6 +94,9 @@ interface GroupLightningRepository {
/** Proposes [pay] to the group; the operator's node pays it once a quorum signs. */
suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession
+ /** Proposes [buy] to the group; the operator's node buys the liquidity once a quorum signs. */
+ suspend fun proposeLiquidity(localChatRoom: LocalChatRoom, userPublicKey: HexKey, buy: GroupLightningAuthorisationEvent.BuyLiquidity): FrostSigningSession
+
/** Proposes closing [channelId] to the onchain wallet, or force-closing it when [force]. */
suspend fun proposeClose(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession
@@ -139,6 +142,7 @@ interface GroupLightningRepository {
override suspend fun requestInvoice(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, amountMsat: Long?, description: String): String = error("No room to ask in")
override fun observeInvoice(chatRoomId: String, chain: Chain, wallet: Long, requestId: String): Flow = flowOf(null)
override suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession = error("No room to propose in")
+ override suspend fun proposeLiquidity(localChatRoom: LocalChatRoom, userPublicKey: HexKey, buy: GroupLightningAuthorisationEvent.BuyLiquidity): FrostSigningSession = error("No room to propose in")
override suspend fun proposeClose(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession = error("No room to propose in")
override suspend fun proposeCloseAll(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelIds: List): FrostSigningSession = error("No room to propose in")
override suspend fun unswept(chatRoomId: String, report: GroupLightningReports.Report?): List = emptyList()
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningLiquidityScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningLiquidityScreen.kt
new file mode 100644
index 00000000..a47f8324
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningLiquidityScreen.kt
@@ -0,0 +1,275 @@
+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.selection.toggleable
+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.Bolt
+import androidx.compose.material3.Button
+import androidx.compose.material3.Card
+import androidx.compose.material3.Checkbox
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.Icon
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.ModalBottomSheet
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.Slider
+import androidx.compose.material3.SnackbarHost
+import androidx.compose.material3.Text
+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.semantics.Role
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.input.ImeAction
+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.add_liquidity
+import bennu.composeapp.generated.resources.after_a_year_the_lsp_may_reclaim
+import bennu.composeapp.generated.resources.ask_the_group
+import bennu.composeapp.generated.resources.buying_liquidity_asks_the_group_to_sign
+import bennu.composeapp.generated.resources.couldn_t_propose_this
+import bennu.composeapp.generated.resources.current_liquidity_s_sats
+import bennu.composeapp.generated.resources.duration
+import bennu.composeapp.generated.resources.fee_limit_in_sats
+import bennu.composeapp.generated.resources.i_understand
+import bennu.composeapp.generated.resources.left_empty_s_sats
+import bennu.composeapp.generated.resources.liquidity_is_an_initial_amount
+import bennu.composeapp.generated.resources.liquidity_lets_the_group_receive_more
+import bennu.composeapp.generated.resources.liquidity_to_add_s_sats
+import bennu.composeapp.generated.resources.miner_fee
+import bennu.composeapp.generated.resources.nobody_runs_this_wallet
+import bennu.composeapp.generated.resources.one_year
+import bennu.composeapp.generated.resources.plan_ahead_your_liquidity
+import bennu.composeapp.generated.resources.priced_at_s_sat_vbyte_in_term_s
+import bennu.composeapp.generated.resources.receive_a_payment_first_it_opens_the_channel
+import bennu.composeapp.generated.resources.review_the_purchase
+import bennu.composeapp.generated.resources.s_sats
+import bennu.composeapp.generated.resources.sats
+import bennu.composeapp.generated.resources.service_fee
+import bennu.composeapp.generated.resources.the_channel_grows_from_s_to_s_sats
+import bennu.composeapp.generated.resources.the_channel_holds_the_most_it_may_for_now
+import bennu.composeapp.generated.resources.the_fee_is_a_quarter_of_the_amount_or_more
+import bennu.composeapp.generated.resources.the_fee_is_more_than_the_group_s_balance
+import bennu.composeapp.generated.resources.the_lsp_sells_none_of_these_amounts
+import bennu.composeapp.generated.resources.the_operator_hasn_t_reported_what_the_lsp_sells
+import bennu.composeapp.generated.resources.total
+import com.machankura.bennu.compose.repository.ChatRepository
+import com.machankura.bennu.compose.repository.GroupLightningRepository
+import com.machankura.bennu.compose.text.GroupedSats
+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.GroupLightningLiquidityViewModel
+import com.machankura.bennu.compose.ui.view.state.GroupLightningLiquidityUIState
+import com.machankura.bennu.compose.wallet.GroupLightningRollout
+import com.machankura.bennu.compose.wallet.lightning.LiquidityPrice
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import fr.acinq.bitcoin.Satoshi
+import kotlin.math.roundToInt
+import org.jetbrains.compose.resources.stringResource
+
+/**
+ * Asking the group to buy inbound liquidity, as Phoenix asks its owner (`docs/group-lightning-liquidity.md`,
+ * Phase 7): an amount on Phoenix's slider, its price worked out on this device, a review with the
+ * acknowledgement Phoenix asks for, and then a proposal rather than a purchase. The group signs it; the
+ * operator's node buys; every member's device checks the splice.
+ */
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun GroupLightningLiquidityScreen(
+ activeUserPublicKey: HexKey,
+ chatRoomId: String,
+ chatRepository: ChatRepository,
+ lightningRepository: GroupLightningRepository,
+ onNavigateToRoute: (Route) -> Unit,
+ onNavigateBack: () -> Unit,
+) {
+ val viewModel: GroupLightningLiquidityViewModel = viewModel(
+ factory = GroupLightningLiquidityViewModel.factory(activeUserPublicKey, chatRoomId, GroupLightningRollout.NETWORK, chatRepository, lightningRepository)
+ )
+ LaunchedEffect(true) { viewModel.initiate() }
+
+ val notify = rememberNotifier(rememberCoroutineScope())
+ val couldNotPropose = stringResource(Res.string.couldn_t_propose_this)
+
+ Scaffold(
+ snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
+ topBar = {
+ TopAppBar(
+ title = { Text(stringResource(Res.string.add_liquidity), maxLines = 1, overflow = TextOverflow.Ellipsis) },
+ navigationIcon = { NavigateBackButton(onNavigateBack) }
+ )
+ }
+ ) { padding ->
+ ScreenStateTransition(viewModel.uiState) { uiState ->
+ when (val state = uiState) {
+ GroupLightningLiquidityUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding))
+
+ is GroupLightningLiquidityUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null)
+
+ is GroupLightningLiquidityUIState.Unavailable -> EmptyState(
+ modifier = Modifier.padding(padding).readableContent(),
+ message = unavailableBecause(state.why),
+ icon = Icons.Default.Bolt,
+ )
+
+ is GroupLightningLiquidityUIState.Form -> LiquidityForm(
+ modifier = Modifier.padding(padding),
+ form = state,
+ viewModel = viewModel,
+ onAsk = {
+ viewModel.propose(
+ onSession = { sessionId -> onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) },
+ onFailure = { notify(couldNotPropose) },
+ )
+ },
+ )
+ }
+ }
+ }
+}
+
+/** Why nothing can be asked for now, in a sentence; the wallet screen says the same where its button would be. */
+@Composable
+internal fun unavailableBecause(why: LiquidityPrice.Availability): String = when (why) {
+ LiquidityPrice.Availability.NoOperator -> stringResource(Res.string.nobody_runs_this_wallet)
+ LiquidityPrice.Availability.NoPrices -> stringResource(Res.string.the_operator_hasn_t_reported_what_the_lsp_sells)
+ LiquidityPrice.Availability.NoChannel -> stringResource(Res.string.receive_a_payment_first_it_opens_the_channel)
+ LiquidityPrice.Availability.AtTheCap -> stringResource(Res.string.the_channel_holds_the_most_it_may_for_now)
+ LiquidityPrice.Availability.NothingSold -> stringResource(Res.string.the_lsp_sells_none_of_these_amounts)
+ is LiquidityPrice.Availability.Available -> ""
+}
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+private fun LiquidityForm(modifier: Modifier, form: GroupLightningLiquidityUIState.Form, viewModel: GroupLightningLiquidityViewModel, onAsk: () -> Unit) {
+ val channel = form.available.channel
+ val offered = form.available.offered
+ val amount = viewModel.amountSat(form)
+ val price = viewModel.price(form)
+ val cap = viewModel.maxFeeSat(form)
+ val overBalance = price != null && price.totalSat > form.snapshot.spendableMsat / 1000
+ Column(
+ modifier = modifier.readableContent().fillMaxSize().verticalScroll(rememberScrollState()).padding(MaterialTheme.spacing.screenMargin),
+ verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
+ ) {
+ Text(stringResource(Res.string.plan_ahead_your_liquidity), style = MaterialTheme.typography.titleMedium)
+ Text(stringResource(Res.string.liquidity_lets_the_group_receive_more), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ Text(stringResource(Res.string.current_liquidity_s_sats, Satoshi(form.snapshot.inboundMsat / 1000).grouped()), style = MaterialTheme.typography.bodyLarge)
+ Text(stringResource(Res.string.liquidity_to_add_s_sats, Satoshi(amount).grouped()), style = MaterialTheme.typography.titleLarge)
+ // Phoenix's discrete slider, over the amounts the LSP sells and the channel has room for.
+ if (offered.size > 1) {
+ Slider(
+ value = viewModel.choice.toFloat(),
+ onValueChange = { viewModel.choice = it.roundToInt() },
+ valueRange = 0f..offered.lastIndex.toFloat(),
+ steps = (offered.size - 2).coerceAtLeast(0),
+ )
+ }
+ Text(stringResource(Res.string.the_channel_grows_from_s_to_s_sats, Satoshi(channel.capacitySat).grouped(), Satoshi(channel.capacitySat + amount).grouped()), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+
+ price?.let { p ->
+ Card(modifier = Modifier.fillMaxWidth()) {
+ Column(modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) {
+ FeeLine(stringResource(Res.string.miner_fee), stringResource(Res.string.s_sats, Satoshi(p.miningSat).grouped()))
+ FeeLine(stringResource(Res.string.service_fee), stringResource(Res.string.s_sats, Satoshi(p.serviceSat).grouped()))
+ FeeLine(stringResource(Res.string.duration), stringResource(Res.string.one_year))
+ Text(stringResource(Res.string.after_a_year_the_lsp_may_reclaim), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ HorizontalDivider()
+ FeeLine(stringResource(Res.string.total), stringResource(Res.string.s_sats, Satoshi(p.totalSat).grouped()), emphasised = true)
+ Text(stringResource(Res.string.priced_at_s_sat_vbyte_in_term_s, form.available.feeratePerByte.toString(), form.term.toString()), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ }
+ }
+ // Phoenix's two checks: a warning that does not stop anyone, and a balance that does.
+ if (LiquidityPrice.expensive(p, amount)) {
+ Text(stringResource(Res.string.the_fee_is_a_quarter_of_the_amount_or_more), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error)
+ }
+ if (overBalance) {
+ Text(stringResource(Res.string.the_fee_is_more_than_the_group_s_balance), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error)
+ }
+ }
+
+ OutlinedTextField(
+ modifier = Modifier.fillMaxWidth(),
+ state = viewModel.maxFeeField,
+ outputTransformation = GroupedSats,
+ lineLimits = TextFieldLineLimits.SingleLine,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done),
+ label = { Text(stringResource(Res.string.fee_limit_in_sats)) },
+ suffix = { Text(stringResource(Res.string.sats)) },
+ isError = cap == null,
+ supportingText = price?.let { p -> { Text(stringResource(Res.string.left_empty_s_sats, Satoshi(LiquidityPrice.defaultCap(p)).grouped())) } },
+ )
+ Text(stringResource(Res.string.buying_liquidity_asks_the_group_to_sign), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ Button(
+ modifier = Modifier.fillMaxWidth(),
+ onClick = { viewModel.acknowledged = false; viewModel.reviewing = true },
+ enabled = price != null && cap != null && !overBalance && !viewModel.isActionPending.value,
+ ) {
+ Text(stringResource(Res.string.review_the_purchase))
+ }
+ }
+
+ if (viewModel.reviewing) {
+ ModalBottomSheet(onDismissRequest = { viewModel.reviewing = false }) {
+ Column(
+ modifier = Modifier.readableContent().padding(MaterialTheme.spacing.screenMargin),
+ verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
+ ) {
+ Text(stringResource(Res.string.review_the_purchase), style = MaterialTheme.typography.titleMedium)
+ Text(stringResource(Res.string.liquidity_to_add_s_sats, Satoshi(amount).grouped()), style = MaterialTheme.typography.bodyLarge)
+ Text(stringResource(Res.string.liquidity_is_an_initial_amount), style = MaterialTheme.typography.bodyMedium)
+ Row(
+ modifier = Modifier.fillMaxWidth().toggleable(value = viewModel.acknowledged, role = Role.Checkbox, onValueChange = { viewModel.acknowledged = it }).minimumInteractiveComponentSize(),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Checkbox(checked = viewModel.acknowledged, onCheckedChange = null)
+ Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
+ Text(stringResource(Res.string.i_understand))
+ }
+ Button(modifier = Modifier.fillMaxWidth(), onClick = onAsk, enabled = viewModel.acknowledged && !viewModel.isActionPending.value) {
+ Icon(Icons.Default.Bolt, contentDescription = Decorative)
+ Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
+ Text(stringResource(Res.string.ask_the_group))
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun FeeLine(label: String, value: String, emphasised: Boolean = false) {
+ Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
+ Text(label, style = MaterialTheme.typography.bodyMedium, fontWeight = if (emphasised) FontWeight.SemiBold else null)
+ Text(value, style = MaterialTheme.typography.bodyMedium, fontWeight = if (emphasised) FontWeight.SemiBold else null)
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningWalletScreen.kt
index cf1da4e4..6503ab83 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningWalletScreen.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningWalletScreen.kt
@@ -1,5 +1,16 @@
package com.machankura.bennu.compose.ui.composable
+import androidx.compose.material.icons.filled.AddLink
+import androidx.compose.material3.TextButton
+import bennu.composeapp.generated.resources.add_liquidity
+import bennu.composeapp.generated.resources.adding_s_sats_of_inbound_liquidity
+import bennu.composeapp.generated.resources.couldn_t_add_liquidity_s
+import bennu.composeapp.generated.resources.inbound_liquidity_added_s_sats_for_s_sats
+import bennu.composeapp.generated.resources.waiting_for_the_last_splice_before_adding_s_sats
+import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupLightningLiquidityRoute
+import com.machankura.bennu.compose.wallet.lightning.LiquidityPrice
+import com.machankura.bennu.compose.wallet.lightning.WalletWire
+
import bennu.composeapp.generated.resources.a_channel_closed_s_sats_to_the_onchain_wallet
import bennu.composeapp.generated.resources.a_channel_is_closing_s_sats_to_the_onchain_wallet
import androidx.compose.material.icons.filled.LinkOff
@@ -232,6 +243,7 @@ fun GroupLightningWalletScreen(
state = state,
onReceive = { onNavigateToRoute(GroupLightningReceiveRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId)) },
onSend = { onNavigateToRoute(GroupLightningSendRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId)) },
+ onAddLiquidity = { onNavigateToRoute(GroupLightningLiquidityRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId)) },
onClose = { channelId, force -> viewModel.close(channelId, force, onSession = toSession, onFailure = { notify(couldNotPropose) }) },
onSweep = { viewModel.sweep(onSession = toSession, onFailure = { notify(couldNotPropose) }) },
onRekey = {
@@ -250,7 +262,7 @@ fun GroupLightningWalletScreen(
}
@Composable
-private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.Opened, onReceive: () -> Unit, onSend: () -> Unit, onClose: (channelId: String, force: Boolean) -> Unit, onSweep: () -> Unit,
+private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.Opened, onReceive: () -> Unit, onSend: () -> Unit, onAddLiquidity: () -> Unit, onClose: (channelId: String, force: Boolean) -> Unit, onSweep: () -> Unit,
onRekey: () -> Unit,
onCloseEarlier: (GroupLightningWalletUIState.Earlier) -> Unit,
onSweepEarlier: (GroupLightningWalletUIState.Earlier) -> Unit,
@@ -278,7 +290,17 @@ private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.
}
}
}
- item { Balance(state.report, onReceive = onReceive.takeIf { state.operator?.publicKey != null }, onSend = onSend.takeIf { state.operator?.publicKey != null }) }
+ val liquidity = LiquidityPrice.availability(state.report?.snapshot, state.operator?.publicKey != null, GroupLightningRollout.channelCapFor(statement.chain)?.sat)
+ .takeIf { GroupLightningRollout.LIQUIDITY_ENABLED && state.isParticipant }
+ item {
+ Balance(
+ state.report,
+ onReceive = onReceive.takeIf { state.operator?.publicKey != null },
+ onSend = onSend.takeIf { state.operator?.publicKey != null },
+ onAddLiquidity = onAddLiquidity.takeIf { liquidity is LiquidityPrice.Availability.Available && !isPending },
+ liquidityNote = liquidity?.takeIf { it !is LiquidityPrice.Availability.Available && it != LiquidityPrice.Availability.NoOperator }?.let { unavailableBecause(it) },
+ )
+ }
if (state.unswept.isNotEmpty()) {
item {
Card(modifier = Modifier.fillMaxWidth()) {
@@ -292,7 +314,10 @@ private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.
}
state.report?.takeIf { it.checks.isNotEmpty() }?.let { report ->
item { Text(stringResource(Res.string.channels), style = MaterialTheme.typography.titleSmall) }
- items(report.checks, key = { it.channel.channelId }) { ChannelRow(it, onClose = { force: Boolean -> onClose(it.channel.channelId, force) }.takeIf { !isPending }) }
+ items(report.checks, key = { it.channel.channelId }) { check ->
+ val purchase = report.snapshot.purchases.lastOrNull { it.channelId == check.channel.channelId && it.state != WalletWire.LOCKED }
+ ChannelRow(check, purchase, onClose = { force: Boolean -> onClose(check.channel.channelId, force) }.takeIf { !isPending })
+ }
}
item { Text(stringResource(Res.string.payments), style = MaterialTheme.typography.titleSmall) }
if (state.payments.isEmpty()) {
@@ -343,9 +368,12 @@ private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.
}
}
-/** The operator's figure for what the group can spend and receive, or a word that there is none yet. */
+/**
+ * The operator's figure for what the group can spend and receive, or a word that there is none yet. Below
+ * the two actions, *Add liquidity* when the group can be asked for it, or [liquidityNote], why not.
+ */
@Composable
-private fun Balance(report: GroupLightningReports.Report?, onReceive: (() -> Unit)?, onSend: (() -> Unit)?) {
+private fun Balance(report: GroupLightningReports.Report?, onReceive: (() -> Unit)?, onSend: (() -> Unit)?, onAddLiquidity: (() -> Unit)? = null, liquidityNote: String? = null) {
Card(modifier = Modifier.fillMaxWidth()) {
Column(modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) {
Text(stringResource(Res.string.balance), style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant)
@@ -376,13 +404,21 @@ private fun Balance(report: GroupLightningReports.Report?, onReceive: (() -> Uni
}
}
}
+ onAddLiquidity?.let {
+ TextButton(onClick = it) {
+ Icon(Icons.Default.AddLink, contentDescription = Decorative)
+ Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
+ Text(stringResource(Res.string.add_liquidity))
+ }
+ }
+ liquidityNote?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) }
}
}
}
/** One channel, and whether the operator's figure for it is the one this device co-signed. */
@Composable
-private fun ChannelRow(check: GroupLightningReports.ChannelCheck, onClose: ((force: Boolean) -> Unit)?) {
+private fun ChannelRow(check: GroupLightningReports.ChannelCheck, purchase: WalletWire.LiquidityPurchase?, onClose: ((force: Boolean) -> Unit)?) {
val channel = check.channel
ListItem(
leadingContent = {
@@ -394,14 +430,28 @@ private fun ChannelRow(check: GroupLightningReports.ChannelCheck, onClose: ((for
},
headlineContent = { Text(stringResource(Res.string.s_of_s_sats_are_the_group_s, Satoshi(channel.oursMsat / 1000).grouped(), Satoshi(channel.capacitySat).grouped())) },
supportingContent = {
- Text(
- when (check.agrees) {
- true -> stringResource(Res.string.matches_what_your_device_signed)
- false -> stringResource(Res.string.your_device_signed_for_s_sats, Satoshi(check.signedOursMsat!! / 1000).grouped())
- null -> stringResource(Res.string.your_device_hasn_t_signed_for_this_channel)
- },
- color = if (check.agrees == false) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
- )
+ Column {
+ Text(
+ when (check.agrees) {
+ true -> stringResource(Res.string.matches_what_your_device_signed)
+ false -> stringResource(Res.string.your_device_signed_for_s_sats, Satoshi(check.signedOursMsat!! / 1000).grouped())
+ null -> stringResource(Res.string.your_device_hasn_t_signed_for_this_channel)
+ },
+ color = if (check.agrees == false) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ // A purchase the operator's node is making for this channel, or could not make.
+ purchase?.let { p ->
+ val amount = Satoshi(p.amountSat).grouped()
+ Text(
+ when (p.state) {
+ WalletWire.WAITING -> stringResource(Res.string.waiting_for_the_last_splice_before_adding_s_sats, amount)
+ WalletWire.FAILED -> stringResource(Res.string.couldn_t_add_liquidity_s, p.reason.orEmpty())
+ else -> stringResource(Res.string.adding_s_sats_of_inbound_liquidity, amount)
+ },
+ color = if (p.state == WalletWire.FAILED) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ }
},
// Closing is a proposal like any other: the menu only opens the signing session.
trailingContent = onClose?.let { close ->
@@ -430,6 +480,7 @@ private fun ChannelRow(check: GroupLightningReports.ChannelCheck, onClose: ((for
@Composable
internal fun PaymentRow(payment: GroupLightningPaymentRow) {
val isClose = GroupLightningReports.isChannelClose(payment.incoming, payment.paymentHash)
+ val liquidity = payment.liquiditySat
val amount = Satoshi(
if (payment.incoming || isClose) payment.amountMsat / 1000
else GroupLightningReports.recipientMsat(payment.amountMsat, payment.feesMsat) / 1000
@@ -438,6 +489,7 @@ internal fun PaymentRow(payment: GroupLightningPaymentRow) {
leadingContent = {
Icon(
when {
+ liquidity != null -> Icons.Default.AddLink
isClose -> Icons.Default.LinkOff
payment.incoming -> Icons.AutoMirrored.Filled.CallReceived
else -> Icons.AutoMirrored.Filled.CallMade
@@ -448,6 +500,8 @@ internal fun PaymentRow(payment: GroupLightningPaymentRow) {
headlineContent = {
Text(
when {
+ // Bought liquidity is room to be paid, never money sent: its amount is what it cost.
+ liquidity != null -> stringResource(Res.string.inbound_liquidity_added_s_sats_for_s_sats, Satoshi(liquidity).grouped(), Satoshi(payment.amountMsat / 1000).grouped())
payment.incoming -> stringResource(Res.string.received_s_sats, amount)
isClose && payment.succeeded -> stringResource(Res.string.a_channel_closed_s_sats_to_the_onchain_wallet, amount)
isClose -> stringResource(Res.string.a_channel_is_closing_s_sats_to_the_onchain_wallet, amount)
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt
index 79287337..d0bb492c 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt
@@ -14,6 +14,8 @@ import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupLightni
import com.machankura.bennu.compose.ui.composable.GroupLightningWalletScreen
import com.machankura.bennu.compose.ui.composable.GroupLightningReceiveScreen
import com.machankura.bennu.compose.ui.composable.GroupLightningSendScreen
+import com.machankura.bennu.compose.ui.composable.GroupLightningLiquidityScreen
+import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupLightningLiquidityRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupLightningSendRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupLightningReceiveRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.IcebergCeremonyRoute
@@ -748,6 +750,22 @@ fun BennuNavHost(
}
)
}
+ composable { backStackEntry ->
+ val route = backStackEntry.toRoute()
+
+ GroupLightningLiquidityScreen(
+ activeUserPublicKey = route.activeUserPublicKey,
+ chatRoomId = route.chatRoomId,
+ chatRepository = databaseChatRepository,
+ lightningRepository = databaseGroupLightningRepository,
+ onNavigateToRoute = { actionRoute ->
+ navController.navigate(route = actionRoute)
+ },
+ onNavigateBack = {
+ navController.popBackStack()
+ }
+ )
+ }
composable { backStackEntry ->
val route = backStackEntry.toRoute()
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupLightningLiquidityRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupLightningLiquidityRoute.kt
new file mode 100644
index 00000000..349bc94c
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupLightningLiquidityRoute.kt
@@ -0,0 +1,10 @@
+package com.machankura.bennu.compose.ui.composable.navigation.routes
+
+import kotlinx.serialization.Serializable
+
+/** Asking the group to buy inbound liquidity for its Lightning wallet, from the Lightning wallet screen. */
+@Serializable
+data class GroupLightningLiquidityRoute(
+ val activeUserPublicKey: String,
+ val chatRoomId: String,
+) : Route()
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt
index 8f36770e..592fcc98 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt
@@ -961,6 +961,8 @@ private fun RitualNotice(
ChatMessage.TYPE_LIGHTNING_PAYMENT_RECEIVED -> Icons.Default.CallReceived
ChatMessage.TYPE_LIGHTNING_PAYMENT_SENT -> Icons.Default.CallMade
ChatMessage.TYPE_LIGHTNING_PAYMENT_FAILED -> Icons.Default.ErrorOutline
+ ChatMessage.TYPE_LIGHTNING_LIQUIDITY_ADDED -> Icons.Default.AddLink
+ ChatMessage.TYPE_LIGHTNING_LIQUIDITY_FAILED -> Icons.Default.ErrorOutline
ChatMessage.TYPE_LIGHTNING_REFUSED -> Icons.Default.Block
ChatMessage.TYPE_LIGHTNING_EQUIVOCATION -> Icons.Default.Warning
@@ -986,6 +988,7 @@ private fun RitualNotice(
chatMessage.messageType == ChatMessage.TYPE_FROST_FAILED ||
chatMessage.messageType == ChatMessage.TYPE_MEMBER_INVITE_FAILED ||
chatMessage.messageType == ChatMessage.TYPE_LIGHTNING_PAYMENT_FAILED ||
+ chatMessage.messageType == ChatMessage.TYPE_LIGHTNING_LIQUIDITY_FAILED ||
chatMessage.messageType == ChatMessage.TYPE_LIGHTNING_REFUSED ||
chatMessage.messageType == ChatMessage.TYPE_LIGHTNING_EQUIVOCATION ||
chatMessage.messageType == ChatMessage.TYPE_CHANGE_REJECTED ->
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningLiquidityViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningLiquidityViewModel.kt
new file mode 100644
index 00000000..72195df7
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningLiquidityViewModel.kt
@@ -0,0 +1,123 @@
+package com.machankura.bennu.compose.ui.view.model
+
+import androidx.compose.foundation.text.input.TextFieldState
+import androidx.compose.runtime.MutableState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+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.managers.GroupLightningAuthorisations
+import com.machankura.bennu.compose.repository.ChatRepository
+import com.machankura.bennu.compose.repository.GroupLightningRepository
+import com.machankura.bennu.compose.text.SatsInput
+import com.machankura.bennu.compose.text.parseSats
+import com.machankura.bennu.compose.ui.view.state.GroupLightningLiquidityUIState
+import com.machankura.bennu.compose.wallet.GroupLightningRollout
+import com.machankura.bennu.compose.wallet.lightning.LiquidityPrice
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import fr.acinq.bitcoin.Chain
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+
+/**
+ * A liquidity purchase, as a proposal (`docs/group-lightning-liquidity.md`, Phase 7): one of Phoenix's
+ * amounts that the LSP sells and the channel has room for, priced on this device from what the
+ * operator reported, and a fee cap with room above the estimate. The group signs it like any decision,
+ * and the operator's node buys once it has.
+ */
+class GroupLightningLiquidityViewModel(
+ val activeUserPublicKey: HexKey,
+ val chatRoomId: String,
+ val chain: Chain,
+ initialUIState: GroupLightningLiquidityUIState,
+ private val chatRepository: ChatRepository,
+ private val lightningRepository: GroupLightningRepository,
+) : ViewModel() {
+ private val logger = Logger.withTag(TAG)
+
+ var uiState: GroupLightningLiquidityUIState by mutableStateOf(initialUIState)
+ private set
+
+ /** Which of the offered amounts is chosen. */
+ var choice by mutableIntStateOf(0)
+
+ val maxFeeField = TextFieldState()
+ /** The review sheet is open, and whether its acknowledgement is ticked. */
+ var reviewing by mutableStateOf(false)
+ var acknowledged by mutableStateOf(false)
+ val isActionPending: MutableState = mutableStateOf(false)
+
+ fun initiate() {
+ viewModelScope.launch(Dispatchers.IO) {
+ val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId)
+ ?: return@launch run { uiState = GroupLightningLiquidityUIState.Error("Couldn't find the group") }
+ val wallet = lightningRepository.lightningWallet(chatRoomId, chain)
+ ?: return@launch run { uiState = GroupLightningLiquidityUIState.Unavailable(LiquidityPrice.Availability.NoOperator) }
+ val hasOperator = lightningRepository.operator(chatRoomId, chain, wallet.statement.wallet)?.publicKey != null
+ lightningRepository.observeReport(chatRoomId, chain, wallet.statement.wallet).collect { report ->
+ uiState = when (val availability = LiquidityPrice.availability(report?.snapshot, hasOperator, GroupLightningRollout.channelCapFor(chain)?.sat)) {
+ is LiquidityPrice.Availability.Available -> {
+ choice = choice.coerceIn(0, availability.offered.lastIndex)
+ GroupLightningLiquidityUIState.Form(localChatRoom, wallet, report!!.snapshot, availability)
+ }
+ else -> GroupLightningLiquidityUIState.Unavailable(availability)
+ }
+ }
+ }
+ }
+
+ /** The amount chosen, in sats. */
+ fun amountSat(form: GroupLightningLiquidityUIState.Form): Long = form.available.offered[choice.coerceIn(0, form.available.offered.lastIndex)]
+
+ fun price(form: GroupLightningLiquidityUIState.Form): LiquidityPrice.Price? =
+ LiquidityPrice.price(form.available.rates, amountSat(form), form.available.feeratePerByte)
+
+ fun maxFee(): SatsInput = parseSats(maxFeeField.text)
+
+ /** The cap the proposal will carry: the field's, or the estimate with room above it when the field is empty. */
+ fun maxFeeSat(form: GroupLightningLiquidityUIState.Form): Long? = when (val fee = maxFee()) {
+ SatsInput.Empty -> price(form)?.let(LiquidityPrice::defaultCap)
+ is SatsInput.Sats -> fee.amount.sat
+ else -> null
+ }
+
+ fun propose(onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) {
+ val form = uiState as? GroupLightningLiquidityUIState.Form ?: return
+ val cap = maxFeeSat(form) ?: return onFailure()
+ val buy = GroupLightningAuthorisations.prepareBuyLiquidity(form.wallet, form.available.channel.channelId, form.available.channel.capacitySat, amountSat(form), cap).getOrNull() ?: return onFailure()
+ if (isActionPending.value) return
+ isActionPending.value = true
+ viewModelScope.launch(Dispatchers.IO) {
+ val session = runCatching { lightningRepository.proposeLiquidity(form.localChatRoom, activeUserPublicKey, buy) }
+ .onFailure { logger.e("Liquidity proposal in $chatRoomId failed", it) }.getOrNull()
+ isActionPending.value = false
+ withContext(Dispatchers.Main) {
+ reviewing = false
+ if (session != null) onSession(session.id) else onFailure()
+ }
+ }
+ }
+
+ companion object {
+ private const val TAG = "GroupLightningLiquidityViewModel"
+
+ fun factory(
+ activeUserPublicKey: HexKey,
+ chatRoomId: String,
+ chain: Chain,
+ chatRepository: ChatRepository,
+ lightningRepository: GroupLightningRepository,
+ ): ViewModelProvider.Factory = viewModelFactory {
+ initializer {
+ GroupLightningLiquidityViewModel(activeUserPublicKey, chatRoomId, chain, GroupLightningLiquidityUIState.Loading, chatRepository, lightningRepository)
+ }
+ }
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningLiquidityUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningLiquidityUIState.kt
new file mode 100644
index 00000000..293894ff
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningLiquidityUIState.kt
@@ -0,0 +1,26 @@
+package com.machankura.bennu.compose.ui.view.state
+
+import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
+import com.machankura.bennu.compose.managers.GroupLightningWalletManager
+import com.machankura.bennu.compose.wallet.lightning.LiquidityPrice
+import com.machankura.bennu.compose.wallet.lightning.WalletWire
+
+/** Asking the group to buy inbound liquidity (`docs/group-lightning-liquidity.md`, Phase 7). */
+sealed class GroupLightningLiquidityUIState {
+ data object Loading : GroupLightningLiquidityUIState()
+
+ data class Error(val message: String) : GroupLightningLiquidityUIState()
+
+ /** Nothing can be asked for now, and [why]. */
+ data class Unavailable(val why: LiquidityPrice.Availability) : GroupLightningLiquidityUIState()
+
+ /** What can be bought, priced from the operator's [snapshot] of the term [term]. */
+ data class Form(
+ val localChatRoom: LocalChatRoom,
+ val wallet: GroupLightningWalletManager.Wallet,
+ val snapshot: WalletWire.Snapshot,
+ val available: LiquidityPrice.Availability.Available,
+ ) : GroupLightningLiquidityUIState() {
+ val term: Long get() = snapshot.term
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupLightningRollout.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupLightningRollout.kt
index 8aa2520d..beccc897 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupLightningRollout.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupLightningRollout.kt
@@ -38,6 +38,13 @@ object GroupLightningRollout {
*/
val MAINNET_CHANNEL_CAP: Satoshi = Satoshi(1_000_000)
+ /**
+ * Whether a member may ask the group to buy inbound liquidity, and the operator's node buys it
+ * (`docs/group-lightning-liquidity.md`). Co-signers check a purchase whether or not it is on, so a
+ * group whose devices all run this build is ready when it lifts.
+ */
+ const val LIQUIDITY_ENABLED: Boolean = false
+
/** The most a channel on [chain] may hold, or null where there is no cap. */
fun channelCapFor(chain: Chain): Satoshi? = MAINNET_CHANNEL_CAP.takeIf { chain.isMainnet() }
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/LiquidityPrice.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/LiquidityPrice.kt
new file mode 100644
index 00000000..ee6c6493
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/LiquidityPrice.kt
@@ -0,0 +1,109 @@
+package com.machankura.bennu.compose.wallet.lightning
+
+import fr.acinq.bitcoin.ByteVector
+import fr.acinq.bitcoin.OutPoint
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.bitcoin.Satoshi
+import fr.acinq.bitcoin.TxId
+import fr.acinq.bitcoin.TxOut
+import fr.acinq.lightning.blockchain.fee.FeeratePerByte
+import fr.acinq.lightning.blockchain.fee.FeeratePerKw
+import fr.acinq.lightning.channel.FundingContributions
+import fr.acinq.lightning.channel.SharedFundingInput
+import fr.acinq.lightning.transactions.Transactions
+import fr.acinq.lightning.wire.LiquidityAds
+
+/**
+ * What buying inbound liquidity costs, worked out on a member's own device from what the operator
+ * reported (`docs/group-lightning-liquidity.md`, decision L5 and Phase 7): the LSP's rates and the
+ * node's feerate. The service fee follows from the rate alone; the mining fee from the feerate, which
+ * is the operator's claim, so the authorisation's cap leaves room above it.
+ *
+ * The arithmetic is lightning-kmp's own, as Phoenix's estimate is: the rate's [LiquidityAds.FundingRate.fees]
+ * for the service fee and the LSP's inputs, and [FundingContributions.computeWeightPaid] for our share of
+ * the splice, which depends only on the sizes of a taproot funding input and output.
+ */
+object LiquidityPrice {
+ /** Phoenix's amounts (`LiquidityLimits.liquidityOptions`), in sats. */
+ val OPTIONS: List = listOf(100_000, 250_000, 500_000, 1_000_000, 2_000_000, 10_000_000)
+
+ /** How much above the estimate the cap the group signs sits, in percent: room for the feerate to rise before the purchase. */
+ const val CAP_HEADROOM_PERCENT = 50
+
+ /** Phoenix warns when the fee reaches this share of the amount, in percent. */
+ const val EXPENSIVE_PERCENT = 25
+
+ /** What one purchase costs: our share of the mining fee, the LSP's inputs' share, and the service fee. */
+ data class Price(val ourMiningSat: Long, val lspMiningSat: Long, val serviceSat: Long) {
+ val miningSat: Long get() = ourMiningSat + lspMiningSat
+ val totalSat: Long get() = miningSat + serviceSat
+ }
+
+ private fun rateOf(rate: WalletWire.FundingRate) = LiquidityAds.FundingRate(
+ Satoshi(rate.minAmountSat), Satoshi(rate.maxAmountSat), rate.fundingWeight, rate.feeProportional, Satoshi(rate.feeBaseSat), Satoshi(rate.channelCreationFeeSat),
+ )
+
+ /** The rate that sells [amountSat], as lightning-kmp's `findRate` picks it: the first that covers it. */
+ fun rateFor(rates: WalletWire.FundingRates, amountSat: Long): WalletWire.FundingRate? =
+ rates.rates.firstOrNull { amountSat in it.minAmountSat..it.maxAmountSat }
+
+ /** Our weight in a splice that only buys liquidity: the shared input and output and the common fields. */
+ private val ourWeight: Int by lazy {
+ val script = Transactions.makeFundingInputInfo(TxId(ByteArray(32)), 0, Satoshi(0), PrivateKey(ByteArray(32) { 1 }).publicKey(), PrivateKey(ByteArray(32) { 2 }).publicKey(), Transactions.CommitmentFormat.SimpleTaprootChannels).txOut.publicKeyScript
+ val shared = SharedFundingInput(Transactions.InputInfo(OutPoint(TxId(ByteArray(32)), 0), TxOut(Satoshi(0), script)), 0, PrivateKey(ByteArray(32) { 2 }).publicKey(), Transactions.CommitmentFormat.SimpleTaprootChannels)
+ FundingContributions.computeWeightPaid(isInitiator = true, sharedInput = shared, sharedOutputScript = ByteVector(script.toByteArray()), walletInputs = emptyList(), localOutputs = emptyList())
+ }
+
+ /** What buying [amountSat] would cost at [feeratePerByte], or null when no rate sells that amount. */
+ fun price(rates: WalletWire.FundingRates, amountSat: Long, feeratePerByte: Long): Price? {
+ val rate = rateFor(rates, amountSat)?.let(::rateOf) ?: return null
+ val feerate = FeeratePerKw(FeeratePerByte(Satoshi(feeratePerByte)))
+ val fees = rate.fees(feerate, Satoshi(amountSat), Satoshi(amountSat), isChannelCreation = false)
+ return Price(Transactions.weight2fee(feerate, ourWeight).sat, fees.miningFee.sat, fees.serviceFee.sat)
+ }
+
+ /** The fee cap a proposal carries by default: the estimate and [CAP_HEADROOM_PERCENT] more. */
+ fun defaultCap(price: Price): Long = price.totalSat + price.totalSat * CAP_HEADROOM_PERCENT / 100
+
+ /** Whether the fee is [EXPENSIVE_PERCENT] of the amount or more, as Phoenix warns. */
+ fun expensive(price: Price, amountSat: Long): Boolean = price.totalSat * 100 >= amountSat * EXPENSIVE_PERCENT
+
+ /**
+ * The amounts that can be offered for a channel of [capacitySat]: Phoenix's, less those no rate sells
+ * and those that would take the channel over [capSat], the most a channel may hold on this network.
+ */
+ fun offered(rates: WalletWire.FundingRates, capacitySat: Long, capSat: Long?): List =
+ OPTIONS.filter { rateFor(rates, it) != null && (capSat == null || capacitySat + it <= capSat) }
+
+ /** Whether the group can be asked to buy liquidity now, and if not, why not. */
+ sealed class Availability {
+ data object NoOperator : Availability()
+ /** The operator has not reported the wallet, or not what the LSP sells. */
+ data object NoPrices : Availability()
+ /** No channel to splice: the first payment opens one. */
+ data object NoChannel : Availability()
+ /** The channel is at the most a channel may hold on this network. */
+ data object AtTheCap : Availability()
+ /** The LSP sells none of [OPTIONS]. */
+ data object NothingSold : Availability()
+ data class Available(val channel: WalletWire.ChannelView, val offered: List, val rates: WalletWire.FundingRates, val feeratePerByte: Long) : Availability()
+ }
+
+ /** What [snapshot] lets a member ask for, on a network whose channels hold at most [capSat]. */
+ fun availability(snapshot: WalletWire.Snapshot?, hasOperator: Boolean, capSat: Long?): Availability {
+ if (!hasOperator) return Availability.NoOperator
+ if (snapshot == null) return Availability.NoPrices
+ val channel = snapshot.channels.firstOrNull { it.state == NORMAL } ?: return Availability.NoChannel
+ val rates = snapshot.fundingRates ?: return Availability.NoPrices
+ val feerate = snapshot.feeratePerByte ?: return Availability.NoPrices
+ val offered = offered(rates, channel.capacitySat, capSat)
+ return when {
+ offered.isNotEmpty() -> Availability.Available(channel, offered, rates, feerate)
+ offered(rates, channel.capacitySat, null).isNotEmpty() -> Availability.AtTheCap
+ else -> Availability.NothingSold
+ }
+ }
+
+ /** lightning-kmp's name for the state a channel can be spliced in. */
+ private const val NORMAL = "Normal"
+}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/LightningPaymentRowJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/LightningPaymentRowJvmTest.kt
index 2c695171..311f8e51 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/LightningPaymentRowJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/LightningPaymentRowJvmTest.kt
@@ -38,4 +38,30 @@ class LightningPaymentRowJvmTest {
onNodeWithText("A channel closed: 76,816 sats to the onchain wallet").assertIsDisplayed()
onNodeWithText("A channel is closing: 50,000 sats to the onchain wallet").assertIsDisplayed()
}
+
+ @Test
+ fun `bought liquidity is room to be paid, with what it cost, never money sent`() = runDesktopComposeUiTest {
+ setContent {
+ BennuTheme {
+ PaymentRow(GroupLightningPaymentRow("w", "liquidity:t", incoming = false, amountMsat = 2_521_000, feesMsat = 2_521_000, paymentHash = null, description = null, completedAt = null, succeeded = true, liquiditySat = 200_000))
+ }
+ }
+ onNodeWithText("Inbound liquidity added: 200,000 sats, for 2,521 sats in fees").assertIsDisplayed()
+ }
+
+ @Test
+ fun `why liquidity cannot be asked for is said in words`() = runDesktopComposeUiTest {
+ setContent {
+ BennuTheme {
+ Column {
+ androidx.compose.material3.Text(unavailableBecause(com.machankura.bennu.compose.wallet.lightning.LiquidityPrice.Availability.NoChannel))
+ androidx.compose.material3.Text(unavailableBecause(com.machankura.bennu.compose.wallet.lightning.LiquidityPrice.Availability.AtTheCap))
+ androidx.compose.material3.Text(unavailableBecause(com.machankura.bennu.compose.wallet.lightning.LiquidityPrice.Availability.NoPrices))
+ }
+ }
+ }
+ onNodeWithText("Receive a payment first: it opens the channel.").assertIsDisplayed()
+ onNodeWithText("The channel holds the most a channel may on this network for now.").assertIsDisplayed()
+ onNodeWithText("The operator hasn't reported what the LSP sells yet.").assertIsDisplayed()
+ }
}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt
index 5d7c3390..6ba00b39 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt
@@ -128,6 +128,7 @@ class GroupLightningWalletViewModelJvmTest {
"r1".also { requests += amountMsat to description }
override fun observeInvoice(chatRoomId: String, chain: Chain, wallet: Long, requestId: String): Flow = flowOf(invoice?.takeIf { it.requestId == requestId })
override suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession = error("unused")
+ override suspend fun proposeLiquidity(localChatRoom: LocalChatRoom, userPublicKey: HexKey, buy: GroupLightningAuthorisationEvent.BuyLiquidity): FrostSigningSession = error("unused")
override suspend fun proposeClose(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession = error("unused")
override suspend fun earlierWallets(chatRoomId: String, chain: Chain): List = earlier
override suspend fun departed(wallet: GroupLightningWalletManager.Wallet): List = departedMembers
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/lightning/LiquidityPriceJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/lightning/LiquidityPriceJvmTest.kt
new file mode 100644
index 00000000..12b4ab99
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/lightning/LiquidityPriceJvmTest.kt
@@ -0,0 +1,59 @@
+package com.machankura.bennu.compose.wallet.lightning
+
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+
+/**
+ * What a member's device works out a purchase costs (`docs/group-lightning-liquidity.md`, Phase 7),
+ * held to what eclair charged in Phase 0's regtest run: 200,000 sats at 2 sat/vbyte for 2,521, our
+ * share of the mining fee 221, the LSP's inputs' 200 and the service fee 2,100.
+ */
+class LiquidityPriceJvmTest {
+ private val regtestRates = WalletWire.FundingRates(listOf(WalletWire.FundingRate(10_000, 10_000_000, 400, 100, 100, 1_000)), listOf("from_channel_balance"))
+
+ @Test
+ fun `the price is what eclair charged`() {
+ val price = LiquidityPrice.price(regtestRates, 200_000, 2)!!
+ assertEquals(LiquidityPrice.Price(ourMiningSat = 221, lspMiningSat = 200, serviceSat = 2_100), price)
+ assertEquals(2_521, price.totalSat)
+ assertEquals(3_781, LiquidityPrice.defaultCap(price))
+ }
+
+ @Test
+ fun `no rate, no price, and the amounts offered are those the LSP sells under the cap`() {
+ assertNull(LiquidityPrice.price(regtestRates, 5_000, 2))
+ assertEquals(LiquidityPrice.OPTIONS, LiquidityPrice.offered(regtestRates, 25_000, null))
+ assertEquals(listOf(100_000L, 250_000L, 500_000L), LiquidityPrice.offered(regtestRates, 25_000, 1_000_000), "a 25,000-sat channel under the mainnet cap")
+ assertEquals(emptyList(), LiquidityPrice.offered(regtestRates, 950_000, 1_000_000), "a channel at the cap buys nothing")
+ val narrow = WalletWire.FundingRates(listOf(WalletWire.FundingRate(200_000, 600_000, 400, 100, 100, 1_000)), listOf("from_channel_balance"))
+ assertEquals(listOf(250_000L, 500_000L), LiquidityPrice.offered(narrow, 25_000, null))
+ }
+
+ @Test
+ fun `a fee of a quarter of the amount or more is expensive, as Phoenix warns`() {
+ assertFalse(LiquidityPrice.expensive(LiquidityPrice.price(regtestRates, 200_000, 2)!!, 200_000))
+ assertTrue(LiquidityPrice.expensive(LiquidityPrice.Price(0, 0, 25_000), 100_000))
+ }
+
+ private fun channel(state: String = "Normal", capacitySat: Long = 25_000) = WalletWire.ChannelView("c", state, capacitySat, 21_900_000, 3_100_000, "f", 0, 1)
+ private fun snapshot(channels: List, rates: WalletWire.FundingRates? = regtestRates, feerate: Long? = 2) =
+ WalletWire.Snapshot("w", 1, "n", 0, channels, emptyList(), fundingRates = rates, feeratePerByte = feerate)
+
+ @Test
+ fun `when the group can be asked, and why not`() {
+ assertEquals(LiquidityPrice.Availability.NoOperator, LiquidityPrice.availability(snapshot(listOf(channel())), hasOperator = false, capSat = null))
+ assertEquals(LiquidityPrice.Availability.NoPrices, LiquidityPrice.availability(null, true, null))
+ assertEquals(LiquidityPrice.Availability.NoChannel, LiquidityPrice.availability(snapshot(emptyList()), true, null))
+ assertEquals(LiquidityPrice.Availability.NoChannel, LiquidityPrice.availability(snapshot(listOf(channel(state = "Closing"))), true, null))
+ assertEquals(LiquidityPrice.Availability.NoPrices, LiquidityPrice.availability(snapshot(listOf(channel()), rates = null), true, null))
+ assertEquals(LiquidityPrice.Availability.NoPrices, LiquidityPrice.availability(snapshot(listOf(channel()), feerate = null), true, null))
+ assertEquals(LiquidityPrice.Availability.AtTheCap, LiquidityPrice.availability(snapshot(listOf(channel(capacitySat = 950_000))), true, 1_000_000))
+ val none = WalletWire.FundingRates(listOf(WalletWire.FundingRate(20_000_000, 30_000_000, 400, 100, 100, 1_000)), listOf("from_channel_balance"))
+ assertEquals(LiquidityPrice.Availability.NothingSold, LiquidityPrice.availability(snapshot(listOf(channel()), rates = none), true, null))
+ val available = LiquidityPrice.availability(snapshot(listOf(channel())), true, 1_000_000)
+ assertTrue(available is LiquidityPrice.Availability.Available && available.offered == listOf(100_000L, 250_000L, 500_000L))
+ }
+}
diff --git a/docs/group-lightning-liquidity.md b/docs/group-lightning-liquidity.md
index 25c68c97..37ca0d7b 100644
--- a/docs/group-lightning-liquidity.md
+++ b/docs/group-lightning-liquidity.md
@@ -35,6 +35,7 @@ differently, this table says so.
| 4 | done: `buy-liquidity` (`GroupLightningAuthorisationEvent.BuyLiquidity`), `liquidityPurchases`, `prepareBuyLiquidity`, `proposeBuyLiquidity`, its summary and its transcript line. `GroupLightningLiquidityJvmTest`, three tests, run on regtest and on mainnet |
| 5 | done: a ledger per funding output (schema 35, `IcebergChannelLedger` keyed by output, with `fundingTxIndex`, `parentOutPoint` and `purchaseId`), `CoSignerPolicy.openSplice`, the shared input checked against S1 to S6, and a payment that settles on both live commitments spending its budget once. `GroupLightningSpliceCoSigningJvmTest`, seven four-device tests on regtest and on mainnet, among them a purchase the script interpreter accepts |
| 6 | done: `PeerHandle.fundingRates`, `feeratePerByte` and `buyLiquidity`, `GroupLightningNode.buyAuthorised` on the node's watch, and the snapshot's rates, feerate and purchases. Four tests with the stand-in peer in `GroupLightningLiquidityJvmTest` |
+| 7 | done, behind `GroupLightningRollout.LIQUIDITY_ENABLED`, which is off until Phase 10: `GroupLightningLiquidityScreen` and its route, view model and state; *Add liquidity* on the wallet's balance card, or the reason it is not there; a purchase's state on its channel row; *Inbound liquidity added* in the payment list; and two transcript lines from the snapshot, added and failed. `LiquidityPrice` works out the price on the member's device, and matches what eclair charged in Phase 0 to the sat. Tests: `LiquidityPriceJvmTest`, and two more cases in `LightningPaymentRowJvmTest`. `m3Audit` meets every budget |
| what the plan said | what it turned out to be |
|---|---|
@@ -53,6 +54,12 @@ differently, this table says so.
| Phase 6: the node records the purchase from the payments database, and on-the-fly opens get the same row | the purchase's row comes from the answer: `buyLiquidity` adds a `liquidity` payment as it returns `PENDING`. On-the-fly opens still report nothing of their own: `LiquidityEvents.Purchased` carries no channel or transaction, and the payments database has no query for every purchase. They are left as they were |
| Phase 6: `requestInboundLiquidity` for the authorisation's channel | for the node's first `Normal` channel, which is all lightning-kmp's `Peer` offers. A group node has one channel to its LSP; the authorisation still names the channel, and every co-signer holds the splice to it |
| Phase 7's *Try again* acts under the same authorisation | a failed purchase is not tried again by the node at all, as a failed payment is not; *Try again* proposes a new authorisation. Every attempt under one authorisation spends the same parent output in any case, so a retry would have bought nothing a new one does not |
+| Phase 7: the price on the member's device | as written, with lightning-kmp's own arithmetic: `LiquidityAds.FundingRate.fees` for the service fee and the LSP's inputs, and `FundingContributions.computeWeightPaid` over a stand-in taproot input for our share. It is the price at the reported feerate before any CPFP bump the node may add, which is why the cap carries 50% more by default |
+| *as reported by Thandi, 2 minutes ago* | *the feerate the operator reported in term N*, as the balance card already says its figures are the operator's of a term |
+| *Ask the group* returns to the wallet screen with a snackbar | it opens the signing session, as *Send* does: the proposer is the first to sign |
+| the payment row comes from the snapshot's `kind` | from a nullable `liquiditySat` on `GroupLightningPaymentRow`. It went into schema 35, which this branch made and nothing installed has, rather than a 36 |
+| Phase 10's gate | added here, off, so the screen and the node's purchases ship dark until the regtest run of Phase 8 passes. Co-signers check a purchase either way |
+| the screen's JVM tests cover each reason, the fee lines and the payment row | the reasons, the price and the payment row. The form itself is not rendered in a test: it needs the view model over a repository, and what it shows is `LiquidityPrice`'s, which is |
| S4: the new funding amount is at least the old one plus the amount less `purchase.fees.miningFee` | less **our own share of the splice's mining fee**, which is the splice's negative local contribution. `purchase.fees.miningFee` is the LSP's inputs' share, which the group pays from its balance with the service fee, in the first commitment on the new output. Phoenix's estimate (`ChannelManagementFees.miningFee`) is the two shares together, so `estimate.total = -localContribution + purchase.fees.total`, and the authorisation's cap covers both |
### What Phase 0 found