Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 67 additions & 105 deletions bitwindow/lib/pages/wallet/wallet_send.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import 'dart:async';
import 'dart:io';
import 'dart:math';

import 'package:bitwindow/env.dart';
import 'package:bitwindow/main.dart';
Expand Down Expand Up @@ -286,15 +285,6 @@ bool isPaymentCode(String address) {
return decoded != null && decoded.checksumValid && decoded.versionByte == 0x47 && decoded.payload.length == 80;
}

/// What the send pays in total: the amounts, plus the fee unless the
/// recipient pays the fee out of the amount, plus a BIP47 notification.
int sendTotalSats({
required int amountSats,
required int feeSats,
required bool subtractFee,
int notificationSats = 0,
}) => (subtractFee ? amountSats : amountSats + feeSats) + notificationSats;

/// A sum of the send summary, or a dash while the fee of the form is unknown.
String summarySats(int? sats, String Function(int sats) format) => sats == null ? '–' : format(sats);

Expand Down Expand Up @@ -340,30 +330,15 @@ String payFromLabel(CoinSelectionStrategy strategy, List<UnspentOutput> selected
return '${selected.length} ${selected.length == 1 ? 'UTXO' : 'UTXOs'} · ${formatBitcoin(satoshiToBTC(total))}';
}

/// The outputs and the fee of a send, as graph lines. The recipient at
/// [feePayer] gets the amount less the fee; null adds the fee on top. Change is
/// what the coins hold above the payments and the fee. The fee payer keeps
/// change below dust. Without one, a priced fee already holds dropped change.
List<GraphLine> sendGraphCreates({
required List<({String address, int sats})> payments,
required int inputSats,
required int feeSats,
required String? feePayer,
}) {
final payer = payments.indexWhere((p) => p.address == feePayer);
final amounts = [
for (var i = 0; i < payments.length; i++) i == payer ? max(payments[i].sats - feeSats, 0) : payments[i].sats,
];
var change = inputSats - amounts.fold<int>(0, (sum, a) => sum + a) - feeSats;
if (payer >= 0 && change > 0 && change < dustSats) {
amounts[payer] += change;
change = 0;
}
/// The outputs and the fee of a previewed send, as graph lines. The payments
/// take the order of [addresses].
List<GraphLine> sendGraphCreates(wmpb.PreviewSendResponse preview, {required List<String> addresses}) {
final payments = preview.outputs.where((o) => !o.isChange).sortedBy<num>((o) => addresses.indexOf(o.address));
final change = preview.outputs.where((o) => o.isChange);
return [
for (var i = 0; i < payments.length; i++)
GraphLine(sats: amounts[i], address: payments[i].address, kind: FlowKind.payment),
if (change > 0) GraphLine(sats: change, address: '', kind: FlowKind.change),
if (feeSats > 0) GraphLine(sats: feeSats, address: '', kind: FlowKind.fee),
for (final o in payments) GraphLine(sats: o.amountSats.toInt(), address: o.address, kind: FlowKind.payment),
for (final o in change) GraphLine(sats: o.amountSats.toInt(), address: '', kind: FlowKind.change),
if (preview.feeSats > 0) GraphLine(sats: preview.feeSats.toInt(), address: '', kind: FlowKind.fee),
];
}

Expand Down Expand Up @@ -723,9 +698,7 @@ class SummaryCard extends ViewModelWidget<SendPageViewModel> {
),
SailDetailLine(
label: 'Fee amount',
value: viewModel.customFee
? fmt(viewModel.feeSats)
: summarySats(failed ? null : viewModel.feeSats, (sats) => '$estimate${fmt(sats)}'),
value: summarySats(failed ? null : viewModel.paidFeeSats, (sats) => '$estimate${fmt(sats)}'),
monospace: true,
),
if (notification > 0) SailDetailLine(label: 'BIP47 notification', value: fmt(notification), monospace: true),
Expand Down Expand Up @@ -1072,17 +1045,20 @@ class SendPageViewModel extends BaseViewModel {
String? _failedKey;
List<UnspentOutput> _pricedInputs = const [];
UnspentOutput? _pricedNotificationInput;
int _pricedFeeSats = 0;
int _pricedPaymentFeeSats = 0;
int _pricedNotificationFeeSats = 0;
bool _pricedIsEstimate = false;
wmpb.PreviewSendResponse? _priced;

/// True when the summary shows an estimate: a first BIP47 payment that can
/// spend the notification change, which no preview can build.
bool get feeIsEstimate => _formPreview?.feeIsEstimate ?? false;

/// True when the fee field shows an estimate: a first BIP47 payment from a
/// one-coin wallet pays from the notification change, which no preview can price.
bool get feeIsEstimate => _pricedIsEstimate && _currentFeePreviewKey() == _pricedKey;
/// The preview of the form as it is. Null while no preview priced it.
wmpb.PreviewSendResponse? get _formPreview {
final key = _currentFeePreviewKey();
return key != null && key == _pricedKey ? _priced : null;
}

/// True when the preview of this form failed, so the fee field holds no fee of this send.
bool get feeFailed => !customFee && _failedKey != null && _currentFeePreviewKey() == _failedKey;
/// True when the preview of this form failed, so no fee of this send is known.
bool get feeFailed => _failedKey != null && _currentFeePreviewKey() == _failedKey;
bool showTransactionGraph = false;

void toggleTransactionGraph() {
Expand All @@ -1100,21 +1076,19 @@ class SendPageViewModel extends BaseViewModel {

int get feeSats => feeController.text.isEmpty ? 0 : parseAmountToSatoshis(feeController.text, currentUnit);

int get totalSats {
if (!_pricedMatchesForm) {
return sendTotalSats(amountSats: amountSats, feeSats: feeSats, subtractFee: _subtractFeeFromAmount);
}
return sendTotalSats(
amountSats: amountSats,
feeSats: _pricedPaymentFeeSats,
subtractFee: _subtractFeeFromAmount,
notificationSats: _pricedNotificationFeeSats > 0 ? _pricedNotificationFeeSats + dustSats : 0,
);
}
/// What the payment pays as a fee. The fee of the BIP47 notification is not in it.
int get paidFeeSats => _formPreview?.feeSats.toInt() ?? feeSats;

int get totalSats => switch (_formPreview) {
final preview? => previewTotalSats(preview, amountSats: amountSats, subtractFee: _subtractFeeFromAmount),
null => _subtractFeeFromAmount ? amountSats : amountSats + feeSats,
};

/// What a first BIP47 payment pays for its notification: the fee and the dust output. 0 when the send has none.
int get notificationCostSats =>
_pricedMatchesForm && _pricedNotificationFeeSats > 0 ? _pricedNotificationFeeSats + dustSats : 0;
int get notificationCostSats => switch (_formPreview) {
final preview? => previewNotificationCostSats(preview),
null => 0,
};

int get balanceSats => btcToSatoshi(balanceProvider.balance);

Expand All @@ -1130,11 +1104,6 @@ class SendPageViewModel extends BaseViewModel {
}
}

bool get _pricedMatchesForm {
final key = _currentFeePreviewKey();
return key != null && key == _pricedKey && !_pricedIsEstimate;
}

/// The coins the send spends. The address comes from the wallet coin list.
List<GraphLine> get graphSpends {
final addresses = {for (final u in allUtxos) u.output: u.address};
Expand All @@ -1149,28 +1118,12 @@ class SendPageViewModel extends BaseViewModel {
];
}

/// The fee of the payment transaction alone. A BIP47 notification pays its
/// own fee from its own coin.
int get _graphFeeSats => _pricedMatchesForm ? _pricedPaymentFeeSats : feeSats;

List<GraphLine> get graphCreates {
final spends = graphSpends;
if (spends.isEmpty) {
final preview = _formPreview;
if (preview == null || preview.outputs.isEmpty) {
return const [];
}
final payments = <String, int>{};
for (final r in recipients) {
if (r.amountController.text.isNotEmpty) {
final address = r.address;
payments[address] = (payments[address] ?? 0) + parseAmountToSatoshis(r.amountController.text, currentUnit);
}
}
return sendGraphCreates(
payments: [for (final e in payments.entries) (address: e.key, sats: e.value)],
inputSats: spends.fold(0, (sum, l) => sum + l.sats),
feeSats: _graphFeeSats,
feePayer: _feePayer?.address,
);
return sendGraphCreates(preview, addresses: recipients.map((r) => r.address).toList());
}

String? sendError;
Expand Down Expand Up @@ -1512,7 +1465,7 @@ class SendPageViewModel extends BaseViewModel {
setBusy(false);
return;
}
if (!await _confirmFeeIsPriced(feeSats)) {
if (!await _confirmFeeIsPriced()) {
setBusy(false);
return;
}
Expand Down Expand Up @@ -1650,7 +1603,7 @@ class SendPageViewModel extends BaseViewModel {
setSendError('Please enter a valid fee.');
return null;
}
if (!await _confirmFeeIsPriced(feeSats)) {
if (!await _confirmFeeIsPriced()) {
return null;
}

Expand Down Expand Up @@ -1869,17 +1822,26 @@ class SendPageViewModel extends BaseViewModel {
}
}

/// The fee fields of a preview. Null while the form has no fee to price.
({double? feeRateSatPerVbyte, int? fixedFeeSats})? get _previewFeeFields {
if (customFee ? feeSats <= 0 : _estimatedSatPerVByte == null) {
return null;
}
return sendFee(estimatedSatPerVByte: estimatedSatPerVByte, typedFeeSats: feeSats);
}

String? _currentFeePreviewKey() {
final walletId = _walletReader.activeWalletId;
final rate = _feeRateSatPerVbyte;
final fee = _previewFeeFields;
final destinations = _destinationsWith();
if (walletId == null || rate == null || destinations == null) {
if (walletId == null || fee == null || destinations == null) {
return null;
}
return feePreviewKey(
walletId: walletId,
destinations: destinations,
feeRateSatPerVbyte: rate,
feeRateSatPerVbyte: fee.feeRateSatPerVbyte,
fixedFeeSats: fee.fixedFeeSats,
subtractFeeFromAmount: _subtractFeeFromAmount,
subtractFeeFrom: _feePayerAddress,
requiredOutpoints: selectedUtxos.map((u) => u.output),
Expand All @@ -1890,8 +1852,7 @@ class SendPageViewModel extends BaseViewModel {
}

/// The coin the BIP47 notification of the priced send spends.
UnspentOutput? get _sendNotificationInput =>
_currentFeePreviewKey() != null && _currentFeePreviewKey() == _pricedKey ? _pricedNotificationInput : null;
UnspentOutput? get _sendNotificationInput => _formPreview == null ? null : _pricedNotificationInput;

List<UnspentOutput> get _sendInputs => sendInputs(
selected: selectedUtxos,
Expand Down Expand Up @@ -1923,15 +1884,17 @@ class SendPageViewModel extends BaseViewModel {
);
}

/// Prices the form, which [key] identifies, and puts the fee in the fee field.
/// Prices the form, which [key] identifies. The fee of a fee target goes in the fee field.
/// A failure shows when the form stayed the same for [feePreviewErrorDelay],
/// or at once when [errorNow] is set.
Future<void> _previewFee(String key, {bool errorNow = false}) async {
final fee = _previewFeeFields!;
try {
final preview = await _orchestratorWallet.previewSend(
walletId: _walletReader.activeWalletId!,
destinations: _destinationsWith()!,
feeRateSatPerVbyte: _feeRateSatPerVbyte!,
feeRateSatPerVbyte: fee.feeRateSatPerVbyte,
fixedFeeSats: fee.fixedFeeSats,
subtractFeeFromAmount: _subtractFeeFromAmount,
subtractFeeFromAddress: _feePayerAddress,
requiredInputs: selectedUtxos,
Expand All @@ -1946,11 +1909,11 @@ class SendPageViewModel extends BaseViewModel {
_pricedKey = key;
_pricedInputs = preview.inputs.map(coin).toList();
_pricedNotificationInput = preview.hasNotificationInput() ? coin(preview.notificationInput) : null;
_pricedFeeSats = previewFeeSats(preview);
_pricedPaymentFeeSats = preview.feeSats.toInt();
_pricedNotificationFeeSats = preview.notificationFeeSats.toInt();
_pricedIsEstimate = preview.feeIsEstimate;
_setFeeFromSats(_pricedFeeSats);
_priced = preview;
if (!customFee) {
_setFeeFromSats(preview.feeSats.toInt());
}
notifyListeners();
} catch (error) {
if (disposed || key != _feePreviewKey) {
return;
Expand All @@ -1972,23 +1935,22 @@ class SendPageViewModel extends BaseViewModel {
}
}

/// Prices the form now when the fee field does not show the fee of this send.
/// False when the fee changed or the preview failed. The page shows why.
Future<bool> _confirmFeeIsPriced(int shownFeeSats) async {
/// Prices the form now when no preview priced it. False when the cost of the
/// send changed or the preview failed. The page shows why.
Future<bool> _confirmFeeIsPriced() async {
final key = _currentFeePreviewKey();
if (key == null || (key == _pricedKey && (_pricedIsEstimate || shownFeeSats == _pricedFeeSats))) {
if (key == null || key == _pricedKey) {
return true;
}
({int fee, int total}) shown() => (fee: paidFeeSats, total: totalSats);
final before = shown();
_feePreviewKey = key;
_feePreviewKeyAt = DateTime.now();
await _previewFee(key, errorNow: true);
if (_pricedKey != key) {
return false;
}
if (_pricedIsEstimate) {
return true;
}
if (parseAmountToSatoshis(feeController.text, currentUnit) != shownFeeSats) {
if (shown() != before) {
setSendError('The fee changed. Check the new fee and send again.');
return false;
}
Expand Down Expand Up @@ -2039,7 +2001,7 @@ class SendPageViewModel extends BaseViewModel {
final key = _currentFeePreviewKey();
_setFeeFromSats(
key != null && key == _pricedKey
? _pricedFeeSats
? _priced!.feeSats.toInt()
: feeSatsForRate(satPerVByte: satPerVByte, txVBytes: _estimatedTxVBytes),
);
}
Expand Down
24 changes: 20 additions & 4 deletions bitwindow/lib/utils/fee_estimation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ Map<String, int>? sendDestinations(Iterable<({String address, int sats})> recipi
String feePreviewKey({
required String walletId,
required Map<String, int> destinations,
required double feeRateSatPerVbyte,
required double? feeRateSatPerVbyte,
required int? fixedFeeSats,
required bool subtractFeeFromAmount,
String subtractFeeFrom = '',
required Iterable<String> requiredOutpoints,
Expand All @@ -86,6 +87,7 @@ String feePreviewKey({
walletId,
coinOrder.value,
feeRateSatPerVbyte,
fixedFeeSats,
subtractFeeFromAmount,
subtractFeeFrom,
sorted(destinations.entries.map((e) => '${e.key}=${e.value}')),
Expand Down Expand Up @@ -123,9 +125,23 @@ List<T> graphInputs<T>({
return pricedInputs;
}

/// The fees of a previewed send: the payment, and the BIP47 notification a
/// first payment publishes before it.
int previewFeeSats(PreviewSendResponse preview) => preview.feeSats.toInt() + preview.notificationFeeSats.toInt();
/// What a first BIP47 payment pays for its notification: the fee and the dust
/// output. 0 when the send has none.
int previewNotificationCostSats(PreviewSendResponse preview) {
final feeSats = preview.notificationFeeSats.toInt();
return feeSats > 0 ? feeSats + dustSats : 0;
}

/// What a previewed send takes from the wallet: the payments, the fee and the
/// BIP47 notification. An estimate has no outputs, so [amountSats] stands for
/// its payments.
int previewTotalSats(PreviewSendResponse preview, {required int amountSats, required bool subtractFee}) {
final feeSats = preview.feeSats.toInt();
final paidSats = preview.outputs.isEmpty
? (subtractFee ? amountSats : amountSats + feeSats)
: preview.outputs.where((o) => !o.isChange).fold(0, (sum, o) => sum + o.amountSats.toInt()) + feeSats;
return paidSats + previewNotificationCostSats(preview);
}

/// The mark before an estimated fee, in the style of the other cost estimates.
String? approximateFeePrefix(bool feeIsEstimate) => feeIsEstimate ? '≈ ' : null;
Expand Down
Loading
Loading