-
Notifications
You must be signed in to change notification settings - Fork 28
fix: check invoice amounts against the order's signed terms #664
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
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 971dcc3
fix(invoice): block payment when invoice terms disagree with the order
AndreaDiazCorreia d89cc1f
feat(invoice): anchor seller hold invoice to signed order amount and …
AndreaDiazCorreia 656cef0
feat(invoice): block buyer payout when invoice request disagrees with…
AndreaDiazCorreia e7d5490
fix(invoice): follow info event stream to prevent stale fee rate reads
AndreaDiazCorreia fb5a9c4
fix(invoice): show the invoice amount in the manual payment flow
AndreaDiazCorreia a54fd45
feat(invoice): say when a settlement could not be checked
AndreaDiazCorreia 883c69a
feat(invoice): hold a settlement to the terms pinned at commitment
AndreaDiazCorreia 431aeb6
feat(invoice): re-price market orders against an independent rate
AndreaDiazCorreia 0c35d7c
test(invoice): cover the settlement gating on both invoice screens
AndreaDiazCorreia 3ae7036
fix(invoice): keep a fee unavailable at commitment from becoming a term
AndreaDiazCorreia dfedb47
fix(invoice): pin the fee rate on range remainder sessions
AndreaDiazCorreia c2414f3
fix(invoice): await cancellation before leaving the payment screen
AndreaDiazCorreia 315e581
feat(invoice): refuse a settlement that runs off market against the user
AndreaDiazCorreia 1f7a877
fix(invoice): record that pinning ran instead of inferring it
AndreaDiazCorreia aa58196
fix(invoice): do not quote an unreadable premium as zero
AndreaDiazCorreia d4a3323
fix(invoice): stop sending an amount NIP-47 wallets may refuse
AndreaDiazCorreia 65fe829
fix(invoice): leave pre-pinning sessions out of the market check
AndreaDiazCorreia 40270fd
fix(invoice): refuse a fee rate that leaves the arithmetic's domain
AndreaDiazCorreia 8b5dac2
fix(invoice): bind the market override to the quote it was given for
AndreaDiazCorreia 6f550dd
fix(invoice): tell the market check's four outcomes apart
AndreaDiazCorreia 51eb490
fix(invoice): durably pin every term the settlement is checked against
AndreaDiazCorreia 4e01319
fix(invoice): stop refusing settlements the check has nothing against
AndreaDiazCorreia f54d219
fix(invoice): keep the market check from flapping, and its anchors in…
AndreaDiazCorreia bb1904b
fix(invoice): fail closed when the settlement terms cannot be stored
AndreaDiazCorreia 1400b6c
Merge remote-tracking branch 'origin/main' into fix/bind-invoice-amou…
AndreaDiazCorreia 2e1a3c1
fix(invoice): check the payout invoice against the order's signed ter…
AndreaDiazCorreia 606e9b9
fix(invoice): do not let a range remainder's anchor block a release
AndreaDiazCorreia 914438d
fix(l10n): standardize Spanish imperative forms to formal second person
AndreaDiazCorreia a15c227
fix(order): fetch node info event before the order book to pin fee ra…
AndreaDiazCorreia 98e7c8c
fix(order): cap the book subscription at 1000 events to bound startup…
AndreaDiazCorreia 030d7b1
fix(invoice): compare late-arriving fee rates against the commitment …
AndreaDiazCorreia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
141 changes: 141 additions & 0 deletions
141
lib/features/order/providers/market_check_provider.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 = | ||
|
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; | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| final check = MarketCheck.of( | ||
| settledSats: settledSats, | ||
| fiatAmount: fiatAmount, | ||
| fiatPerBtc: fiatPerBtc, | ||
| premium: premium, | ||
| ); | ||
|
AndreaDiazCorreia marked this conversation as resolved.
|
||
| if (check == null) return MarketCheckResult.unavailable; | ||
|
|
||
| return MarketCheckResult.checked(check); | ||
| }); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.