-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDeriveBalanceStateUseCase.kt
More file actions
209 lines (180 loc) · 8.97 KB
/
Copy pathDeriveBalanceStateUseCase.kt
File metadata and controls
209 lines (180 loc) · 8.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package to.bitkit.usecases
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
import org.lightningdevkit.ldknode.BalanceDetails
import org.lightningdevkit.ldknode.BalanceSource
import org.lightningdevkit.ldknode.ChannelDetails
import org.lightningdevkit.ldknode.LightningBalance
import to.bitkit.data.SettingsStore
import to.bitkit.data.entities.TransferEntity
import to.bitkit.di.BgDispatcher
import to.bitkit.env.Defaults
import to.bitkit.ext.amountSats
import to.bitkit.ext.channelId
import to.bitkit.ext.totalNextOutboundHtlcLimitSats
import to.bitkit.models.BalanceState
import to.bitkit.models.TransferType
import to.bitkit.models.safe
import to.bitkit.models.toBalance
import to.bitkit.repositories.HwWalletRepo
import to.bitkit.repositories.LightningRepo
import to.bitkit.repositories.TransferRepo
import to.bitkit.utils.Logger
import to.bitkit.utils.jsonLogOf
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DeriveBalanceStateUseCase @Inject constructor(
@BgDispatcher private val bgDispatcher: CoroutineDispatcher,
private val lightningRepo: LightningRepo,
private val transferRepo: TransferRepo,
private val settingsStore: SettingsStore,
private val hwWalletRepo: HwWalletRepo,
) {
suspend operator fun invoke(): Result<BalanceState> = withContext(bgDispatcher) {
runCatching {
val balanceDetails = lightningRepo.getBalancesAsync().getOrThrow()
val channels = lightningRepo.getChannels().orEmpty()
val activeTransfers = transferRepo.activeTransfers.first()
val paidOrdersSats = getOrderPaymentsSats(activeTransfers, channels, balanceDetails)
val pendingChannelsSats = getPendingChannelsSats(activeTransfers, channels, balanceDetails)
val toSavingsAmount = getTransferToSavingsSats(activeTransfers, channels, balanceDetails)
val coopCloseSavingsSats = getCoopCloseTransferSats(activeTransfers, channels, balanceDetails)
val lingeringCoopCloseSats = getLingeringCoopCloseSats(activeTransfers, channels, balanceDetails)
val toSpendingAmount = paidOrdersSats.safe() + pendingChannelsSats.safe()
val totalOnchainSats = balanceDetails.totalOnchainBalanceSats
val channelFundableBalance = getMaxChannelFundableAmount(lightningRepo.getChannelFundableBalance())
val afterPendingChannels = balanceDetails.totalLightningBalanceSats.safe() - pendingChannelsSats.safe()
val afterClosingChannels = afterPendingChannels.safe() - toSavingsAmount.safe()
val totalLightningSats = afterClosingChannels.safe() - lingeringCoopCloseSats.safe()
val balanceState = BalanceState(
totalOnchainSats = totalOnchainSats,
channelFundableBalance = channelFundableBalance,
totalLightningSats = totalLightningSats,
maxSendLightningSats = lightningRepo.getChannels().totalNextOutboundHtlcLimitSats(),
maxSendOnchainSats = getMaxSendAmount(balanceDetails),
balanceInTransferToSavings = toSavingsAmount.safe() - coopCloseSavingsSats.safe(),
balanceInTransferToSpending = toSpendingAmount,
hardwareWallets = hwWalletRepo.wallets.value.map { it.toBalance() },
)
val height = lightningRepo.lightningState.value.block()?.height
Logger.verbose("Active transfers at block height=$height: ${jsonLogOf(activeTransfers)}", context = TAG)
Logger.verbose("Balances in ldk-node at block height=$height: ${jsonLogOf(balanceDetails)}", context = TAG)
Logger.verbose("Balances in state at block height=$height: ${jsonLogOf(balanceState)}", context = TAG)
return@runCatching balanceState
}
}
private suspend fun getOrderPaymentsSats(
transfers: List<TransferEntity>,
channels: List<ChannelDetails>,
balances: BalanceDetails,
): ULong {
var amount = 0uL
val paidOrders = transfers.filter { it.type.isToSpending() && it.lspOrderId != null }
for (transfer in paidOrders) {
val channelId = transferRepo.resolveChannelIdForTransfer(transfer, channels)
val channelBalance = channelId?.let { id ->
balances.lightningBalances.find { it.channelId() == id }
}
if (channelBalance == null) {
amount = amount.safe() + transfer.amountSats.toULong().safe()
}
}
return amount
}
private suspend fun getPendingChannelsSats(
transfers: List<TransferEntity>,
channels: List<ChannelDetails>,
balances: BalanceDetails,
): ULong {
var amount = 0uL
val pendingTransfers = transfers.filter { it.type.isToSpending() }
for (transfer in pendingTransfers) {
val channelId = transferRepo.resolveChannelIdForTransfer(transfer, channels)
val channel = channels.find { it.channelId == channelId }
if (channel != null && !channel.isChannelReady) {
val channelBalance = balances.lightningBalances.find { it.channelId() == channel.channelId }
amount = amount.safe() + (channelBalance?.amountSats() ?: 0uL).safe()
}
}
return amount
}
private suspend fun getTransferToSavingsSats(
transfers: List<TransferEntity>,
channels: List<ChannelDetails>,
balanceDetails: BalanceDetails,
): ULong {
var toSavingsAmount = 0uL
val toSavings = transfers.filter { it.type.isToSavings() }
for (transfer in toSavings) {
val channelId = transferRepo.resolveChannelIdForTransfer(transfer, channels)
val channelBalance = balanceDetails.lightningBalances.find { it.channelId() == channelId }
toSavingsAmount = toSavingsAmount.safe() + (channelBalance?.amountSats() ?: 0uL).safe()
}
return toSavingsAmount
}
private suspend fun getMaxChannelFundableAmount(fundableBalance: ULong): ULong {
if (fundableBalance == 0uL) return 0u
val fallback = (fundableBalance.toDouble() * FALLBACK_FEE_PERCENT).toULong()
val speed = settingsStore.data.first().defaultTransactionSpeed
val fee = lightningRepo.estimateSendAllFee(
speed = speed,
).onFailure {
Logger.debug("Could not calculate channel funding fee, using fallback of: $fallback", context = TAG)
}.getOrDefault(fallback)
return fundableBalance.safe() - fee.safe()
}
private suspend fun getCoopCloseTransferSats(
transfers: List<TransferEntity>,
channels: List<ChannelDetails>,
balanceDetails: BalanceDetails,
): ULong {
var amount = 0uL
for (transfer in transfers.filter { it.type == TransferType.COOP_CLOSE }) {
val channelId = transferRepo.resolveChannelIdForTransfer(transfer, channels)
val channelBalance = balanceDetails.lightningBalances.find { it.channelId() == channelId }
amount = amount.safe() + (channelBalance?.amountSats() ?: 0uL).safe()
}
return amount
}
private suspend fun getLingeringCoopCloseSats(
transfers: List<TransferEntity>,
channels: List<ChannelDetails>,
balanceDetails: BalanceDetails,
): ULong {
val channelIds = channels.map { it.channelId }.toSet()
val transferChannelIds = mutableSetOf<String>()
for (transfer in transfers.filter { it.type.isToSavings() }) {
transferRepo.resolveChannelIdForTransfer(transfer, channels)?.let { transferChannelIds.add(it) }
}
var amount = 0uL
val claimableBalances = balanceDetails.lightningBalances
.filterIsInstance<LightningBalance.ClaimableAwaitingConfirmations>()
for (balance in claimableBalances) {
val isLingeringCoopClose = balance.source == BalanceSource.COOP_CLOSE &&
balance.channelId !in channelIds &&
balance.channelId !in transferChannelIds
if (isLingeringCoopClose) {
amount = amount.safe() + balance.amountSatoshis.safe()
}
}
return amount
}
private suspend fun getMaxSendAmount(balanceDetails: BalanceDetails): ULong {
val spendableOnchainSats = balanceDetails.spendableOnchainBalanceSats
if (spendableOnchainSats == 0uL) return 0u
val fallback = (spendableOnchainSats.toDouble() * FALLBACK_FEE_PERCENT).toULong()
val speed = settingsStore.data.first().defaultTransactionSpeed
val fee = lightningRepo.estimateSendAllFee(
speed = speed,
).onFailure {
Logger.debug("Could not calculate max send amount, using fallback of: $fallback", context = TAG)
}.getOrDefault(fallback)
return spendableOnchainSats.safe() - fee.safe()
}
companion object {
const val TAG = "DeriveBalanceStateUseCase"
const val FALLBACK_FEE_PERCENT = Defaults.fallbackFeePercent
}
}