-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAppViewModel.kt
More file actions
2649 lines (2335 loc) · 102 KB
/
AppViewModel.kt
File metadata and controls
2649 lines (2335 loc) · 102 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
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package to.bitkit.viewmodels
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.annotation.StringRes
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.synonym.bitkitcore.Activity
import com.synonym.bitkitcore.ActivityFilter
import com.synonym.bitkitcore.FeeRates
import com.synonym.bitkitcore.LightningInvoice
import com.synonym.bitkitcore.LnurlAuthData
import com.synonym.bitkitcore.LnurlChannelData
import com.synonym.bitkitcore.LnurlPayData
import com.synonym.bitkitcore.LnurlWithdrawData
import com.synonym.bitkitcore.OnChainInvoice
import com.synonym.bitkitcore.PaymentType
import com.synonym.bitkitcore.Scanner
import com.synonym.bitkitcore.SortDirection
import com.synonym.bitkitcore.validateBitcoinAddress
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.ImmutableMap
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.persistentMapOf
import kotlinx.collections.immutable.toImmutableList
import kotlinx.collections.immutable.toImmutableMap
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
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.asSharedFlow
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.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import org.lightningdevkit.ldknode.ChannelDataMigration
import org.lightningdevkit.ldknode.ClosureReason
import org.lightningdevkit.ldknode.Event
import org.lightningdevkit.ldknode.PaymentFailureReason
import org.lightningdevkit.ldknode.PaymentId
import org.lightningdevkit.ldknode.SpendableUtxo
import org.lightningdevkit.ldknode.Txid
import to.bitkit.BuildConfig
import to.bitkit.R
import to.bitkit.data.CacheStore
import to.bitkit.data.SettingsStore
import to.bitkit.data.keychain.Keychain
import to.bitkit.data.resetPin
import to.bitkit.di.BgDispatcher
import to.bitkit.domain.commands.NotifyPaymentReceived
import to.bitkit.domain.commands.NotifyPaymentReceivedHandler
import to.bitkit.env.Defaults
import to.bitkit.env.Env
import to.bitkit.ext.WatchResult
import to.bitkit.ext.amountOnClose
import to.bitkit.ext.amountSats
import to.bitkit.ext.channelId
import to.bitkit.ext.claimableAtHeight
import to.bitkit.ext.getClipboardText
import to.bitkit.ext.getSatsPerVByteFor
import to.bitkit.ext.callbackAmountMsats
import to.bitkit.ext.isFixedAmount
import to.bitkit.ext.maxSendableSat
import to.bitkit.ext.maxWithdrawableSat
import to.bitkit.ext.minSendableSat
import to.bitkit.ext.minWithdrawableSat
import to.bitkit.ext.rawId
import to.bitkit.ext.removeSpaces
import to.bitkit.ext.setClipboardText
import to.bitkit.ext.toHex
import to.bitkit.ext.toUserMessage
import to.bitkit.ext.totalValue
import to.bitkit.ext.watchUntil
import to.bitkit.models.FeeRate
import to.bitkit.models.msatFloorOf
import to.bitkit.models.NewTransactionSheetDetails
import to.bitkit.models.NewTransactionSheetDirection
import to.bitkit.models.NewTransactionSheetType
import to.bitkit.models.NodeLifecycleState
import to.bitkit.models.Suggestion
import to.bitkit.models.Toast
import to.bitkit.models.TransactionSpeed
import to.bitkit.models.TransferType
import to.bitkit.models.safe
import to.bitkit.models.toActivityFilter
import to.bitkit.models.toLdkNetwork
import to.bitkit.models.toTxType
import to.bitkit.repositories.ActivityRepo
import to.bitkit.repositories.BackupRepo
import to.bitkit.repositories.BlocktankRepo
import to.bitkit.repositories.ConnectivityRepo
import to.bitkit.repositories.ConnectivityState
import to.bitkit.repositories.CurrencyRepo
import to.bitkit.repositories.HealthRepo
import to.bitkit.repositories.LightningRepo
import to.bitkit.repositories.PaymentPendingException
import to.bitkit.repositories.PendingPaymentNotification
import to.bitkit.repositories.PendingPaymentRepo
import to.bitkit.repositories.PendingPaymentResolution
import to.bitkit.repositories.PreActivityMetadataRepo
import to.bitkit.repositories.TransferRepo
import to.bitkit.repositories.WalletRepo
import to.bitkit.repositories.WidgetsRepo
import to.bitkit.services.AppUpdaterService
import to.bitkit.services.CoreService
import to.bitkit.services.MigrationService
import to.bitkit.ui.Routes
import to.bitkit.ui.components.Sheet
import to.bitkit.ui.shared.toast.ToastEventBus
import to.bitkit.ui.shared.toast.ToastQueueManager
import to.bitkit.ui.sheets.SendRoute
import to.bitkit.ui.theme.TRANSITION_SCREEN_MS
import to.bitkit.usecases.FormatMoneyValue
import to.bitkit.utils.AppError
import to.bitkit.utils.Bip21Utils
import to.bitkit.utils.Logger
import to.bitkit.utils.NetworkValidationHelper
import to.bitkit.utils.jsonLogOf
import to.bitkit.utils.timedsheets.TimedSheetManager
import to.bitkit.utils.timedsheets.sheets.AppUpdateTimedSheet
import to.bitkit.utils.timedsheets.sheets.BackupTimedSheet
import to.bitkit.utils.timedsheets.sheets.HighBalanceTimedSheet
import to.bitkit.utils.timedsheets.sheets.NotificationsTimedSheet
import to.bitkit.utils.timedsheets.sheets.QuickPayTimedSheet
import java.math.BigDecimal
import javax.inject.Inject
import kotlin.coroutines.cancellation.CancellationException
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.ExperimentalTime
@OptIn(ExperimentalTime::class)
@Suppress("TooManyFunctions", "LargeClass", "LongParameterList")
@HiltViewModel
class AppViewModel @Inject constructor(
connectivityRepo: ConnectivityRepo,
healthRepo: HealthRepo,
toastManagerProvider: @JvmSuppressWildcards (CoroutineScope) -> ToastQueueManager,
timedSheetManagerProvider: @JvmSuppressWildcards (CoroutineScope) -> TimedSheetManager,
@ApplicationContext private val context: Context,
@BgDispatcher private val bgDispatcher: CoroutineDispatcher,
private val keychain: Keychain,
private val lightningRepo: LightningRepo,
private val pendingPaymentRepo: PendingPaymentRepo,
private val walletRepo: WalletRepo,
private val backupRepo: BackupRepo,
private val settingsStore: SettingsStore,
private val currencyRepo: CurrencyRepo,
private val activityRepo: ActivityRepo,
private val preActivityMetadataRepo: PreActivityMetadataRepo,
private val blocktankRepo: BlocktankRepo,
private val appUpdaterService: AppUpdaterService,
private val notifyPaymentReceivedHandler: NotifyPaymentReceivedHandler,
private val cacheStore: CacheStore,
private val transferRepo: TransferRepo,
private val migrationService: MigrationService,
private val coreService: CoreService,
private val appUpdateSheet: AppUpdateTimedSheet,
private val backupSheet: BackupTimedSheet,
private val notificationsSheet: NotificationsTimedSheet,
private val quickPaySheet: QuickPayTimedSheet,
private val highBalanceSheet: HighBalanceTimedSheet,
private val formatMoneyValue: FormatMoneyValue,
private val widgetsRepo: WidgetsRepo,
) : ViewModel() {
val healthState = healthRepo.healthState
val isOnline = connectivityRepo.isOnline
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), ConnectivityState.CONNECTED)
var splashVisible by mutableStateOf(true)
private set
val isGeoBlocked = lightningRepo.lightningState.map { it.isGeoBlocked }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false)
val forceCloseRemainingDuration = transferRepo.forceCloseRemainingDuration
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null)
private val _sendUiState = MutableStateFlow(SendUiState())
val sendUiState = _sendUiState.asStateFlow()
private val _quickPayData = MutableStateFlow<QuickPayData?>(null)
val quickPayData = _quickPayData.asStateFlow()
private var activeScanJob: Job? = null
@Volatile
private var activeScanInput: String? = null
private val _sendEffect = MutableSharedFlow<SendEffect>(extraBufferCapacity = 1)
val sendEffect = _sendEffect.asSharedFlow()
private fun setSendEffect(effect: SendEffect) = viewModelScope.launch { _sendEffect.emit(effect) }
private val _mainScreenEffect = MutableSharedFlow<MainScreenEffect>(extraBufferCapacity = 1)
val mainScreenEffect = _mainScreenEffect.asSharedFlow()
private fun mainScreenEffect(effect: MainScreenEffect) = viewModelScope.launch { _mainScreenEffect.emit(effect) }
private val sendEvents = MutableSharedFlow<SendEvent>()
fun setSendEvent(event: SendEvent) = viewModelScope.launch { sendEvents.emit(event) }
private val _isAuthenticated = MutableStateFlow(false)
val isAuthenticated = _isAuthenticated.asStateFlow()
private val _showForgotPinSheet = MutableStateFlow(false)
val showForgotPinSheet = _showForgotPinSheet.asStateFlow()
private val _currentSheet: MutableStateFlow<Sheet?> = MutableStateFlow(null)
val currentSheet = _currentSheet.asStateFlow()
private val processedPayments = mutableSetOf<String>()
private val timedSheetManager = timedSheetManagerProvider(viewModelScope).apply {
registerSheet(appUpdateSheet)
registerSheet(backupSheet)
registerSheet(notificationsSheet)
registerSheet(quickPaySheet)
registerSheet(highBalanceSheet)
}
private var isCompletingMigration = false
private var addressValidationJob: Job? = null
fun setShowForgotPin(value: Boolean) {
_showForgotPinSheet.value = value
}
fun setIsAuthenticated(value: Boolean) {
_isAuthenticated.value = value
}
val pinAttemptsRemaining = keychain.pinAttemptsRemaining()
.map { attempts -> attempts ?: Env.PIN_ATTEMPTS }
.stateIn(viewModelScope, SharingStarted.Lazily, Env.PIN_ATTEMPTS)
fun addTagToSelected(newTag: String) {
_sendUiState.update {
it.copy(
selectedTags = (it.selectedTags + newTag).distinct().toImmutableList()
)
}
viewModelScope.launch {
settingsStore.addLastUsedTag(newTag)
}
}
fun removeTag(tag: String) {
_sendUiState.update {
it.copy(
selectedTags = it.selectedTags.filterNot { tagItem -> tagItem == tag }.toImmutableList()
)
}
}
init {
viewModelScope.launch {
ToastEventBus.events.collect {
toast(it)
}
}
viewModelScope.launch {
// Delays are required for auth check on launch functionality
delay(AUTH_CHECK_INITIAL_DELAY_MS)
resetIsAuthenticatedState()
delay(AUTH_CHECK_SPLASH_DELAY_MS)
splashVisible = false
}
viewModelScope.launch {
lightningRepo.updateGeoBlockState()
}
viewModelScope.launch {
widgetsRepo.refreshEnabledWidgets()
}
viewModelScope.launch {
timedSheetManager.currentSheet.collect { sheetType ->
if (sheetType != null) {
val currentSheet = _currentSheet.value
val isHighPrioritySheetShowing = currentSheet is Sheet.Gift ||
currentSheet is Sheet.Send ||
currentSheet is Sheet.LnurlAuth ||
currentSheet is Sheet.Pin
if (!isHighPrioritySheetShowing) {
showSheet(Sheet.TimedSheet(sheetType))
}
} else {
// Clear the timed sheet when manager sets it to null
_currentSheet.update { current ->
if (current is Sheet.TimedSheet) null else current
}
}
}
}
observeLdkNodeEvents()
observeSendEvents()
viewModelScope.launch {
checkCriticalAppUpdate()
}
viewModelScope.launch {
migrationService.isShowingMigrationLoading.collect { isShowing ->
if (isShowing) {
@Suppress("SwallowedException")
try {
withTimeout(MIGRATION_LOADING_TIMEOUT_MS) {
migrationService.isShowingMigrationLoading.first { !it }
}
} catch (e: TimeoutCancellationException) {
val timeoutSecs = MIGRATION_LOADING_TIMEOUT_MS / 1000
Logger.warn("Migration loading timeout (${timeoutSecs}s), dismissing", context = TAG)
migrationService.setShowingMigrationLoading(false)
}
} else {
if (migrationService.needsPostMigrationSync()) {
ToastEventBus.send(
type = Toast.ToastType.WARNING,
title = context.getString(R.string.migration__network_required_title),
description = context.getString(R.string.migration__network_required_msg),
)
}
}
}
}
}
private fun observeLdkNodeEvents() {
viewModelScope.launch {
lightningRepo.nodeEvents.collect { handleLdkEvent(it) }
}
}
@Suppress("CyclomaticComplexMethod")
private fun handleLdkEvent(event: Event) {
if (!walletRepo.walletExists()) return
Logger.debug("LDK-node event received in $TAG: ${jsonLogOf(event)}", context = TAG)
viewModelScope.launch {
runCatching {
when (event) {
is Event.BalanceChanged -> handleBalanceChanged()
is Event.ChannelClosed -> handleChannelClosed(event)
is Event.ChannelPending -> handleChannelPending()
is Event.ChannelReady -> handleChannelReady(event)
is Event.OnchainTransactionConfirmed -> handleOnchainTransactionConfirmed(event)
is Event.OnchainTransactionEvicted -> handleOnchainTransactionEvicted(event)
is Event.OnchainTransactionReceived -> handleOnchainTransactionReceived(event)
is Event.OnchainTransactionReorged -> handleOnchainTransactionReorged(event)
is Event.OnchainTransactionReplaced -> handleOnchainTransactionReplaced(event)
is Event.PaymentClaimable -> Unit
is Event.PaymentFailed -> handlePaymentFailed(event)
is Event.PaymentForwarded -> Unit
is Event.PaymentReceived -> handlePaymentReceived(event)
is Event.PaymentSuccessful -> handlePaymentSuccessful(event)
is Event.SpliceFailed -> Unit
is Event.SplicePending -> Unit
is Event.SyncCompleted -> handleSyncCompleted()
is Event.SyncProgress -> Unit
}
}.onFailure { e ->
if (e is CancellationException) throw e
Logger.error("LDK event handler error", e, context = TAG)
}
}
}
private suspend fun handleBalanceChanged() {
walletRepo.syncBalances()
transferRepo.syncTransferStates()
}
private suspend fun handleChannelReady(event: Event.ChannelReady) {
transferRepo.syncTransferStates()
walletRepo.syncBalances()
notifyChannelReady(event)
}
private suspend fun handleChannelPending() = transferRepo.syncTransferStates()
private suspend fun handleChannelClosed(event: Event.ChannelClosed) {
val reason = event.reason
if (reason != null) {
val (isCounterpartyClose, isForceClose) = classifyClosureReason(reason)
if (isCounterpartyClose) {
createTransferForCounterpartyClose(event.channelId, isForceClose)
showSheet(Sheet.ConnectionClosed)
}
}
transferRepo.syncTransferStates()
walletRepo.syncBalances()
}
private suspend fun createTransferForCounterpartyClose(channelId: String, isForceClose: Boolean) {
val transferType = if (isForceClose) TransferType.FORCE_CLOSE else TransferType.COOP_CLOSE
val balances = lightningRepo.getBalancesAsync().getOrNull()
val lightningBalance = balances?.lightningBalances?.find { it.channelId() == channelId }
var channelBalance = lightningBalance?.amountSats() ?: 0uL
if (channelBalance == 0uL) {
val closedChannels = runCatching {
coreService.activity.closedChannels(SortDirection.DESC)
}.getOrNull()
channelBalance = closedChannels
?.firstOrNull { it.channelId == channelId }
?.channelValueSats ?: 0uL
}
if (channelBalance > 0uL) {
transferRepo.createTransfer(
type = transferType,
amountSats = channelBalance.toLong(),
channelId = channelId,
claimableAtHeight = lightningBalance?.claimableAtHeight(),
)
}
}
private fun classifyClosureReason(reason: ClosureReason): Pair<Boolean, Boolean> {
return when (reason) {
is ClosureReason.CounterpartyForceClosed -> true to true
is ClosureReason.CommitmentTxConfirmed -> true to true
is ClosureReason.CounterpartyInitiatedCooperativeClosure -> true to false
is ClosureReason.CounterpartyCoopClosedUnfundedChannel -> true to false
else -> false to false
}
}
private suspend fun handleSyncCompleted() {
val isShowingLoading = migrationService.isShowingMigrationLoading.value
val isRestoringRemote = migrationService.isRestoringFromRNRemoteBackup.value
val needsPostMigrationSync = migrationService.needsPostMigrationSync()
val pendingPrune = settingsStore.data.first().pendingRestoreAddressTypePrune
when {
(isShowingLoading || needsPostMigrationSync) && !isCompletingMigration -> completeMigration()
isRestoringRemote -> completeRNRemoteBackupRestore()
pendingPrune -> {
settingsStore.update { it.copy(pendingRestoreAddressTypePrune = false) }
delay(POST_RESTORE_PRUNE_DELAY_MS)
lightningRepo.pruneEmptyAddressTypesAfterRestore()
walletRepo.debounceSyncByEvent()
}
!isShowingLoading && !needsPostMigrationSync && !isCompletingMigration -> walletRepo.debounceSyncByEvent()
else -> Unit
}
}
private suspend fun completeRNRemoteBackupRestore() {
val channelMigration = buildChannelMigrationIfAvailable()
if (channelMigration != null) {
lightningRepo.stop().onFailure {
Logger.error("Failed to stop node during remote restore restart", it, context = TAG)
}
delay(REMOTE_RESTORE_NODE_RESTART_DELAY_MS)
lightningRepo.start(channelMigration = channelMigration, shouldRetry = false)
.onSuccess {
migrationService.consumePendingChannelMigration()
walletRepo.syncNodeAndWallet()
walletRepo.syncBalances()
}
.onFailure { e ->
Logger.error("Failed to restart node after remote restore: $e", e, context = TAG)
}
}
lightningRepo.getPayments().onSuccess { activityRepo.syncLdkNodePayments(it) }
migrationService.reapplyMetadataAfterSync()
activityRepo.syncActivities()
walletRepo.syncBalances()
if (migrationService.canCleanupAfterMigration) {
migrationService.cleanupAfterMigration()
migrationService.setRestoringFromRNRemoteBackup(false)
migrationService.setShowingMigrationLoading(false)
} else {
Logger.info("Post-migration sync incomplete (remote restore), will retry on next sync", context = TAG)
migrationService.setShowingMigrationLoading(false)
}
}
private fun buildChannelMigrationIfAvailable(): ChannelDataMigration? {
val migration = migrationService.peekPendingChannelMigration() ?: return null
return ChannelDataMigration(
channelManager = migration.channelManager.map { it.toUByte() },
channelMonitors = migration.channelMonitors.map { monitor -> monitor.map { it.toUByte() } },
)
}
private suspend fun completeMigration() {
if (isCompletingMigration) return
isCompletingMigration = true
runCatching {
lightningRepo.getPayments().onSuccess { payments ->
activityRepo.syncLdkNodePayments(payments)
}.onFailure { e ->
Logger.warn("Failed to get payments during migration: $e", e, context = TAG)
}
activityRepo.markAllUnseenActivitiesAsSeen()
migrationService.consumePendingChannelMigration()
walletRepo.syncNodeAndWallet()
.onSuccess { finishMigrationSuccessfully() }
.onFailure { e ->
Logger.warn("Sync failed during migration: $e", e, context = TAG)
finishMigrationWithFallbackSync()
}
}.onFailure { e ->
Logger.error("Migration completion error: $e", e, context = TAG)
finishMigrationWithError()
}.also {
isCompletingMigration = false
}
}
private suspend fun finishMigrationSuccessfully() {
lightningRepo.getPayments().onSuccess { payments ->
activityRepo.syncLdkNodePayments(payments)
}
transferRepo.syncTransferStates()
migrationService.reapplyMetadataAfterSync()
if (migrationService.canCleanupAfterMigration) {
migrationService.cleanupAfterMigration()
migrationService.setShowingMigrationLoading(false)
delay(MIGRATION_AUTH_RESET_DELAY_MS)
resetIsAuthenticatedStateInternal()
} else {
Logger.info("Post-migration sync incomplete, will retry on next sync", context = TAG)
migrationService.setShowingMigrationLoading(false)
}
}
private suspend fun finishMigrationWithFallbackSync() {
walletRepo.syncBalances()
lightningRepo.getPayments().onSuccess { payments ->
activityRepo.syncLdkNodePayments(payments)
}
transferRepo.syncTransferStates()
migrationService.reapplyMetadataAfterSync()
if (migrationService.canCleanupAfterMigration) {
migrationService.cleanupAfterMigration()
migrationService.setShowingMigrationLoading(false)
delay(MIGRATION_AUTH_RESET_DELAY_MS)
resetIsAuthenticatedStateInternal()
} else {
Logger.info("Post-migration sync incomplete (fallback), will retry on next sync", context = TAG)
migrationService.setShowingMigrationLoading(false)
}
}
private suspend fun finishMigrationWithError() {
migrationService.setShowingMigrationLoading(false)
delay(MIGRATION_AUTH_RESET_DELAY_MS)
resetIsAuthenticatedStateInternal()
toast(
type = Toast.ToastType.ERROR,
title = "Migration Warning",
description = "Migration completed but node restart failed. Please restart the app."
)
}
private suspend fun handleOnchainTransactionConfirmed(event: Event.OnchainTransactionConfirmed) {
activityRepo.handleOnchainTransactionConfirmed(event.txid, event.details)
}
private suspend fun handleOnchainTransactionEvicted(event: Event.OnchainTransactionEvicted) {
activityRepo.handleOnchainTransactionEvicted(event.txid)
notifyTransactionRemoved(event)
}
private suspend fun handleOnchainTransactionReceived(event: Event.OnchainTransactionReceived) {
notifyPaymentReceived(event)
}
private suspend fun handleOnchainTransactionReorged(event: Event.OnchainTransactionReorged) {
activityRepo.handleOnchainTransactionReorged(event.txid)
notifyTransactionUnconfirmed()
}
private suspend fun handleOnchainTransactionReplaced(event: Event.OnchainTransactionReplaced) {
// If the replaced transaction was just boosted via RBF from within the app, we already show a
// dedicated boost success toast; suppress the generic "transaction replaced" toast to avoid
// flakiness/noise (notably in E2E flows).
val shouldSuppressReplacedToast = activityRepo
.getOnchainActivityByTxId(event.txid)
?.let { it.isBoosted && it.txType == PaymentType.SENT } == true
activityRepo.handleOnchainTransactionReplaced(event.txid, event.conflicts)
if (!shouldSuppressReplacedToast) {
notifyTransactionReplaced(event)
}
}
private suspend fun handlePaymentFailed(event: Event.PaymentFailed) {
event.paymentHash?.let { paymentHash ->
activityRepo.handlePaymentEvent(paymentHash)
if (pendingPaymentRepo.isPending(paymentHash)) {
pendingPaymentRepo.resolve(PendingPaymentResolution.Failure(paymentHash))
if (_currentSheet.value !is Sheet.Send || !pendingPaymentRepo.isActive(paymentHash)) {
notifyPendingPaymentFailed()
}
return
}
}
notifyPaymentFailed(event.reason)
}
private suspend fun handlePaymentReceived(event: Event.PaymentReceived) {
event.paymentHash.let { paymentHash ->
activityRepo.handlePaymentEvent(paymentHash)
}
notifyPaymentReceived(event)
}
private suspend fun handlePaymentSuccessful(event: Event.PaymentSuccessful) {
event.paymentHash.let { paymentHash ->
activityRepo.handlePaymentEvent(paymentHash)
if (pendingPaymentRepo.isPending(paymentHash)) {
pendingPaymentRepo.resolve(PendingPaymentResolution.Success(paymentHash))
if (_currentSheet.value !is Sheet.Send || !pendingPaymentRepo.isActive(paymentHash)) {
notifyPendingPaymentSucceeded()
}
return
}
}
notifyPaymentSentOnLightning(event)
}
// region Notifications
private suspend fun notifyChannelReady(event: Event.ChannelReady) {
val channel = lightningRepo.getChannels()?.find { it.channelId == event.channelId }
val cjitEntry = channel?.let { blocktankRepo.getCjitEntry(it) }
if (cjitEntry != null) {
val amount = channel.amountOnClose.toLong()
showTransactionSheet(
NewTransactionSheetDetails(
type = NewTransactionSheetType.LIGHTNING,
direction = NewTransactionSheetDirection.RECEIVED,
sats = amount,
),
)
activityRepo.insertActivityFromCjit(cjitEntry = cjitEntry, channel = channel)
return
}
toast(
type = Toast.ToastType.LIGHTNING,
title = context.getString(R.string.lightning__channel_opened_title),
description = context.getString(R.string.lightning__channel_opened_msg),
testTag = "SpendingBalanceReadyToast",
)
}
private suspend fun notifyTransactionRemoved(event: Event.OnchainTransactionEvicted) {
if (activityRepo.wasTransactionReplaced(event.txid)) return
toast(
type = Toast.ToastType.WARNING,
title = context.getString(R.string.wallet__toast_transaction_removed_title),
description = context.getString(R.string.wallet__toast_transaction_removed_description),
testTag = "TransactionRemovedToast",
)
}
private suspend fun notifyPaymentReceived(event: Event) {
if (migrationService.isShowingMigrationLoading.value || migrationService.needsPostMigrationSync()) {
return
}
val command = NotifyPaymentReceived.Command.from(event) ?: return
val result = notifyPaymentReceivedHandler(command).getOrNull()
if (result !is NotifyPaymentReceived.Result.ShowSheet) return
showTransactionSheet(result.sheet)
}
private fun notifyTransactionUnconfirmed() = toast(
type = Toast.ToastType.WARNING,
title = context.getString(R.string.wallet__toast_transaction_unconfirmed_title),
description = context.getString(R.string.wallet__toast_transaction_unconfirmed_description),
testTag = "TransactionUnconfirmedToast",
)
private suspend fun notifyTransactionReplaced(event: Event.OnchainTransactionReplaced) {
val isReceive = activityRepo.isReceivedTransaction(event.txid)
toast(
type = Toast.ToastType.INFO,
title = when (isReceive) {
true -> R.string.wallet__toast_received_transaction_replaced_title
else -> R.string.wallet__toast_transaction_replaced_title
}.let { context.getString(it) },
description = when (isReceive) {
true -> R.string.wallet__toast_received_transaction_replaced_description
else -> R.string.wallet__toast_transaction_replaced_description
}.let { context.getString(it) },
testTag = when (isReceive) {
true -> "ReceivedTransactionReplacedToast"
else -> "TransactionReplacedToast"
},
)
}
private fun notifyPendingPaymentSucceeded() = PendingPaymentNotification.success(context).let {
toast(
type = Toast.ToastType.LIGHTNING,
title = it.title,
description = it.body,
testTag = "PendingPaymentSucceededToast",
)
}
private fun notifyPendingPaymentFailed() = PendingPaymentNotification.error(context).let {
toast(
type = Toast.ToastType.ERROR,
title = it.title,
description = it.body,
testTag = "PendingPaymentFailedToast",
)
}
private fun notifyPaymentFailed(reason: PaymentFailureReason? = null) = toast(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.wallet__toast_payment_failed_title),
description = reason.toUserMessage(context),
testTag = "PaymentFailedToast",
)
private suspend fun notifyPaymentSentOnLightning(event: Event.PaymentSuccessful): Result<Activity> {
val paymentHash = event.paymentHash
// TODO Temporary solution while LDK node doesn't return the sent value in the event
return activityRepo.findActivityByPaymentId(
paymentHashOrTxId = paymentHash,
type = ActivityFilter.LIGHTNING,
txType = PaymentType.SENT,
retry = true
).onSuccess { activity ->
onSendSuccess(
NewTransactionSheetDetails(
type = NewTransactionSheetType.LIGHTNING,
direction = NewTransactionSheetDirection.SENT,
paymentHashOrTxId = event.paymentHash,
sats = activity.totalValue().toLong(),
),
)
}.onFailure {
Logger.warn("Failed displaying sheet for event: $event", it, context = TAG)
}
}
// endregion
// region send
@Suppress("CyclomaticComplexMethod")
private fun observeSendEvents() {
viewModelScope.launch {
sendEvents.collect {
when (it) {
SendEvent.EnterManually -> onEnterManuallyClick()
SendEvent.Paste -> onPasteClick()
SendEvent.Scan -> onScanClick()
is SendEvent.AddressChange -> onAddressChange(it.value)
SendEvent.AddressReset -> resetAddressInput()
is SendEvent.AddressContinue -> onAddressContinue(it.data)
is SendEvent.AmountChange -> onAmountChange(it.amount)
SendEvent.AmountReset -> resetAmountInput()
SendEvent.AmountContinue -> onAmountContinue()
SendEvent.PaymentMethodSwitch -> onPaymentMethodSwitch()
is SendEvent.CoinSelectionContinue -> onCoinSelectionContinue(it.utxos)
is SendEvent.CommentChange -> onCommentChange(it.value)
SendEvent.SpeedAndFee -> {
if (_sendUiState.value.fees.isEmpty()) {
viewModelScope.launch {
refreshFeeEstimates()
setSendEffect(SendEffect.NavigateToFee)
}
} else {
setSendEffect(SendEffect.NavigateToFee)
}
}
SendEvent.SwipeToPay -> onSwipeToPay()
is SendEvent.ConfirmAmountWarning -> onConfirmAmountWarning(it.warning)
SendEvent.DismissAmountWarning -> onDismissAmountWarning()
SendEvent.EstimateMaxRoutingFee -> viewModelScope.launch {
estimateMaxAmountRoutingFee()
}
SendEvent.PayConfirmed -> onConfirmPay()
SendEvent.ClearPayConfirmation -> _sendUiState.update { s -> s.copy(shouldConfirmPay = false) }
SendEvent.BackToAmount -> setSendEffect(SendEffect.PopBack(SendRoute.Amount))
SendEvent.NavToAddress -> setSendEffect(SendEffect.NavigateToAddress)
SendEvent.Contacts -> setSendEffect(SendEffect.NavigateToComingSoon)
}
}
}
}
private val isMainScanner get() = currentSheet.value !is Sheet.Send
private fun onEnterManuallyClick() {
resetAddressInput()
setSendEffect(SendEffect.NavigateToAddress)
}
private fun resetAddressInput() {
addressValidationJob?.cancel()
_sendUiState.update { state ->
state.copy(
addressInput = "",
isAddressInputValid = false,
)
}
}
private fun onAddressChange(value: String) {
val valueWithoutSpaces = value.removeSpaces()
// Update text immediately, reset validity until validation completes
_sendUiState.update {
it.copy(
addressInput = valueWithoutSpaces,
isAddressInputValid = false,
)
}
// Cancel pending validation
addressValidationJob?.cancel()
// Skip validation for empty input
if (valueWithoutSpaces.isEmpty()) return
// Start debounced validation
addressValidationJob = viewModelScope.launch {
delay(ADDRESS_VALIDATION_DEBOUNCE_MS)
validateAddressWithFeedback(valueWithoutSpaces)
}
}
private suspend fun validateAddressWithFeedback(input: String) = withContext(bgDispatcher) {
// TODO Workaround for https://github.com/synonymdev/bitkit-core/issues/63
if (Bip21Utils.isDuplicatedBip21(input)) {
showAddressValidationError(
titleRes = R.string.other__scan_err_decoding,
descriptionRes = R.string.other__scan__error__generic,
testTag = "DuplicatedBip21Toast",
)
return@withContext
}
val scanResult = runCatching { coreService.decode(input.removeLightningSchemes()) }
if (scanResult.isFailure) {
showAddressValidationError(
titleRes = R.string.other__scan_err_decoding,
descriptionRes = R.string.other__scan__error__generic,
testTag = "InvalidAddressToast",
)
return@withContext
}
when (val decoded = scanResult.getOrNull()) {
is Scanner.Lightning -> validateLightningInvoice(decoded.invoice)
is Scanner.OnChain -> validateOnChainAddress(decoded.invoice)
else -> _sendUiState.update { it.copy(isAddressInputValid = true) }
}
}
private suspend fun validateLightningInvoice(invoice: LightningInvoice) {
if (invoice.isExpired) {
showAddressValidationError(
titleRes = R.string.other__scan_err_decoding,
descriptionRes = R.string.other__scan__error__expired,
testTag = "ExpiredLightningToast",
)
return
}
if (invoice.amountSatoshis > 0uL) {
val maxSendLightning = walletRepo.balanceState.value.maxSendLightningSats
if (maxSendLightning == 0uL || !lightningRepo.canSend(invoice.amountSatoshis)) {
val shortfall = invoice.amountSatoshis.safe() - maxSendLightning.safe()
showAddressValidationError(
titleRes = R.string.other__pay_insufficient_spending,
descriptionRes = R.string.other__pay_insufficient_spending_amount_description,
descriptionArgs = mapOf("amount" to formatMoneyValue(shortfall)),
testTag = "InsufficientSpendingToast",
)
return
}
}
_sendUiState.update { it.copy(isAddressInputValid = true) }
}
private suspend fun validateOnChainAddress(invoice: OnChainInvoice) {
val validatedAddress = runCatching { validateBitcoinAddress(invoice.address) }
.getOrElse {
showAddressValidationError(
titleRes = R.string.other__scan_err_decoding,
descriptionRes = R.string.wallet__error_invalid_bitcoin_address,
testTag = "InvalidAddressToast",
)
return
}
if (NetworkValidationHelper.isNetworkMismatch(validatedAddress.network.toLdkNetwork(), Env.network)) {
showAddressValidationError(
titleRes = R.string.other__scan_err_decoding,
descriptionRes = R.string.other__scan__error__generic,
testTag = "InvalidAddressToast",
)
return
}
extractViableLightningInvoice(invoice.params)?.let { lnInvoice ->
_sendUiState.update {
it.copy(
isAddressInputValid = true,
isUnified = true,
decodedInvoice = lnInvoice,
payMethod = SendMethod.LIGHTNING,
)
}
updateCanSwitchWallet()
return
}
val maxSendOnchain = walletRepo.balanceState.value.maxSendOnchainSats
if (maxSendOnchain == 0uL) {
showAddressValidationError(
titleRes = R.string.other__pay_insufficient_savings,
descriptionRes = R.string.other__pay_insufficient_savings_description,
testTag = "InsufficientSavingsToast",
)
return
}
if (invoice.amountSatoshis > 0uL && invoice.amountSatoshis > maxSendOnchain) {
val shortfall = invoice.amountSatoshis - maxSendOnchain
showAddressValidationError(
titleRes = R.string.other__pay_insufficient_savings,
descriptionRes = R.string.other__pay_insufficient_savings_amount_description,
descriptionArgs = mapOf("amount" to formatMoneyValue(shortfall)),
testTag = "InsufficientSavingsToast",
)
return
}
_sendUiState.update { it.copy(isAddressInputValid = true) }
}
private suspend fun extractViableLightningInvoice(params: Map<String, String>?): LightningInvoice? =
params?.get("lightning")?.let { bolt11 ->
runCatching { coreService.decode(bolt11) }.getOrNull()
?.let { it as? Scanner.Lightning }
?.invoice
?.takeIf { lnInv ->
if (lnInv.isExpired) {
Logger.debug(
"Lightning invoice expired in unified URI, defaulting to onchain-only",
context = TAG
)
return@takeIf false
}
val canSend = lightningRepo.canSend(lnInv.amountSatoshis.coerceAtLeast(1u))
if (!canSend) {
val nodeState = lightningRepo.lightningState.value.nodeLifecycleState
if (nodeState is NodeLifecycleState.Stopped) {
Logger.debug(
"Node stopped, optimistically including LN invoice in unified QR",
context = TAG,
)
return@takeIf true
}
Logger.debug(
"Cannot pay unified invoice using LN, defaulting to onchain-only",
context = TAG,