-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathsend_state.dart
More file actions
531 lines (466 loc) · 16.7 KB
/
Copy pathsend_state.dart
File metadata and controls
531 lines (466 loc) · 16.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
import 'package:bb_mobile/core/errors/bull_exception.dart';
import 'package:bb_mobile/core/fees/domain/fees_entity.dart';
import 'package:bb_mobile/core/payjoin/domain/entity/payjoin.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/utils/amount_conversions.dart';
import 'package:bb_mobile/core/utils/amount_formatting.dart';
import 'package:bb_mobile/core/utils/payment_request.dart';
import 'package:bb_mobile/core/utils/percentage.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:freezed_annotation/freezed_annotation.dart';
part 'send_state.freezed.dart';
enum SendType {
bitcoin,
lightning,
liquid;
static SendType from(PaymentRequest paymentRequest) {
switch (paymentRequest) {
case ArkPaymentRequest():
throw UnimplementedError(
'ARK payment requests are available from experimental Ark feature only.',
);
case BitcoinPaymentRequest():
return SendType.bitcoin;
case LiquidPaymentRequest():
return SendType.liquid;
case Bolt11PaymentRequest():
case LnAddressPaymentRequest():
return SendType.lightning;
case Bip21PaymentRequest():
if (paymentRequest.network.isBitcoin) {
return SendType.bitcoin;
} else {
return SendType.liquid;
}
case PsbtPaymentRequest():
return SendType.bitcoin; //TODO(azad): nop
}
}
String get displayName {
switch (this) {
case SendType.bitcoin:
return 'Bitcoin';
case SendType.lightning:
return 'Lightning';
case SendType.liquid:
return 'Liquid';
}
}
}
enum SendStep { address, amount, confirm, sending, success }
@freezed
abstract class SendState with _$SendState {
const factory SendState({
@Default(SendStep.address) SendStep step,
@Default(SendType.lightning) SendType sendType,
@Default('') String scannedRawPaymentRequest,
@Default('') String copiedRawPaymentRequest,
PaymentRequest? paymentRequest,
@Default([]) List<Wallet> wallets,
Wallet? selectedWallet,
@Default(false) bool isWalletManuallySelected,
bool? isToSelf,
@Default('') String amount,
int? confirmedAmountSat,
BitcoinUnit? bitcoinUnit,
@Default([]) List<String> fiatCurrencyCodes,
@Default('CAD') String fiatCurrencyCode,
@Default('') String inputAmountCurrencyCode,
@Default(0) double exchangeRate,
@Default('') String label,
@Default([]) List<WalletUtxo> utxos,
@Default([]) List<WalletUtxo> selectedUtxos,
@Default(true) bool replaceByFee,
@Default(false) bool invoiceHasMrh,
FeeOptions? bitcoinFeesList,
FeeOptions? liquidFeesList,
NetworkFee? customFee,
@Default(FeeSelection.fastest) FeeSelection selectedFeeOption,
int? bitcoinTxSize,
int? liquidAbsoluteFees,
// prepare
String? unsignedPsbt,
String? signedBitcoinPsbt,
String? signedBitcoinTx,
String? signedLiquidTx,
LnSendSwap? lightningSwap,
ChainSwap? chainSwap,
// confirm
String? txId,
PayjoinSender? payjoinSender,
WalletTransaction? walletTransaction,
Object? error,
@Default(false) bool sendMax,
@Default(false) bool amountConfirmedClicked,
@Default(false) bool loadingBestWallet,
@Default(false) bool creatingSwap,
@Default(false) bool buildingTransaction,
@Default(false) bool signingTransaction,
@Default(false) bool broadcastingTransaction,
@Default('') String balanceApproximatedAmount,
SwapCreationException? swapCreationException,
InsufficientBalanceException? insufficientBalanceException,
InvalidBitcoinStringException? invalidBitcoinStringException,
SwapLimitsException? swapLimitsException,
BuildTransactionException? buildTransactionException,
ConfirmTransactionException? confirmTransactionException,
// swapLimits
SwapLimits? bitcoinLnSwapLimits,
SwapLimits? liquidLnSwapLimits,
SwapLimits? btcToLbtcChainSwapLimits,
SwapLimits? lbtcToBtcChainSwapLimits,
SwapLimits? selectedSwapLimits,
SwapFees? bitcoinLnSwapFees,
SwapFees? liquidLnSwapFees,
SwapFees? btcToLbtcChainSwapFees,
SwapFees? lbtcToBtcChainSwapFees,
SwapFees? selectedSwapFees,
}) = _SendState;
const SendState._();
List<String> get inputAmountCurrencyCodes {
return [BitcoinUnit.btc.code, BitcoinUnit.sats.code, ...fiatCurrencyCodes];
}
/// Whether we have a valid payment request
bool get hasValidPaymentRequest => paymentRequest != null;
String get paymentRequestAddress {
if (paymentRequest == null) {
return copiedRawPaymentRequest.isNotEmpty
? copiedRawPaymentRequest
: scannedRawPaymentRequest;
}
if (paymentRequest!.isBip21) {
if (invoiceHasMrh) {
// Return the raw string instead of the payment request
return copiedRawPaymentRequest.isNotEmpty
? copiedRawPaymentRequest
: scannedRawPaymentRequest;
}
final bip21PaymentRequest = paymentRequest! as Bip21PaymentRequest;
return bip21PaymentRequest.address;
}
if (paymentRequest!.isBolt11) {
final bolt11PaymentRequest = paymentRequest! as Bolt11PaymentRequest;
return bolt11PaymentRequest.invoice;
}
if (paymentRequest!.isLnAddress) {
final lnAddressPaymentRequest =
paymentRequest! as LnAddressPaymentRequest;
return lnAddressPaymentRequest.address;
}
if (paymentRequest!.isBitcoinAddress) {
final bitcoinPaymentRequest = paymentRequest! as BitcoinPaymentRequest;
return bitcoinPaymentRequest.address;
}
if (paymentRequest!.isLiquidAddress) {
final liquidPaymentRequest = paymentRequest! as LiquidPaymentRequest;
return liquidPaymentRequest.address;
}
return copiedRawPaymentRequest.isNotEmpty
? copiedRawPaymentRequest
: scannedRawPaymentRequest;
}
bool get isInputAmountFiat => ![
BitcoinUnit.btc.code,
BitcoinUnit.sats.code,
].contains(inputAmountCurrencyCode);
int get inputAmountSat {
int amountSat = 0;
if (amount.isNotEmpty) {
if (isInputAmountFiat) {
final amountFiat = double.tryParse(amount) ?? 0;
amountSat = ConvertAmount.fiatToSats(amountFiat, exchangeRate);
} else if (inputAmountCurrencyCode == BitcoinUnit.sats.code) {
amountSat = int.tryParse(amount) ?? 0;
} else {
final amountBtc = double.tryParse(amount) ?? 0;
amountSat = ConvertAmount.btcToSats(amountBtc);
}
}
return amountSat;
}
double get inputAmountBtc => ConvertAmount.satsToBtc(inputAmountSat);
double get inputAmountFiat {
return ConvertAmount.btcToFiat(inputAmountBtc, exchangeRate);
}
double get confirmedAmountBtc => confirmedAmountSat != null
? ConvertAmount.satsToBtc(confirmedAmountSat!)
: 0;
double get confirmedAmountFiat {
return ConvertAmount.btcToFiat(confirmedAmountBtc, exchangeRate);
}
double get confirmedSwapAmountBtc => lightningSwap != null
? ConvertAmount.satsToBtc(lightningSwap!.paymentAmount)
: 0;
String get formattedConfirmedAmountBitcoin {
if (bitcoinUnit == null) {
return '';
} else if (bitcoinUnit == BitcoinUnit.sats) {
return FormatAmount.sats(confirmedAmountSat ?? 0);
} else {
return FormatAmount.btc(confirmedAmountBtc);
}
}
String get formattedSwapAmountBitcoin {
if (bitcoinUnit == null || lightningSwap == null) return '';
if (bitcoinUnit == BitcoinUnit.sats) {
return FormatAmount.sats(lightningSwap!.paymentAmount);
} else {
return FormatAmount.btc(confirmedSwapAmountBtc);
}
}
String get formattedConfirmedAmountFiat {
return FormatAmount.fiat(confirmedAmountFiat, fiatCurrencyCode);
}
String get formattedAmountInputEquivalent {
if (isInputAmountFiat) {
// If the input is in fiat, the equivalent should be in bitcoin
if (bitcoinUnit == null) {
return '';
} else if (bitcoinUnit == BitcoinUnit.sats) {
return FormatAmount.sats(inputAmountSat);
} else {
return FormatAmount.btc(inputAmountBtc);
}
} else {
return FormatAmount.fiat(inputAmountFiat, fiatCurrencyCode);
}
}
String formattedWalletBalance() {
if (selectedWallet == null) return '0';
if (inputAmountCurrencyCode == BitcoinUnit.btc.code) {
return FormatAmount.btc(
ConvertAmount.satsToBtc(selectedWallet!.balanceSat.toInt()),
);
} else if (inputAmountCurrencyCode == BitcoinUnit.sats.code) {
return FormatAmount.sats(selectedWallet!.balanceSat.toInt());
} else {
return FormatAmount.fiat(
ConvertAmount.satsToFiat(
selectedWallet!.balanceSat.toInt(),
exchangeRate,
),
inputAmountCurrencyCode,
);
}
}
String formattedApproximateBalance() {
if (selectedWallet == null) return '0';
final satsBalance = selectedWallet!.balanceSat.toInt();
if (inputAmountCurrencyCode == BitcoinUnit.btc.code ||
inputAmountCurrencyCode == BitcoinUnit.sats.code) {
return FormatAmount.fiat(
ConvertAmount.satsToFiat(satsBalance, exchangeRate),
fiatCurrencyCode,
);
} else {
if (bitcoinUnit == BitcoinUnit.sats) {
return FormatAmount.sats(satsBalance);
} else {
return FormatAmount.btc(ConvertAmount.satsToBtc(satsBalance));
}
}
}
String get formattedAbsoluteFees {
if (absoluteFees == null) return '0';
if (bitcoinUnit == BitcoinUnit.sats) {
return FormatAmount.sats(absoluteFees!);
} else {
return FormatAmount.btc(ConvertAmount.satsToBtc(absoluteFees!));
}
}
bool get walletHasBalance =>
// ignore: avoid_bool_literals_in_conditional_expressions
selectedWallet == null
? false
: (inputAmountSat > 0 &&
inputAmountSat <= selectedWallet!.balanceSat.toInt());
String sendTypeName() {
switch (sendType) {
case SendType.bitcoin:
return 'Send';
case SendType.lightning:
return 'Swap';
case SendType.liquid:
return 'Send';
}
}
bool get isLightning => sendType == SendType.lightning;
bool get isLightningBitcoinSwap =>
isLightning && selectedWallet!.network.isBitcoin;
bool get swapAmountBelowLimit {
if (isLightning && inputAmountSat != 0) {
if (selectedSwapLimits == null) return false;
// Allow 100 sats minimum for Liquid to Lightning swaps
final isLiquidToLightning =
selectedWallet != null && selectedWallet!.isLiquid;
final minLimit = isLiquidToLightning ? 100 : selectedSwapLimits!.min;
return inputAmountSat < minLimit;
}
if (requireChainSwap && inputAmountSat != 0) {
return selectedSwapLimits != null &&
inputAmountSat < selectedSwapLimits!.min;
}
return false;
}
int get swapMinimum {
final min = selectedSwapLimits?.min ?? 0;
if (min != 0) return min;
return selectedWallet?.isLiquid == true ? 100 : 25000;
}
bool get swapAmountAboveLimit {
if (isLightning) {
return selectedSwapLimits != null &&
inputAmountSat > selectedSwapLimits!.max;
}
if (requireChainSwap && inputAmountSat != 0) {
return selectedSwapLimits != null &&
inputAmountSat > selectedSwapLimits!.max;
}
return false;
}
bool get isSwapAmountValid =>
isLightning ||
requireChainSwap &&
(selectedSwapLimits == null ||
inputAmountSat == 0 ||
swapAmountBelowLimit ||
swapAmountAboveLimit);
bool get isLnInvoicePaid {
return lightningSwap != null && lightningSwap!.status == SwapStatus.canCoop;
}
bool get isSwapCompleted {
return lightningSwap != null &&
lightningSwap!.status == SwapStatus.completed;
}
bool get disableConfirmSend =>
buildingTransaction || signingTransaction || broadcastingTransaction;
bool get blocksSwapDueToBitcoinHardwareWallet {
final wallet = selectedWallet;
if (wallet == null) return false;
final isSwap =
sendType == SendType.lightning ||
(sendType == SendType.liquid && !wallet.isLiquid) ||
(sendType == SendType.bitcoin && wallet.isLiquid);
return isSwap && wallet.isBitcoinHardwareWallet;
}
bool get requireChainSwap {
if (selectedWallet == null) return false;
return (selectedWallet!.network.isBitcoin && sendType == SendType.liquid) ||
(selectedWallet!.network.isLiquid && sendType == SendType.bitcoin);
}
NetworkFee? get selectedFee {
switch (selectedFeeOption) {
case FeeSelection.fastest:
return selectedWallet!.isLiquid
? liquidFeesList?.fastest
: bitcoinFeesList?.fastest;
case FeeSelection.economic:
return selectedWallet!.isLiquid
? liquidFeesList?.economic
: bitcoinFeesList?.economic;
case FeeSelection.slow:
return selectedWallet!.isLiquid
? liquidFeesList?.slow
: bitcoinFeesList?.slow;
case FeeSelection.custom:
return customFee;
}
}
bool get isChainSwap =>
(sendType == SendType.liquid && !selectedWallet!.isLiquid) ||
sendType == SendType.bitcoin && selectedWallet!.isLiquid;
FeeOptions? get feeOptions => selectedWallet == null
? null
: selectedWallet!.isLiquid
? liquidFeesList
: bitcoinFeesList;
int? get absoluteFees => selectedWallet == null
? null
: selectedWallet!.isLiquid
? liquidAbsoluteFees
: selectedFee?.toAbsolute(bitcoinTxSize ?? 0).value.toInt();
int? get totalSwapFees {
if (lightningSwap == null) return null;
return lightningSwap!.fees?.totalFees(lightningSwap!.paymentAmount) ?? 0;
}
bool get isSlowPayment =>
// ignore: avoid_bool_literals_in_conditional_expressions
selectedWallet == null
? false
// ignore: avoid_bool_literals_in_conditional_expressions
: selectedWallet!.isLiquid
? false
: true;
}
extension SendStateFeePercent on SendState {
double getFeeAsPercentOfAmount() {
if (lightningSwap != null) {
return lightningSwap!.getFeeAsPercentOfAmount();
}
if (chainSwap != null) {
return chainSwap!.getFeeAsPercentOfAmount();
}
final fee = absoluteFees ?? 0;
final amount = confirmedAmountSat ?? 0;
if (fee == 0 || amount == 0) return 0.0;
return calculatePercentage(amount, fee);
}
bool get showFeeWarning => getFeeAsPercentOfAmount() > 5.0;
}
class SwapCreationException extends BullException {
SwapCreationException(super.message);
}
class AmountlessInvoiceException extends SwapCreationException {
AmountlessInvoiceException(super.message);
}
class HardwareWalletSwapException extends SwapCreationException {
HardwareWalletSwapException()
: super('Hardware wallets cannot be used for swaps');
}
class ExpiredInvoiceException extends SwapCreationException {
ExpiredInvoiceException() : super('Expired invoice');
}
class InsufficientBalanceException extends BullException {
InsufficientBalanceException([
super.message = 'Not enough balance to cover this payment',
]);
}
class InvalidBitcoinStringException extends BullException {
InvalidBitcoinStringException([
super.message = 'Invalid Bitcoin Payment Address or Invoice',
]);
}
class UnsupportedQrFormatException extends InvalidBitcoinStringException {}
/// Exception for swap limit violations.
/// Stored in SendState with min/max limit values for localized error messages.
/// UI displays context-specific messages using sendErrorAmountBelowMinimum,
/// sendErrorAmountAboveMaximum, sendErrorBalanceTooLowForMinimum, etc.
class SwapLimitsException extends BullException {
SwapLimitsException(
super.message, {
this.minLimit,
this.maxLimit,
this.suggestInstantPayments = false,
});
final int? minLimit;
final int? maxLimit;
final bool suggestInstantPayments;
bool get isBelowMinimum => minLimit != null;
bool get isAboveMaximum => maxLimit != null;
}
/// Exception for transaction build failures.
/// Stored in SendState and displayed by UI using sendErrorBuildFailed.
/// The message parameter is for debugging/logging only.
class BuildTransactionException extends BullException {
BuildTransactionException(super.message);
}
/// Exception for transaction confirmation failures.
/// Stored in SendState and displayed by UI using sendErrorConfirmationFailed.
/// The message parameter is for debugging/logging only.
class ConfirmTransactionException extends BullException {
ConfirmTransactionException(super.message, {this.isBroadcastFailure = false});
final bool isBroadcastFailure;
}