Skip to content
Closed
Show file tree
Hide file tree
Changes from 22 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
129 changes: 129 additions & 0 deletions lib/data/models/session.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,53 @@ 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;

/// The currency, fiat figure and premium this session committed to.
///
/// The independent market quote is priced from these three, and all three
/// live in the same addressable kind-38383 event as the sats amount. Read
/// live, they let a node make a shaved settlement quote exactly: resolve
/// fewer sats than the trade was agreed at, then republish the premium so
/// the quote lands on the shaved figure. Pinned, the quote prices what the
/// user accepted.
///
/// Null where there was nothing to pin — a session written before pinning
/// existed, or an order event that had not arrived at commitment.
String? pinnedFiatCode;
int? pinnedFiatAmount;
double? pinnedPremium;

/// Whether the terms were pinned when this session committed.
///
/// Separates a session that pinned whatever there was to pin — possibly
/// nothing, for a market-price order with no resolved sats, or for a
/// commitment made before the info event arrived — from one written before
/// pinning existed at all. Only the second has any business reading a term
/// the node publishes later; for the first, an absent figure means the node
/// could not supply it at the moment of agreement, and letting it supply
/// one afterwards is the move pinning exists to stop.
///
/// False for every session written by an earlier version, which keeps them
/// behaving as they did.
final bool termsPinned;

/// 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 +85,37 @@ class Session {
this.parentOrderId,
this.role,
this.disputeId,
int? pinnedAmountSats,
double? pinnedFeeRate,
String? pinnedFiatCode,
int? pinnedFiatAmount,
double? pinnedPremium,
this.termsPinned = false,
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;
this.pinnedFiatCode =
(pinnedFiatCode != null && pinnedFiatCode.isNotEmpty)
? pinnedFiatCode
: null;
this.pinnedFiatAmount =
(pinnedFiatAmount != null && pinnedFiatAmount > 0)
? pinnedFiatAmount
: null;
this.pinnedPremium =
(pinnedPremium != null && pinnedPremium.isFinite) ? pinnedPremium : null;

