-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTransferViewModel.kt
More file actions
985 lines (858 loc) · 38.7 KB
/
Copy pathTransferViewModel.kt
File metadata and controls
985 lines (858 loc) · 38.7 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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
package to.bitkit.viewmodels
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.synonym.bitkitcore.BtOrderState2
import com.synonym.bitkitcore.IBtOrder
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.withTimeoutOrNull
import org.lightningdevkit.ldknode.ChannelDetails
import to.bitkit.R
import to.bitkit.data.CacheStore
import to.bitkit.data.SettingsStore
import to.bitkit.env.Defaults
import to.bitkit.ext.amountOnClose
import to.bitkit.ext.isTrezorDeviceBusy
import to.bitkit.ext.isTrezorUserCancellation
import to.bitkit.models.HwFundingBroadcastResult
import to.bitkit.models.HwFundingTransaction
import to.bitkit.models.Toast
import to.bitkit.models.TransactionSpeed
import to.bitkit.models.TransferType
import to.bitkit.models.safe
import to.bitkit.repositories.BlocktankRepo
import to.bitkit.repositories.HwWalletRepo
import to.bitkit.repositories.LightningRepo
import to.bitkit.repositories.TransferRepo
import to.bitkit.repositories.WalletRepo
import to.bitkit.ui.shared.toast.ToastEventBus
import to.bitkit.utils.AppError
import to.bitkit.utils.Logger
import to.bitkit.utils.TrezorErrorPresenter
import javax.inject.Inject
import kotlin.math.min
import kotlin.math.roundToLong
import kotlin.time.Clock
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.ExperimentalTime
const val RETRY_INTERVAL_MS = 1 * 60 * 1000L // 1 minutes in ms
const val GIVE_UP_MS = 30 * 60 * 1000L // 30 minutes in ms
@Suppress("LargeClass", "TooManyFunctions", "LongParameterList")
@OptIn(ExperimentalTime::class)
@HiltViewModel
class TransferViewModel @Inject constructor(
@ApplicationContext private val context: Context,
private val lightningRepo: LightningRepo,
private val blocktankRepo: BlocktankRepo,
private val hwWalletRepo: HwWalletRepo,
private val walletRepo: WalletRepo,
private val settingsStore: SettingsStore,
private val cacheStore: CacheStore,
private val transferRepo: TransferRepo,
private val clock: Clock,
) : ViewModel() {
private val _spendingUiState = MutableStateFlow(TransferToSpendingUiState())
val spendingUiState = _spendingUiState.asStateFlow()
private val _isForceTransferLoading = MutableStateFlow(false)
val isForceTransferLoading = _isForceTransferLoading.asStateFlow()
val lightningSetupStep: StateFlow<Int> = settingsStore.data.map { it.lightningSetupStep }
.stateIn(viewModelScope, SharingStarted.Lazily, 0)
val isNodeRunning = lightningRepo.lightningState.map { it.nodeStatus?.isRunning ?: false }
.stateIn(viewModelScope, SharingStarted.Lazily, false)
private val _selectedChannelIdsState = MutableStateFlow<Set<String>>(emptySet())
val selectedChannelIdsState = _selectedChannelIdsState.asStateFlow()
private val _transferValues = MutableStateFlow(TransferValues())
val transferValues = _transferValues.asStateFlow()
val transferEffects = MutableSharedFlow<TransferEffect>()
fun setTransferEffect(effect: TransferEffect) = viewModelScope.launch { transferEffects.emit(effect) }
var maxLspFee = 0uL
private var hwTransferSignJob: Job? = null
// region Spending
fun onConfirmAmount(satsAmount: Long) {
val values = blocktankRepo.calculateLiquidityOptions(satsAmount.toULong()).getOrNull()
if (values == null || values.maxLspBalanceSat == 0uL) {
setTransferEffect(
TransferEffect.ToastError(
title = context.getString(R.string.lightning__spending_amount__error_max__title),
description = context.getString(
R.string.lightning__spending_amount__error_max__description_zero
),
)
)
return
}
val lspBalance = maxOf(values.defaultLspBalanceSat, values.minLspBalanceSat)
viewModelScope.launch {
_spendingUiState.update { it.copy(isLoading = true) }
withTimeoutOrNull(1.minutes) {
isNodeRunning.first { it }
}
blocktankRepo.createOrder(
spendingBalanceSats = satsAmount.toULong(),
receivingBalanceSats = lspBalance,
)
.onSuccess { order ->
settingsStore.update { it.copy(lightningSetupStep = 0) }
onOrderCreated(order)
delay(1.seconds) // Give time to settle the UI
_spendingUiState.update { it.copy(isLoading = false) }
}.onFailure { e ->
setTransferEffect(TransferEffect.ToastException(e))
delay(1.seconds) // Give time to settle the UI
_spendingUiState.update { it.copy(isLoading = false) }
}
}
}
fun updateLimits(satsAmount: Long = 0) {
updateTransferValues(satsAmount.toULong())
updateAvailableAmount()
}
fun onReceivingAmountChange(amount: Long) {
viewModelScope.launch {
_spendingUiState.update { it.copy(receivingAmount = amount, feeEstimate = null) }
if (amount == 0L) return@launch
val transferValues = _transferValues.value
if (transferValues.minLspBalance == 0uL) return@launch
val isValid = amount.toULong() >= transferValues.minLspBalance &&
amount.toULong() <= transferValues.maxLspBalance
if (!isValid) return@launch
val result = blocktankRepo.estimateOrderFee(
spendingBalanceSats = _spendingUiState.value.order?.clientBalanceSat ?: 0u,
receivingBalanceSats = amount.toULong(),
)
result.fold(
onSuccess = { response ->
_spendingUiState.update {
it.copy(feeEstimate = response.feeSat.toLong())
}
},
onFailure = { error ->
Logger.error("Failed to estimate fee", error, context = TAG)
_spendingUiState.update {
it.copy(feeEstimate = null)
}
}
)
}
}
fun onSpendingAdvancedContinue(receivingAmountSats: Long) {
viewModelScope.launch {
runCatching {
val oldOrder = _spendingUiState.value.order ?: return@launch
val newOrder = blocktankRepo.createOrder(
spendingBalanceSats = oldOrder.clientBalanceSat,
receivingBalanceSats = receivingAmountSats.toULong(),
).getOrThrow()
_spendingUiState.update {
it.copy(
order = newOrder,
defaultOrder = oldOrder,
isAdvanced = true,
)
}
setTransferEffect(TransferEffect.OnOrderCreated)
}.onFailure { e ->
setTransferEffect(TransferEffect.ToastException(e))
}
}
}
/** Pays for the order and start watching it for state updates */
fun onTransferToSpendingConfirm(order: IBtOrder, speed: TransactionSpeed? = null) {
viewModelScope.launch {
val address = order.payment?.onchain?.address.orEmpty()
// Use live spendableOnchainBalanceSats (not cached) to respect anchor reserves
val balanceDetails = lightningRepo.getBalancesAsync().getOrNull()
val spendableBalance = balanceDetails?.spendableOnchainBalanceSats ?: 0uL
val sendAllFee = lightningRepo.estimateSendAllFee(
address = address,
speed = speed,
).getOrElse {
Logger.error("Failed to estimate send-all fee", it, context = TAG)
ToastEventBus.send(it)
return@launch
}
val expectedChange =
spendableBalance.toLong() - order.feeSat.toLong() - sendAllFee.toLong()
val shouldUseSendAll =
expectedChange >= 0 && expectedChange < TRANSFER_SEND_ALL_THRESHOLD_SATS
val miningFee = if (shouldUseSendAll) {
sendAllFee
} else {
lightningRepo.calculateTotalFee(
amountSats = order.feeSat,
address = address,
speed = speed,
).getOrElse {
Logger.warn("Failed to estimate transfer funding fee", it, context = TAG)
0uL
}
}
val txTotalSats = if (shouldUseSendAll) {
spendableBalance
} else {
order.feeSat.safe() + miningFee.safe()
}
Logger.debug(
"BT confirm: spendable=$spendableBalance, feeSat=${order.feeSat}, " +
"sendAllFee=$sendAllFee, expectedChange=$expectedChange, sendAll=$shouldUseSendAll",
context = TAG,
)
lightningRepo
.sendOnChain(
address = address,
sats = order.feeSat,
speed = speed,
isTransfer = true,
channelId = order.channel?.shortChannelId,
isMaxAmount = shouldUseSendAll,
)
.onSuccess { txId ->
fundPaidOrder(
order = order,
txId = txId,
txTotalSats = txTotalSats,
preTransferOnchainSats = balanceDetails?.totalOnchainBalanceSats ?: spendableBalance,
)
}
.onFailure { error ->
ToastEventBus.send(error)
}
}
}
/** Records a paid order and starts watching it, after the funding tx was broadcast (local or HW signed). */
private suspend fun fundPaidOrder(
order: IBtOrder,
txId: String,
createTransferActivity: Boolean = false,
fee: ULong = 0uL,
feeRate: ULong = 0uL,
txTotalSats: ULong? = null,
preTransferOnchainSats: ULong? = null,
) {
cacheStore.addPaidOrder(orderId = order.id, txId = txId)
transferRepo.createTransfer(
type = TransferType.TO_SPENDING,
amountSats = order.clientBalanceSat.toLong(),
fundingTxId = txId,
lspOrderId = order.id,
txTotalSats = txTotalSats?.toLong(),
preTransferOnchainSats = preTransferOnchainSats?.toLong(),
)
if (createTransferActivity) {
transferRepo.createPendingToSpendingActivity(
order = order,
txId = txId,
fee = fee,
feeRate = feeRate,
)
}
viewModelScope.launch { walletRepo.syncBalances() }
viewModelScope.launch { watchOrder(order.id) }
}
private suspend fun watchOrder(orderId: String): Result<Boolean> = runCatching {
Logger.debug("Started watching order: '$orderId'", context = TAG)
// Step 0: Starting
settingsStore.update { it.copy(lightningSetupStep = LN_SETUP_STEP_0) }
Logger.debug("LN setup step: $LN_SETUP_STEP_0", context = TAG)
delay(MIN_STEP_DELAY_MS)
// Poll until payment is confirmed (order state becomes PAID or EXECUTED)
val paidOrder = pollUntil(orderId) { order ->
order.state2 == BtOrderState2.PAID || order.state2 == BtOrderState2.EXECUTED
} ?: return Result.failure(Exception("Order not found or expired"))
// Step 1: Payment confirmed
settingsStore.update { it.copy(lightningSetupStep = LN_SETUP_STEP_1) }
Logger.debug("LN setup step: $LN_SETUP_STEP_1", context = TAG)
delay(MIN_STEP_DELAY_MS)
// Try to open channel (idempotent - safe to call multiple times)
blocktankRepo.openChannel(paidOrder.id)
// Step 2: Channel opening requested
settingsStore.update { it.copy(lightningSetupStep = LN_SETUP_STEP_2) }
Logger.debug("LN setup step: $LN_SETUP_STEP_2", context = TAG)
delay(MIN_STEP_DELAY_MS)
// Poll until channel is ready (EXECUTED state or channel has state)
pollUntil(orderId) { order ->
order.state2 == BtOrderState2.EXECUTED || order.channel?.state != null
} ?: return Result.failure(Exception("Order not found or expired"))
// Step 3: Complete
transferRepo.syncTransferStates()
settingsStore.update { it.copy(lightningSetupStep = LN_SETUP_STEP_3) }
Logger.debug("LN setup step: $LN_SETUP_STEP_3", context = TAG)
Logger.debug("Order settled: '$orderId'", context = TAG)
return@runCatching true
}.onFailure {
Logger.error("Failed to watch order: '$orderId'", it, context = TAG)
}.also {
Logger.debug("Stopped watching order: '$orderId'", context = TAG)
}
private suspend fun pollUntil(orderId: String, condition: (IBtOrder) -> Boolean): IBtOrder? {
var consecutiveErrors = 0
while (true) {
blocktankRepo.getOrder(orderId, refresh = true).fold(
onSuccess = { order ->
consecutiveErrors = 0
if (order == null) {
Logger.error("Order not found: '$orderId'", context = TAG)
return null
}
if (order.state2 == BtOrderState2.EXPIRED) {
Logger.error("Order expired: '$orderId'", context = TAG)
return null
}
if (condition(order)) {
return order
}
},
onFailure = {
consecutiveErrors++
Logger.warn(
"Failed to fetch order '$orderId' (attempt $consecutiveErrors/$MAX_CONSECUTIVE_ERRORS)",
it,
context = TAG
)
if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {
Logger.error("Too many consecutive errors polling order '$orderId', giving up", context = TAG)
return null
}
}
)
delay(POLL_INTERVAL_MS)
}
}
private suspend fun onOrderCreated(order: IBtOrder) {
settingsStore.update { it.copy(lightningSetupStep = 0) }
_spendingUiState.update { it.copy(order = order, isAdvanced = false, defaultOrder = null) }
setTransferEffect(TransferEffect.OnOrderCreated)
}
private fun updateAvailableAmount() {
viewModelScope.launch {
_spendingUiState.update { it.copy(isLoading = true) }
val availableAmount = walletRepo.balanceState.value.maxSendOnchainSats
awaitNodeRunning()
val initialLspFees = estimateInitialLspFees(availableAmount)
if (initialLspFees == null) {
_spendingUiState.update { it.copy(isLoading = false) }
return@launch
}
val balanceAfterLspFee = availableAmount.safe() - initialLspFees.safe()
estimateFinalMaxSendAmount(availableAmount, balanceAfterLspFee)
}
}
private suspend fun awaitNodeRunning() {
withTimeoutOrNull(1.minutes) {
isNodeRunning.first { it }
}
}
private suspend fun estimateInitialLspFees(availableAmount: ULong): ULong? {
val liquidity = blocktankRepo
.calculateLiquidityOptions(availableAmount)
.getOrNull() ?: return null
val lspBalance = maxOf(liquidity.defaultLspBalanceSat, liquidity.minLspBalanceSat)
val orderFee = blocktankRepo.estimateOrderFee(
spendingBalanceSats = availableAmount,
receivingBalanceSats = lspBalance,
).getOrNull() ?: return null
return orderFee.networkFeeSat.safe() + orderFee.serviceFeeSat.safe()
}
private suspend fun estimateFinalMaxSendAmount(
availableAmount: ULong,
balanceAfterLspFee: ULong,
) {
// An on-chain balance larger than the LSP's max channel size makes
// calculateLiquidityOptions report maxLspBalanceSat = 0 (the client balance already
// saturates the channel). Clamp the prospective client balance to the LSP's
// maxClientBalanceSat so the spendable amount caps at that limit instead of collapsing
// to zero, leaving the rest of the funds on-chain.
val lspMaxClientBalance = blocktankRepo.blocktankState.value.info?.options?.maxClientBalanceSat
val cappedClientBalance = lspMaxClientBalance
?.let { max -> minOf(balanceAfterLspFee, max) }
?: balanceAfterLspFee
val liquidity = blocktankRepo.calculateLiquidityOptions(cappedClientBalance).getOrNull()
if (liquidity == null || liquidity.maxClientBalanceSat == 0uL) {
_spendingUiState.update { it.copy(isLoading = false, maxAllowedToSend = 0) }
return
}
val receivingAmount = maxOf(liquidity.defaultLspBalanceSat, liquidity.minLspBalanceSat)
blocktankRepo.estimateOrderFee(
spendingBalanceSats = cappedClientBalance,
receivingBalanceSats = receivingAmount,
).onSuccess { estimate ->
maxLspFee = estimate.feeSat
val lspFees = estimate.networkFeeSat.safe() + estimate.serviceFeeSat.safe()
val maxClientBalance = availableAmount.safe() - lspFees.safe()
val maxSend = min(
liquidity.maxClientBalanceSat.toLong(),
maxClientBalance.toLong()
)
val quarterAmount = min((maxSend.toDouble() * 0.25).roundToLong(), maxSend)
_spendingUiState.update {
it.copy(
maxAllowedToSend = maxSend,
isLoading = false,
balanceAfterFee = maxSend,
quarterAmount = quarterAmount,
)
}
}.onFailure {
_spendingUiState.update { it.copy(isLoading = false) }
Logger.error("Failure", it, context = TAG)
setTransferEffect(TransferEffect.ToastException(it))
}
}
fun onUseDefaultLspBalanceClick() {
val defaultOrder = _spendingUiState.value.defaultOrder
_spendingUiState.update { it.copy(order = defaultOrder, defaultOrder = null, isAdvanced = false) }
}
fun resetSpendingState() {
hwTransferSignJob?.cancel()
hwTransferSignJob = null
_spendingUiState.update { TransferToSpendingUiState() }
_transferValues.update { TransferValues() }
}
// endregion
// region Hardware Wallet
fun updateHwLimits(deviceId: String) {
viewModelScope.launch {
_spendingUiState.update { it.copy(isLoading = true) }
val account = hwWalletRepo.getFundingAccount(deviceId).getOrElse {
Logger.error("Failed to load hardware funding account", it, context = TAG)
_spendingUiState.update { s -> s.copy(isLoading = false, maxAllowedToSend = 0, balanceAfterFee = 0) }
setTransferEffect(TransferEffect.ToastException(it))
return@launch
}
awaitNodeRunning()
updateTransferValues(0uL)
val availableAmount = account.balanceSats.safe() - hwFundingFeeReserve(account.balanceSats).safe()
val initialLspFees = estimateInitialLspFees(availableAmount)
if (initialLspFees == null) {
_spendingUiState.update { it.copy(isLoading = false) }
return@launch
}
val balanceAfterLspFee = availableAmount.safe() - initialLspFees.safe()
estimateFinalMaxSendAmount(availableAmount, balanceAfterLspFee)
}
}
/** Pays for the order by composing and signing the funding send on the Trezor, then watches it. */
fun warmUpHardwareConnection(deviceId: String) {
hwWalletRepo.warmUpKnownDevice(deviceId)
}
fun onTransferToSpendingHwConfirm(order: IBtOrder, deviceId: String) {
if (hwTransferSignJob?.isActive == true) return
hwTransferSignJob = viewModelScope.launch {
_spendingUiState.update { it.copy(isSigning = true) }
try {
val address = order.payment?.onchain?.address.orEmpty()
if (address.isEmpty()) {
ToastEventBus.send(type = Toast.ToastType.ERROR, title = context.getString(R.string.common__error))
return@launch
}
signTransferToSpendingWithHardware(order, deviceId, address)
.onSuccess { result ->
fundPaidOrder(
order = order,
txId = result.txId,
createTransferActivity = true,
fee = result.miningFeeSats,
feeRate = result.feeRate,
)
setTransferEffect(TransferEffect.OnHwTxSigned)
}
.onFailure { handleHardwareTransferFailure(it, deviceId) }
} finally {
_spendingUiState.update { it.copy(isSigning = false) }
hwTransferSignJob = null
}
}
}
private suspend fun signTransferToSpendingWithHardware(
order: IBtOrder,
deviceId: String,
address: String,
): Result<HwFundingBroadcastResult> {
val result = runCatching {
ensureHardwareConnected(deviceId)
val satsPerVByte = hwFundingSatsPerVByte()
val funding = composeHardwareFundingTransaction(
deviceId = deviceId,
address = address,
sats = order.feeSat,
satsPerVByte = satsPerVByte,
)
signAndBroadcastHardwareFunding(deviceId, funding)
}
result.exceptionOrNull()?.let {
if (it is CancellationException && it !is TimeoutCancellationException) throw it
}
return result
}
private suspend fun ensureHardwareConnected(deviceId: String) {
runCatching {
withTimeout(HW_RECONNECT_TIMEOUT) {
hwWalletRepo.ensureConnected(deviceId).getOrThrow()
}
}.getOrElse {
if (it is CancellationException && it !is TimeoutCancellationException) throw it
if (it.isTrezorUserCancellation()) throw it
throw HardwareReconnectError(it)
}
}
private suspend fun composeHardwareFundingTransaction(
deviceId: String,
address: String,
sats: ULong,
satsPerVByte: ULong,
): HwFundingTransaction {
return runCatching {
withTimeout(HW_COMPOSE_TIMEOUT) {
hwWalletRepo.composeFundingTransaction(
deviceId = deviceId,
address = address,
sats = sats,
satsPerVByte = satsPerVByte,
).getOrThrow()
}
}.getOrElse {
if (it is CancellationException && it !is TimeoutCancellationException) throw it
throw HardwareFundingError(it)
}
}
@Suppress("ThrowsCount")
private suspend fun signAndBroadcastHardwareFunding(
deviceId: String,
funding: HwFundingTransaction,
): HwFundingBroadcastResult {
return runCatching {
withTimeout(HW_SIGN_TIMEOUT) {
hwWalletRepo.signAndBroadcastFunding(
deviceId = deviceId,
funding = funding,
).getOrThrow()
}
}.getOrElse {
if (it is CancellationException && it !is TimeoutCancellationException) throw it
if (it is TimeoutCancellationException) {
hwWalletRepo.disconnectStaleSession(deviceId)
throw HardwareSigningTimeoutError(it)
}
throw it
}
}
private suspend fun handleHardwareTransferFailure(e: Throwable, deviceId: String) {
if (e.isTrezorUserCancellation()) {
Logger.info("Hardware transfer cancelled on device for '$deviceId'", context = TAG)
return
}
if (e.isTrezorDeviceBusy()) {
Logger.warn("Hardware transfer blocked by busy Trezor for '$deviceId'", e, context = TAG)
ToastEventBus.send(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.common__error),
description = TrezorErrorPresenter.userMessage(context, e),
)
return
}
when (e) {
is HardwareReconnectError -> {
Logger.error("Failed to reconnect hardware device", e, context = TAG)
showHardwareReconnectError(deviceId)
}
is HardwareSigningTimeoutError -> {
Logger.warn("Timed out hardware transfer signing for '$deviceId'", e, context = TAG)
showHardwareTimeoutError()
}
is HardwareFundingError -> {
Logger.warn("Failed to compose hardware transfer funding for '$deviceId'", e, context = TAG)
showHardwareFundingError(e)
}
else -> {
Logger.error("Hardware transfer failed", e, context = TAG)
ToastEventBus.send(e)
}
}
}
private suspend fun showHardwareReconnectError(deviceId: String) {
if (hwWalletRepo.isKnownBluetoothDevice(deviceId)) {
ToastEventBus.send(
type = Toast.ToastType.INFO,
title = context.getString(R.string.hardware__connect_error),
)
return
}
ToastEventBus.send(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.lightning__transfer_hw__reconnect_error_title),
description = context.getString(R.string.lightning__transfer_hw__reconnect_error_description),
)
}
private suspend fun showHardwareTimeoutError() {
ToastEventBus.send(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.common__error),
description = context.getString(R.string.wallet__toast_payment_failed_timeout),
)
}
private suspend fun showHardwareFundingError(e: Throwable) {
ToastEventBus.send(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.common__error),
description = e.cause?.message ?: e.message ?: context.getString(R.string.common__error_body),
)
}
private suspend fun hwFundingFeeReserve(balanceSats: ULong): ULong {
val satsPerVByte = fetchHwFundingSatsPerVByte().getOrNull()
?: return hwFundingFallbackFeeReserve(balanceSats)
return satsPerVByte.safe() * HW_FUNDING_TX_VBYTES.safe()
}
private fun hwFundingFallbackFeeReserve(balanceSats: ULong): ULong {
val minReserve = HW_FUNDING_FALLBACK_SATS_PER_VBYTE.safe() * HW_FUNDING_TX_VBYTES.safe()
val fallback = (balanceSats.toDouble() * Defaults.fallbackFeePercent).toULong()
return maxOf(minReserve, fallback)
}
private suspend fun hwFundingSatsPerVByte(): ULong =
fetchHwFundingSatsPerVByte().getOrDefault(HW_FUNDING_FALLBACK_SATS_PER_VBYTE)
private suspend fun fetchHwFundingSatsPerVByte(): Result<ULong> {
val speed = settingsStore.data.first().defaultTransactionSpeed
return lightningRepo.getFeeRateForSpeed(speed)
}
// endregion
// region Balance Calc
fun updateTransferValues(clientBalanceSat: ULong) {
val options = blocktankRepo.calculateLiquidityOptions(clientBalanceSat).getOrNull()
_transferValues.value = if (options != null) {
TransferValues(
defaultLspBalance = options.defaultLspBalanceSat,
minLspBalance = options.minLspBalanceSat,
maxLspBalance = options.maxLspBalanceSat,
maxClientBalance = options.maxClientBalanceSat,
)
} else {
TransferValues()
}
}
// endregion
// region Savings
private var channelsToClose = emptyList<ChannelDetails>()
fun setSelectedChannelIds(channelIds: Set<String>) {
_selectedChannelIdsState.update { channelIds }
}
fun onTransferToSavingsConfirm(channels: List<ChannelDetails>) {
_selectedChannelIdsState.update { emptySet() }
channelsToClose = channels
}
/** Closes the channels selected earlier, pending closure */
suspend fun closeSelectedChannels() = closeChannels(channelsToClose)
fun separateTrustedChannels(
channels: List<ChannelDetails>,
): Pair<List<ChannelDetails>, List<ChannelDetails>> = lightningRepo.separateTrustedChannels(channels)
private suspend fun closeChannels(channels: List<ChannelDetails>): List<ChannelDetails> {
lightningRepo.awaitPeerConnected()
val channelsFailedToClose = coroutineScope {
channels.map { channel ->
async {
lightningRepo.closeChannel(channel)
.onSuccess {
transferRepo.createTransfer(
type = TransferType.COOP_CLOSE,
amountSats = channel.amountOnClose.toLong(),
channelId = channel.channelId,
fundingTxId = channel.fundingTxo?.txid,
)
}
.fold(
onSuccess = { null },
onFailure = { channel }
)
}
}.awaitAll()
}.filterNotNull()
return channelsFailedToClose
}
private var coopCloseRetryJob: Job? = null
/** Retry to coop close the channel(s) for 30 min */
fun startCoopCloseRetries(
channels: List<ChannelDetails>,
onGiveUp: () -> Unit,
onTransferUnavailable: () -> Unit,
) {
val startTimeMs = clock.now().toEpochMilliseconds()
channelsToClose = channels
coopCloseRetryJob?.cancel()
coopCloseRetryJob = viewModelScope.launch {
val giveUpTime = startTimeMs + GIVE_UP_MS
while (isActive && System.currentTimeMillis() < giveUpTime) {
Logger.info("Trying coop close...")
val channelsFailedToCoopClose = closeChannels(channelsToClose)
if (channelsFailedToCoopClose.isEmpty()) {
channelsToClose = emptyList()
Logger.info("Coop close success.")
return@launch
} else {
channelsToClose = channelsFailedToCoopClose
Logger.info("Coop close failed: ${channelsFailedToCoopClose.map { it.channelId }}")
}
delay(RETRY_INTERVAL_MS)
}
Logger.info("Giving up on coop close. Checking if force close is possible.", context = TAG)
// Check if any channels can be force closed (filter out trusted peers)
val (_, nonTrustedChannels) = lightningRepo.separateTrustedChannels(channelsToClose)
if (nonTrustedChannels.isNotEmpty()) {
onGiveUp()
} else {
Logger.warn("All channels are with trusted peers. Cannot force close.", context = TAG)
channelsToClose = emptyList()
onTransferUnavailable()
}
}
}
fun forceTransfer(onComplete: () -> Unit) = viewModelScope.launch {
_isForceTransferLoading.value = true
runCatching {
// Filter out trusted peer channels (cannot force close LSP channels)
val (trustedChannels, nonTrustedChannels) = lightningRepo.separateTrustedChannels(channelsToClose)
if (trustedChannels.isNotEmpty()) {
Logger.warn("Skipping ${trustedChannels.size} trusted peer channel(s)", context = TAG)
}
if (nonTrustedChannels.isEmpty()) {
channelsToClose = emptyList()
Logger.error("Cannot force close channels with trusted peer", context = TAG)
ToastEventBus.send(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.lightning__force_failed_title),
description = context.getString(R.string.lightning__force_failed_msg)
)
return@runCatching
}
val failedChannels = forceCloseChannels(nonTrustedChannels)
// Remove successfully closed channels and trusted peer channels from the list
val successfulChannelIds = nonTrustedChannels
.filterNot { channel -> failedChannels.any { it.channelId == channel.channelId } }
.map { it.channelId }
.toSet()
val trustedChannelIds = trustedChannels.map { it.channelId }.toSet()
channelsToClose = channelsToClose.filterNot {
it.channelId in successfulChannelIds || it.channelId in trustedChannelIds
}
if (failedChannels.isEmpty()) {
Logger.info("Force close initiated successfully for all channels", context = TAG)
val initMsg = context.getString(R.string.lightning__force_init_msg)
val skippedMsg = context.getString(R.string.lightning__force_channels_skipped)
val description = if (trustedChannels.isNotEmpty()) "$initMsg $skippedMsg" else initMsg
ToastEventBus.send(
type = Toast.ToastType.LIGHTNING,
title = context.getString(R.string.lightning__force_init_title),
description = description,
)
} else {
Logger.error("Force close failed for ${failedChannels.size} channels", context = TAG)
ToastEventBus.send(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.lightning__force_failed_title),
description = context.getString(R.string.lightning__force_failed_msg)
)
}
}.onFailure {
Logger.error("Force close failed", e = it, context = TAG)
ToastEventBus.send(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.lightning__force_failed_title),
description = context.getString(R.string.lightning__force_failed_msg)
)
}
_isForceTransferLoading.value = false
onComplete()
}
private suspend fun forceCloseChannels(channels: List<ChannelDetails>): List<ChannelDetails> {
val channelsFailedToClose = coroutineScope {
channels.map { channel ->
async {
lightningRepo.closeChannel(channel, force = true)
.onSuccess {
transferRepo.createTransfer(
type = TransferType.FORCE_CLOSE,
amountSats = channel.amountOnClose.toLong(),
channelId = channel.channelId,
fundingTxId = channel.fundingTxo?.txid,
)
}
.onFailure { e -> Logger.error("Error force closing channel: ${channel.channelId}", e) }
.fold(
onSuccess = { null },
onFailure = { channel },
)
}
}.awaitAll()
}.filterNotNull()
return channelsFailedToClose
}
// endregion
companion object {
private const val TAG = "TransferViewModel"
private const val TRANSFER_SEND_ALL_THRESHOLD_SATS = 1000
private const val MIN_STEP_DELAY_MS = 500L
private const val POLL_INTERVAL_MS = 2_500L
private const val MAX_CONSECUTIVE_ERRORS = 5
/** Conservative vbyte reserve for multi-input hardware funding before exact compose runs. */
private const val HW_FUNDING_TX_VBYTES = 1_200uL
/** Minimum fallback fee rate when fee estimates are temporarily unavailable. */
private const val HW_FUNDING_FALLBACK_SATS_PER_VBYTE = 1uL
/** Upper bound for reconnecting a known device before the UI asks for reconnect. */
private val HW_RECONNECT_TIMEOUT = 30.seconds
/** Upper bound for exact hardware funding composition before signing starts. */
private val HW_COMPOSE_TIMEOUT = 45.seconds
/** Upper bound for one hardware signing attempt before the UI releases the button. */
private val HW_SIGN_TIMEOUT = 120.seconds
const val LN_SETUP_STEP_0 = 0
const val LN_SETUP_STEP_1 = 1
const val LN_SETUP_STEP_2 = 2
const val LN_SETUP_STEP_3 = 3
}
}
private class HardwareReconnectError(cause: Throwable) : AppError(cause)
private class HardwareFundingError(cause: Throwable) : AppError(cause)
private class HardwareSigningTimeoutError(cause: Throwable) : AppError(cause)
// region state
data class TransferToSpendingUiState(
val order: IBtOrder? = null,
val defaultOrder: IBtOrder? = null,
val isAdvanced: Boolean = false,
val maxAllowedToSend: Long = 0,
val balanceAfterFee: Long = 0,
val quarterAmount: Long = 0,
val isLoading: Boolean = false,
val isSigning: Boolean = false,
val receivingAmount: Long = 0,
val feeEstimate: Long? = null,
)
data class TransferValues(
val defaultLspBalance: ULong = 0u,
val minLspBalance: ULong = 0u,
val maxLspBalance: ULong = 0u,
val maxClientBalance: ULong = 0u,
)
sealed interface TransferEffect {
data object OnOrderCreated : TransferEffect
data object OnHwTxSigned : TransferEffect
data class ToastException(val e: Throwable) : TransferEffect
data class ToastError(val title: String, val description: String) : TransferEffect
}
// endregion