-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathswap.dart
More file actions
557 lines (499 loc) · 17.5 KB
/
Copy pathswap.dart
File metadata and controls
557 lines (499 loc) · 17.5 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
import 'package:bb_mobile/core/settings/domain/settings_entity.dart';
import 'package:bb_mobile/core/utils/build_context_x.dart';
import 'package:bb_mobile/core/utils/constants.dart';
import 'package:bb_mobile/core/utils/percentage.dart';
import 'package:bb_mobile/core/utils/string_formatting.dart';
import 'package:bolt11_decoder/bolt11_decoder.dart';
import 'package:flutter/material.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'swap.freezed.dart';
enum SwapType {
lightningToBitcoin,
lightningToLiquid,
liquidToLightning,
bitcoinToLightning,
liquidToBitcoin,
bitcoinToLiquid,
}
extension SwapTypeX on SwapType {
bool get isReverse =>
this == SwapType.lightningToBitcoin || this == SwapType.lightningToLiquid;
bool get isSubmarine =>
this == SwapType.bitcoinToLightning || this == SwapType.liquidToLightning;
bool get isChain =>
this == SwapType.bitcoinToLiquid || this == SwapType.liquidToBitcoin;
}
enum SwapStatus {
pending,
paid,
claimable,
refundable,
canCoop,
completed,
refunded,
expired,
failed;
String displayName(BuildContext context) {
switch (this) {
case SwapStatus.pending:
return context.loc.coreSwapsStatusPending;
case SwapStatus.paid:
case SwapStatus.claimable:
case SwapStatus.refundable:
case SwapStatus.canCoop:
return context.loc.coreSwapsStatusInProgress;
case SwapStatus.completed:
return context.loc.coreSwapsStatusCompleted;
case SwapStatus.refunded:
return context.loc.coreSwapsStatusRefunded;
case SwapStatus.expired:
return context.loc.coreSwapsStatusExpired;
case SwapStatus.failed:
return context.loc.coreSwapsStatusFailed;
}
}
/// Done states: no further watcher action will ever run for this swap.
bool get isTerminal =>
this == SwapStatus.completed ||
this == SwapStatus.refunded ||
this == SwapStatus.expired ||
this == SwapStatus.failed;
}
@freezed
abstract class SwapFees with _$SwapFees {
const factory SwapFees({
double? boltzPercent,
int? boltzFee,
int? lockupFee,
int? claimFee,
int? refundFee,
int? serverNetworkFees,
}) = _SwapFees;
const SwapFees._();
int totalFees(int? amount) {
int total = 0;
// Always use percentage-based calculation for Boltz fees to ensure proper rounding
if (boltzPercent != null) {
final boltzFee = boltzFeeFromPercent(amount ?? 0);
total += boltzFee;
} else if (boltzFee != null) {
total += boltzFee!;
}
if (lockupFee != null) total += lockupFee!;
// The user's spend of the locked output is one leg: a claim on success or
// a refund on failure — never both. When the refund happened, its actual
// fee replaces the claim estimate.
if (refundFee != null) {
total += refundFee!;
} else if (claimFee != null) {
total += claimFee!;
}
if (serverNetworkFees != null) total += serverNetworkFees!;
return total;
}
int totalFeesMinusLockup(int? amount) {
return totalFees(amount) - (lockupFee ?? 0);
}
int boltzFeeFromPercent(int amount) {
if (boltzPercent == null) {
return 0;
}
return ((amount * boltzPercent!) / 100).ceil();
}
double boltzPercentFromFees(int amount) {
if (boltzFee == null) {
return 0;
}
return double.parse(((boltzFee! / amount) * 100).toStringAsFixed(2));
}
double totalFeeAsPercentOfAmount(int amount) {
final fees = totalFees(amount);
return calculatePercentage(amount, fees);
}
int calculateSwapAmountFromReceivableAmount(int receivableAmount) {
final claimFee = this.claimFee ?? 0;
final serverNetworkFees = this.serverNetworkFees ?? 0;
if (boltzPercent == null) {
final boltzFee = this.boltzFee ?? 0;
return receivableAmount + boltzFee + claimFee + serverNetworkFees;
}
final baseAmount = receivableAmount + claimFee + serverNetworkFees;
final rate = 1.0 - (boltzPercent! / 100.0);
int paymentAmount = (baseAmount / rate).ceil();
int calculatedReceivable =
paymentAmount -
boltzFeeFromPercent(paymentAmount) -
claimFee -
serverNetworkFees;
while (calculatedReceivable < receivableAmount) {
paymentAmount++;
calculatedReceivable =
paymentAmount -
boltzFeeFromPercent(paymentAmount) -
claimFee -
serverNetworkFees;
}
return paymentAmount;
}
}
@freezed
sealed class Swap with _$Swap {
const factory Swap.lnReceive({
required String id,
required int keyIndex,
required SwapType type,
required SwapStatus status,
required Environment environment,
required DateTime creationTime,
required String receiveWalletId,
required String invoice,
String? receiveAddress,
String? receiveTxid,
@Default(false) bool wasDirectPayment,
SwapFees? fees,
DateTime? completionTime,
// Reconstructed by the restore/rescue flow rather than created in-app.
//
// For a recovered swap the following are NOT trustworthy — they aren't in
// the Boltz restore response and weren't produced by our own creation flow
// — so the UI hides them rather than show a guess:
// - the counterpart wallet: the send/receive side the user did NOT pick is
// a default-of-chain guess (rescue only asks for one wallet);
// - `fees.lockupFee`: the original on-chain lockup tx fee (paid on the old
// device, unknowable here);
// - `fees.serverNetworkFees`: Boltz's server miner fee from the original
// quote (only a *current* estimate is fetchable, not what was paid).
//
// What IS trustworthy: the locked amount, the actual received amount
// (on-chain), the Boltz % service fee (the rate is stable, so we recompute
// it from the live fees), the claim we performed + its fee, status, dates.
// TODO: recover the uncertain fields accurately later — e.g. query Boltz
// for the historical swap, and read the original lockup tx fee on-chain.
@Default(false) bool recovered,
}) = LnReceiveSwap;
const factory Swap.lnSend({
required String id,
required int keyIndex,
required SwapType type,
required SwapStatus status,
required Environment environment,
required DateTime creationTime,
required String sendWalletId,
required String invoice,
required String paymentAddress,
required int paymentAmount,
String? sendTxid,
String? preimage,
String? refundAddress,
String? refundTxid,
SwapFees? fees,
DateTime? completionTime,
@Default(false) bool recovered,
}) = LnSendSwap;
const factory Swap.chain({
required String id,
required int keyIndex,
required SwapType type,
required SwapStatus status,
required Environment environment,
required DateTime creationTime,
required String sendWalletId,
required String paymentAddress,
required int paymentAmount,
String? sendTxid,
String? receiveWalletId,
String? receiveAddress,
String? receiveTxid,
String? refundAddress,
String? refundTxid,
SwapFees? fees,
DateTime? completionTime,
@Default(false) bool recovered,
}) = ChainSwap;
const Swap._();
bool get isLnReceiveSwap => this is LnReceiveSwap;
bool get isLnSendSwap => this is LnSendSwap;
bool get isChainSwap => this is ChainSwap;
bool get requiresAction => switch (this) {
LnReceiveSwap(:final status) => status == SwapStatus.claimable,
LnSendSwap(:final status) =>
status == SwapStatus.canCoop ||
status == SwapStatus.failed ||
status == SwapStatus.refundable,
ChainSwap(:final status) =>
status == SwapStatus.claimable || status == SwapStatus.refundable,
};
String? get txId => switch (this) {
LnReceiveSwap(:final receiveTxid) => receiveTxid,
LnSendSwap(:final sendTxid) => sendTxid,
ChainSwap(:final sendTxid) => sendTxid,
};
String get abbreviatedReceiveTxid => switch (this) {
final LnReceiveSwap swap => StringFormatting.truncateMiddle(
swap.receiveTxid ?? '',
),
final ChainSwap swap => StringFormatting.truncateMiddle(
swap.receiveTxid ?? '',
),
_ => '',
};
String get abbreviatedInvoice => switch (this) {
final LnReceiveSwap swap => StringFormatting.truncateMiddle(swap.invoice),
final LnSendSwap swap => StringFormatting.truncateMiddle(swap.invoice),
_ => '',
};
@override
String get id => switch (this) {
LnReceiveSwap(:final id) => id,
LnSendSwap(:final id) => id,
ChainSwap(:final id) => id,
};
@override
SwapType get type => switch (this) {
LnReceiveSwap(:final type) => type,
LnSendSwap(:final type) => type,
ChainSwap(:final type) => type,
};
@override
SwapStatus get status => switch (this) {
LnReceiveSwap(:final status) => status,
LnSendSwap(:final status) => status,
ChainSwap(:final status) => status,
};
@override
SwapFees? get fees => switch (this) {
LnReceiveSwap(:final fees) => fees,
LnSendSwap(:final fees) => fees,
ChainSwap(:final fees) => fees,
};
int get amountSat => switch (this) {
LnReceiveSwap(:final invoice) => _invoiceAmountSat(invoice),
LnSendSwap(:final invoice) => _invoiceAmountSat(invoice),
ChainSwap(:final paymentAmount) => paymentAmount,
};
// Restored/rescued LN swaps can carry an empty invoice (Boltz's restore
// response doesn't return it), so parse defensively instead of crashing the
// bolt11 bech32 decoder ("separator '1' at invalid position: -1").
static int _invoiceAmountSat(String invoice) {
if (invoice.isEmpty) return 0;
try {
// Exact conversion without package:decimal — the BTC amount as a
// rational, sats = numerator * 10^8 / denominator, truncated toward
// zero exactly like the previous Decimal.toBigInt() call.
final amount = Bolt11PaymentRequest(invoice).amount.toRational();
return ((amount.numerator * ConversionConstants.satsAmountOfOneBitcoin) ~/
amount.denominator)
.toInt();
} catch (_) {
return 0;
}
}
String? get sendTxId => switch (this) {
LnReceiveSwap() => null,
LnSendSwap(:final sendTxid) => sendTxid,
ChainSwap(:final sendTxid) => sendTxid,
};
String? get receiveTxId => switch (this) {
LnReceiveSwap(:final receiveTxid) => receiveTxid,
LnSendSwap() => null,
ChainSwap(:final receiveTxid) => receiveTxid,
};
String? get refundTxId => switch (this) {
LnReceiveSwap() => null,
LnSendSwap(:final refundTxid) => refundTxid,
ChainSwap(:final refundTxid) => refundTxid,
};
String get walletId => switch (this) {
LnReceiveSwap(:final receiveWalletId) => receiveWalletId,
LnSendSwap(:final sendWalletId) => sendWalletId,
ChainSwap(:final sendWalletId) => sendWalletId,
};
bool get swapInProgress =>
status == SwapStatus.paid ||
status == SwapStatus.canCoop ||
status == SwapStatus.claimable ||
status == SwapStatus.refundable;
bool get swapRefunded =>
status == SwapStatus.refunded ||
(status == SwapStatus.completed &&
((this is ChainSwap && (this as ChainSwap).refundTxid != null) ||
(this is LnSendSwap && (this as LnSendSwap).refundTxid != null)));
bool get isChainSwapInternal =>
this is ChainSwap && (this as ChainSwap).receiveWalletId != null;
bool get isChainSwapExternal =>
this is ChainSwap && (this as ChainSwap).receiveWalletId == null;
String swapAction(BuildContext context) => status == SwapStatus.claimable
? context.loc.coreSwapsActionClaim
: status == SwapStatus.canCoop
? context.loc.coreSwapsActionClose
: status == SwapStatus.refundable
? context.loc.coreSwapsActionRefund
: '';
bool get swapCompleted => status == SwapStatus.completed;
bool get isBitcoin =>
[
SwapType.bitcoinToLightning,
SwapType.lightningToBitcoin,
].contains(type) ||
(type == SwapType.liquidToBitcoin && isChainSwapInternal ||
type == SwapType.bitcoinToLiquid && !isChainSwapInternal);
bool get isLiquid => [
SwapType.liquidToLightning,
SwapType.lightningToLiquid,
SwapType.liquidToBitcoin,
SwapType.bitcoinToLiquid,
].contains(type);
String? get receiveAddress => switch (this) {
LnReceiveSwap(:final receiveAddress) => receiveAddress,
ChainSwap(:final receiveAddress) => receiveAddress,
_ => null,
};
int? get receieveAmount => switch (this) {
ChainSwap(:final paymentAmount, :final fees) => () {
if (fees == null) return null;
final totalSwapFees = fees.totalFeesMinusLockup(paymentAmount);
return paymentAmount - totalSwapFees;
}(),
LnSendSwap(:final paymentAmount, :final fees) => () {
if (fees == null) return null;
final totalSwapFees = fees.totalFeesMinusLockup(paymentAmount);
return paymentAmount - totalSwapFees;
}(),
LnReceiveSwap(:final invoice, :final fees) => () {
if (fees == null) return null;
final invoiceAmount = _invoiceAmountSat(invoice);
final totalFees = fees.totalFees(invoiceAmount);
return invoiceAmount - totalFees;
}(),
};
int? get sendAmount => switch (this) {
ChainSwap(:final paymentAmount, :final fees) => () {
if (fees == null) return null;
return paymentAmount;
}(),
LnSendSwap(:final paymentAmount, :final fees) => () {
if (fees == null) return null;
return paymentAmount;
}(),
LnReceiveSwap(:final invoice) => _invoiceAmountSat(invoice),
};
}
extension SwapFeePercent on Swap {
double getFeeAsPercentOfAmount() {
final fees = this.fees;
final amount = amountSat;
if (fees == null || amount == 0) return 0.0;
final totalFees = fees.totalFees(amount);
return calculatePercentage(amount, totalFees);
}
bool showFeeWarning() {
final feePercent = getFeeAsPercentOfAmount();
return feePercent > 5.0;
}
}
class SwapLimits {
final int min;
final int max;
const SwapLimits({required this.min, required this.max});
}
class Invoice {
final int sats;
final bool isExpired;
final String? magicBip21;
final String? description;
const Invoice({
required this.sats,
required this.isExpired,
this.magicBip21,
this.description,
});
}
extension SwapStatusMessage on Swap {
String getDisplayMessage(BuildContext context) {
if (isLnReceiveSwap) {
switch (status) {
case SwapStatus.pending:
return context.loc.coreSwapsLnReceivePending;
case SwapStatus.paid:
return context.loc.coreSwapsLnReceivePaid;
case SwapStatus.claimable:
return context.loc.coreSwapsLnReceiveClaimable;
case SwapStatus.refundable:
return context.loc.coreSwapsLnReceiveRefundable;
case SwapStatus.canCoop:
return context.loc.coreSwapsLnReceiveCanCoop;
case SwapStatus.completed:
return context.loc.coreSwapsLnReceiveCompleted;
case SwapStatus.refunded:
return context.loc.coreSwapsLnReceiveFailed;
case SwapStatus.expired:
return context.loc.coreSwapsLnReceiveExpired;
case SwapStatus.failed:
return context.loc.coreSwapsLnReceiveFailed;
}
} else if (isLnSendSwap) {
switch (status) {
case SwapStatus.pending:
return context.loc.coreSwapsLnSendPending;
case SwapStatus.paid:
return context.loc.coreSwapsLnSendPaid;
case SwapStatus.claimable:
return context.loc.coreSwapsLnSendClaimable;
case SwapStatus.refundable:
return context.loc.coreSwapsLnSendRefundable;
case SwapStatus.canCoop:
return context.loc.coreSwapsLnSendCanCoop;
case SwapStatus.completed:
final swap = this;
if (swap is LnSendSwap && swap.refundTxid != null) {
return context.loc.coreSwapsLnSendCompletedRefunded;
} else {
return context.loc.coreSwapsLnSendCompletedSuccess;
}
case SwapStatus.refunded:
return context.loc.coreSwapsLnSendCompletedRefunded;
case SwapStatus.expired:
return context.loc.coreSwapsLnSendExpired;
case SwapStatus.failed:
final swap = this;
if (swap is LnSendSwap && swap.sendTxid != null) {
return context.loc.coreSwapsLnSendFailedRefunding;
} else {
return context.loc.coreSwapsLnSendFailed;
}
}
} else if (isChainSwap) {
switch (status) {
case SwapStatus.pending:
return context.loc.coreSwapsChainPending;
case SwapStatus.paid:
return context.loc.coreSwapsChainPaid;
case SwapStatus.claimable:
return context.loc.coreSwapsChainClaimable;
case SwapStatus.refundable:
return context.loc.coreSwapsChainRefundable;
case SwapStatus.canCoop:
return context.loc.coreSwapsChainCanCoop;
case SwapStatus.completed:
final swap = this;
if (swap is ChainSwap && swap.refundTxid != null) {
return context.loc.coreSwapsChainCompletedRefunded;
} else {
return context.loc.coreSwapsChainCompletedSuccess;
}
case SwapStatus.refunded:
return context.loc.coreSwapsChainCompletedRefunded;
case SwapStatus.expired:
return context.loc.coreSwapsChainExpired;
case SwapStatus.failed:
final swap = this;
if (swap is ChainSwap && swap.sendTxid != null) {
return context.loc.coreSwapsChainFailedRefunding;
} else {
return context.loc.coreSwapsChainFailed;
}
}
}
return "";
}
}