-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathsend_cubit.dart
More file actions
2415 lines (2303 loc) · 90.3 KB
/
Copy pathsend_cubit.dart
File metadata and controls
2415 lines (2303 loc) · 90.3 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
import 'dart:async';
import 'package:bb_mobile/core/blockchain/domain/usecases/broadcast_bitcoin_transaction_usecase.dart';
import 'package:bb_mobile/core/blockchain/domain/usecases/broadcast_liquid_transaction_usecase.dart';
import 'package:bb_mobile/core/errors/send_errors.dart'
show BroadcastTransactionException;
import 'package:bb_mobile/core/exchange/domain/usecases/convert_sats_to_currency_amount_usecase.dart';
import 'package:bb_mobile/core/exchange/domain/usecases/get_available_currencies_usecase.dart';
import 'package:bb_mobile/core/fees/domain/fee_preview_cache.dart';
import 'package:bb_mobile/core/fees/domain/fees_entity.dart';
import 'package:bb_mobile/core/fees/domain/get_network_fees_usecase.dart';
import 'package:bb_mobile/core/payjoin/domain/usecases/send_with_payjoin_usecase.dart';
import 'package:bb_mobile/core/settings/domain/get_settings_usecase.dart';
import 'package:bb_mobile/core/settings/domain/settings_entity.dart';
import 'package:bb_mobile/core/swaps/domain/entity/swap.dart';
import 'package:bb_mobile/core/swaps/domain/usecases/create_chain_swap_to_external_usecase.dart';
import 'package:bb_mobile/core/swaps/domain/usecases/decode_invoice_usecase.dart';
import 'package:bb_mobile/core/swaps/domain/usecases/get_swap_limits_usecase.dart';
import 'package:bb_mobile/core/swaps/domain/usecases/update_send_swap_lockup_fees_usecase.dart';
import 'package:bb_mobile/core/swaps/domain/usecases/verify_chain_swap_amount_send_usecase.dart';
import 'package:bb_mobile/core/swaps/domain/usecases/watch_swap_usecase.dart';
import 'package:bb_mobile/core/utils/amount_conversions.dart';
import 'package:bb_mobile/core/utils/constants.dart';
import 'package:bb_mobile/core/utils/lightning.dart';
import 'package:bb_mobile/core/utils/logger.dart';
import 'package:bb_mobile/core/utils/payment_request.dart';
import 'package:bb_mobile/core/wallet/domain/entities/wallet.dart';
import 'package:bb_mobile/core/wallet/domain/entities/wallet_transaction.dart';
import 'package:bb_mobile/core/wallet/domain/entities/wallet_utxo.dart';
import 'package:bb_mobile/core/wallet/domain/usecases/get_wallet_usecase.dart';
import 'package:bb_mobile/core/wallet/domain/usecases/get_wallet_utxos_usecase.dart';
import 'package:bb_mobile/core/wallet/domain/usecases/get_wallets_usecase.dart';
import 'package:bb_mobile/core/wallet/domain/usecases/watch_finished_wallet_syncs_usecase.dart';
import 'package:bb_mobile/core/wallet/domain/usecases/watch_wallet_transaction_by_tx_id_usecase.dart';
import 'package:bb_mobile/core/widgets/fees/fee_modal_controller.dart';
import 'package:bb_mobile/core/wallet/domain/usecases/calculate_bitcoin_absolute_fees_usecase.dart';
import 'package:bb_mobile/features/send/domain/usecases/calculate_liquid_absolute_fees_usecase.dart';
import 'package:bb_mobile/features/send/domain/usecases/calculate_liquid_pset_size_usecase.dart';
import 'package:bb_mobile/features/send/domain/usecases/create_send_swap_usecase.dart';
import 'package:bb_mobile/features/send/domain/usecases/detect_bitcoin_string_usecase.dart';
import 'package:bb_mobile/core/wallet/domain/usecases/prepare_bitcoin_send_usecase.dart';
import 'package:bb_mobile/features/send/domain/usecases/prepare_liquid_send_usecase.dart';
import 'package:bb_mobile/features/send/domain/usecases/preview_bitcoin_fee_presets_usecase.dart';
import 'package:bb_mobile/features/send/domain/usecases/preview_bitcoin_fee_usecase.dart';
import 'package:bb_mobile/features/send/domain/usecases/select_best_wallet_usecase.dart';
import 'package:bb_mobile/features/send/domain/usecases/sign_bitcoin_tx_usecase.dart';
import 'package:bb_mobile/features/send/domain/usecases/sign_liquid_tx_usecase.dart';
import 'package:bb_mobile/features/send/domain/usecases/update_paid_send_swap_usecase.dart';
import 'package:bb_mobile/features/labels/labels_facade.dart';
import 'package:bb_mobile/features/send/presentation/bloc/send_state.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SendCubit extends Cubit<SendState>
implements FeeModalActions, FeeModalViewState {
SendCubit({
this._wallet,
required this._labelsFacade,
required this._bestWalletUsecase,
required this._detectBitcoinStringUsecase,
required this._getSettingsUsecase,
required this._convertSatsToCurrencyAmountUsecase,
required this._getNetworkFeesUsecase,
required this._getWalletUtxosUsecase,
required this._getAvailableCurrenciesUsecase,
required this._prepareBitcoinSendUsecase,
required this._prepareLiquidSendUsecase,
required this._sendWithPayjoinUsecase,
required this._getWalletsUsecase,
required this._getWalletUsecase,
required this._createSendSwapUsecase,
required this._updatePaidSendSwapUsecase,
required this._getSwapLimitsUsecase,
required this._watchSwapUsecase,
required this._watchFinishedWalletSyncsUsecase,
required this._decodeInvoiceUsecase,
required this._signBitcoinTxUsecase,
required this._signLiquidTxUsecase,
required this._broadcastBitcoinTxUsecase,
required this._broadcastLiquidTxUsecase,
required this._calculateLiquidAbsoluteFeesUsecase,
required this._calculateLiquidPsetSizeUsecase,
required this._createChainSwapToExternalUsecase,
required this._watchWalletTransactionByTxIdUsecase,
required this._calculateBitcoinAbsoluteFeesUsecase,
required this._updateSendSwapLockupFeesUsecase,
required this._verifyChainSwapAmountSendUsecase,
required this._previewBitcoinFeeUsecase,
required this._previewBitcoinFeePresetsUsecase,
}) : super(const SendState());
/// Distinct user-defined labels for the suggestion chips in the label
/// bottom sheet. Wraps [LabelsFacade.fetchDistinctLabels] so widgets
/// don't need to reach into the locator.
Future<Set<String>> fetchDistinctLabels() =>
_labelsFacade.fetchDistinctLabels();
// ignore: unused_field
final Wallet? _wallet;
final LabelsFacade _labelsFacade;
final SelectBestWalletUsecase _bestWalletUsecase;
final DetectBitcoinStringUsecase _detectBitcoinStringUsecase;
final GetAvailableCurrenciesUsecase _getAvailableCurrenciesUsecase;
final GetSettingsUsecase _getSettingsUsecase;
final ConvertSatsToCurrencyAmountUsecase _convertSatsToCurrencyAmountUsecase;
final GetNetworkFeesUsecase _getNetworkFeesUsecase;
final GetWalletUtxosUsecase _getWalletUtxosUsecase;
final GetWalletsUsecase _getWalletsUsecase;
final GetWalletUsecase _getWalletUsecase;
final PrepareBitcoinSendUsecase _prepareBitcoinSendUsecase;
final PrepareLiquidSendUsecase _prepareLiquidSendUsecase;
final CalculateLiquidPsetSizeUsecase _calculateLiquidPsetSizeUsecase;
final CreateSendSwapUsecase _createSendSwapUsecase;
final SignBitcoinTxUsecase _signBitcoinTxUsecase;
final SignLiquidTxUsecase _signLiquidTxUsecase;
final BroadcastLiquidTransactionUsecase _broadcastLiquidTxUsecase;
final BroadcastBitcoinTransactionUsecase _broadcastBitcoinTxUsecase;
final SendWithPayjoinUsecase _sendWithPayjoinUsecase;
final UpdatePaidSendSwapUsecase _updatePaidSendSwapUsecase;
final GetSwapLimitsUsecase _getSwapLimitsUsecase;
final DecodeInvoiceUsecase _decodeInvoiceUsecase;
final CalculateLiquidAbsoluteFeesUsecase _calculateLiquidAbsoluteFeesUsecase;
final WatchSwapUsecase _watchSwapUsecase;
final WatchFinishedWalletSyncsUsecase _watchFinishedWalletSyncsUsecase;
final WatchWalletTransactionByTxIdUsecase
_watchWalletTransactionByTxIdUsecase;
final CreateChainSwapToExternalUsecase _createChainSwapToExternalUsecase;
final CalculateBitcoinAbsoluteFeesUsecase
_calculateBitcoinAbsoluteFeesUsecase;
final UpdateSendSwapLockupFeesUsecase _updateSendSwapLockupFeesUsecase;
final VerifyChainSwapAmountSendUsecase _verifyChainSwapAmountSendUsecase;
final PreviewBitcoinFeeUsecase _previewBitcoinFeeUsecase;
final PreviewBitcoinFeePresetsUsecase _previewBitcoinFeePresetsUsecase;
StreamSubscription<Swap>? _swapSubscription;
StreamSubscription<Wallet>? _selectedWalletSyncingSubscription;
StreamSubscription<WalletTransaction>? _txSubscription;
/// Monotonic token bumped by [clearBitcoinFeePreviews]. A preview build
/// captures it before its `await` and re-checks before writing results
/// back; if any input-shape change cleared the cache mid-flight the
/// token moved on and the stale build is discarded instead of
/// re-populating an emptied cache (which could otherwise stage a PSBT
/// built for the previous tx shape for broadcast).
int _bitcoinPreviewEpoch = 0;
@override
Future<void> close() async {
await (
_swapSubscription?.cancel() ?? Future.value(),
_selectedWalletSyncingSubscription?.cancel() ?? Future.value(),
_txSubscription?.cancel() ?? Future.value(),
).wait;
return super.close();
}
/// LWK and the RBF builder are rate-only at the SDK boundary. When the user
/// picked an absolute custom fee, we need a tx vsize to convert the absolute
/// amount back to a rate. We get vsize by building a placeholder PSET at
/// Liquid's minrelayfee — vsize is essentially independent of the fee rate,
/// so the placeholder is accurate to within a single vbyte.
Future<RelativeFee> _resolveLiquidFeeRate({
required NetworkFee fee,
required String walletId,
required String address,
required int? amountSat,
required bool drain,
}) async {
if (fee is RelativeFee) return fee;
if (fee is! AbsoluteFee) {
throw StateError('Unexpected NetworkFee variant: $fee');
}
final placeholderPset = await _prepareLiquidSendUsecase.execute(
walletId: walletId,
address: address,
amountSat: amountSat,
feeRate: const RelativeFee(25),
drain: drain,
);
final vsize = await _calculateLiquidPsetSizeUsecase.execute(
pset: placeholderPset,
);
return NetworkFee.relativeFromAbsoluteAndVsize(
absoluteSats: fee.sats,
vsize: vsize,
);
}
void clearAllExceptions() {
emit(
state.copyWith(
insufficientBalanceException: null,
swapCreationException: null,
swapLimitsException: null,
invalidBitcoinStringException: null,
buildTransactionException: null,
confirmTransactionException: null,
),
);
}
void backClicked() {
if (state.step == SendStep.address) {
emit(state.copyWith(step: SendStep.address));
} else if (state.step == SendStep.amount) {
emit(state.copyWith(step: SendStep.address));
} else if (state.step == SendStep.confirm) {
// Leaving confirm to edit the amount/recipient invalidates whatever
// was built/signed for the transaction currently on screen — the
// next createTransaction() call (triggered by re-confirming the
// amount) already clears these before rebuilding, but clear them
// here too so a finalized hardware-wallet signature can never be
// shown as "ready to broadcast" while the user is mid-edit.
emit(
state.copyWith(
step: SendStep.amount,
buildTransactionException: null,
signedBitcoinTx: null,
signedBitcoinPsbt: null,
signedLiquidTx: null,
),
);
}
}
Future<void> loadWalletWithRatesAndFees() async {
try {
final wallets = await _getWalletsUsecase.execute();
emit(
state.copyWith(wallets: wallets.where((w) => !w.isWatchOnly).toList()),
);
await getCurrencies();
await getExchangeRate();
await loadFees();
} catch (e) {
emit(state.copyWith(error: e.toString()));
}
}
/// Called when a payment request is detected directly from the scanner
Future<void> onScannedPaymentRequest(
String scannedRawPaymentRequest,
PaymentRequest? paymentRequest,
) async {
clearAllExceptions();
final sanitizedText = scannedRawPaymentRequest.trim().replaceAll(
RegExp(r'^["\"]+|["\"]+$'),
'',
);
final recipientChanged =
state.paymentRequest != paymentRequest ||
state.scannedRawPaymentRequest != scannedRawPaymentRequest;
emit(
state.copyWith(
scannedRawPaymentRequest: scannedRawPaymentRequest,
copiedRawPaymentRequest: sanitizedText,
paymentRequest: paymentRequest,
),
);
// Recipient is part of the cache fingerprint — a different address
// means a different output script in the PSBT. Skip the clear when
// nothing actually changed so the modal doesn't re-shimmer on a
// no-op scan.
if (recipientChanged) clearBitcoinFeePreviews();
await continueOnAddressConfirmed();
}
/// Called when text is pasted or entered manually
Future<void> onChangedText(String text) async {
try {
clearAllExceptions();
final sanitizedText = text.trim().replaceAll(
RegExp(r'^["\"]+|["\"]+$'),
'',
);
final paymentRequest = await _detectBitcoinStringUsecase.execute(
data: sanitizedText,
);
final recipientChanged = state.paymentRequest != paymentRequest;
emit(
state.copyWith(
copiedRawPaymentRequest: sanitizedText,
paymentRequest: paymentRequest,
),
);
// Same invalidation reason as onScannedPaymentRequest — recipient
// changed. Skip when paste/typing resolves to the same paymentRequest.
if (recipientChanged) clearBitcoinFeePreviews();
} catch (e) {
final recipientCleared = state.paymentRequest != null;
emit(
state.copyWith(
copiedRawPaymentRequest: text,
paymentRequest: null,
// Don't show exception if text field is clear
invalidBitcoinStringException: text.isNotEmpty
? InvalidBitcoinStringException()
: null,
),
);
if (recipientCleared) clearBitcoinFeePreviews();
}
}
Future<void> continueOnAddressConfirmed() async {
try {
emit(state.copyWith(loadingBestWallet: true, invoiceHasMrh: false));
await unifiedBip21Prioritization();
if (!state.hasValidPaymentRequest) {
emit(
state.copyWith(
loadingBestWallet: false,
invalidBitcoinStringException:
state.scannedRawPaymentRequest.isNotEmpty
? UnsupportedQrFormatException()
: InvalidBitcoinStringException(),
),
);
return;
}
if (state.paymentRequest!.isBolt11) {
final paymentRequest = state.paymentRequest! as Bolt11PaymentRequest;
final invoice = await _decodeInvoiceUsecase.execute(
invoice: paymentRequest.invoice,
);
if (invoice.isExpired) {
emit(
state.copyWith(
loadingBestWallet: false,
swapCreationException: ExpiredInvoiceException(),
),
);
return;
}
if (invoice.sats == 0) {
emit(
state.copyWith(
loadingBestWallet: false,
swapCreationException: AmountlessInvoiceException(
'Invoice has no amount',
),
),
);
return;
}
if (invoice.magicBip21 != null) {
final updatedRequest = await _detectBitcoinStringUsecase.execute(
data: invoice.magicBip21!,
);
emit(
state.copyWith(
// copiedRawPaymentRequest: invoice.toString(),
paymentRequest: updatedRequest,
invoiceHasMrh: true,
),
);
}
}
// [CHAIN SWAP LIFECYCLE — Step 1: trigger]
// SelectBestWalletUsecase picks a same-network wallet with sufficient
// funds first. A chain swap is only triggered when:
// (a) no same-network wallet has enough balance, so a wallet from the
// OTHER network is chosen (BTC <-> L-BTC), OR
// (b) the user explicitly pre-selected a different-network wallet via
// `_wallet`.
// The `state.isChainSwap` getter (see send_state.dart) flips true when
// selectedWallet.network does not match the payment request's network.
final wallet =
_wallet ??
_bestWalletUsecase.execute(
wallets: state.wallets,
request: state.paymentRequest!,
amountSat: state.paymentRequest!.amountSat,
);
final sendType = SendType.from(state.paymentRequest!);
// Pre-populate label from the embedded invoice description or BIP21 label
// if the user hasn't manually set one already.
final embeddedLabel = switch (state.paymentRequest!) {
Bolt11PaymentRequest(description: final d) when d.isNotEmpty => d,
Bip21PaymentRequest(label: final l) when l.isNotEmpty => l,
_ => null,
};
if (embeddedLabel != null && state.label.isEmpty) {
emit(state.copyWith(label: embeddedLabel));
}
await _setSelectedWallet(wallet, manual: false);
emit(state.copyWith(sendType: sendType));
await loadFees();
if (state.invoiceHasMrh) {
if (!await hasBalance()) {
emit(
state.copyWith(
insufficientBalanceException: InsufficientBalanceException(),
creatingSwap: false,
loadingBestWallet: false,
),
);
return;
}
//
emit(
state.copyWith(confirmedAmountSat: state.paymentRequest!.amountSat),
);
await handleChainSwap();
if (state.swapAmountAboveLimit ||
state.swapAmountBelowLimit ||
state.swapCreationException != null) {
return;
}
await createTransaction();
emit(
state.copyWith(
step: SendStep.confirm,
confirmedAmountSat: state.paymentRequest!.amountSat,
),
);
return;
}
if (state.paymentRequest!.isBolt11) {
emit(state.copyWith(creatingSwap: true));
if (!await hasBalance()) {
emit(
state.copyWith(
insufficientBalanceException: InsufficientBalanceException(),
creatingSwap: false,
loadingBestWallet: false,
),
);
return;
}
final swapType = wallet.isLiquid
? SwapType.liquidToLightning
: SwapType.bitcoinToLightning;
await loadSwapLimits();
setSelectedSwapLimits();
if (state.swapAmountBelowLimit) {
final swapMinimum = state.swapMinimum;
if (!state.selectedWallet!.isLiquid) {
emit(
state.copyWith(
creatingSwap: false,
swapLimitsException: SwapLimitsException(
'Amount is below swap limits of $swapMinimum sats.',
minLimit: swapMinimum,
suggestInstantPayments: true,
),
loadingBestWallet: false,
),
);
return;
} else {
emit(
state.copyWith(
creatingSwap: false,
swapLimitsException: SwapLimitsException(
'Amount is below swap limit of $swapMinimum sats.',
minLimit: swapMinimum,
),
loadingBestWallet: false,
),
);
}
return;
}
if (state.swapAmountAboveLimit) {
emit(
state.copyWith(
creatingSwap: false,
swapLimitsException: SwapLimitsException(
'Amount is above swap limits',
maxLimit: state.selectedSwapLimits?.max,
),
loadingBestWallet: false,
),
);
return;
}
try {
final paymentRequest = state.paymentRequest! as Bolt11PaymentRequest;
final swap = await _createSendSwapUsecase.execute(
walletId: wallet.id,
type: swapType,
invoice: paymentRequest.invoice,
);
emit(
state.copyWith(
step: SendStep.confirm,
lightningSwap: swap,
confirmedAmountSat: state.paymentRequest!.amountSat,
creatingSwap: false,
),
);
await createTransaction();
// updateSwapLockupFees();
return;
} catch (e) {
log.severe(
message: 'Failed to create swap',
error: e,
trace: StackTrace.current,
);
emit(
state.copyWith(
creatingSwap: false,
swapCreationException: SwapCreationException(
'Something went wrong. Please try again.',
),
loadingBestWallet: false,
),
);
return;
}
}
if (state.paymentRequest!.isBip21) {
if (state.paymentRequest!.amountSat == null) {
emit(state.copyWith(step: SendStep.amount, loadingBestWallet: false));
} else {
await handleChainSwap();
if (state.swapAmountAboveLimit ||
state.swapAmountBelowLimit ||
state.swapCreationException != null) {
return;
}
await createTransaction();
}
return;
}
if (state.paymentRequest!.isLnAddress) {
try {
final lnAddressPaymentRequest =
state.paymentRequest! as LnAddressPaymentRequest;
// Validate the LNURL by trying to create an invoice with a dummy amount
// This uses the same function that will be used when creating the actual swap
const dummyAmount = 1000; // 1000 sats dummy amount
await invoiceFromLnAddress(
lnAddress: lnAddressPaymentRequest.address,
amountSat: dummyAmount,
);
// If successful, proceed to amount step
emit(state.copyWith(step: SendStep.amount, loadingBestWallet: false));
} catch (e) {
// If LNURL validation fails, set error and stay on address step
emit(
state.copyWith(
loadingBestWallet: false,
invalidBitcoinStringException: InvalidBitcoinStringException(),
),
);
return;
}
} else {
emit(state.copyWith(step: SendStep.amount, loadingBestWallet: false));
return;
}
} catch (e) {
if (e is NotEnoughFundsException) {
emit(
state.copyWith(
loadingBestWallet: false,
insufficientBalanceException: InsufficientBalanceException(),
creatingSwap: false,
),
);
} else {
emit(
state.copyWith(
invalidBitcoinStringException: InvalidBitcoinStringException(
e.toString(),
),
loadingBestWallet: false,
creatingSwap: false,
),
);
}
}
}
// [CHAIN SWAP LIFECYCLE — Step 2: create the swap]
// Single chain-swap orchestration point. Runs to completion BEFORE the
// real funding tx is built. The sequence is:
// (a) If sendMax: drain to a dummy P2TR address (matching Boltz's
// P2TR lockup) to discover absolute fees and derive
// state.amount = balance - fees. See buildDummyTxsForMaxSwapAmount.
// (b) Load swap limits + fees, compute paymentAmount:
// - sendMax: paymentAmount = state.inputAmountSat
// (already balance - txFees from Step 2a; Boltz deducts its
// fees from this amount before paying the receiver).
// - otherwise: paymentAmount = receivable + boltz fees, so the
// receiver gets the exact requested amount.
// (c) Call createChainSwapToExternalUsecase → Boltz LOCKS IN
// swap.paymentAmount and swap.paymentAddress (P2TR lockup). From
// this point, the final funding tx MUST send exactly
// swap.paymentAmount to swap.paymentAddress.
// After this returns, createTransaction is invoked to build the funding tx.
Future<void> handleChainSwap() async {
final isChainSwap =
(state.sendType == SendType.liquid &&
!state.selectedWallet!.isLiquid) ||
state.sendType == SendType.bitcoin && state.selectedWallet!.isLiquid ||
state.isChainSwap;
if (isChainSwap) {
try {
if (state.sendMax) {
// [CHAIN SWAP LIFECYCLE — Step 2a: first drain (dummy address)]
// Computes fees against a dummy address. Result feeds state.amount,
// which becomes the swap paymentAmount below.
await buildDummyTxsForMaxSwapAmount();
}
final swapType = state.selectedWallet!.isLiquid
? SwapType.liquidToBitcoin
: SwapType.bitcoinToLiquid;
await loadSwapLimits();
setSelectedSwapLimits();
if (state.swapAmountBelowLimit) {
emit(
state.copyWith(
swapLimitsException: SwapLimitsException(
'Amount below minimum swap limit: ${state.selectedSwapLimits!.min} sats',
minLimit: state.selectedSwapLimits!.min,
),
amountConfirmedClicked: false,
),
);
return;
}
if (state.swapAmountAboveLimit) {
emit(
state.copyWith(
swapLimitsException: SwapLimitsException(
'Amount above maximum swap limit: ${state.selectedSwapLimits!.max} sats',
maxLimit: state.selectedSwapLimits!.max,
),
amountConfirmedClicked: false,
),
);
return;
}
emit(state.copyWith(creatingSwap: true));
final receivableAmount =
state.paymentRequest!.amountSat ?? state.inputAmountSat;
final swapFees = state.selectedSwapFees;
if (swapFees == null) {
emit(
state.copyWith(
creatingSwap: false,
swapCreationException: SwapCreationException(
'Swap fees not loaded',
),
loadingBestWallet: false,
),
);
return;
}
// For sendMax, state.inputAmountSat is already balance - txFees
// (set by buildDummyTxsForMaxSwapAmount). It IS the funding
// amount, not a receivable — Boltz deducts its fees from this
// before paying the receiver. Running it through
// calculateSwapAmountFromReceivableAmount would add boltz fees on
// top, over-quoting paymentAmount and tripping Step 3b. #1735.
final paymentAmount = state.sendMax
? state.inputAmountSat
: swapFees.calculateSwapAmountFromReceivableAmount(
receivableAmount,
);
// [CHAIN SWAP LIFECYCLE — Step 2c: commit paymentAmount]
// Boltz locks in the exact amount that must be paid to its lockup
// address. swap.paymentAmount and swap.paymentAddress are now fixed.
// Any deviation in the final funding tx will be rejected by
// VerifyChainSwapAmountSendUsecase (the fail-safe at Step 3b).
final swap = await _createChainSwapToExternalUsecase.execute(
sendWalletId: state.selectedWallet!.id,
receiveAddress: state.paymentRequest!.isBip21
? (state.paymentRequest! as Bip21PaymentRequest).address
: state.paymentRequestAddress,
type: swapType,
amountSat: paymentAmount,
);
_watchSendSwap(swap.id);
emit(
state.copyWith(
chainSwap: swap,
confirmedAmountSat: swap.paymentAmount,
creatingSwap: false,
),
);
} catch (e) {
emit(
state.copyWith(
creatingSwap: false,
swapCreationException: SwapCreationException(e.toString()),
loadingBestWallet: false,
),
);
return;
}
}
emit(
state.copyWith(
// Amountless external addresses carry no request amount; fall back to
// the entered amount so the confirm headline never flashes 0 sats
// before createTransaction settles it.
confirmedAmountSat:
state.paymentRequest!.amountSat ?? state.inputAmountSat,
step: SendStep.confirm,
loadingBestWallet: false,
),
);
}
Future<void> loadSwapLimits() async {
final paymentRequest = state.paymentRequest;
final loadLnSwapLimits =
paymentRequest?.isBolt11 == true || paymentRequest?.isLnAddress == true;
if (loadLnSwapLimits) {
final (
(liquidSwapLimits, liquidSwapFees),
(bitcoinSwapLimits, bitcoinSwapFees),
) = await (
_getSwapLimitsUsecase.execute(type: SwapType.liquidToLightning),
_getSwapLimitsUsecase.execute(type: SwapType.bitcoinToLightning),
).wait;
emit(
state.copyWith(
liquidLnSwapLimits: liquidSwapLimits,
liquidLnSwapFees: liquidSwapFees,
bitcoinLnSwapLimits: bitcoinSwapLimits,
bitcoinLnSwapFees: bitcoinSwapFees,
),
);
}
if (state.requireChainSwap) {
final (
(lbtcToBtcSwapLimits, lbtcToBtcSwapFees),
(btcToLbtcSwapLimits, btcToLbtcSwapFees),
) = await (
_getSwapLimitsUsecase.execute(type: SwapType.liquidToBitcoin),
_getSwapLimitsUsecase.execute(type: SwapType.bitcoinToLiquid),
).wait;
emit(
state.copyWith(
btcToLbtcChainSwapLimits: btcToLbtcSwapLimits,
btcToLbtcChainSwapFees: btcToLbtcSwapFees,
lbtcToBtcChainSwapLimits: lbtcToBtcSwapLimits,
lbtcToBtcChainSwapFees: lbtcToBtcSwapFees,
),
);
}
}
void setSelectedSwapLimits() {
if (state.selectedWallet == null) return;
final walletNetwork = state.selectedWallet!.network;
switch (walletNetwork) {
case Network.bitcoinMainnet:
case Network.bitcoinTestnet:
if (state.paymentRequest?.isBolt11 == true ||
state.paymentRequest?.isLnAddress == true) {
emit(
state.copyWith(
selectedSwapFees: state.bitcoinLnSwapFees,
selectedSwapLimits: state.bitcoinLnSwapLimits,
),
);
} else {
emit(
state.copyWith(
selectedSwapFees: state.btcToLbtcChainSwapFees,
selectedSwapLimits: state.btcToLbtcChainSwapLimits,
),
);
}
case Network.liquidMainnet:
case Network.liquidTestnet:
if (state.paymentRequest?.isBolt11 == true ||
state.paymentRequest?.isLnAddress == true) {
emit(
state.copyWith(
selectedSwapFees: state.liquidLnSwapFees,
selectedSwapLimits: state.liquidLnSwapLimits,
),
);
} else {
emit(
state.copyWith(
selectedSwapFees: state.lbtcToBtcChainSwapFees,
selectedSwapLimits: state.lbtcToBtcChainSwapLimits,
),
);
}
}
}
Future<bool> hasBalance() async {
if ((state.selectedWallet == null && state.paymentRequest == null) ||
state.paymentRequest == null) {
return false;
}
final paymentRequest = state.paymentRequest!;
// D7: frozen coins are never spendable, so every balance check compares
// against the spendable balance (wallet balance − frozen total), not the
// raw wallet balance. Degrades to the full balance on Liquid / before
// utxos load (nothing frozen there).
final spendableSat = state.spendableBalanceSat;
switch (paymentRequest) {
case Bolt11PaymentRequest _:
// final swapLimits = state.swapLimits!.;
final invoice = await _decodeInvoiceUsecase.execute(
invoice: state.paymentRequestAddress,
);
final invoiceAmount = invoice.sats;
final feeEstimate =
state.selectedSwapFees?.totalFees(invoiceAmount) ?? 0;
final totalPayable = invoiceAmount + feeEstimate;
return spendableSat > totalPayable;
case LnAddressPaymentRequest _:
final invoiceAmount = state.inputAmountSat;
final feeEstimate =
state.selectedSwapFees?.totalFees(invoiceAmount) ?? 0;
final totalPayable = invoiceAmount + feeEstimate;
return spendableSat > totalPayable;
default:
return spendableSat >=
(state.inputAmountSat + (state.absoluteFees ?? 0));
}
}
Future<void> getCurrencies() async {
final settings = await _getSettingsUsecase.execute();
final (exchangeRate, fiatCurrencies) = await (
_convertSatsToCurrencyAmountUsecase.execute(),
_getAvailableCurrenciesUsecase.execute(),
).wait;
final bitcoinUnit = settings.bitcoinUnit;
final fiatCurrency = settings.currencyCode;
emit(
state.copyWith(
fiatCurrencyCodes: fiatCurrencies,
fiatCurrencyCode: fiatCurrency,
exchangeRate: exchangeRate,
bitcoinUnit: bitcoinUnit,
inputAmountCurrencyCode: bitcoinUnit.code,
),
);
}
Future<void> amountChanged({String? amount, bool isMax = false}) async {
try {
clearAllExceptions();
String validatedAmount;
if (amount == null) {
if (!isMax) {
throw Exception('Amount should be provided if max is not selected');
}
// To avoid converting rounding errors when max is set, set the
// input currency to bitcoin unit if it was fiat
if (state.isInputAmountFiat) {
final bitcoinUnit = state.bitcoinUnit ?? BitcoinUnit.btc;
emit(state.copyWith(inputAmountCurrencyCode: bitcoinUnit.code));
}
// D7: Max drains only spendable coins (frozen are excluded at build),
// so the Max amount must reflect spendable balance, not the raw
// wallet balance — otherwise Max overshoots by the frozen total.
final spendableSat = state.spendableBalanceSat;
if (state.inputAmountCurrencyCode == BitcoinUnit.sats.code) {
validatedAmount = spendableSat.toString();
} else {
final spendableBtc = ConvertAmount.satsToBtc(spendableSat);
validatedAmount = spendableBtc.toStringAsFixed(8);
}
} else {
if (amount.isEmpty) {
validatedAmount = amount;
} else if (state.isInputAmountFiat) {
final amountFiat = double.tryParse(amount);
final isDecimalPoint = amount == '.';
validatedAmount = amountFiat == null && !isDecimalPoint
? state.amount
: amount;
} else if (state.inputAmountCurrencyCode == BitcoinUnit.sats.code) {
// If the amount is in sats, make sure it is a valid BigInt and do not
// allow a decimal point.
final amountSats = BigInt.tryParse(amount);
final hasDecimals = amount.contains('.');
validatedAmount =
amountSats == null ||
hasDecimals ||
amountSats > ConversionConstants.maxSatsAmount
? state.amount
: amountSats.toString();
} else {
// If the amount is in BTC, make sure it is a valid double and
// do not allow more than 8 decimal places.
final amountBtc = double.tryParse(amount);
final decimals = amount.split('.').last.length;
final isDecimalPoint = amount == '.';
validatedAmount =
(amountBtc == null && !isDecimalPoint) ||
decimals > BitcoinUnit.btc.decimals ||
(amountBtc != null &&
amountBtc >
ConversionConstants.maxBitcoinAmount.toDouble())
? state.amount
: amount;
}
}
final amountChanged =
state.amount != validatedAmount || state.sendMax != isMax;
emit(state.copyWith(amount: validatedAmount, sendMax: isMax));
// Amount is part of the cache fingerprint — any change invalidates
// every previously-built preview PSBT. Without this clear, the user
// can open the fee modal at amount A, change the amount to B
// without re-opening the modal, and `createTransaction` reads back
// a stale cached PSBT for A. Skip the clear when the validator
// bounced the input (validatedAmount == state.amount).
if (amountChanged) clearBitcoinFeePreviews();
// Don't update wallet when MAX is clicked to avoid changing network and triggering chain swaps
if (!isMax) {
await updateBestWallet();
}
} catch (e) {
emit(state.copyWith(error: e.toString()));
}
}
Future<void> onCurrencyChanged(String currencyCode) async {
double exchangeRate = state.exchangeRate;
String fiatCurrencyCode = state.fiatCurrencyCode;
if (![BitcoinUnit.btc.code, BitcoinUnit.sats.code].contains(currencyCode)) {
// If the currency is a fiat currency, retrieve the exchange rate and replace
// the current exchange rate and fiat currency code.
fiatCurrencyCode = currencyCode;
exchangeRate = await _convertSatsToCurrencyAmountUsecase.execute(
currencyCode: currencyCode,
);
} else {
// If the currency is a bitcoin unit, set the fiat currency and exchange
// rate back to the currency from the settings.
final currencyValues = await Future.wait([
_getSettingsUsecase.execute(),
_convertSatsToCurrencyAmountUsecase.execute(),
]);
fiatCurrencyCode = (currencyValues[0] as SettingsEntity).currencyCode;
exchangeRate = currencyValues[1] as double;
}
emit(
state.copyWith(
inputAmountCurrencyCode: currencyCode,
fiatCurrencyCode: fiatCurrencyCode,
exchangeRate: exchangeRate,
amount: '', // Clear the amount when changing the currency
),
);
}
Future<void> updateBestWallet() async {
if (state.paymentRequest == null || state.selectedWallet == null) return;
// Respect the user's manual wallet pick — auto-switching it silently
// can route funds from the wrong wallet (e.g. cold → hot). See #1918.
if (state.isWalletManuallySelected) return;
emit(state.copyWith(loadingBestWallet: true));
try {
final wallet =
_wallet ??
_bestWalletUsecase.execute(
wallets: state.wallets,
request: state.paymentRequest!,
amountSat: state.inputAmountSat,