Skip to content
Open
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
ce714a4
feat: add BOLT-11 invoice prefix parser for amount validation
AndreaDiazCorreia Aug 21, 2026
971dcc3
fix(invoice): block payment when invoice terms disagree with the order
AndreaDiazCorreia Aug 21, 2026
d89cc1f
feat(invoice): anchor seller hold invoice to signed order amount and …
AndreaDiazCorreia Aug 21, 2026
656cef0
feat(invoice): block buyer payout when invoice request disagrees with…
AndreaDiazCorreia Aug 21, 2026
e7d5490
fix(invoice): follow info event stream to prevent stale fee rate reads
AndreaDiazCorreia Aug 24, 2026
fb5a9c4
fix(invoice): show the invoice amount in the manual payment flow
AndreaDiazCorreia Aug 24, 2026
a54fd45
feat(invoice): say when a settlement could not be checked
AndreaDiazCorreia Aug 24, 2026
883c69a
feat(invoice): hold a settlement to the terms pinned at commitment
AndreaDiazCorreia Aug 24, 2026
431aeb6
feat(invoice): re-price market orders against an independent rate
AndreaDiazCorreia Aug 24, 2026
0c35d7c
test(invoice): cover the settlement gating on both invoice screens
AndreaDiazCorreia Aug 24, 2026
3ae7036
fix(invoice): keep a fee unavailable at commitment from becoming a term
AndreaDiazCorreia Aug 24, 2026
dfedb47
fix(invoice): pin the fee rate on range remainder sessions
AndreaDiazCorreia Aug 24, 2026
c2414f3
fix(invoice): await cancellation before leaving the payment screen
AndreaDiazCorreia Aug 24, 2026
315e581
feat(invoice): refuse a settlement that runs off market against the user
AndreaDiazCorreia Aug 24, 2026
1f7a877
fix(invoice): record that pinning ran instead of inferring it
AndreaDiazCorreia Aug 24, 2026
aa58196
fix(invoice): do not quote an unreadable premium as zero
AndreaDiazCorreia Aug 24, 2026
d4a3323
fix(invoice): stop sending an amount NIP-47 wallets may refuse
AndreaDiazCorreia Aug 25, 2026
65fe829
fix(invoice): leave pre-pinning sessions out of the market check
AndreaDiazCorreia Aug 25, 2026
40270fd
fix(invoice): refuse a fee rate that leaves the arithmetic's domain
AndreaDiazCorreia Aug 25, 2026
8b5dac2
fix(invoice): bind the market override to the quote it was given for
AndreaDiazCorreia Aug 25, 2026
6f550dd
fix(invoice): tell the market check's four outcomes apart
AndreaDiazCorreia Aug 25, 2026
51eb490
fix(invoice): durably pin every term the settlement is checked against
AndreaDiazCorreia Aug 25, 2026
4e01319
fix(invoice): stop refusing settlements the check has nothing against
AndreaDiazCorreia Aug 25, 2026
f54d219
fix(invoice): keep the market check from flapping, and its anchors in…
AndreaDiazCorreia Aug 25, 2026
bb1904b
fix(invoice): fail closed when the settlement terms cannot be stored
AndreaDiazCorreia Aug 25, 2026
1400b6c
Merge remote-tracking branch 'origin/main' into fix/bind-invoice-amou…
AndreaDiazCorreia Aug 25, 2026
2e1a3c1
fix(invoice): check the payout invoice against the order's signed ter…
AndreaDiazCorreia Aug 25, 2026
606e9b9
fix(invoice): do not let a range remainder's anchor block a release
AndreaDiazCorreia Aug 25, 2026
914438d
fix(l10n): standardize Spanish imperative forms to formal second person
AndreaDiazCorreia Aug 27, 2026
a15c227
fix(order): fetch node info event before the order book to pin fee ra…
AndreaDiazCorreia Aug 27, 2026
98e7c8c
fix(order): cap the book subscription at 1000 events to bound startup…
AndreaDiazCorreia Aug 27, 2026
030d7b1
fix(invoice): compare late-arriving fee rates against the commitment …
AndreaDiazCorreia Aug 27, 2026
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
55 changes: 55 additions & 0 deletions lib/data/models/session.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,24 @@ class Session {
NostrKeyPairs? _adminSharedKey;
String? disputeId;

/// The order amount in satoshis as it stood when this session committed to
/// the trade, or null when there was no resolved figure to pin.
///
/// The settlement checks derive what a payment should be from the node's
/// kind-38383 order event and kind-38385 info event, both of which are
/// addressable and can be republished after the fact. Pinning the figures
/// the user actually agreed to holds the check to those terms rather than
/// to whatever the node last said.
///
/// Null for a market-price or range order, whose sats figure the node only
/// resolves after the take — there is nothing to pin at the moment of
/// commitment, and those orders fall back to the live events.
int? pinnedAmountSats;

/// The node's fee rate when this session committed, on the same terms as
/// [pinnedAmountSats].
double? pinnedFeeRate;

/// Transient marker (never persisted): set while a maker-created order is in
/// the anti-abuse bond limbo, so the shared pay-bond handler skips persisting
/// the still-uncommitted session. Cleared and persisted on confirmation.
Expand All @@ -38,9 +56,23 @@ class Session {
this.parentOrderId,
this.role,
this.disputeId,
int? pinnedAmountSats,
double? pinnedFeeRate,
Peer? peer,
String? adminPubkey,
}) {
// Normalized here rather than at each reader: a figure that cannot anchor
// anything is the same as no figure, and the checks that consult these
// fields have to agree on which is which.
this.pinnedAmountSats =
(pinnedAmountSats != null && pinnedAmountSats > 0)
? pinnedAmountSats
: null;
this.pinnedFeeRate =
(pinnedFeeRate != null && pinnedFeeRate >= 0 && pinnedFeeRate.isFinite)
? pinnedFeeRate
: null;

_peer = peer;
if (peer != null) {
_sharedKey = NostrUtils.computeSharedKey(
Expand All @@ -64,6 +96,8 @@ class Session {
'peer': peer?.publicKey,
'admin_peer': _adminPubkey,
'dispute_id': disputeId,
'pinned_amount_sats': pinnedAmountSats,
'pinned_fee_rate': pinnedFeeRate,
};

factory Session.fromJson(Map<String, dynamic> json) {
Expand Down Expand Up @@ -181,6 +215,25 @@ class Session {
disputeId = disputeIdValue;
}

// Absent in sessions written before the terms were pinned, so a missing
// or unusable value reads as "nothing was pinned" rather than an error:
// those trades fall back to the live events, as they always did.
final pinnedAmountValue = json['pinned_amount_sats'];
int? pinnedAmountSats;
if (pinnedAmountValue is int) {
pinnedAmountSats = pinnedAmountValue;
} else if (pinnedAmountValue is String) {
pinnedAmountSats = int.tryParse(pinnedAmountValue);
}

final pinnedFeeValue = json['pinned_fee_rate'];
double? pinnedFeeRate;
if (pinnedFeeValue is num) {
pinnedFeeRate = pinnedFeeValue.toDouble();
} else if (pinnedFeeValue is String) {
pinnedFeeRate = double.tryParse(pinnedFeeValue);
}

return Session(
masterKey: masterKeyValue,
tradeKey: tradeKeyValue,
Expand All @@ -193,6 +246,8 @@ class Session {
peer: peer,
adminPubkey: adminPubkey,
disputeId: disputeId,
pinnedAmountSats: pinnedAmountSats,
pinnedFeeRate: pinnedFeeRate,
);
} catch (e) {
throw FormatException('Failed to parse Session from JSON: $e');
Expand Down
7 changes: 7 additions & 0 deletions lib/features/order/notifiers/add_order_notifier.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import 'package:mostro_mobile/features/order/providers/order_notifier_provider.d
import 'package:mostro_mobile/features/order/models/order_state.dart';
import 'package:mostro_mobile/services/logger_service.dart';
import 'package:mostro_mobile/services/mostro_service.dart';
import 'package:mostro_mobile/features/order/providers/settlement_anchor_provider.dart';

class AddOrderNotifier extends AbstractMostroNotifier {
late final MostroService mostroService;
Expand Down Expand Up @@ -114,9 +115,15 @@ class AddOrderNotifier extends AbstractMostroNotifier {
// reset runs, and if a restore is in progress we block until it releases.
await ref.read(sessionLifecycleLockProvider).withSessionLock(() async {
final sessionNotifier = ref.read(sessionNotifierProvider.notifier);
// Pin the terms this order is being created on. The maker's own figure
// is the agreement here, so it is the one the settlement is later held
// to rather than whatever the node ends up publishing. A market-price
// or range order carries no sats amount to pin.
session = await sessionNotifier.newSession(
requestId: requestId,
role: order.kind == OrderType.buy ? Role.buyer : Role.seller,
pinnedAmountSats: order.amount > 0 ? order.amount : null,
pinnedFeeRate: ref.read(nodeFeeRateProvider),
);

// Start 10s timeout cleanup timer for create orders
Expand Down
17 changes: 17 additions & 0 deletions lib/features/order/notifiers/order_notifier.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:mostro_mobile/features/order/models/order_state.dart';
import 'package:mostro_mobile/features/notifications/providers/notifications_provider.dart';
import 'package:mostro_mobile/shared/providers.dart';
import 'package:mostro_mobile/features/order/notifiers/abstract_mostro_notifier.dart';
import 'package:mostro_mobile/features/order/providers/settlement_anchor_provider.dart';
import 'package:mostro_mobile/services/logger_service.dart';
import 'package:mostro_mobile/services/mostro_service.dart';

Expand Down Expand Up @@ -91,9 +92,17 @@ class OrderNotifier extends AbstractMostroNotifier {
// restore (TOCTOU-safe). See [SessionLifecycleLock].
await ref.read(sessionLifecycleLockProvider).withSessionLock(() async {
final sessionNotifier = ref.read(sessionNotifierProvider.notifier);
// Pin the terms being agreed to. Both inputs come from addressable
// events the node can republish, so reading them again later would let
// it move the figure this trade is checked against after the fact.
final pinnedAmountSats = ref.read(publishedOrderAmountProvider(orderId));
final pinnedFeeRate = ref.read(nodeFeeRateProvider);
Comment thread
AndreaDiazCorreia marked this conversation as resolved.

session = await sessionNotifier.newSession(
orderId: orderId,
role: Role.buyer,
pinnedAmountSats: pinnedAmountSats,
pinnedFeeRate: pinnedFeeRate,
);

// Drop any stale grace timer/flag from a previous cycle on this order so
Expand All @@ -117,9 +126,17 @@ class OrderNotifier extends AbstractMostroNotifier {
// restore (TOCTOU-safe). See [SessionLifecycleLock].
await ref.read(sessionLifecycleLockProvider).withSessionLock(() async {
final sessionNotifier = ref.read(sessionNotifierProvider.notifier);
// Pin the terms being agreed to. Both inputs come from addressable
// events the node can republish, so reading them again later would let
// it move the figure this trade is checked against after the fact.
final pinnedAmountSats = ref.read(publishedOrderAmountProvider(orderId));
final pinnedFeeRate = ref.read(nodeFeeRateProvider);

session = await sessionNotifier.newSession(
orderId: orderId,
role: Role.seller,
pinnedAmountSats: pinnedAmountSats,
pinnedFeeRate: pinnedFeeRate,
);

// Drop any stale grace timer/flag from a previous cycle on this order so
Expand Down
81 changes: 81 additions & 0 deletions lib/features/order/providers/market_check_provider.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mostro_mobile/data/models/nostr_event.dart';
import 'package:mostro_mobile/features/order/providers/settlement_anchor_provider.dart';
import 'package:mostro_mobile/services/exchange_service.dart';
import 'package:mostro_mobile/services/logger_service.dart';
import 'package:mostro_mobile/services/yadio_exchange_service.dart';
import 'package:mostro_mobile/shared/providers/order_repository_provider.dart';
import 'package:mostro_mobile/shared/providers/session_notifier_provider.dart';
import 'package:mostro_mobile/shared/utils/market_quote.dart';

/// A bitcoin price from a source the connected node does not control.
///
/// Deliberately not [exchangeServiceProvider], which asks the node first: it
/// reads the node's own kind-30078 rates event and only falls back to Yadio if
/// that fails. That is the right order for pricing an order the user is
/// composing, and the wrong one for checking the node's arithmetic — a node
/// that skims a settlement can publish the rate that makes the skim look
/// correct.
final independentExchangeServiceProvider = Provider<ExchangeService>(
(ref) => YadioExchangeService(),
);

/// Fiat units per bitcoin for [fiatCode], from the independent source.
///
/// Null rather than an error when the rate cannot be had: this check is a
/// second opinion, and being offline is not evidence against a settlement.
final independentFiatPerBtcProvider =
Comment thread
AndreaDiazCorreia marked this conversation as resolved.
FutureProvider.family<double?, String>((ref, fiatCode) async {
if (fiatCode.isEmpty) return null;

try {
final service = ref.watch(independentExchangeServiceProvider);
return await service.getExchangeRate(fiatCode, 'BTC');
} catch (e) {
logger.w('Independent rate for $fiatCode unavailable: $e');
return null;
}
});

/// Re-prices [orderId] against the independent rate, or null when the check
/// does not apply or cannot be made.
///
/// Only runs where the client holds no figure of its own. A session that
/// pinned the sats amount at commitment is already held to what the user saw
/// on the take screen, and re-pricing it would only second-guess a number
/// they accepted with their eyes open: a fixed-amount order may sit off the
/// market on purpose. What is left is the market-price and range orders,
/// whose sats the node resolved after the commitment, and sessions from
/// before the pin existed.
final marketCheckProvider =
Provider.family<MarketCheck?, String>((ref, orderId) {
final session = ref.watch(sessionProvider(orderId));
if (session?.pinnedAmountSats != null) return null;

final settledSats = ref.watch(signedOrderAmountProvider(orderId));
if (settledSats == null) return null;

final event = ref.watch(eventProvider(orderId));
Comment thread
AndreaDiazCorreia marked this conversation as resolved.
Outdated
if (event == null) return null;

final fiatCode = event.currency;
if (fiatCode == null || fiatCode.isEmpty) return null;

// A range order still advertising its band has not been resolved to the one
// fiat figure this trade is for, so there is nothing to re-price yet.
final fiat = event.fiatAmount;
if (fiat.isRange() || fiat.minimum <= 0) return null;

final premium = double.tryParse(event.premium ?? '') ?? 0.0;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated

final fiatPerBtc =
ref.watch(independentFiatPerBtcProvider(fiatCode)).valueOrNull;
if (fiatPerBtc == null) return null;

return MarketCheck.of(
settledSats: settledSats,
fiatAmount: fiat.minimum,
fiatPerBtc: fiatPerBtc,
premium: premium,
);
Comment thread
AndreaDiazCorreia marked this conversation as resolved.
});
139 changes: 139 additions & 0 deletions lib/features/order/providers/settlement_anchor_provider.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mostro_mobile/data/models/nostr_event.dart';
import 'package:mostro_mobile/features/mostro/mostro_instance.dart';
import 'package:mostro_mobile/features/settings/settings_provider.dart';
import 'package:mostro_mobile/services/logger_service.dart';
import 'package:mostro_mobile/shared/providers/order_repository_provider.dart';
import 'package:mostro_mobile/shared/providers/session_notifier_provider.dart';
import 'package:mostro_mobile/shared/utils/settlement_amounts.dart';

/// The order amount the node currently publishes for [orderId], in satoshis.
///
/// Read off the kind-38383 order event rather than the direct message that
/// asks for the payment. Both come from the node, but only one of them is the
/// order the user chose: the event is addressable and public, and it is what
/// the take screen showed. A market-price order carries no amount until it is
/// taken, and the node republishes the event with the resolved figure as part
/// of that flow, so by the time either side is asked to act the amount is
/// there.
///
/// Being addressable cuts both ways: the node can republish it again at any
/// point, which is why a settlement is held to [signedOrderAmountProvider]
/// and not to this.
///
/// Null when no event has arrived, or when it carries no usable amount.
final publishedOrderAmountProvider =
Provider.family<int?, String>((ref, orderId) {
final event = ref.watch(eventProvider(orderId));
if (event == null) return null;

final amount = int.tryParse(event.amount ?? '');
if (amount == null || amount <= 0) return null;
return amount;
});

/// The order amount this settlement is held to, in satoshis.
///
/// The figure pinned when the session committed to the trade, so republishing
/// the order event afterwards cannot move what the client will accept. Falls
/// back to the live event where nothing was pinned: sessions written before
/// the pin existed, and market-price and range orders, whose sats figure the
/// node only resolves after the commitment there was to make.
final signedOrderAmountProvider = Provider.family<int?, String>((ref, orderId) {
final pinned = ref.watch(sessionProvider(orderId))?.pinnedAmountSats;
if (pinned != null) return pinned;

return ref.watch(publishedOrderAmountProvider(orderId));
});

/// The node's fee rate, from its kind-38385 info event.
///
/// Followed rather than sampled: the info event arrives asynchronously after
/// the order subscription is opened, so a screen built first would otherwise
/// hold a null read for the rest of the session and keep falling back to the
/// weaker check.
///
/// The event is pinned to the node currently selected. Switching instances
/// clears the repository's cached event without emitting the drop, so an
/// unpinned fee rate would go on deriving amounts from the previous node's
/// terms and refuse settlements that are in fact correct.
///
/// Null when the info event has not arrived, belongs to another node, or does
/// not carry the tag. The getter parses eagerly and throws on a missing tag,
/// which is fine for the About screen it was written for and not for a
/// payment check.
final nodeFeeRateProvider = Provider<double?>((ref) {
final nodePubkey = ref.watch(
settingsProvider.select((settings) => settings.mostroPublicKey),
);
final info = ref.watch(mostroInfoEventProvider).valueOrNull;
if (info == null || info.pubkey != nodePubkey) return null;
try {
return info.fee;
} catch (e) {
logger.w('Node info event carries no usable fee rate: $e');
return null;
}
});

/// The fee rate this settlement is held to.
///
/// [nodeFeeRateProvider] tracks whatever the node currently advertises, which
/// it can change under a trade already in flight. This prefers the rate
/// pinned when the session committed, on the same terms as
/// [signedOrderAmountProvider].
final orderFeeRateProvider = Provider.family<double?, String>((ref, orderId) {
final session = ref.watch(sessionProvider(orderId));

final pinned = session?.pinnedFeeRate;
if (pinned != null) return pinned;

// A session holding an amount but no rate is one that committed while the
// info event was still missing: pinning ran, and there was nothing to pin.
// Reading the live rate here would let the node publish the term after the
// fact, which is the whole of what pinning exists to prevent. Report it
// unknown instead and let the screen say the check could not be made.
if (session?.pinnedAmountSats != null) return null;

return ref.watch(nodeFeeRateProvider);
});

/// What the seller's hold invoice for [orderId] should ask for, derived from
/// the signed order amount and the signed fee rate.
///
/// Null when either input is missing. A caller that gets null has not learned
/// that the payment is wrong — only that it cannot re-derive what it should
/// be, and should fall back to the weaker check it can still make.
final anchoredSellerAmountProvider =
Provider.family<int?, String>((ref, orderId) {
final amountSats = ref.watch(signedOrderAmountProvider(orderId));
final feeRate = ref.watch(orderFeeRateProvider(orderId));
if (amountSats == null || feeRate == null) return null;

return SettlementAmounts.sellerPays(
amountSats: amountSats,
feeRate: feeRate,
);
});

/// What the buyer's payout invoice for [orderId] should ask for, derived from
/// the signed order amount and the signed fee rate.
///
/// The figure is the order amount less the buyer's half of the fee, so it is
/// never the amount shown on the order — a client comparing against that
/// would refuse every correct payout.
///
/// Null on the same terms as [anchoredSellerAmountProvider]: the caller has
/// learned nothing about whether the request is right, only that it cannot
/// re-derive what it should be.
final anchoredBuyerAmountProvider =
Provider.family<int?, String>((ref, orderId) {
final amountSats = ref.watch(signedOrderAmountProvider(orderId));
final feeRate = ref.watch(orderFeeRateProvider(orderId));
if (amountSats == null || feeRate == null) return null;

return SettlementAmounts.buyerReceives(
amountSats: amountSats,
feeRate: feeRate,
);
});
Loading
Loading