Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
132 changes: 132 additions & 0 deletions lib/data/models/session.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,56 @@ 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.
late final int? pinnedAmountSats;

/// The node's fee rate when this session committed, on the same terms as
/// [pinnedAmountSats].
late final 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.
late final String? pinnedFiatCode;
late final int? pinnedFiatAmount;
late final double? pinnedPremium;

/// Whether the terms were pinned when this session committed.
///
/// Together with the figures above: all of it is written once, in the
/// constructor body, and never moved afterwards. That is what a pin is.
///
/// 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 +88,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 +142,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 +265,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 +319,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
99 changes: 84 additions & 15 deletions lib/data/repositories/open_orders_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,21 @@ const orderEventKind = 38383;
const infoEventKind = 38385;
const orderFilterDurationHours = 48;

/// Upper bound on the stored order events a relay may return when the book
/// subscription opens.
///
/// A backstop, not a page size. Kind 38383 is addressable, so a relay that
/// follows NIP-01 already holds one event per order rather than one per status
/// change, and this figure sits well above what any node's 48-hour window
/// carries — the book is not expected to reach it, and a relay that honours it
/// returns the most recent events, which is where an in-flight trade's own
/// order sits.
///
/// What it bounds is the pathological case: every event that arrives is parsed
/// on the main isolate, so an unbounded backlog is unbounded work between
/// launch and the first thing the user can act on.
const orderFilterLimit = 1000;

class OpenOrdersRepository implements OrderRepository<NostrEvent> {
final NostrService _nostrService;
NostrEvent? _mostroInstance;
Expand All @@ -29,6 +44,10 @@ class OpenOrdersRepository implements OrderRepository<NostrEvent> {
final Map<String, NostrEvent> _events = {};
StreamSubscription<NostrEvent>? _subscription;

/// The node info subscription, kept apart from the order one. See
/// [_subscribeToOrders] for why it does not share a filter.
StreamSubscription<NostrEvent>? _infoSubscription;

/// Polls for NostrService readiness when the repository is built before
/// init() completes, so the order subscription can be opened once Nostr is up.
Timer? _initRetryTimer;
Expand All @@ -48,9 +67,28 @@ class OpenOrdersRepository implements OrderRepository<NostrEvent> {
_emitEvents();
}

/// Subscribes to events matching the given filter.
/// Subscribes to the node's order book and to its info event.
///
/// The two go out as separate requests, and the info one first. Sharing a
/// filter put the info event behind the entire order backlog: one request,
/// answered in whatever order the relay holds its events, and the book is
/// every order the node touched in [orderFilterDurationHours].
///
/// That ordering is not cosmetic. The fee rate the settlement checks are
/// anchored to is read off this event, and it is pinned at the moment the
/// user commits to a trade. A take that lands before the event does pins no
/// rate at all, and the settlement screens then report — for the life of
/// that trade — an amount they could not verify. On a slow link, or via a
/// `mostro:` deep link that opens straight onto the take screen, that is a
/// caution the user's bandwidth decides rather than the node's honesty.
///
/// Its own request also lets the filter drop `since`. The node republishes
/// its info event on its own schedule, not the order book's, so a node that
/// has been quiet for longer than the order window would otherwise never
/// announce itself at all.
void _subscribeToOrders() {
_subscription?.cancel();
_infoSubscription?.cancel();
_initRetryTimer?.cancel();

// The repository can be built before NostrService.init() completes (the
Expand All @@ -63,30 +101,42 @@ class OpenOrdersRepository implements OrderRepository<NostrEvent> {
return;
}

final nodePubkey = _settings.mostroPublicKey;

_infoSubscription = _nostrService
.subscribeToEvents(
NostrRequest(
filters: [
NostrFilter(
kinds: [infoEventKind],
authors: [nodePubkey],
limit: 1,
),
],
),
)
.listen(_handleInfoEvent, onError: (error) {
logger.e('Error in Mostro info subscription: $error');
});

final filterTime =
DateTime.now().subtract(Duration(hours: orderFilterDurationHours));

final filter = NostrFilter(
kinds: [orderEventKind, infoEventKind],
since: filterTime,
authors: [_settings.mostroPublicKey],
);

final request = NostrRequest(
filters: [filter],
filters: [
NostrFilter(
kinds: [orderEventKind],
since: filterTime,
authors: [nodePubkey],
limit: orderFilterLimit,
),
],
);

_subscription = _nostrService.subscribeToEvents(request).listen((event) {
if (event.type == 'order') {
_events[event.orderId!] = event;
_eventStreamController.add(_events.values.toList());
} else if (event.kind == infoEventKind &&
event.pubkey == _settings.mostroPublicKey) {
logger.i('Mostro instance info loaded: $event');
_mostroInstance = event;
if (!_mostroInstanceController.isClosed) {
_mostroInstanceController.add(event);
}
}
}, onError: (error) {
logger.e('Error in order subscription: $error');
Expand All @@ -97,6 +147,24 @@ class OpenOrdersRepository implements OrderRepository<NostrEvent> {
_emitEvents();
}

/// Records the node's info event and announces it.
///
/// The author is checked rather than assumed: a node switch cancels this
/// subscription, but an event already in flight when it does must not be
/// reported as the new node's terms.
void _handleInfoEvent(NostrEvent event) {
if (event.kind != infoEventKind ||
event.pubkey != _settings.mostroPublicKey) {
return;
}

logger.i('Mostro instance info loaded: $event');
_mostroInstance = event;
if (!_mostroInstanceController.isClosed) {
_mostroInstanceController.add(event);
}
}

/// Polls NostrService until it reports initialized, then opens the order
/// subscription. Bounded so a failed init does not leave a timer running
/// forever; `reloadData`/`updateSettings` can still re-trigger later.
Expand Down Expand Up @@ -127,6 +195,7 @@ class OpenOrdersRepository implements OrderRepository<NostrEvent> {
@override
void dispose() {
_subscription?.cancel();
_infoSubscription?.cancel();
_initRetryTimer?.cancel();
_eventStreamController.close();
_mostroInstanceController.close();
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
Loading
Loading