-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathProbingToolViewModel.kt
More file actions
258 lines (223 loc) · 10.2 KB
/
Copy pathProbingToolViewModel.kt
File metadata and controls
258 lines (223 loc) · 10.2 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package to.bitkit.viewmodels
import android.content.ClipboardManager
import android.content.Context
import androidx.compose.runtime.Stable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.synonym.bitkitcore.Scanner
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import to.bitkit.di.BgDispatcher
import to.bitkit.ext.maxSendableSat
import to.bitkit.ext.minSendableSat
import to.bitkit.ext.totalNextOutboundHtlcLimitSats
import to.bitkit.models.BITCOIN_SYMBOL
import to.bitkit.models.Toast
import to.bitkit.repositories.LightningRepo
import to.bitkit.services.CoreService
import to.bitkit.ui.shared.toast.ToastEventBus
import to.bitkit.utils.Logger
import javax.inject.Inject
@HiltViewModel
class ProbingToolViewModel @Inject constructor(
@ApplicationContext private val context: Context,
@BgDispatcher private val bgDispatcher: CoroutineDispatcher,
private val coreService: CoreService,
private val lightningRepo: LightningRepo,
) : ViewModel() {
private val _uiState = MutableStateFlow(ProbingToolUiState())
val uiState = _uiState.asStateFlow()
fun updateInvoice(invoice: String) {
_uiState.update { it.copy(invoice = invoice, probeResult = null) }
detectInputType(invoice)
}
fun updateAmountSats(amount: String) {
val filtered = amount.filter { it.isDigit() }
_uiState.update { it.copy(amountSats = filtered) }
}
fun pasteInvoice() {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clipData = clipboard.primaryClip
val pastedInvoice = clipData?.getItemAt(0)?.text?.toString()?.trim()
if (pastedInvoice.isNullOrEmpty()) {
viewModelScope.launch {
ToastEventBus.send(
type = Toast.ToastType.WARNING,
title = "Clipboard is empty",
)
}
return
}
updateInvoice(pastedInvoice)
}
fun sendProbe() {
val input = _uiState.value.invoice.trim()
if (input.isEmpty()) {
viewModelScope.launch {
ToastEventBus.send(type = Toast.ToastType.WARNING, title = "Please enter an invoice")
}
return
}
viewModelScope.launch(bgDispatcher) {
_uiState.update { it.copy(isLoading = true, probeResult = null) }
val userAmount = _uiState.value.amountSats.toULongOrNull()
val amountSats = userAmount ?: 1uL.takeIf { _uiState.value.isZeroAmountInvoice }
val bolt11 = extractBolt11Invoice(input, amountSats)
if (bolt11 == null) {
ToastEventBus.send(
type = Toast.ToastType.WARNING,
title = "Invalid invoice format",
description = "Could not extract Lightning invoice",
)
_uiState.update { it.copy(isLoading = false) }
return@launch
}
val effectiveAmount = amountSats ?: getInvoiceAmount(input)
if (effectiveAmount != null && effectiveAmount > 0uL) {
val outbound = lightningRepo.lightningState.value.channels
.totalNextOutboundHtlcLimitSats()
val estimatedFee = getEstimatedFee(bolt11, amountSats)
val nearCapacityThreshold = outbound * 95uL / 100uL
if (estimatedFee == null && effectiveAmount >= nearCapacityThreshold) {
ToastEventBus.send(
type = Toast.ToastType.WARNING,
title = "Amount too close to capacity",
description = "Available: $BITCOIN_SYMBOL $outbound. " +
"Reduce amount to leave room for routing fees.",
)
_uiState.update { it.copy(isLoading = false) }
return@launch
}
val totalRequired = effectiveAmount + (estimatedFee ?: 0uL)
if (!lightningRepo.canSend(totalRequired)) {
ToastEventBus.send(
type = Toast.ToastType.WARNING,
title = "Amount + fees exceed capacity",
description = "Needed: $BITCOIN_SYMBOL $totalRequired" +
"(includes ~${estimatedFee ?: 0uL} fee), " +
"available: $BITCOIN_SYMBOL $outbound",
)
_uiState.update { it.copy(isLoading = false) }
return@launch
}
}
val startTime = System.currentTimeMillis()
lightningRepo.sendProbeForInvoice(bolt11, amountSats)
.onSuccess { handleProbeSuccess(startTime, bolt11, amountSats) }
.onFailure { handleProbeFailure(startTime, it) }
_uiState.update { it.copy(isLoading = false) }
}
}
private fun detectInputType(input: String) {
viewModelScope.launch(bgDispatcher) {
val data = runCatching { coreService.decode(input.trim()) }.getOrNull()
when (data) {
is Scanner.LnurlPay -> {
val min = data.data.minSendableSat()
val max = data.data.maxSendableSat()
val isFixed = min == max && min > 0uL
_uiState.update {
it.copy(
isLnurlPay = true,
isZeroAmountInvoice = false,
amountSats = if (isFixed) min.toString() else it.amountSats,
)
}
}
is Scanner.Lightning if data.invoice.amountSatoshis == 0uL -> {
_uiState.update { it.copy(isLnurlPay = false, isZeroAmountInvoice = true) }
}
is Scanner.OnChain -> {
val lightningParam = data.invoice.params?.get("lightning")
val lightning = lightningParam?.let {
runCatching { coreService.decode(it) }.getOrNull() as? Scanner.Lightning
}
val isZeroAmount = lightning?.invoice?.amountSatoshis == 0uL
_uiState.update { it.copy(isLnurlPay = false, isZeroAmountInvoice = isZeroAmount) }
}
else -> {
_uiState.update { it.copy(isLnurlPay = false, isZeroAmountInvoice = false) }
}
}
}
}
private suspend fun extractBolt11Invoice(input: String, amountSats: ULong?): String? = runCatching {
when (val decoded = coreService.decode(input)) {
is Scanner.Lightning -> decoded.invoice.bolt11
is Scanner.OnChain -> {
val lightningParam = decoded.invoice.params?.get("lightning") ?: return@runCatching null
(coreService.decode(lightningParam) as? Scanner.Lightning)?.invoice?.bolt11
}
is Scanner.LnurlPay -> {
val amount = amountSats ?: return@runCatching null
lightningRepo.fetchLnurlInvoice(decoded.data.callback, amount * 1000u).getOrThrow().bolt11
}
else -> null
}
}.getOrNull()
private suspend fun handleProbeSuccess(startTime: Long, invoice: String, amountSats: ULong?) {
val durationMs = System.currentTimeMillis() - startTime
Logger.info("Probe successful for invoice in ${durationMs}ms", context = TAG)
val estimatedFee = getEstimatedFee(invoice, amountSats)
_uiState.update {
it.copy(probeResult = ProbeResult(success = true, durationMs = durationMs, estimatedFeeSats = estimatedFee))
}
ToastEventBus.send(type = Toast.ToastType.SUCCESS, title = "Probe successful")
}
private suspend fun handleProbeFailure(startTime: Long, error: Throwable) {
val durationMs = System.currentTimeMillis() - startTime
Logger.error("Probe failed in ${durationMs}ms", error, context = TAG)
val friendlyMessage = getFriendlyErrorMessage(error)
_uiState.update {
it.copy(probeResult = ProbeResult(success = false, durationMs = durationMs, errorMessage = friendlyMessage))
}
ToastEventBus.send(type = Toast.ToastType.ERROR, title = "Probe failed", description = friendlyMessage)
}
private suspend fun getInvoiceAmount(input: String): ULong? = runCatching {
when (val decoded = coreService.decode(input.trim())) {
is Scanner.Lightning -> decoded.invoice.amountSatoshis.takeIf { it > 0uL }
else -> null
}
}.getOrNull()
private suspend fun getEstimatedFee(invoice: String, amountSats: ULong?): ULong? = run {
if (amountSats != null) {
lightningRepo.estimateRoutingFeesForAmount(invoice, amountSats)
} else {
lightningRepo.estimateRoutingFees(invoice)
}.getOrNull()
}
companion object {
private const val TAG = "ProbingToolViewModel"
private fun getFriendlyErrorMessage(error: Throwable): String {
val msg = error.message ?: return "Unknown error"
return when {
msg.contains("RouteNotFound", ignoreCase = true) -> "No route found to destination"
msg.contains("InsufficientFunds", ignoreCase = true) -> "Insufficient funds for this probe"
msg.contains("PaymentPathFailed", ignoreCase = true) -> "Payment path failed"
msg.contains("SendingFailed", ignoreCase = true) -> "Probe sending failed"
else -> msg
}
}
}
}
@Stable
data class ProbingToolUiState(
val invoice: String = "",
val amountSats: String = "",
val isLoading: Boolean = false,
val isLnurlPay: Boolean = false,
val isZeroAmountInvoice: Boolean = false,
val probeResult: ProbeResult? = null,
)
@Stable
data class ProbeResult(
val success: Boolean,
val durationMs: Long,
val estimatedFeeSats: ULong? = null,
val errorMessage: String? = null,
)