_peer = peer;
if (peer != null) {
_sharedKey = NostrUtils.computeSharedKey(
Expand All @@ -64,6 +139,12 @@ class Session {
'peer': peer?.publicKey,
'admin_peer': _adminPubkey,
'dispute_id': disputeId,
'pinned_amount_sats': pinnedAmountSats,
'pinned_fee_rate': pinnedFeeRate,
'pinned_fiat_code': pinnedFiatCode,
'pinned_fiat_amount': pinnedFiatAmount,
'pinned_premium': pinnedPremium,
'terms_pinned': termsPinned,
};

factory Session.fromJson(Map<String, dynamic> json) {
Expand Down Expand Up @@ -181,6 +262,48 @@ 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 termsPinnedValue = json['terms_pinned'];
final termsPinned = termsPinnedValue is bool
? termsPinnedValue
: termsPinnedValue is String
? termsPinnedValue.toLowerCase() == 'true'
: false;

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

final pinnedFiatAmountValue = json['pinned_fiat_amount'];
int? pinnedFiatAmount;
if (pinnedFiatAmountValue is int) {
pinnedFiatAmount = pinnedFiatAmountValue;
} else if (pinnedFiatAmountValue is String) {
pinnedFiatAmount = int.tryParse(pinnedFiatAmountValue);
}

final pinnedPremiumValue = json['pinned_premium'];
double? pinnedPremium;
if (pinnedPremiumValue is num) {
pinnedPremium = pinnedPremiumValue.toDouble();
} else if (pinnedPremiumValue is String) {
pinnedPremium = double.tryParse(pinnedPremiumValue);
}

return Session(
masterKey: masterKeyValue,
tradeKey: tradeKeyValue,
Expand All @@ -193,6 +316,12 @@ class Session {
peer: peer,
adminPubkey: adminPubkey,
disputeId: disputeId,
pinnedAmountSats: pinnedAmountSats,
pinnedFeeRate: pinnedFeeRate,
pinnedFiatCode: json['pinned_fiat_code']?.toString(),
pinnedFiatAmount: pinnedFiatAmount,
pinnedPremium: pinnedPremium,
termsPinned: termsPinned,
);
} catch (e) {
throw FormatException('Failed to parse Session from JSON: $e');
Expand Down
15 changes: 15 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,23 @@ 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.
// The maker's own figures are the agreement, so they are pinned from
// the order being submitted rather than read back off the event the
// node publishes for it. A range order carries no single fiat figure
// until a taker resolves the band.
final isRange = order.maxAmount != null;
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),
pinnedFiatCode: order.fiatCode,
pinnedFiatAmount: isRange ? null : order.fiatAmount,
pinnedPremium: order.premium.toDouble(),
);

// Start 10s timeout cleanup timer for create orders
Expand Down
26 changes: 26 additions & 0 deletions lib/features/order/notifiers/order_notifier.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ 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';
import 'package:mostro_mobile/shared/utils/pricing_terms.dart';

class OrderNotifier extends AbstractMostroNotifier {
late final MostroService mostroService;
Expand Down Expand Up @@ -91,9 +93,21 @@ 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.
final terms = pricingTermsOf(ref.read(eventProvider(orderId)));

session = await sessionNotifier.newSession(
orderId: orderId,
role: Role.buyer,
pinnedAmountSats: pinnedAmountSats,
pinnedFeeRate: pinnedFeeRate,
pinnedFiatCode: terms?.fiatCode,
pinnedFiatAmount: terms?.fiatAmount,
pinnedPremium: terms?.premium,
);

// Drop any stale grace timer/flag from a previous cycle on this order so
Expand All @@ -117,9 +131,21 @@ 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);
final terms = pricingTermsOf(ref.read(eventProvider(orderId)));

session = await sessionNotifier.newSession(
orderId: orderId,
role: Role.seller,
pinnedAmountSats: pinnedAmountSats,
pinnedFeeRate: pinnedFeeRate,
pinnedFiatCode: terms?.fiatCode,
pinnedFiatAmount: terms?.fiatAmount,
pinnedPremium: terms?.premium,
);

// Drop any stale grace timer/flag from a previous cycle on this order so
Expand Down
141 changes: 141 additions & 0 deletions lib/features/order/providers/market_check_provider.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import 'dart:async';

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';

/// How long a fetched rate may be reused before it is asked for again.
///
/// Bitcoin moves, and a settlement checked against a price from hours ago is
/// not checked against the market. Short enough that a rate cannot outlive
/// the screen it was fetched for by much, long enough that a rebuild does not
/// mean another request.
const Duration kQuoteTtl = Duration(minutes: 2);

/// 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: being offline is not
/// evidence against a settlement, and the caller reports it as a check it
/// could not make rather than as a settlement that passed.
///
/// Disposed with its last listener and refetched on a [kQuoteTtl] timer. Held
/// alive for the process, as a plain family is, the first rate fetched would
/// go on pricing every later trade — a settlement hours later would be
/// compared against a price from the first screen that ever asked.
final independentFiatPerBtcProvider =
Comment thread
AndreaDiazCorreia marked this conversation as resolved.
FutureProvider.autoDispose.family<double?, String>((ref, fiatCode) async {
if (fiatCode.isEmpty) return null;

final staleAt = Timer(kQuoteTtl, ref.invalidateSelf);
ref.onDispose(staleAt.cancel);

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.
///
/// Only applies 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.
///
/// Sessions written before pinning existed are left out. They pinned no sats
/// either, so without this they would all fall through to the check — and a
/// fixed-amount order among them, priced by hand and legitimately far from
/// the market, would draw a caution on a settlement that is perfectly honest.
/// Trades already in flight when the user updates would carry it. Declining
/// to apply a new check to a commitment that predates it is the same call
/// [orderFeeRateProvider] makes for the fee.
///
/// The quote is priced from the terms the session pinned, not from the event
/// the node currently publishes. Currency, fiat figure and premium all live
/// in the same addressable event as the sats amount, so a node reading them
/// back could resolve a shaved settlement and then republish the premium that
/// makes the shave quote exactly — the check would agree with the skim.
///
/// The four outcomes stay distinct. "Does not apply" and "could not be made"
/// are different facts about a settlement, and neither is "priced correctly":
/// a commitment made with no order event pinned no currency or premium, so
/// silence there would be a state the node can produce by withholding it.
final marketCheckProvider =
Provider.autoDispose.family<MarketCheckResult, String>((ref, orderId) {
final session = ref.watch(sessionProvider(orderId));
if (session?.termsPinned != true) return MarketCheckResult.notApplicable;
if (session?.pinnedAmountSats != null) return MarketCheckResult.notApplicable;

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

// Currency and premium come from what the session committed to, never from
// the live event. All three inputs sit in the same addressable kind-38383
// event as the sats amount, so reading them back would let a node make a
// shaved settlement quote exactly right: resolve fewer sats than the trade
// was agreed at, then republish the premium so the quote lands on the
// shaved figure and the gap disappears.
//
// The fiat figure is the exception that has to be read live, and only for a
// range order: the band is not resolved to one figure until a taker settles
// it, so there was nothing to pin at commitment. A node moving it there
// moves a term nobody had agreed to yet.
final fiatCode = session!.pinnedFiatCode;
final premium = session.pinnedPremium;
if (fiatCode == null || fiatCode.isEmpty || premium == null) {
return MarketCheckResult.unavailable;
}

int? fiatAmount = session.pinnedFiatAmount;
if (fiatAmount == null) {
final event = ref.watch(eventProvider(orderId));
if (event == null) return MarketCheckResult.notApplicable;

// 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 MarketCheckResult.notApplicable;
}
fiatAmount = fiat.minimum;
}

final rate = ref.watch(independentFiatPerBtcProvider(fiatCode));
if (rate.isLoading) return MarketCheckResult.loading;

final fiatPerBtc = rate.valueOrNull;
if (fiatPerBtc == null) return MarketCheckResult.unavailable;
Comment thread
coderabbitai[bot] marked this conversation as resolved.

final check = MarketCheck.of(
settledSats: settledSats,
fiatAmount: fiatAmount,
fiatPerBtc: fiatPerBtc,
premium: premium,
);
Comment thread
AndreaDiazCorreia marked this conversation as resolved.
if (check == null) return MarketCheckResult.unavailable;

return MarketCheckResult.checked(check);
});
Loading
Loading