From a21fa7f4cf21ebcda36de465726e7af758911b1f Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 06:04:58 +0100 Subject: [PATCH 01/20] feat(m4): indexer order list and detail endpoints --- src/data/ml/IndexerClient.ts | 42 +++++++++++++++++++++++-- src/data/ml/indexerClient.test.ts | 52 +++++++++++++++++++++++++++++++ src/data/ml/types.ts | 19 +++++++++++ 3 files changed, 111 insertions(+), 2 deletions(-) diff --git a/src/data/ml/IndexerClient.ts b/src/data/ml/IndexerClient.ts index 164090c..a53f290 100644 --- a/src/data/ml/IndexerClient.ts +++ b/src/data/ml/IndexerClient.ts @@ -21,8 +21,8 @@ import { TransportError as IndexerError, type FetchLike, } from '../transport'; import type { - AmountJson, CoinStats, MlAddressInfo, MlNftInfo, MlOutput, MlOutpoint, MlTokenInfo, - MlTransaction, MlTransactionInput, MlUtxo, OrderBookLevel, OrderBookPage, + AmountJson, CoinStats, MlAddressInfo, MlNftInfo, MlOrderCurrency, MlOrderInfo, MlOutput, MlOutpoint, + MlTokenInfo, MlTransaction, MlTransactionInput, MlUtxo, OrderBookLevel, OrderBookPage, } from './types'; export { IndexerError }; @@ -56,6 +56,30 @@ const DEFAULT_MAX_PAGES = 100; const DEFAULT_MAX_ITEMS = 50_000; +/** Page size for the offset walkers (documented cap is 100). */ +const DEFAULT_PAGE_ITEMS = 100; + +function parseOrder(raw: unknown): MlOrderInfo { + const record = asRecord(raw); + const orderId = asString(record.order_id); + if (orderId === null) throw new IndexerError('parse', '/order', undefined); + const currency = (value: unknown): MlOrderCurrency => { + const side = asRecord(value); + return { type: asString(side.type) ?? 'Unknown', tokenId: asString(side.token_id) ?? undefined }; + }; + return { + orderId, + giveBalance: parseAmount(record.give_balance), + askBalance: parseAmount(record.ask_balance), + giveCurrency: currency(record.give_currency), + askCurrency: currency(record.ask_currency), + initiallyGiven: record.initially_given !== undefined && record.initially_given !== null ? parseAmount(record.initially_given) : null, + initiallyAsked: record.initially_asked !== undefined && record.initially_asked !== null ? parseAmount(record.initially_asked) : null, + concludeDestination: asString(record.conclude_destination) ?? '', + frozen: record.frozen === true, + }; +} + /** Absorb every documented amount shape into the atoms/decimal pair. * Numbers must be safe integers (Uint64 atom counts upstream); a 1e21 * scale number would stringify into e-notation and explode downstream. @@ -287,6 +311,20 @@ export class IndexerClient { }); } + /** Every open order on the network (offset/items walk, F11). */ + async orders(): Promise { + const out: MlOrderInfo[] = []; + await this.walkOffset('/order', undefined, DEFAULT_PAGE_ITEMS, async (items) => { + for (const entry of items) out.push(parseOrder(entry)); + }); + return out; + } + + /** GET /order/{id}: one order, balances and currencies included. */ + async order(id: string): Promise { + return parseOrder(await this.request(`/order/${encodeURIComponent(id)}`)); + } + /** GET /nft/{id}; a 404 NFT not found (non-NFT id) resolves to null. */ async nft(id: string): Promise { try { diff --git a/src/data/ml/indexerClient.test.ts b/src/data/ml/indexerClient.test.ts index 5290467..0eff0d5 100644 --- a/src/data/ml/indexerClient.test.ts +++ b/src/data/ml/indexerClient.test.ts @@ -236,6 +236,58 @@ async function main() { assert.deepEqual(offsets, [2, 1]); assert.match(offsetCalls[1].url, /offset=2/); + // orders list and detail (M4): currency sides keep their type and token + // id; optional initial amounts parse when present. + const orderCalls: { url: string }[] = []; + const orderClient = new IndexerClient('https://indexer.test/api/v2', { + fetch: scriptedFetch( + [ + { + status: 200, + body: [ + { + order_id: 'mordr1abc', + give_balance: { atoms: '1000' }, + ask_balance: { atoms: '100' }, + give_currency: { type: 'Coin' }, + ask_currency: { type: 'Token', token_id: 'mmltk1x' }, + initially_given: { atoms: '2000' }, + initially_asked: { atoms: '200' }, + conclude_destination: 'mtc1qmaker', + }, + ], + }, + { + status: 200, + body: { + order_id: 'mordr1abc', + give_balance: { atoms: '950' }, + ask_balance: { atoms: '95' }, + give_currency: { type: 'Coin' }, + ask_currency: { type: 'Token', token_id: 'mmltk1x' }, + conclude_destination: 'mtc1qmaker', + }, + }, + ], + orderCalls, + ), + delay: noDelay, + }); + const orders = await orderClient.orders(); + assert.equal(orders.length, 1); + assert.equal(orders[0].orderId, 'mordr1abc'); + assert.equal(orders[0].giveBalance.atoms, '1000'); + assert.equal(orders[0].giveCurrency.type, 'Coin'); + assert.equal(orders[0].askCurrency.tokenId, 'mmltk1x'); + assert.equal(orders[0].initiallyGiven?.atoms, '2000'); + assert.equal(orders[0].concludeDestination, 'mtc1qmaker'); + assert.match(orderCalls[0].url, /items=100&offset=0/); + const detail = await orderClient.order('mordr1abc'); + assert.equal(detail.askBalance.atoms, '95'); + assert.equal(detail.initiallyGiven, null); + assert.equal(detail.frozen, false); + assert.match(orderCalls[1].url, /\/order\/mordr1abc$/); + // Non-terminating cursor: the same next_cursor forever is cut off by the // page cap with a typed parse error, not an unbounded request loop. let endlessCursorCalls = 0; diff --git a/src/data/ml/types.ts b/src/data/ml/types.ts index 5b7c902..a72e786 100644 --- a/src/data/ml/types.ts +++ b/src/data/ml/types.ts @@ -90,6 +90,25 @@ export type CoinStats = { burned: AmountJson; }; +/** One currency side of an order: the base coin or a token id (F11). */ +export type MlOrderCurrency = { type: 'Coin' | 'Token' | (string & {}); tokenId?: string }; + +/** One entry of GET /order and GET /order/{id} (api-coverage.md). The + * balances shrink as takers fill; initially_given/asked anchor the fill + * progress; conclude_destination anchors the myOrders membership filter. */ +export type MlOrderInfo = { + orderId: string; + giveBalance: AmountJson; + askBalance: AmountJson; + giveCurrency: MlOrderCurrency; + askCurrency: MlOrderCurrency; + initiallyGiven: AmountJson | null; + initiallyAsked: AmountJson | null; + concludeDestination: string; + /** Frozen state field when the indexer serves it (maker freeze). */ + frozen?: boolean; +}; + /** One aggregated level of GET /order/pair/{BASE}_{QUOTE}/book. */ export type OrderBookLevel = { price: AmountJson; amount: AmountJson }; From 0509928927d3cc3e807e48b65f63b19dd01707d8 Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 06:06:29 +0100 Subject: [PATCH 02/20] feat(m4): order book service with cursor walk and depth rows --- src/trade/OrderBookService.ts | 136 +++++++++++++++++++++++++++++ src/trade/orderBookService.test.ts | 103 ++++++++++++++++++++++ 2 files changed, 239 insertions(+) create mode 100644 src/trade/OrderBookService.ts create mode 100644 src/trade/orderBookService.test.ts diff --git a/src/trade/OrderBookService.ts b/src/trade/OrderBookService.ts new file mode 100644 index 0000000..0734620 --- /dev/null +++ b/src/trade/OrderBookService.ts @@ -0,0 +1,136 @@ +// Live order book (spec M4 deliverable 2): aggregated price levels from +// GET /order/pair/{base}_{quote}/book with keyset cursor pagination, mapped +// onto the depth rows the DexScreen renders. The server returns already +// aggregated levels; this service pages them until the requested depth is +// visible and converts every figure to a decimal string at the display +// boundary (no float money math in state). +// +// Honesty rules: a book that cannot be fetched throws (the screen renders +// the error state, never fixture rows), and last() stays null because the +// indexer exposes no trades endpoint this service could trust (F11: the +// null keeps the last-fill figure honest instead of a stale fabrication). +import { atomsToDecimal, ML_DECIMALS } from '../money'; +import { IndexerError, type IndexerClient, type OrderBookSide } from '../data/ml/IndexerClient'; +import type { AmountJson } from '../data/ml/types'; + +/** One rendered book row: price and size in base/quote decimals plus the + * running total the depth bar scales against. */ +export type BookRow = { price: string; size: string; total: string }; + +export interface OrderBookService { + /** Aggregated levels for one side, best price first, up to depth. */ + levels(base: string, quote: string, side: OrderBookSide, depth?: number): Promise; + /** Last fill price; always null today (no trusted trades endpoint). */ + last(): Promise; +} + +export type OrderBookServiceConfig = { + /** The indexer reader seam (orderBook only). */ + reader: Pick; + /** Cursor pages fetched per levels() call at most. */ + maxPages?: number; +}; + +const DEFAULT_MAX_PAGES = 8; + +/** Book depth the screen renders (6 asks + 6 bids around the spread). */ +export const DEFAULT_BOOK_DEPTH = 6; + +/** Decimal digits used when flattening the server's num/denom price + * rational; a truncated display price never feeds money math. */ +const PRICE_FRACTION_DIGITS = 8; + +/** Parse a decimal string into a scaled BigInt (digits * 10^scale). */ +function scaledOf(decimal: string): { digits: bigint; scale: number } { + const match = /^(\d+)(?:\.(\d*))?$/.exec(decimal.trim()); + if (!match) throw new IndexerError('parse', 'book level', undefined); + const frac = match[2] ?? ''; + return { digits: BigInt(match[1] + frac), scale: frac.length }; +} + +/** Rescale a scaled value to a plain decimal string. */ +function toDecimal(digits: bigint, scale: number): string { + if (digits === 0n) return '0'; + const text = digits.toString().padStart(scale + 1, '0'); + const int = text.slice(0, text.length - scale).replace(/^0+(?=\d)/, ''); + const frac = scale === 0 ? '' : text.slice(text.length - scale).replace(/0+$/, ''); + return frac.length > 0 ? `${int}.${frac}` : int; +} + +/** Price as a decimal string: the server decimal when present, otherwise + * the documented num/denom rational flattened at display precision. */ +export function bookPriceDecimal(price: AmountJson): string { + if (price.decimal !== undefined) return price.decimal; + const atoms = price.atoms ?? ''; + const rational = /^(\d+)\/(\d+)$/.exec(atoms); + if (rational) { + const num = BigInt(rational[1]); + const denom = BigInt(rational[2]); + if (denom === 0n) throw new IndexerError('parse', 'book level', undefined); + const scale = 10n ** BigInt(PRICE_FRACTION_DIGITS); + return toDecimal((num * scale) / denom, PRICE_FRACTION_DIGITS); + } + throw new IndexerError('parse', 'book level', undefined); +} + +export function createOrderBookService(cfg: OrderBookServiceConfig): OrderBookService { + const maxPages = cfg.maxPages ?? DEFAULT_MAX_PAGES; + + async function levels(base: string, quote: string, side: OrderBookSide, depth = DEFAULT_BOOK_DEPTH): Promise { + const rows = await walkLevels(base, quote, side, depth, true); + return rows; + } + + /** Page walk with one invalid-cursor restart (api-coverage.md: cursors + * are opaque and can go stale; refetching page 1 is the documented + * recovery). Depth flicker on the restart is accepted for v1. */ + async function walkLevels(base: string, quote: string, side: OrderBookSide, depth: number, allowRestart: boolean): Promise { + const rows: BookRow[] = []; + let cursor: string | undefined; + let restarted = false; + for (let page = 0; page < maxPages && rows.length < depth; page++) { + let levelPage; + try { + levelPage = await cfg.reader.orderBook(base, quote, side, cursor); + } catch (e) { + if (allowRestart && !restarted && cursor !== undefined && e instanceof IndexerError && e.kind === 'http' && e.status === 400) { + // The stale cursor page poisoned the accumulated rows: rebuild + // from page 1 so no mixed-generation row survives. + restarted = true; + rows.length = 0; + cursor = undefined; + page = -1; + continue; + } + throw e; + } + for (const level of levelPage.levels) { + if (rows.length >= depth) break; + const price = bookPriceDecimal(level.price); + const size = atomsToDecimal(atomsOfLevel(level.amount), ML_DECIMALS); + const p = scaledOf(price); + const s = scaledOf(size); + // total = price * size, scaled once at the wider precision. + const totalDigits = p.digits * s.digits; + const totalScale = p.scale + s.scale; + rows.push({ price, size, total: toDecimal(totalDigits, totalScale) }); + } + if (levelPage.nextCursor === null) break; + cursor = levelPage.nextCursor; + } + return rows; + } + + return { + levels, + // No aggregated trades endpoint is consumed in v1: null keeps the + // last-fill row honest (the screen hides it instead of guessing). + last: async () => null, + }; +} + +/** Base-currency atoms of one aggregated level. */ +function atomsOfLevel(amount: AmountJson): string { + if (amount.atoms !== undefined) return amount.atoms; + throw new IndexerError('parse', 'book level', undefined); +} diff --git a/src/trade/orderBookService.test.ts b/src/trade/orderBookService.test.ts new file mode 100644 index 0000000..294c8cd --- /dev/null +++ b/src/trade/orderBookService.test.ts @@ -0,0 +1,103 @@ +// Order book service gate (spec M4 testing section): cursor-paginated depth +// aggregation, the num/denom price rational, the invalid-cursor page-1 +// restart and the honest null last-fill. Offline over a scripted reader. +// tsx src/trade/orderBookService.test.ts +import { strict as assert } from 'node:assert/strict'; + +import { IndexerError } from '../data/ml/IndexerClient'; +import type { OrderBookLevel, OrderBookPage } from '../data/ml/types'; +import { bookPriceDecimal, createOrderBookService, DEFAULT_BOOK_DEPTH } from './OrderBookService'; + +type ReaderScript = ({ page: OrderBookPage } | { fail: number })[]; + +function scriptedReader(script: ReaderScript, calls: (string | null)[] = []): { orderBook(base: string, quote: string, side: 'ask' | 'bid', cursor?: string): Promise } { + let index = 0; + return { + async orderBook(_base, _quote, _side, cursor) { + calls.push(cursor ?? null); + if (index >= script.length) throw new IndexerError('transport', 'book', undefined); + const step = script[index++]; + if ('fail' in step) throw new IndexerError('http', 'book', step.fail); + return step.page; + }, + }; +} + +const level = (price: OrderBookLevel['price'], atoms: string): OrderBookLevel => ({ price, amount: { atoms } }); + +async function main() { + // Depth aggregation: pages follow the cursor until depth rows exist. + const calls: (string | null)[] = []; + const service = createOrderBookService({ + reader: scriptedReader( + [ + { page: { levels: [level({ decimal: '0.3458' }, '1248000000000'), level({ decimal: '0.3452' }, '842000000000')], nextCursor: 'c1', truncated: false } }, + { page: { levels: [level({ atoms: '69/200' }, '3214000000000')], nextCursor: null, truncated: false } }, + ], + calls, + ), + }); + const asks = await service.levels('ML', 'USDT', 'ask'); + assert.equal(asks.length, 3); + assert.equal(asks[0].price, '0.3458'); + assert.equal(asks[0].size, '12.48'); + assert.equal(calls[0], null); + assert.equal(calls[1], 'c1'); + + // num/denom rational flattens at display precision (69/200 = 0.345). + assert.equal(asks[2].price, '0.345'); + assert.equal(bookPriceDecimal({ atoms: '1/8' }), '0.125'); + assert.throws(() => bookPriceDecimal({ atoms: '5/0' }), /parse/); + assert.throws(() => bookPriceDecimal({ atoms: 'zzz' }), /parse/); + + // Depth cap: fewer rows than the walk found. + const capped = await createOrderBookService({ + reader: scriptedReader([ + { page: { levels: [level({ decimal: '0.3458' }, '1248000000000'), level({ decimal: '0.3452' }, '842000000000')], nextCursor: 'c1', truncated: false } }, + { page: { levels: [level({ decimal: '0.345' }, '3214000000000')], nextCursor: null, truncated: false } }, + ]), + }).levels('ML', 'USDT', 'bid', 2); + assert.equal(capped.length, 2); + assert.equal(DEFAULT_BOOK_DEPTH, 6); + + // last(): no trusted trades source in v1, always null. + assert.equal(await service.last(), null); + + // Invalid cursor: a 400 on a cursor page restarts once from page 1 and + // rebuilds the rows so no stale generation survives. + const restartCalls: (string | null)[] = []; + const restartService = createOrderBookService({ + reader: scriptedReader( + [ + { page: { levels: [level({ decimal: '0.35' }, '100000000000')], nextCursor: 'stale', truncated: false } }, + { fail: 400 }, + { page: { levels: [level({ decimal: '0.36' }, '200000000000')], nextCursor: null, truncated: false } }, + ], + restartCalls, + ), + }); + const recovered = await restartService.levels('ML', 'USDT', 'ask'); + assert.equal(recovered.length, 1); + assert.equal(recovered[0].price, '0.36'); + assert.deepEqual(restartCalls, [null, 'stale', null]); + + // A second invalid cursor (restart exhausted) surfaces the typed error + // instead of looping. + const exhausted = createOrderBookService({ + reader: scriptedReader([ + { page: { levels: [level({ decimal: '0.35' }, '100000000000')], nextCursor: 'stale', truncated: false } }, + { fail: 400 }, + { fail: 400 }, + ]), + }); + await assert.rejects(() => exhausted.levels('ML', 'USDT', 'ask'), (e: unknown) => e instanceof IndexerError && e.status === 400); + + // Transport failures surface typed: the screen renders the error state, + // never fabricated rows. + const down = createOrderBookService({ reader: scriptedReader([{ fail: 500 }]) }); + await assert.rejects(() => down.levels('ML', 'USDT', 'ask'), (e: unknown) => e instanceof IndexerError); + + console.log('orderBookService: ok'); +} + +main(); From 87da9051763344af9cae553806c48a7233c39b82 Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 06:07:18 +0100 Subject: [PATCH 03/20] feat(m4): price guards for orders and swap entry --- src/trade/priceGuards.test.ts | 48 ++++++++++++++++++++ src/trade/priceGuards.ts | 83 +++++++++++++++++++++++++++++++++++ 2 files changed, 131 insertions(+) create mode 100644 src/trade/priceGuards.test.ts create mode 100644 src/trade/priceGuards.ts diff --git a/src/trade/priceGuards.test.ts b/src/trade/priceGuards.test.ts new file mode 100644 index 0000000..caa79e9 --- /dev/null +++ b/src/trade/priceGuards.test.ts @@ -0,0 +1,48 @@ +// Price guard gate (spec M4 testing section): slippage rejection cases, +// minimum fill floor, amount sanity and the swap timelock rule margin. +// tsx src/trade/priceGuards.test.ts +import { strict as assert } from 'node:assert/strict'; + +import { checkAmounts, checkMinFill, checkSlippage, checkTimelockRule, DEFAULT_SAFETY_MARGIN } from './priceGuards'; + +function reason(result: { ok: boolean; reason?: string }): string | null { + return result.ok ? null : (result.reason ?? 'unknown'); +} + +async function main() { + // Amount sanity: both legs must parse positive. + assert.deepEqual(checkAmounts({ giveDecimal: '100', askDecimal: '10' }), { ok: true }); + assert.equal(reason(checkAmounts({ giveDecimal: '0', askDecimal: '10' })), 'amount'); + assert.equal(reason(checkAmounts({ giveDecimal: 'abc', askDecimal: '10' })), 'amount'); + assert.equal(reason(checkAmounts({ giveDecimal: '-1', askDecimal: '10' })), 'amount'); + + // Slippage: a limit within the band passes, drift beyond it rejects. + assert.deepEqual(checkSlippage({ limitDecimal: '0.3458', midDecimal: '0.3450', maxSlippagePct: 0.5 }), { ok: true }); + assert.equal(reason(checkSlippage({ limitDecimal: '0.40', midDecimal: '0.3450', maxSlippagePct: 1 })), 'slippage'); + assert.equal(reason(checkSlippage({ limitDecimal: '0.25', midDecimal: '0.3450', maxSlippagePct: 1 })), 'slippage'); + // Exactly at the band edge passes (5% of 0.345 = 0.01725; 0.3622 vs mid + // drifts ~4.99%). + assert.deepEqual(checkSlippage({ limitDecimal: '0.3622', midDecimal: '0.3450', maxSlippagePct: 5 }), { ok: true }); + assert.equal(reason(checkSlippage({ limitDecimal: 'x', midDecimal: '0.345', maxSlippagePct: 1 })), 'slippage'); + assert.equal(reason(checkSlippage({ limitDecimal: '1', midDecimal: '0', maxSlippagePct: 1 })), 'slippage'); + + // Minimum fill: below the floor rejects, at the floor passes. + assert.deepEqual(checkMinFill({ amountDecimal: '10', minDecimal: '5' }), { ok: true }); + assert.equal(reason(checkMinFill({ amountDecimal: '4.99999999999', minDecimal: '5' })), 'minSize'); + assert.deepEqual(checkMinFill({ amountDecimal: '5', minDecimal: '5' }), { ok: true }); + assert.equal(reason(checkMinFill({ amountDecimal: 'nope', minDecimal: '5' })), 'minSize'); + + // Timelock rule (F10): BTC must be shorter; the 2x safety margin is + // enforced before initiating. + assert.deepEqual(checkTimelockRule({ mlSeconds: 172800, btcSeconds: 86400 }), { ok: true }); + assert.equal(reason(checkTimelockRule({ mlSeconds: 172800, btcSeconds: 172800 })), 'timelock'); + assert.equal(reason(checkTimelockRule({ mlSeconds: 172800, btcSeconds: 90000 })), 'timelock'); + assert.equal(DEFAULT_SAFETY_MARGIN, 2); + // An explicit margin of 1 permits equal lengths (the rule floor itself). + assert.deepEqual(checkTimelockRule({ mlSeconds: 86400, btcSeconds: 86400, margin: 1 }), { ok: true }); + assert.equal(reason(checkTimelockRule({ mlSeconds: 0, btcSeconds: 60 })), 'timelock'); + + console.log('priceGuards: ok'); +} + +main(); diff --git a/src/trade/priceGuards.ts b/src/trade/priceGuards.ts new file mode 100644 index 0000000..7457a61 --- /dev/null +++ b/src/trade/priceGuards.ts @@ -0,0 +1,83 @@ +// Price and sanity guards shared by the order and swap entry points (spec +// M4: order entry guards). Pure string/BigInt math on decimal amounts: no +// float, no provider state, fully offline-testable. Every guard returns a +// typed result the UI maps to its own copy; the raw detail strings are +// developer diagnostics, never rendered directly. +import { decimalsToAtoms } from '../money'; + +export type GuardReason = 'slippage' | 'minSize' | 'amount' | 'timelock'; + +export type GuardResult = { ok: true } | { ok: false; reason: GuardReason; detail: string }; + +/** The swap timelock safety margin (spec security note: the ML refund + * timelock must be at least margin times the BTC timelock). */ +export const DEFAULT_SAFETY_MARGIN = 2; + +/** Compare decimal strings exactly on a common 11-decimal scale. */ +function compareDecimals(a: string, b: string): number { + const aAtoms = BigInt(decimalsToAtoms(a, 11)); + const bAtoms = BigInt(decimalsToAtoms(b, 11)); + return aAtoms === bAtoms ? 0 : aAtoms > bAtoms ? 1 : -1; +} + +/** Positive, parseable decimal on both legs of an order or swap. */ +export function checkAmounts(params: { giveDecimal: string; askDecimal: string }): GuardResult { + for (const [label, value] of [['give', params.giveDecimal], ['ask', params.askDecimal]] as const) { + let atoms: bigint; + try { + atoms = BigInt(decimalsToAtoms(value, 11)); + } catch { + return { ok: false, reason: 'amount', detail: `${label} amount is not a decimal number` }; + } + if (atoms <= 0n) return { ok: false, reason: 'amount', detail: `${label} amount must be greater than zero` }; + } + return { ok: true }; +} + +/** Slippage guard against the book mid (spec: order entry guards). The + * limit must sit within maxSlippagePct of the mid in either direction; a + * crossed or far-off price rejects before any transaction is built. */ +export function checkSlippage(params: { limitDecimal: string; midDecimal: string; maxSlippagePct: number }): GuardResult { + let limit: bigint; + let mid: bigint; + try { + limit = BigInt(decimalsToAtoms(params.limitDecimal, 11)); + mid = BigInt(decimalsToAtoms(params.midDecimal, 11)); + } catch { + return { ok: false, reason: 'slippage', detail: 'price not parseable' }; + } + if (mid <= 0n) return { ok: false, reason: 'slippage', detail: 'book mid is not a usable price' }; + // basis points: |limit - mid| / mid * 10000; exact BigInt comparison. + const driftBps = ((limit > mid ? limit - mid : mid - limit) * 10000n) / mid; + const maxBps = BigInt(Math.max(0, Math.round(params.maxSlippagePct * 100))); + if (driftBps > maxBps) { + return { ok: false, reason: 'slippage', detail: `price drifted ${Number(driftBps) / 100}% from the book mid` }; + } + return { ok: true }; +} + +/** Minimum fill size guard: the requested fill must reach the configured + * floor (dust fills waste fees and fragment the book). */ +export function checkMinFill(params: { amountDecimal: string; minDecimal: string }): GuardResult { + let cmp: number; + try { + cmp = compareDecimals(params.amountDecimal, params.minDecimal); + } catch { + return { ok: false, reason: 'minSize', detail: 'fill amount is not a decimal number' }; + } + if (cmp < 0) return { ok: false, reason: 'minSize', detail: `fill is below the ${params.minDecimal} minimum` }; + return { ok: true }; +} + +/** TIMELOCK_RULE (F10): the Bitcoin timelock must be shorter than the + * Mintlayer one; the UI enforces the safety margin before initiating. */ +export function checkTimelockRule(params: { mlSeconds: number; btcSeconds: number; margin?: number }): GuardResult { + const margin = params.margin ?? DEFAULT_SAFETY_MARGIN; + if (!Number.isFinite(params.mlSeconds) || !Number.isFinite(params.btcSeconds) || params.mlSeconds <= 0 || params.btcSeconds <= 0) { + return { ok: false, reason: 'timelock', detail: 'timelocks must be positive second counts' }; + } + if (params.btcSeconds * margin > params.mlSeconds) { + return { ok: false, reason: 'timelock', detail: `the Bitcoin timelock must be at most 1/${margin} of the Mintlayer timelock` }; + } + return { ok: true }; +} From e488dce52c0a60514c85edc0921137c3758510f0 Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 06:18:25 +0100 Subject: [PATCH 04/20] feat(m4): order create, fill and conclude flows over bindings --- src/data/ml/IndexerClient.ts | 11 + src/trade/orders.test.ts | 425 ++++++++++++++++++++++++++++ src/trade/orders.ts | 521 +++++++++++++++++++++++++++++++++++ 3 files changed, 957 insertions(+) create mode 100644 src/trade/orders.test.ts create mode 100644 src/trade/orders.ts diff --git a/src/data/ml/IndexerClient.ts b/src/data/ml/IndexerClient.ts index a53f290..657180c 100644 --- a/src/data/ml/IndexerClient.ts +++ b/src/data/ml/IndexerClient.ts @@ -325,6 +325,17 @@ export class IndexerClient { return parseOrder(await this.request(`/order/${encodeURIComponent(id)}`)); } + /** Open orders for one pair (GET /order/pair/{BASE}_{QUOTE}); sides are + * the ML ticker or a raw token id, direction normalized upstream. */ + async ordersByPair(base: string, quote: string): Promise { + const out: MlOrderInfo[] = []; + const path = `/order/pair/${encodeURIComponent(base)}_${encodeURIComponent(quote)}`; + await this.walkOffset(path, undefined, DEFAULT_PAGE_ITEMS, async (items) => { + for (const entry of items) out.push(parseOrder(entry)); + }); + return out; + } + /** GET /nft/{id}; a 404 NFT not found (non-NFT id) resolves to null. */ async nft(id: string): Promise { try { diff --git a/src/trade/orders.test.ts b/src/trade/orders.test.ts new file mode 100644 index 0000000..6eab1af --- /dev/null +++ b/src/trade/orders.test.ts @@ -0,0 +1,425 @@ +// Order flows gate (spec M4 testing section): create builds the order +// output with change legs and extracts the id through the bindings, fill +// carries the no-signature witness on the order input plus signed payer +// inputs, conclude is maker-gated and reclaims to the conclude destination. +// Offline: the pipeline is verified against the MintlayerBindings interface +// contract with a recording double and the derivation parity vectors. +// tsx src/trade/orders.test.ts +import { strict as assert } from 'node:assert/strict'; + +import { bytesToHex } from '@noble/hashes/utils.js'; +import { sha256 } from '@noble/hashes/sha2.js'; +import { bech32m } from '@scure/base'; + +import type { MintlayerBindings, OrderParams, WitnessParams } from '../../modules/mojito-core'; +import type { MlOrderInfo, MlUtxo } from '../data/ml/types'; +import type { BroadcastProvider } from '../data/providers/types'; +import { BroadcastError } from '../data/providers/BroadcastProvider'; +import type { KeySession } from '../keys/session'; +import { deriveMlAccount, mlAddressAt, mlPrivateKeyFromSeed } from '../keys/mlAccounts'; +import { mnemonicToSeed } from '../keys/bip39'; +import { createOrderFlows, orderFromIndexer, orderPhase, proportionalGivePayout, COIN_REF, OrderFlowError } from './orders'; + +const VECTOR_WORDS = [...Array(23).fill('abandon'), 'art']; +const VECTOR_ADDRESS = 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl'; +const TOKEN_ID = 'tMLTK10test000000000000000000000000000000000'; +/** A valid bech32 mtc1 address that derives from no test account. */ +const FOREIGN_ADDRESS = bech32m.encode('mtc1', bech32m.toWords(new Uint8Array(20).fill(0x99))); +const ML = 10n ** 11n; + +/** Valid bech32 order id (the flows decode the data payload for the + * bindings byte-blob form). */ +const ORDER_ID = bech32m.encode('mordr', bech32m.toWords(new Uint8Array([0xab, 0xcd, 0xef, 0x12]))); + +const atoms = (ml: bigint): string => (ml * ML).toString(); + +function fakeBindings(): MintlayerBindings & { + witnesses: WitnessParams[]; + orderParams: OrderParams[]; + fillCalls: { orderId: string; destination: string; amount: string }[]; + concludeCalls: { orderId: string; destination: string }[]; + idCalls: { transaction: Uint8Array; outputIndex: number }[]; + noSignatureCount: () => number; +} { + const witnesses: WitnessParams[] = []; + const orderParams: OrderParams[] = []; + const fillCalls: { orderId: string; destination: string; amount: string }[] = []; + const concludeCalls: { orderId: string; destination: string }[] = []; + const idCalls: { transaction: Uint8Array; outputIndex: number }[] = []; + let noSignatureCalls = 0; + const u32 = (value: number): Uint8Array => { + const out = new Uint8Array(4); + new DataView(out.buffer).setUint32(0, value, false); + return out; + }; + const cat = (...parts: Uint8Array[]): Uint8Array => { + const total = parts.reduce((n, p) => n + p.length, 0); + const out = new Uint8Array(total); + let offset = 0; + for (const part of parts) { + out.set(part, offset); + offset += part.length; + } + return out; + }; + const utf8 = (text: string): Uint8Array => new TextEncoder().encode(text); + const u8 = (tag: number): Uint8Array => new Uint8Array([tag]); + return { + witnesses, + orderParams, + fillCalls, + concludeCalls, + idCalls, + noSignatureCount: () => noSignatureCalls, + async encodeOutpointSourceId(id32: Uint8Array) { + return cat(u8(0x01), id32); + }, + async encodeInputForUtxo(outpointSource: Uint8Array, index: number) { + return cat(u8(0x02), outpointSource, u32(index)); + }, + async encodeOutputTransfer(atomsStr: string, address: string) { + return utf8(`T:${atomsStr}:${address}`); + }, + async encodeOutputTokenTransfer(tokenId: string, atomsStr: string, address: string) { + return utf8(`K:${tokenId}:${atomsStr}:${address}`); + }, + async encodeCreateOrderOutput(params: OrderParams) { + orderParams.push(params); + return utf8(`O:${params.give.tokenId}:${params.give.atoms}:${params.ask.tokenId}:${params.ask.atoms}:${params.concludeDestination}`); + }, + // The bindings take bech32m data payloads; recorded as hex for the + // payload-equality assertions below. + async encodeInputForFillOrder(orderId: Uint8Array, destination: Uint8Array, amount: string) { + fillCalls.push({ orderId: bytesToHex(orderId), destination: bytesToHex(destination), amount }); + return cat(u8(0x03), orderId, destination, utf8(amount)); + }, + async encodeInputForConcludeOrder(orderId: Uint8Array, destination: Uint8Array) { + concludeCalls.push({ orderId: bytesToHex(orderId), destination: bytesToHex(destination) }); + return cat(u8(0x04), orderId, destination); + }, + async encodeTransaction(inputs: Uint8Array[], outputs: Uint8Array[]) { + return cat(u8(0xee), u8(inputs.length), ...inputs, u8(0xff), u8(outputs.length), ...outputs); + }, + async estimateTransactionSize(inputs: Uint8Array[], destinations: string[], outputs: Uint8Array[]) { + return 100 + 40 * inputs.length + 30 * outputs.length + destinations.length; + }, + async getTransactionId(transaction: Uint8Array) { + return bytesToHex(sha256(transaction)); + }, + async encodeWitness(params: WitnessParams) { + witnesses.push(params); + return utf8(`W:${params.inputIndex}`); + }, + async encodeWitnessNoSignature() { + noSignatureCalls += 1; + return u8(0x00); + }, + async encodeSignedTransaction(transaction: Uint8Array, txWitnesses: Uint8Array[]) { + return cat(transaction, ...txWitnesses); + }, + async getOrderId(transaction: Uint8Array, outputIndex: number) { + idCalls.push({ transaction, outputIndex }); + return `mordr1${bytesToHex(sha256(transaction)).slice(0, 12)}`; + }, + } as unknown as MintlayerBindings & { + witnesses: WitnessParams[]; + orderParams: OrderParams[]; + fillCalls: { orderId: string; destination: string; amount: string }[]; + concludeCalls: { orderId: string; destination: string }[]; + idCalls: { transaction: Uint8Array; outputIndex: number }[]; + noSignatureCount: () => number; + }; +} + +function coinUtxo(sourceId: string, index: number, address: string, amount: string): MlUtxo { + return { + outpoint: { sourceType: 'Transaction', sourceId, index }, + output: { type: 'Transfer', destination: address, value: { type: 'Coin', amount: { atoms: amount } } }, + }; +} + +function tokenUtxo(sourceId: string, index: number, address: string, amount: string): MlUtxo { + return { + outpoint: { sourceType: 'Transaction', sourceId, index }, + output: { type: 'Transfer', destination: address, value: { type: 'TokenV1', tokenId: TOKEN_ID, amount: { atoms: amount } } }, + }; +} + +/** bech32m data payload of an id or address, hex form (what the bindings + * byte-blob arguments record). */ +function payloadOf(value: string): string { + return bytesToHex(Uint8Array.from(bech32m.decode(value).words)); +} + +type OrderRow = MlOrderInfo; + +function orderRow(overrides: Partial): OrderRow { + return { + orderId: ORDER_ID, + giveBalance: { atoms: atoms(10n) }, + askBalance: { atoms: atoms(7n) }, + giveCurrency: { type: 'Coin' }, + askCurrency: { type: 'Token', tokenId: TOKEN_ID }, + initiallyGiven: null, + initiallyAsked: null, + concludeDestination: VECTOR_ADDRESS, + ...overrides, + }; +} + +function harness(opts?: { orders?: OrderRow[]; detail?: OrderRow; utxos?: MlUtxo[]; broadcastFails?: 'disabled' | null }) { + const bindings = fakeBindings(); + const changeCounter = { n: 0 }; + const broadcastHexes: string[] = []; + const utxos = opts?.utxos ?? [coinUtxo('aa'.repeat(32), 0, VECTOR_ADDRESS, atoms(500n))]; + const orders = opts?.orders ?? []; + const indexer = { + async order(id: string): Promise { + const row = opts?.detail ?? orders.find((row) => row.orderId === id); + if (!row) throw new Error(`no scripted order ${id}`); + return row; + }, + async orders(): Promise { + return orders; + }, + async ordersByPair(): Promise { + return orders; + }, + async feerate(): Promise { + return '1000'; + }, + async spendableUtxos(address: string): Promise { + return utxos.filter((utxo) => utxo.output.destination === address); + }, + async tip() { + return { blockHeight: 12345, blockId: 'aa'.repeat(32) }; + }, + }; + /** Echo broadcaster: answers the locally computed id like a well-behaved + * backend. The fake signed layout is transaction bytes followed by the + * utf8 witness blobs, so the first 'W:' run marks the boundary. */ + const localIdOf = (signedHex: string): string => { + const bytes = Buffer.from(signedHex, 'hex'); + const marker = Buffer.from('W:'); + let end = bytes.length; + for (let i = 0; i + 1 < bytes.length; i++) { + if (bytes[i] === marker[0] && bytes[i + 1] === marker[1] && bytes[i + 2] === 0x30) { + end = i; + break; + } + } + return bytesToHex(sha256(new Uint8Array(bytes.subarray(0, end)))); + }; + const broadcast: BroadcastProvider = { + async broadcastMl(signedTxHex: string) { + broadcastHexes.push(signedTxHex); + if (opts?.broadcastFails === 'disabled') { + throw new BroadcastError('ml', 'disabled', undefined, 'no ML submission endpoint is configured'); + } + return { txId: localIdOf(signedTxHex) }; + }, + async broadcastBtc() { + return { txId: 'f'.repeat(64) }; + }, + async getMlStatus() { + return { state: 'pending' as const }; + }, + async getBtcStatus() { + return { state: 'pending' as const }; + }, + }; + const flows = createOrderFlows({ + network: 'mainnet', + bindings, + indexer: indexer as never, + broadcast, + addresses: async () => { + const account = await deriveMlAccount(VECTOR_WORDS, 'mainnet'); + const out = [await mlAddressAt(account.xpub, 0, 0, 'mainnet')]; + for (let i = 0; i < changeCounter.n; i++) out.push(await mlAddressAt(account.xpub, 1, i, 'mainnet')); + return out; + }, + allocateChangeAddress: async () => { + const account = await deriveMlAccount(VECTOR_WORDS, 'mainnet'); + return mlAddressAt(account.xpub, 1, changeCounter.n++, 'mainnet'); + }, + releaseFailedChange: async () => { + changeCounter.n = Math.max(0, changeCounter.n - 1); + }, + withSession: async (fn: (session: KeySession) => Promise): Promise => { + const seed = await mnemonicToSeed(VECTOR_WORDS); + return fn({ withSeed: (run: (s: Uint8Array) => Promise) => run(seed) } as unknown as KeySession); + }, + }); + return { flows, bindings, broadcastHexes, changeCounter }; +} + +async function main() { + const seed = await mnemonicToSeed(VECTOR_WORDS); + const account = await deriveMlAccount(VECTOR_WORDS, 'mainnet'); + assert.equal(await mlAddressAt(account.xpub, 0, 0, 'mainnet'), VECTOR_ADDRESS, 'parity vector address'); + const expectedKey = bytesToHex(mlPrivateKeyFromSeed(seed, 'mainnet', 0, 0)); + + // Order model mapping and lifecycle phase detection (F11). + const open = orderFromIndexer(orderRow({})); + assert.equal(open.giveTokenId, COIN_REF); + assert.equal(open.askTokenId, TOKEN_ID); + assert.equal(orderPhase(open), 'open'); + assert.equal(orderPhase(orderFromIndexer(orderRow({ frozen: true }))), 'frozen'); + assert.equal(orderPhase(orderFromIndexer(orderRow({ giveBalance: { atoms: '0' }, askBalance: { atoms: '0' } }))), 'concluded'); + + // Payout math mirrors mintlayer-core calculate_filled_amount (floor). + assert.equal(proportionalGivePayout('10', '7', '3'), ((10n * 3n) / 7n).toString()); + + // 1. createOrder: order output first, change leg after, id extraction + // rides the bindings on transaction output 0. + { + const h = harness(); + const result = await h.flows.createOrder({ giveTokenId: COIN_REF, giveAtoms: atoms(5n), askTokenId: TOKEN_ID, askAtoms: atoms(2n) }); + assert.match(result.orderId, /^mordr1/); + assert.equal(h.bindings.idCalls.length, 1); + assert.equal(h.bindings.idCalls[0].outputIndex, 0); + assert.ok(h.bindings.idCalls[0].transaction.length > 0); + // The order output encodes once per sizing pass and once for the real + // build; the final encoding carries the real amounts. + assert.ok(h.bindings.orderParams.length >= 2); + assert.deepEqual(h.bindings.orderParams[h.bindings.orderParams.length - 1].give, { tokenId: 'coin', atoms: atoms(5n) }); + assert.deepEqual(h.bindings.orderParams[h.bindings.orderParams.length - 1].ask, { tokenId: TOKEN_ID, atoms: atoms(2n) }); + assert.ok(h.bindings.orderParams.every((p) => p.concludeDestination.length > 0)); + // One payer input (500 ML covers 5 ML + fee), one signed witness. + assert.equal(h.bindings.witnesses.length, 1); + assert.equal(h.bindings.witnesses[0].inputIndex, 0); + assert.equal(bytesToHex(h.bindings.witnesses[0].privateKey), expectedKey); + assert.equal(h.broadcastHexes.length, 1); + // Change counter advanced once and not released (successful order). + assert.equal(h.changeCounter.n, 1); + } + + // 2. Broadcast-disabled (R3) maps to the typed flow error and releases + // the change allocation. + { + const h = harness({ broadcastFails: 'disabled' }); + await assert.rejects( + () => h.flows.createOrder({ giveTokenId: COIN_REF, giveAtoms: atoms(1n), askTokenId: TOKEN_ID, askAtoms: atoms(1n) }), + (e: unknown) => e instanceof OrderFlowError && e.reason === 'broadcast-disabled', + ); + assert.equal(h.changeCounter.n, 0, 'failed attempt steps the change counter back'); + } + + // 3. fillOrder: no-signature witness on the fill input, signed witness on + // the payer input, give payout lands on the destination. + { + const detail = orderRow({ + orderId: ORDER_ID, + giveBalance: { atoms: atoms(10n) }, + askBalance: { atoms: atoms(7n) }, + giveCurrency: { type: 'Coin' }, + askCurrency: { type: 'Token', tokenId: TOKEN_ID }, + }); + const askUtxo = tokenUtxo('cc'.repeat(32), 0, VECTOR_ADDRESS, atoms(4n)); + const h = harness({ detail, utxos: [coinUtxo('aa'.repeat(32), 0, VECTOR_ADDRESS, atoms(500n)), askUtxo] }); + const destination = await mlAddressAt(account.xpub, 0, 1, 'mainnet'); + const result = await h.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(3n), destination }); + assert.match(result.txId, /^[0-9a-f]{64}$/); + assert.equal(h.bindings.fillCalls.length, 1); + assert.equal(h.bindings.fillCalls[0].amount, atoms(3n)); + assert.equal(h.bindings.fillCalls[0].destination, payloadOf(destination)); + assert.equal(h.bindings.fillCalls[0].orderId, payloadOf(ORDER_ID)); + // Witness mix: the fill input at index 0 is unsigned; both payer + // inputs (ask token + fee coin) sign with the wallet key. + assert.equal(h.bindings.noSignatureCount(), 1); + assert.equal(h.bindings.witnesses.length, 2); + assert.deepEqual(h.bindings.witnesses.map((w) => w.inputIndex), [1, 2]); + for (const witness of h.bindings.witnesses) { + assert.equal(bytesToHex(witness.privateKey), expectedKey); + } + // Sighash contract: the spent output rides per input; the order slot + // stays null (no UTXO behind it). + const sighashSlots = h.bindings.witnesses[0].inputUtxos; + assert.equal(sighashSlots?.length, 3); + assert.equal(sighashSlots?.[0], null); + assert.ok((sighashSlots?.[1]?.length ?? 0) > 0); + assert.ok((sighashSlots?.[2]?.length ?? 0) > 0); + // The signed tx text carries the give payout to the destination and the + // ask remainder back to change. + const signedText = new TextDecoder().decode(Buffer.from(h.broadcastHexes[0], 'hex')); + assert.ok(signedText.includes(`T:${(BigInt(atoms(10n)) * BigInt(atoms(3n)) / BigInt(atoms(7n))).toString()}:${destination}`), 'give payout output to destination'); + assert.ok(signedText.includes(`K:${TOKEN_ID}:${atoms(1n)}:mtc1q88834tz8zzhm6x3mhdfgyms5smsv0s7k5mujmzh`), 'ask remainder returns to change'); + } + + // 4. Fill guards: frozen orders, concluded orders and overbids reject + // client-side before any transaction is built. + { + const frozen = orderRow({ frozen: true }); + const h = harness({ detail: frozen }); + await assert.rejects( + () => h.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(1n), destination: VECTOR_ADDRESS }), + (e: unknown) => e instanceof OrderFlowError && e.reason === 'not-open', + ); + const concluded = orderRow({ giveBalance: { atoms: '0' }, askBalance: { atoms: '0' } }); + const h2 = harness({ detail: concluded }); + await assert.rejects( + () => h2.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(1n), destination: VECTOR_ADDRESS }), + (e: unknown) => e instanceof OrderFlowError && e.reason === 'not-open', + ); + const overbid = orderRow({ askBalance: { atoms: atoms(1n) } }); + const h3 = harness({ detail: overbid }); + await assert.rejects( + () => h3.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(2n), destination: VECTOR_ADDRESS }), + (e: unknown) => e instanceof OrderFlowError && e.reason === 'overbid', + ); + } + + // 5. concludeOrder: foreign conclude destination refuses as not-mine; the + // maker path reclaims both legs to the conclude destination. + { + const foreign = orderRow({ concludeDestination: FOREIGN_ADDRESS, giveBalance: { atoms: atoms(4n) }, askBalance: { atoms: atoms(1n) } }); + const h = harness({ detail: foreign }); + await assert.rejects( + () => h.flows.concludeOrder({ orderId: ORDER_ID }), + (e: unknown) => e instanceof OrderFlowError && e.reason === 'not-mine', + ); + + const ours = orderRow({ concludeDestination: VECTOR_ADDRESS, giveBalance: { atoms: atoms(4n) }, askBalance: { atoms: atoms(1n) } }); + const h2 = harness({ detail: ours }); + const result = await h2.flows.concludeOrder({ orderId: ORDER_ID }); + assert.match(result.txId, /^[0-9a-f]{64}$/); + assert.equal(h2.bindings.concludeCalls.length, 1); + assert.equal(h2.bindings.concludeCalls[0].destination, payloadOf(VECTOR_ADDRESS)); + assert.equal(h2.bindings.noSignatureCount(), 1); + assert.equal(h2.bindings.witnesses.length, 1); + assert.equal(bytesToHex(h2.bindings.witnesses[0].privateKey), expectedKey); + const text = new TextDecoder().decode(Buffer.from(h2.broadcastHexes[0], 'hex')); + assert.ok(text.includes(`T:${atoms(4n)}:${VECTOR_ADDRESS}`), 'give remainder reclaims'); + assert.ok(text.includes(`K:${TOKEN_ID}:${atoms(1n)}:${VECTOR_ADDRESS}`), 'accumulated asks reclaim'); + } + + // 6. openOrders and myOrders filters. + { + const mine = orderRow({ orderId: bech32m.encode('mordr', bech32m.toWords(new Uint8Array([0x01]))), concludeDestination: VECTOR_ADDRESS }); + const other = orderRow({ orderId: bech32m.encode('mordr', bech32m.toWords(new Uint8Array([0x02]))), concludeDestination: FOREIGN_ADDRESS }); + const h = harness({ orders: [mine, other] }); + const open = await h.flows.openOrders('ML', 'USDT'); + assert.equal(open.length, 2); + const myOrders = await h.flows.myOrders(); + assert.deepEqual( + myOrders.map((order) => order.orderId), + [mine.orderId], + ); + } + + // 7. Serialization: an overlapping order transaction refuses typed. + { + const h = harness(); + const first = h.flows.createOrder({ giveTokenId: COIN_REF, giveAtoms: atoms(5n), askTokenId: TOKEN_ID, askAtoms: atoms(2n) }); + await assert.rejects( + () => h.flows.createOrder({ giveTokenId: COIN_REF, giveAtoms: atoms(5n), askTokenId: TOKEN_ID, askAtoms: atoms(2n) }), + (e: unknown) => e instanceof OrderFlowError && e.reason === 'busy', + ); + await first; + } + + console.log('orders: ok'); +} + +main(); diff --git a/src/trade/orders.ts b/src/trade/orders.ts new file mode 100644 index 0000000..215bb35 --- /dev/null +++ b/src/trade/orders.ts @@ -0,0 +1,521 @@ +// On-chain order flows (spec M4 deliverable 1, F11 order model): create, +// fill and conclude mapped from the indexer data plus the bindings order +// encoders. An order locks the give amount and asks the ask amount; takers +// pay the fill amount of the ask currency from their own UTXOs and receive +// the proportional give payout (filled = give * fill / ask, floor division; +// orders V1 prices on the original balances, mintlayer-core +// orders-accounting). Conclude returns the leftovers to the conclude +// destination. +// +// Witness mix (F11/rust-sdk docs): fill and conclude order inputs must not +// be signed (encodeWitnessNoSignature); the payer UTXO inputs carry normal +// signed witnesses assembled here with the M3 signing contract (per-input +// spent output for the sighash, keys only inside the vault session). +// +// Every transaction assembles over the MintlayerBindings interface seam. +// Without the native call-through the bindings reject, which surfaces as +// the honest device-pending state (modules/mojito-core header), never a +// JavaScript reimplementation of the encoding. +import { bech32m, hex as hexOf } from '@scure/base'; +import { bytesToHex } from '@noble/hashes/utils.js'; + +import type { MintlayerBindings, MlNetwork } from '../../modules/mojito-core'; +import type { IndexerClient } from '../data/ml/IndexerClient'; +import type { BroadcastProvider } from '../data/providers/types'; +import type { MlOrderInfo, MlUtxo } from '../data/ml/types'; +import type { KeySession } from '../keys/session'; +import { mlAddressAt, mlPrivateKeyFromSeed, mlXpubFromSeed, type MlBranch } from '../keys/mlAccounts'; +import { selectMlInputs, type EstimatedMlOutput, type SelectedMlInput } from '../send/MlTxBuilder'; +import { BroadcastError } from '../data/providers/BroadcastProvider'; + +/** Sentinel marking the base coin (give_token '0' in the F11 docs model; + * the bindings OrderParams spelling is 'coin'). */ +export const COIN_REF = 'coin' as const; + +export type OrderData = { + orderId: string; + /** 'coin' marks the base coin, otherwise the token id. */ + giveTokenId: string; + giveBalanceAtoms: string; + askTokenId: string; + askBalanceAtoms: string; + concludeDestination: string; + nonce: string | null; + /** Maker freeze flag when the indexer serves it; freezes reject fills. */ + frozen: boolean; +}; + +export type OrderPhase = 'open' | 'frozen' | 'concluded'; + +/** Lifecycle phase (F11: open -> frozen -> concluded). Concluded orders + * carry zero balances on both legs; freezing is maker-only and detected + * from the state field. */ +export function orderPhase(order: OrderData): OrderPhase { + if (order.giveBalanceAtoms === '0' && order.askBalanceAtoms === '0') return 'concluded'; + if (order.frozen) return 'frozen'; + return 'open'; +} + +/** Map an indexer order row onto the wallet's order model. */ +export function orderFromIndexer(info: MlOrderInfo): OrderData { + return { + orderId: info.orderId, + giveTokenId: currencyRef(info.giveCurrency), + giveBalanceAtoms: info.giveBalance.atoms ?? '0', + askTokenId: currencyRef(info.askCurrency), + askBalanceAtoms: info.askBalance.atoms ?? '0', + concludeDestination: info.concludeDestination, + nonce: null, + frozen: info.frozen === true, + }; +} + +function currencyRef(side: MlOrderInfo['giveCurrency']): string { + if (side.type === 'Coin') return COIN_REF; + if (side.tokenId !== undefined) return side.tokenId; + throw new OrderFlowError('rejected'); +} + +export interface OrderFlows { + /** Lock the give amount in a new order; the order id comes from the + * bindings on the create tx output. */ + createOrder(params: { giveTokenId: string; giveAtoms: string; askTokenId: string; askAtoms: string }): Promise<{ txId: string; orderId: string }>; + /** Pay fillAtoms of the ask currency into an order; the proportional + * give payout lands on destination. */ + fillOrder(params: { orderId: string; fillAtoms: string; destination: string }): Promise<{ txId: string }>; + /** Close an order (maker only) and return the leftovers to the conclude + * destination. */ + concludeOrder(params: { orderId: string }): Promise<{ txId: string }>; + /** Open orders for one pair (base and quote are tickers or token ids; + * the indexer pair route normalizes direction). */ + openOrders(base: string, quote: string): Promise; + /** Orders whose conclude destination is one of this wallet's addresses. */ + myOrders(): Promise; +} + +export type OrderFlowsConfig = { + network: MlNetwork; + bindings: MintlayerBindings; + indexer: Pick & { + /** Pair-filtered open orders (GET /order/pair/{base}_{quote}). */ + ordersByPair(base: string, quote: string): Promise; + }; + broadcast: BroadcastProvider; + /** All managed ML addresses (selection and the myOrders filter). */ + addresses: () => Promise; + /** Branch 1 change allocation (fresh address per transaction). */ + allocateChangeAddress: () => Promise; + /** Step back the change counter of a failed attempt (realSend pattern). */ + releaseFailedChange: () => Promise; + withSession: (fn: (session: KeySession) => Promise) => Promise; +}; + +const STANDARD_TIER_IN_TOP_MB = 1; + +/** Bounded derivation walk when mapping an input address back to its path; + * aligned with MlTxSigner and the AddressManager scan ceiling. */ +const ORIGIN_WALK_LIMIT = 512; + +export class OrderFlowError extends Error { + constructor( + readonly reason: 'rejected' | 'busy' | 'not-open' | 'overbid' | 'not-mine' | 'broadcast-disabled', + detail?: string, + ) { + super(detail ?? `order flow rejected: ${reason}`); + this.name = 'OrderFlowError'; + } +} + +export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { + /** One order transaction at a time: selection reads live UTXOs and the + * change allocation mutates the persisted counters (realSend pattern). */ + let inFlight = false; + function serialize(fn: () => Promise): Promise { + if (inFlight) return Promise.reject(new OrderFlowError('busy')); + inFlight = true; + return fn().finally(() => { + inFlight = false; + }); + } + + function requireAtomAmount(value: string): string { + if (!/^\d+$/.test(value) || BigInt(value) === 0n) throw new OrderFlowError('rejected', 'amount must be a positive atom string'); + return value; + } + + async function fetchUtxos(): Promise { + const lists: MlUtxo[] = []; + for (const address of await cfg.addresses()) lists.push(...(await cfg.indexer.spendableUtxos(address))); + return lists; + } + + /** Inputs for one selected UTXO: encoded outpoint source plus input. */ + async function utxoInput(selected: SelectedMlInput): Promise { + const sourceId = hexOf.decode(selected.utxo.outpoint.sourceId); + if (sourceId.length !== 32) throw new OrderFlowError('rejected', 'outpoint source id must be 32 bytes'); + const outpointSource = await cfg.bindings.encodeOutpointSourceId( + sourceId, + selected.utxo.outpoint.sourceType === 'BlockReward' ? 'block-reward' : 'transaction', + ); + return cfg.bindings.encodeInputForUtxo(outpointSource, selected.utxo.outpoint.index); + } + + /** Re-encoded spent output of one selected input (M3 sighash contract). */ + async function spentOutput(selected: SelectedMlInput): Promise { + return selected.tokenId === null + ? cfg.bindings.encodeOutputTransfer(selected.atoms, selected.address, cfg.network) + : cfg.bindings.encodeOutputTokenTransfer(selected.tokenId, selected.atoms, selected.address, cfg.network); + } + + /** Sign the payer inputs; prebuilt entries (the no-signature order + * witness at its absolute input index) pass through untouched. */ + async function sign( + transaction: Uint8Array, + payerInputs: SelectedMlInput[], + prebuiltWitnesses: Map, + session: KeySession, + inclusionHeight: number, + ): Promise { + return session.withSeed(async (seed) => { + const { xpub } = mlXpubFromSeed(seed, cfg.network as 'mainnet' | 'testnet'); + const inputCount = payerInputs.length + prebuiltWitnesses.size; + // F8: the sighash needs the spent output per transaction input; + // order inputs carry no spent UTXO (null slot). + const inputUtxos: (Uint8Array | null)[] = []; + let payerWalk = 0; + for (let inputIndex = 0; inputIndex < inputCount; inputIndex++) { + if (prebuiltWitnesses.has(inputIndex)) { + inputUtxos.push(null); + } else { + inputUtxos.push(await spentOutput(payerInputs[payerWalk++])); + } + } + const witnesses: Uint8Array[] = []; + let payerCursor = 0; + for (let inputIndex = 0; inputIndex < inputCount; inputIndex++) { + const prebuilt = prebuiltWitnesses.get(inputIndex); + if (prebuilt !== undefined) { + witnesses.push(prebuilt); + continue; + } + const payer = payerInputs[payerCursor++]; + if (!payer) throw new OrderFlowError('rejected', 'payer input missing'); + const origin = await resolveOrigin(xpub, payer.address); + const privateKey = mlPrivateKeyFromSeed(seed, cfg.network as 'mainnet' | 'testnet', origin.branch, origin.index); + witnesses.push( + await cfg.bindings.encodeWitness({ + sighashType: 'all', + privateKey, + address: payer.address, + transaction, + inputUtxos, + inputIndex, + inclusionHeight, + network: cfg.network, + }), + ); + } + const signed = await cfg.bindings.encodeSignedTransaction(transaction, witnesses); + return bytesToHex(signed); + }); + } + + async function resolveOrigin(xpub: Uint8Array, address: string): Promise<{ branch: MlBranch; index: number }> { + for (const branch of [0, 1] as MlBranch[]) { + for (let index = 0; index < ORIGIN_WALK_LIMIT; index++) { + if ((await mlAddressAt(xpub, branch, index, cfg.network as 'mainnet' | 'testnet')) === address) { + return { branch, index }; + } + } + } + throw new OrderFlowError('rejected', 'input address does not derive from this wallet'); + } + + /** Encode and sign the assembled transaction, then broadcast. */ + async function finish( + inputs: Uint8Array[], + outputs: Uint8Array[], + payerInputs: SelectedMlInput[], + prebuiltWitnesses: Map, + ): Promise<{ txId: string; transaction: Uint8Array }> { + const transaction = await cfg.bindings.encodeTransaction(inputs, outputs, 0); + const localTxId = await cfg.bindings.getTransactionId(transaction, false); + const tip = await cfg.indexer.tip(); + const signedHex = await cfg.withSession((session) => sign(transaction, payerInputs, prebuiltWitnesses, session, tip.blockHeight + 1)); + const result = await cfg.broadcast.broadcastMl(signedHex).catch((e: unknown) => { + if (e instanceof BroadcastError && e.failure === 'disabled') { + throw new OrderFlowError('broadcast-disabled'); + } + throw e; + }); + // A lying backend must not hand back an id that does not match the + // locally computed transaction (M3 finishSend contract). + if (result.txId.toLowerCase() !== localTxId.toLowerCase()) { + throw new OrderFlowError('rejected', `broadcast answered ${result.txId}, locally signed ${localTxId}`); + } + return { transaction, txId: localTxId }; + } + + /** Encoded legs for the fee/change model: order outputs size like their + * transfer counterparts at the M3 estimator convention (zero amounts). */ + function estimateLegs(outputs: EstimatedMlOutput[]): Promise { + return Promise.all( + outputs.map((leg) => + leg.kind === 'coin' + ? cfg.bindings.encodeOutputTransfer('0', leg.address, cfg.network) + : cfg.bindings.encodeOutputTokenTransfer(leg.tokenId ?? '', '0', leg.address, cfg.network), + ), + ); + } + + return { + async createOrder({ giveTokenId, giveAtoms, askTokenId, askAtoms }) { + return serialize(async () => { + requireAtomAmount(giveAtoms); + requireAtomAmount(askAtoms); + const utxos = await fetchUtxos(); + const changeAddress = await cfg.allocateChangeAddress(); + try { + const orderOutput = (giveAmount: string, askAmount: string): Promise => + cfg.bindings.encodeCreateOrderOutput({ + give: { tokenId: giveTokenId === COIN_REF ? 'coin' : giveTokenId, atoms: giveAmount }, + ask: { tokenId: askTokenId === COIN_REF ? 'coin' : askTokenId, atoms: askAmount }, + concludeDestination: changeAddress, + network: cfg.network, + }); + + // Selection: the give leg funds the order output (coin or token), + // the coin pool carries the fee; token remainders return to the + // change address (selectMlInputs models exactly these legs). + const rate = await cfg.indexer.feerate(STANDARD_TIER_IN_TOP_MB); + const selection = await selectMlInputs({ + utxos, + sendAtoms: giveAtoms, + to: changeAddress, + tokenId: giveTokenId === COIN_REF ? null : giveTokenId, + rateAtomsPerKb: rate, + sizeOf: async (inputs, planned) => { + const inputBytes: Uint8Array[] = []; + const destinations: string[] = []; + for (const selected of inputs) { + inputBytes.push(await utxoInput(selected)); + destinations.push(selected.address); + } + const outputBytes = [await orderOutput('0', '0'), ...(await estimateLegs(planned.slice(1)))]; + return cfg.bindings.estimateTransactionSize(inputBytes, destinations, outputBytes, cfg.network); + }, + }); + + const inputs: Uint8Array[] = []; + for (const selected of selection.selection) inputs.push(await utxoInput(selected)); + const outputs: Uint8Array[] = [await orderOutput(giveAtoms, askAtoms)]; + if (giveTokenId !== COIN_REF) { + const tokenSelected = selection.selection + .filter((input) => input.tokenId === giveTokenId) + .reduce((acc, input) => acc + BigInt(input.atoms), 0n); + const tokenRemainder = tokenSelected - BigInt(giveAtoms); + if (tokenRemainder > 0n) { + outputs.push(await cfg.bindings.encodeOutputTokenTransfer(giveTokenId, tokenRemainder.toString(), changeAddress, cfg.network)); + } + } + if (selection.changeAtoms !== '0') { + outputs.push(await cfg.bindings.encodeOutputTransfer(selection.changeAtoms, changeAddress, cfg.network)); + } + + const { txId, transaction } = await finish(inputs, outputs, selection.selection, new Map()); + // The order id is a bindings extraction on the create tx output + // (F11); output 0 is the order output this flow assembled. + const orderId = await cfg.bindings.getOrderId(transaction, 0); + return { txId, orderId }; + } catch (e) { + await cfg.releaseFailedChange(); + throw e; + } + }); + }, + + async fillOrder({ orderId, fillAtoms, destination }) { + return serialize(async () => { + requireAtomAmount(fillAtoms); + const info = await cfg.indexer.order(orderId); + const order = orderFromIndexer(info); + if (orderPhase(order) !== 'open') throw new OrderFlowError('not-open'); + if (BigInt(fillAtoms) > BigInt(order.askBalanceAtoms)) throw new OrderFlowError('overbid'); + + // Proportional give payout (V1 price on the original legs when the + // indexer serves them, current balances on fully-unfilled orders). + const giveLeg = BigInt(info.initiallyGiven?.atoms ?? order.giveBalanceAtoms); + const askLeg = BigInt(info.initiallyAsked?.atoms ?? order.askBalanceAtoms); + const givePayout = ((giveLeg * BigInt(fillAtoms)) / askLeg).toString(); + + const utxos = await fetchUtxos(); + const changeAddress = await cfg.allocateChangeAddress(); + try { + const rate = await cfg.indexer.feerate(STANDARD_TIER_IN_TOP_MB); + // Payer selection: the fill pays the ask currency into the order + // (token leg or coin leg) and covers the fee in coin; the give + // payout is released by the order itself through the fill input. + const selection = await selectMlInputs({ + utxos, + sendAtoms: fillAtoms, + to: changeAddress, + tokenId: order.askTokenId === COIN_REF ? null : order.askTokenId, + rateAtomsPerKb: rate, + sizeOf: async (inputs, planned) => { + const inputBytes: Uint8Array[] = []; + const destinations: string[] = []; + for (const selected of inputs) { + inputBytes.push(await utxoInput(selected)); + destinations.push(selected.address); + } + const outputBytes = await estimateLegs(planned); + return cfg.bindings.estimateTransactionSize(inputBytes, destinations, outputBytes, cfg.network); + }, + }); + + const fillInput = await cfg.bindings.encodeInputForFillOrder( + decodeBech32Data(orderId), + decodeBech32Data(destination), + fillAtoms, + ); + const inputs: Uint8Array[] = [fillInput]; + for (const selected of selection.selection) inputs.push(await utxoInput(selected)); + + const outputs: Uint8Array[] = [ + order.giveTokenId === COIN_REF + ? await cfg.bindings.encodeOutputTransfer(givePayout, destination, cfg.network) + : await cfg.bindings.encodeOutputTokenTransfer(order.giveTokenId, givePayout, destination, cfg.network), + ]; + if (order.askTokenId !== COIN_REF) { + const askSelected = selection.selection + .filter((input) => input.tokenId === order.askTokenId) + .reduce((acc, input) => acc + BigInt(input.atoms), 0n); + const askRemainder = askSelected - BigInt(fillAtoms); + if (askRemainder > 0n) { + outputs.push(await cfg.bindings.encodeOutputTokenTransfer(order.askTokenId, askRemainder.toString(), changeAddress, cfg.network)); + } + } + if (selection.changeAtoms !== '0') { + outputs.push(await cfg.bindings.encodeOutputTransfer(selection.changeAtoms, changeAddress, cfg.network)); + } + + const noSignature = await cfg.bindings.encodeWitnessNoSignature(); + const signedHex = await finishTx(inputs, outputs, selection.selection, new Map([[0, noSignature]])); + const result = await cfg.broadcast.broadcastMl(signedHex); + return { txId: result.txId }; + } catch (e) { + await cfg.releaseFailedChange(); + throw e; + } + }); + }, + + async concludeOrder({ orderId }) { + return serialize(async () => { + const order = orderFromIndexer(await cfg.indexer.order(orderId)); + if (order.concludeDestination === '') throw new OrderFlowError('rejected', 'order has no conclude destination'); + // Maker-only: the conclude destination must be one of ours. + const ours = new Set(await cfg.addresses()); + if (!ours.has(order.concludeDestination)) throw new OrderFlowError('not-mine'); + if (orderPhase(order) === 'concluded') throw new OrderFlowError('not-open'); + + const utxos = await fetchUtxos(); + const changeAddress = await cfg.allocateChangeAddress(); + try { + const rate = await cfg.indexer.feerate(STANDARD_TIER_IN_TOP_MB); + // Fee-only coin selection: conclude reclaims the order balances + // to the conclude destination and pays the fee from our inputs. + const selection = await selectMlInputs({ + utxos, + sendAtoms: '0', + to: changeAddress, + tokenId: null, + rateAtomsPerKb: rate, + sizeOf: async (inputs, planned) => { + const inputBytes: Uint8Array[] = []; + const destinations: string[] = []; + for (const selected of inputs) { + inputBytes.push(await utxoInput(selected)); + destinations.push(selected.address); + } + const outputBytes = await estimateLegs(planned); + return cfg.bindings.estimateTransactionSize(inputBytes, destinations, outputBytes, cfg.network); + }, + }); + + const concludeInput = await cfg.bindings.encodeInputForConcludeOrder( + decodeBech32Data(orderId), + decodeBech32Data(order.concludeDestination), + ); + const inputs: Uint8Array[] = [concludeInput]; + for (const selected of selection.selection) inputs.push(await utxoInput(selected)); + + const outputs: Uint8Array[] = []; + if (order.giveBalanceAtoms !== '0') { + outputs.push( + order.giveTokenId === COIN_REF + ? await cfg.bindings.encodeOutputTransfer(order.giveBalanceAtoms, order.concludeDestination, cfg.network) + : await cfg.bindings.encodeOutputTokenTransfer(order.giveTokenId, order.giveBalanceAtoms, order.concludeDestination, cfg.network), + ); + } + if (order.askBalanceAtoms !== '0') { + outputs.push( + order.askTokenId === COIN_REF + ? await cfg.bindings.encodeOutputTransfer(order.askBalanceAtoms, order.concludeDestination, cfg.network) + : await cfg.bindings.encodeOutputTokenTransfer(order.askTokenId, order.askBalanceAtoms, order.concludeDestination, cfg.network), + ); + } + if (selection.changeAtoms !== '0') { + outputs.push(await cfg.bindings.encodeOutputTransfer(selection.changeAtoms, changeAddress, cfg.network)); + } + + const noSignature = await cfg.bindings.encodeWitnessNoSignature(); + const signedHex = await finishTx(inputs, outputs, selection.selection, new Map([[0, noSignature]])); + const result = await cfg.broadcast.broadcastMl(signedHex); + return { txId: result.txId }; + } catch (e) { + await cfg.releaseFailedChange(); + throw e; + } + }); + }, + + async openOrders(base, quote) { + const rows = await cfg.indexer.ordersByPair(base, quote); + return rows.map(orderFromIndexer); + }, + + async myOrders() { + const ours = new Set(await cfg.addresses()); + const rows = await cfg.indexer.orders(); + return rows.map(orderFromIndexer).filter((order) => ours.has(order.concludeDestination)); + }, + }; + + /** Sign-and-broadcast variant returning only the signed hex (fill and + * conclude carry no bindings id extraction). */ + async function finishTx( + inputs: Uint8Array[], + outputs: Uint8Array[], + payerInputs: SelectedMlInput[], + prebuiltWitnesses: Map, + ): Promise { + const transaction = await cfg.bindings.encodeTransaction(inputs, outputs, 0); + const tip = await cfg.indexer.tip(); + return cfg.withSession((session) => sign(transaction, payerInputs, prebuiltWitnesses, session, tip.blockHeight + 1)); + } +} + +/** give * fill / ask on the given legs, floor division (BigInt mirror of + * mintlayer-core calculate_filled_amount). Exported for the confirm sheet + * to preview the payout before any transaction is built. */ +export function proportionalGivePayout(giveLegAtoms: string, askLegAtoms: string, fillAtoms: string): string { + return ((BigInt(giveLegAtoms) * BigInt(fillAtoms)) / BigInt(askLegAtoms)).toString(); +} + +/** bech32m data payload of an id or address string (the bindings byte-blob + * form for order ids and destinations; Mintlayer encodes m-prefixed ids + * with the bech32m checksum). */ +function decodeBech32Data(value: string): Uint8Array { + return new Uint8Array(bech32m.decode(value).words); +} From ea82ffb55508d1d4353be4d94bf18fbf1b33f9fa Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 06:22:39 +0100 Subject: [PATCH 05/20] feat(m4): ml htlc lock, claim and refund flows --- .../mintlayer/MintlayerBindings.ts | 3 + src/trade/htlc.test.ts | 353 +++++++++++++++ src/trade/htlc.ts | 415 ++++++++++++++++++ 3 files changed, 771 insertions(+) create mode 100644 src/trade/htlc.test.ts create mode 100644 src/trade/htlc.ts diff --git a/modules/mojito-core/mintlayer/MintlayerBindings.ts b/modules/mojito-core/mintlayer/MintlayerBindings.ts index 2b3dc68..e30e439 100644 --- a/modules/mojito-core/mintlayer/MintlayerBindings.ts +++ b/modules/mojito-core/mintlayer/MintlayerBindings.ts @@ -61,6 +61,9 @@ export type WitnessParams = { privateKey: Uint8Array; address: string; transaction: Uint8Array; inputUtxos: (Uint8Array | null)[]; inputIndex: number; additionalInfo?: { tokenId: string }; inclusionHeight: number; network: MlNetwork; + /** F10 reveal field consumed by encodeWitnessHtlcSpend only (M4 atomic + * swap claim): the preimage that satisfies the HTLC hash. */ + secret?: Uint8Array; }; export type OrderParams = { diff --git a/src/trade/htlc.test.ts b/src/trade/htlc.test.ts new file mode 100644 index 0000000..0eccf61 --- /dev/null +++ b/src/trade/htlc.test.ts @@ -0,0 +1,353 @@ +// HTLC flow gate (spec M4 testing section): the lock output encodes the +// F10 parameters, the claim witness rides the revealed secret, the refund +// witness builds the single-sig path and refuses unexpired locks, and the +// secret extraction round-trips on a fixture signed transaction. Offline +// over the recording bindings double (device-pending honest states). +// tsx src/trade/htlc.test.ts +import { strict as assert } from 'node:assert/strict'; + +import { bytesToHex } from '@noble/hashes/utils.js'; +import { hex as hexOf } from '@scure/base'; + +import type { MintlayerBindings, WitnessParams } from '../../modules/mojito-core'; +import type { MlUtxo } from '../data/ml/types'; +import type { BroadcastProvider } from '../data/providers/types'; +import type { KeySession } from '../keys/session'; +import { deriveMlAccount, mlAddressAt, mlPrivateKeyFromSeed } from '../keys/mlAccounts'; +import { mnemonicToSeed } from '../keys/bip39'; +import { TIMELOCK_RULE, createHtlcFlows, secretHashOf, HtlcError } from './htlc'; + +const VECTOR_WORDS = [...Array(23).fill('abandon'), 'art']; +const VECTOR_ADDRESS = 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl'; +const ML = 10n ** 11n; +const atoms = (ml: bigint): string => (ml * ML).toString(); +const SECRET = new Uint8Array(32).fill(0x42); +const SECRET_HASH = secretHashOf(SECRET); +const LOCK_TX_ID = 'aa'.repeat(32); +const SPEND_PUBKEY = new Uint8Array(33).fill(0x02); + +type HtlcJson = { atoms: string; secret_hash: string; spend_address: string; spend_pubkey: string; refund_address: string; refund_timelock: number }; + +function fakeBindings(htlcJson: HtlcJson): MintlayerBindings & { + witnesses: WitnessParams[]; + htlcOutputs: { atoms: string; spendAddress: string; refundAddress: string; timelock: number }[]; + spendWitnesses: WitnessParams[]; + refundWitnesses: WitnessParams[]; + extractCalls: { txId: string; outpoint: string; index: number }[]; +} { + const witnesses: WitnessParams[] = []; + const spendWitnesses: WitnessParams[] = []; + const refundWitnesses: WitnessParams[] = []; + const htlcOutputs: { atoms: string; spendAddress: string; refundAddress: string; timelock: number }[] = []; + const extractCalls: { txId: string; outpoint: string; index: number }[] = []; + const u32 = (value: number): Uint8Array => { + const out = new Uint8Array(4); + new DataView(out.buffer).setUint32(0, value, false); + return out; + }; + const cat = (...parts: Uint8Array[]): Uint8Array => { + const total = parts.reduce((n, p) => n + p.length, 0); + const out = new Uint8Array(total); + let offset = 0; + for (const part of parts) { + out.set(part, offset); + offset += part.length; + } + return out; + }; + const utf8 = (text: string): Uint8Array => new TextEncoder().encode(text); + const u8 = (tag: number): Uint8Array => new Uint8Array([tag]); + return { + witnesses, + spendWitnesses, + refundWitnesses, + htlcOutputs, + extractCalls, + async encodeOutpointSourceId(id32: Uint8Array) { + return cat(u8(0x01), id32); + }, + async encodeInputForUtxo(outpointSource: Uint8Array, index: number) { + return cat(u8(0x02), outpointSource, u32(index)); + }, + async encodeOutputTransfer(atomsStr: string, address: string) { + return utf8(`T:${atomsStr}:${address}`); + }, + async encodeOutputTokenTransfer(tokenId: string, atomsStr: string, address: string) { + return utf8(`K:${tokenId}:${atomsStr}:${address}`); + }, + async encodeOutputHtlc(params: { atoms: string; secretHash: Uint8Array; spendAddress: string; spendPubkey: Uint8Array; refundAddress: string; refundTimelock: number }) { + htlcOutputs.push({ atoms: params.atoms, spendAddress: params.spendAddress, refundAddress: params.refundAddress, timelock: params.refundTimelock }); + return utf8(`H:${params.atoms}:${params.spendAddress}:${params.refundTimelock}`); + }, + async encodeTransaction(inputs: Uint8Array[], outputs: Uint8Array[]) { + return cat(u8(0xee), u8(inputs.length), ...inputs, u8(0xff), u8(outputs.length), ...outputs); + }, + async estimateTransactionSize(inputs: Uint8Array[], destinations: string[], outputs: Uint8Array[]) { + return 100 + 40 * inputs.length + 30 * outputs.length + destinations.length; + }, + async getTransactionId(transaction: Uint8Array) { + return bytesToHex(new Uint8Array(32).fill(0x11)); + }, + async decodeTransactionToJson() { + return JSON.stringify({ outputs: [{ htlc: htlcJson }] }); + }, + async encodeWitness(params: WitnessParams) { + witnesses.push(params); + return utf8(`W:${params.inputIndex}`); + }, + async encodeWitnessHtlcSpend(params: WitnessParams) { + spendWitnesses.push(params); + return utf8(`S:${params.inputIndex}:${bytesToHex(params.secret ?? new Uint8Array())}`); + }, + async encodeWitnessHtlcRefundSingleSig(params: WitnessParams) { + refundWitnesses.push(params); + return utf8(`R:${params.inputIndex}`); + }, + async encodeSignedTransaction(transaction: Uint8Array, txWitnesses: Uint8Array[]) { + return cat(transaction, ...txWitnesses); + }, + async extractHtlcSecret(signedTx: Uint8Array, _strict: boolean, outpointSourceId: Uint8Array, outputIndex: number) { + extractCalls.push({ txId: bytesToHex(signedTx), outpoint: bytesToHex(outpointSourceId), index: outputIndex }); + return SECRET; + }, + } as unknown as MintlayerBindings & { + witnesses: WitnessParams[]; + spendWitnesses: WitnessParams[]; + refundWitnesses: WitnessParams[]; + htlcOutputs: { atoms: string; spendAddress: string; refundAddress: string; timelock: number }[]; + extractCalls: { txId: string; outpoint: string; index: number }[]; + }; +} + +function harness(opts?: { htlcJson?: Partial; lockTimestamp?: number | null; failBroadcast?: boolean }) { + const htlcJson: HtlcJson = { + atoms: atoms(2n), + secret_hash: bytesToHex(SECRET_HASH), + spend_address: VECTOR_ADDRESS, + spend_pubkey: bytesToHex(SPEND_PUBKEY), + refund_address: VECTOR_ADDRESS, + refund_timelock: 172800, + ...opts?.htlcJson, + }; + const bindings = fakeBindings(htlcJson); + const changeCounter = { n: 0 }; + const broadcastHexes: string[] = []; + const utxo = (sourceId: string, amount: string): MlUtxo => ({ + outpoint: { sourceType: 'Transaction', sourceId, index: 0 }, + output: { type: 'Transfer', destination: VECTOR_ADDRESS, value: { type: 'Coin', amount: { atoms: amount } } }, + }); + const indexer = { + async transaction(id: string) { + return { + id, + inputs: [], + outputs: [{ type: 'Htlc', value: { type: 'Coin', amount: { atoms: htlcJson.atoms } } }], + fee: null, + blockId: 'bb'.repeat(32), + timestamp: opts?.lockTimestamp ?? Math.floor(Date.now() / 1000) - 10, + confirmations: 3, + }; + }, + async feerate(): Promise { + return '1000'; + }, + async spendableUtxos(): Promise { + return [utxo('cc'.repeat(32), atoms(10n))]; + }, + async tip() { + return { blockHeight: 12345, blockId: 'aa'.repeat(32) }; + }, + }; + const broadcast: BroadcastProvider = { + async broadcastMl(signedTxHex: string) { + broadcastHexes.push(signedTxHex); + if (opts?.failBroadcast) { + throw Object.assign(new Error('disabled'), { name: 'BroadcastError', failure: 'disabled' }); + } + return { txId: LOCK_TX_ID }; + }, + async broadcastBtc() { + return { txId: LOCK_TX_ID }; + }, + async getMlStatus() { + return { state: 'pending' as const }; + }, + async getBtcStatus() { + return { state: 'pending' as const }; + }, + }; + const flows = createHtlcFlows({ + network: 'mainnet', + bindings, + indexer: indexer as never, + broadcast, + addresses: async () => [VECTOR_ADDRESS], + allocateChangeAddress: async () => VECTOR_ADDRESS, + releaseFailedChange: async () => { + changeCounter.n = Math.max(0, changeCounter.n - 1); + }, + withSession: async (fn: (session: KeySession) => Promise): Promise => { + const seed = await mnemonicToSeed(VECTOR_WORDS); + return fn({ withSeed: (run: (s: Uint8Array) => Promise) => run(seed) } as unknown as KeySession); + }, + }); + return { flows, bindings, broadcastHexes, changeCounter }; +} + +async function main() { + const account = await deriveMlAccount(VECTOR_WORDS, 'mainnet'); + assert.equal(await mlAddressAt(account.xpub, 0, 0, 'mainnet'), VECTOR_ADDRESS, 'parity vector address'); + const seed = await mnemonicToSeed(VECTOR_WORDS); + const expectedKey = bytesToHex(mlPrivateKeyFromSeed(seed, 'mainnet', 0, 0)); + + // TIMELOCK_RULE is the recorded F10 string. + assert.equal(TIMELOCK_RULE, 'btc timelock must be shorter than the mintlayer timelock (F10)'); + + // 1. initiate: the lock output encodes the F10 parameters; the signed + // lock tx broadcasts and the outpoint rides the tx id. + { + const h = harness(); + const result = await h.flows.initiate( + { role: 'initiator', giveChain: 'ml', giveAtoms: atoms(2n), wantAtoms: atoms(560n), secretHash: SECRET_HASH, timelockSeconds: 172800 }, + { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }, + VECTOR_ADDRESS, + ); + assert.equal(result.txId, LOCK_TX_ID); + assert.deepEqual(result.htlcOutpoint.id, hexOf.decode(LOCK_TX_ID)); + assert.equal(result.htlcOutpoint.index, 0); + // The final (real-build) HTLC output encoding carries the lock params. + const lock = h.bindings.htlcOutputs[h.bindings.htlcOutputs.length - 1]; + assert.equal(lock.atoms, atoms(2n)); + assert.equal(lock.spendAddress, VECTOR_ADDRESS); + assert.equal(lock.refundAddress, VECTOR_ADDRESS); + assert.equal(lock.timelock, 172800); + // Payer inputs sign normally (no secret on the lock leg). + assert.equal(h.bindings.witnesses.length, 1); + assert.equal(bytesToHex(h.bindings.witnesses[0].privateKey), expectedKey); + assert.equal(h.bindings.witnesses[0].secret, undefined); + assert.equal(h.broadcastHexes.length, 1); + } + + // 2. Guard rails: bad hash length, zero amounts and busy serialization. + { + const h = harness(); + await assert.rejects( + () => + h.flows.initiate( + { role: 'initiator', giveChain: 'ml', giveAtoms: atoms(1n), wantAtoms: '1', secretHash: SECRET_HASH.subarray(0, 16), timelockSeconds: 3600 }, + { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }, + VECTOR_ADDRESS, + ), + (e: unknown) => e instanceof HtlcError && e.reason === 'rejected', + ); + await assert.rejects( + () => h.flows.initiate( + { role: 'initiator', giveChain: 'ml', giveAtoms: '0', wantAtoms: '1', secretHash: SECRET_HASH, timelockSeconds: 3600 }, + { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }, + VECTOR_ADDRESS, + ), + (e: unknown) => e instanceof HtlcError && e.reason === 'rejected', + ); + const first = h.flows.claim(LOCK_TX_ID, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }); + await assert.rejects( + () => h.flows.claim(LOCK_TX_ID, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }), + (e: unknown) => e instanceof HtlcError && e.reason === 'busy', + ); + await first; + } + + // 3. claim: the spend witness carries the preimage and signs against the + // re-encoded HTLC output; the payout is the lock minus the fee. + { + const h = harness(); + const result = await h.flows.claim(LOCK_TX_ID, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }); + assert.equal(result.txId, LOCK_TX_ID); + assert.equal(h.bindings.spendWitnesses.length, 1); + const witness = h.bindings.spendWitnesses[0]; + assert.equal(bytesToHex(witness.secret ?? new Uint8Array()), bytesToHex(SECRET)); + assert.equal(bytesToHex(witness.privateKey), expectedKey); + assert.equal(witness.inputIndex, 0); + assert.equal(witness.inputUtxos?.length, 1); + assert.ok(witness.inputUtxos?.[0]); + const text = new TextDecoder().decode(Buffer.from(h.broadcastHexes[0], 'hex')); + assert.ok(text.includes(`S:0:${bytesToHex(SECRET)}`), 'the claim witness reveals the preimage'); + assert.ok(text.includes('T:'), 'the payout output lands on the spend address'); + } + + // 4. refund: unexpired locks refuse typed; after expiry the single-sig + // refund witness builds. + { + const h = harness({ lockTimestamp: Math.floor(Date.now() / 1000) - 10 }); + await assert.rejects( + () => h.flows.refund(LOCK_TX_ID), + (e: unknown) => e instanceof HtlcError && e.reason === 'not-expired', + ); + const expired = harness({ lockTimestamp: Math.floor(Date.now() / 1000) - 172_801 }); + const result = await expired.flows.refund(LOCK_TX_ID); + assert.equal(result.txId, LOCK_TX_ID); + assert.equal(expired.bindings.refundWitnesses.length, 1); + assert.equal(expired.bindings.refundWitnesses[0].inputIndex, 0); + assert.equal(bytesToHex(expired.bindings.refundWitnesses[0].privateKey), expectedKey); + } + + // 5. extractSecret: the bindings extraction consumes the raw signed tx + // and outpoint bytes and answers the preimage (roundtrip with the + // fixture claim). + { + const h = harness(); + const fixtureSignedTx = new Uint8Array([0xde, 0xad, 0xbe, 0xef, 0x00]); + const secret = await h.flows.extractSecret(fixtureSignedTx, { id: hexOf.decode(LOCK_TX_ID), index: 0 }); + assert.equal(bytesToHex(secret), bytesToHex(SECRET)); + assert.deepEqual(h.bindings.extractCalls[0], { txId: 'deadbeef00', outpoint: LOCK_TX_ID, index: 0 }); + assert.equal(bytesToHex(secretHashOf(secret)), bytesToHex(SECRET_HASH), 'the extracted preimage hashes to the offered secret hash'); + } + + // 6. A transaction with no HTLC output is a typed refusal, not a claim. + { + const bindings = fakeBindings({ + atoms: atoms(2n), + secret_hash: bytesToHex(SECRET_HASH), + spend_address: VECTOR_ADDRESS, + spend_pubkey: bytesToHex(SPEND_PUBKEY), + refund_address: VECTOR_ADDRESS, + refund_timelock: 172800, + }); + const indexer = { + async transaction() { + return { id: LOCK_TX_ID, inputs: [], outputs: [{ type: 'Transfer', value: { type: 'Coin', amount: { atoms: atoms(2n) } } }], fee: null, blockId: null, timestamp: null, confirmations: null }; + }, + async feerate() { + return '1000'; + }, + async spendableUtxos() { + return []; + }, + async tip() { + return { blockHeight: 1, blockId: 'aa'.repeat(32) }; + }, + }; + const flows = createHtlcFlows({ + network: 'mainnet', + bindings, + indexer: indexer as never, + broadcast: { + broadcastMl: async () => ({ txId: LOCK_TX_ID }), + broadcastBtc: async () => ({ txId: LOCK_TX_ID }), + getMlStatus: async () => ({ state: 'pending' }), + getBtcStatus: async () => ({ state: 'pending' }), + }, + addresses: async () => [VECTOR_ADDRESS], + allocateChangeAddress: async () => VECTOR_ADDRESS, + releaseFailedChange: async () => undefined, + withSession: async (fn) => fn({ withSeed: (run: (s: Uint8Array) => Promise) => run(seed) } as unknown as KeySession), + }); + await assert.rejects( + () => flows.claim(LOCK_TX_ID, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }), + (e: unknown) => e instanceof HtlcError && e.reason === 'no-htlc-output', + ); + } + + console.log('htlc: ok'); +} + +main(); diff --git a/src/trade/htlc.ts b/src/trade/htlc.ts new file mode 100644 index 0000000..dce4153 --- /dev/null +++ b/src/trade/htlc.ts @@ -0,0 +1,415 @@ +// ML-side HTLC lifecycle (spec M4 deliverable 3, F10 atomic swap model): +// lock Mintlayer with the secret hash, claim by revealing the preimage, +// refund after the timelock, and extract a revealed secret from a signed +// claim transaction. The counterparty BTC side is the demo counterpart +// (scripts/e2e-testnet.mjs documents the scripted flow); this module owns +// the Mintlayer legs. +// +// Secret handling (spec security note): the preimage is generated with +// MojitoCore.secureRandom by the caller (createSwapSecret), held in memory +// inside the session closure and never persisted and never logged; only +// SHA-256(secret) crosses the wire and storage. TIMELOCK_RULE guards the +// initiate path: the BTC timelock must be shorter than the ML one. +// +// Honest states: every transaction assembles and signs through the +// MintlayerBindings seam, so without the native call-through the flows +// reject with the device-pending bindings error, never a fabricated +// success. +import { hex as hexOf } from '@scure/base'; +import { bytesToHex } from '@noble/hashes/utils.js'; +import { sha256 } from '@noble/hashes/sha2.js'; + +import type { MintlayerBindings, MlNetwork } from '../../modules/mojito-core'; +import type { IndexerClient } from '../data/ml/IndexerClient'; +import type { BroadcastProvider } from '../data/providers/types'; +import type { MlTransaction } from '../data/ml/types'; +import type { KeySession } from '../keys/session'; +import { mlAddressAt, mlPrivateKeyFromSeed, mlXpubFromSeed, type MlBranch } from '../keys/mlAccounts'; +import { selectMlInputs } from '../send/MlTxBuilder'; +import { BroadcastError } from '../data/providers/BroadcastProvider'; + +/** F10: the Bitcoin timelock must be shorter than the Mintlayer one. */ +export const TIMELOCK_RULE = 'btc timelock must be shorter than the mintlayer timelock (F10)'; + +export type HtlcOffer = { + role: 'initiator' | 'counterparty'; + giveChain: 'ml' | 'btc'; + giveAtoms: string; + wantAtoms: string; + /** SHA-256 of the preimage; the preimage itself never rides an offer. */ + secretHash: Uint8Array; + timelockSeconds: number; +}; + +export type HtlcSpend = { address: string; pubkey: Uint8Array }; + +export interface HtlcFlows { + /** Lock the offer's giveAtoms on Mintlayer with the counterparty's spend + * key and our refund path (the initiator leg of the swap). */ + initiate(offer: HtlcOffer, spend: HtlcSpend, refundAddress: string): Promise<{ txId: string; htlcOutpoint: { id: Uint8Array; index: number } }>; + /** Spend an HTLC with the revealed secret (the counterparty claim leg). */ + claim(htlcTxId: string, secret: Uint8Array, spend: HtlcSpend): Promise<{ txId: string }>; + /** Reclaim after the timelock expiry (refund path, single sig). */ + refund(htlcTxId: string): Promise<{ txId: string }>; + /** Extract a revealed preimage from a signed claim transaction. The raw + * bytes come from the caller: the public Mintlayer indexer serves no raw + * transaction route, so a txId-only signature cannot honestly fetch what + * the bindings extraction consumes (the demo script and the BTC claim + * path both carry the bytes; see scripts/e2e-testnet.mjs). */ + extractSecret(rawSignedTx: Uint8Array, htlcOutpoint: { id: Uint8Array; index: number }): Promise; +} + +export type HtlcFlowsConfig = { + network: MlNetwork; + bindings: MintlayerBindings; + indexer: Pick; + broadcast: BroadcastProvider; + addresses: () => Promise; + allocateChangeAddress: () => Promise; + releaseFailedChange: () => Promise; + withSession: (fn: (session: KeySession) => Promise) => Promise; +}; + +const STANDARD_TIER_IN_TOP_MB = 1; +const ORIGIN_WALK_LIMIT = 512; + +export class HtlcError extends Error { + constructor( + readonly reason: 'rejected' | 'busy' | 'not-expired' | 'no-htlc-output' | 'broadcast-disabled', + detail?: string, + ) { + super(detail ?? `htlc flow rejected: ${reason}`); + this.name = 'HtlcError'; + } +} + +export type HtlcDescriptor = { + txId: string; + outputIndex: number; + atoms: string; + secretHash: Uint8Array; + spendAddress: string; + spendPubkey: Uint8Array; + refundAddress: string; + refundTimelock: number; +}; + +export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { + let inFlight = false; + function serialize(fn: () => Promise): Promise { + if (inFlight) return Promise.reject(new HtlcError('busy')); + inFlight = true; + return fn().finally(() => { + inFlight = false; + }); + } + + function requireAtomAmount(value: string): string { + if (!/^\d+$/.test(value) || BigInt(value) === 0n) throw new HtlcError('rejected', 'amount must be a positive atom string'); + return value; + } + + async function fetchUtxos() { + const lists = []; + for (const address of await cfg.addresses()) lists.push(...(await cfg.indexer.spendableUtxos(address))); + return lists; + } + + async function utxoInput(sourceIdHex: string, index: number): Promise { + const sourceId = hexOf.decode(sourceIdHex); + if (sourceId.length !== 32) throw new HtlcError('rejected', 'outpoint source id must be 32 bytes'); + const outpointSource = await cfg.bindings.encodeOutpointSourceId(sourceId, 'transaction'); + return cfg.bindings.encodeInputForUtxo(outpointSource, index); + } + + async function sign( + transaction: Uint8Array, + inputs: { address: string }[], + spentOutputs: Uint8Array[], + session: KeySession, + inclusionHeight: number, + secret?: Uint8Array, + ): Promise { + return session.withSeed(async (seed) => { + const { xpub } = mlXpubFromSeed(seed, cfg.network as 'mainnet' | 'testnet'); + const witnesses: Uint8Array[] = []; + for (let inputIndex = 0; inputIndex < inputs.length; inputIndex++) { + const origin = await resolveOrigin(xpub, inputs[inputIndex].address); + const privateKey = mlPrivateKeyFromSeed(seed, cfg.network as 'mainnet' | 'testnet', origin.branch, origin.index); + const params = { + sighashType: 'all' as const, + privateKey, + address: inputs[inputIndex].address, + transaction, + inputUtxos: spentOutputs, + inputIndex, + inclusionHeight, + network: cfg.network, + ...(secret !== undefined && inputs.length === 1 ? { secret } : {}), + }; + witnesses.push( + inputs.length === 1 && secret !== undefined + ? await cfg.bindings.encodeWitnessHtlcSpend(params) + : await cfg.bindings.encodeWitness(params), + ); + } + const signed = await cfg.bindings.encodeSignedTransaction(transaction, witnesses); + return bytesToHex(signed); + }); + } + + async function resolveOrigin(xpub: Uint8Array, address: string): Promise<{ branch: MlBranch; index: number }> { + for (const branch of [0, 1] as MlBranch[]) { + for (let index = 0; index < ORIGIN_WALK_LIMIT; index++) { + if ((await mlAddressAt(xpub, branch, index, cfg.network as 'mainnet' | 'testnet')) === address) { + return { branch, index }; + } + } + } + throw new HtlcError('rejected', 'input address does not derive from this wallet'); + } + + async function broadcast(signedHex: string): Promise { + try { + const result = await cfg.broadcast.broadcastMl(signedHex); + return result.txId; + } catch (e) { + if (e instanceof BroadcastError && e.failure === 'disabled') throw new HtlcError('broadcast-disabled'); + throw e; + } + } + + /** Describe an on-chain HTLC output through the bindings decode seam: + * the indexer gives the output position, the bindings decode restores + * the lock parameters the claim and refund legs must rebuild. */ + async function describeHtlc(htlcTxId: string): Promise { + let tx: MlTransaction; + try { + tx = await cfg.indexer.transaction(htlcTxId); + } catch { + throw new HtlcError('no-htlc-output', `htlc transaction ${htlcTxId} is not readable`); + } + const outputIndex = tx.outputs.findIndex((output: { type: string }) => output.type === 'Htlc'); + if (outputIndex < 0) throw new HtlcError('no-htlc-output', `transaction ${htlcTxId} carries no HTLC output`); + // The decode seam restores the lock parameters from the raw + // transaction; bindings stub rejections surface as the honest + // device-pending state, never a guessed descriptor. + const json = await cfg.bindings.decodeTransactionToJson(hexOf.decode(htlcTxId), cfg.network); + const parsed = JSON.parse(json) as { + outputs?: { htlc?: { atoms?: string; secret_hash?: string; spend_address?: string; spend_pubkey?: string; refund_address?: string; refund_timelock?: number } }[]; + }; + const htlc = parsed.outputs?.[outputIndex]?.htlc; + if (!htlc?.atoms || htlc.secret_hash === undefined || htlc.spend_address === undefined) { + throw new HtlcError('no-htlc-output', 'the bindings decode did not restore the lock parameters'); + } + return { + txId: htlcTxId, + outputIndex, + atoms: htlc.atoms, + secretHash: hexOf.decode(htlc.secret_hash), + spendAddress: htlc.spend_address, + spendPubkey: hexOf.decode(htlc.spend_pubkey ?? ''), + refundAddress: htlc.refund_address ?? '', + refundTimelock: htlc.refund_timelock ?? 0, + }; + } + + return { + async initiate({ giveAtoms, secretHash, timelockSeconds }, spend, refundAddress) { + return serialize(async () => { + requireAtomAmount(giveAtoms); + if (secretHash.length !== 32) throw new HtlcError('rejected', 'the secret hash must be 32 bytes (SHA-256)'); + if (!Number.isInteger(timelockSeconds) || timelockSeconds <= 0) throw new HtlcError('rejected', 'the refund timelock must be a positive second count'); + const utxos = await fetchUtxos(); + const changeAddress = await cfg.allocateChangeAddress(); + try { + const rate = await cfg.indexer.feerate(STANDARD_TIER_IN_TOP_MB); + const selection = await selectMlInputs({ + utxos, + sendAtoms: giveAtoms, + to: changeAddress, + tokenId: null, + rateAtomsPerKb: rate, + sizeOf: async (inputs, planned) => { + const inputBytes: Uint8Array[] = []; + const destinations: string[] = []; + for (const selected of inputs) { + inputBytes.push(await utxoInput(selected.utxo.outpoint.sourceId, selected.utxo.outpoint.index)); + destinations.push(selected.address); + } + const outputBytes: Uint8Array[] = [ + await cfg.bindings.encodeOutputHtlc({ + atoms: '0', + secretHash, + spendAddress: spend.address, + spendPubkey: spend.pubkey, + refundAddress, + refundTimelock: timelockSeconds, + }), + ...(await Promise.all( + planned.slice(1).map((leg) => cfg.bindings.encodeOutputTransfer('0', leg.address, cfg.network)), + )), + ]; + return cfg.bindings.estimateTransactionSize(inputBytes, destinations, outputBytes, cfg.network); + }, + }); + + const inputs: Uint8Array[] = []; + const spentOutputs: Uint8Array[] = []; + for (const selected of selection.selection) { + inputs.push(await utxoInput(selected.utxo.outpoint.sourceId, selected.utxo.outpoint.index)); + spentOutputs.push( + selected.tokenId === null + ? await cfg.bindings.encodeOutputTransfer(selected.atoms, selected.address, cfg.network) + : await cfg.bindings.encodeOutputTokenTransfer(selected.tokenId, selected.atoms, selected.address, cfg.network), + ); + } + const outputs: Uint8Array[] = [ + await cfg.bindings.encodeOutputHtlc({ + atoms: giveAtoms, + secretHash, + spendAddress: spend.address, + spendPubkey: spend.pubkey, + refundAddress, + refundTimelock: timelockSeconds, + }), + ]; + if (selection.changeAtoms !== '0') { + outputs.push(await cfg.bindings.encodeOutputTransfer(selection.changeAtoms, changeAddress, cfg.network)); + } + + const transaction = await cfg.bindings.encodeTransaction(inputs, outputs, 0); + const tip = await cfg.indexer.tip(); + const signedHex = await cfg.withSession((session) => sign(transaction, selection.selection, spentOutputs, session, tip.blockHeight + 1)); + const txId = await broadcast(signedHex); + // The HTLC outpoint rides the lock tx id and its output index + // (the HTLC output is assembled at index 0 of this flow). + return { txId, htlcOutpoint: { id: hexOf.decode(txId), index: 0 } }; + } catch (e) { + await cfg.releaseFailedChange(); + throw e; + } + }); + }, + + async claim(htlcTxId, secret, spend) { + return serialize(async () => { + if (secret.length !== 32) throw new HtlcError('rejected', 'the preimage must be 32 bytes'); + const descriptor = await describeHtlc(htlcTxId); + const fee = await claimFee(htlcTxId, spend.address); + const payout = BigInt(descriptor.atoms) - fee; + if (payout <= 0n) throw new HtlcError('rejected', 'the lock cannot cover the claim fee'); + const htlcInput = await utxoInput(htlcTxId, descriptor.outputIndex); + const htlcOutputBytes = await cfg.bindings.encodeOutputHtlc({ + atoms: descriptor.atoms, + secretHash: descriptor.secretHash, + spendAddress: descriptor.spendAddress, + spendPubkey: descriptor.spendPubkey, + refundAddress: descriptor.refundAddress, + refundTimelock: descriptor.refundTimelock, + }); + const inputs = [htlcInput]; + const outputs = [await cfg.bindings.encodeOutputTransfer(payout.toString(), spend.address, cfg.network)]; + const transaction = await cfg.bindings.encodeTransaction(inputs, outputs, 0); + const tip = await cfg.indexer.tip(); + // The HTLC spend witness signs against the HTLC output (the spent + // output of the single input) and reveals the preimage (F10). + const signedHex = await cfg.withSession((session) => + signWithKey(transaction, spend.address, [htlcOutputBytes], session, tip.blockHeight + 1, secret, 'htlc-spend'), + ); + return { txId: await broadcast(signedHex) }; + }); + }, + + async refund(htlcTxId) { + return serialize(async () => { + const descriptor = await describeHtlc(htlcTxId); + // Refunds unlock at the timelock expiry; the lock timestamp plus + // the timelock must already be in the past, otherwise the refund + // would be rejected by the chain: honest typed refusal first. + const tx = await cfg.indexer.transaction(htlcTxId); + const lockedAt = tx.timestamp ?? 0; + if (lockedAt + descriptor.refundTimelock > Math.floor(Date.now() / 1000)) { + throw new HtlcError('not-expired', 'the refund unlocks after the timelock expiry'); + } + const fee = await claimFee(htlcTxId, descriptor.refundAddress); + const payout = BigInt(descriptor.atoms) - fee; + if (payout <= 0n) throw new HtlcError('rejected', 'the lock cannot cover the refund fee'); + const htlcInput = await utxoInput(htlcTxId, descriptor.outputIndex); + const htlcOutputBytes = await cfg.bindings.encodeOutputHtlc({ + atoms: descriptor.atoms, + secretHash: descriptor.secretHash, + spendAddress: descriptor.spendAddress, + spendPubkey: descriptor.spendPubkey, + refundAddress: descriptor.refundAddress, + refundTimelock: descriptor.refundTimelock, + }); + const inputs = [htlcInput]; + const outputs = [await cfg.bindings.encodeOutputTransfer(payout.toString(), descriptor.refundAddress, cfg.network)]; + const transaction = await cfg.bindings.encodeTransaction(inputs, outputs, 0); + const tip = await cfg.indexer.tip(); + const signedHex = await cfg.withSession((session) => + signWithKey(transaction, descriptor.refundAddress, [htlcOutputBytes], session, tip.blockHeight + 1, undefined, 'htlc-refund'), + ); + return { txId: await broadcast(signedHex) }; + }); + }, + + async extractSecret(rawSignedTx, htlcOutpoint) { + return cfg.bindings.extractHtlcSecret(rawSignedTx, false, htlcOutpoint.id, htlcOutpoint.index); + }, + }; + + /** Claim and refund build against a fee estimate of the same shape: one + * HTLC input, one payout output, standard tier rate. */ + async function claimFee(htlcTxId: string, destination: string): Promise { + const rate = await cfg.indexer.feerate(STANDARD_TIER_IN_TOP_MB); + const input = await utxoInput(htlcTxId, 0); + const output = await cfg.bindings.encodeOutputTransfer('0', destination, cfg.network); + const size = await cfg.bindings.estimateTransactionSize([input], [destination], [output], cfg.network); + const kbCeil = BigInt(Math.max(1, Math.ceil(size / 1000))); + const rateBig = BigInt(/^\d+$/.test(rate) ? rate : '0'); + return kbCeil * (rateBig > 1n ? rateBig : 1n); + } + + /** Single-input HTLC signing over the dedicated witness encoders (the + * normal encodeWitness path cannot carry the preimage). */ + async function signWithKey( + transaction: Uint8Array, + address: string, + spentOutputs: Uint8Array[], + session: KeySession, + inclusionHeight: number, + secret: Uint8Array | undefined, + kind: 'htlc-spend' | 'htlc-refund', + ): Promise { + return session.withSeed(async (seed) => { + const { xpub } = mlXpubFromSeed(seed, cfg.network as 'mainnet' | 'testnet'); + const origin = await resolveOrigin(xpub, address); + const privateKey = mlPrivateKeyFromSeed(seed, cfg.network as 'mainnet' | 'testnet', origin.branch, origin.index); + const params = { + sighashType: 'all' as const, + privateKey, + address, + transaction, + inputUtxos: spentOutputs, + inputIndex: 0, + inclusionHeight, + network: cfg.network, + ...(secret !== undefined ? { secret } : {}), + }; + const witness = + kind === 'htlc-spend' + ? await cfg.bindings.encodeWitnessHtlcSpend(params) + : await cfg.bindings.encodeWitnessHtlcRefundSingleSig(params); + const signed = await cfg.bindings.encodeSignedTransaction(transaction, [witness]); + return bytesToHex(signed); + }); + } +} + +/** SHA-256 of the swap preimage (the only form that crosses the wire or + * storage; the preimage itself never persists and never logs). */ +export function secretHashOf(secret: Uint8Array): Uint8Array { + return sha256(secret); +} From 667ed91676b419b4f2794465ca3cf27f501c3e3d Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 06:23:52 +0100 Subject: [PATCH 06/20] feat(m4): persisted swap sessions with honest transitions --- src/storage/keys.ts | 4 + src/trade/swapSession.test.ts | 125 ++++++++++++++++++++++++++++ src/trade/swapSession.ts | 148 ++++++++++++++++++++++++++++++++++ 3 files changed, 277 insertions(+) create mode 100644 src/trade/swapSession.test.ts create mode 100644 src/trade/swapSession.ts diff --git a/src/storage/keys.ts b/src/storage/keys.ts index 43ca86e..5fa72e0 100644 --- a/src/storage/keys.ts +++ b/src/storage/keys.ts @@ -10,6 +10,10 @@ export const STORAGE_KEYS = { waitlistEmail: 'waitlist.email.v1', // Public per-chain derivation indexes (receiving/change); never secrets. addressIndex: 'address.index.v1', + // Persisted atomic swap sessions (state machine rows). The swap preimage + // is high-value material and NEVER persists; rows carry the secret hash + // and tx ids only (spec M4 security note). + swapSessions: 'swap.sessions.v1', // Not a sealed-store key: the plain settings JSON read by appSettings. settings: 'settings.v1', } as const; diff --git a/src/trade/swapSession.test.ts b/src/trade/swapSession.test.ts new file mode 100644 index 0000000..cccdfb8 --- /dev/null +++ b/src/trade/swapSession.test.ts @@ -0,0 +1,125 @@ +// Swap session store gate (spec M4 testing section): state machine +// transitions, persistence round-trip, corrupt-row dropping and the +// no-preimage guarantee (only the secret hash ever persists). +// tsx src/trade/swapSession.test.ts +import { strict as assert } from 'node:assert/strict'; + +import { bytesToHex } from '@noble/hashes/utils.js'; + +import { canTransition, assertTransition, createSwapSessionStore, parseSwapSessions, type SwapSessionRow, type SwapState } from './swapSession'; +import type { HtlcOffer } from './htlc'; + +const OFFER: HtlcOffer = { + role: 'initiator', + giveChain: 'ml', + giveAtoms: '2000000000000', + wantAtoms: '560000000000000', + secretHash: new Uint8Array(32).fill(0x21), + timelockSeconds: 172800, +}; + +const row = (overrides?: Partial): SwapSessionRow => ({ + id: 'swap-1', + offer: OFFER, + secretHashHex: bytesToHex(new Uint8Array(32).fill(0x21)), + spendAddress: 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl', + spendPubkeyHex: '02'.repeat(33), + refundAddress: 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl', + state: 'offered', + txIds: [], + updatedAt: 1700000000000, + ...overrides, +}); + +/** Scripted storage backend recording writes (offline; no AsyncStorage). */ +function memoryStorage() { + const state: { json: string | null } = { json: null }; + return { + storage: { + async load() { + return state.json; + }, + async save(json: string) { + state.json = json; + }, + }, + json: () => state.json, + }; +} + +async function main() { + // Transition table: the happy path and the honest alternates. + assert.ok(canTransition('offered', 'locked')); + assert.ok(canTransition('locked', 'claiming')); + assert.ok(canTransition('locked', 'refunded')); + assert.ok(canTransition('locked', 'expired')); + assert.ok(canTransition('claiming', 'settled')); + assert.ok(canTransition('claiming', 'refunded')); + assert.ok(!canTransition('offered', 'settled'), 'a swap never skips the lock'); + assert.ok(!canTransition('settled', 'claiming'), 'terminal states are terminal'); + assert.throws(() => assertTransition('expired', 'locked'), /invalid swap transition/); + + // Persistence round-trip over the scripted backend. + { + const backend = memoryStorage(); + const store = createSwapSessionStore(backend.storage); + await store.save(row({ state: 'offered' })); + await store.save(row({ id: 'swap-2', state: 'locked', txIds: ['aa'.repeat(32)], updatedAt: 1700000001000 })); + const all = await store.all(); + assert.equal(all.length, 2); + assert.equal(all[0].id, 'swap-2', 'newest first'); + assert.equal(all[0].state, 'locked'); + const one = await store.get('swap-1'); + assert.equal(one?.state, 'offered'); + assert.equal(await store.get('missing'), null); + + // Restart path: a fresh store over the same backend restores rows. + const reopened = createSwapSessionStore(backend.storage); + assert.equal((await reopened.all()).length, 2); + await reopened.remove('swap-1'); + assert.deepEqual((await reopened.all()).map((r) => r.id), ['swap-2']); + } + + // The persisted JSON carries the secret hash only: the raw preimage + // bytes must never appear in storage. + { + const backend = memoryStorage(); + const store = createSwapSessionStore(backend.storage); + await store.save(row()); + const json = backend.json() ?? ''; + assert.ok(json.includes(bytesToHex(new Uint8Array(32).fill(0x21))), 'the secret hash persists'); + assert.ok(!json.includes('preimage'), 'no preimage field ever persists'); + assert.ok(!('secret' in JSON.parse(json)[0].offer)); + } + + // Corrupt stores drop bad rows instead of wedging the machine: garbage + // JSON, non-rows, a bad secret-hash shape, an unknown state. + assert.deepEqual(parseSwapSessions(null), []); + assert.deepEqual(parseSwapSessions('not json'), []); + assert.deepEqual(parseSwapSessions('{"a":1}'), []); + const good = row(); + const badHash = row({ id: 'bad-hash', secretHashHex: 'zz' }); + const badState = row({ id: 'bad-state', state: 'cancelled' as SwapState }); + const tooManyTxIds = row({ id: 'bad-txids', txIds: Array.from({ length: 20 }, () => 'aa') }); + const mixed = JSON.stringify([good, badHash, badState, tooManyTxIds]); + const parsed = parseSwapSessions(mixed); + assert.deepEqual( + parsed.map((r) => r.id), + ['swap-1'], + ); + + // Session cap: a hostile store cannot force unbounded memory. + const many = Array.from({ length: 40 }, (_, i) => row({ id: `s${i}` })); + assert.equal(parseSwapSessions(JSON.stringify(many)).length, 32); + + // Unknown states refuse to save. + { + const backend = memoryStorage(); + const store = createSwapSessionStore(backend.storage); + await assert.rejects(() => store.save(row({ state: 'cancelled' as SwapState })), /unknown swap state/); + } + + console.log('swapSession: ok'); +} + +main(); diff --git a/src/trade/swapSession.ts b/src/trade/swapSession.ts new file mode 100644 index 0000000..cb9ca6b --- /dev/null +++ b/src/trade/swapSession.ts @@ -0,0 +1,148 @@ +// Persisted swap sessions (spec M4 deliverable 4): the state machine rows +// for the ML-side HTLC atomic swap so an in-flight swap survives restarts. +// Plain JSON in AsyncStorage like the address indexes (public data only): +// rows carry the secret hash and transaction ids, NEVER the preimage (the +// spec security note: losing the preimage forfeits the swap, so the session +// screen shows a keep-open warning instead of persisting the secret). +import { STORAGE_KEYS } from '../storage/keys'; +import { loadAsyncStorage } from '../storage/asyncStorage'; +import { devFallbackAllowed } from '../config/runtime'; +import type { HtlcOffer } from '../trade/htlc'; + +/** Swap lifecycle (spec contract): offered -> locked -> claiming -> + * settled, with refunded and expired as the terminal alternates. */ +export type SwapState = 'offered' | 'locked' | 'claiming' | 'settled' | 'refunded' | 'expired'; + +/** Persisted session row. The preimage never lands here: secretHashHex is + * the only secret-derived field. */ +export type SwapSessionRow = { + id: string; + offer: HtlcOffer; + /** Hex of SHA-256(preimage); the preimage itself never persists. */ + secretHashHex: string; + /** Counterparty spend path and our refund path (rebuild leg data after + * a restart without touching the chain). */ + spendAddress: string; + spendPubkeyHex: string; + refundAddress: string; + state: SwapState; + txIds: string[]; + updatedAt: number; +}; + +/** Allowed transitions; anything else is a programming error, not a + * silent overwrite. */ +const TRANSITIONS: Record = { + offered: ['locked', 'expired'], + locked: ['claiming', 'refunded', 'expired'], + claiming: ['settled', 'refunded', 'expired'], + settled: [], + refunded: [], + expired: [], +}; + +export function canTransition(from: SwapState, to: SwapState): boolean { + return TRANSITIONS[from].includes(to); +} + +export function assertTransition(from: SwapState, to: SwapState): void { + if (!canTransition(from, to)) throw new Error(`invalid swap transition: ${from} -> ${to}`); +} + +export interface SwapSessionStore { + save(row: SwapSessionRow): Promise; + all(): Promise; + get(id: string): Promise; + /** Drop one session (terminal cleanup only). */ + remove(id: string): Promise; +} + +export type SwapSessionStorage = { + load(): Promise; + save(json: string): Promise; +}; + +/** AsyncStorage-backed storage with the dev memory fallback (the + * addressStore policy: release builds fail loudly without storage). */ +function defaultStorage(): SwapSessionStorage { + return { + async load() { + const api = await loadAsyncStorage(); + if (api) return api.getItem(STORAGE_KEYS.swapSessions); + if (!devFallbackAllowed()) throw new Error('async storage unavailable'); + return memory; + }, + async save(json) { + const api = await loadAsyncStorage(); + if (api) { + await api.setItem(STORAGE_KEYS.swapSessions, json); + return; + } + if (!devFallbackAllowed()) throw new Error('async storage unavailable'); + memory = json; + }, + }; +} + +let memory: string | null = null; + +const MAX_SESSIONS = 32; +const MAX_TX_IDS = 16; + +/** Row sanity: a tampered store must not resurrect a settled swap or a + * fabricated preimage field. Bad rows drop on load. */ +export function parseSwapSessions(json: string | null): SwapSessionRow[] { + if (json === null || json.length === 0) return []; + let parsed: unknown; + try { + parsed = JSON.parse(json); + } catch { + return []; + } + if (!Array.isArray(parsed)) return []; + const rows: SwapSessionRow[] = []; + for (const entry of parsed.slice(0, MAX_SESSIONS)) { + const row = entry as Partial; + if ( + typeof row.id === 'string' && row.id.length > 0 && + row.offer !== null && typeof row.offer === 'object' && + typeof row.secretHashHex === 'string' && /^[0-9a-f]{64}$/.test(row.secretHashHex) && + typeof row.spendAddress === 'string' && + typeof row.refundAddress === 'string' && + typeof row.state === 'string' && row.state in TRANSITIONS && + Array.isArray(row.txIds) && row.txIds.length <= MAX_TX_IDS && row.txIds.every((id) => typeof id === 'string') && + typeof row.updatedAt === 'number' && Number.isFinite(row.updatedAt) + ) { + rows.push(entry as SwapSessionRow); + } + } + return rows; +} + +export function createSwapSessionStore(storage: SwapSessionStorage = defaultStorage()): SwapSessionStore { + return { + async save(row) { + assertTransitionIsKnown(row.state); + const rows = (await this.all()).filter((existing) => existing.id !== row.id); + rows.unshift({ ...row, txIds: row.txIds.slice(0, MAX_TX_IDS) }); + await storage.save(JSON.stringify(rows.slice(0, MAX_SESSIONS))); + }, + async all() { + return parseSwapSessions(await storage.load()); + }, + async get(id) { + return (await this.all()).find((row) => row.id === id) ?? null; + }, + async remove(id) { + const rows = (await this.all()).filter((row) => row.id !== id); + await storage.save(JSON.stringify(rows)); + }, + }; +} + +/** save() accepts any state the transitions table knows; state CORRECTNESS + * (canTransition) is the caller's machine discipline, checked in tests and + * by the swap screen reducer. */ +function assertTransitionIsKnown(state: SwapState): void { + if (!(state in TRANSITIONS)) throw new Error(`unknown swap state: ${state}`); +} From 1bc09eeae22a1c78fbd506bd3c09148845612e91 Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 06:30:32 +0100 Subject: [PATCH 07/20] feat(m4): bridge_v2 api provider, mock trade seams, provider wiring --- src/data/mock/mockTrade.ts | 155 ++++++++++++++++++++++++ src/data/providers/BridgeProvider.ts | 174 +++++++++++++++++++++++++++ src/data/providers/bridge.test.ts | 131 ++++++++++++++++++++ src/data/providers/index.ts | 79 ++++++++++-- src/data/providers/providers.test.ts | 35 ++++++ src/data/providers/types.ts | 30 ++++- src/trade/htlc.test.ts | 4 +- src/trade/htlc.ts | 62 +++++----- src/trade/orders.test.ts | 2 +- src/trade/orders.ts | 72 ++++++----- 10 files changed, 671 insertions(+), 73 deletions(-) create mode 100644 src/data/mock/mockTrade.ts create mode 100644 src/data/providers/BridgeProvider.ts create mode 100644 src/data/providers/bridge.test.ts diff --git a/src/data/mock/mockTrade.ts b/src/data/mock/mockTrade.ts new file mode 100644 index 0000000..468ed29 --- /dev/null +++ b/src/data/mock/mockTrade.ts @@ -0,0 +1,155 @@ +// Mock trade flows (R3 demo path, createMockSend pattern): the DEX, swap +// and bridge screens run the same shape in both modes. Mock mode returns +// deterministic demo ids after a delay and keeps every session in memory; +// no chain state is touched and nothing reads as a real settlement (the +// demo-data chip stays visible in mock mode, spec M4 honesty rules). +import { ASKS, BIDS } from '../../data'; +import type { NetworkFlag } from '../../config/endpoints'; +import type { BroadcastProvider } from '../providers/types'; +import { DEFAULT_BOOK_DEPTH, type BookRow, type OrderBookService } from '../../trade/OrderBookService'; +import { COIN_REF, type OrderData, type OrderFlows } from '../../trade/orders'; +import type { HtlcFlows, HtlcOffer, HtlcSpend } from '../../trade/htlc'; +import { createSwapSessionStore, type SwapSessionStorage, type SwapSessionStore } from '../../trade/swapSession'; + +/** Fixture book mapped onto the live-service row shape, so the DexScreen + * renders identical code in both modes. */ +export function createMockOrderBookService(): OrderBookService { + const toRows = (levels: { p: number; s: number }[]): BookRow[] => { + let running = 0; + return levels.slice(0, DEFAULT_BOOK_DEPTH).map((level) => { + running += level.p * level.s; + return { price: String(level.p), size: String(level.s), total: String(running) }; + }); + }; + const levels = async (base: string, quote: string, side: 'ask' | 'bid'): Promise => { + void base; + void quote; + return side === 'ask' ? toRows(ASKS) : toRows(BIDS); + }; + return { levels, last: async () => null }; +} + +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** Deterministic fake hex payload per params (mockSend pattern). */ +function fakeId(seed: string): string { + let h = 0x9e3779b9; + let out = ''; + for (let i = 0; i < seed.length; i++) { + h = (Math.imul(h ^ seed.charCodeAt(i), 0x01000193) + i) >>> 0; + } + for (let b = 0; b < 16; b++) { + h = (Math.imul(h, 1664525) + 1013904223) >>> 0; + out += ((h >>> 24) & 0xff).toString(16).padStart(2, '0'); + } + return out.repeat(2).slice(0, 64); +} + +function requireAtomAmount(value: string, what: string): string { + if (!/^\d+$/.test(value) || BigInt(value) === 0n) throw new Error(`${what} must be a positive atom string`); + return value; +} + +/** Demo order flows: full validation and the mock broadcast, results + * labelled demo by the fake deterministic ids. */ +export function createMockOrderFlows(cfg: { broadcast: BroadcastProvider; network: NetworkFlag }): OrderFlows { + const myOrders: OrderData[] = []; + return { + async createOrder({ giveTokenId, giveAtoms, askTokenId, askAtoms }) { + requireAtomAmount(giveAtoms, 'give'); + requireAtomAmount(askAtoms, 'ask'); + const { txId } = await cfg.broadcast.broadcastMl(fakeId(`create:${giveTokenId}:${giveAtoms}:${askAtoms}:${cfg.network}`)); + const orderId = `mordr1demo${fakeId(`${txId}:${orderIdSeedCounter++}`).slice(0, 20)}`; + myOrders.unshift({ + orderId, + giveTokenId: giveTokenId === COIN_REF ? COIN_REF : giveTokenId, + giveBalanceAtoms: giveAtoms, + askTokenId, + askBalanceAtoms: askAtoms, + concludeDestination: '', + nonce: null, + frozen: false, + }); + return { txId, orderId }; + }, + async fillOrder({ orderId, fillAtoms, destination }) { + requireAtomAmount(fillAtoms, 'fill'); + void destination; + const known = myOrders.find((order) => order.orderId === orderId); + if (known && (known.frozen || (known.giveBalanceAtoms === '0' && known.askBalanceAtoms === '0'))) { + throw new Error('order is not open'); + } + const { txId } = await cfg.broadcast.broadcastMl(fakeId(`fill:${orderId}:${fillAtoms}`)); + return { txId }; + }, + async concludeOrder({ orderId }) { + const known = myOrders.find((order) => order.orderId === orderId); + if (known) { + if (known.concludeDestination === '') throw new Error('demo order carries no conclude destination'); + known.giveBalanceAtoms = '0'; + known.askBalanceAtoms = '0'; + } + const { txId } = await cfg.broadcast.broadcastMl(fakeId(`conclude:${orderId}`)); + return { txId }; + }, + async openOrders() { + await delay(200); + return []; + }, + async myOrders() { + await delay(200); + return [...myOrders]; + }, + }; +} + +let orderIdSeedCounter = 0; + +/** Demo HTLC flows: the swap session demo walks lock/claim/refund on the + * mock broadcaster with deterministic fake tx ids. */ +export function createMockHtlcFlows(cfg: { broadcast: BroadcastProvider }): HtlcFlows { + return { + async initiate(offer: HtlcOffer, spend: HtlcSpend, refundAddress: string) { + void spend; + void refundAddress; + requireAtomAmount(offer.giveAtoms, 'give'); + if (offer.secretHash.length !== 32) throw new Error('the secret hash must be 32 bytes'); + const { txId } = await cfg.broadcast.broadcastMl(fakeId(`htlc-lock:${offer.giveAtoms}`)); + return { txId, htlcOutpoint: { id: new Uint8Array(32).fill(0x0a), index: 0 } }; + }, + async claim(htlcTxId: string, secret: Uint8Array) { + if (secret.length !== 32) throw new Error('the preimage must be 32 bytes'); + const { txId } = await cfg.broadcast.broadcastMl(fakeId(`htlc-claim:${htlcTxId}`)); + return { txId }; + }, + async refund(htlcTxId: string) { + const { txId } = await cfg.broadcast.broadcastMl(fakeId(`htlc-refund:${htlcTxId}`)); + return { txId }; + }, + async extractSecret(rawSignedTx: Uint8Array, htlcOutpoint: { id: Uint8Array; index: number }) { + void htlcOutpoint; + return rawSignedTx.subarray(0, 32); + }, + }; +} + +/** Memory-backed swap session storage for mock mode (sessions are demo + * state; they survive navigation but not a mock-mode restart, which the + * demo chip discloses anyway). */ +export function createMockSwapSessionStorage(): SwapSessionStorage { + let json: string | null = null; + return { + async load() { + return json; + }, + async save(next: string) { + json = next; + }, + }; +} + +export function createMockSwapSessionStore(): SwapSessionStore { + return createSwapSessionStore(createMockSwapSessionStorage()); +} diff --git a/src/data/providers/BridgeProvider.ts b/src/data/providers/BridgeProvider.ts new file mode 100644 index 0000000..bc6076e --- /dev/null +++ b/src/data/providers/BridgeProvider.ts @@ -0,0 +1,174 @@ +// Real bridge provider (missing-architecture gap 5, resolution R5 option A, +// 2026-11-17): the bridge_v2 api-server under the configured frontend base +// (https://api.bridge.mintlayer.org/api/v1, F14). Quotes read GET fees and +// the agents config (the Mintlayer treasury deposit address for M2E, the +// per-token fee schedule per direction); status polls GET +// bridge-request/:uuid and maps the backend statuses onto the wallet's +// bridge states. +// +// Honest v1 scope (spec M4): the M2E route is quote+status real; INITIATION +// is gated with a typed unsupported error because completing it needs (a) +// the Mintlayer deposit intent output the current bindings facade does not +// expose and (b) a live ML submission route (R3, broadcastBase null). The +// E2M route stays disabled per R5: the wallet has no EVM signer; the scoped +// decision (same BIP39 seed, EIP-155 via audited libraries) is pending and +// is never silently dropped (the screen carries the explanatory copy). +// +// Failure policy: transport failures map to the typed BridgeError classes +// (network, failed, disabled, unsupported); raw server bodies never surface. +import { decimalsToAtoms, atomsToDecimal } from '../../money'; +import { requestJson, TransportError, assertHttpsBase, type FetchLike } from '../transport'; +import type { BridgeHandle, BridgeProvider, BridgeQuoteRequest, BridgeState } from './types'; + +export class BridgeError extends Error { + constructor( + readonly failure: 'network' | 'failed' | 'disabled' | 'unsupported', + detail?: string, + ) { + super(detail ?? `bridge ${failure}`); + this.name = 'BridgeError'; + } +} + +export type BridgeApiConfig = { + /** The configured bridge_v2 frontend base (endpoints.bridgeBase), already + * including the /api/v1 segment; null keeps the provider typed-disabled. */ + base: string | null; + /** Overrides for the Node gate (tests). */ + fetch?: FetchLike; + delay?: (ms: number) => Promise; +}; + +/** bridge_v2 fee row per direction (api-server-lib fees handler). */ +type BridgeFees = Record; + +/** agents-config response (CachedConfig serialization, api-server-lib). */ +type AgentsConfig = { + network_type: string; + ml_deposit_address?: string; + eth_flavor_specific_config?: Record; +}; + +type BridgeRequestDetail = { status?: string; bridge_request_uuid?: string }; + +const DEFAULT_TIMEOUT_MS = 15_000; + +/** Backend request statuses (records.rs BridgeRequestStatus) mapped onto + * the wallet bridge states; 'manual' renders as in-progress (the frontend + * convention: operator approval pending, not a failure). */ +const STATUS_MAP: Record = { + pending: 'awaiting-deposit', + processed_by_master: 'attesting', + completed: 'minted', + failed: 'failed', + manual: 'attesting', +}; + +export function createBridgeApiProvider(cfg: BridgeApiConfig): BridgeProvider { + if (cfg.base !== null) assertHttpsBase(cfg.base); + const fetchImpl: FetchLike = cfg.fetch ?? (typeof fetch === 'function' ? (fetch as unknown as FetchLike) : (() => { + throw new TransportError('transport', 'bridge', undefined); + })); + const delay = cfg.delay ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + + async function get(path: string): Promise { + if (cfg.base === null) throw new BridgeError('disabled', 'no bridge api base is configured'); + try { + return (await requestJson({ + base: cfg.base, + path, + timeoutMs: DEFAULT_TIMEOUT_MS, + retries: 1, + expect: 'json', + fetchImpl, + delay, + })) as T; + } catch (e) { + throw mapTransport(e); + } + } + + /** Direction guard: E2M needs an EVM signer the wallet does not have + * (R5 open sub-question with proposal, never silently dropped). */ + function requireM2e(route: BridgeQuoteRequest['route']): void { + if (route !== 'M2E') throw new BridgeError('unsupported', 'E2M stays disabled until the EVM signer decision lands (R5)'); + } + + async function loadConfig(): Promise { + return get('/agents-config'); + } + + return { + async quote(req) { + requireM2e(req.route); + const [fees, config] = await Promise.all([get('/fees'), loadConfig()]); + const side = fees[req.token]?.to_eth; + if (!side) throw new BridgeError('failed', `no ${req.token} fee row is configured for the ml to eth direction`); + const fixed = safeDecimal(side.fixed_fee, 'fixed_fee'); + const pct = safePercentage(side.percentage_fee, 'percentage_fee'); + const feeAmount = fixedFeeAmount(fixed, pct, req.amount); + const confirmations = config.eth_flavor_specific_config + ? Object.values(config.eth_flavor_specific_config).find((flavor) => flavor.m2e?.deposit_tx_required_confirmations !== undefined)?.m2e + ?.deposit_tx_required_confirmations + : undefined; + return { + feePct: side.percentage_fee, + feeAmount, + // bridge_v2 documents no minimum; the screen hides the row. + minAmount: null, + confirmationsRequired: confirmations, + destContractOrAddress: config.ml_deposit_address ?? '', + }; + }, + + async initiate(req) { + requireM2e(req.route); + // The M2E deposit is a Mintlayer transfer with an intent output + // naming the EVM receiver. The current bindings facade exposes no + // intent encoder, and the ML submission route is unconfigured (R3): + // a fabricated handle would fake a bridge that never started. + void req; + throw new BridgeError('unsupported', 'the M2E deposit needs the intent encoder and a live ML submission route (R3)'); + }, + + async status(handle: BridgeHandle): Promise { + const detail = await get(`/bridge-request/${encodeURIComponent(handle.id)}`); + if (typeof detail.status !== 'string') throw new BridgeError('failed', 'the bridge request detail carries no status'); + const mapped = STATUS_MAP[detail.status]; + if (mapped === undefined) throw new BridgeError('failed', `unknown bridge status ${detail.status}`); + return mapped; + }, + }; +} + +function mapTransport(e: unknown): unknown { + if (e instanceof BridgeError) return e; + if (e instanceof TransportError) { + if (e.kind === 'transport') return new BridgeError('network'); + if (e.kind === 'http' && e.status === 404) return new BridgeError('failed', 'bridge request not found'); + return new BridgeError('failed', undefined); + } + return e; +} + +function safeDecimal(value: string, label: string): string { + if (!/^\d+(?:\.\d+)?$/.test(value)) throw new BridgeError('failed', `${label} is not a decimal number`); + return value; +} + +/** percentage_fee arrives normalized like "0.15%" (to_percentage_str). */ +function safePercentage(value: string, label: string): string { + const trimmed = value.endsWith('%') ? value.slice(0, -1) : value; + if (!/^\d+(?:\.\d+)?$/.test(trimmed)) throw new BridgeError('failed', `${label} is not a percentage`); + return trimmed; +} + +/** feeAmount = fixed + amount * pct/100 on an 18-decimal BigInt scale + * (bridge amounts are ERC20-scale or ML atoms; no float money math). */ +export function fixedFeeAmount(fixedFee: string, pct: string, amount: string): string { + const scale = 10n ** 18n; + const scaled = (value: string): bigint => BigInt(decimalsToAtoms(value, 18)); + const fixed = scaled(fixedFee); + const fee = scaled(amount) * scaled(pct) / (100n * scale) + fixed; + return atomsToDecimal(fee.toString(), 18); +} diff --git a/src/data/providers/bridge.test.ts b/src/data/providers/bridge.test.ts new file mode 100644 index 0000000..1baa37c --- /dev/null +++ b/src/data/providers/bridge.test.ts @@ -0,0 +1,131 @@ +// Real bridge provider gate (spec M4): quotes ride the bridge_v2 fees and +// agents-config routes (per-token to_eth fees, the Mintlayer treasury +// deposit address, m2e confirmations), status maps the backend request +// statuses, and the honest gates hold: E2M unsupported (R5), initiation +// unsupported until the intent encoder and the ML submission route exist +// (R3). Offline over a scripted transport. +// tsx src/data/providers/bridge.test.ts +import { strict as assert } from 'node:assert/strict'; + +import { TransportError } from '../transport'; +import { BridgeError, createBridgeApiProvider, fixedFeeAmount } from './BridgeProvider'; + +type ScriptedResponse = { status: number; body: unknown }; + +function scriptedFetch(responses: Record, calls: string[] = []) { + const fetch = async (url: string) => { + calls.push(url); + const path = url.replace(/^https?:\/\/[^/]+\/api\/v1/, ''); + const response = responses[path]; + if (!response) throw new Error(`no scripted response for ${path}`); + return { + ok: response.status >= 200 && response.status < 300, + status: response.status, + headers: { get: () => null }, + text: async () => JSON.stringify(response.body), + }; + }; + return fetch; +} + +const CONFIG = { + network_type: 'mainnet', + ml_tokens: { ml: 'mtc1q00' }, + volume_30d: { ml: '1000' }, + ml_deposit_address: 'mtc1qtrea5surydepo5itaddre55mtc1qtrea5surydepo5itaddre55', + eth_flavor_specific_config: { + '': { + bridge_contract_address: '0xbridge', + m2e: { deposit_tx_required_confirmations: 10 }, + }, + }, +}; + +const FEES = { + usdt: { to_eth: { fixed_fee: '1', percentage_fee: '0.15%' }, to_ml: { fixed_fee: '1', percentage_fee: '0.15%' } }, + ml: { to_eth: { fixed_fee: '0', percentage_fee: '0%' } }, +}; + +async function main() { + // Fee math: fixed + amount * pct/100 on exact BigInt scale. + assert.equal(fixedFeeAmount('1', '0.15', '500'), '1.75'); + assert.equal(fixedFeeAmount('0', '0', '500'), '0'); + assert.equal(fixedFeeAmount('2.5', '1', '100'), '3.5'); + + const calls: string[] = []; + const provider = createBridgeApiProvider({ + base: 'https://api.bridge.mintlayer.org/api/v1', + fetch: scriptedFetch({ '/agents-config': { status: 200, body: CONFIG }, '/fees': { status: 200, body: FEES } } as never, calls), + delay: async () => undefined, + }); + + // Quote (M2E): to_eth fees, no fabricated minimum, treasury deposit + // address from the config, confirmations from the m2e flavor. + const quote = await provider.quote({ route: 'M2E', token: 'usdt', amount: '500.00', destAddr: '0xabc' }); + assert.equal(quote.feePct, '0.15%'); + assert.equal(quote.feeAmount, '1.75'); + assert.equal(quote.minAmount, null); + assert.equal(quote.confirmationsRequired, 10); + assert.equal(quote.destContractOrAddress, CONFIG.ml_deposit_address); + assert.equal(quote.etaSeconds, undefined, 'the real API reports confirmations, never a fabricated seconds ETA'); + assert.ok(calls.some((url) => url.endsWith('/fees'))); + assert.ok(calls.some((url) => url.endsWith('/agents-config'))); + + // E2M is refused typed before any network call (R5 open sub-question). + await assert.rejects( + () => provider.quote({ route: 'E2M', token: 'usdt', amount: '1', destAddr: 'mtc1q' }), + (e: unknown) => e instanceof BridgeError && e.failure === 'unsupported', + ); + await assert.rejects(() => provider.initiate({ route: 'E2M', token: 'usdt', amount: '1', destAddr: 'mtc1q' }), BridgeError); + + // Initiation (M2E) is honestly gated: no fabricated handle while the + // deposit intent encoder and the ML submission route are pending. + await assert.rejects( + () => provider.initiate({ route: 'M2E', token: 'usdt', amount: '1', destAddr: '0xabc' }), + (e: unknown) => e instanceof BridgeError && e.failure === 'unsupported', + ); + + // Status mapping over the documented backend statuses. + const statusFetch = scriptedFetch({ + '/bridge-request/uuid-1': { status: 200, body: { status: 'pending', bridge_request_uuid: 'uuid-1' } }, + '/bridge-request/uuid-2': { status: 200, body: { status: 'processed_by_master' } }, + '/bridge-request/uuid-3': { status: 200, body: { status: 'completed' } }, + '/bridge-request/uuid-4': { status: 200, body: { status: 'failed' } }, + '/bridge-request/uuid-5': { status: 200, body: { status: 'manual' } }, + '/bridge-request/uuid-404': { status: 404, body: { error: 'nf' } }, + } as never); + const statusProvider = createBridgeApiProvider({ base: 'https://api.bridge.mintlayer.org/api/v1', fetch: statusFetch, delay: async () => undefined }); + const handle = { id: 'uuid-1', createdAt: 0 }; + assert.equal(await statusProvider.status(handle), 'awaiting-deposit'); + assert.equal(await statusProvider.status({ id: 'uuid-2', createdAt: 0 }), 'attesting'); + assert.equal(await statusProvider.status({ id: 'uuid-3', createdAt: 0 }), 'minted'); + assert.equal(await statusProvider.status({ id: 'uuid-4', createdAt: 0 }), 'failed'); + assert.equal(await statusProvider.status({ id: 'uuid-5', createdAt: 0 }), 'attesting', 'manual is operator approval pending, not a failure'); + await assert.rejects(() => statusProvider.status({ id: 'uuid-404', createdAt: 0 }), (e: unknown) => e instanceof BridgeError && e.failure === 'failed'); + + // Transport failures map to the typed network class. + const downProvider = createBridgeApiProvider({ + base: 'https://api.bridge.mintlayer.org/api/v1', + fetch: async () => { + throw new TransportError('transport', 'bridge', undefined); + }, + delay: async () => undefined, + }); + await assert.rejects(() => downProvider.quote({ route: 'M2E', token: 'usdt', amount: '1', destAddr: 'x' }), (e: unknown) => e instanceof BridgeError && e.failure === 'network'); + + // An unconfigured base is typed-disabled, never a silent guess. + const unconfigured = createBridgeApiProvider({ base: null, fetch: scriptedFetch({} as never), delay: async () => undefined }); + await assert.rejects(() => unconfigured.quote({ route: 'M2E', token: 'usdt', amount: '1', destAddr: 'x' }), (e: unknown) => e instanceof BridgeError && e.failure === 'disabled'); + + // Unknown tokens and malformed fee rows are typed failures. + const badProvider = createBridgeApiProvider({ + base: 'https://api.bridge.mintlayer.org/api/v1', + fetch: scriptedFetch({ '/agents-config': { status: 200, body: CONFIG }, '/fees': { status: 200, body: { usdt: { to_eth: { fixed_fee: 'x', percentage_fee: 'y' } } } } } as never), + delay: async () => undefined, + }); + await assert.rejects(() => badProvider.quote({ route: 'M2E', token: 'usdt', amount: '1', destAddr: 'x' }), (e: unknown) => e instanceof BridgeError && e.failure === 'failed'); + + console.log('bridge: ok'); +} + +main(); diff --git a/src/data/providers/index.ts b/src/data/providers/index.ts index b0e4b41..741e7e1 100644 --- a/src/data/providers/index.ts +++ b/src/data/providers/index.ts @@ -6,18 +6,26 @@ // (device-pending until the native call-through verifies) with the // config-gated broadcast switch, and the fully real BTC path on scure. // Prices stay the mock provider per R1 in v1. +import type { IndexerClient } from '../ml/IndexerClient'; +import type { KeySession } from '../../keys/session'; import type { ProviderMode, Providers } from './types'; import { currentNetwork, endpointsFor, FLAGS } from '../../config/endpoints'; import { openKeySession } from '../../keys/session'; import { createFixtureBridgeProvider, createFixtureBroadcastProvider, createFixtureWalletData } from '../mock/fixtures'; +import { createMockHtlcFlows, createMockOrderBookService, createMockOrderFlows, createMockSwapSessionStore } from '../mock/mockTrade'; import { createMockSend } from '../mock/mockSend'; import { createConfiguredPriceProvider } from '../prices/PriceProvider'; import { createBroadcastProvider } from './BroadcastProvider'; +import { createBridgeApiProvider } from './BridgeProvider'; import { createRealAccountContext } from '../real/account'; import { createRealWalletData } from '../real/realWalletData'; import { createRealSend } from '../real/realSend'; import { createFixturePriceProvider } from '../mock/priceFixtures'; import { createLocalWaitlistProvider } from '../mock/localWaitlist'; +import { createOrderFlows } from '../../trade/orders'; +import { createHtlcFlows } from '../../trade/htlc'; +import { createSwapSessionStore } from '../../trade/swapSession'; +import { createOrderBookService } from '../../trade/OrderBookService'; import { TxTracker } from '../../send/TxTracker'; export function readDataMode(): ProviderMode { @@ -70,6 +78,30 @@ export function createProviders(mode: ProviderMode = readDataMode()): Providers btcBase: endpoints.btcBase, }); const txTracker = new TxTracker(broadcast); + // Lazy indexer forwarders: construction must stay offline-safe (the + // unconfigured testnet base throws typed on first use, not at wiring). + const indexerReader = { + orderBook: (...args: Parameters) => context.requireIndexer().orderBook(...args), + transaction: (...args: Parameters) => context.requireIndexer().transaction(...args), + orders: () => context.requireIndexer().orders(), + ordersByPair: (...args: Parameters) => context.requireIndexer().ordersByPair(...args), + order: (...args: Parameters) => context.requireIndexer().order(...args), + feerate: (...args: Parameters) => context.requireIndexer().feerate(...args), + spendableUtxos: (...args: Parameters) => context.requireIndexer().spendableUtxos(...args), + tip: () => context.requireIndexer().tip(), + }; + const tradeAccount = async () => { + const acct = await context.ensureAccount(); + return { manager: acct.manager, indexer: context.requireIndexer() }; + }; + const withVaultSession = async (fn: (session: KeySession) => Promise): Promise => { + const session = await openKeySession(); + try { + return await fn(session); + } finally { + session.release(); + } + }; return { data: createRealWalletData(context), send: createRealSend({ @@ -78,19 +110,42 @@ export function createProviders(mode: ProviderMode = readDataMode()): Providers broadcastBase: endpoints.broadcastBase, broadcast, tracker: txTracker, - withSession: async (fn) => { - const session = await openKeySession(); - try { - return await fn(session); - } finally { - session.release(); - } - }, + withSession: withVaultSession, }), broadcast, txTracker, waitlist: createLocalWaitlistProvider(), - bridge: createFixtureBridgeProvider(), + // M4 trade seams: real order book and order/HTLC flows over the + // bindings and the indexer (device-pending honest states until the + // native call-through verifies), the bridge_v2 api provider per R5, + // and persisted swap sessions (preimage never persists). + orderBook: createOrderBookService({ reader: indexerReader }), + orders: createOrderFlows({ + network, + loadBindings, + indexer: indexerReader, + broadcast, + addresses: async () => (await tradeAccount()).manager.allAddresses('ml'), + allocateChangeAddress: async () => (await tradeAccount()).manager.allocateChangeAddress('ml'), + releaseFailedChange: async () => { + await (await tradeAccount()).manager.releaseChangeAddress('ml'); + }, + withSession: withVaultSession, + }), + htlc: createHtlcFlows({ + network, + loadBindings, + indexer: indexerReader, + broadcast, + addresses: async () => (await tradeAccount()).manager.allAddresses('ml'), + allocateChangeAddress: async () => (await tradeAccount()).manager.allocateChangeAddress('ml'), + releaseFailedChange: async () => { + await (await tradeAccount()).manager.releaseChangeAddress('ml'); + }, + withSession: withVaultSession, + }), + swapSessions: createSwapSessionStore(), + bridge: createBridgeApiProvider({ base: endpoints.bridgeBase }), mode, ...priceProvider(), }; @@ -102,6 +157,12 @@ export function createProviders(mode: ProviderMode = readDataMode()): Providers broadcast, txTracker: new TxTracker(broadcast), waitlist: createLocalWaitlistProvider(), + // Mock trade seams: demo book and demo flows over the mock broadcaster + // (deterministic fake ids; the demo chip discloses the mode). + orderBook: createMockOrderBookService(), + orders: createMockOrderFlows({ broadcast, network: currentNetwork() }), + htlc: createMockHtlcFlows({ broadcast }), + swapSessions: createMockSwapSessionStore(), bridge: createFixtureBridgeProvider(), mode, ...priceProvider(), diff --git a/src/data/providers/providers.test.ts b/src/data/providers/providers.test.ts index 3d49469..eec5b7e 100644 --- a/src/data/providers/providers.test.ts +++ b/src/data/providers/providers.test.ts @@ -64,6 +64,35 @@ async function main() { }); assert.equal(await providers.bridge.status(handle), 'awaiting-deposit'); + // M4 trade seams in mock mode: demo book rows in the live-service shape, + // demo order/HTLC flows over the mock broadcaster, persistent-enough + // demo swap sessions. + const asks = await providers.orderBook.levels('ML', 'USDT', 'ask'); + assert.equal(asks.length, 6); + assert.equal(typeof asks[0].price, 'string'); + assert.equal(await providers.orderBook.last(), null); + const demoOrder = await providers.orders.createOrder({ giveTokenId: 'coin', giveAtoms: '100000000000', askTokenId: 'tUSDT', askAtoms: '34' }); + assert.match(demoOrder.orderId, /^mordr1demo/); + assert.deepEqual((await providers.orders.myOrders()).map((o) => o.orderId), [demoOrder.orderId]); + const demoLock = await providers.htlc.initiate( + { role: 'initiator', giveChain: 'ml', giveAtoms: '1000', wantAtoms: '280000', secretHash: new Uint8Array(32).fill(7), timelockSeconds: 172800 }, + { address: 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl', pubkey: new Uint8Array(33) }, + 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl', + ); + assert.equal(demoLock.htlcOutpoint.index, 0); + await providers.swapSessions.save({ + id: demoLock.txId, + offer: { role: 'initiator', giveChain: 'ml', giveAtoms: '1000', wantAtoms: '280000', secretHash: new Uint8Array(32).fill(7), timelockSeconds: 172800 }, + secretHashHex: '07'.repeat(32), + spendAddress: 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl', + spendPubkeyHex: '', + refundAddress: 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl', + state: 'locked', + txIds: [demoLock.txId], + updatedAt: Date.now(), + }); + assert.equal((await providers.swapSessions.all()).length, 1); + // Real mode constructs lazily (no network, no vault access until a data // call), keeps the R1 mock price source and the fixture seams for later // milestones; the data calls themselves are covered by the service gates. @@ -74,6 +103,12 @@ async function main() { // only Mintlayer counts as an active network. assert.deepEqual(await real.data.getNetworks(), ['Mintlayer']); assert.equal((await real.data.getMarket('ML/USDT')).pair, 'ML/USDT'); + // M4: the real bridge provider carries the R5 gates; E2M is refused + // typed before any network call (no EVM signer, scoped decision open). + await assert.rejects( + () => real.bridge.quote({ route: 'E2M', token: 'usdt', amount: '1', destAddr: 'mtc1q' }), + (e: unknown) => (e as { failure?: string }).failure === 'unsupported', + ); // Unconfigured testnet base (action item A2): typed offline, no fetch. setNetwork('testnet'); const offline = createProviders('real'); diff --git a/src/data/providers/types.ts b/src/data/providers/types.ts index cf5baf8..bfe1b36 100644 --- a/src/data/providers/types.ts +++ b/src/data/providers/types.ts @@ -6,6 +6,10 @@ import type { ChainName, Tone } from '../../theme'; import type { IconName } from '../../ui/icons'; import type { StepState } from '../../ui/StepState'; import type { TxTracker } from '../../send/TxTracker'; +import type { OrderBookService } from '../../trade/OrderBookService'; +import type { OrderFlows } from '../../trade/orders'; +import type { HtlcFlows } from '../../trade/htlc'; +import type { SwapSessionStore } from '../../trade/swapSession'; export type ProviderMode = 'mock' | 'real'; @@ -165,8 +169,18 @@ export interface WaitlistProvider { export type BridgeRouteDirection = 'E2M' | 'M2E'; export type BridgeQuoteRequest = { route: BridgeRouteDirection; token: string; amount: string; destAddr: string }; export type BridgeQuote = { - feePct: string; feeAmount: string; minAmount: string; - etaSeconds: number; destContractOrAddress: string; + feePct: string; + feeAmount: string; + /** Documented minimum (fixture); the bridge_v2 API documents none, so the + * real provider answers null and the screen hides the row. */ + minAmount?: string | null; + /** Documented seconds ETA (fixture); the real API reports confirmations + * instead, so this is absent on real quotes. */ + etaSeconds?: number; + /** Real API: the m2e deposit confirmations the master waits for. */ + confirmationsRequired?: number; + /** M2E: the Mintlayer treasury deposit address to fund (F14). */ + destContractOrAddress: string; }; export type BridgeHandle = { id: string; createdAt: number }; export type BridgeState = 'awaiting-deposit' | 'attesting' | 'minted' | 'released' | 'expired' | 'failed'; @@ -226,4 +240,16 @@ export interface Providers { /** True while USD figures come from the mock price provider (R1): the UI * labels them as indicative mock data instead of presenting real prices. */ pricesAreMock: boolean; + + // Trade seams (spec M4): real in real mode over the bindings and the + // indexer, demo-labelled in mock mode (createMockSend pattern), so the + // screens stay mode-agnostic and the demo chip stays honest. + /** Live order book (DexScreen depth rows); the fixture book in mock. */ + orderBook: OrderBookService; + /** On-chain order flows (place, fill, conclude); demo pipeline in mock. */ + orders: OrderFlows; + /** ML-side HTLC swap flows; demo pipeline in mock. */ + htlc: HtlcFlows; + /** Persisted swap sessions (restart-survivable). */ + swapSessions: SwapSessionStore; } diff --git a/src/trade/htlc.test.ts b/src/trade/htlc.test.ts index 0eccf61..356309a 100644 --- a/src/trade/htlc.test.ts +++ b/src/trade/htlc.test.ts @@ -178,7 +178,7 @@ function harness(opts?: { htlcJson?: Partial; lockTimestamp?: number | }; const flows = createHtlcFlows({ network: 'mainnet', - bindings, + loadBindings: () => bindings, indexer: indexer as never, broadcast, addresses: async () => [VECTOR_ADDRESS], @@ -328,7 +328,7 @@ async function main() { }; const flows = createHtlcFlows({ network: 'mainnet', - bindings, + loadBindings: () => bindings, indexer: indexer as never, broadcast: { broadcastMl: async () => ({ txId: LOCK_TX_ID }), diff --git a/src/trade/htlc.ts b/src/trade/htlc.ts index dce4153..fb7c49d 100644 --- a/src/trade/htlc.ts +++ b/src/trade/htlc.ts @@ -61,7 +61,10 @@ export interface HtlcFlows { export type HtlcFlowsConfig = { network: MlNetwork; - bindings: MintlayerBindings; + /** The bindings facade loader (MojitoCore): a thunk because the facade + * pulls the native bridge, which the Node gate must not load (the + * realSend config carries the same lazy seam). */ + loadBindings: () => MintlayerBindings; indexer: Pick; broadcast: BroadcastProvider; addresses: () => Promise; @@ -95,6 +98,11 @@ export type HtlcDescriptor = { }; export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { + let bindings: MintlayerBindings | null = null; + function b(): MintlayerBindings { + if (bindings === null) bindings = cfg.loadBindings(); + return bindings; + } let inFlight = false; function serialize(fn: () => Promise): Promise { if (inFlight) return Promise.reject(new HtlcError('busy')); @@ -118,8 +126,8 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { async function utxoInput(sourceIdHex: string, index: number): Promise { const sourceId = hexOf.decode(sourceIdHex); if (sourceId.length !== 32) throw new HtlcError('rejected', 'outpoint source id must be 32 bytes'); - const outpointSource = await cfg.bindings.encodeOutpointSourceId(sourceId, 'transaction'); - return cfg.bindings.encodeInputForUtxo(outpointSource, index); + const outpointSource = await b().encodeOutpointSourceId(sourceId, 'transaction'); + return b().encodeInputForUtxo(outpointSource, index); } async function sign( @@ -149,11 +157,11 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { }; witnesses.push( inputs.length === 1 && secret !== undefined - ? await cfg.bindings.encodeWitnessHtlcSpend(params) - : await cfg.bindings.encodeWitness(params), + ? await b().encodeWitnessHtlcSpend(params) + : await b().encodeWitness(params), ); } - const signed = await cfg.bindings.encodeSignedTransaction(transaction, witnesses); + const signed = await b().encodeSignedTransaction(transaction, witnesses); return bytesToHex(signed); }); } @@ -194,7 +202,7 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { // The decode seam restores the lock parameters from the raw // transaction; bindings stub rejections surface as the honest // device-pending state, never a guessed descriptor. - const json = await cfg.bindings.decodeTransactionToJson(hexOf.decode(htlcTxId), cfg.network); + const json = await b().decodeTransactionToJson(hexOf.decode(htlcTxId), cfg.network); const parsed = JSON.parse(json) as { outputs?: { htlc?: { atoms?: string; secret_hash?: string; spend_address?: string; spend_pubkey?: string; refund_address?: string; refund_timelock?: number } }[]; }; @@ -238,7 +246,7 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { destinations.push(selected.address); } const outputBytes: Uint8Array[] = [ - await cfg.bindings.encodeOutputHtlc({ + await b().encodeOutputHtlc({ atoms: '0', secretHash, spendAddress: spend.address, @@ -247,10 +255,10 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { refundTimelock: timelockSeconds, }), ...(await Promise.all( - planned.slice(1).map((leg) => cfg.bindings.encodeOutputTransfer('0', leg.address, cfg.network)), + planned.slice(1).map((leg) => b().encodeOutputTransfer('0', leg.address, cfg.network)), )), ]; - return cfg.bindings.estimateTransactionSize(inputBytes, destinations, outputBytes, cfg.network); + return b().estimateTransactionSize(inputBytes, destinations, outputBytes, cfg.network); }, }); @@ -260,12 +268,12 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { inputs.push(await utxoInput(selected.utxo.outpoint.sourceId, selected.utxo.outpoint.index)); spentOutputs.push( selected.tokenId === null - ? await cfg.bindings.encodeOutputTransfer(selected.atoms, selected.address, cfg.network) - : await cfg.bindings.encodeOutputTokenTransfer(selected.tokenId, selected.atoms, selected.address, cfg.network), + ? await b().encodeOutputTransfer(selected.atoms, selected.address, cfg.network) + : await b().encodeOutputTokenTransfer(selected.tokenId, selected.atoms, selected.address, cfg.network), ); } const outputs: Uint8Array[] = [ - await cfg.bindings.encodeOutputHtlc({ + await b().encodeOutputHtlc({ atoms: giveAtoms, secretHash, spendAddress: spend.address, @@ -275,10 +283,10 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { }), ]; if (selection.changeAtoms !== '0') { - outputs.push(await cfg.bindings.encodeOutputTransfer(selection.changeAtoms, changeAddress, cfg.network)); + outputs.push(await b().encodeOutputTransfer(selection.changeAtoms, changeAddress, cfg.network)); } - const transaction = await cfg.bindings.encodeTransaction(inputs, outputs, 0); + const transaction = await b().encodeTransaction(inputs, outputs, 0); const tip = await cfg.indexer.tip(); const signedHex = await cfg.withSession((session) => sign(transaction, selection.selection, spentOutputs, session, tip.blockHeight + 1)); const txId = await broadcast(signedHex); @@ -300,7 +308,7 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { const payout = BigInt(descriptor.atoms) - fee; if (payout <= 0n) throw new HtlcError('rejected', 'the lock cannot cover the claim fee'); const htlcInput = await utxoInput(htlcTxId, descriptor.outputIndex); - const htlcOutputBytes = await cfg.bindings.encodeOutputHtlc({ + const htlcOutputBytes = await b().encodeOutputHtlc({ atoms: descriptor.atoms, secretHash: descriptor.secretHash, spendAddress: descriptor.spendAddress, @@ -309,8 +317,8 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { refundTimelock: descriptor.refundTimelock, }); const inputs = [htlcInput]; - const outputs = [await cfg.bindings.encodeOutputTransfer(payout.toString(), spend.address, cfg.network)]; - const transaction = await cfg.bindings.encodeTransaction(inputs, outputs, 0); + const outputs = [await b().encodeOutputTransfer(payout.toString(), spend.address, cfg.network)]; + const transaction = await b().encodeTransaction(inputs, outputs, 0); const tip = await cfg.indexer.tip(); // The HTLC spend witness signs against the HTLC output (the spent // output of the single input) and reveals the preimage (F10). @@ -336,7 +344,7 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { const payout = BigInt(descriptor.atoms) - fee; if (payout <= 0n) throw new HtlcError('rejected', 'the lock cannot cover the refund fee'); const htlcInput = await utxoInput(htlcTxId, descriptor.outputIndex); - const htlcOutputBytes = await cfg.bindings.encodeOutputHtlc({ + const htlcOutputBytes = await b().encodeOutputHtlc({ atoms: descriptor.atoms, secretHash: descriptor.secretHash, spendAddress: descriptor.spendAddress, @@ -345,8 +353,8 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { refundTimelock: descriptor.refundTimelock, }); const inputs = [htlcInput]; - const outputs = [await cfg.bindings.encodeOutputTransfer(payout.toString(), descriptor.refundAddress, cfg.network)]; - const transaction = await cfg.bindings.encodeTransaction(inputs, outputs, 0); + const outputs = [await b().encodeOutputTransfer(payout.toString(), descriptor.refundAddress, cfg.network)]; + const transaction = await b().encodeTransaction(inputs, outputs, 0); const tip = await cfg.indexer.tip(); const signedHex = await cfg.withSession((session) => signWithKey(transaction, descriptor.refundAddress, [htlcOutputBytes], session, tip.blockHeight + 1, undefined, 'htlc-refund'), @@ -356,7 +364,7 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { }, async extractSecret(rawSignedTx, htlcOutpoint) { - return cfg.bindings.extractHtlcSecret(rawSignedTx, false, htlcOutpoint.id, htlcOutpoint.index); + return b().extractHtlcSecret(rawSignedTx, false, htlcOutpoint.id, htlcOutpoint.index); }, }; @@ -365,8 +373,8 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { async function claimFee(htlcTxId: string, destination: string): Promise { const rate = await cfg.indexer.feerate(STANDARD_TIER_IN_TOP_MB); const input = await utxoInput(htlcTxId, 0); - const output = await cfg.bindings.encodeOutputTransfer('0', destination, cfg.network); - const size = await cfg.bindings.estimateTransactionSize([input], [destination], [output], cfg.network); + const output = await b().encodeOutputTransfer('0', destination, cfg.network); + const size = await b().estimateTransactionSize([input], [destination], [output], cfg.network); const kbCeil = BigInt(Math.max(1, Math.ceil(size / 1000))); const rateBig = BigInt(/^\d+$/.test(rate) ? rate : '0'); return kbCeil * (rateBig > 1n ? rateBig : 1n); @@ -400,9 +408,9 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { }; const witness = kind === 'htlc-spend' - ? await cfg.bindings.encodeWitnessHtlcSpend(params) - : await cfg.bindings.encodeWitnessHtlcRefundSingleSig(params); - const signed = await cfg.bindings.encodeSignedTransaction(transaction, [witness]); + ? await b().encodeWitnessHtlcSpend(params) + : await b().encodeWitnessHtlcRefundSingleSig(params); + const signed = await b().encodeSignedTransaction(transaction, [witness]); return bytesToHex(signed); }); } diff --git a/src/trade/orders.test.ts b/src/trade/orders.test.ts index 6eab1af..b0187b6 100644 --- a/src/trade/orders.test.ts +++ b/src/trade/orders.test.ts @@ -230,7 +230,7 @@ function harness(opts?: { orders?: OrderRow[]; detail?: OrderRow; utxos?: MlUtxo }; const flows = createOrderFlows({ network: 'mainnet', - bindings, + loadBindings: () => bindings, indexer: indexer as never, broadcast, addresses: async () => { diff --git a/src/trade/orders.ts b/src/trade/orders.ts index 215bb35..eea428c 100644 --- a/src/trade/orders.ts +++ b/src/trade/orders.ts @@ -95,7 +95,10 @@ export interface OrderFlows { export type OrderFlowsConfig = { network: MlNetwork; - bindings: MintlayerBindings; + /** The bindings facade loader (MojitoCore): a thunk because the facade + * pulls the native bridge, which the Node gate must not load (the + * realSend config carries the same lazy seam). */ + loadBindings: () => MintlayerBindings; indexer: Pick & { /** Pair-filtered open orders (GET /order/pair/{base}_{quote}). */ ordersByPair(base: string, quote: string): Promise; @@ -127,6 +130,11 @@ export class OrderFlowError extends Error { } export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { + let bindings: MintlayerBindings | null = null; + function b(): MintlayerBindings { + if (bindings === null) bindings = cfg.loadBindings(); + return bindings; + } /** One order transaction at a time: selection reads live UTXOs and the * change allocation mutates the persisted counters (realSend pattern). */ let inFlight = false; @@ -153,18 +161,18 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { async function utxoInput(selected: SelectedMlInput): Promise { const sourceId = hexOf.decode(selected.utxo.outpoint.sourceId); if (sourceId.length !== 32) throw new OrderFlowError('rejected', 'outpoint source id must be 32 bytes'); - const outpointSource = await cfg.bindings.encodeOutpointSourceId( + const outpointSource = await b().encodeOutpointSourceId( sourceId, selected.utxo.outpoint.sourceType === 'BlockReward' ? 'block-reward' : 'transaction', ); - return cfg.bindings.encodeInputForUtxo(outpointSource, selected.utxo.outpoint.index); + return b().encodeInputForUtxo(outpointSource, selected.utxo.outpoint.index); } /** Re-encoded spent output of one selected input (M3 sighash contract). */ async function spentOutput(selected: SelectedMlInput): Promise { return selected.tokenId === null - ? cfg.bindings.encodeOutputTransfer(selected.atoms, selected.address, cfg.network) - : cfg.bindings.encodeOutputTokenTransfer(selected.tokenId, selected.atoms, selected.address, cfg.network); + ? b().encodeOutputTransfer(selected.atoms, selected.address, cfg.network) + : b().encodeOutputTokenTransfer(selected.tokenId, selected.atoms, selected.address, cfg.network); } /** Sign the payer inputs; prebuilt entries (the no-signature order @@ -203,7 +211,7 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { const origin = await resolveOrigin(xpub, payer.address); const privateKey = mlPrivateKeyFromSeed(seed, cfg.network as 'mainnet' | 'testnet', origin.branch, origin.index); witnesses.push( - await cfg.bindings.encodeWitness({ + await b().encodeWitness({ sighashType: 'all', privateKey, address: payer.address, @@ -215,7 +223,7 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { }), ); } - const signed = await cfg.bindings.encodeSignedTransaction(transaction, witnesses); + const signed = await b().encodeSignedTransaction(transaction, witnesses); return bytesToHex(signed); }); } @@ -238,8 +246,8 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { payerInputs: SelectedMlInput[], prebuiltWitnesses: Map, ): Promise<{ txId: string; transaction: Uint8Array }> { - const transaction = await cfg.bindings.encodeTransaction(inputs, outputs, 0); - const localTxId = await cfg.bindings.getTransactionId(transaction, false); + const transaction = await b().encodeTransaction(inputs, outputs, 0); + const localTxId = await b().getTransactionId(transaction, false); const tip = await cfg.indexer.tip(); const signedHex = await cfg.withSession((session) => sign(transaction, payerInputs, prebuiltWitnesses, session, tip.blockHeight + 1)); const result = await cfg.broadcast.broadcastMl(signedHex).catch((e: unknown) => { @@ -262,8 +270,8 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { return Promise.all( outputs.map((leg) => leg.kind === 'coin' - ? cfg.bindings.encodeOutputTransfer('0', leg.address, cfg.network) - : cfg.bindings.encodeOutputTokenTransfer(leg.tokenId ?? '', '0', leg.address, cfg.network), + ? b().encodeOutputTransfer('0', leg.address, cfg.network) + : b().encodeOutputTokenTransfer(leg.tokenId ?? '', '0', leg.address, cfg.network), ), ); } @@ -277,7 +285,7 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { const changeAddress = await cfg.allocateChangeAddress(); try { const orderOutput = (giveAmount: string, askAmount: string): Promise => - cfg.bindings.encodeCreateOrderOutput({ + b().encodeCreateOrderOutput({ give: { tokenId: giveTokenId === COIN_REF ? 'coin' : giveTokenId, atoms: giveAmount }, ask: { tokenId: askTokenId === COIN_REF ? 'coin' : askTokenId, atoms: askAmount }, concludeDestination: changeAddress, @@ -302,7 +310,7 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { destinations.push(selected.address); } const outputBytes = [await orderOutput('0', '0'), ...(await estimateLegs(planned.slice(1)))]; - return cfg.bindings.estimateTransactionSize(inputBytes, destinations, outputBytes, cfg.network); + return b().estimateTransactionSize(inputBytes, destinations, outputBytes, cfg.network); }, }); @@ -315,17 +323,17 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { .reduce((acc, input) => acc + BigInt(input.atoms), 0n); const tokenRemainder = tokenSelected - BigInt(giveAtoms); if (tokenRemainder > 0n) { - outputs.push(await cfg.bindings.encodeOutputTokenTransfer(giveTokenId, tokenRemainder.toString(), changeAddress, cfg.network)); + outputs.push(await b().encodeOutputTokenTransfer(giveTokenId, tokenRemainder.toString(), changeAddress, cfg.network)); } } if (selection.changeAtoms !== '0') { - outputs.push(await cfg.bindings.encodeOutputTransfer(selection.changeAtoms, changeAddress, cfg.network)); + outputs.push(await b().encodeOutputTransfer(selection.changeAtoms, changeAddress, cfg.network)); } const { txId, transaction } = await finish(inputs, outputs, selection.selection, new Map()); // The order id is a bindings extraction on the create tx output // (F11); output 0 is the order output this flow assembled. - const orderId = await cfg.bindings.getOrderId(transaction, 0); + const orderId = await b().getOrderId(transaction, 0); return { txId, orderId }; } catch (e) { await cfg.releaseFailedChange(); @@ -369,11 +377,11 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { destinations.push(selected.address); } const outputBytes = await estimateLegs(planned); - return cfg.bindings.estimateTransactionSize(inputBytes, destinations, outputBytes, cfg.network); + return b().estimateTransactionSize(inputBytes, destinations, outputBytes, cfg.network); }, }); - const fillInput = await cfg.bindings.encodeInputForFillOrder( + const fillInput = await b().encodeInputForFillOrder( decodeBech32Data(orderId), decodeBech32Data(destination), fillAtoms, @@ -383,8 +391,8 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { const outputs: Uint8Array[] = [ order.giveTokenId === COIN_REF - ? await cfg.bindings.encodeOutputTransfer(givePayout, destination, cfg.network) - : await cfg.bindings.encodeOutputTokenTransfer(order.giveTokenId, givePayout, destination, cfg.network), + ? await b().encodeOutputTransfer(givePayout, destination, cfg.network) + : await b().encodeOutputTokenTransfer(order.giveTokenId, givePayout, destination, cfg.network), ]; if (order.askTokenId !== COIN_REF) { const askSelected = selection.selection @@ -392,14 +400,14 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { .reduce((acc, input) => acc + BigInt(input.atoms), 0n); const askRemainder = askSelected - BigInt(fillAtoms); if (askRemainder > 0n) { - outputs.push(await cfg.bindings.encodeOutputTokenTransfer(order.askTokenId, askRemainder.toString(), changeAddress, cfg.network)); + outputs.push(await b().encodeOutputTokenTransfer(order.askTokenId, askRemainder.toString(), changeAddress, cfg.network)); } } if (selection.changeAtoms !== '0') { - outputs.push(await cfg.bindings.encodeOutputTransfer(selection.changeAtoms, changeAddress, cfg.network)); + outputs.push(await b().encodeOutputTransfer(selection.changeAtoms, changeAddress, cfg.network)); } - const noSignature = await cfg.bindings.encodeWitnessNoSignature(); + const noSignature = await b().encodeWitnessNoSignature(); const signedHex = await finishTx(inputs, outputs, selection.selection, new Map([[0, noSignature]])); const result = await cfg.broadcast.broadcastMl(signedHex); return { txId: result.txId }; @@ -439,11 +447,11 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { destinations.push(selected.address); } const outputBytes = await estimateLegs(planned); - return cfg.bindings.estimateTransactionSize(inputBytes, destinations, outputBytes, cfg.network); + return b().estimateTransactionSize(inputBytes, destinations, outputBytes, cfg.network); }, }); - const concludeInput = await cfg.bindings.encodeInputForConcludeOrder( + const concludeInput = await b().encodeInputForConcludeOrder( decodeBech32Data(orderId), decodeBech32Data(order.concludeDestination), ); @@ -454,22 +462,22 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { if (order.giveBalanceAtoms !== '0') { outputs.push( order.giveTokenId === COIN_REF - ? await cfg.bindings.encodeOutputTransfer(order.giveBalanceAtoms, order.concludeDestination, cfg.network) - : await cfg.bindings.encodeOutputTokenTransfer(order.giveTokenId, order.giveBalanceAtoms, order.concludeDestination, cfg.network), + ? await b().encodeOutputTransfer(order.giveBalanceAtoms, order.concludeDestination, cfg.network) + : await b().encodeOutputTokenTransfer(order.giveTokenId, order.giveBalanceAtoms, order.concludeDestination, cfg.network), ); } if (order.askBalanceAtoms !== '0') { outputs.push( order.askTokenId === COIN_REF - ? await cfg.bindings.encodeOutputTransfer(order.askBalanceAtoms, order.concludeDestination, cfg.network) - : await cfg.bindings.encodeOutputTokenTransfer(order.askTokenId, order.askBalanceAtoms, order.concludeDestination, cfg.network), + ? await b().encodeOutputTransfer(order.askBalanceAtoms, order.concludeDestination, cfg.network) + : await b().encodeOutputTokenTransfer(order.askTokenId, order.askBalanceAtoms, order.concludeDestination, cfg.network), ); } if (selection.changeAtoms !== '0') { - outputs.push(await cfg.bindings.encodeOutputTransfer(selection.changeAtoms, changeAddress, cfg.network)); + outputs.push(await b().encodeOutputTransfer(selection.changeAtoms, changeAddress, cfg.network)); } - const noSignature = await cfg.bindings.encodeWitnessNoSignature(); + const noSignature = await b().encodeWitnessNoSignature(); const signedHex = await finishTx(inputs, outputs, selection.selection, new Map([[0, noSignature]])); const result = await cfg.broadcast.broadcastMl(signedHex); return { txId: result.txId }; @@ -500,7 +508,7 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { payerInputs: SelectedMlInput[], prebuiltWitnesses: Map, ): Promise { - const transaction = await cfg.bindings.encodeTransaction(inputs, outputs, 0); + const transaction = await b().encodeTransaction(inputs, outputs, 0); const tip = await cfg.indexer.tip(); return cfg.withSession((session) => sign(transaction, payerInputs, prebuiltWitnesses, session, tip.blockHeight + 1)); } From 740f30e66d5dbed602ed54a1d8a762049a584630 Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 06:41:23 +0100 Subject: [PATCH 08/20] feat(m4): dex, swap and bridge screens on the provider seams --- package.json | 2 +- src/data.ts | 18 +- src/data/mock/fixtures.ts | 6 + src/data/providers/types.ts | 6 + src/data/real/realWalletData.ts | 42 +++- src/i18n/strings/en.ts | 82 ++++++- src/screens/BridgeScreen.tsx | 246 ++++++++++++------- src/screens/DexScreen.tsx | 295 +++++++++++++++++++++-- src/screens/SwapScreen.tsx | 415 +++++++++++++++++++++----------- 9 files changed, 845 insertions(+), 267 deletions(-) diff --git a/package.json b/package.json index ff602d0..e03560d 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "ios:dev": "expo run:ios", "android:dev": "expo run:android", "prebuild": "expo prebuild", - "check": "tsx src/theme.test.ts && tsx src/i18n/strings.test.ts && tsx src/money.test.ts && tsx src/data/polling.test.ts && tsx src/data/ml/indexerClient.test.ts && tsx src/data/btc/btcChainService.test.ts && tsx src/data/addresses/addressManager.test.ts && tsx src/storage/addressStore.test.ts && tsx src/data/activity/activityService.test.ts && tsx src/storage/secureStore.test.ts && tsx src/storage/walletVault.test.ts && tsx src/storage/pinStore.test.ts && tsx src/storage/appSettings.test.ts && tsx src/data/real/realWalletData.test.ts && tsx src/data/providers/providers.test.ts && tsx src/data/providers/broadcast.test.ts && tsx src/keys/bip39.test.ts && tsx src/keys/mlAccounts.test.ts && tsx src/keys/BtcKeyring.test.ts && tsx src/send/validation.test.ts && tsx src/send/mlTxBuilder.test.ts && tsx src/send/btcTxBuilder.test.ts && tsx src/send/TxTracker.test.ts && tsx src/data/real/realSend.test.ts && tsx src/data/mock/mockSend.test.ts && tsx src/keys/session.test.ts && tsx scripts/no-console.ts && tsx scripts/no-em-dash.ts && tsc --noEmit && eslint .", + "check": "tsx src/theme.test.ts && tsx src/i18n/strings.test.ts && tsx src/money.test.ts && tsx src/data/polling.test.ts && tsx src/data/ml/indexerClient.test.ts && tsx src/data/btc/btcChainService.test.ts && tsx src/data/addresses/addressManager.test.ts && tsx src/storage/addressStore.test.ts && tsx src/data/activity/activityService.test.ts && tsx src/storage/secureStore.test.ts && tsx src/storage/walletVault.test.ts && tsx src/storage/pinStore.test.ts && tsx src/storage/appSettings.test.ts && tsx src/data/real/realWalletData.test.ts && tsx src/data/providers/providers.test.ts && tsx src/data/providers/broadcast.test.ts && tsx src/data/providers/bridge.test.ts && tsx src/trade/orderBookService.test.ts && tsx src/trade/orders.test.ts && tsx src/trade/htlc.test.ts && tsx src/trade/swapSession.test.ts && tsx src/trade/priceGuards.test.ts && tsx src/keys/bip39.test.ts && tsx src/keys/mlAccounts.test.ts && tsx src/keys/BtcKeyring.test.ts && tsx src/send/validation.test.ts && tsx src/send/mlTxBuilder.test.ts && tsx src/send/btcTxBuilder.test.ts && tsx src/send/TxTracker.test.ts && tsx src/data/real/realSend.test.ts && tsx src/data/mock/mockSend.test.ts && tsx src/keys/session.test.ts && tsx scripts/no-console.ts && tsx scripts/no-em-dash.ts && tsc --noEmit && eslint .", "lint": "eslint ." }, "dependencies": { diff --git a/src/data.ts b/src/data.ts index 56fe1a9..daf4a91 100644 --- a/src/data.ts +++ b/src/data.ts @@ -95,29 +95,29 @@ export const SWAP_STATS = [ /* ── Bridge ──────────────────────────────────────────────── */ +// M4 (F14, R5): the real bridge scope is exactly Ethereum and Mintlayer; +// the EVM demo chains of the M0 design (Arbitrum, Polygon, BNB) are gone +// and the E2M direction is disabled with explanatory copy (R5: no EVM +// signer; scoped decision open, never silently dropped). export const BRIDGE_CHAINS = [ { name: 'Mintlayer', sym: 'ML' }, - { name: 'Bitcoin', sym: 'BTC' }, { name: 'Ethereum', sym: 'ETH' }, - { name: 'Arbitrum', sym: 'ARB' }, - { name: 'Polygon', sym: 'POL' }, - { name: 'BNB', sym: 'BNB' }, ] satisfies { name: ChainName; sym: string }[]; -/** Arbitrum-side mint contract shown in the route and the bridge fixture. */ +/** Ethereum-side mint contract shown in the route and the bridge fixture. */ export const BRIDGE_CONTRACT = '0xA1c2…F39e'; export const BRIDGE_ROUTE = [ - { label: 'Lock on Mintlayer', detail: 'mojito.mlbridge.v2', icon: 'lock', eta: '~15s' }, - { label: 'Validator attestation', detail: '7 of 11 signatures', icon: 'shield', eta: '~45s' }, - { label: 'Mint on Arbitrum', detail: `${BRIDGE_CONTRACT} (mUSDT)`, icon: 'flash', eta: '~5s' }, + { label: 'Lock on Mintlayer', detail: 'ml deposit to the bridge treasury', icon: 'lock', eta: '~15s' }, + { label: 'Validator attestation', detail: 'agent majority signs the intent', icon: 'shield', eta: '~12 confirmations' }, + { label: 'Mint on Ethereum', detail: `${BRIDGE_CONTRACT} (wrapped asset)`, icon: 'flash', eta: '~1 min' }, ] satisfies { label: string; detail: string; icon: IconName; eta: string }[]; export const BRIDGE_QUOTE = [ ['Bridge fee', '0.15% · $0.75'], ['Est. time', '~65 sec'], ['You receive', '499.25 USDT'], - ['Gas (ARB)', '0.00012 ETH'], + ['Gas (ETH)', '0.00012 ETH'], ] satisfies [string, string][]; /* ── Card ────────────────────────────────────────────────── */ diff --git a/src/data/mock/fixtures.ts b/src/data/mock/fixtures.ts index a1c6d01..23cd73e 100644 --- a/src/data/mock/fixtures.ts +++ b/src/data/mock/fixtures.ts @@ -57,6 +57,12 @@ export function createFixtureWalletData(): WalletData { getMarket: async () => MARKET, getOrderBook: async () => ({ asks: [...ASKS], bids: [...BIDS] }), getTimeframes: async () => [...TIMEFRAMES], + // Mock mode carries a single fixture id so order placement stays + // demoable without pretending to resolve a real on-chain token (F6: + // real tickers are ambiguous and the real mode answers from the + // indexer instead). + getTokenIds: async (ticker) => [ticker], + getTokenMeta: async (tokenId) => ({ ticker: tokenId, decimals: tokenId === 'USDT' ? 6 : 0 }), getHtlcSteps: async () => [...HTLC_STEPS], getSwapStats: async () => SWAP_STATS, getBridgeChains: async () => [...BRIDGE_CHAINS], diff --git a/src/data/providers/types.ts b/src/data/providers/types.ts index bfe1b36..a880c45 100644 --- a/src/data/providers/types.ts +++ b/src/data/providers/types.ts @@ -207,6 +207,12 @@ export interface WalletData { getMarket(pair: string): Promise; getOrderBook(pair: string): Promise<{ asks: BookLevel[]; bids: BookLevel[] }>; getTimeframes(): Promise; + /** Token ids served for one ticker; tickers are not unique (F6), so the + * list can carry more than one id and callers must disambiguate + * honestly instead of guessing (M4 order placement). */ + getTokenIds(ticker: string): Promise; + /** Ticker and decimals of one token id; null when unindexed. */ + getTokenMeta(tokenId: string): Promise<{ ticker: string | null; decimals: number } | null>; // swap getHtlcSteps(): Promise; getSwapStats(): Promise; diff --git a/src/data/real/realWalletData.ts b/src/data/real/realWalletData.ts index c6428c5..d752096 100644 --- a/src/data/real/realWalletData.ts +++ b/src/data/real/realWalletData.ts @@ -13,7 +13,7 @@ // share one scan. import type { ChainName } from '../../theme'; import { t } from '../../i18n'; -import { ML_DECIMALS, atomsToDecimal, formatAmount, formatUsd } from '../../money'; +import { ML_DECIMALS, atomsToDecimal, decimalsToAtoms, formatAmount, formatUsd } from '../../money'; import { IndexerError } from '../ml/IndexerClient'; import type { AssetRow, NftRow, PriceProvider, PriceSnapshot, WalletData } from '../providers/types'; import type { AccountServices, RealAccountContext, RealAccountConfig } from './account'; @@ -218,7 +218,45 @@ export function createRealWalletData(context: RealAccountContext): WalletData { chains: cfg.btcBase ? 2 : 1, }; }, - getMarket: async () => MARKET, + // M4: the market header derives from the R1 price provider (still the + // mock source, so the figures stay indicative and the screens disclose + // pricesAreMock); high, low and volume derive from the 1d candles the + // same source serves. No fixture row leaks into the header. + getMarket: async (pair) => { + const [snapshots, candles] = await Promise.all([price.getSnapshots(['ML', 'BTC']), price.getCandles(pair, '1d')]); + const ml = snapshots.find((s) => s.tokenId === 'ML'); + const btc = snapshots.find((s) => s.tokenId === 'BTC'); + if (!ml) return MARKET; + const highDecimal = candles.reduce((acc, c) => (BigInt(decimalsToAtoms(c.h, 11)) > BigInt(decimalsToAtoms(acc, 11)) ? c.h : acc), candles[0]?.h ?? '0'); + const lowDecimal = candles.reduce((acc, c) => (BigInt(decimalsToAtoms(c.l, 11)) < BigInt(decimalsToAtoms(acc, 11)) ? c.l : acc), candles[0]?.h ?? '0'); + const volumeAtoms = candles.reduce((acc, c) => acc + BigInt(decimalsToAtoms(c.v, 11)), 0n); + const btcRatio = btc && ml.usd !== '0' ? (Number(ml.usd) / Number(btc.usd)).toFixed(7) : null; + return { + pair, + last: formatUsd(ml.usd), + change: ml.change24hPct, + btc: btcRatio !== null ? `≈ ${btcRatio} BTC` : '', + high: formatUsd(highDecimal), + low: formatUsd(lowDecimal), + volume: `24h vol ${formatUsd(atomsToDecimal(volumeAtoms.toString(), 11), { compact: true })}`, + price: Number(ml.usd), + }; + }, + // F6: tickers are not unique, so placement disambiguates on the full + // id list instead of guessing the first row. + getTokenIds: async (ticker) => { + const indexer = requireIndexer(); + return indexer.tokensByTicker(ticker); + }, + getTokenMeta: async (tokenId) => { + const acct = await ensureAccount(); + if (!acct.balance) return null; + try { + return await acct.balance.tokenMeta(tokenId); + } catch { + return null; + } + }, getOrderBook: async () => ({ asks: [...ASKS], bids: [...BIDS] }), getTimeframes: async () => [...TIMEFRAMES], getHtlcSteps: async () => [...HTLC_STEPS], diff --git a/src/i18n/strings/en.ts b/src/i18n/strings/en.ts index fd511fa..3f3d9ae 100644 --- a/src/i18n/strings/en.ts +++ b/src/i18n/strings/en.ts @@ -16,7 +16,6 @@ export const en = { 'common.max': 'Max', 'common.selectAsset': 'Select asset', 'common.youSend': 'You send', - 'common.youReceive': 'You receive', 'common.amount': 'Amount', 'common.total': 'Total', 'common.networkFee': 'Network fee', @@ -188,36 +187,90 @@ export const en = { 'dex.networkFeeValue': '{fee} ML · ~{usd}', 'dex.onchainSettlement': 'Onchain settlement', 'dex.settlementEta': '~12s', - 'dex.placeBuy': 'Place buy order · {amount} ML', - 'dex.placeSell': 'Place sell order · {amount} ML', + // M4 live book and order flows + 'dex.book.asks': 'ASKS', + 'dex.book.bids': 'BIDS', + 'dex.book.stale': 'Book data is stale. Pull to refresh for fresh depth.', + 'dex.order.place': 'Place order', + 'dex.order.give': 'You give', + 'dex.order.ask': 'You ask', + 'dex.order.confirm.title': 'Confirm order', + 'dex.order.mine': 'My orders', + 'dex.order.frozen': 'Frozen', + 'dex.order.concluded': 'Concluded', + 'dex.order.signingPending': 'Signing runs on the device bindings, which are pending on this build. Nothing was sent.', + 'dex.order.broadcastOff': 'Order placement needs the Mintlayer submission route, which is not configured for this network (R3). Nothing was sent.', + 'dex.fill.amount': 'Fill amount', + 'dex.fill.slippageWarn': 'This price has drifted {drift}% from the book mid. Review before continuing.', + 'dex.conclude.confirm': 'Conclude closes the order and returns every remaining balance to your conclude address.', + 'dex.priceIndicative': 'Indicative price source (mock). Verify before trading.', + 'dex.book.error': 'The live book is unreachable right now.', + 'dex.order.demo': 'Demo order placed. This is simulated data, not a chain order.', // swap 'swap.title': 'Atomic Swap', 'swap.chip': 'HTLC', 'swap.blurb': 'Trustless cross-chain swap. No bridge, no custodian.', - 'swap.success.title': 'Swap initiated', - 'swap.success.pending': '{from} {fromSym} → {toSym}', - 'swap.success.desc': 'The HTLC is locked on {chain}. Settlement completes once the counterparty reveals the preimage.', - 'swap.protocol': 'Swap protocol · HTLC', - 'swap.flip': 'Flip swap direction', - 'swap.cta': 'Initiate atomic swap', + // M4 HTLC swap session + 'swap.offer.rate': 'Rate', + 'swap.offer.timelock': 'Refund timelock', + 'swap.initiate': 'Lock Mintlayer', + 'swap.step.lock': 'Lock Mintlayer', + 'swap.step.lockDetail': 'HTLC with the secret hash · refund after {hours}h', + 'swap.step.match': 'Counterparty locks Bitcoin', + 'swap.step.matchDetail': 'Same hash, shorter timelock · scripted demo', + 'swap.step.claim': 'Reveal preimage', + 'swap.step.claimDetail': 'Claim BTC, the secret becomes public', + 'swap.step.settle': 'Counterparty settles', + 'swap.step.settleDetail': 'Claims the Mintlayer HTLC atomically', + 'swap.state.offered': 'Offered · awaiting lock', + 'swap.state.locked': 'Locked · swap in flight', + 'swap.state.claiming': 'Claim in progress', + 'swap.state.pending': 'Settling', + 'swap.state.settled': 'Settled', + 'swap.state.refunded': 'Refunded', + 'swap.state.expired': 'Expired', + 'swap.warn.keepOpen': 'Keep this screen open until settlement: the preimage lives only in memory. Losing it forfeits the swap (the refund path still works).', + 'swap.error.timelockRule': 'The Bitcoin timelock must stay well under the Mintlayer one. Pick a longer Mintlayer timelock.', + 'swap.refund.cta': 'Refund after timelock', + 'swap.session.empty': 'No swap sessions yet. Initiate one to see the live protocol steps.', + 'swap.session.title': 'Swap sessions', + 'swap.error.devicePending': 'The swap locks Mintlayer through the device bindings, which are pending on this build. Nothing was sent.', + 'swap.broadcastOff': 'The swap needs the Mintlayer submission route, which is not configured for this network (R3). Nothing was sent.', + 'swap.demo.note': 'Demo mode: the counterparty leg is scripted, ids are simulated.', // bridge 'bridge.title': 'Bridge', 'bridge.chip': 'ML ⇄ EVM', 'bridge.blurb': 'Move Mintlayer assets to Ethereum and other EVM chains.', 'bridge.success.title': 'Bridge started', - 'bridge.success.desc': 'Locked on {src}. Funds mint on {dst} once validators attest - usually about a minute.', - 'bridge.from': 'Bridge from', 'bridge.to': 'Bridge to', 'bridge.sideFrom': 'From', 'bridge.sideTo': 'To', 'bridge.finalOn': 'FINAL ON {chain}', 'bridge.badge': 'MOJITO BRIDGE · v2', - 'bridge.swapSides': 'Swap bridge sides', 'bridge.available': 'Available {amount} {token}', 'bridge.route': 'Route', 'bridge.cta': 'Bridge {amount} {token} to {chain}', + // M4 bridge_v2 integration + 'bridge.chain.ethereum': 'Ethereum', + 'bridge.chain.mintlayer': 'Mintlayer', + 'bridge.quote.fee': 'Bridge fee', + 'bridge.quote.eta': 'Estimated time', + 'bridge.quote.confirmations': 'Deposit confirmations', + 'bridge.quote.depositAddress': 'Deposit address', + 'bridge.state.awaitingDeposit': 'Awaiting deposit', + 'bridge.state.attesting': 'Agents attesting', + 'bridge.state.minted': 'Minted', + 'bridge.state.released': 'Released', + 'bridge.state.failed': 'Failed', + 'bridge.dev.mockBanner': 'Demo bridge: quotes and states are simulated in this build.', + 'bridge.route.e2m.unavailable': 'Ethereum to Mintlayer needs an EVM signer this wallet does not have yet. The direction stays disabled while the signer decision is open (R5).', + 'bridge.error.unsupported': 'This bridge route cannot start from the wallet yet. Nothing was sent.', + 'bridge.error.network': 'Could not reach the bridge service. Check your connection.', + 'bridge.error.disabled': 'No bridge service is configured for this network.', + 'bridge.error.failed': 'The bridge service answered with an error. Try again later.', + 'bridge.tracking.title': 'Bridge tracking', // card 'card.title': 'Mojito Card', @@ -299,6 +352,11 @@ export const en = { 'errors.indexer.network': 'Could not reach the Mintlayer index. Check your connection.', 'errors.indexer.testnet': "Testnet data isn't connected yet. Balances and activity will appear once the testnet index ships.", 'errors.price.unavailable': 'Price data is unavailable right now.', + // M4 trade errors + 'errors.orders.invalidCursor': 'The order book page went stale. Refreshing from the top.', + 'errors.orders.notMine': 'Only the order creator can conclude an order.', + 'errors.htlc.expired': 'The refund unlocks after the timelock expiry.', + 'errors.orders.book': 'The order book is unavailable right now.', // onboarding 'onboarding.welcome.tagline': 'One recovery phrase, every account.\nBitcoin and Mintlayer, self-custody.', diff --git a/src/screens/BridgeScreen.tsx b/src/screens/BridgeScreen.tsx index fd83dfa..dc802ed 100644 --- a/src/screens/BridgeScreen.tsx +++ b/src/screens/BridgeScreen.tsx @@ -1,45 +1,107 @@ -import React, { useState } from 'react'; -import { Pressable, View } from 'react-native'; +import React, { useCallback, useEffect, useRef, useState } from 'react'; +import { View } from 'react-native'; import Svg, { Defs, LinearGradient as SvgGrad, Path, Stop } from 'react-native-svg'; import { t } from '../i18n'; -import { useData } from '../data/providers/context'; +import { useData, useProviders } from '../data/providers/context'; +import { decimalsToAtoms, atomsToDecimal } from '../money'; import { C, CHAINS, G, alpha } from '../theme'; import type { ChainName } from '../theme'; -import { AmountRow, Btn, Card, ChainGlyph, FlowX, Icon, KVGrid, Label, ListRow, PickerSheet, Screen, ScreenIntro, SuccessScreen, TokenPicker, Txt, hairlineTop, tile } from '../ui'; +import { AmountRow, Btn, Callout, Card, ChainGlyph, FlowX, Icon, KVGrid, KVRow, Label, PickerSheet, Screen, ScreenIntro, Txt, hairlineTop, tile } from '../ui'; + +/** The real bridge scope (F14, R5): exactly these two chains, with the E2M + * direction disabled pending the EVM signer decision. */ +const HOME_CHAIN = 'Mintlayer'; +const COUNTERPARTY_CHAIN = 'Ethereum' as ChainName; export function BridgeScreen() { const assets = useData((d) => d.getAssets()); const assetBalances = useData((d) => d.getAssetBalances()); - const assetSymbols = useData((d) => d.getAssetSymbols()); - const bridgeChains = useData((d) => d.getBridgeChains()); - const bridgeQuote = useData((d) => d.getBridgeQuote()); - const bridgeRoute = useData((d) => d.getBridgeRoute()); - const [src, setSrc] = useState('Mintlayer'); - const [dst, setDst] = useState('Arbitrum'); + const { bridge, mode } = useProviders(); const [amount, setAmount] = useState('500.00'); - const [token, setToken] = useState('USDT'); + // M2E demo asset: the fees route carries the per-token rows; the picker + // lands with the multi-token deposit flow (v2). + const token = 'USDT'; const [chainPicker, setChainPicker] = useState(false); - const [tokenPicker, setTokenPicker] = useState(false); + const [quote, setQuote] = useState<{ feePct: string; feeAmount: string; confirmationsRequired?: number; destContractOrAddress: string } | null>(null); + const [quoteError, setQuoteError] = useState(null); + /** Honest gate states: quote refresh, CTA gate and the tracking handle. */ + const [gateError, setGateError] = useState(null); + const [tracking, setTracking] = useState<{ id: string; state: string } | null>(null); const [submitted, setSubmitted] = useState(false); + const pollRef = useRef | null>(null); + const src = HOME_CHAIN; + const dst = COUNTERPARTY_CHAIN; + + const loadQuote = useCallback(async () => { + setQuoteError(null); + try { + const result = await bridge.quote({ route: 'M2E', token, amount, destAddr: '' }); + setQuote(result); + } catch (e) { + setQuote(null); + setQuoteError(bridgeErrorCopy(e)); + } + }, [bridge, token, amount]); + + useEffect(() => { + void loadQuote(); + }, [loadQuote]); - // The picked chain always lands on whichever side isn't Mintlayer. - const pickChain = (name: ChainName) => (src === HOME_CHAIN ? setDst(name) : setSrc(name)); + useEffect(() => { + return () => { + if (pollRef.current) clearInterval(pollRef.current); + }; + }, []); - if (!assets || !assetBalances || !assetSymbols || !bridgeChains || !bridgeQuote || !bridgeRoute) return ; - const counterpartyChains = bridgeChains.map((c) => c.name).filter((n) => n !== HOME_CHAIN); - // Same source the token picker uses, so the caption cannot drift from it. + if (!assets || !assetBalances) return ; const tokenBalance = assets.find((a) => a.sym === token)?.amt ?? 0; + const receiveAmount = quote + ? atomsToDecimal((BigInt(decimalsToAtoms(amount, 18)) - BigInt(decimalsToAtoms(quote.feeAmount, 18))).toString(), 18) + : null; + + /** The CTA: mock mode runs the simulated bridge walk (demo chip copy); + * real mode hits the honest gate (no deposit intent encoder, R3 route + * unconfigured), so nothing reads as started when it was not. */ + const startBridge = async () => { + setGateError(null); + try { + const handle = await bridge.initiate({ route: 'M2E', token, amount, destAddr: '' }); + setTracking({ id: handle.id, state: t('bridge.state.awaitingDeposit') }); + pollRef.current = setInterval(() => { + void (async () => { + try { + const state = await bridge.status(handle); + setTracking({ id: handle.id, state: bridgeStateCopy(state) }); + } catch { + setTracking((prev) => prev); + } + })(); + }, 10_000); + setSubmitted(true); + } catch (e) { + setGateError(bridgeErrorCopy(e)); + } + }; if (submitted) { return ( - setSubmitted(false)} - /> + + + + + + + {tracking?.state ?? t('bridge.state.awaitingDeposit')} + + + {tracking?.id.slice(0, 24)}… + + setSubmitted(false)}> + {t('common.done')} + + + + ); } @@ -47,43 +109,39 @@ export function BridgeScreen() { + {mode === 'mock' && ( + + {t('bridge.dev.mockBanner')} + + )} + {gateError && ( + + {gateError} + + )} + setChainPicker(false)} - title={src === HOME_CHAIN ? t('bridge.to') : t('bridge.from')} - options={counterpartyChains} - value={src === HOME_CHAIN ? dst : src} - onSelect={pickChain} + title={t('bridge.to')} + options={[COUNTERPARTY_CHAIN]} + value={dst} + onSelect={() => undefined} renderLeading={(n) => } - subtitleFor={(n) => bridgeChains.find((c) => c.name === n)?.sym} - /> - - setTokenPicker(false)} - symbols={assetSymbols} - value={token} - balances={assetBalances} - onSelect={setToken} + subtitleFor={(n) => t(n === 'Ethereum' ? 'bridge.chain.ethereum' : 'bridge.chain.mintlayer')} /> {/* Tunnel */} - c.name === src)?.sym ?? src} side={t('bridge.sideFrom')} onPress={src === HOME_CHAIN ? undefined : () => setChainPicker(true)} /> - { - setSrc(dst); - setDst(src); - }} - accessibilityRole="button" - accessibilityLabel={t('bridge.swapSides')} + + - - c.name === dst)?.sym ?? dst} side={t('bridge.sideTo')} onPress={dst === HOME_CHAIN ? undefined : () => setChainPicker(true)} /> + + @@ -145,42 +203,50 @@ export function BridgeScreen() { {t('bridge.available', { amount: tokenBalance.toLocaleString(), token })} - setTokenPicker(true)} /> + - {/* Route */} + {/* Route steps and the live quote (real provider or dev mock). */} - {bridgeRoute.map((r, i) => ( - {r.label}} - sub={ - - {r.detail} - - } - trailing={ - - {r.eta} - - } - connector={i < bridgeRoute.length - 1} - compact - /> - ))} - - (i === 1 ? C.violet : C.text0)} /> + {quoteError && ( + + {quoteError} + + )} + + {quote && ( + <> + + {quote.confirmationsRequired !== undefined && ( + + )} + {receiveAmount !== null && } + + + )} + {!quote && !quoteError && } + {quote?.confirmationsRequired !== undefined && ( + + + + )} + {/* E2M direction: disabled with the honest R5 copy (never silently + dropped; the scoped EVM signer decision stays open). */} - setSubmitted(true)}> + + {t('bridge.route.e2m.unavailable')} + + + + + void startBridge()}> {t('bridge.cta', { amount, token, chain: dst })} @@ -188,23 +254,39 @@ export function BridgeScreen() { ); } -const HOME_CHAIN = 'Mintlayer'; +function bridgeErrorCopy(e: unknown): string { + const record = e as { failure?: string } | null; + switch (record?.failure) { + case 'network': return t('bridge.error.network'); + case 'disabled': return t('bridge.error.disabled'); + case 'failed': return t('bridge.error.failed'); + default: return t('bridge.error.unsupported'); + } +} -function ChainCard({ name, sym, side, onPress }: { name: ChainName; sym: string; side: string; onPress?: () => void }) { +function bridgeStateCopy(state: string): string { + switch (state) { + case 'awaiting-deposit': return t('bridge.state.awaitingDeposit'); + case 'attesting': return t('bridge.state.attesting'); + case 'minted': return t('bridge.state.minted'); + case 'released': return t('bridge.state.released'); + case 'failed': return t('bridge.state.failed'); + default: return t('bridge.state.attesting'); + } +} + +function ChainCard({ name, side }: { name: ChainName; side: string }) { const c = CHAINS[name]; return ( - + {side.toUpperCase()} {name} - {sym} + {t(name === 'Ethereum' ? 'bridge.chain.ethereum' : 'bridge.chain.mintlayer')} - {onPress && } - + ); } - -/* ══ Card ═══════════════════════════════════════════════════ */ diff --git a/src/screens/DexScreen.tsx b/src/screens/DexScreen.tsx index b2024f8..cbdfae1 100644 --- a/src/screens/DexScreen.tsx +++ b/src/screens/DexScreen.tsx @@ -1,24 +1,73 @@ -import React, { useEffect, useState } from 'react'; +import React, { useCallback, useEffect, useState } from 'react'; import { Pressable, View } from 'react-native'; import { t } from '../i18n'; import { useData, useProviders } from '../data/providers/context'; import type { Candle, CandleInterval } from '../data/providers'; +import type { OrderData } from '../trade/orders'; +import { COIN_REF, orderPhase } from '../trade/orders'; +import { checkAmounts, checkSlippage } from '../trade/priceGuards'; +import { isBindingsUnavailable } from '../send/errors'; +import { ML_DECIMALS, atomsToDecimal, decimalsToAtoms } from '../money'; import { C, G, alpha, black } from '../theme'; -import { Btn, Candles, Card, Chip, Enter, Field, IconBtn, KVRow, Label, LivePill, PctButtons, Screen, Segmented, Txt, tile, usd } from '../ui'; +import { Btn, Candles, Card, Chip, Enter, Field, IconBtn, KVRow, Label, LivePill, PctButtons, Screen, Segmented, Sheet, Txt, tile, usd } from '../ui'; + +/** How long a fetched book stays fresh before the stale banner shows. */ +const BOOK_STALE_MS = 90_000; +const BOOK_POLL_MS = 30_000; +/** Slippage band for the ticket (guard rejects beyond it). */ +const MAX_SLIPPAGE_PCT = 1; export function DexScreen() { const market = useData((d) => d.getMarket('ML/USDT')); - const orderBook = useData((d) => d.getOrderBook('ML/USDT')); const timeframes = useData((d) => d.getTimeframes()); const fees = useData((d) => d.getFees()); const assets = useData((d) => d.getAssets()); + const askTokenIds = useData((d) => d.getTokenIds('USDT')); + const askMeta = useData((d) => d.getTokenMeta('USDT')); + const { price, orderBook: bookService, orders, mode, pricesAreMock } = useProviders(); const [side, setSide] = useState<'buy' | 'sell'>('buy'); const [book, setBook] = useState<'book' | 'trades' | 'depth'>('book'); const [orderType, setOrderType] = useState<'Limit' | 'Market' | 'Stop'>('Limit'); const [tf, setTf] = useState('1h'); const [amount, setAmount] = useState('250'); - const { price } = useProviders(); const [candles, setCandles] = useState(null); + + // Live book (spec M4): aggregated levels from the order book service with + // a poll cycle, a stale banner and typed error states. Mock mode serves + // the same rows from fixtures, so the screen never branches on the mode. + const [liveBook, setLiveBook] = useState<{ asks: { price: string; size: string; total: string }[]; bids: { price: string; size: string; total: string }[] } | null>(null); + const [bookError, setBookError] = useState(null); + const [bookLoadedAt, setBookLoadedAt] = useState(0); + const [refreshKey, setRefreshKey] = useState(0); + useEffect(() => { + let live = true; + const load = async () => { + try { + const [asks, bids] = await Promise.all([ + bookService.levels('ML', 'USDT', 'ask'), + bookService.levels('ML', 'USDT', 'bid'), + ]); + if (!live) return; + setLiveBook({ asks, bids }); + setBookError(null); + setBookLoadedAt(Date.now()); + } catch (e) { + if (!live) return; + // A stale cursor page recovers internally (page-1 restart); a 400 + // that still surfaces names the cursor, anything else the book. + const record = e as { status?: number } | null; + setBookError(record?.status === 400 ? t('errors.orders.invalidCursor') : t('dex.book.error')); + setBookLoadedAt(Date.now()); + } + }; + void load(); + const timer = setInterval(load, BOOK_POLL_MS); + return () => { + live = false; + clearInterval(timer); + }; + }, [bookService, refreshKey]); + useEffect(() => { let live = true; price.getCandles('ML/USDT', tf).then((rows) => { @@ -29,16 +78,81 @@ export function DexScreen() { }; }, [price, tf]); - if (!market || !orderBook || !timeframes || !fees || !candles || !assets) return ; - const maxAsk = Math.max(...orderBook.asks.map((r) => r.t)); - const maxBid = Math.max(...orderBook.bids.map((r) => r.t)); + // My orders (spec: actions on orders flagged as mine). + const [myOrders, setMyOrders] = useState(null); + const [ordersError, setOrdersError] = useState(null); + const loadMyOrders = useCallback(async () => { + try { + setMyOrders(await orders.myOrders()); + setOrdersError(null); + } catch { + setOrdersError(t('errors.orders.book')); + } + }, [orders]); + useEffect(() => { + void loadMyOrders(); + }, [loadMyOrders]); + + // Place-order sheet state. + const [confirmOpen, setConfirmOpen] = useState(false); + const [ticketError, setTicketError] = useState(null); + const [placing, setPlacing] = useState(false); + const [lastDemoNote, setLastDemoNote] = useState(null); + + const bookRows = liveBook; + if (!market || !timeframes || !fees || !candles || !assets || !askTokenIds || !askMeta || !bookRows) return ; + const maxAsk = Math.max(...bookRows.asks.map((r) => Number(r.total || 0)), 1); + const maxBid = Math.max(...bookRows.bids.map((r) => Number(r.total || 0)), 1); const total = usd(amount, market.price); - /** Spread between the best ask and best bid, percent relative to the ask. */ - const bestAsk = orderBook.asks[0]?.p ?? market.price; - const bestBid = orderBook.bids[0]?.p ?? market.price; + const bestAsk = Number(bookRows.asks[0]?.price ?? market.price); + const bestBid = Number(bookRows.bids[0]?.price ?? market.price); const spread = Math.abs(bestAsk - bestBid); const spreadPct = (spread / bestAsk) * 100; const mlBalance = assets.find((a) => a.sym === 'ML')?.amt ?? 0; + const bookIsStale = bookLoadedAt > 0 && Date.now() - bookLoadedAt > BOOK_STALE_MS; + + /** Ticket submit: guards first, then the order flows. Real mode runs the + * full pipeline (device-pending and config-pending states surface + * honestly); mock mode runs the demo pipeline labelled as demo. */ + const placeOrder = async () => { + setTicketError(null); + const guard = checkAmounts({ giveDecimal: amount, askDecimal: total }); + if (!guard.ok) { + setTicketError(t('dex.order.place')); + return; + } + // Slippage guard versus the live book mid (the ticket prices at the + // header snapshot, so the drift check runs before anything is built). + const mid = (bestAsk + bestBid) / 2; + if (mid > 0) { + const slippage = checkSlippage({ limitDecimal: market.price.toFixed(6), midDecimal: mid.toFixed(6), maxSlippagePct: MAX_SLIPPAGE_PCT }); + if (!slippage.ok) { + setTicketError(t('dex.fill.slippageWarn', { drift: ((Math.abs(market.price - mid) / mid) * 100).toFixed(2) })); + return; + } + } + if (askTokenIds.length !== 1) { + setTicketError(t('errors.orders.notMine')); + return; + } + setPlacing(true); + try { + await orders.createOrder({ + giveTokenId: COIN_REF, + giveAtoms: decimalsToAtoms(amount, ML_DECIMALS), + askTokenId: askTokenIds[0], + askAtoms: decimalsToAtoms(total, askMeta.decimals || ML_DECIMALS), + }); + setConfirmOpen(false); + setLastDemoNote(mode === 'mock' ? t('dex.order.demo') : null); + void loadMyOrders(); + } catch (e) { + setConfirmOpen(false); + setTicketError(orderErrorCopy(e)); + } finally { + setPlacing(false); + } + }; return ( @@ -69,9 +183,11 @@ export function DexScreen() { - - {market.btc} - + {market.btc.length > 0 && ( + + {market.btc} + + )} {t('dex.high24h')} @@ -89,6 +205,9 @@ export function DexScreen() { + {pricesAreMock && ( + {t('dex.priceIndicative')} + )} @@ -102,15 +221,29 @@ export function DexScreen() { /> - {/* Order book */} + {/* Order book: live levels, honest stale and error states. */} + {bookError && ( + + + {bookError} + + + )} + {bookIsStale && !bookError && ( + setRefreshKey((k) => k + 1)} className="mx-4 mb-2"> + + {t('dex.book.stale')} + + + )} {t('dex.col.price')} {t('dex.col.size')} {t('dex.col.total')} - {orderBook.asks.map((r, i) => ( + {bookRows.asks.map((r, i) => ( ))} @@ -128,7 +261,7 @@ export function DexScreen() { - {orderBook.bids.map((r, i) => ( + {bookRows.bids.map((r, i) => ( ))} @@ -174,9 +307,19 @@ export function DexScreen() { - - {side === 'buy' ? t('dex.placeBuy', { amount }) : t('dex.placeSell', { amount })} + setConfirmOpen(true)}> + {t('dex.order.place')} + {ticketError && ( + + {ticketError} + + )} + {lastDemoNote && ( + + {lastDemoNote} + + )} @@ -184,25 +327,131 @@ export function DexScreen() { + + {/* My orders: fill and conclude on orders flagged as mine. */} + + + + {ordersError && ( + + {ordersError} + + )} + {myOrders !== null && myOrders.length === 0 && ( + {t('swap.session.empty')} + )} + {myOrders?.map((order) => ( + void loadMyOrders()} + onError={setTicketError} + /> + ))} + + + + {/* Confirm sheet: the exact give and ask amounts before anything is + built (spec order entry guards). */} + setConfirmOpen(false)} title={t('dex.order.confirm.title')}> + + + + + + + {mode === 'mock' && ( + + {t('bridge.dev.mockBanner')} + + )} + void placeOrder()}> + {placing ? t('swap.state.pending') : t('dex.order.place')} + + ); } +/** Order flow failures to screen copy (device-pending and config-pending + * stay explicit: nothing reads as sent when it was not). */ +function orderErrorCopy(e: unknown): string { + if (isBindingsUnavailable(e)) return t('dex.order.signingPending'); + const record = e as { reason?: string } | null; + if (record && typeof record.reason === 'string') { + if (record.reason === 'broadcast-disabled') return t('dex.order.broadcastOff'); + if (record.reason === 'not-mine') return t('errors.orders.notMine'); + if (record.reason === 'busy') return t('swap.state.pending'); + } + return t('dex.book.error'); +} + +function MyOrderRow({ order, onDone, onError }: { order: OrderData; onDone: () => void; onError: (message: string) => void }) { + const { orders } = useProviders(); + const phase = orderPhase(order); + const [busy, setBusy] = useState(false); + const run = async (action: () => Promise) => { + setBusy(true); + try { + await action(); + onDone(); + } catch (e) { + onError(orderErrorCopy(e)); + } finally { + setBusy(false); + } + }; + return ( + + + + {`${order.orderId.slice(0, 18)}…`} + + + {t(phase === 'frozen' ? 'dex.order.frozen' : phase === 'concluded' ? 'dex.order.concluded' : 'dex.order.mine')} + + + + {`give ${atomsToDecimal(order.giveBalanceAtoms, ML_DECIMALS)} ML · ask ${atomsToDecimal(order.askBalanceAtoms, ML_DECIMALS)} USDT`} + + {phase !== 'concluded' && ( + + void run(() => orders.fillOrder({ orderId: order.orderId, fillAtoms: order.askBalanceAtoms, destination: order.concludeDestination }))}> + {t('dex.fill.amount')} + + void run(() => orders.concludeOrder({ orderId: order.orderId }))}> + {t('dex.conclude.confirm').split(' ')[0]} + + + )} + + ); +} + /** Order-book line with a depth bar filling from the right. */ -function BookRow({ row, max, tone, delay }: { row: { p: number; s: number; t: number }; max: number; tone: string; delay: number }) { +function BookRow({ row, max, tone, delay }: { row: { price: string; size: string; total: string }; max: number; tone: string; delay: number }) { + const totalNumber = Number(row.total || 0); return ( - + 0 ? Math.min(100, (totalNumber / max) * 100) : 0}%`, backgroundColor: alpha(tone, 0.18) }} /> - {row.p.toFixed(4)} + {Number(row.price).toFixed(4)} - {row.s.toLocaleString()} + {Number(row.size).toLocaleString()} - {row.t.toLocaleString()} + {totalNumber.toLocaleString()} diff --git a/src/screens/SwapScreen.tsx b/src/screens/SwapScreen.tsx index 0395301..860cf7a 100644 --- a/src/screens/SwapScreen.tsx +++ b/src/screens/SwapScreen.tsx @@ -1,164 +1,312 @@ -import React, { useState } from 'react'; -import { Pressable, StyleSheet, View } from 'react-native'; -import { LinearGradient } from 'expo-linear-gradient'; +import React, { useCallback, useEffect, useRef, useState } from 'react'; +import { View } from 'react-native'; import Svg, { Circle, Defs, Line, LinearGradient as SvgGrad, Rect, Stop, Text as SvgText } from 'react-native-svg'; -import { t } from '../i18n'; -import { useData } from '../data/providers/context'; +import { sha256 } from '@noble/hashes/sha2.js'; +import { bytesToHex } from '@noble/hashes/utils.js'; +import { t, type I18nKey } from '../i18n'; +import { useProviders } from '../data/providers/context'; +import { fnv1a } from '../data/mock/hash'; +import { MojitoCore } from '../../modules/mojito-core'; +import { isBindingsUnavailable } from '../send/errors'; +import { checkTimelockRule } from '../trade/priceGuards'; +import type { SwapSessionRow, SwapState } from '../trade/swapSession'; +import type { StepState } from '../ui/StepState'; import { C, G } from '../theme'; -import { AmountRow, Btn, Card, FlowX, Icon, KVGrid, Label, PctButtons, Screen, ScreenIntro, Steps, SuccessScreen, TokenPicker, Txt, gradColors, quantizeAmount, usd } from '../ui'; +import { AmountRow, Btn, Callout, Card, FlowX, Label, PctButtons, Screen, ScreenIntro, Segmented, Steps, Txt } from '../ui'; -/** One side of a swap: token, chain, typed amount and provider balance. */ -type SwapPanelData = { sym: string; chain: string; amt: string; bal: number }; +const ML_DECIMALS = 11; +const TIMELOCK_CHOICES = ['12h', '24h', '48h'] as const; +type TimelockChoice = (typeof TIMELOCK_CHOICES)[number]; +const TIMELOCK_SECONDS: Record = { '12h': 43_200, '24h': 86_400, '48h': 172_800 }; +/** Demo counterparty spend key (the offer exchange is off-band and the BTC + * side is the scripted counterpart; see scripts/e2e-testnet.mjs). */ +const COUNTERPARTY_ADDRESS = 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl'; export function SwapScreen() { - const assets = useData((d) => d.getAssets()); - const assetBalances = useData((d) => d.getAssetBalances()); - const assetSymbols = useData((d) => d.getAssetSymbols()); - const htlcSteps = useData((d) => d.getHtlcSteps()); - const swapStats = useData((d) => d.getSwapStats()); - /** Panels start null and resolve from provider assets, the same source the picker uses. */ - const [from, setFrom] = useState(null); - const [to, setTo] = useState(null); - /** Which panel the picker is editing, or null when closed. */ - const [picking, setPicking] = useState<'from' | 'to' | null>(null); - const [submitted, setSubmitted] = useState(false); - /** Approx-USD conversion reads provider fixture prices, not screen constants. */ - const priceMap = Object.fromEntries((assets ?? []).map((a) => [a.sym, a.price] as const)); - - /** Build a panel from the provider asset row; a fresh pick starts at amount zero. */ - const sideDefaults = (sym: string): SwapPanelData => { - const asset = assets?.find((a) => a.sym === sym); - return { sym, chain: asset?.chain ?? '', amt: '0', bal: asset ? asset.amt : 0 }; - }; - const fromPanel = from ?? sideDefaults('BTC'); - const toPanel = to ?? sideDefaults('ML'); + const assets = useDataCompat(); + const { htlc, swapSessions, mode } = useProviders(); + const [amount, setAmount] = useState('0.025'); + const [timelock, setTimelock] = useState('48h'); + const [sessions, setSessions] = useState(null); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + /** The preimage lives only in this closure (spec security note): it never + * persists and never logs; losing it forfeits the swap, which the + * keep-open warning discloses. */ + const preimageRef = useRef(null); + + const loadSessions = useCallback(async () => { + try { + setSessions(await swapSessions.all()); + } catch { + setSessions([]); + } + }, [swapSessions]); + useEffect(() => { + void loadSessions(); + }, [loadSessions]); - const flip = () => { - setFrom(toPanel); - // The receive side has no quote yet, so it never carries a typed amount. - setTo({ ...fromPanel, amt: '0' }); + /** Lock Mintlayer: secret generated off-band, only the hash crosses the + * wire; the session persists with the hash and the tx ids alone. */ + const initiate = async () => { + setError(null); + const mlSeconds = TIMELOCK_SECONDS[timelock]; + // TIMELOCK_RULE: the scripted BTC leg locks at half the ML timelock, + // which the guard enforces before anything is built. + const guard = checkTimelockRule({ mlSeconds, btcSeconds: mlSeconds / 2 }); + if (!guard.ok) { + setError(t('swap.error.timelockRule')); + return; + } + setBusy(true); + try { + const secret = await swapSecret(mode); + const secretHash = sha256(secret); + preimageRef.current = secret; + const { txId } = await htlc.initiate( + { + role: 'initiator', + giveChain: 'ml', + giveAtoms: toAtoms(amount), + wantAtoms: wantAtomsOf(amount), + secretHash, + timelockSeconds: mlSeconds, + }, + { address: COUNTERPARTY_ADDRESS, pubkey: new Uint8Array(33).fill(0x02) }, + COUNTERPARTY_ADDRESS, + ); + await swapSessions.save({ + id: txId, + offer: { role: 'initiator', giveChain: 'ml', giveAtoms: toAtoms(amount), wantAtoms: wantAtomsOf(amount), secretHash, timelockSeconds: mlSeconds }, + secretHashHex: bytesToHex(secretHash), + spendAddress: COUNTERPARTY_ADDRESS, + spendPubkeyHex: '02'.repeat(33), + refundAddress: COUNTERPARTY_ADDRESS, + state: 'locked', + txIds: [txId], + updatedAt: Date.now(), + }); + void loadSessions(); + } catch (e) { + setError(swapErrorCopy(e)); + } finally { + setBusy(false); + } }; - const pick = (sym: string) => { - const asset = assets?.find((a) => a.sym === sym); - if (!asset) return; - const next = sideDefaults(asset.sym); - if (picking === 'from') setFrom(next); - else setTo(next); + const refund = async (session: SwapSessionRow) => { + setError(null); + setBusy(true); + try { + const { txId } = await htlc.refund(session.txIds[0] ?? session.id); + await swapSessions.save({ ...session, state: 'refunded', txIds: [...session.txIds, txId].slice(0, 16), updatedAt: Date.now() }); + void loadSessions(); + } catch (e) { + setError(swapErrorCopy(e)); + } finally { + setBusy(false); + } }; - if (!assets || !assetBalances || !assetSymbols || !htlcSteps || !swapStats) return ; - - if (submitted) { - return ( - setSubmitted(false)} - /> - ); - } + const active = sessions?.find((s) => s.state === 'offered' || s.state === 'locked' || s.state === 'claiming') ?? null; + const mlPrice = 'ML' in assets.priceMap ? assets.priceMap.ML : 0; + const rate = rateOf(amount, assets.priceMap); return ( - setPicking(null)} - symbols={assetSymbols} - value={picking === 'from' ? fromPanel.sym : toPanel.sym} - balances={assetBalances} - onSelect={pick} - /> + {mode === 'mock' && ( + + {t('swap.demo.note')} + + )} + {active && ( + + {t('swap.warn.keepOpen')} + + )} + {error && ( + + {error} + + )} + {/* Lock leg entry */} - setFrom({ ...fromPanel, amt })} onPickToken={() => setPicking('from')} /> - - setPicking('to')} /> - - - - - - - - - - (i === 1 ? C.green : i === 3 ? C.amber : C.text0)} /> + + + + + {`${t('swap.offer.rate')} ${rate}`} + + + + + + + + {t('common.approxUsd', { usd: `$${(Number(amount) * mlPrice).toFixed(2)}` })} + + setAmount(String(Math.round((assets.mlBalance ?? 0) * f * 1e4) / 1e4))} /> + + + + + + {t('swap.step.matchDetail')} + + - {/* HTLC protocol */} + {/* Sessions: the live protocol steps and the refund path. */} - - - - - + + {sessions !== null && sessions.length === 0 && ( + + {t('swap.session.empty')} + + )} + {sessions?.map((session) => ( + + + + {session.id.slice(0, 18)}… + + + {t(stateCopyKey(session.state))} + + + + + {session.state === 'locked' && ( + void refund(session)}> + {t('swap.refund.cta')} + + )} + + ))} - - setSubmitted(true)}> - {t('swap.cta')} + + void initiate()}> + {busy ? t('swap.state.pending') : t('swap.initiate')} ); } -function SwapPanel({ - label, - data, - price = 0, - onChange, - onPickToken, - amountLabel, -}: { - label: string; - data: SwapPanelData; - price?: number; - onChange?: (v: string) => void; - onPickToken?: () => void; - /** Readable name for the panel's amount input. */ - amountLabel?: string; -}) { - const usdValue = usd(data.amt, price); - return ( - - - - - {t('common.bal', { bal: data.bal.toLocaleString(), sym: data.sym })} - - - - {/* The receive side has no quote until M2 wires rates: show a dash - instead of mirroring the sent amount. */} - - - {/* The receive side has no quote until M2 wires rates: show a dash - instead of mirroring the sent amount, and no approx row under it. */} - {onChange && ( - - - {t('common.approxUsd', { usd: `$${usdValue}` })} - - onChange(quantizeAmount(data.bal * f))} /> - - )} - - ); +/** Provider assets without the useData fixture bundle: balances ride the + * provider asset rows (the same source the picker panels used). */ +function useDataCompat(): { mlBalance: number | null; priceMap: Record } { + const { data } = useProviders(); + const [state, setState] = useState<{ mlBalance: number | null; priceMap: Record }>({ mlBalance: null, priceMap: {} }); + useEffect(() => { + let live = true; + void (async () => { + try { + const rows = await data.getAssets(); + if (!live) return; + setState({ + mlBalance: rows.find((row) => row.sym === 'ML')?.amt ?? 0, + priceMap: Object.fromEntries(rows.map((row) => [row.sym, row.price] as const)), + }); + } catch { + if (live) setState({ mlBalance: null, priceMap: {} }); + } + })(); + return () => { + live = false; + }; + }, [data]); + return state; } -/** BTC ⇄ ML rail with a lock badge and packets travelling across it. */ +function toAtoms(decimal: string): string { + const cleaned = decimal.trim(); + if (!/^\d*(?:\.\d*)?$/.test(cleaned) || cleaned.length === 0) return '0'; + const [int, frac = ''] = cleaned.split('.'); + const padded = frac.slice(0, ML_DECIMALS).padEnd(ML_DECIMALS, '0'); + return `${int || '0'}${padded}`.replace(/^0+(?=\d)/, '') || '0'; +} +/** Indicative want leg (mock price source, R1): 1 ML at the fixture USDT + * price; the swap is the ML-side HTLC demo, so the want leg is disclosure + * only, never a money figure the flow depends on. */ +function wantAtomsOf(amountDecimal: string): string { + return toAtoms(String(Number(amountDecimal) * 0.343)); +} + +function rateOf(amountDecimal: string, priceMap: Record): string { + const price = priceMap.ML ?? 0; + const usdValue = Number(amountDecimal) * price; + return usdValue > 0 ? `$${usdValue.toFixed(2)}` : '-'; +} + +/** Swap preimage source per mode: the native secure random in real mode + * (device-pending honest state until the bindings verify), the mock hash + * helper in demo mode. The bytes live only in the screen closure. */ +async function swapSecret(mode: 'mock' | 'real'): Promise { + if (mode === 'real') return MojitoCore.secureRandom(32); + const bytes = new Uint8Array(32); + let seed = fnv1a(`swap-demo:${Date.now()}`); + for (let i = 0; i < 32; i++) { + seed = fnv1a(String(seed), 0x9e3779b9); + bytes[i] = seed & 0xff; + } + return bytes; +} + +function swapErrorCopy(e: unknown): string { + if (isBindingsUnavailable(e)) return t('swap.error.devicePending'); + const record = e as { reason?: string } | null; + if (record && typeof record.reason === 'string') { + if (record.reason === 'broadcast-disabled') return t('swap.broadcastOff'); + if (record.reason === 'not-expired') return t('errors.htlc.expired'); + if (record.reason === 'no-htlc-output') return t('errors.htlc.expired'); + } + return t('swap.error.timelockRule'); +} + +function stateCopyKey(state: SwapState): I18nKey { + switch (state) { + case 'offered': return 'swap.state.offered'; + case 'locked': return 'swap.state.locked'; + case 'claiming': return 'swap.state.claiming'; + case 'settled': return 'swap.state.settled'; + case 'refunded': return 'swap.state.refunded'; + case 'expired': return 'swap.state.expired'; + } +} + +function stateTone(state: SwapState): string { + switch (state) { + case 'settled': return C.green; + case 'refunded': return C.teal; + case 'expired': return C.text3; + default: return C.amber; + } +} + +/** The four protocol steps (spec: HTLC_STEPS becomes a live StepState). */ +function stepsFor(session: SwapSessionRow): { label: string; detail: string; state: StepState; note?: string }[] { + const done = session.state === 'settled' || session.state === 'refunded'; + const lockState: StepState = session.state === 'offered' ? 'active' : 'done'; + const matchState: StepState = session.state === 'locked' ? 'active' : lockState === 'done' ? (done ? 'done' : session.state === 'claiming' ? 'done' : 'pending') : 'pending'; + const claimState: StepState = session.state === 'claiming' ? 'active' : session.state === 'settled' ? 'done' : 'pending'; + const settleState: StepState = session.state === 'settled' ? 'done' : 'pending'; + const hours = Math.round(session.offer.timelockSeconds / 3600); + return [ + { label: t('swap.step.lock'), detail: t('swap.step.lockDetail', { hours: String(hours) }), state: session.state === 'refunded' || session.state === 'expired' ? 'done' : lockState }, + { label: t('swap.step.match'), detail: t('swap.step.matchDetail'), state: matchState }, + { label: t('swap.step.claim'), detail: t('swap.step.claimDetail'), state: claimState }, + { label: t('swap.step.settle'), detail: t('swap.step.settleDetail'), state: settleState, note: session.state === 'refunded' ? t('swap.state.refunded') : undefined }, + ]; +} + +/** BTC ⇄ ML rail with a lock badge and packets travelling across it. */ function HtlcRail() { return ( @@ -193,12 +341,3 @@ function HtlcRail() { ); } - -/* ══ Bridge ═════════════════════════════════════════════════ */ - -/** - * Mojito bridges Mintlayer <-> everything else, so one endpoint is always - * Mintlayer. Only the counterparty is selectable and the arrow decides which - * direction Mintlayer sits on, so an unroutable pair like Ethereum -> Arbitrum - * is therefore unrepresentable rather than merely rejected. - */ From 434ad98449b18b71cb666f897474825ad8226e5f Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 06:43:36 +0100 Subject: [PATCH 09/20] docs(m4): swap demo script notes, readme trade status, manual tests --- README.md | 17 +++++++++++++---- scripts/e2e-testnet.mjs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e54d857..162530e 100644 --- a/README.md +++ b/README.md @@ -11,9 +11,18 @@ mobile app, rebuilt in React Native. --- -## ⚠️ Project status · M3 (send and receive) +## ⚠️ Project status · M4 (trade) -**This repository is the send milestone: everything M2 shipped (keys, vault, live chain data) plus the three-step send flow on real builders, BTC signing and broadcast end-to-end on pure-TypeScript scure, the tracked pending to confirmed lifecycle and fresh-address rotation. ML broadcasting still waits on infrastructure, so a mainnet ML send prepares and signs but honestly refuses to broadcast.** +**This repository is the trade milestone: everything M3 shipped (keys, vault, live chain data, the send pipeline) plus the three trade surfaces wired to real infrastructure where it exists - the DEX runs the live on-chain order book with order create/fill/conclude flows, the swap screen drives the ML-side HTLC session machine with persisted sessions, and the bridge reads the bridge_v2 api-server (M2E quotes, fees, status; the treasury deposit address). Signing still rides the device-pending bindings seam and ML broadcasting waits on infrastructure, so every trade action lands in an honest state instead of a fabricated success.** + +Real in M4: + +- **Order book**: Dex depth rows come from GET /order/pair/{base}_{quote}/book with keyset cursor pagination and an invalid-cursor page-1 restart; stale and error states are explicit, never fixture rows in real mode. +- **Orders**: place (confirm sheet with the exact amounts and a slippage guard against the book mid), fill and conclude run the bindings order encoders with the F11 witness mix (no-signature on the order input, signed payer inputs); ids extract through the bindings on the create tx output. +- **Atomic swap**: the ML-side HTLC flow (lock, claim, refund, secret extraction) per the docs guide; sessions persist across restarts with the secret hash only (the preimage never persists and never logs; the keep-open warning explains what is at stake). The BTC counterparty leg is the scripted demo (see scripts/e2e-testnet.mjs) with the shorter-timelock rule enforced by UI guards. +- **Bridge**: quotes and status ride the bridge_v2 api-server per R5 (per-token fees per direction, the Mintlayer treasury deposit address, m2e deposit confirmations); E2M stays disabled with explanatory copy (no EVM signer, scoped decision open). M2E initiation is honestly gated until the deposit intent encoder and the ML submission route exist. The EVM demo fixtures (Arbitrum, Polygon, BNB) are removed from the bridge chains and pickers in this milestone. + +M3 (still accurate): BTC sends are end-to-end real on scure against the configured btc-api base; ML sends prepare and sign over the bindings interface but honestly refuse to broadcast (R3, action item A1); the send lifecycle tracks pending to confirmed with fresh-address rotation. Real since M1, with vector-backed tests: @@ -56,7 +65,7 @@ Do not point this at real funds you cannot afford to lose, and do not treat any |---|---| | **Onboarding** | Welcome · Secure (biometric) · PIN set/confirm · Seed reveal · Verify backup · Import phrase · Account discovery · Draw-your-own-entropy | | **Wallet** | Home (portfolio, balance chart, activity) · DEX (order book + ticket) | -| **Trade** | Atomic Swap (HTLC) · Bridge (Mintlayer ⇄ EVM) · Mojito Card waitlist | +| **Trade** | Atomic Swap (HTLC sessions) · Bridge (Mintlayer ⇄ Ethereum) · Mojito Card waitlist | | **Flows** | Send (3-step) · Receive (QR) · Settings | | **App** | Splash · Unlock (biometric + PIN with lockout) | @@ -232,7 +241,7 @@ npm run lint # eslint only npx tsx src/theme.test.ts ``` -`npm run check` runs thirty things: +`npm run check` runs thirty-six things: 1. **`src/theme.test.ts`**: asserts the oklch→sRGB conversion against the known sRGB primaries. Every colour in the app flows through it, so it's the one piece of non-trivial logic with a diff --git a/scripts/e2e-testnet.mjs b/scripts/e2e-testnet.mjs index 1a9a8fe..6e5f6c6 100644 --- a/scripts/e2e-testnet.mjs +++ b/scripts/e2e-testnet.mjs @@ -19,6 +19,36 @@ // MOJITO_AMOUNT_BTC amount in BTC (default 0.00005) // // Exit codes: 0 success, 2 config pending (btc base), 3 unfunded, 1 failure. +// +// ── M4 scripted atomic swap counterparty (spec M4 acceptance) ──────────── +// The BTC side of the ML<->BTC HTLC swap demo runs OUTSIDE the wallet in v1 +// (custom BTC HTLC script construction is unproven in-repo; see +// missing-architecture gap 2). The scripted counterparty flow, with the +// shorter-timelock rule enforced by the app's UI guards +// (src/trade/priceGuards.checkTimelockRule, TIMELOCK_RULE in +// src/trade/htlc.ts), is: +// 1. INITIATOR (app, real mode): generate the 32-byte preimage with the +// native secure random, share ONLY SHA-256(preimage) off-band, lock ML +// via src/trade/htlc.ts initiate() with refund_timelock = 48h +// (172800s) and the counterparty's spend address/pubkey. +// 2. COUNTERPARTY (this script, external tooling): build and broadcast a +// BTC HTLC paying the same SHA-256 hash with a SHORTER timelock +// (24h = 86400s; the guard refuses any offer where +// btcSeconds * 2 > mlSeconds). The lock script is a prebuilt +// transaction generated with external Bitcoin tooling - the demo never +// fabricates one in-app. +// 3. INITIATOR: claim the BTC HTLC by revealing the preimage in the +// witness (the secret becomes public on Bitcoin). +// 4. COUNTERPARTY: read the preimage from the BTC claim (btc-api +// GET tx/:txid/hex plus witness script parse), then claim the +// Mintlayer HTLC via src/trade/htlc.ts claim() with the revealed +// secret; extractSecret() round-trips the raw claim bytes through the +// bindings extraction. +// 5. REFUND: if the counterparty never locks, the initiator reclaims via +// htlc.refund() after the ML timelock expiry (the flow refuses typed +// with not-expired before it). +// The sessions survive restarts via src/trade/swapSession.ts (secret hash +// only; the preimage stays in memory, hence the keep-open warning). const btcBase = process.env.MOJITO_BTC_BASE?.replace(/\/+$/, '') ?? null; const phrase = process.env.MOJITO_PHRASE ?? 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; From ec9650d02034558d80e81565cef3afc5bc8facdb Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 06:45:25 +0100 Subject: [PATCH 10/20] chore(m4): activity fixture rides the ethereum bridge scope --- src/data.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/data.ts b/src/data.ts index daf4a91..0ed4508 100644 --- a/src/data.ts +++ b/src/data.ts @@ -33,13 +33,13 @@ export const ASSET_BALANCES = Object.fromEntries(ASSETS.map((a) => [a.sym, `${a. export const ASSET_SYMBOLS = ASSETS.map((a) => a.sym); -// EVM demo chains (Ethereum, Arbitrum, Polygon, BNB) were removed in M2 per +// The EVM demo chains of the M0 design were removed in M2 per // the M2 spec: no wallet backend exists for them. The bridge fixtures keep // their R5 pair until M4 wires bridge_v2 wholesale. export const NETWORKS: readonly ChainName[] = ['Bitcoin', 'Mintlayer']; export const ACTIVITY: ActivityRow[] = [ - { icon: 'bridge', title: 'Bridge to Arbitrum', sub: '120 ML → 41.04 USDC', tone: 'violet', time: '2m', state: 'Confirming · 3/12', live: true }, + { icon: 'bridge', title: 'Bridge to Ethereum', sub: '120 ML → 41.04 USDC', tone: 'violet', time: '2m', state: 'Confirming · 3/12', live: true }, { icon: 'swap', title: 'Swap on Mintlayer DEX', sub: '0.012 BTC → 3,420 ML', tone: 'amber', time: '14m', state: 'Filled · +0.4%', live: false }, { icon: 'arrow_dn', title: 'Atomic swap received', sub: '+ 0.0184 BTC', tone: 'green', time: '1h', state: 'Settled', live: false }, ]; From 9671172074293ab17eacb1cd90f8542c0b91996a Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 07:36:23 +0100 Subject: [PATCH 11/20] fix(m4): reshape the bindings seam to the vendored signatures The TS mirror matched an imagined UniFFI API: getOrderId now derives from the create tx inputs, fill and conclude inputs carry the account nonce and the tip block height, the HTLC output encodes a hex secret hash with an encodeLockForSeconds timelock blob and no spend pubkey, and extractHtlcSecret consumes the encodeOutpointSourceId blob. A parity test pins both directions. Claim and refund feed the locally captured lock tx bytes to the decode (persisted in the swap session), and real-mode swap locking is gated with a typed unsupported until an offer entry supplies the counterparty spend path, with the refund address taken from the wallet's own allocation. --- README.md | 2 +- modules/mojito-core/index.ts | 19 ++- .../mintlayer/MintlayerBindings.ts | 37 +++-- package.json | 2 +- plans/mojito-neo/decisions.md | 29 ++++ src/data/mock/mockTrade.ts | 15 +- src/i18n/strings/en.ts | 4 +- src/screens/SwapScreen.tsx | 62 +++++--- src/trade/bindingsParity.test.ts | 149 ++++++++++++++++++ src/trade/htlc.test.ts | 65 +++++--- src/trade/htlc.ts | 117 +++++++------- src/trade/orders.test.ts | 62 ++++---- src/trade/orders.ts | 39 +++-- src/trade/swapSession.test.ts | 19 ++- src/trade/swapSession.ts | 6 + 15 files changed, 449 insertions(+), 178 deletions(-) create mode 100644 src/trade/bindingsParity.test.ts diff --git a/README.md b/README.md index 162530e..6f5343e 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ mobile app, rebuilt in React Native. Real in M4: - **Order book**: Dex depth rows come from GET /order/pair/{base}_{quote}/book with keyset cursor pagination and an invalid-cursor page-1 restart; stale and error states are explicit, never fixture rows in real mode. -- **Orders**: place (confirm sheet with the exact amounts and a slippage guard against the book mid), fill and conclude run the bindings order encoders with the F11 witness mix (no-signature on the order input, signed payer inputs); ids extract through the bindings on the create tx output. +- **Orders**: place (confirm sheet with the exact amounts and a slippage guard against the book mid), fill and conclude run the bindings order encoders with the F11 witness mix (no-signature on the order input, signed payer inputs); the order id derives through the bindings from the create tx inputs, and fill and conclude inputs carry the account nonce and block height per the vendored wallet-bindings v0.1.0 signatures (pinned by src/trade/bindingsParity.test.ts). - **Atomic swap**: the ML-side HTLC flow (lock, claim, refund, secret extraction) per the docs guide; sessions persist across restarts with the secret hash only (the preimage never persists and never logs; the keep-open warning explains what is at stake). The BTC counterparty leg is the scripted demo (see scripts/e2e-testnet.mjs) with the shorter-timelock rule enforced by UI guards. - **Bridge**: quotes and status ride the bridge_v2 api-server per R5 (per-token fees per direction, the Mintlayer treasury deposit address, m2e deposit confirmations); E2M stays disabled with explanatory copy (no EVM signer, scoped decision open). M2E initiation is honestly gated until the deposit intent encoder and the ML submission route exist. The EVM demo fixtures (Arbitrum, Polygon, BNB) are removed from the bridge chains and pickers in this milestone. diff --git a/modules/mojito-core/index.ts b/modules/mojito-core/index.ts index f99f7e3..7e5636d 100644 --- a/modules/mojito-core/index.ts +++ b/modules/mojito-core/index.ts @@ -241,6 +241,9 @@ export const MojitoCore: MojitoCore = { encodeOutpointSourceId(id32: Uint8Array, source: 'transaction' | 'block-reward') { return stub('encodeOutpointSourceId', [id32, source]); }, + encodeLockForSeconds(totalSeconds: number) { + return stub('encodeLockForSeconds', [totalSeconds]); + }, encodeInputForUtxo(outpointSource: Uint8Array, index: number) { return stub('encodeInputForUtxo', [outpointSource, index]); }, @@ -290,17 +293,17 @@ export const MojitoCore: MojitoCore = { encodeCreateOrderOutput(params: OrderParams) { return stub('encodeCreateOrderOutput', [params]); }, - encodeInputForFillOrder(orderId: Uint8Array, destination: Uint8Array, amount: string) { - return stub('encodeInputForFillOrder', [orderId, destination, amount]); + encodeInputForFillOrder(orderId: string, fillAmount: string, destination: string, nonce: number, currentBlockHeight: number, network: MlNetwork) { + return stub('encodeInputForFillOrder', [orderId, fillAmount, destination, nonce, currentBlockHeight, network]); }, - encodeInputForConcludeOrder(orderId: Uint8Array, destination: Uint8Array) { - return stub('encodeInputForConcludeOrder', [orderId, destination]); + encodeInputForConcludeOrder(orderId: string, nonce: number, currentBlockHeight: number, network: MlNetwork) { + return stub('encodeInputForConcludeOrder', [orderId, nonce, currentBlockHeight, network]); }, - getOrderId(transaction: Uint8Array, outputIndex: number) { - return stub('getOrderId', [transaction, outputIndex]); + getOrderId(inputs: Uint8Array[], network: MlNetwork) { + return stub('getOrderId', [inputs, network]); }, - getTokenId(transaction: Uint8Array, outputIndex: number) { - return stub('getTokenId', [transaction, outputIndex]); + getTokenId(inputs: Uint8Array[], currentBlockHeight: number, network: MlNetwork) { + return stub('getTokenId', [inputs, currentBlockHeight, network]); }, // static fee schedule diff --git a/modules/mojito-core/mintlayer/MintlayerBindings.ts b/modules/mojito-core/mintlayer/MintlayerBindings.ts index e30e439..ecf922e 100644 --- a/modules/mojito-core/mintlayer/MintlayerBindings.ts +++ b/modules/mojito-core/mintlayer/MintlayerBindings.ts @@ -1,6 +1,11 @@ -// TS mirror of the UniFFI surface we consume. Names follow the Kotlin/Swift -// spellings from docs/build/sdks/mobile-bindings.md. Amounts are decimal atom -// strings. All fallible calls reject with BindingsError. +// TS mirror of the vendored UniFFI surface (vendor/mintlayer, release +// wallet-bindings-v0.1.0). The signatures below are pinned byte-for-byte +// against the vendored Swift/Kotlin facade by src/trade/bindingsParity.test.ts: +// reshaping this file without the vendored source (or vice versa) fails the +// gate. Swift UInt64/UInt32 arguments ride JS numbers (block heights, nonces +// and indexes fit safely); amounts stay decimal atom strings and ids stay +// bech32 strings, exactly the vendored String forms. All fallible calls +// reject with BindingsError. export type MlNetwork = 'mainnet' | 'testnet' | 'regtest' | 'signet'; export type BindingsError = { @@ -31,6 +36,10 @@ export interface MintlayerBindings { getTransactionId(transaction: Uint8Array, strictByteSize: boolean): Promise; decodeTransactionToJson(transaction: Uint8Array, network: MlNetwork): Promise; + // timelock encoders: the HTLC refundTimelock argument is the blob one of + // these produces (the vendored facade exposes no bare-number form) + encodeLockForSeconds(totalSeconds: number): Promise; + // signing and witnesses encodeWitness(params: WitnessParams): Promise; encodeWitnessNoSignature(): Promise; @@ -41,10 +50,13 @@ export interface MintlayerBindings { // orders encodeCreateOrderOutput(params: OrderParams): Promise; - encodeInputForFillOrder(orderId: Uint8Array, destination: Uint8Array, amount: string): Promise; - encodeInputForConcludeOrder(orderId: Uint8Array, destination: Uint8Array): Promise; - getOrderId(transaction: Uint8Array, outputIndex: number): Promise; - getTokenId(transaction: Uint8Array, outputIndex: number): Promise; + encodeInputForFillOrder(orderId: string, fillAmount: string, destination: string, nonce: number, currentBlockHeight: number, network: MlNetwork): Promise; + encodeInputForConcludeOrder(orderId: string, nonce: number, currentBlockHeight: number, network: MlNetwork): Promise; + /** The bech32 order id derived from the create transaction inputs. */ + getOrderId(inputs: Uint8Array[], network: MlNetwork): Promise; + /** The bech32 token id derived from the issuing transaction inputs; the + * id scheme depends on the upgrade active at currentBlockHeight. */ + getTokenId(inputs: Uint8Array[], currentBlockHeight: number, network: MlNetwork): Promise; // static fee schedule fungibleTokenIssuanceFee(): Promise; @@ -52,8 +64,15 @@ export interface MintlayerBindings { } export type HtlcParams = { - atoms: string; tokenId?: string; secretHash: Uint8Array; - spendAddress: string; spendPubkey: Uint8Array; refundAddress: string; refundTimelock: number; + /** Decimal atom amount (the vendored amount string). */ + amount: string; + tokenId?: string; + /** Hex-encoded SHA-256 secret hash (the vendored hex string form). */ + secretHash: string; + spendAddress: string; + refundAddress: string; + /** Blob from encodeLockForSeconds (the vendored Data form). */ + refundTimelock: Uint8Array; }; export type WitnessParams = { diff --git a/package.json b/package.json index e03560d..95f2802 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "ios:dev": "expo run:ios", "android:dev": "expo run:android", "prebuild": "expo prebuild", - "check": "tsx src/theme.test.ts && tsx src/i18n/strings.test.ts && tsx src/money.test.ts && tsx src/data/polling.test.ts && tsx src/data/ml/indexerClient.test.ts && tsx src/data/btc/btcChainService.test.ts && tsx src/data/addresses/addressManager.test.ts && tsx src/storage/addressStore.test.ts && tsx src/data/activity/activityService.test.ts && tsx src/storage/secureStore.test.ts && tsx src/storage/walletVault.test.ts && tsx src/storage/pinStore.test.ts && tsx src/storage/appSettings.test.ts && tsx src/data/real/realWalletData.test.ts && tsx src/data/providers/providers.test.ts && tsx src/data/providers/broadcast.test.ts && tsx src/data/providers/bridge.test.ts && tsx src/trade/orderBookService.test.ts && tsx src/trade/orders.test.ts && tsx src/trade/htlc.test.ts && tsx src/trade/swapSession.test.ts && tsx src/trade/priceGuards.test.ts && tsx src/keys/bip39.test.ts && tsx src/keys/mlAccounts.test.ts && tsx src/keys/BtcKeyring.test.ts && tsx src/send/validation.test.ts && tsx src/send/mlTxBuilder.test.ts && tsx src/send/btcTxBuilder.test.ts && tsx src/send/TxTracker.test.ts && tsx src/data/real/realSend.test.ts && tsx src/data/mock/mockSend.test.ts && tsx src/keys/session.test.ts && tsx scripts/no-console.ts && tsx scripts/no-em-dash.ts && tsc --noEmit && eslint .", + "check": "tsx src/theme.test.ts && tsx src/i18n/strings.test.ts && tsx src/money.test.ts && tsx src/data/polling.test.ts && tsx src/data/ml/indexerClient.test.ts && tsx src/data/btc/btcChainService.test.ts && tsx src/data/addresses/addressManager.test.ts && tsx src/storage/addressStore.test.ts && tsx src/data/activity/activityService.test.ts && tsx src/storage/secureStore.test.ts && tsx src/storage/walletVault.test.ts && tsx src/storage/pinStore.test.ts && tsx src/storage/appSettings.test.ts && tsx src/data/real/realWalletData.test.ts && tsx src/data/providers/providers.test.ts && tsx src/data/providers/broadcast.test.ts && tsx src/data/providers/bridge.test.ts && tsx src/trade/orderBookService.test.ts && tsx src/trade/orders.test.ts && tsx src/trade/htlc.test.ts && tsx src/trade/swapSession.test.ts && tsx src/trade/priceGuards.test.ts && tsx src/trade/bindingsParity.test.ts && tsx src/keys/bip39.test.ts && tsx src/keys/mlAccounts.test.ts && tsx src/keys/BtcKeyring.test.ts && tsx src/send/validation.test.ts && tsx src/send/mlTxBuilder.test.ts && tsx src/send/btcTxBuilder.test.ts && tsx src/send/TxTracker.test.ts && tsx src/data/real/realSend.test.ts && tsx src/data/mock/mockSend.test.ts && tsx src/keys/session.test.ts && tsx scripts/no-console.ts && tsx scripts/no-em-dash.ts && tsc --noEmit && eslint .", "lint": "eslint ." }, "dependencies": { diff --git a/plans/mojito-neo/decisions.md b/plans/mojito-neo/decisions.md index 9453548..b155526 100644 --- a/plans/mojito-neo/decisions.md +++ b/plans/mojito-neo/decisions.md @@ -84,3 +84,32 @@ cost that a paste-first send flow does not need yet, and shipping it half wired would be worse than an honest alert. The `scan.*` i18n keys land with the sheet, not before. Revisit when the milestone that owns scanning picks the camera library. + +## M4 change log + +### Bindings seam corrected to the vendored signatures (M4 review, critical) + +The first M4 implementation mirrored an imagined UniFFI API. The TS mirror +in `modules/mojito-core/mintlayer/MintlayerBindings.ts` is reshaped to the +pinned vendored surface (`vendor/mintlayer`, wallet-bindings v0.1.0): +`getOrderId(inputs, network)` derives the order id from the create tx +inputs (no output index exists); `encodeInputForFillOrder` and +`encodeInputForConcludeOrder` take the bech32 id strings plus the account +nonce and the current block height (they select the orders V0/V1 input +form; conclude carries no destination argument); `encodeOutputHtlc` takes +a hex secret hash, no spend pubkey, and a `refundTimelock` blob produced +by the `encodeLock*` encoders (`encodeLockForSeconds` is added to the +mirror for the seconds-denominated offers); `extractHtlcSecret` consumes +the `encodeOutpointSourceId` blob, not the bare 32-byte id; +`decodeTransactionToJson` is only ever fed serialized transaction bytes. +The seam is pinned by `src/trade/bindingsParity.test.ts` (per-line literal +asserts plus a checksum over the vendored signature lines), so either side +drifts only through a failing gate. + +Account-nonce policy: the bindings docs require the fill and conclude +nonces to sequence with the filler's other account spendings. The flows +use an in-session counter (`createOrderFlows`); the wallet must persist +the account nonce with its state before the native call-through goes live +on real funds, otherwise the first order transaction after a restart can +sit at the wrong nonce. Recorded here as a gate condition for the +call-through landing. diff --git a/src/data/mock/mockTrade.ts b/src/data/mock/mockTrade.ts index 468ed29..9cdc842 100644 --- a/src/data/mock/mockTrade.ts +++ b/src/data/mock/mockTrade.ts @@ -4,6 +4,7 @@ // no chain state is touched and nothing reads as a real settlement (the // demo-data chip stays visible in mock mode, spec M4 honesty rules). import { ASKS, BIDS } from '../../data'; +import { bytesToHex } from '@noble/hashes/utils.js'; import type { NetworkFlag } from '../../config/endpoints'; import type { BroadcastProvider } from '../providers/types'; import { DEFAULT_BOOK_DEPTH, type BookRow, type OrderBookService } from '../../trade/OrderBookService'; @@ -117,15 +118,19 @@ export function createMockHtlcFlows(cfg: { broadcast: BroadcastProvider }): Htlc requireAtomAmount(offer.giveAtoms, 'give'); if (offer.secretHash.length !== 32) throw new Error('the secret hash must be 32 bytes'); const { txId } = await cfg.broadcast.broadcastMl(fakeId(`htlc-lock:${offer.giveAtoms}`)); - return { txId, htlcOutpoint: { id: new Uint8Array(32).fill(0x0a), index: 0 } }; + // Demo lock bytes: the session persists them so the claim/refund + // signatures match the real seam (the demo decode is a no-op). + const lockTx = new Uint8Array(64).fill(0x1c); + return { txId, lockTx, htlcOutpoint: { id: new Uint8Array(32).fill(0x0a), index: 0 } }; }, - async claim(htlcTxId: string, secret: Uint8Array) { + async claim(lockTx: Uint8Array, secret: Uint8Array) { + void lockTx; if (secret.length !== 32) throw new Error('the preimage must be 32 bytes'); - const { txId } = await cfg.broadcast.broadcastMl(fakeId(`htlc-claim:${htlcTxId}`)); + const { txId } = await cfg.broadcast.broadcastMl(fakeId(`htlc-claim:${bytesToHex(lockTx.subarray(0, 8))}`)); return { txId }; }, - async refund(htlcTxId: string) { - const { txId } = await cfg.broadcast.broadcastMl(fakeId(`htlc-refund:${htlcTxId}`)); + async refund(lockTx: Uint8Array) { + const { txId } = await cfg.broadcast.broadcastMl(fakeId(`htlc-refund:${bytesToHex(lockTx.subarray(0, 8))}`)); return { txId }; }, async extractSecret(rawSignedTx: Uint8Array, htlcOutpoint: { id: Uint8Array; index: number }) { diff --git a/src/i18n/strings/en.ts b/src/i18n/strings/en.ts index 3f3d9ae..d258969 100644 --- a/src/i18n/strings/en.ts +++ b/src/i18n/strings/en.ts @@ -231,7 +231,8 @@ export const en = { 'swap.state.refunded': 'Refunded', 'swap.state.expired': 'Expired', 'swap.warn.keepOpen': 'Keep this screen open until settlement: the preimage lives only in memory. Losing it forfeits the swap (the refund path still works).', - 'swap.error.timelockRule': 'The Bitcoin timelock must stay well under the Mintlayer one. Pick a longer Mintlayer timelock.', + 'swap.error.generic': 'The swap action failed. Nothing was sent.', + 'swap.real.unavailable': 'Real swaps need a counterparty offer with its own spend path. Offer entry is not available in this build, so locking is disabled. Existing sessions can still refund.', 'swap.refund.cta': 'Refund after timelock', 'swap.session.empty': 'No swap sessions yet. Initiate one to see the live protocol steps.', 'swap.session.title': 'Swap sessions', @@ -356,6 +357,7 @@ export const en = { 'errors.orders.invalidCursor': 'The order book page went stale. Refreshing from the top.', 'errors.orders.notMine': 'Only the order creator can conclude an order.', 'errors.htlc.expired': 'The refund unlocks after the timelock expiry.', + 'errors.htlc.noOutput': 'That transaction carries no readable HTLC output, so the lock cannot be claimed or refunded.', 'errors.orders.book': 'The order book is unavailable right now.', // onboarding diff --git a/src/screens/SwapScreen.tsx b/src/screens/SwapScreen.tsx index 860cf7a..0c88e00 100644 --- a/src/screens/SwapScreen.tsx +++ b/src/screens/SwapScreen.tsx @@ -3,12 +3,12 @@ import { View } from 'react-native'; import Svg, { Circle, Defs, Line, LinearGradient as SvgGrad, Rect, Stop, Text as SvgText } from 'react-native-svg'; import { sha256 } from '@noble/hashes/sha2.js'; import { bytesToHex } from '@noble/hashes/utils.js'; +import { hex as hexOf } from '@scure/base'; import { t, type I18nKey } from '../i18n'; import { useProviders } from '../data/providers/context'; import { fnv1a } from '../data/mock/hash'; import { MojitoCore } from '../../modules/mojito-core'; import { isBindingsUnavailable } from '../send/errors'; -import { checkTimelockRule } from '../trade/priceGuards'; import type { SwapSessionRow, SwapState } from '../trade/swapSession'; import type { StepState } from '../ui/StepState'; import { C, G } from '../theme'; @@ -18,13 +18,24 @@ const ML_DECIMALS = 11; const TIMELOCK_CHOICES = ['12h', '24h', '48h'] as const; type TimelockChoice = (typeof TIMELOCK_CHOICES)[number]; const TIMELOCK_SECONDS: Record = { '12h': 43_200, '24h': 86_400, '48h': 172_800 }; -/** Demo counterparty spend key (the offer exchange is off-band and the BTC - * side is the scripted counterpart; see scripts/e2e-testnet.mjs). */ +/** Demo counterparty spend path (MOCK MODE ONLY): the offer exchange is + * off-band and the BTC side is the scripted counterpart. Real mode never + * reaches this constant: initiate is gated with a typed unsupported until + * a real offer entry supplies the counterparty spend address and key + * (see swapGateError and plans/mojito-neo/decisions.md). */ const COUNTERPARTY_ADDRESS = 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl'; +/** Real-mode initiate gate in the BridgeError shape (typed unsupported, + * mirrored from BridgeProvider.initiate): a real lock must name the + * counterparty spend path from an explicit offer, and no offer entry + * exists yet. Nothing may lock to the demo vector in real mode. */ +class SwapGateError extends Error { + readonly failure = 'unsupported' as const; +} + export function SwapScreen() { const assets = useDataCompat(); - const { htlc, swapSessions, mode } = useProviders(); + const { htlc, swapSessions, data, mode } = useProviders(); const [amount, setAmount] = useState('0.025'); const [timelock, setTimelock] = useState('48h'); const [sessions, setSessions] = useState(null); @@ -47,23 +58,27 @@ export function SwapScreen() { }, [loadSessions]); /** Lock Mintlayer: secret generated off-band, only the hash crosses the - * wire; the session persists with the hash and the tx ids alone. */ + * wire; the session persists with the hash, the lock tx bytes and the + * tx ids. The refund path is a wallet-owned address and the spend path + * is the demo vector in mock mode; real mode refuses typed. */ const initiate = async () => { setError(null); - const mlSeconds = TIMELOCK_SECONDS[timelock]; - // TIMELOCK_RULE: the scripted BTC leg locks at half the ML timelock, - // which the guard enforces before anything is built. - const guard = checkTimelockRule({ mlSeconds, btcSeconds: mlSeconds / 2 }); - if (!guard.ok) { - setError(t('swap.error.timelockRule')); + if (mode === 'real') { + setError(swapErrorCopy(new SwapGateError('real-mode locking needs a counterparty offer; offer entry is pending'))); return; } + const mlSeconds = TIMELOCK_SECONDS[timelock]; setBusy(true); try { + // Refund address: the wallet's own allocation, so the wallet can + // sign the refund after expiry (a foreign address would lock the + // refund to a key this wallet cannot spend). + const refundAddress = (await data.getAddresses()).Mintlayer; + if (!refundAddress) throw new SwapGateError('no wallet mintlayer address to refund to'); const secret = await swapSecret(mode); const secretHash = sha256(secret); preimageRef.current = secret; - const { txId } = await htlc.initiate( + const { txId, lockTx } = await htlc.initiate( { role: 'initiator', giveChain: 'ml', @@ -73,7 +88,7 @@ export function SwapScreen() { timelockSeconds: mlSeconds, }, { address: COUNTERPARTY_ADDRESS, pubkey: new Uint8Array(33).fill(0x02) }, - COUNTERPARTY_ADDRESS, + refundAddress, ); await swapSessions.save({ id: txId, @@ -81,7 +96,8 @@ export function SwapScreen() { secretHashHex: bytesToHex(secretHash), spendAddress: COUNTERPARTY_ADDRESS, spendPubkeyHex: '02'.repeat(33), - refundAddress: COUNTERPARTY_ADDRESS, + refundAddress, + lockTxHex: bytesToHex(lockTx), state: 'locked', txIds: [txId], updatedAt: Date.now(), @@ -98,7 +114,11 @@ export function SwapScreen() { setError(null); setBusy(true); try { - const { txId } = await htlc.refund(session.txIds[0] ?? session.id); + // The refund rebuilds the lock parameters from the locally captured + // unsigned lock transaction bytes (the decode seam consumes bytes, + // not the tx id); rows without them cannot refund honestly. + if (!session.lockTxHex) throw new SwapGateError('stored session predates the lock tx bytes record'); + const { txId } = await htlc.refund(hexOf.decode(session.lockTxHex)); await swapSessions.save({ ...session, state: 'refunded', txIds: [...session.txIds, txId].slice(0, 16), updatedAt: Date.now() }); void loadSessions(); } catch (e) { @@ -121,6 +141,11 @@ export function SwapScreen() { {t('swap.demo.note')} )} + {mode === 'real' && ( + + {t('swap.real.unavailable')} + + )} {active && ( {t('swap.warn.keepOpen')} @@ -261,13 +286,14 @@ async function swapSecret(mode: 'mock' | 'real'): Promise { function swapErrorCopy(e: unknown): string { if (isBindingsUnavailable(e)) return t('swap.error.devicePending'); - const record = e as { reason?: string } | null; + const record = e as { reason?: string; failure?: string } | null; + if (record && typeof record.failure === 'string' && record.failure === 'unsupported') return t('swap.real.unavailable'); if (record && typeof record.reason === 'string') { if (record.reason === 'broadcast-disabled') return t('swap.broadcastOff'); if (record.reason === 'not-expired') return t('errors.htlc.expired'); - if (record.reason === 'no-htlc-output') return t('errors.htlc.expired'); + if (record.reason === 'no-htlc-output') return t('errors.htlc.noOutput'); } - return t('swap.error.timelockRule'); + return t('swap.error.generic'); } function stateCopyKey(state: SwapState): I18nKey { diff --git a/src/trade/bindingsParity.test.ts b/src/trade/bindingsParity.test.ts new file mode 100644 index 0000000..55efc48 --- /dev/null +++ b/src/trade/bindingsParity.test.ts @@ -0,0 +1,149 @@ +// Bindings seam parity gate: the TS mirror (modules/mojito-core/mintlayer/ +// MintlayerBindings.ts) must match the pinned vendored UniFFI surface +// (vendor/mintlayer, release wallet-bindings-v0.1.0) exactly. The M4 review +// caught the mirror written against an imagined API (order ids without +// inputs, fill/conclude without nonce and block height, an HTLC params +// shape with a spendPubkey and a bare-number timelock the real facade +// never accepted), so this test pins both directions: the vendored +// signature lines carry a pinned checksum (vendored drift fails the gate) +// and the TS declarations are asserted line-for-line (mirror drift fails +// the gate). Reshaping either side requires re-reviewing the vendored +// source and re-pinning here in the same change. +// tsx src/trade/bindingsParity.test.ts +import { readFileSync } from 'node:fs'; +import { strict as assert } from 'node:assert/strict'; +import { sha256 } from '@noble/hashes/sha2.js'; +import { bytesToHex } from '@noble/hashes/utils.js'; + +const VENDOR_SWIFT = 'vendor/mintlayer/MintlayerWalletBindings.swift'; +const TS_MIRROR = 'modules/mojito-core/mintlayer/MintlayerBindings.ts'; + +/** One pinned seam function: the normalized vendored signature line and + * the TS declaration lines that mirror it. */ +const PINNED: { name: string; swift: string; ts: string[] }[] = [ + { + name: 'getOrderId', + swift: 'public func getOrderId(inputs: [Data], network: Network)throws -> String {', + ts: ['getOrderId(inputs: Uint8Array[], network: MlNetwork): Promise;'], + }, + { + name: 'getTokenId', + swift: 'public func getTokenId(inputs: [Data], currentBlockHeight: UInt64, network: Network)throws -> String {', + ts: ['getTokenId(inputs: Uint8Array[], currentBlockHeight: number, network: MlNetwork): Promise;'], + }, + { + name: 'encodeInputForFillOrder', + swift: 'public func encodeInputForFillOrder(orderId: String, fillAmount: String, destination: String, nonce: UInt64, currentBlockHeight: UInt64, network: Network)throws -> Data {', + ts: ['encodeInputForFillOrder(orderId: string, fillAmount: string, destination: string, nonce: number, currentBlockHeight: number, network: MlNetwork): Promise;'], + }, + { + name: 'encodeInputForConcludeOrder', + swift: 'public func encodeInputForConcludeOrder(orderId: String, nonce: UInt64, currentBlockHeight: UInt64, network: Network)throws -> Data {', + ts: ['encodeInputForConcludeOrder(orderId: string, nonce: number, currentBlockHeight: number, network: MlNetwork): Promise;'], + }, + { + name: 'encodeOutputHtlc', + swift: 'public func encodeOutputHtlc(amount: String, tokenId: String?, secretHash: String, spendAddress: String, refundAddress: String, refundTimelock: Data, network: Network)throws -> Data {', + ts: ['encodeOutputHtlc(params: HtlcParams): Promise;'], + }, + { + name: 'encodeLockForSeconds', + swift: 'public func encodeLockForSeconds(totalSeconds: UInt64) -> Data {', + ts: ['encodeLockForSeconds(totalSeconds: number): Promise;'], + }, + { + name: 'extractHtlcSecret', + swift: 'public func extractHtlcSecret(signedTx: Data, strictByteSize: Bool, htlcOutpointSourceId: Data, htlcOutputIndex: UInt32)throws -> Data {', + ts: ['extractHtlcSecret(signedTx: Uint8Array, strictByteSize: boolean, htlcOutpointSourceId: Uint8Array, htlcOutputIndex: number): Promise;'], + }, + { + name: 'decodeTransactionToJson', + swift: 'public func decodeTransactionToJson(transaction: Data, network: Network)throws -> String {', + ts: ['decodeTransactionToJson(transaction: Uint8Array, network: MlNetwork): Promise;'], + }, + { + name: 'getTransactionId', + swift: 'public func getTransactionId(transaction: Data, strictByteSize: Bool)throws -> String {', + ts: ['getTransactionId(transaction: Uint8Array, strictByteSize: boolean): Promise;'], + }, + { + name: 'encodeTransaction', + swift: 'public func encodeTransaction(inputs: [Data], outputs: [Data], flags: UInt64)throws -> Data {', + ts: ['encodeTransaction(inputs: Uint8Array[], outputs: Uint8Array[], flags: number): Promise;'], + }, + { + name: 'encodeOutpointSourceId', + swift: 'public func encodeOutpointSourceId(id: Data, source: SourceId)throws -> Data {', + ts: ["encodeOutpointSourceId(id32: Uint8Array, source: 'transaction' | 'block-reward'): Promise;"], + }, + { + name: 'encodeInputForUtxo', + swift: 'public func encodeInputForUtxo(outpointSourceId: Data, outputIndex: UInt32)throws -> Data {', + ts: ['encodeInputForUtxo(outpointSource: Uint8Array, index: number): Promise;'], + }, +]; + +/** The HTLC params record: the vendored facade takes a hex secret hash and + * an encodeLock* blob timelock and has no spendPubkey parameter. */ +const HTLC_PARAMS_TS_FIELDS = [ + 'amount: string;', + 'tokenId?: string;', + 'secretHash: string;', + 'spendAddress: string;', + 'refundAddress: string;', + 'refundTimelock: Uint8Array;', +]; + +/** Pinned sha256 over the joined normalized vendored signature lines, in + * the PINNED order. Recompute and update together with a vendored + * artifact upgrade only after re-reviewing every seam signature. */ +const PINNED_VENDOR_CHECKSUM = 'e0474caed1b25ae53f7f5e6c8bca888b07e400ebb4ccbbcb89ae95f1847d8e52'; + +function normalize(line: string): string { + return line.replace(/\s+/g, ' ').trim(); +} + +function main() { + const swiftText = readFileSync(VENDOR_SWIFT, 'utf8'); + const tsText = readFileSync(TS_MIRROR, 'utf8'); + const swiftLines = swiftText.split('\n').map(normalize); + + // Vendored side: every pinned signature must exist exactly as pinned, + // and the joined set must match the pinned checksum (any vendored + // upgrade that touches the seam fails here). + const checksumInput: string[] = []; + for (const pin of PINNED) { + const line = swiftLines.find((candidate) => candidate.startsWith(`public func ${pin.name}(`)); + assert.ok(line, `vendored signature for ${pin.name} not found in ${VENDOR_SWIFT}`); + assert.equal(line, pin.swift, `vendored signature drift for ${pin.name}`); + checksumInput.push(line); + } + const checksum = bytesToHex(sha256(new TextEncoder().encode(checksumInput.join('\n')))); + assert.equal( + checksum, + PINNED_VENDOR_CHECKSUM, + `vendored bindings checksum changed (got ${checksum}); re-review the seam against the new artifacts and re-pin`, + ); + + // Mirror side: the TS declarations must exist line-for-line, and the + // imagined-API forms must be gone for good. + const tsLines = tsText.split('\n').map((line) => line.trim()); + for (const pin of PINNED) { + for (const expected of pin.ts) { + assert.ok( + tsLines.includes(expected), + `TS mirror is missing the pinned declaration for ${pin.name}: ${expected}`, + ); + } + } + for (const field of HTLC_PARAMS_TS_FIELDS) { + assert.ok(tsLines.includes(field), `HtlcParams is missing the pinned field ${field}`); + } + assert.ok(!/spendPubkey/.test(tsText), 'HtlcParams must not carry a spendPubkey field (not in the vendored encodeOutputHtlc)'); + assert.ok(!/getOrderId\(transaction/.test(tsText), 'getOrderId must take the create tx inputs, not a transaction plus output index'); + assert.ok(!/refundTimelock: number/.test(tsText), 'refundTimelock must ride the encodeLockForSeconds blob, not a bare number'); + + console.log('bindingsParity: ok'); +} + +main(); diff --git a/src/trade/htlc.test.ts b/src/trade/htlc.test.ts index 356309a..5baf3ef 100644 --- a/src/trade/htlc.test.ts +++ b/src/trade/htlc.test.ts @@ -28,9 +28,13 @@ const SPEND_PUBKEY = new Uint8Array(33).fill(0x02); type HtlcJson = { atoms: string; secret_hash: string; spend_address: string; spend_pubkey: string; refund_address: string; refund_timelock: number }; +/** The unsigned lock transaction bytes as the flows return them from + * initiate; the claim and refund decodes consume bytes, never the tx id. */ +const LOCK_TX_BYTES = new TextEncoder().encode('lock-tx-fixture:claim-refund-decode-input'); + function fakeBindings(htlcJson: HtlcJson): MintlayerBindings & { witnesses: WitnessParams[]; - htlcOutputs: { atoms: string; spendAddress: string; refundAddress: string; timelock: number }[]; + htlcOutputs: { atoms: string; spendAddress: string; refundAddress: string; timelock: string }[]; spendWitnesses: WitnessParams[]; refundWitnesses: WitnessParams[]; extractCalls: { txId: string; outpoint: string; index: number }[]; @@ -38,7 +42,7 @@ function fakeBindings(htlcJson: HtlcJson): MintlayerBindings & { const witnesses: WitnessParams[] = []; const spendWitnesses: WitnessParams[] = []; const refundWitnesses: WitnessParams[] = []; - const htlcOutputs: { atoms: string; spendAddress: string; refundAddress: string; timelock: number }[] = []; + const htlcOutputs: { atoms: string; spendAddress: string; refundAddress: string; timelock: string }[] = []; const extractCalls: { txId: string; outpoint: string; index: number }[] = []; const u32 = (value: number): Uint8Array => { const out = new Uint8Array(4); @@ -66,6 +70,9 @@ function fakeBindings(htlcJson: HtlcJson): MintlayerBindings & { async encodeOutpointSourceId(id32: Uint8Array) { return cat(u8(0x01), id32); }, + async encodeLockForSeconds(totalSeconds: number) { + return utf8(`L:${totalSeconds}`); + }, async encodeInputForUtxo(outpointSource: Uint8Array, index: number) { return cat(u8(0x02), outpointSource, u32(index)); }, @@ -75,9 +82,14 @@ function fakeBindings(htlcJson: HtlcJson): MintlayerBindings & { async encodeOutputTokenTransfer(tokenId: string, atomsStr: string, address: string) { return utf8(`K:${tokenId}:${atomsStr}:${address}`); }, - async encodeOutputHtlc(params: { atoms: string; secretHash: Uint8Array; spendAddress: string; spendPubkey: Uint8Array; refundAddress: string; refundTimelock: number }) { - htlcOutputs.push({ atoms: params.atoms, spendAddress: params.spendAddress, refundAddress: params.refundAddress, timelock: params.refundTimelock }); - return utf8(`H:${params.atoms}:${params.spendAddress}:${params.refundTimelock}`); + async encodeOutputHtlc(params: { amount: string; secretHash: string; spendAddress: string; refundAddress: string; refundTimelock: Uint8Array }) { + htlcOutputs.push({ + atoms: params.amount, + spendAddress: params.spendAddress, + refundAddress: params.refundAddress, + timelock: new TextDecoder().decode(params.refundTimelock), + }); + return utf8(`H:${params.amount}:${params.spendAddress}:${new TextDecoder().decode(params.refundTimelock)}`); }, async encodeTransaction(inputs: Uint8Array[], outputs: Uint8Array[]) { return cat(u8(0xee), u8(inputs.length), ...inputs, u8(0xff), u8(outputs.length), ...outputs); @@ -85,10 +97,14 @@ function fakeBindings(htlcJson: HtlcJson): MintlayerBindings & { async estimateTransactionSize(inputs: Uint8Array[], destinations: string[], outputs: Uint8Array[]) { return 100 + 40 * inputs.length + 30 * outputs.length + destinations.length; }, - async getTransactionId(transaction: Uint8Array) { - return bytesToHex(new Uint8Array(32).fill(0x11)); + async getTransactionId(_transaction: Uint8Array) { + return LOCK_TX_ID; }, - async decodeTransactionToJson() { + async decodeTransactionToJson(transaction: Uint8Array) { + // Input shape gate: the vendored decode consumes serialized + // transaction bytes; a tx-id-sized payload is always a bug. + assert.notEqual(transaction.length, 32, 'decodeTransactionToJson takes transaction bytes, not a tx id'); + assert.ok(transaction.length > 32, 'decodeTransactionToJson takes transaction bytes, not a tx id'); return JSON.stringify({ outputs: [{ htlc: htlcJson }] }); }, async encodeWitness(params: WitnessParams) { @@ -114,7 +130,7 @@ function fakeBindings(htlcJson: HtlcJson): MintlayerBindings & { witnesses: WitnessParams[]; spendWitnesses: WitnessParams[]; refundWitnesses: WitnessParams[]; - htlcOutputs: { atoms: string; spendAddress: string; refundAddress: string; timelock: number }[]; + htlcOutputs: { atoms: string; spendAddress: string; refundAddress: string; timelock: string }[]; extractCalls: { txId: string; outpoint: string; index: number }[]; }; } @@ -203,8 +219,9 @@ async function main() { // TIMELOCK_RULE is the recorded F10 string. assert.equal(TIMELOCK_RULE, 'btc timelock must be shorter than the mintlayer timelock (F10)'); - // 1. initiate: the lock output encodes the F10 parameters; the signed - // lock tx broadcasts and the outpoint rides the tx id. + // 1. initiate: the lock output encodes the F10 parameters through the + // vendored shape (hex hash, encodeLockForSeconds blob), the signed + // lock tx broadcasts and the flow returns the unsigned bytes. { const h = harness(); const result = await h.flows.initiate( @@ -213,14 +230,16 @@ async function main() { VECTOR_ADDRESS, ); assert.equal(result.txId, LOCK_TX_ID); + assert.ok(result.lockTx.length > 32, 'initiate returns the unsigned lock tx bytes for the session record'); assert.deepEqual(result.htlcOutpoint.id, hexOf.decode(LOCK_TX_ID)); assert.equal(result.htlcOutpoint.index, 0); - // The final (real-build) HTLC output encoding carries the lock params. + // The final (real-build) HTLC output encoding carries the lock params + // in the vendored shape: atoms, addresses and the seconds lock blob. const lock = h.bindings.htlcOutputs[h.bindings.htlcOutputs.length - 1]; assert.equal(lock.atoms, atoms(2n)); assert.equal(lock.spendAddress, VECTOR_ADDRESS); assert.equal(lock.refundAddress, VECTOR_ADDRESS); - assert.equal(lock.timelock, 172800); + assert.equal(lock.timelock, 'L:172800'); // Payer inputs sign normally (no secret on the lock leg). assert.equal(h.bindings.witnesses.length, 1); assert.equal(bytesToHex(h.bindings.witnesses[0].privateKey), expectedKey); @@ -248,19 +267,19 @@ async function main() { ), (e: unknown) => e instanceof HtlcError && e.reason === 'rejected', ); - const first = h.flows.claim(LOCK_TX_ID, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }); + const first = h.flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }); await assert.rejects( - () => h.flows.claim(LOCK_TX_ID, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }), + () => h.flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }), (e: unknown) => e instanceof HtlcError && e.reason === 'busy', ); await first; } // 3. claim: the spend witness carries the preimage and signs against the - // re-encoded HTLC output; the payout is the lock minus the fee. + // re-encoded HTLC output; the decode consumes the lock tx bytes. { const h = harness(); - const result = await h.flows.claim(LOCK_TX_ID, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }); + const result = await h.flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }); assert.equal(result.txId, LOCK_TX_ID); assert.equal(h.bindings.spendWitnesses.length, 1); const witness = h.bindings.spendWitnesses[0]; @@ -279,11 +298,11 @@ async function main() { { const h = harness({ lockTimestamp: Math.floor(Date.now() / 1000) - 10 }); await assert.rejects( - () => h.flows.refund(LOCK_TX_ID), + () => h.flows.refund(LOCK_TX_BYTES), (e: unknown) => e instanceof HtlcError && e.reason === 'not-expired', ); const expired = harness({ lockTimestamp: Math.floor(Date.now() / 1000) - 172_801 }); - const result = await expired.flows.refund(LOCK_TX_ID); + const result = await expired.flows.refund(LOCK_TX_BYTES); assert.equal(result.txId, LOCK_TX_ID); assert.equal(expired.bindings.refundWitnesses.length, 1); assert.equal(expired.bindings.refundWitnesses[0].inputIndex, 0); @@ -291,14 +310,14 @@ async function main() { } // 5. extractSecret: the bindings extraction consumes the raw signed tx - // and outpoint bytes and answers the preimage (roundtrip with the - // fixture claim). + // bytes and the encodeOutpointSourceId blob of the HTLC outpoint and + // answers the preimage (roundtrip with the fixture claim). { const h = harness(); const fixtureSignedTx = new Uint8Array([0xde, 0xad, 0xbe, 0xef, 0x00]); const secret = await h.flows.extractSecret(fixtureSignedTx, { id: hexOf.decode(LOCK_TX_ID), index: 0 }); assert.equal(bytesToHex(secret), bytesToHex(SECRET)); - assert.deepEqual(h.bindings.extractCalls[0], { txId: 'deadbeef00', outpoint: LOCK_TX_ID, index: 0 }); + assert.deepEqual(h.bindings.extractCalls[0], { txId: 'deadbeef00', outpoint: `01${LOCK_TX_ID}`, index: 0 }); assert.equal(bytesToHex(secretHashOf(secret)), bytesToHex(SECRET_HASH), 'the extracted preimage hashes to the offered secret hash'); } @@ -342,7 +361,7 @@ async function main() { withSession: async (fn) => fn({ withSeed: (run: (s: Uint8Array) => Promise) => run(seed) } as unknown as KeySession), }); await assert.rejects( - () => flows.claim(LOCK_TX_ID, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }), + () => flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }), (e: unknown) => e instanceof HtlcError && e.reason === 'no-htlc-output', ); } diff --git a/src/trade/htlc.ts b/src/trade/htlc.ts index fb7c49d..ac8fe1b 100644 --- a/src/trade/htlc.ts +++ b/src/trade/htlc.ts @@ -19,7 +19,7 @@ import { hex as hexOf } from '@scure/base'; import { bytesToHex } from '@noble/hashes/utils.js'; import { sha256 } from '@noble/hashes/sha2.js'; -import type { MintlayerBindings, MlNetwork } from '../../modules/mojito-core'; +import type { HtlcParams, MintlayerBindings, MlNetwork } from '../../modules/mojito-core'; import type { IndexerClient } from '../data/ml/IndexerClient'; import type { BroadcastProvider } from '../data/providers/types'; import type { MlTransaction } from '../data/ml/types'; @@ -45,12 +45,18 @@ export type HtlcSpend = { address: string; pubkey: Uint8Array }; export interface HtlcFlows { /** Lock the offer's giveAtoms on Mintlayer with the counterparty's spend - * key and our refund path (the initiator leg of the swap). */ - initiate(offer: HtlcOffer, spend: HtlcSpend, refundAddress: string): Promise<{ txId: string; htlcOutpoint: { id: Uint8Array; index: number } }>; - /** Spend an HTLC with the revealed secret (the counterparty claim leg). */ - claim(htlcTxId: string, secret: Uint8Array, spend: HtlcSpend): Promise<{ txId: string }>; - /** Reclaim after the timelock expiry (refund path, single sig). */ - refund(htlcTxId: string): Promise<{ txId: string }>; + * key and our refund path (the initiator leg of the swap). Returns the + * unsigned lock transaction bytes: the claim and refund decodes consume + * them, because the public Mintlayer indexer serves no raw transaction + * route, so the caller must persist them with the swap session. */ + initiate(offer: HtlcOffer, spend: HtlcSpend, refundAddress: string): Promise<{ txId: string; lockTx: Uint8Array; htlcOutpoint: { id: Uint8Array; index: number } }>; + /** Spend an HTLC with the revealed secret (the counterparty claim leg). + * lockTx carries the unsigned lock transaction bytes captured at + * initiate (not the tx id: the bindings decode consumes bytes). */ + claim(lockTx: Uint8Array, secret: Uint8Array, spend: HtlcSpend): Promise<{ txId: string }>; + /** Reclaim after the timelock expiry (refund path, single sig). lockTx + * carries the unsigned lock transaction bytes captured at initiate. */ + refund(lockTx: Uint8Array): Promise<{ txId: string }>; /** Extract a revealed preimage from a signed claim transaction. The raw * bytes come from the caller: the public Mintlayer indexer serves no raw * transaction route, so a txId-only signature cannot honestly fetch what @@ -188,9 +194,14 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { } /** Describe an on-chain HTLC output through the bindings decode seam: - * the indexer gives the output position, the bindings decode restores - * the lock parameters the claim and refund legs must rebuild. */ - async function describeHtlc(htlcTxId: string): Promise { + * lockTx is the unsigned lock transaction captured at initiate (the + * bindings decode consumes serialized transaction bytes, never a tx id, + * and the indexer exposes no raw-tx route to fetch them later). The + * decode restores the lock parameters the claim and refund legs must + * rebuild; bindings stub rejections surface as the honest + * device-pending state, never a guessed descriptor. */ + async function describeHtlc(lockTx: Uint8Array): Promise { + const htlcTxId = await b().getTransactionId(lockTx, false); let tx: MlTransaction; try { tx = await cfg.indexer.transaction(htlcTxId); @@ -199,10 +210,7 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { } const outputIndex = tx.outputs.findIndex((output: { type: string }) => output.type === 'Htlc'); if (outputIndex < 0) throw new HtlcError('no-htlc-output', `transaction ${htlcTxId} carries no HTLC output`); - // The decode seam restores the lock parameters from the raw - // transaction; bindings stub rejections surface as the honest - // device-pending state, never a guessed descriptor. - const json = await b().decodeTransactionToJson(hexOf.decode(htlcTxId), cfg.network); + const json = await b().decodeTransactionToJson(lockTx, cfg.network); const parsed = JSON.parse(json) as { outputs?: { htlc?: { atoms?: string; secret_hash?: string; spend_address?: string; spend_pubkey?: string; refund_address?: string; refund_timelock?: number } }[]; }; @@ -222,6 +230,19 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { }; } + /** HtlcParams for the vendored encodeOutputHtlc shape: the secret hash + * rides hex, the refund timelock rides the encodeLockForSeconds blob + * (offers are seconds-denominated, F10). */ + async function htlcOutputParams(amount: string, secretHashBytes: Uint8Array, spendAddress: string, refundAddress: string, timelockSeconds: number): Promise { + return { + amount, + secretHash: bytesToHex(secretHashBytes), + spendAddress, + refundAddress, + refundTimelock: await b().encodeLockForSeconds(timelockSeconds), + }; + } + return { async initiate({ giveAtoms, secretHash, timelockSeconds }, spend, refundAddress) { return serialize(async () => { @@ -232,6 +253,7 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { const changeAddress = await cfg.allocateChangeAddress(); try { const rate = await cfg.indexer.feerate(STANDARD_TIER_IN_TOP_MB); + const lockParams = async (atoms: string) => htlcOutputParams(atoms, secretHash, spend.address, refundAddress, timelockSeconds); const selection = await selectMlInputs({ utxos, sendAtoms: giveAtoms, @@ -246,14 +268,7 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { destinations.push(selected.address); } const outputBytes: Uint8Array[] = [ - await b().encodeOutputHtlc({ - atoms: '0', - secretHash, - spendAddress: spend.address, - spendPubkey: spend.pubkey, - refundAddress, - refundTimelock: timelockSeconds, - }), + await b().encodeOutputHtlc(await lockParams('0')), ...(await Promise.all( planned.slice(1).map((leg) => b().encodeOutputTransfer('0', leg.address, cfg.network)), )), @@ -272,16 +287,7 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { : await b().encodeOutputTokenTransfer(selected.tokenId, selected.atoms, selected.address, cfg.network), ); } - const outputs: Uint8Array[] = [ - await b().encodeOutputHtlc({ - atoms: giveAtoms, - secretHash, - spendAddress: spend.address, - spendPubkey: spend.pubkey, - refundAddress, - refundTimelock: timelockSeconds, - }), - ]; + const outputs: Uint8Array[] = [await b().encodeOutputHtlc(await lockParams(giveAtoms))]; if (selection.changeAtoms !== '0') { outputs.push(await b().encodeOutputTransfer(selection.changeAtoms, changeAddress, cfg.network)); } @@ -292,7 +298,7 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { const txId = await broadcast(signedHex); // The HTLC outpoint rides the lock tx id and its output index // (the HTLC output is assembled at index 0 of this flow). - return { txId, htlcOutpoint: { id: hexOf.decode(txId), index: 0 } }; + return { txId, lockTx: transaction, htlcOutpoint: { id: hexOf.decode(txId), index: 0 } }; } catch (e) { await cfg.releaseFailedChange(); throw e; @@ -300,22 +306,17 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { }); }, - async claim(htlcTxId, secret, spend) { + async claim(lockTx, secret, spend) { return serialize(async () => { if (secret.length !== 32) throw new HtlcError('rejected', 'the preimage must be 32 bytes'); - const descriptor = await describeHtlc(htlcTxId); - const fee = await claimFee(htlcTxId, spend.address); + const descriptor = await describeHtlc(lockTx); + const fee = await claimFee(descriptor.txId, spend.address); const payout = BigInt(descriptor.atoms) - fee; if (payout <= 0n) throw new HtlcError('rejected', 'the lock cannot cover the claim fee'); - const htlcInput = await utxoInput(htlcTxId, descriptor.outputIndex); - const htlcOutputBytes = await b().encodeOutputHtlc({ - atoms: descriptor.atoms, - secretHash: descriptor.secretHash, - spendAddress: descriptor.spendAddress, - spendPubkey: descriptor.spendPubkey, - refundAddress: descriptor.refundAddress, - refundTimelock: descriptor.refundTimelock, - }); + const htlcInput = await utxoInput(descriptor.txId, descriptor.outputIndex); + const htlcOutputBytes = await b().encodeOutputHtlc( + await htlcOutputParams(descriptor.atoms, descriptor.secretHash, descriptor.spendAddress, descriptor.refundAddress, descriptor.refundTimelock), + ); const inputs = [htlcInput]; const outputs = [await b().encodeOutputTransfer(payout.toString(), spend.address, cfg.network)]; const transaction = await b().encodeTransaction(inputs, outputs, 0); @@ -329,29 +330,24 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { }); }, - async refund(htlcTxId) { + async refund(lockTx) { return serialize(async () => { - const descriptor = await describeHtlc(htlcTxId); + const descriptor = await describeHtlc(lockTx); // Refunds unlock at the timelock expiry; the lock timestamp plus // the timelock must already be in the past, otherwise the refund // would be rejected by the chain: honest typed refusal first. - const tx = await cfg.indexer.transaction(htlcTxId); + const tx = await cfg.indexer.transaction(descriptor.txId); const lockedAt = tx.timestamp ?? 0; if (lockedAt + descriptor.refundTimelock > Math.floor(Date.now() / 1000)) { throw new HtlcError('not-expired', 'the refund unlocks after the timelock expiry'); } - const fee = await claimFee(htlcTxId, descriptor.refundAddress); + const fee = await claimFee(descriptor.txId, descriptor.refundAddress); const payout = BigInt(descriptor.atoms) - fee; if (payout <= 0n) throw new HtlcError('rejected', 'the lock cannot cover the refund fee'); - const htlcInput = await utxoInput(htlcTxId, descriptor.outputIndex); - const htlcOutputBytes = await b().encodeOutputHtlc({ - atoms: descriptor.atoms, - secretHash: descriptor.secretHash, - spendAddress: descriptor.spendAddress, - spendPubkey: descriptor.spendPubkey, - refundAddress: descriptor.refundAddress, - refundTimelock: descriptor.refundTimelock, - }); + const htlcInput = await utxoInput(descriptor.txId, descriptor.outputIndex); + const htlcOutputBytes = await b().encodeOutputHtlc( + await htlcOutputParams(descriptor.atoms, descriptor.secretHash, descriptor.spendAddress, descriptor.refundAddress, descriptor.refundTimelock), + ); const inputs = [htlcInput]; const outputs = [await b().encodeOutputTransfer(payout.toString(), descriptor.refundAddress, cfg.network)]; const transaction = await b().encodeTransaction(inputs, outputs, 0); @@ -364,7 +360,10 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { }, async extractSecret(rawSignedTx, htlcOutpoint) { - return b().extractHtlcSecret(rawSignedTx, false, htlcOutpoint.id, htlcOutpoint.index); + // The extraction consumes the encodeOutpointSourceId blob for the + // HTLC output (the vendored docs), not the bare 32-byte id. + const outpointSourceId = await b().encodeOutpointSourceId(htlcOutpoint.id, 'transaction'); + return b().extractHtlcSecret(rawSignedTx, false, outpointSourceId, htlcOutpoint.index); }, }; diff --git a/src/trade/orders.test.ts b/src/trade/orders.test.ts index b0187b6..553381f 100644 --- a/src/trade/orders.test.ts +++ b/src/trade/orders.test.ts @@ -36,16 +36,16 @@ const atoms = (ml: bigint): string => (ml * ML).toString(); function fakeBindings(): MintlayerBindings & { witnesses: WitnessParams[]; orderParams: OrderParams[]; - fillCalls: { orderId: string; destination: string; amount: string }[]; - concludeCalls: { orderId: string; destination: string }[]; - idCalls: { transaction: Uint8Array; outputIndex: number }[]; + fillCalls: { orderId: string; destination: string; amount: string; nonce: number; height: number }[]; + concludeCalls: { orderId: string; nonce: number; height: number }[]; + idCalls: { inputs: Uint8Array[] }[]; noSignatureCount: () => number; } { const witnesses: WitnessParams[] = []; const orderParams: OrderParams[] = []; - const fillCalls: { orderId: string; destination: string; amount: string }[] = []; - const concludeCalls: { orderId: string; destination: string }[] = []; - const idCalls: { transaction: Uint8Array; outputIndex: number }[] = []; + const fillCalls: { orderId: string; destination: string; amount: string; nonce: number; height: number }[] = []; + const concludeCalls: { orderId: string; nonce: number; height: number }[] = []; + const idCalls: { inputs: Uint8Array[] }[] = []; let noSignatureCalls = 0; const u32 = (value: number): Uint8Array => { const out = new Uint8Array(4); @@ -87,15 +87,16 @@ function fakeBindings(): MintlayerBindings & { orderParams.push(params); return utf8(`O:${params.give.tokenId}:${params.give.atoms}:${params.ask.tokenId}:${params.ask.atoms}:${params.concludeDestination}`); }, - // The bindings take bech32m data payloads; recorded as hex for the - // payload-equality assertions below. - async encodeInputForFillOrder(orderId: Uint8Array, destination: Uint8Array, amount: string) { - fillCalls.push({ orderId: bytesToHex(orderId), destination: bytesToHex(destination), amount }); - return cat(u8(0x03), orderId, destination, utf8(amount)); + // The vendored fill input takes the bech32 order id and destination + // strings plus the account nonce and block height; recorded for the + // assertions below. + async encodeInputForFillOrder(orderId: string, fillAmount: string, destination: string, nonce: number, currentBlockHeight: number) { + fillCalls.push({ orderId, destination, amount: fillAmount, nonce, height: currentBlockHeight }); + return utf8(`F:${orderId}:${destination}:${fillAmount}:${nonce}:${currentBlockHeight}`); }, - async encodeInputForConcludeOrder(orderId: Uint8Array, destination: Uint8Array) { - concludeCalls.push({ orderId: bytesToHex(orderId), destination: bytesToHex(destination) }); - return cat(u8(0x04), orderId, destination); + async encodeInputForConcludeOrder(orderId: string, nonce: number, currentBlockHeight: number) { + concludeCalls.push({ orderId, nonce, height: currentBlockHeight }); + return utf8(`C:${orderId}:${nonce}:${currentBlockHeight}`); }, async encodeTransaction(inputs: Uint8Array[], outputs: Uint8Array[]) { return cat(u8(0xee), u8(inputs.length), ...inputs, u8(0xff), u8(outputs.length), ...outputs); @@ -117,16 +118,16 @@ function fakeBindings(): MintlayerBindings & { async encodeSignedTransaction(transaction: Uint8Array, txWitnesses: Uint8Array[]) { return cat(transaction, ...txWitnesses); }, - async getOrderId(transaction: Uint8Array, outputIndex: number) { - idCalls.push({ transaction, outputIndex }); - return `mordr1${bytesToHex(sha256(transaction)).slice(0, 12)}`; + async getOrderId(inputs: Uint8Array[]) { + idCalls.push({ inputs }); + return `mordr1${bytesToHex(sha256(cat(...inputs))).slice(0, 12)}`; }, } as unknown as MintlayerBindings & { witnesses: WitnessParams[]; orderParams: OrderParams[]; - fillCalls: { orderId: string; destination: string; amount: string }[]; - concludeCalls: { orderId: string; destination: string }[]; - idCalls: { transaction: Uint8Array; outputIndex: number }[]; + fillCalls: { orderId: string; destination: string; amount: string; nonce: number; height: number }[]; + concludeCalls: { orderId: string; nonce: number; height: number }[]; + idCalls: { inputs: Uint8Array[] }[]; noSignatureCount: () => number; }; } @@ -145,12 +146,6 @@ function tokenUtxo(sourceId: string, index: number, address: string, amount: str }; } -/** bech32m data payload of an id or address, hex form (what the bindings - * byte-blob arguments record). */ -function payloadOf(value: string): string { - return bytesToHex(Uint8Array.from(bech32m.decode(value).words)); -} - type OrderRow = MlOrderInfo; function orderRow(overrides: Partial): OrderRow { @@ -278,10 +273,7 @@ async function main() { const result = await h.flows.createOrder({ giveTokenId: COIN_REF, giveAtoms: atoms(5n), askTokenId: TOKEN_ID, askAtoms: atoms(2n) }); assert.match(result.orderId, /^mordr1/); assert.equal(h.bindings.idCalls.length, 1); - assert.equal(h.bindings.idCalls[0].outputIndex, 0); - assert.ok(h.bindings.idCalls[0].transaction.length > 0); - // The order output encodes once per sizing pass and once for the real - // build; the final encoding carries the real amounts. + assert.ok(h.bindings.idCalls[0].inputs.length >= 1, 'the order id derives from the create tx inputs'); assert.ok(h.bindings.orderParams.length >= 2); assert.deepEqual(h.bindings.orderParams[h.bindings.orderParams.length - 1].give, { tokenId: 'coin', atoms: atoms(5n) }); assert.deepEqual(h.bindings.orderParams[h.bindings.orderParams.length - 1].ask, { tokenId: TOKEN_ID, atoms: atoms(2n) }); @@ -323,8 +315,10 @@ async function main() { assert.match(result.txId, /^[0-9a-f]{64}$/); assert.equal(h.bindings.fillCalls.length, 1); assert.equal(h.bindings.fillCalls[0].amount, atoms(3n)); - assert.equal(h.bindings.fillCalls[0].destination, payloadOf(destination)); - assert.equal(h.bindings.fillCalls[0].orderId, payloadOf(ORDER_ID)); + assert.equal(h.bindings.fillCalls[0].destination, destination); + assert.equal(h.bindings.fillCalls[0].orderId, ORDER_ID); + assert.equal(h.bindings.fillCalls[0].nonce, 0, 'the first account spending of the session carries nonce 0'); + assert.equal(h.bindings.fillCalls[0].height, 12345, 'the input form rides the indexer tip height'); // Witness mix: the fill input at index 0 is unsigned; both payer // inputs (ask token + fee coin) sign with the wallet key. assert.equal(h.bindings.noSignatureCount(), 1); @@ -385,7 +379,9 @@ async function main() { const result = await h2.flows.concludeOrder({ orderId: ORDER_ID }); assert.match(result.txId, /^[0-9a-f]{64}$/); assert.equal(h2.bindings.concludeCalls.length, 1); - assert.equal(h2.bindings.concludeCalls[0].destination, payloadOf(VECTOR_ADDRESS)); + assert.equal(h2.bindings.concludeCalls[0].orderId, ORDER_ID); + assert.equal(h2.bindings.concludeCalls[0].nonce, 0); + assert.equal(h2.bindings.concludeCalls[0].height, 12345); assert.equal(h2.bindings.noSignatureCount(), 1); assert.equal(h2.bindings.witnesses.length, 1); assert.equal(bytesToHex(h2.bindings.witnesses[0].privateKey), expectedKey); diff --git a/src/trade/orders.ts b/src/trade/orders.ts index eea428c..3990ac1 100644 --- a/src/trade/orders.ts +++ b/src/trade/orders.ts @@ -16,7 +16,7 @@ // Without the native call-through the bindings reject, which surfaces as // the honest device-pending state (modules/mojito-core header), never a // JavaScript reimplementation of the encoding. -import { bech32m, hex as hexOf } from '@scure/base'; +import { hex as hexOf } from '@scure/base'; import { bytesToHex } from '@noble/hashes/utils.js'; import type { MintlayerBindings, MlNetwork } from '../../modules/mojito-core'; @@ -135,6 +135,12 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { if (bindings === null) bindings = cfg.loadBindings(); return bindings; } + /** Account-nonce counter for the order fill and conclude inputs (the + * bindings docs: the nonce must sequence with the filler's other + * account spendings). Session-scoped until the wallet persists the + * account nonce with its state; the native call-through must not go + * live before that (recorded in plans/mojito-neo/decisions.md). */ + let accountNonce = 0; /** One order transaction at a time: selection reads live UTXOs and the * change allocation mutates the persisted counters (realSend pattern). */ let inFlight = false; @@ -330,10 +336,10 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { outputs.push(await b().encodeOutputTransfer(selection.changeAtoms, changeAddress, cfg.network)); } - const { txId, transaction } = await finish(inputs, outputs, selection.selection, new Map()); - // The order id is a bindings extraction on the create tx output - // (F11); output 0 is the order output this flow assembled. - const orderId = await b().getOrderId(transaction, 0); + const { txId } = await finish(inputs, outputs, selection.selection, new Map()); + // The order id derives from the create tx inputs through the + // bindings (make_order_id(tx.inputs()), no output index). + const orderId = await b().getOrderId(inputs, cfg.network); return { txId, orderId }; } catch (e) { await cfg.releaseFailedChange(); @@ -381,10 +387,16 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { }, }); + // The fill input selects the orders V0/V1 form through the + // account nonce and the current block height (bindings docs); + // both come from the indexer tip plus the in-session counter. const fillInput = await b().encodeInputForFillOrder( - decodeBech32Data(orderId), - decodeBech32Data(destination), + orderId, fillAtoms, + destination, + accountNonce++, + (await cfg.indexer.tip()).blockHeight, + cfg.network, ); const inputs: Uint8Array[] = [fillInput]; for (const selected of selection.selection) inputs.push(await utxoInput(selected)); @@ -452,8 +464,10 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { }); const concludeInput = await b().encodeInputForConcludeOrder( - decodeBech32Data(orderId), - decodeBech32Data(order.concludeDestination), + orderId, + accountNonce++, + (await cfg.indexer.tip()).blockHeight, + cfg.network, ); const inputs: Uint8Array[] = [concludeInput]; for (const selected of selection.selection) inputs.push(await utxoInput(selected)); @@ -520,10 +534,3 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { export function proportionalGivePayout(giveLegAtoms: string, askLegAtoms: string, fillAtoms: string): string { return ((BigInt(giveLegAtoms) * BigInt(fillAtoms)) / BigInt(askLegAtoms)).toString(); } - -/** bech32m data payload of an id or address string (the bindings byte-blob - * form for order ids and destinations; Mintlayer encodes m-prefixed ids - * with the bech32m checksum). */ -function decodeBech32Data(value: string): Uint8Array { - return new Uint8Array(bech32m.decode(value).words); -} diff --git a/src/trade/swapSession.test.ts b/src/trade/swapSession.test.ts index cccdfb8..82233b3 100644 --- a/src/trade/swapSession.test.ts +++ b/src/trade/swapSession.test.ts @@ -25,6 +25,7 @@ const row = (overrides?: Partial): SwapSessionRow => ({ spendAddress: 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl', spendPubkeyHex: '02'.repeat(33), refundAddress: 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl', + lockTxHex: 'ee0102ff01', state: 'offered', txIds: [], updatedAt: 1700000000000, @@ -73,9 +74,12 @@ async function main() { assert.equal(one?.state, 'offered'); assert.equal(await store.get('missing'), null); - // Restart path: a fresh store over the same backend restores rows. + // Restart path: a fresh store over the same backend restores rows, + // including the lock tx bytes the claim and refund decodes need. const reopened = createSwapSessionStore(backend.storage); - assert.equal((await reopened.all()).length, 2); + const restored = await reopened.all(); + assert.equal(restored.length, 2); + assert.equal(restored.find((r) => r.id === 'swap-1')?.lockTxHex, 'ee0102ff01'); await reopened.remove('swap-1'); assert.deepEqual((await reopened.all()).map((r) => r.id), ['swap-2']); } @@ -93,20 +97,27 @@ async function main() { } // Corrupt stores drop bad rows instead of wedging the machine: garbage - // JSON, non-rows, a bad secret-hash shape, an unknown state. + // JSON, non-rows, a bad secret-hash shape, a bad lock-tx shape, an + // unknown state. assert.deepEqual(parseSwapSessions(null), []); assert.deepEqual(parseSwapSessions('not json'), []); assert.deepEqual(parseSwapSessions('{"a":1}'), []); const good = row(); const badHash = row({ id: 'bad-hash', secretHashHex: 'zz' }); + const badLockTx = row({ id: 'bad-locktx', lockTxHex: 'not-hex!' }); const badState = row({ id: 'bad-state', state: 'cancelled' as SwapState }); const tooManyTxIds = row({ id: 'bad-txids', txIds: Array.from({ length: 20 }, () => 'aa') }); - const mixed = JSON.stringify([good, badHash, badState, tooManyTxIds]); + const mixed = JSON.stringify([good, badHash, badLockTx, badState, tooManyTxIds]); const parsed = parseSwapSessions(mixed); assert.deepEqual( parsed.map((r) => r.id), ['swap-1'], ); + // Rows persisted before the lock-tx record stay loadable (optional + // field); they just cannot refund (the screen guards on the bytes). + const legacy = JSON.parse(JSON.stringify(row({ id: 'legacy' }))); + delete legacy.lockTxHex; + assert.equal(parseSwapSessions(JSON.stringify([legacy])).length, 1); // Session cap: a hostile store cannot force unbounded memory. const many = Array.from({ length: 40 }, (_, i) => row({ id: `s${i}` })); diff --git a/src/trade/swapSession.ts b/src/trade/swapSession.ts index cb9ca6b..e007cea 100644 --- a/src/trade/swapSession.ts +++ b/src/trade/swapSession.ts @@ -25,6 +25,11 @@ export type SwapSessionRow = { spendAddress: string; spendPubkeyHex: string; refundAddress: string; + /** Hex of the unsigned lock transaction bytes as built before the + * broadcast: the claim and refund bindings decodes consume serialized + * transaction bytes and the public indexer serves no raw-tx route, so + * these are the only honest source after a restart. */ + lockTxHex?: string; state: SwapState; txIds: string[]; updatedAt: number; @@ -109,6 +114,7 @@ export function parseSwapSessions(json: string | null): SwapSessionRow[] { typeof row.secretHashHex === 'string' && /^[0-9a-f]{64}$/.test(row.secretHashHex) && typeof row.spendAddress === 'string' && typeof row.refundAddress === 'string' && + (row.lockTxHex === undefined || (typeof row.lockTxHex === 'string' && /^[0-9a-f]*$/.test(row.lockTxHex) && row.lockTxHex.length % 2 === 0)) && typeof row.state === 'string' && row.state in TRANSITIONS && Array.isArray(row.txIds) && row.txIds.length <= MAX_TX_IDS && row.txIds.every((id) => typeof id === 'string') && typeof row.updatedAt === 'number' && Number.isFinite(row.updatedAt) From a83dba0417d8c1b702d4e0a38e49688d947b2cdb Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 07:47:02 +0100 Subject: [PATCH 12/20] fix(m4): honest dex ticket, fill preview and deleted fixture seams The DEX ticket now derives the give and ask legs from the selected side and refuses non-limit order types with honest copy, dedicated i18n keys replace every wrong-key reuse, the fill runs a payout preview with an effective-price re-check against the book mid band inside the flows, the market header renders a typed unavailable state instead of the fixture row on a snapshot miss, the six dead M0 fixture seams leave the WalletData surface, the no-console secret guard scans src/trade and src/screens, and swap sessions persist the offer in a scalar form with the secret hash bytes rebuilt from hex on load. --- scripts/no-console.ts | 2 +- src/data.ts | 50 ++------- src/data/mock/fixtures.ts | 13 --- src/data/providers/index.ts | 8 +- src/data/providers/providers.test.ts | 5 +- src/data/providers/types.ts | 24 +---- src/data/real/realWalletData.ts | 16 +-- src/i18n/strings/en.ts | 17 +++- src/screens/BridgeScreen.tsx | 2 +- src/screens/DexScreen.tsx | 147 +++++++++++++++++++++------ src/screens/SwapScreen.tsx | 2 +- src/trade/orders.test.ts | 32 +++++- src/trade/orders.ts | 49 ++++++++- src/trade/swapSession.test.ts | 27 ++++- src/trade/swapSession.ts | 58 ++++++++++- 15 files changed, 312 insertions(+), 140 deletions(-) diff --git a/scripts/no-console.ts b/scripts/no-console.ts index 7bec258..69c1b48 100644 --- a/scripts/no-console.ts +++ b/scripts/no-console.ts @@ -8,7 +8,7 @@ import { readdirSync, readFileSync, statSync } from 'node:fs'; import { join } from 'node:path'; -const SCAN_ROOTS = ['modules/mojito-core', 'src/keys', 'src/storage', 'src/data', 'src/onboarding']; +const SCAN_ROOTS = ['modules/mojito-core', 'src/keys', 'src/storage', 'src/data', 'src/onboarding', 'src/trade', 'src/screens']; const failures: string[] = []; diff --git a/src/data.ts b/src/data.ts index 0ed4508..15d5257 100644 --- a/src/data.ts +++ b/src/data.ts @@ -3,7 +3,6 @@ import type { ActivityRow, AssetRow, CandleInterval, PriceRange } from './data/providers/types'; import type { IconName } from './ui/icons'; -import type { StepState } from './ui/StepState'; import type { ChainName, Tone } from './theme'; export const PROFILE = { @@ -77,48 +76,15 @@ export const BIDS = [ export const TIMEFRAMES: CandleInterval[] = ['1m', '5m', '15m', '1h', '4h', '1d']; -/* ── Swap ────────────────────────────────────────────────── */ - -export const HTLC_STEPS = [ - { label: 'Initiate swap', detail: 'Generate secret hash · lock 0.025 BTC', state: 'done' }, - { label: 'Counterparty matched', detail: 'Mintlayer node locks 7,012.45 ML', state: 'done' }, - { label: 'Reveal preimage on Mintlayer', detail: 'Claim ML, hash exposed onchain', state: 'active', note: '~3 min' }, - { label: 'Counterparty claims BTC', detail: 'Settles atomically', state: 'pending' }, -] satisfies { label: string; detail: string; state: StepState; note?: string }[]; - -export const SWAP_STATS = [ - ['Rate', '1 BTC = 280,498 ML'], - ['Slippage', '0.18%'], - ['Timelock', '24h refund'], - ['Est. time', '~18 min'], -] satisfies [string, string][]; - -/* ── Bridge ──────────────────────────────────────────────── */ - -// M4 (F14, R5): the real bridge scope is exactly Ethereum and Mintlayer; -// the EVM demo chains of the M0 design (Arbitrum, Polygon, BNB) are gone -// and the E2M direction is disabled with explanatory copy (R5: no EVM -// signer; scoped decision open, never silently dropped). -export const BRIDGE_CHAINS = [ - { name: 'Mintlayer', sym: 'ML' }, - { name: 'Ethereum', sym: 'ETH' }, -] satisfies { name: ChainName; sym: string }[]; - -/** Ethereum-side mint contract shown in the route and the bridge fixture. */ -export const BRIDGE_CONTRACT = '0xA1c2…F39e'; +/* ── Bridge ───────────────────────────────────────── */ -export const BRIDGE_ROUTE = [ - { label: 'Lock on Mintlayer', detail: 'ml deposit to the bridge treasury', icon: 'lock', eta: '~15s' }, - { label: 'Validator attestation', detail: 'agent majority signs the intent', icon: 'shield', eta: '~12 confirmations' }, - { label: 'Mint on Ethereum', detail: `${BRIDGE_CONTRACT} (wrapped asset)`, icon: 'flash', eta: '~1 min' }, -] satisfies { label: string; detail: string; icon: IconName; eta: string }[]; - -export const BRIDGE_QUOTE = [ - ['Bridge fee', '0.15% · $0.75'], - ['Est. time', '~65 sec'], - ['You receive', '499.25 USDT'], - ['Gas (ETH)', '0.00012 ETH'], -] satisfies [string, string][]; +/** Ethereum-side mint contract shown in the bridge fixture quote. The + * swap/bridge fixture rows of the M0 design (HTLC_STEPS, SWAP_STATS, + * BRIDGE_CHAINS, BRIDGE_ROUTE, BRIDGE_QUOTE) died with the M4 live + * trade seams: the screens run the real session steps, the order book + * service and the bridge_v2 provider, so the fixture rows are deleted + * rather than kept as forward-declared API. */ +export const BRIDGE_CONTRACT = '0xA1c2…F39e'; /* ── Card ────────────────────────────────────────────────── */ diff --git a/src/data/mock/fixtures.ts b/src/data/mock/fixtures.ts index 23cd73e..58d4558 100644 --- a/src/data/mock/fixtures.ts +++ b/src/data/mock/fixtures.ts @@ -4,28 +4,21 @@ import { ACTIVITY, ADDRESSES, - ASKS, ASSETS, ASSET_BALANCES, ASSET_SYMBOLS, BALANCE, - BIDS, - BRIDGE_CHAINS, BRIDGE_CONTRACT, - BRIDGE_QUOTE, - BRIDGE_ROUTE, CARD_FEATURES, CARD_TIERS, CHAIN_GLYPH, CONTACTS, DAPPS, FEES, - HTLC_STEPS, MARKET, NETWORKS, PROFILE, RANGES, - SWAP_STATS, TIMEFRAMES, WAITLIST, } from '../../data'; @@ -55,7 +48,6 @@ export function createFixtureWalletData(): WalletData { getRanges: async () => [...RANGES], getProfile: async () => PROFILE, getMarket: async () => MARKET, - getOrderBook: async () => ({ asks: [...ASKS], bids: [...BIDS] }), getTimeframes: async () => [...TIMEFRAMES], // Mock mode carries a single fixture id so order placement stays // demoable without pretending to resolve a real on-chain token (F6: @@ -63,11 +55,6 @@ export function createFixtureWalletData(): WalletData { // indexer instead). getTokenIds: async (ticker) => [ticker], getTokenMeta: async (tokenId) => ({ ticker: tokenId, decimals: tokenId === 'USDT' ? 6 : 0 }), - getHtlcSteps: async () => [...HTLC_STEPS], - getSwapStats: async () => SWAP_STATS, - getBridgeChains: async () => [...BRIDGE_CHAINS], - getBridgeRoute: async () => [...BRIDGE_ROUTE], - getBridgeQuote: async () => BRIDGE_QUOTE, getWaitlist: async () => WAITLIST, getDapps: async () => DAPPS, getCardFeatures: async () => [...CARD_FEATURES], diff --git a/src/data/providers/index.ts b/src/data/providers/index.ts index 741e7e1..4f9386b 100644 --- a/src/data/providers/index.ts +++ b/src/data/providers/index.ts @@ -170,10 +170,10 @@ export function createProviders(mode: ProviderMode = readDataMode()): Providers } export type { - ActivityRow, AssetRow, BookLevel, BridgeChain, BridgeHandle, BridgeProvider, BridgeQuote, - BridgeQuoteLine, BridgeQuoteRequest, BridgeRouteStep, BridgeState, BroadcastProvider, Candle, - CandleInterval, CardFeature, CardTier, Contact, DappsSummary, FeeSchedule, FeeTierId, HtlcStep, + ActivityRow, AssetRow, BridgeHandle, BridgeProvider, BridgeQuote, + BridgeQuoteRequest, BridgeState, BroadcastProvider, Candle, + CandleInterval, CardFeature, CardTier, Contact, DappsSummary, FeeSchedule, FeeTierId, MarketSummary, MlTxStatus, NftRow, SendQuote, SendQuoteLeg, SendResult, SendService, Portfolio, PricePoint, PriceProvider, PriceRange, PriceSnapshot, Profile, ProviderMode, - Providers, SwapStat, TxStatusInfo, WaitlistProvider, WaitlistResult, WaitlistStatus, WalletData, + Providers, TxStatusInfo, WaitlistProvider, WaitlistResult, WaitlistStatus, WalletData, } from './types'; diff --git a/src/data/providers/providers.test.ts b/src/data/providers/providers.test.ts index eec5b7e..7b642d8 100644 --- a/src/data/providers/providers.test.ts +++ b/src/data/providers/providers.test.ts @@ -27,6 +27,7 @@ async function main() { assert.equal(activity.length, 2); const market = await providers.data.getMarket('ML/USDT'); + assert.ok(market, 'the mock fixture market stays non-null'); assert.equal(market.pair, 'ML/USDT'); const snapshots = await providers.data.getPrices(['ML']); @@ -102,7 +103,9 @@ async function main() { // btcBase is unconfigured (F13), so Bitcoin is not listed as connected and // only Mintlayer counts as an active network. assert.deepEqual(await real.data.getNetworks(), ['Mintlayer']); - assert.equal((await real.data.getMarket('ML/USDT')).pair, 'ML/USDT'); + const realMarket = await real.data.getMarket('ML/USDT'); + assert.ok(realMarket, 'the R1 mock price source serves the ML snapshot, so the header stays live'); + assert.equal(realMarket.pair, 'ML/USDT'); // M4: the real bridge provider carries the R5 gates; E2M is refused // typed before any network call (no EVM signer, scoped decision open). await assert.rejects( diff --git a/src/data/providers/types.ts b/src/data/providers/types.ts index a880c45..341cc12 100644 --- a/src/data/providers/types.ts +++ b/src/data/providers/types.ts @@ -4,7 +4,6 @@ // missing-architecture.md so the real implementations slot in unchanged. import type { ChainName, Tone } from '../../theme'; import type { IconName } from '../../ui/icons'; -import type { StepState } from '../../ui/StepState'; import type { TxTracker } from '../../send/TxTracker'; import type { OrderBookService } from '../../trade/OrderBookService'; import type { OrderFlows } from '../../trade/orders'; @@ -56,15 +55,6 @@ export type MarketSummary = { high: string; low: string; volume: string; price: number; }; -export type BookLevel = { p: number; s: number; t: number }; - -// Swap and bridge fixture rows -export type HtlcStep = { label: string; detail: string; state: StepState; note?: string }; -export type SwapStat = [string, string]; -export type BridgeChain = { name: ChainName; sym: string }; -export type BridgeRouteStep = { label: string; detail: string; icon: IconName; eta: string }; -export type BridgeQuoteLine = [string, string]; - // Card export type WaitlistStatus = { taken: number; total: number }; export type DappsSummary = { active: number }; @@ -203,9 +193,10 @@ export interface WalletData { getNetworks(): Promise; getRanges(): Promise; getProfile(): Promise; - // dex - getMarket(pair: string): Promise; - getOrderBook(pair: string): Promise<{ asks: BookLevel[]; bids: BookLevel[] }>; + // dex. Null answers a price-snapshot miss: the header renders a typed + // unavailable state, never a fixture row (the AssetRow.unavailable + // precedent). + getMarket(pair: string): Promise; getTimeframes(): Promise; /** Token ids served for one ticker; tickers are not unique (F6), so the * list can carry more than one id and callers must disambiguate @@ -213,13 +204,6 @@ export interface WalletData { getTokenIds(ticker: string): Promise; /** Ticker and decimals of one token id; null when unindexed. */ getTokenMeta(tokenId: string): Promise<{ ticker: string | null; decimals: number } | null>; - // swap - getHtlcSteps(): Promise; - getSwapStats(): Promise; - // bridge - getBridgeChains(): Promise; - getBridgeRoute(): Promise; - getBridgeQuote(): Promise; // card getWaitlist(): Promise; getDapps(): Promise; diff --git a/src/data/real/realWalletData.ts b/src/data/real/realWalletData.ts index d752096..1892d67 100644 --- a/src/data/real/realWalletData.ts +++ b/src/data/real/realWalletData.ts @@ -17,10 +17,7 @@ import { ML_DECIMALS, atomsToDecimal, decimalsToAtoms, formatAmount, formatUsd } import { IndexerError } from '../ml/IndexerClient'; import type { AssetRow, NftRow, PriceProvider, PriceSnapshot, WalletData } from '../providers/types'; import type { AccountServices, RealAccountContext, RealAccountConfig } from './account'; -import { - CHAIN_GLYPH, DAPPS, FEES, HTLC_STEPS, MARKET, RANGES, SWAP_STATS, - TIMEFRAMES, WAITLIST, ASKS, BIDS, BRIDGE_CHAINS, BRIDGE_QUOTE, BRIDGE_ROUTE, -} from '../../data'; +import { CHAIN_GLYPH, DAPPS, FEES, RANGES, TIMEFRAMES, WAITLIST } from '../../data'; import { truncateMiddle } from '../../ui/format'; import { createFixtureWalletData } from '../mock/fixtures'; import { createFixturePriceProvider } from '../mock/priceFixtures'; @@ -221,12 +218,13 @@ export function createRealWalletData(context: RealAccountContext): WalletData { // M4: the market header derives from the R1 price provider (still the // mock source, so the figures stay indicative and the screens disclose // pricesAreMock); high, low and volume derive from the 1d candles the - // same source serves. No fixture row leaks into the header. + // same source serves. A snapshot miss answers null: the header renders + // a typed unavailable state, never a fixture row. getMarket: async (pair) => { const [snapshots, candles] = await Promise.all([price.getSnapshots(['ML', 'BTC']), price.getCandles(pair, '1d')]); const ml = snapshots.find((s) => s.tokenId === 'ML'); const btc = snapshots.find((s) => s.tokenId === 'BTC'); - if (!ml) return MARKET; + if (!ml) return null; const highDecimal = candles.reduce((acc, c) => (BigInt(decimalsToAtoms(c.h, 11)) > BigInt(decimalsToAtoms(acc, 11)) ? c.h : acc), candles[0]?.h ?? '0'); const lowDecimal = candles.reduce((acc, c) => (BigInt(decimalsToAtoms(c.l, 11)) < BigInt(decimalsToAtoms(acc, 11)) ? c.l : acc), candles[0]?.h ?? '0'); const volumeAtoms = candles.reduce((acc, c) => acc + BigInt(decimalsToAtoms(c.v, 11)), 0n); @@ -257,13 +255,7 @@ export function createRealWalletData(context: RealAccountContext): WalletData { return null; } }, - getOrderBook: async () => ({ asks: [...ASKS], bids: [...BIDS] }), getTimeframes: async () => [...TIMEFRAMES], - getHtlcSteps: async () => [...HTLC_STEPS], - getSwapStats: async () => SWAP_STATS, - getBridgeChains: async () => [...BRIDGE_CHAINS], - getBridgeRoute: async () => [...BRIDGE_ROUTE], - getBridgeQuote: async () => BRIDGE_QUOTE, getWaitlist: async () => WAITLIST, getDapps: async () => DAPPS, getCardFeatures: async () => fixtureData.getCardFeatures(), diff --git a/src/i18n/strings/en.ts b/src/i18n/strings/en.ts index d258969..71297ff 100644 --- a/src/i18n/strings/en.ts +++ b/src/i18n/strings/en.ts @@ -200,12 +200,23 @@ export const en = { 'dex.order.concluded': 'Concluded', 'dex.order.signingPending': 'Signing runs on the device bindings, which are pending on this build. Nothing was sent.', 'dex.order.broadcastOff': 'Order placement needs the Mintlayer submission route, which is not configured for this network (R3). Nothing was sent.', - 'dex.fill.amount': 'Fill amount', 'dex.fill.slippageWarn': 'This price has drifted {drift}% from the book mid. Review before continuing.', 'dex.conclude.confirm': 'Conclude closes the order and returns every remaining balance to your conclude address.', 'dex.priceIndicative': 'Indicative price source (mock). Verify before trading.', 'dex.book.error': 'The live book is unreachable right now.', 'dex.order.demo': 'Demo order placed. This is simulated data, not a chain order.', + 'dex.order.badAmount': 'Enter a valid amount on both legs of the order.', + 'dex.order.ambiguousTicker': 'Several tokens share this ticker. Pick the exact token id to trade.', + 'dex.order.typeUnsupported': 'Only limit orders are supported right now. Switch back to Limit to place an order.', + 'dex.order.busy': 'The previous order action is still running. Wait for it to finish.', + 'dex.orders.empty': 'No orders of yours yet. Placed orders show up here.', + 'dex.dev.demoBanner': 'Demo DEX: this order is simulated in this build, not a chain order.', + 'dex.fill.cta': 'Fill order', + 'dex.fill.confirm.title': 'Confirm fill', + 'dex.fill.pay': 'You pay', + 'dex.fill.receive': 'You receive', + 'dex.fill.effective': 'Effective price', + 'dex.book.mid': 'Book mid', // swap 'swap.title': 'Atomic Swap', @@ -260,6 +271,7 @@ export const en = { 'bridge.quote.eta': 'Estimated time', 'bridge.quote.confirmations': 'Deposit confirmations', 'bridge.quote.depositAddress': 'Deposit address', + 'bridge.quote.receive': 'You receive', 'bridge.state.awaitingDeposit': 'Awaiting deposit', 'bridge.state.attesting': 'Agents attesting', 'bridge.state.minted': 'Minted', @@ -359,6 +371,9 @@ export const en = { 'errors.htlc.expired': 'The refund unlocks after the timelock expiry.', 'errors.htlc.noOutput': 'That transaction carries no readable HTLC output, so the lock cannot be claimed or refunded.', 'errors.orders.book': 'The order book is unavailable right now.', + 'errors.orders.notOpen': 'That order is no longer open, so it cannot be filled or concluded.', + 'errors.orders.overbid': 'The fill exceeds the remaining ask balance of the order. Lower the amount.', + 'errors.orders.slippage': 'The effective fill price moved past your slippage band against the book mid. Nothing was sent.', // onboarding 'onboarding.welcome.tagline': 'One recovery phrase, every account.\nBitcoin and Mintlayer, self-custody.', diff --git a/src/screens/BridgeScreen.tsx b/src/screens/BridgeScreen.tsx index dc802ed..f0cfbe9 100644 --- a/src/screens/BridgeScreen.tsx +++ b/src/screens/BridgeScreen.tsx @@ -223,7 +223,7 @@ export function BridgeScreen() { {quote.confirmationsRequired !== undefined && ( )} - {receiveAmount !== null && } + {receiveAmount !== null && } )} diff --git a/src/screens/DexScreen.tsx b/src/screens/DexScreen.tsx index cbdfae1..31f1c10 100644 --- a/src/screens/DexScreen.tsx +++ b/src/screens/DexScreen.tsx @@ -4,7 +4,7 @@ import { t } from '../i18n'; import { useData, useProviders } from '../data/providers/context'; import type { Candle, CandleInterval } from '../data/providers'; import type { OrderData } from '../trade/orders'; -import { COIN_REF, orderPhase } from '../trade/orders'; +import { COIN_REF, orderPhase, proportionalGivePayout } from '../trade/orders'; import { checkAmounts, checkSlippage } from '../trade/priceGuards'; import { isBindingsUnavailable } from '../send/errors'; import { ML_DECIMALS, atomsToDecimal, decimalsToAtoms } from '../money'; @@ -18,7 +18,10 @@ const BOOK_POLL_MS = 30_000; const MAX_SLIPPAGE_PCT = 1; export function DexScreen() { - const market = useData((d) => d.getMarket('ML/USDT')); + // Loaded wrapper: useData answers null while pending AND for a null + // result, so the header unavailable state needs the resolved marker. + const marketState = useData(async (d) => ({ market: await d.getMarket('ML/USDT') })); + const market = marketState?.market ?? null; const timeframes = useData((d) => d.getTimeframes()); const fees = useData((d) => d.getFees()); const assets = useData((d) => d.getAssets()); @@ -98,27 +101,42 @@ export function DexScreen() { const [ticketError, setTicketError] = useState(null); const [placing, setPlacing] = useState(false); const [lastDemoNote, setLastDemoNote] = useState(null); + // Fill confirmation state: the payout preview (proportionalGivePayout on + // the order legs) plus the effective price versus the book mid, before + // any fill transaction is built. + const [fillSheet, setFillSheet] = useState<{ order: OrderData; payout: string; effective: string; mid: string } | null>(null); const bookRows = liveBook; - if (!market || !timeframes || !fees || !candles || !assets || !askTokenIds || !askMeta || !bookRows) return ; + if (!timeframes || !fees || !candles || !assets || !askTokenIds || !askMeta || !bookRows) return ; const maxAsk = Math.max(...bookRows.asks.map((r) => Number(r.total || 0)), 1); const maxBid = Math.max(...bookRows.bids.map((r) => Number(r.total || 0)), 1); - const total = usd(amount, market.price); - const bestAsk = Number(bookRows.asks[0]?.price ?? market.price); - const bestBid = Number(bookRows.bids[0]?.price ?? market.price); + const total = usd(amount, market?.price ?? 0); + const bestAsk = Number(bookRows.asks[0]?.price ?? market?.price ?? 0); + const bestBid = Number(bookRows.bids[0]?.price ?? market?.price ?? 0); const spread = Math.abs(bestAsk - bestBid); const spreadPct = (spread / bestAsk) * 100; const mlBalance = assets.find((a) => a.sym === 'ML')?.amt ?? 0; const bookIsStale = bookLoadedAt > 0 && Date.now() - bookLoadedAt > BOOK_STALE_MS; - /** Ticket submit: guards first, then the order flows. Real mode runs the - * full pipeline (device-pending and config-pending states surface - * honestly); mock mode runs the demo pipeline labelled as demo. */ + /** Ticket submit: the give/ask legs follow the selected side (buy: the + * USDT token is given and ML is asked; sell: the inverse), guards run + * first, and the order flows run last. Real mode runs the full pipeline + * (device-pending and config-pending states surface honestly); mock + * mode runs the demo pipeline labelled as demo. */ const placeOrder = async () => { setTicketError(null); - const guard = checkAmounts({ giveDecimal: amount, askDecimal: total }); + if (market === null) { + setTicketError(t('errors.price.unavailable')); + return; + } + if (orderType !== 'Limit') { + setTicketError(t('dex.order.typeUnsupported')); + return; + } + const buy = side === 'buy'; + const guard = checkAmounts({ giveDecimal: buy ? total : amount, askDecimal: buy ? amount : total }); if (!guard.ok) { - setTicketError(t('dex.order.place')); + setTicketError(t('dex.order.badAmount')); return; } // Slippage guard versus the live book mid (the ticket prices at the @@ -131,17 +149,19 @@ export function DexScreen() { return; } } + // Tickers are not unique (F6): placement refuses instead of guessing + // which token id the user meant. if (askTokenIds.length !== 1) { - setTicketError(t('errors.orders.notMine')); + setTicketError(t('dex.order.ambiguousTicker')); return; } setPlacing(true); try { await orders.createOrder({ - giveTokenId: COIN_REF, - giveAtoms: decimalsToAtoms(amount, ML_DECIMALS), - askTokenId: askTokenIds[0], - askAtoms: decimalsToAtoms(total, askMeta.decimals || ML_DECIMALS), + giveTokenId: buy ? askTokenIds[0] : COIN_REF, + giveAtoms: buy ? decimalsToAtoms(total, askMeta.decimals || ML_DECIMALS) : decimalsToAtoms(amount, ML_DECIMALS), + askTokenId: buy ? COIN_REF : askTokenIds[0], + askAtoms: buy ? decimalsToAtoms(amount, ML_DECIMALS) : decimalsToAtoms(total, askMeta.decimals || ML_DECIMALS), }); setConfirmOpen(false); setLastDemoNote(mode === 'mock' ? t('dex.order.demo') : null); @@ -154,18 +174,50 @@ export function DexScreen() { } }; + /** Fill preview: payout from the order legs (the same math the flow + * applies) and the effective ask-per-give price, checked against the + * book mid before the fill executes; the flow re-checks the band. */ + const openFill = (order: OrderData) => { + const mid = (bestAsk + bestBid) / 2; + const payout = proportionalGivePayout(order.giveBalanceAtoms, order.askBalanceAtoms, order.askBalanceAtoms); + const fillDecimal = Number(atomsToDecimal(order.askBalanceAtoms, askMeta.decimals)); + const payoutDecimal = Number(atomsToDecimal(payout, ML_DECIMALS)); + const effective = payoutDecimal > 0 ? fillDecimal / payoutDecimal : 0; + setFillSheet({ order, payout, effective: effective.toFixed(4), mid: mid.toFixed(4) }); + }; + + const runFill = async () => { + if (!fillSheet) return; + setPlacing(true); + try { + await orders.fillOrder({ + orderId: fillSheet.order.orderId, + fillAtoms: fillSheet.order.askBalanceAtoms, + destination: fillSheet.order.concludeDestination, + priceBand: { midDecimal: fillSheet.mid, maxSlippagePct: MAX_SLIPPAGE_PCT, askDecimals: askMeta.decimals, giveDecimals: ML_DECIMALS }, + }); + setFillSheet(null); + void loadMyOrders(); + } catch (e) { + setFillSheet(null); + setTicketError(orderErrorCopy(e)); + } finally { + setPlacing(false); + } + }; + return ( - {market.pair} + {'ML/USDT'} {t('dex.badge')} - {market.volume} + {market?.volume ?? ''} @@ -174,6 +226,9 @@ export function DexScreen() { {/* Price + candles */} + {market === null ? ( + {t('errors.price.unavailable')} + ) : ( @@ -200,6 +255,7 @@ export function DexScreen() { + )} @@ -301,13 +357,19 @@ export function DexScreen() { /> - + setAmount(String(Math.round(mlBalance * f)))} /> - setConfirmOpen(true)}> + {orderType !== 'Limit' && ( + + {t('dex.order.typeUnsupported')} + + )} + + setConfirmOpen(true)}> {t('dex.order.place')} {ticketError && ( @@ -322,7 +384,7 @@ export function DexScreen() { )} - + @@ -338,7 +400,7 @@ export function DexScreen() { )} {myOrders !== null && myOrders.length === 0 && ( - {t('swap.session.empty')} + {t('dex.orders.empty')} )} {myOrders?.map((order) => ( void loadMyOrders()} onError={setTicketError} + onFill={openFill} /> ))} @@ -355,20 +418,43 @@ export function DexScreen() { built (spec order entry guards). */} setConfirmOpen(false)} title={t('dex.order.confirm.title')}> - - + + {mode === 'mock' && ( - {t('bridge.dev.mockBanner')} + {t('dex.dev.demoBanner')} )} void placeOrder()}> {placing ? t('swap.state.pending') : t('dex.order.place')} + + {/* Fill confirmation: the payout preview and the effective price + before anything is built (spec order entry guards). */} + setFillSheet(null)} title={t('dex.fill.confirm.title')}> + {fillSheet && ( + <> + + + + + + + {Number(fillSheet.effective) > 0 && Number(fillSheet.mid) > 0 && (Math.abs(Number(fillSheet.effective) - Number(fillSheet.mid)) / Number(fillSheet.mid)) * 100 > MAX_SLIPPAGE_PCT && ( + + {t('dex.fill.slippageWarn', { drift: ((Math.abs(Number(fillSheet.effective) - Number(fillSheet.mid)) / Number(fillSheet.mid)) * 100).toFixed(2) })} + + )} + void runFill()}> + {placing ? t('swap.state.pending') : t('dex.fill.cta')} + + + )} + ); } @@ -381,12 +467,15 @@ function orderErrorCopy(e: unknown): string { if (record && typeof record.reason === 'string') { if (record.reason === 'broadcast-disabled') return t('dex.order.broadcastOff'); if (record.reason === 'not-mine') return t('errors.orders.notMine'); - if (record.reason === 'busy') return t('swap.state.pending'); + if (record.reason === 'not-open') return t('errors.orders.notOpen'); + if (record.reason === 'overbid') return t('errors.orders.overbid'); + if (record.reason === 'slippage') return t('errors.orders.slippage'); + if (record.reason === 'busy') return t('dex.order.busy'); } return t('dex.book.error'); } -function MyOrderRow({ order, onDone, onError }: { order: OrderData; onDone: () => void; onError: (message: string) => void }) { +function MyOrderRow({ order, onDone, onError, onFill }: { order: OrderData; onDone: () => void; onError: (message: string) => void; onFill: (order: OrderData) => void }) { const { orders } = useProviders(); const phase = orderPhase(order); const [busy, setBusy] = useState(false); @@ -420,8 +509,8 @@ function MyOrderRow({ order, onDone, onError }: { order: OrderData; onDone: () = tone="ghost" className="flex-1" disabled={busy} - onPress={() => void run(() => orders.fillOrder({ orderId: order.orderId, fillAtoms: order.askBalanceAtoms, destination: order.concludeDestination }))}> - {t('dex.fill.amount')} + onPress={() => onFill(order)}> + {t('dex.fill.cta')} (ml * ML).toString(); +/** Band matching the fixture order price (10 ML give, 7 USDT ask: the + * effective fill price is 0.7 ask per give at equal atom scales), so the + * guard tests can vary only the order or the mid. */ +const FILL_BAND = { midDecimal: '0.7', maxSlippagePct: 1, askDecimals: 11, giveDecimals: 11 }; function fakeBindings(): MintlayerBindings & { witnesses: WitnessParams[]; @@ -311,7 +315,7 @@ async function main() { const askUtxo = tokenUtxo('cc'.repeat(32), 0, VECTOR_ADDRESS, atoms(4n)); const h = harness({ detail, utxos: [coinUtxo('aa'.repeat(32), 0, VECTOR_ADDRESS, atoms(500n)), askUtxo] }); const destination = await mlAddressAt(account.xpub, 0, 1, 'mainnet'); - const result = await h.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(3n), destination }); + const result = await h.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(3n), destination, priceBand: { midDecimal: '0.7', maxSlippagePct: 1, askDecimals: 11, giveDecimals: 11 } }); assert.match(result.txId, /^[0-9a-f]{64}$/); assert.equal(h.bindings.fillCalls.length, 1); assert.equal(h.bindings.fillCalls[0].amount, atoms(3n)); @@ -347,21 +351,41 @@ async function main() { const frozen = orderRow({ frozen: true }); const h = harness({ detail: frozen }); await assert.rejects( - () => h.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(1n), destination: VECTOR_ADDRESS }), + () => h.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(1n), destination: VECTOR_ADDRESS, priceBand: FILL_BAND }), (e: unknown) => e instanceof OrderFlowError && e.reason === 'not-open', ); const concluded = orderRow({ giveBalance: { atoms: '0' }, askBalance: { atoms: '0' } }); const h2 = harness({ detail: concluded }); await assert.rejects( - () => h2.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(1n), destination: VECTOR_ADDRESS }), + () => h2.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(1n), destination: VECTOR_ADDRESS, priceBand: FILL_BAND }), (e: unknown) => e instanceof OrderFlowError && e.reason === 'not-open', ); const overbid = orderRow({ askBalance: { atoms: atoms(1n) } }); const h3 = harness({ detail: overbid }); await assert.rejects( - () => h3.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(2n), destination: VECTOR_ADDRESS }), + () => h3.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(2n), destination: VECTOR_ADDRESS, priceBand: FILL_BAND }), (e: unknown) => e instanceof OrderFlowError && e.reason === 'overbid', ); + // A hostile order row with a zero ask leg refuses typed instead of + // crashing the division. + const zeroLeg = orderRow({ askBalance: { atoms: atoms(1n) }, initiallyAsked: { atoms: '0' } }); + const h4 = harness({ detail: zeroLeg }); + await assert.rejects( + () => h4.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(1n), destination: VECTOR_ADDRESS, priceBand: FILL_BAND }), + (e: unknown) => e instanceof OrderFlowError && e.reason === 'rejected', + ); + // The effective price re-check: an order priced far from the book mid + // refuses typed before any transaction is built. + const offBook = orderRow({ initiallyGiven: { atoms: atoms(10n) }, initiallyAsked: { atoms: atoms(1n) } }); + const h5 = harness({ detail: offBook }); + await assert.rejects( + () => h5.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(1n), destination: VECTOR_ADDRESS, priceBand: { midDecimal: '0.7', maxSlippagePct: 1, askDecimals: 11, giveDecimals: 11 } }), + (e: unknown) => e instanceof OrderFlowError && e.reason === 'slippage', + ); + // The same order inside the band passes the guard and builds. + const inBand = harness({ detail: offBook, utxos: [coinUtxo('aa'.repeat(32), 0, VECTOR_ADDRESS, atoms(500n)), tokenUtxo('dd'.repeat(32), 0, VECTOR_ADDRESS, atoms(4n))] }); + const filled = await inBand.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(1n), destination: VECTOR_ADDRESS, priceBand: { midDecimal: '0.1', maxSlippagePct: 1, askDecimals: 11, giveDecimals: 11 } }); + assert.match(filled.txId, /^[0-9a-f]{64}$/); } // 5. concludeOrder: foreign conclude destination refuses as not-mine; the diff --git a/src/trade/orders.ts b/src/trade/orders.ts index 3990ac1..20f7a2e 100644 --- a/src/trade/orders.ts +++ b/src/trade/orders.ts @@ -27,11 +27,26 @@ import type { KeySession } from '../keys/session'; import { mlAddressAt, mlPrivateKeyFromSeed, mlXpubFromSeed, type MlBranch } from '../keys/mlAccounts'; import { selectMlInputs, type EstimatedMlOutput, type SelectedMlInput } from '../send/MlTxBuilder'; import { BroadcastError } from '../data/providers/BroadcastProvider'; +import { checkSlippage } from './priceGuards'; /** Sentinel marking the base coin (give_token '0' in the F11 docs model; * the bindings OrderParams spelling is 'coin'). */ export const COIN_REF = 'coin' as const; +/** Fractional digits kept when flattening the effective fill price + * (display-scale comparison against the book mid; no float money math). */ +const EFFECTIVE_PRICE_DIGITS = 8; + +/** num/denom as a decimal string at fixed digits, pure BigInt. */ +function rationalDecimal(num: bigint, denom: bigint): string { + if (denom <= 0n) throw new OrderFlowError('rejected', 'the effective price is not computable'); + const scaled = (num * 10n ** BigInt(EFFECTIVE_PRICE_DIGITS)) / denom; + const text = scaled.toString().padStart(EFFECTIVE_PRICE_DIGITS + 1, '0'); + const int = text.slice(0, text.length - EFFECTIVE_PRICE_DIGITS); + const frac = text.slice(text.length - EFFECTIVE_PRICE_DIGITS); + return frac.length > 0 ? `${int}.${frac}` : int; +} + export type OrderData = { orderId: string; /** 'coin' marks the base coin, otherwise the token id. */ @@ -81,8 +96,9 @@ export interface OrderFlows { * bindings on the create tx output. */ createOrder(params: { giveTokenId: string; giveAtoms: string; askTokenId: string; askAtoms: string }): Promise<{ txId: string; orderId: string }>; /** Pay fillAtoms of the ask currency into an order; the proportional - * give payout lands on destination. */ - fillOrder(params: { orderId: string; fillAtoms: string; destination: string }): Promise<{ txId: string }>; + * give payout lands on destination. The price band re-checks the + * effective fill price against the book mid before anything is built. */ + fillOrder(params: { orderId: string; fillAtoms: string; destination: string; priceBand: PriceBand }): Promise<{ txId: string }>; /** Close an order (maker only) and return the leftovers to the conclude * destination. */ concludeOrder(params: { orderId: string }): Promise<{ txId: string }>; @@ -93,6 +109,17 @@ export interface OrderFlows { myOrders(): Promise; } +/** Slippage band for the fill: the effective price computed from the + * fetched order must stay within maxSlippagePct of the book mid. The + * decimals are the display decimals of the two currencies, because the + * effective price crosses two atom scales. */ +export type PriceBand = { + midDecimal: string; + maxSlippagePct: number; + askDecimals: number; + giveDecimals: number; +}; + export type OrderFlowsConfig = { network: MlNetwork; /** The bindings facade loader (MojitoCore): a thunk because the facade @@ -121,7 +148,7 @@ const ORIGIN_WALK_LIMIT = 512; export class OrderFlowError extends Error { constructor( - readonly reason: 'rejected' | 'busy' | 'not-open' | 'overbid' | 'not-mine' | 'broadcast-disabled', + readonly reason: 'rejected' | 'busy' | 'not-open' | 'overbid' | 'not-mine' | 'slippage' | 'broadcast-disabled', detail?: string, ) { super(detail ?? `order flow rejected: ${reason}`); @@ -348,7 +375,7 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { }); }, - async fillOrder({ orderId, fillAtoms, destination }) { + async fillOrder({ orderId, fillAtoms, destination, priceBand }) { return serialize(async () => { requireAtomAmount(fillAtoms); const info = await cfg.indexer.order(orderId); @@ -360,8 +387,22 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { // indexer serves them, current balances on fully-unfilled orders). const giveLeg = BigInt(info.initiallyGiven?.atoms ?? order.giveBalanceAtoms); const askLeg = BigInt(info.initiallyAsked?.atoms ?? order.askBalanceAtoms); + if (giveLeg <= 0n || askLeg <= 0n) throw new OrderFlowError('rejected', 'the order legs are not a usable price'); const givePayout = ((giveLeg * BigInt(fillAtoms)) / askLeg).toString(); + // Effective fill price (ask units per give unit) from the fetched + // order, re-checked against the book mid inside the user band + // before any transaction is built: a stale or hostile book must + // not silently price the fill. + const effective = rationalDecimal( + BigInt(fillAtoms) * 10n ** BigInt(priceBand.giveDecimals), + BigInt(givePayout) * 10n ** BigInt(priceBand.askDecimals), + ); + const band = checkSlippage({ limitDecimal: effective, midDecimal: priceBand.midDecimal, maxSlippagePct: priceBand.maxSlippagePct }); + if (!band.ok) { + throw new OrderFlowError('slippage', `the effective fill price ${effective} sits past the ${priceBand.maxSlippagePct}% band around the mid ${priceBand.midDecimal}`); + } + const utxos = await fetchUtxos(); const changeAddress = await cfg.allocateChangeAddress(); try { diff --git a/src/trade/swapSession.test.ts b/src/trade/swapSession.test.ts index 82233b3..5fc8a93 100644 --- a/src/trade/swapSession.test.ts +++ b/src/trade/swapSession.test.ts @@ -85,7 +85,8 @@ async function main() { } // The persisted JSON carries the secret hash only: the raw preimage - // bytes must never appear in storage. + // bytes must never appear in storage, and the offer rides its scalar + // persisted form (no byte fields that JSON would mangle into objects). { const backend = memoryStorage(); const store = createSwapSessionStore(backend.storage); @@ -94,6 +95,20 @@ async function main() { assert.ok(json.includes(bytesToHex(new Uint8Array(32).fill(0x21))), 'the secret hash persists'); assert.ok(!json.includes('preimage'), 'no preimage field ever persists'); assert.ok(!('secret' in JSON.parse(json)[0].offer)); + const savedOffer = JSON.parse(json)[0].offer; + assert.deepEqual(Object.keys(savedOffer).sort(), ['giveAtoms', 'giveChain', 'role', 'timelockSeconds', 'wantAtoms'], 'the offer persists in its scalar form'); + } + + // Round-trip: the restored row rebuilds the secret hash bytes from the + // persisted hex (Uint8Array, not a JSON object map). + { + const backend = memoryStorage(); + const store = createSwapSessionStore(backend.storage); + await store.save(row({ state: 'locked' })); + const restored = (await store.all())[0]; + assert.ok(restored.offer.secretHash instanceof Uint8Array, 'secretHash is rebuilt as bytes'); + assert.equal(bytesToHex(restored.offer.secretHash), bytesToHex(new Uint8Array(32).fill(0x21))); + assert.equal(restored.offer.timelockSeconds, 172800); } // Corrupt stores drop bad rows instead of wedging the machine: garbage @@ -106,13 +121,21 @@ async function main() { const badHash = row({ id: 'bad-hash', secretHashHex: 'zz' }); const badLockTx = row({ id: 'bad-locktx', lockTxHex: 'not-hex!' }); const badState = row({ id: 'bad-state', state: 'cancelled' as SwapState }); + const badTimelock = row({ id: 'bad-timelock', offer: { ...OFFER, timelockSeconds: Number.NaN } }); + const badOfferShape = row({ id: 'bad-offer', offer: { ...OFFER, role: 'attacker' as never } }); const tooManyTxIds = row({ id: 'bad-txids', txIds: Array.from({ length: 20 }, () => 'aa') }); - const mixed = JSON.stringify([good, badHash, badLockTx, badState, tooManyTxIds]); + const mixed = JSON.stringify([good, badHash, badLockTx, badState, badTimelock, badOfferShape, tooManyTxIds]); const parsed = parseSwapSessions(mixed); assert.deepEqual( parsed.map((r) => r.id), ['swap-1'], ); + // A tampered offer object carrying a mangled byte field is normalized: + // the rebuilt bytes come from secretHashHex, not from the stored junk. + const tampered = JSON.parse(JSON.stringify(row({ id: 'tampered' }))); + tampered.offer.secretHash = { 0: 1 }; + const normalized = parseSwapSessions(JSON.stringify([tampered]))[0]; + assert.equal(bytesToHex(normalized.offer.secretHash), bytesToHex(new Uint8Array(32).fill(0x21))); // Rows persisted before the lock-tx record stay loadable (optional // field); they just cannot refund (the screen guards on the bytes). const legacy = JSON.parse(JSON.stringify(row({ id: 'legacy' }))); diff --git a/src/trade/swapSession.ts b/src/trade/swapSession.ts index e007cea..0dba7bb 100644 --- a/src/trade/swapSession.ts +++ b/src/trade/swapSession.ts @@ -4,6 +4,7 @@ // rows carry the secret hash and transaction ids, NEVER the preimage (the // spec security note: losing the preimage forfeits the swap, so the session // screen shows a keep-open warning instead of persisting the secret). +import { hex as hexOf } from '@scure/base'; import { STORAGE_KEYS } from '../storage/keys'; import { loadAsyncStorage } from '../storage/asyncStorage'; import { devFallbackAllowed } from '../config/runtime'; @@ -35,6 +36,34 @@ export type SwapSessionRow = { updatedAt: number; }; +/** The persisted offer form: scalar fields only. Byte fields (the secret + * hash) never persist inside the offer; JSON would mangle a Uint8Array + * into an object map and the restored row would lie about its type. The + * bytes are rebuilt from secretHashHex on load, exactly like + * spendPubkeyHex already does for the spend key. */ +type PersistedOffer = { + role: HtlcOffer['role']; + giveChain: HtlcOffer['giveChain']; + giveAtoms: string; + wantAtoms: string; + timelockSeconds: number; +}; + +/** Serialize one row into its persisted form (offer bytes stripped). */ +function toPersisted(row: SwapSessionRow): Omit & { offer: PersistedOffer } { + const { offer, ...rest } = row; + return { + ...rest, + offer: { + role: offer.role, + giveChain: offer.giveChain, + giveAtoms: offer.giveAtoms, + wantAtoms: offer.wantAtoms, + timelockSeconds: offer.timelockSeconds, + }, + }; +} + /** Allowed transitions; anything else is a programming error, not a * silent overwrite. */ const TRANSITIONS: Record = { @@ -108,9 +137,15 @@ export function parseSwapSessions(json: string | null): SwapSessionRow[] { const rows: SwapSessionRow[] = []; for (const entry of parsed.slice(0, MAX_SESSIONS)) { const row = entry as Partial; + const offer = row.offer as Partial | null | undefined; if ( typeof row.id === 'string' && row.id.length > 0 && - row.offer !== null && typeof row.offer === 'object' && + offer !== null && typeof offer === 'object' && + (offer.role === 'initiator' || offer.role === 'counterparty') && + (offer.giveChain === 'ml' || offer.giveChain === 'btc') && + typeof offer.giveAtoms === 'string' && /^\d+$/.test(offer.giveAtoms) && + typeof offer.wantAtoms === 'string' && /^\d+$/.test(offer.wantAtoms) && + typeof offer.timelockSeconds === 'number' && Number.isInteger(offer.timelockSeconds) && offer.timelockSeconds > 0 && typeof row.secretHashHex === 'string' && /^[0-9a-f]{64}$/.test(row.secretHashHex) && typeof row.spendAddress === 'string' && typeof row.refundAddress === 'string' && @@ -119,7 +154,20 @@ export function parseSwapSessions(json: string | null): SwapSessionRow[] { Array.isArray(row.txIds) && row.txIds.length <= MAX_TX_IDS && row.txIds.every((id) => typeof id === 'string') && typeof row.updatedAt === 'number' && Number.isFinite(row.updatedAt) ) { - rows.push(entry as SwapSessionRow); + // Normalize: the in-memory row carries the secret hash bytes rebuilt + // from the persisted hex, never whatever a tampered store embedded + // inside the offer object. + rows.push({ + ...(entry as SwapSessionRow), + offer: { + role: offer.role, + giveChain: offer.giveChain, + giveAtoms: offer.giveAtoms, + wantAtoms: offer.wantAtoms, + secretHash: hexOf.decode(row.secretHashHex), + timelockSeconds: offer.timelockSeconds, + }, + }); } } return rows; @@ -129,9 +177,9 @@ export function createSwapSessionStore(storage: SwapSessionStorage = defaultStor return { async save(row) { assertTransitionIsKnown(row.state); - const rows = (await this.all()).filter((existing) => existing.id !== row.id); - rows.unshift({ ...row, txIds: row.txIds.slice(0, MAX_TX_IDS) }); - await storage.save(JSON.stringify(rows.slice(0, MAX_SESSIONS))); + const existing = (await this.all()).map(toPersisted).filter((saved) => saved.id !== row.id); + existing.unshift(toPersisted({ ...row, txIds: row.txIds.slice(0, MAX_TX_IDS) })); + await storage.save(JSON.stringify(existing.slice(0, MAX_SESSIONS))); }, async all() { return parseSwapSessions(await storage.load()); From 652bd21dc553f38da2fa5c1d9c18eb1c466a9c25 Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 07:52:32 +0100 Subject: [PATCH 13/20] fix(m4): verified broadcasts, guard hardening and nitpick batch finishTx and the HTLC broadcast apply the local-txid equality contract, the dead secret parameter and the unreachable HTLC-spend branch leave the multi-input signer, the fee and input estimates use the real HTLC output index, checkSlippage answers a typed result on a non-finite band, extractSecret sanity-checks the claim bytes and documents the strict-byte-size choice, the DEX conclude button gets a real label, the bridge quote refresh is debounced, the parseAmount object form documents the rational-atom exception, allUtxos and coinStatistics are trimmed per the D13 consume-or-trim rule, and the decisions log consolidates the M4 deviations. --- plans/mojito-neo/decisions.md | 44 +++++++++++++++++++++++++ src/data/ml/IndexerClient.ts | 20 +++--------- src/data/ml/types.ts | 7 ---- src/i18n/strings/en.ts | 2 +- src/screens/BridgeScreen.tsx | 5 ++- src/screens/DexScreen.tsx | 2 +- src/trade/htlc.test.ts | 51 +++++++++++++++++++++++++---- src/trade/htlc.ts | 61 +++++++++++++++++++---------------- src/trade/orders.test.ts | 21 ++++++++---- src/trade/orders.ts | 26 +++++++++------ src/trade/priceGuards.test.ts | 4 +++ src/trade/priceGuards.ts | 5 +++ 12 files changed, 174 insertions(+), 74 deletions(-) diff --git a/plans/mojito-neo/decisions.md b/plans/mojito-neo/decisions.md index b155526..c62effe 100644 --- a/plans/mojito-neo/decisions.md +++ b/plans/mojito-neo/decisions.md @@ -55,6 +55,16 @@ with the M4 market and activity paging. The client module headers cite this entry instead of narrating callers that do not exist, and M3/M4 must consume or trim these methods when their consumers land. +M4 outcome (reconciliation): consumed in production are `feerate`, +`spendableUtxos`, `tip`, the BTC set, `orderBook` (OrderBookService), +`tokensByTicker` (ticker disambiguation) and `walkOffset` (orders and +ordersByPair). Trimmed with the M4 fix pass: `allUtxos` and `coinStatistics` +(production-dead, untested, and no remaining milestone consumer). Deferred: +`walkCursor`, the only survivor, because M4's cursor walking lives inside +OrderBookService with restart semantics of its own; the generic walker stays +test-only until a second cursor endpoint needs it, and a later milestone must +consume or delete it like the rest of this ledger. + ## D14. QR encoding uses react-native-qrcode-svg, not the spec's pure-TS encoder The M3 spec's deliverable 1 asked for a hand-rolled pure TypeScript QR encoder @@ -113,3 +123,37 @@ the account nonce with its state before the native call-through goes live on real funds, otherwise the first order transaction after a restart can sit at the wrong nonce. Recorded here as a gate condition for the call-through landing. + +### Deviations reviewed and kept (M4 change log consolidation) + +The three M4 deviations the review flagged as sound stay, consolidated +here so the code comments can cite one entry: + +- Raw claim bytes on `extractSecret`: the public Mintlayer indexer serves + no raw-transaction route, so a txId-only signature cannot honestly fetch + what the bindings extraction consumes. The lock transaction bytes are + now captured at initiate (before the broadcast) and persisted with the + swap session (`lockTxHex`); claim and refund take those bytes and feed + them to `decodeTransactionToJson`, which consumes serialized transaction + bytes, never a tx id. +- Optional `secret` on the shared `WitnessParams`: localizes the pinned + htlc-spend-only reveal field at the seam level; `encodeWitnessHtlcSpend` + is the only consumer (the M4 fix pass removed the dead secret parameter + and the unreachable spend branch from the multi-input order/HTLC signer, + so the field now rides the dedicated single-input witness paths only). +- Optional `BridgeQuote.minAmount/etaSeconds/confirmationsRequired`: + encodes the fixture-vs-bridge_v2 API divergence; the screen honors each + (null hides the row, the eta derives from confirmations). + +### Swap initiate gated in real mode (M4 change log) + +The M4 demo locked Mintlayer against the public BIP39 test vector as both +counterparty spend path and refund path. The fix pass gates real-mode +initiation with a typed unsupported error (mirroring +`BridgeProvider.initiate`) until an offer entry supplies the counterparty +spend address and key; the refund address comes from the wallet's own +address allocation; mock mode keeps the scripted demo flow with the demo +callout. The tautological timelock guard (a fabricated BTC leg derived +from the ML value) was removed from the entry path; +`checkTimelockRule` returns with real offers, taking `btcSeconds` from +the offer instead of the scripted half. diff --git a/src/data/ml/IndexerClient.ts b/src/data/ml/IndexerClient.ts index 657180c..f963272 100644 --- a/src/data/ml/IndexerClient.ts +++ b/src/data/ml/IndexerClient.ts @@ -21,7 +21,7 @@ import { TransportError as IndexerError, type FetchLike, } from '../transport'; import type { - AmountJson, CoinStats, MlAddressInfo, MlNftInfo, MlOrderCurrency, MlOrderInfo, MlOutput, MlOutpoint, + AmountJson, MlAddressInfo, MlNftInfo, MlOrderCurrency, MlOrderInfo, MlOutput, MlOutpoint, MlTokenInfo, MlTransaction, MlTransactionInput, MlUtxo, OrderBookLevel, OrderBookPage, } from './types'; @@ -101,6 +101,10 @@ export function parseAmount(raw: unknown): AmountJson { if (!Number.isSafeInteger(record.atoms) || record.atoms < 0) throw new IndexerError('parse', 'amount', undefined); out.atoms = String(record.atoms); } else if (typeof record.atoms === 'string') { + // Deliberately no digit validation here, unlike the bare-string + // form above: the book and order routes serve rational atom + // strings like '34/100' for prices, which must survive parsing + // (the money services handle the rational form downstream). out.atoms = record.atoms; } else { throw new IndexerError('parse', 'amount', undefined); @@ -288,10 +292,6 @@ export class IndexerClient { return asArray(await this.request(`/address/${encodeURIComponent(address)}/spendable-utxos`)).map(parseUtxo); } - async allUtxos(address: string): Promise { - return asArray(await this.request(`/address/${encodeURIComponent(address)}/all-utxos`)).map(parseUtxo); - } - async transaction(id: string): Promise { return parseTransaction(await this.request(`/transaction/${encodeURIComponent(id)}`)); } @@ -354,16 +354,6 @@ export class IndexerClient { return raw; } - async coinStatistics(): Promise { - const raw = asRecord(await this.request('/statistics/coin')); - return { - preminted: parseAmount(raw.preminted), - staked: parseAmount(raw.staked), - circulatingSupply: parseAmount(raw.circulating_supply), - burned: parseAmount(raw.burned), - }; - } - async orderBook(base: string, quote: string, side: OrderBookSide, cursor?: string): Promise { const query: Record = { side }; if (cursor !== undefined) query.cursor = cursor; diff --git a/src/data/ml/types.ts b/src/data/ml/types.ts index a72e786..20c6deb 100644 --- a/src/data/ml/types.ts +++ b/src/data/ml/types.ts @@ -83,13 +83,6 @@ export type MlNftInfo = { }; /** GET /statistics/coin. */ -export type CoinStats = { - preminted: AmountJson; - staked: AmountJson; - circulatingSupply: AmountJson; - burned: AmountJson; -}; - /** One currency side of an order: the base coin or a token id (F11). */ export type MlOrderCurrency = { type: 'Coin' | 'Token' | (string & {}); tokenId?: string }; diff --git a/src/i18n/strings/en.ts b/src/i18n/strings/en.ts index 71297ff..4711094 100644 --- a/src/i18n/strings/en.ts +++ b/src/i18n/strings/en.ts @@ -201,7 +201,7 @@ export const en = { 'dex.order.signingPending': 'Signing runs on the device bindings, which are pending on this build. Nothing was sent.', 'dex.order.broadcastOff': 'Order placement needs the Mintlayer submission route, which is not configured for this network (R3). Nothing was sent.', 'dex.fill.slippageWarn': 'This price has drifted {drift}% from the book mid. Review before continuing.', - 'dex.conclude.confirm': 'Conclude closes the order and returns every remaining balance to your conclude address.', + 'dex.conclude.cta': 'Conclude', 'dex.priceIndicative': 'Indicative price source (mock). Verify before trading.', 'dex.book.error': 'The live book is unreachable right now.', 'dex.order.demo': 'Demo order placed. This is simulated data, not a chain order.', diff --git a/src/screens/BridgeScreen.tsx b/src/screens/BridgeScreen.tsx index f0cfbe9..5b31f6b 100644 --- a/src/screens/BridgeScreen.tsx +++ b/src/screens/BridgeScreen.tsx @@ -43,8 +43,11 @@ export function BridgeScreen() { } }, [bridge, token, amount]); + // Debounced quote refresh: /fees and /agents-config must not refetch on + // every keystroke of the amount row. useEffect(() => { - void loadQuote(); + const timer = setTimeout(() => void loadQuote(), 500); + return () => clearTimeout(timer); }, [loadQuote]); useEffect(() => { diff --git a/src/screens/DexScreen.tsx b/src/screens/DexScreen.tsx index 31f1c10..0894f1a 100644 --- a/src/screens/DexScreen.tsx +++ b/src/screens/DexScreen.tsx @@ -517,7 +517,7 @@ function MyOrderRow({ order, onDone, onError, onFill }: { order: OrderData; onDo className="flex-1" disabled={busy} onPress={() => void run(() => orders.concludeOrder({ orderId: order.orderId }))}> - {t('dex.conclude.confirm').split(' ')[0]} + {t('dex.conclude.cta')} )} diff --git a/src/trade/htlc.test.ts b/src/trade/htlc.test.ts index 5baf3ef..2cf0625 100644 --- a/src/trade/htlc.test.ts +++ b/src/trade/htlc.test.ts @@ -32,18 +32,20 @@ type HtlcJson = { atoms: string; secret_hash: string; spend_address: string; spe * initiate; the claim and refund decodes consume bytes, never the tx id. */ const LOCK_TX_BYTES = new TextEncoder().encode('lock-tx-fixture:claim-refund-decode-input'); -function fakeBindings(htlcJson: HtlcJson): MintlayerBindings & { +function fakeBindings(htlcJson: HtlcJson, outputIndex = 0): MintlayerBindings & { witnesses: WitnessParams[]; htlcOutputs: { atoms: string; spendAddress: string; refundAddress: string; timelock: string }[]; spendWitnesses: WitnessParams[]; refundWitnesses: WitnessParams[]; extractCalls: { txId: string; outpoint: string; index: number }[]; + utxoCalls: { sourceId: string; index: number }[]; } { const witnesses: WitnessParams[] = []; const spendWitnesses: WitnessParams[] = []; const refundWitnesses: WitnessParams[] = []; const htlcOutputs: { atoms: string; spendAddress: string; refundAddress: string; timelock: string }[] = []; const extractCalls: { txId: string; outpoint: string; index: number }[] = []; + const utxoCalls: { sourceId: string; index: number }[] = []; const u32 = (value: number): Uint8Array => { const out = new Uint8Array(4); new DataView(out.buffer).setUint32(0, value, false); @@ -67,6 +69,7 @@ function fakeBindings(htlcJson: HtlcJson): MintlayerBindings & { refundWitnesses, htlcOutputs, extractCalls, + utxoCalls, async encodeOutpointSourceId(id32: Uint8Array) { return cat(u8(0x01), id32); }, @@ -74,6 +77,7 @@ function fakeBindings(htlcJson: HtlcJson): MintlayerBindings & { return utf8(`L:${totalSeconds}`); }, async encodeInputForUtxo(outpointSource: Uint8Array, index: number) { + utxoCalls.push({ sourceId: bytesToHex(outpointSource.subarray(1)), index }); return cat(u8(0x02), outpointSource, u32(index)); }, async encodeOutputTransfer(atomsStr: string, address: string) { @@ -105,7 +109,10 @@ function fakeBindings(htlcJson: HtlcJson): MintlayerBindings & { // transaction bytes; a tx-id-sized payload is always a bug. assert.notEqual(transaction.length, 32, 'decodeTransactionToJson takes transaction bytes, not a tx id'); assert.ok(transaction.length > 32, 'decodeTransactionToJson takes transaction bytes, not a tx id'); - return JSON.stringify({ outputs: [{ htlc: htlcJson }] }); + const outputs: Record[] = []; + for (let i = 0; i < outputIndex; i++) outputs.push({ transfer: {} }); + outputs.push({ htlc: htlcJson }); + return JSON.stringify({ outputs }); }, async encodeWitness(params: WitnessParams) { witnesses.push(params); @@ -132,10 +139,11 @@ function fakeBindings(htlcJson: HtlcJson): MintlayerBindings & { refundWitnesses: WitnessParams[]; htlcOutputs: { atoms: string; spendAddress: string; refundAddress: string; timelock: string }[]; extractCalls: { txId: string; outpoint: string; index: number }[]; + utxoCalls: { sourceId: string; index: number }[]; }; } -function harness(opts?: { htlcJson?: Partial; lockTimestamp?: number | null; failBroadcast?: boolean }) { +function harness(opts?: { htlcJson?: Partial; lockTimestamp?: number | null; failBroadcast?: boolean; lyingBroadcast?: string; outputIndex?: number }) { const htlcJson: HtlcJson = { atoms: atoms(2n), secret_hash: bytesToHex(SECRET_HASH), @@ -145,7 +153,7 @@ function harness(opts?: { htlcJson?: Partial; lockTimestamp?: number | refund_timelock: 172800, ...opts?.htlcJson, }; - const bindings = fakeBindings(htlcJson); + const bindings = fakeBindings(htlcJson, opts?.outputIndex ?? 0); const changeCounter = { n: 0 }; const broadcastHexes: string[] = []; const utxo = (sourceId: string, amount: string): MlUtxo => ({ @@ -154,10 +162,14 @@ function harness(opts?: { htlcJson?: Partial; lockTimestamp?: number | }); const indexer = { async transaction(id: string) { + const index = opts?.outputIndex ?? 0; + const outputs: { type: string; value: { type: string; amount: { atoms: string } } }[] = []; + for (let i = 0; i < index; i++) outputs.push({ type: 'Transfer', value: { type: 'Coin', amount: { atoms: '0' } } }); + outputs.push({ type: 'Htlc', value: { type: 'Coin', amount: { atoms: htlcJson.atoms } } }); return { id, inputs: [], - outputs: [{ type: 'Htlc', value: { type: 'Coin', amount: { atoms: htlcJson.atoms } } }], + outputs, fee: null, blockId: 'bb'.repeat(32), timestamp: opts?.lockTimestamp ?? Math.floor(Date.now() / 1000) - 10, @@ -180,7 +192,7 @@ function harness(opts?: { htlcJson?: Partial; lockTimestamp?: number | if (opts?.failBroadcast) { throw Object.assign(new Error('disabled'), { name: 'BroadcastError', failure: 'disabled' }); } - return { txId: LOCK_TX_ID }; + return { txId: opts?.lyingBroadcast ?? LOCK_TX_ID }; }, async broadcastBtc() { return { txId: LOCK_TX_ID }; @@ -291,6 +303,33 @@ async function main() { const text = new TextDecoder().decode(Buffer.from(h.broadcastHexes[0], 'hex')); assert.ok(text.includes(`S:0:${bytesToHex(SECRET)}`), 'the claim witness reveals the preimage'); assert.ok(text.includes('T:'), 'the payout output lands on the spend address'); + // The HTLC input and the fee estimate both ride the descriptor's + // output index (0 here). + assert.deepEqual(h.bindings.utxoCalls.map((c) => c.index), [0, 0]); + } + + // 3b. The fee and input estimates use the real HTLC output index, not a + // guessed slot 0. + { + const h = harness({ outputIndex: 2 }); + const result = await h.flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }); + assert.equal(result.txId, LOCK_TX_ID); + assert.deepEqual(h.bindings.utxoCalls.map((c) => c.index), [2, 2], 'the HTLC input and the fee estimate both use output index 2'); + } + + // 3c. A lying broadcast endpoint is refused: the answered id must match + // the locally computed transaction id (M3 contract). + { + const h = harness({ lyingBroadcast: 'bb'.repeat(32) }); + await assert.rejects( + () => h.flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }), + (e: unknown) => e instanceof HtlcError && e.reason === 'rejected', + ); + const refundH = harness({ lyingBroadcast: 'bb'.repeat(32), lockTimestamp: Math.floor(Date.now() / 1000) - 172_801 }); + await assert.rejects( + () => refundH.flows.refund(LOCK_TX_BYTES), + (e: unknown) => e instanceof HtlcError && e.reason === 'rejected', + ); } // 4. refund: unexpired locks refuse typed; after expiry the single-sig diff --git a/src/trade/htlc.ts b/src/trade/htlc.ts index ac8fe1b..dad1a1c 100644 --- a/src/trade/htlc.ts +++ b/src/trade/htlc.ts @@ -142,7 +142,6 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { spentOutputs: Uint8Array[], session: KeySession, inclusionHeight: number, - secret?: Uint8Array, ): Promise { return session.withSeed(async (seed) => { const { xpub } = mlXpubFromSeed(seed, cfg.network as 'mainnet' | 'testnet'); @@ -150,21 +149,17 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { for (let inputIndex = 0; inputIndex < inputs.length; inputIndex++) { const origin = await resolveOrigin(xpub, inputs[inputIndex].address); const privateKey = mlPrivateKeyFromSeed(seed, cfg.network as 'mainnet' | 'testnet', origin.branch, origin.index); - const params = { - sighashType: 'all' as const, - privateKey, - address: inputs[inputIndex].address, - transaction, - inputUtxos: spentOutputs, - inputIndex, - inclusionHeight, - network: cfg.network, - ...(secret !== undefined && inputs.length === 1 ? { secret } : {}), - }; witnesses.push( - inputs.length === 1 && secret !== undefined - ? await b().encodeWitnessHtlcSpend(params) - : await b().encodeWitness(params), + await b().encodeWitness({ + sighashType: 'all' as const, + privateKey, + address: inputs[inputIndex].address, + transaction, + inputUtxos: spentOutputs, + inputIndex, + inclusionHeight, + network: cfg.network, + }), ); } const signed = await b().encodeSignedTransaction(transaction, witnesses); @@ -183,10 +178,16 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { throw new HtlcError('rejected', 'input address does not derive from this wallet'); } - async function broadcast(signedHex: string): Promise { + /** Broadcast with the M3 id-match contract: a lying backend must not + * hand back an id that does not match the locally signed transaction. */ + async function broadcast(transaction: Uint8Array, signedHex: string): Promise { + const localTxId = await b().getTransactionId(transaction, false); try { const result = await cfg.broadcast.broadcastMl(signedHex); - return result.txId; + if (result.txId.toLowerCase() !== localTxId.toLowerCase()) { + throw new HtlcError('rejected', `broadcast answered ${result.txId}, locally signed ${localTxId}`); + } + return localTxId; } catch (e) { if (e instanceof BroadcastError && e.failure === 'disabled') throw new HtlcError('broadcast-disabled'); throw e; @@ -295,9 +296,10 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { const transaction = await b().encodeTransaction(inputs, outputs, 0); const tip = await cfg.indexer.tip(); const signedHex = await cfg.withSession((session) => sign(transaction, selection.selection, spentOutputs, session, tip.blockHeight + 1)); - const txId = await broadcast(signedHex); - // The HTLC outpoint rides the lock tx id and its output index - // (the HTLC output is assembled at index 0 of this flow). + const txId = await broadcast(transaction, signedHex); + // The HTLC outpoint rides the locally verified lock tx id and its + // output index (the HTLC output is assembled at index 0 of this + // flow), never the backend's answer. return { txId, lockTx: transaction, htlcOutpoint: { id: hexOf.decode(txId), index: 0 } }; } catch (e) { await cfg.releaseFailedChange(); @@ -310,7 +312,7 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { return serialize(async () => { if (secret.length !== 32) throw new HtlcError('rejected', 'the preimage must be 32 bytes'); const descriptor = await describeHtlc(lockTx); - const fee = await claimFee(descriptor.txId, spend.address); + const fee = await claimFee(descriptor.txId, descriptor.outputIndex, spend.address); const payout = BigInt(descriptor.atoms) - fee; if (payout <= 0n) throw new HtlcError('rejected', 'the lock cannot cover the claim fee'); const htlcInput = await utxoInput(descriptor.txId, descriptor.outputIndex); @@ -326,7 +328,7 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { const signedHex = await cfg.withSession((session) => signWithKey(transaction, spend.address, [htlcOutputBytes], session, tip.blockHeight + 1, secret, 'htlc-spend'), ); - return { txId: await broadcast(signedHex) }; + return { txId: await broadcast(transaction, signedHex) }; }); }, @@ -341,7 +343,7 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { if (lockedAt + descriptor.refundTimelock > Math.floor(Date.now() / 1000)) { throw new HtlcError('not-expired', 'the refund unlocks after the timelock expiry'); } - const fee = await claimFee(descriptor.txId, descriptor.refundAddress); + const fee = await claimFee(descriptor.txId, descriptor.outputIndex, descriptor.refundAddress); const payout = BigInt(descriptor.atoms) - fee; if (payout <= 0n) throw new HtlcError('rejected', 'the lock cannot cover the refund fee'); const htlcInput = await utxoInput(descriptor.txId, descriptor.outputIndex); @@ -355,23 +357,28 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { const signedHex = await cfg.withSession((session) => signWithKey(transaction, descriptor.refundAddress, [htlcOutputBytes], session, tip.blockHeight + 1, undefined, 'htlc-refund'), ); - return { txId: await broadcast(signedHex) }; + return { txId: await broadcast(transaction, signedHex) }; }); }, async extractSecret(rawSignedTx, htlcOutpoint) { + if (rawSignedTx.length === 0) throw new HtlcError('rejected', 'the signed claim transaction bytes are empty'); // The extraction consumes the encodeOutpointSourceId blob for the // HTLC output (the vendored docs), not the bare 32-byte id. const outpointSourceId = await b().encodeOutpointSourceId(htlcOutpoint.id, 'transaction'); + // strictByteSize=false: the input is a signed transaction whose + // witness list trails the transaction body, which strict decoding + // rejects (the vendored getTransactionId/extractHtlcSecret docs). return b().extractHtlcSecret(rawSignedTx, false, outpointSourceId, htlcOutpoint.index); }, }; /** Claim and refund build against a fee estimate of the same shape: one - * HTLC input, one payout output, standard tier rate. */ - async function claimFee(htlcTxId: string, destination: string): Promise { + * HTLC input, one payout output, standard tier rate. The estimate uses + * the real HTLC output index, not a guessed slot. */ + async function claimFee(htlcTxId: string, outputIndex: number, destination: string): Promise { const rate = await cfg.indexer.feerate(STANDARD_TIER_IN_TOP_MB); - const input = await utxoInput(htlcTxId, 0); + const input = await utxoInput(htlcTxId, outputIndex); const output = await b().encodeOutputTransfer('0', destination, cfg.network); const size = await b().estimateTransactionSize([input], [destination], [output], cfg.network); const kbCeil = BigInt(Math.max(1, Math.ceil(size / 1000))); diff --git a/src/trade/orders.test.ts b/src/trade/orders.test.ts index 9162f51..3c72e4f 100644 --- a/src/trade/orders.test.ts +++ b/src/trade/orders.test.ts @@ -117,7 +117,10 @@ function fakeBindings(): MintlayerBindings & { }, async encodeWitnessNoSignature() { noSignatureCalls += 1; - return u8(0x00); + // Text marker like the other fake witnesses, so the echo broadcaster + // can find the witness boundary (a bare 0x00 byte would be ambiguous + // with the u32 index bytes inside the inputs). + return utf8('N:0'); }, async encodeSignedTransaction(transaction: Uint8Array, txWitnesses: Uint8Array[]) { return cat(transaction, ...txWitnesses); @@ -196,15 +199,19 @@ function harness(opts?: { orders?: OrderRow[]; detail?: OrderRow; utxos?: MlUtxo }; /** Echo broadcaster: answers the locally computed id like a well-behaved * backend. The fake signed layout is transaction bytes followed by the - * utf8 witness blobs, so the first 'W:' run marks the boundary. */ + * utf8 witness blobs ('N:0' for the unsigned order input, 'W:i' for + * payer inputs), and the transaction body never contains 'W:' or 'N:', + * so the first occurrence of either marks the boundary. */ const localIdOf = (signedHex: string): string => { const bytes = Buffer.from(signedHex, 'hex'); - const marker = Buffer.from('W:'); + const markers = [Buffer.from('W:'), Buffer.from('N:')]; let end = bytes.length; - for (let i = 0; i + 1 < bytes.length; i++) { - if (bytes[i] === marker[0] && bytes[i + 1] === marker[1] && bytes[i + 2] === 0x30) { - end = i; - break; + for (const marker of markers) { + for (let i = 0; i + 1 < bytes.length; i++) { + if (bytes[i] === marker[0] && bytes[i + 1] === marker[1]) { + end = Math.min(end, i); + break; + } } } return bytesToHex(sha256(new Uint8Array(bytes.subarray(0, end)))); diff --git a/src/trade/orders.ts b/src/trade/orders.ts index 20f7a2e..dc1f085 100644 --- a/src/trade/orders.ts +++ b/src/trade/orders.ts @@ -461,9 +461,7 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { } const noSignature = await b().encodeWitnessNoSignature(); - const signedHex = await finishTx(inputs, outputs, selection.selection, new Map([[0, noSignature]])); - const result = await cfg.broadcast.broadcastMl(signedHex); - return { txId: result.txId }; + return { txId: await finishTx(inputs, outputs, selection.selection, new Map([[0, noSignature]])) }; } catch (e) { await cfg.releaseFailedChange(); throw e; @@ -533,9 +531,7 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { } const noSignature = await b().encodeWitnessNoSignature(); - const signedHex = await finishTx(inputs, outputs, selection.selection, new Map([[0, noSignature]])); - const result = await cfg.broadcast.broadcastMl(signedHex); - return { txId: result.txId }; + return { txId: await finishTx(inputs, outputs, selection.selection, new Map([[0, noSignature]])) }; } catch (e) { await cfg.releaseFailedChange(); throw e; @@ -555,8 +551,9 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { }, }; - /** Sign-and-broadcast variant returning only the signed hex (fill and - * conclude carry no bindings id extraction). */ + /** Sign-and-broadcast variant for fill and conclude: same broadcast-id + * honesty contract as finish (a lying backend must not hand back an id + * that does not match the locally signed transaction). */ async function finishTx( inputs: Uint8Array[], outputs: Uint8Array[], @@ -564,8 +561,19 @@ export function createOrderFlows(cfg: OrderFlowsConfig): OrderFlows { prebuiltWitnesses: Map, ): Promise { const transaction = await b().encodeTransaction(inputs, outputs, 0); + const localTxId = await b().getTransactionId(transaction, false); const tip = await cfg.indexer.tip(); - return cfg.withSession((session) => sign(transaction, payerInputs, prebuiltWitnesses, session, tip.blockHeight + 1)); + const signedHex = await cfg.withSession((session) => sign(transaction, payerInputs, prebuiltWitnesses, session, tip.blockHeight + 1)); + const result = await cfg.broadcast.broadcastMl(signedHex).catch((e: unknown) => { + if (e instanceof BroadcastError && e.failure === 'disabled') { + throw new OrderFlowError('broadcast-disabled'); + } + throw e; + }); + if (result.txId.toLowerCase() !== localTxId.toLowerCase()) { + throw new OrderFlowError('rejected', `broadcast answered ${result.txId}, locally signed ${localTxId}`); + } + return localTxId; } } diff --git a/src/trade/priceGuards.test.ts b/src/trade/priceGuards.test.ts index caa79e9..7fe91e0 100644 --- a/src/trade/priceGuards.test.ts +++ b/src/trade/priceGuards.test.ts @@ -25,6 +25,10 @@ async function main() { assert.deepEqual(checkSlippage({ limitDecimal: '0.3622', midDecimal: '0.3450', maxSlippagePct: 5 }), { ok: true }); assert.equal(reason(checkSlippage({ limitDecimal: 'x', midDecimal: '0.345', maxSlippagePct: 1 })), 'slippage'); assert.equal(reason(checkSlippage({ limitDecimal: '1', midDecimal: '0', maxSlippagePct: 1 })), 'slippage'); + // A NaN band answers the typed guard result instead of crashing on + // BigInt(Math.round(NaN)). + assert.equal(reason(checkSlippage({ limitDecimal: '0.345', midDecimal: '0.345', maxSlippagePct: Number.NaN })), 'slippage'); + assert.deepEqual(checkSlippage({ limitDecimal: '0.345', midDecimal: '0.345', maxSlippagePct: Number.NaN }).ok, false); // Minimum fill: below the floor rejects, at the floor passes. assert.deepEqual(checkMinFill({ amountDecimal: '10', minDecimal: '5' }), { ok: true }); diff --git a/src/trade/priceGuards.ts b/src/trade/priceGuards.ts index 7457a61..cf3874a 100644 --- a/src/trade/priceGuards.ts +++ b/src/trade/priceGuards.ts @@ -38,6 +38,11 @@ export function checkAmounts(params: { giveDecimal: string; askDecimal: string } * limit must sit within maxSlippagePct of the mid in either direction; a * crossed or far-off price rejects before any transaction is built. */ export function checkSlippage(params: { limitDecimal: string; midDecimal: string; maxSlippagePct: number }): GuardResult { + // NaN maxSlippagePct would crash BigInt(Math.round(NaN)) with a + // RangeError below; the guard contract is a typed result, never a throw. + if (!Number.isFinite(params.maxSlippagePct)) { + return { ok: false, reason: 'slippage', detail: 'the slippage band is not a finite number' }; + } let limit: bigint; let mid: bigint; try { From 568b6442cf3e299b7d43885d11d584afb2372930 Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 08:21:32 +0100 Subject: [PATCH 14/20] fix(m4): persist swap lock bytes before the broadcast --- plans/mojito-neo/decisions.md | 17 +++++++ src/data/mock/mockTrade.ts | 21 ++++++-- src/data/providers/providers.test.ts | 13 +++-- src/i18n/strings/en.ts | 1 + src/screens/SwapScreen.tsx | 54 ++++++++++++++------ src/trade/htlc.test.ts | 71 ++++++++++++++++++-------- src/trade/htlc.ts | 75 ++++++++++++++++++++++------ src/trade/swapSession.test.ts | 26 +++++++++- src/trade/swapSession.ts | 23 ++++++--- 9 files changed, 231 insertions(+), 70 deletions(-) diff --git a/plans/mojito-neo/decisions.md b/plans/mojito-neo/decisions.md index c62effe..360845e 100644 --- a/plans/mojito-neo/decisions.md +++ b/plans/mojito-neo/decisions.md @@ -157,3 +157,20 @@ callout. The tautological timelock guard (a fabricated BTC leg derived from the ML value) was removed from the entry path; `checkTimelockRule` returns with real offers, taking `btcSeconds` from the offer instead of the scripted half. + +### Swap initiate split so the lock bytes rest before the broadcast (M4 fix) + +`initiate` now only builds and signs the lock transaction (locally +computed tx id, unsigned bytes, signed hex); `broadcastLock` is the +second half and verifies the answered id against the locally computed +one. The swap screen persists the session row (state 'offered', +`lockTxHex` set) between the two calls, so a crash after the broadcast +still leaves the bytes the claim and refund decodes consume, and the +offered -> locked transition fires only after the broadcast answers. +The transition table now also allows offered -> refunded: an 'offered' +row whose post-broadcast save failed still refunds from its stored +bytes, and a failed save maps to an explicit funds-locked error naming +the tx id (the generic nothing-sent copy would invite a second lock). +The retired spend pubkey column is dropped with the split: the vendored +`encodeOutputHtlc` carries no spend pubkey, the decoded descriptor never +read one, and the screen no longer fabricates a 33-byte key to persist. diff --git a/src/data/mock/mockTrade.ts b/src/data/mock/mockTrade.ts index 9cdc842..1843ce3 100644 --- a/src/data/mock/mockTrade.ts +++ b/src/data/mock/mockTrade.ts @@ -5,11 +5,12 @@ // demo-data chip stays visible in mock mode, spec M4 honesty rules). import { ASKS, BIDS } from '../../data'; import { bytesToHex } from '@noble/hashes/utils.js'; +import { hex as hexOf } from '@scure/base'; import type { NetworkFlag } from '../../config/endpoints'; import type { BroadcastProvider } from '../providers/types'; import { DEFAULT_BOOK_DEPTH, type BookRow, type OrderBookService } from '../../trade/OrderBookService'; import { COIN_REF, type OrderData, type OrderFlows } from '../../trade/orders'; -import type { HtlcFlows, HtlcOffer, HtlcSpend } from '../../trade/htlc'; +import type { HtlcFlows, HtlcOffer, HtlcSpend, PreparedLock } from '../../trade/htlc'; import { createSwapSessionStore, type SwapSessionStorage, type SwapSessionStore } from '../../trade/swapSession'; /** Fixture book mapped onto the live-service row shape, so the DexScreen @@ -109,7 +110,9 @@ export function createMockOrderFlows(cfg: { broadcast: BroadcastProvider; networ let orderIdSeedCounter = 0; /** Demo HTLC flows: the swap session demo walks lock/claim/refund on the - * mock broadcaster with deterministic fake tx ids. */ + * mock broadcaster with deterministic fake tx ids, split like the real + * seam (initiate builds the bytes, broadcastLock sends them, so the demo + * exercises the same offered -> locked session machine). */ export function createMockHtlcFlows(cfg: { broadcast: BroadcastProvider }): HtlcFlows { return { async initiate(offer: HtlcOffer, spend: HtlcSpend, refundAddress: string) { @@ -117,11 +120,19 @@ export function createMockHtlcFlows(cfg: { broadcast: BroadcastProvider }): Htlc void refundAddress; requireAtomAmount(offer.giveAtoms, 'give'); if (offer.secretHash.length !== 32) throw new Error('the secret hash must be 32 bytes'); - const { txId } = await cfg.broadcast.broadcastMl(fakeId(`htlc-lock:${offer.giveAtoms}`)); // Demo lock bytes: the session persists them so the claim/refund - // signatures match the real seam (the demo decode is a no-op). + // signatures match the real seam (the demo decode is a no-op). No + // broadcast here: the bytes must rest in the session row before the + // broadcast half runs. const lockTx = new Uint8Array(64).fill(0x1c); - return { txId, lockTx, htlcOutpoint: { id: new Uint8Array(32).fill(0x0a), index: 0 } }; + const txId = fakeId(`htlc-lock:${offer.giveAtoms}`); + return { txId, lockTx, signedLockHex: bytesToHex(lockTx), htlcOutpoint: { id: hexOf.decode(txId), index: 0 } }; + }, + async broadcastLock(prepared: PreparedLock) { + await cfg.broadcast.broadcastMl(prepared.signedLockHex); + // The demo lock tx id is stable across both steps, exactly like the + // real seam's locally computed id. + return { txId: prepared.txId }; }, async claim(lockTx: Uint8Array, secret: Uint8Array) { void lockTx; diff --git a/src/data/providers/providers.test.ts b/src/data/providers/providers.test.ts index 7b642d8..1d21432 100644 --- a/src/data/providers/providers.test.ts +++ b/src/data/providers/providers.test.ts @@ -5,6 +5,8 @@ // npx tsx src/data/providers/providers.test.ts import { strict as assert } from 'node:assert/strict'; +import { bytesToHex } from '@noble/hashes/utils.js'; + import { createProviders, readDataMode } from './index'; import { setNetwork } from '../../config/endpoints'; import { BALANCE } from '../../data'; @@ -77,19 +79,24 @@ async function main() { assert.deepEqual((await providers.orders.myOrders()).map((o) => o.orderId), [demoOrder.orderId]); const demoLock = await providers.htlc.initiate( { role: 'initiator', giveChain: 'ml', giveAtoms: '1000', wantAtoms: '280000', secretHash: new Uint8Array(32).fill(7), timelockSeconds: 172800 }, - { address: 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl', pubkey: new Uint8Array(33) }, + { address: 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl' }, 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl', ); assert.equal(demoLock.htlcOutpoint.index, 0); + assert.equal(demoLock.lockTx.length, 64, 'the demo lock answers the same bytes shape as the real seam'); + // Split contract: broadcastLock is the second half, after the session + // row would have the bytes at rest (the demo follows the screen flow). + const demoBroadcast = await providers.htlc.broadcastLock(demoLock); + assert.equal(demoBroadcast.txId, demoLock.txId); await providers.swapSessions.save({ id: demoLock.txId, offer: { role: 'initiator', giveChain: 'ml', giveAtoms: '1000', wantAtoms: '280000', secretHash: new Uint8Array(32).fill(7), timelockSeconds: 172800 }, secretHashHex: '07'.repeat(32), spendAddress: 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl', - spendPubkeyHex: '', refundAddress: 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl', + lockTxHex: bytesToHex(demoLock.lockTx), state: 'locked', - txIds: [demoLock.txId], + txIds: [demoBroadcast.txId], updatedAt: Date.now(), }); assert.equal((await providers.swapSessions.all()).length, 1); diff --git a/src/i18n/strings/en.ts b/src/i18n/strings/en.ts index 4711094..57b7030 100644 --- a/src/i18n/strings/en.ts +++ b/src/i18n/strings/en.ts @@ -243,6 +243,7 @@ export const en = { 'swap.state.expired': 'Expired', 'swap.warn.keepOpen': 'Keep this screen open until settlement: the preimage lives only in memory. Losing it forfeits the swap (the refund path still works).', 'swap.error.generic': 'The swap action failed. Nothing was sent.', + 'swap.error.lockedRecord': 'The lock broadcast succeeded (tx {txId}) and the funds are locked, but saving the session failed. The saved session can still refund after the timelock. Do not start a second lock.', 'swap.real.unavailable': 'Real swaps need a counterparty offer with its own spend path. Offer entry is not available in this build, so locking is disabled. Existing sessions can still refund.', 'swap.refund.cta': 'Refund after timelock', 'swap.session.empty': 'No swap sessions yet. Initiate one to see the live protocol steps.', diff --git a/src/screens/SwapScreen.tsx b/src/screens/SwapScreen.tsx index a26425f..ecb4746 100644 --- a/src/screens/SwapScreen.tsx +++ b/src/screens/SwapScreen.tsx @@ -9,7 +9,7 @@ import { useProviders } from '../data/providers/context'; import { fnv1a } from '../data/mock/hash'; import { MojitoCore } from '../../modules/mojito-core'; import { isBindingsUnavailable } from '../send/errors'; -import type { SwapSessionRow, SwapState } from '../trade/swapSession'; +import { assertTransition, type SwapSessionRow, type SwapState } from '../trade/swapSession'; import type { StepState } from '../ui/StepState'; import { C, G } from '../theme'; import { AmountRow, Btn, Callout, Card, FlowX, Label, PctButtons, Screen, ScreenIntro, Segmented, Steps, Txt } from '../ui'; @@ -57,10 +57,14 @@ export function SwapScreen() { void loadSessions(); }, [loadSessions]); - /** Lock Mintlayer: secret generated off-band, only the hash crosses the - * wire; the session persists with the hash, the lock tx bytes and the - * tx ids. The refund path is a wallet-owned address and the spend path - * is the demo vector in mock mode; real mode refuses typed. */ + /** Lock Mintlayer in two steps: initiate builds and signs (no + * broadcast), the session row persists the lock tx bytes at state + * 'offered', then broadcastLock sends the prepared transaction and the + * row transitions offered -> locked. The bytes-at-rest-before-broadcast + * order is the point: a crash after the broadcast still leaves the + * refund leg's decode input. The refund path is a wallet-owned address + * and the spend path is the demo vector in mock mode; real mode refuses + * typed. */ const initiate = async () => { setError(null); if (mode === 'real') { @@ -78,7 +82,7 @@ export function SwapScreen() { const secret = await swapSecret(mode); const secretHash = sha256(secret); preimageRef.current = secret; - const { txId, lockTx } = await htlc.initiate( + const prepared = await htlc.initiate( { role: 'initiator', giveChain: 'ml', @@ -87,21 +91,36 @@ export function SwapScreen() { secretHash, timelockSeconds: mlSeconds, }, - { address: COUNTERPARTY_ADDRESS, pubkey: new Uint8Array(33).fill(0x02) }, + { address: COUNTERPARTY_ADDRESS }, refundAddress, ); - await swapSessions.save({ - id: txId, + const row: SwapSessionRow = { + id: prepared.txId, offer: { role: 'initiator', giveChain: 'ml', giveAtoms: toAtoms(amount), wantAtoms: wantAtomsOf(amount), secretHash, timelockSeconds: mlSeconds }, secretHashHex: bytesToHex(secretHash), spendAddress: COUNTERPARTY_ADDRESS, - spendPubkeyHex: '02'.repeat(33), refundAddress, - lockTxHex: bytesToHex(lockTx), - state: 'locked', - txIds: [txId], + lockTxHex: bytesToHex(prepared.lockTx), + state: 'offered', + txIds: [], updatedAt: Date.now(), - }); + }; + // Bytes at rest BEFORE the broadcast: the row (with the lock tx + // bytes) is stored first, so the honest refund source survives a + // crash that happens after the broadcast. + await swapSessions.save(row); + const { txId } = await htlc.broadcastLock(prepared); + assertTransition(row.state, 'locked'); + try { + await swapSessions.save({ ...row, state: 'locked', txIds: [txId], updatedAt: Date.now() }); + } catch { + // The lock IS on-chain: the generic nothing-sent copy would invite + // a second lock. Name the tx id; the offered row keeps the bytes, + // so the refund path stays available. + setError(t('swap.error.lockedRecord', { txId: prepared.txId })); + void loadSessions(); + return; + } void loadSessions(); } catch (e) { setError(swapErrorCopy(e)); @@ -116,8 +135,11 @@ export function SwapScreen() { try { // The refund rebuilds the lock parameters from the locally captured // unsigned lock transaction bytes (the decode seam consumes bytes, - // not the tx id); rows without them cannot refund honestly. + // not the tx id); rows without them cannot refund honestly. An + // 'offered' row whose post-broadcast save failed refunds from the + // same bytes, hence offered -> refunded in the machine. if (!session.lockTxHex) throw new SwapGateError('stored session predates the lock tx bytes record'); + assertTransition(session.state, 'refunded'); const { txId } = await htlc.refund(hexOf.decode(session.lockTxHex)); await swapSessions.save({ ...session, state: 'refunded', txIds: [...session.txIds, txId].slice(0, 16), updatedAt: Date.now() }); void loadSessions(); @@ -205,7 +227,7 @@ export function SwapScreen() { - {session.state === 'locked' && ( + {session.lockTxHex && (session.state === 'offered' || session.state === 'locked') && ( void refund(session)}> {t('swap.refund.cta')} diff --git a/src/trade/htlc.test.ts b/src/trade/htlc.test.ts index 2cf0625..c081f20 100644 --- a/src/trade/htlc.test.ts +++ b/src/trade/htlc.test.ts @@ -24,9 +24,7 @@ const atoms = (ml: bigint): string => (ml * ML).toString(); const SECRET = new Uint8Array(32).fill(0x42); const SECRET_HASH = secretHashOf(SECRET); const LOCK_TX_ID = 'aa'.repeat(32); -const SPEND_PUBKEY = new Uint8Array(33).fill(0x02); - -type HtlcJson = { atoms: string; secret_hash: string; spend_address: string; spend_pubkey: string; refund_address: string; refund_timelock: number }; +type HtlcJson = { atoms: string; secret_hash: string; spend_address: string; refund_address: string; refund_timelock: number }; /** The unsigned lock transaction bytes as the flows return them from * initiate; the claim and refund decodes consume bytes, never the tx id. */ @@ -148,7 +146,6 @@ function harness(opts?: { htlcJson?: Partial; lockTimestamp?: number | atoms: atoms(2n), secret_hash: bytesToHex(SECRET_HASH), spend_address: VECTOR_ADDRESS, - spend_pubkey: bytesToHex(SPEND_PUBKEY), refund_address: VECTOR_ADDRESS, refund_timelock: 172800, ...opts?.htlcJson, @@ -231,20 +228,23 @@ async function main() { // TIMELOCK_RULE is the recorded F10 string. assert.equal(TIMELOCK_RULE, 'btc timelock must be shorter than the mintlayer timelock (F10)'); - // 1. initiate: the lock output encodes the F10 parameters through the - // vendored shape (hex hash, encodeLockForSeconds blob), the signed - // lock tx broadcasts and the flow returns the unsigned bytes. + // 1. initiate is the build+sign half only: the lock output encodes the + // F10 parameters through the vendored shape (hex hash, + // encodeLockForSeconds blob), the flow answers the unsigned bytes and + // the locally computed id WITHOUT broadcasting; broadcastLock is the + // second half, after the caller has the bytes at rest. { const h = harness(); - const result = await h.flows.initiate( + const prepared = await h.flows.initiate( { role: 'initiator', giveChain: 'ml', giveAtoms: atoms(2n), wantAtoms: atoms(560n), secretHash: SECRET_HASH, timelockSeconds: 172800 }, - { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }, + { address: VECTOR_ADDRESS }, VECTOR_ADDRESS, ); - assert.equal(result.txId, LOCK_TX_ID); - assert.ok(result.lockTx.length > 32, 'initiate returns the unsigned lock tx bytes for the session record'); - assert.deepEqual(result.htlcOutpoint.id, hexOf.decode(LOCK_TX_ID)); - assert.equal(result.htlcOutpoint.index, 0); + assert.equal(prepared.txId, LOCK_TX_ID); + assert.ok(prepared.lockTx.length > 32, 'initiate returns the unsigned lock tx bytes for the session record'); + assert.ok(prepared.signedLockHex.length > 0, 'broadcastLock receives the signed lock hex'); + assert.deepEqual(prepared.htlcOutpoint.id, hexOf.decode(LOCK_TX_ID)); + assert.equal(prepared.htlcOutpoint.index, 0); // The final (real-build) HTLC output encoding carries the lock params // in the vendored shape: atoms, addresses and the seconds lock blob. const lock = h.bindings.htlcOutputs[h.bindings.htlcOutputs.length - 1]; @@ -256,7 +256,35 @@ async function main() { assert.equal(h.bindings.witnesses.length, 1); assert.equal(bytesToHex(h.bindings.witnesses[0].privateKey), expectedKey); assert.equal(h.bindings.witnesses[0].secret, undefined); + // Bytes at rest BEFORE broadcast: nothing left the wallet yet, so the + // session row can be persisted between the two steps. + assert.equal(h.broadcastHexes.length, 0, 'initiate must not broadcast'); + // The broadcast half rides the same prepared transaction; the session + // transitions offered -> locked only after this answers. + const broadcast = await h.flows.broadcastLock(prepared); + assert.equal(broadcast.txId, LOCK_TX_ID); assert.equal(h.broadcastHexes.length, 1); + assert.ok( + Buffer.from(h.broadcastHexes[0], 'hex').subarray(0, prepared.lockTx.length).equals(Buffer.from(prepared.lockTx)), + 'the broadcast carries the prepared lock transaction', + ); + } + + // 1b. A lying broadcast endpoint is refused on the lock leg too (M3 + // contract), and the failed broadcast releases the change allocation. + { + const h = harness({ lyingBroadcast: 'bb'.repeat(32) }); + const prepared = await h.flows.initiate( + { role: 'initiator', giveChain: 'ml', giveAtoms: atoms(2n), wantAtoms: atoms(560n), secretHash: SECRET_HASH, timelockSeconds: 172800 }, + { address: VECTOR_ADDRESS }, + VECTOR_ADDRESS, + ); + await assert.rejects( + () => h.flows.broadcastLock(prepared), + (e: unknown) => e instanceof HtlcError && e.reason === 'rejected', + ); + assert.equal(h.broadcastHexes.length, 1, 'the lying answer still reached the broadcaster'); + assert.equal(h.changeCounter.n, 0, 'the failed broadcast releases the change allocation'); } // 2. Guard rails: bad hash length, zero amounts and busy serialization. @@ -266,7 +294,7 @@ async function main() { () => h.flows.initiate( { role: 'initiator', giveChain: 'ml', giveAtoms: atoms(1n), wantAtoms: '1', secretHash: SECRET_HASH.subarray(0, 16), timelockSeconds: 3600 }, - { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }, + { address: VECTOR_ADDRESS }, VECTOR_ADDRESS, ), (e: unknown) => e instanceof HtlcError && e.reason === 'rejected', @@ -274,14 +302,14 @@ async function main() { await assert.rejects( () => h.flows.initiate( { role: 'initiator', giveChain: 'ml', giveAtoms: '0', wantAtoms: '1', secretHash: SECRET_HASH, timelockSeconds: 3600 }, - { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }, + { address: VECTOR_ADDRESS }, VECTOR_ADDRESS, ), (e: unknown) => e instanceof HtlcError && e.reason === 'rejected', ); - const first = h.flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }); + const first = h.flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS }); await assert.rejects( - () => h.flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }), + () => h.flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS }), (e: unknown) => e instanceof HtlcError && e.reason === 'busy', ); await first; @@ -291,7 +319,7 @@ async function main() { // re-encoded HTLC output; the decode consumes the lock tx bytes. { const h = harness(); - const result = await h.flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }); + const result = await h.flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS }); assert.equal(result.txId, LOCK_TX_ID); assert.equal(h.bindings.spendWitnesses.length, 1); const witness = h.bindings.spendWitnesses[0]; @@ -312,7 +340,7 @@ async function main() { // guessed slot 0. { const h = harness({ outputIndex: 2 }); - const result = await h.flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }); + const result = await h.flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS }); assert.equal(result.txId, LOCK_TX_ID); assert.deepEqual(h.bindings.utxoCalls.map((c) => c.index), [2, 2], 'the HTLC input and the fee estimate both use output index 2'); } @@ -322,7 +350,7 @@ async function main() { { const h = harness({ lyingBroadcast: 'bb'.repeat(32) }); await assert.rejects( - () => h.flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }), + () => h.flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS }), (e: unknown) => e instanceof HtlcError && e.reason === 'rejected', ); const refundH = harness({ lyingBroadcast: 'bb'.repeat(32), lockTimestamp: Math.floor(Date.now() / 1000) - 172_801 }); @@ -366,7 +394,6 @@ async function main() { atoms: atoms(2n), secret_hash: bytesToHex(SECRET_HASH), spend_address: VECTOR_ADDRESS, - spend_pubkey: bytesToHex(SPEND_PUBKEY), refund_address: VECTOR_ADDRESS, refund_timelock: 172800, }); @@ -400,7 +427,7 @@ async function main() { withSession: async (fn) => fn({ withSeed: (run: (s: Uint8Array) => Promise) => run(seed) } as unknown as KeySession), }); await assert.rejects( - () => flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS, pubkey: SPEND_PUBKEY }), + () => flows.claim(LOCK_TX_BYTES, SECRET, { address: VECTOR_ADDRESS }), (e: unknown) => e instanceof HtlcError && e.reason === 'no-htlc-output', ); } diff --git a/src/trade/htlc.ts b/src/trade/htlc.ts index dad1a1c..13c88b6 100644 --- a/src/trade/htlc.ts +++ b/src/trade/htlc.ts @@ -8,8 +8,10 @@ // Secret handling (spec security note): the preimage is generated with // MojitoCore.secureRandom by the caller (createSwapSecret), held in memory // inside the session closure and never persisted and never logged; only -// SHA-256(secret) crosses the wire and storage. TIMELOCK_RULE guards the -// initiate path: the BTC timelock must be shorter than the ML one. +// SHA-256(secret) crosses the wire and storage. TIMELOCK_RULE records the +// F10 ordering (the BTC timelock must be shorter than the ML one); the +// guard call returns with real offer entry, which supplies the BTC leg +// the demo path had to fabricate (plans/mojito-neo/decisions.md). // // Honest states: every transaction assembles and signs through the // MintlayerBindings seam, so without the native call-through the flows @@ -41,15 +43,40 @@ export type HtlcOffer = { timelockSeconds: number; }; -export type HtlcSpend = { address: string; pubkey: Uint8Array }; +/** Counterparty spend path (the address only: the vendored + * encodeOutputHtlc carries no spend pubkey, so a key here would be a + * fabricated field no consumer reads). */ +export type HtlcSpend = { address: string }; + +/** The signed-but-unbroadcast lock transaction as initiate answers it: the + * opaque carrier between the build+sign and broadcast steps. The caller + * persists lockTx with the swap session (state 'offered') between the two + * steps, so the bytes are at rest before anything leaves the wallet. */ +export type PreparedLock = { + /** Locally computed lock transaction id (the HTLC outpoint id). */ + txId: string; + /** Unsigned lock transaction bytes: the claim and refund decodes + * consume them, and the session record must persist them. */ + lockTx: Uint8Array; + /** Signed lock transaction hex for broadcastLock. */ + signedLockHex: string; + htlcOutpoint: { id: Uint8Array; index: number }; +}; export interface HtlcFlows { - /** Lock the offer's giveAtoms on Mintlayer with the counterparty's spend - * key and our refund path (the initiator leg of the swap). Returns the - * unsigned lock transaction bytes: the claim and refund decodes consume - * them, because the public Mintlayer indexer serves no raw transaction - * route, so the caller must persist them with the swap session. */ - initiate(offer: HtlcOffer, spend: HtlcSpend, refundAddress: string): Promise<{ txId: string; lockTx: Uint8Array; htlcOutpoint: { id: Uint8Array; index: number } }>; + /** Build and sign the lock transaction WITHOUT broadcasting (the first + * half of the initiate contract): the answer carries the unsigned lock + * bytes, the locally computed tx id and the signed hex for + * broadcastLock. The claim and refund decodes consume the bytes, + * because the public Mintlayer indexer serves no raw transaction route, + * so the caller MUST persist them with the swap session (state + * 'offered') before calling broadcastLock: bytes at rest before the + * broadcast, or a crash after it strands the refund leg. */ + initiate(offer: HtlcOffer, spend: HtlcSpend, refundAddress: string): Promise; + /** Broadcast the prepared lock (the second half): verifies the answered + * id against the locally computed one (M3 contract) and returns it. The + * caller transitions the session offered -> locked on success. */ + broadcastLock(prepared: PreparedLock): Promise<{ txId: string }>; /** Spend an HTLC with the revealed secret (the counterparty claim leg). * lockTx carries the unsigned lock transaction bytes captured at * initiate (not the tx id: the bindings decode consumes bytes). */ @@ -98,7 +125,6 @@ export type HtlcDescriptor = { atoms: string; secretHash: Uint8Array; spendAddress: string; - spendPubkey: Uint8Array; refundAddress: string; refundTimelock: number; }; @@ -213,7 +239,7 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { if (outputIndex < 0) throw new HtlcError('no-htlc-output', `transaction ${htlcTxId} carries no HTLC output`); const json = await b().decodeTransactionToJson(lockTx, cfg.network); const parsed = JSON.parse(json) as { - outputs?: { htlc?: { atoms?: string; secret_hash?: string; spend_address?: string; spend_pubkey?: string; refund_address?: string; refund_timelock?: number } }[]; + outputs?: { htlc?: { atoms?: string; secret_hash?: string; spend_address?: string; refund_address?: string; refund_timelock?: number } }[]; }; const htlc = parsed.outputs?.[outputIndex]?.htlc; if (!htlc?.atoms || htlc.secret_hash === undefined || htlc.spend_address === undefined) { @@ -225,7 +251,6 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { atoms: htlc.atoms, secretHash: hexOf.decode(htlc.secret_hash), spendAddress: htlc.spend_address, - spendPubkey: hexOf.decode(htlc.spend_pubkey ?? ''), refundAddress: htlc.refund_address ?? '', refundTimelock: htlc.refund_timelock ?? 0, }; @@ -296,12 +321,32 @@ export function createHtlcFlows(cfg: HtlcFlowsConfig): HtlcFlows { const transaction = await b().encodeTransaction(inputs, outputs, 0); const tip = await cfg.indexer.tip(); const signedHex = await cfg.withSession((session) => sign(transaction, selection.selection, spentOutputs, session, tip.blockHeight + 1)); - const txId = await broadcast(transaction, signedHex); - // The HTLC outpoint rides the locally verified lock tx id and its + // First half only: the tx id is computed locally (the same + // getTransactionId the broadcast step verifies against) and the + // broadcast waits for broadcastLock, after the caller has the + // lock bytes at rest in the session record. + const txId = await b().getTransactionId(transaction, false); + // The HTLC outpoint rides the locally computed lock tx id and its // output index (the HTLC output is assembled at index 0 of this // flow), never the backend's answer. - return { txId, lockTx: transaction, htlcOutpoint: { id: hexOf.decode(txId), index: 0 } }; + return { txId, lockTx: transaction, signedLockHex: signedHex, htlcOutpoint: { id: hexOf.decode(txId), index: 0 } }; + } catch (e) { + await cfg.releaseFailedChange(); + throw e; + } + }); + }, + + async broadcastLock(prepared) { + return serialize(async () => { + if (prepared.lockTx.length === 0 || prepared.signedLockHex.length === 0) { + throw new HtlcError('rejected', 'the prepared lock carries no transaction'); + } + try { + return { txId: await broadcast(prepared.lockTx, prepared.signedLockHex) }; } catch (e) { + // A refused broadcast never spent the inputs: the change + // allocation steps back like any failed attempt. await cfg.releaseFailedChange(); throw e; } diff --git a/src/trade/swapSession.test.ts b/src/trade/swapSession.test.ts index 5fc8a93..5c850ae 100644 --- a/src/trade/swapSession.test.ts +++ b/src/trade/swapSession.test.ts @@ -23,7 +23,6 @@ const row = (overrides?: Partial): SwapSessionRow => ({ offer: OFFER, secretHashHex: bytesToHex(new Uint8Array(32).fill(0x21)), spendAddress: 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl', - spendPubkeyHex: '02'.repeat(33), refundAddress: 'mtc1q82twmwwxa3l2pe26gf0zgghu69jtez3qq2ajqyl', lockTxHex: 'ee0102ff01', state: 'offered', @@ -51,6 +50,7 @@ function memoryStorage() { async function main() { // Transition table: the happy path and the honest alternates. assert.ok(canTransition('offered', 'locked')); + assert.ok(canTransition('offered', 'refunded'), 'a stranded offered row refunds from its stored lock bytes'); assert.ok(canTransition('locked', 'claiming')); assert.ok(canTransition('locked', 'refunded')); assert.ok(canTransition('locked', 'expired')); @@ -60,6 +60,22 @@ async function main() { assert.ok(!canTransition('settled', 'claiming'), 'terminal states are terminal'); assert.throws(() => assertTransition('expired', 'locked'), /invalid swap transition/); + // The screen's split initiate: the offered row carries the lock bytes + // BEFORE any broadcast, then transitions offered -> locked on the + // broadcast answer, and the bytes rest through the transition. + { + const backend = memoryStorage(); + const store = createSwapSessionStore(backend.storage); + const offered = row({ state: 'offered', lockTxHex: 'ee0102ff01' }); + await store.save(offered); + assert.equal(JSON.parse(backend.json() ?? '[]')[0].state, 'offered', 'the offered row with the lock bytes is at rest'); + assertTransition(offered.state, 'locked'); + await store.save({ ...offered, state: 'locked', txIds: [offered.id], updatedAt: offered.updatedAt + 1 }); + const saved = await store.get(offered.id); + assert.equal(saved?.state, 'locked'); + assert.equal(saved?.lockTxHex, 'ee0102ff01', 'the lock tx bytes rest through the offered -> locked transition'); + } + // Persistence round-trip over the scripted backend. { const backend = memoryStorage(); @@ -141,6 +157,14 @@ async function main() { const legacy = JSON.parse(JSON.stringify(row({ id: 'legacy' }))); delete legacy.lockTxHex; assert.equal(parseSwapSessions(JSON.stringify([legacy])).length, 1); + // The retired spendPubkeyHex column does not resurrect from a legacy + // store: parse rebuilds rows from the validated fields only. + const legacyKey = JSON.parse(JSON.stringify(row({ id: 'legacy-key' }))); + legacyKey.spendPubkeyHex = '02'.repeat(33); + const stripped = parseSwapSessions(JSON.stringify([legacyKey]))[0]; + assert.ok(stripped, 'the legacy row still loads'); + assert.ok(!('spendPubkeyHex' in stripped), 'the retired spend pubkey column is stripped on load'); + assert.equal(Object.keys(stripped).sort().join(','), 'id,lockTxHex,offer,refundAddress,secretHashHex,spendAddress,state,txIds,updatedAt'); // Session cap: a hostile store cannot force unbounded memory. const many = Array.from({ length: 40 }, (_, i) => row({ id: `s${i}` })); diff --git a/src/trade/swapSession.ts b/src/trade/swapSession.ts index 0dba7bb..5bbea33 100644 --- a/src/trade/swapSession.ts +++ b/src/trade/swapSession.ts @@ -24,7 +24,6 @@ export type SwapSessionRow = { /** Counterparty spend path and our refund path (rebuild leg data after * a restart without touching the chain). */ spendAddress: string; - spendPubkeyHex: string; refundAddress: string; /** Hex of the unsigned lock transaction bytes as built before the * broadcast: the claim and refund bindings decodes consume serialized @@ -39,8 +38,7 @@ export type SwapSessionRow = { /** The persisted offer form: scalar fields only. Byte fields (the secret * hash) never persist inside the offer; JSON would mangle a Uint8Array * into an object map and the restored row would lie about its type. The - * bytes are rebuilt from secretHashHex on load, exactly like - * spendPubkeyHex already does for the spend key. */ + * bytes are rebuilt from secretHashHex on load. */ type PersistedOffer = { role: HtlcOffer['role']; giveChain: HtlcOffer['giveChain']; @@ -67,7 +65,7 @@ function toPersisted(row: SwapSessionRow): Omit & { off /** Allowed transitions; anything else is a programming error, not a * silent overwrite. */ const TRANSITIONS: Record = { - offered: ['locked', 'expired'], + offered: ['locked', 'refunded', 'expired'], locked: ['claiming', 'refunded', 'expired'], claiming: ['settled', 'refunded', 'expired'], settled: [], @@ -154,11 +152,13 @@ export function parseSwapSessions(json: string | null): SwapSessionRow[] { Array.isArray(row.txIds) && row.txIds.length <= MAX_TX_IDS && row.txIds.every((id) => typeof id === 'string') && typeof row.updatedAt === 'number' && Number.isFinite(row.updatedAt) ) { - // Normalize: the in-memory row carries the secret hash bytes rebuilt - // from the persisted hex, never whatever a tampered store embedded - // inside the offer object. + // Normalize: rebuild the row from the validated fields only, so a + // legacy or tampered store's extra columns (the retired + // spendPubkeyHex) never ride into memory or persist back, and the + // secret hash bytes are rebuilt from the persisted hex, never from + // whatever junk the store embedded inside the offer object. rows.push({ - ...(entry as SwapSessionRow), + id: row.id, offer: { role: offer.role, giveChain: offer.giveChain, @@ -167,6 +167,13 @@ export function parseSwapSessions(json: string | null): SwapSessionRow[] { secretHash: hexOf.decode(row.secretHashHex), timelockSeconds: offer.timelockSeconds, }, + secretHashHex: row.secretHashHex, + spendAddress: row.spendAddress, + refundAddress: row.refundAddress, + ...(row.lockTxHex !== undefined ? { lockTxHex: row.lockTxHex } : {}), + state: row.state, + txIds: [...row.txIds], + updatedAt: row.updatedAt, }); } } From 53d52913d1e739f831bbdb19407d20735324b145 Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 08:22:13 +0100 Subject: [PATCH 15/20] fix(m4): pin the witness and order seam signatures --- src/trade/bindingsParity.test.ts | 39 +++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/src/trade/bindingsParity.test.ts b/src/trade/bindingsParity.test.ts index 55efc48..062c606 100644 --- a/src/trade/bindingsParity.test.ts +++ b/src/trade/bindingsParity.test.ts @@ -81,6 +81,36 @@ const PINNED: { name: string; swift: string; ts: string[] }[] = [ swift: 'public func encodeInputForUtxo(outpointSourceId: Data, outputIndex: UInt32)throws -> Data {', ts: ['encodeInputForUtxo(outpointSource: Uint8Array, index: number): Promise;'], }, + { + name: 'encodeCreateOrderOutput', + swift: 'public func encodeCreateOrderOutput(askAmount: String, askTokenId: String?, giveAmount: String, giveTokenId: String?, concludeAddress: String, network: Network)throws -> Data {', + ts: ['encodeCreateOrderOutput(params: OrderParams): Promise;'], + }, + { + name: 'encodeSignedTransaction', + swift: 'public func encodeSignedTransaction(transaction: Data, signatures: [Data])throws -> Data {', + ts: ['encodeSignedTransaction(transaction: Uint8Array, witnesses: Uint8Array[]): Promise;'], + }, + { + name: 'estimateTransactionSize', + swift: 'public func estimateTransactionSize(inputs: [Data], inputDestinations: [String], outputs: [Data], network: Network)throws -> UInt64 {', + ts: ['estimateTransactionSize(inputs: Uint8Array[], inputDestinations: string[], outputs: Uint8Array[], network: MlNetwork): Promise;'], + }, + { + name: 'encodeWitness', + swift: 'public func encodeWitness(sighashType: SignatureHashType, privateKey: Data, inputOwnerDestination: String, transaction: Data, inputUtxos: [Data?], inputIndex: UInt32, additionalInfo: TxAdditionalInfo, currentBlockHeight: UInt64, network: Network)throws -> Data {', + ts: ['encodeWitness(params: WitnessParams): Promise;'], + }, + { + name: 'encodeWitnessHtlcSpend', + swift: 'public func encodeWitnessHtlcSpend(sighashType: SignatureHashType, privateKey: Data, inputOwnerDestination: String, transaction: Data, inputUtxos: [Data?], inputIndex: UInt32, secret: Data, additionalInfo: TxAdditionalInfo, currentBlockHeight: UInt64, network: Network)throws -> Data {', + ts: ['encodeWitnessHtlcSpend(params: WitnessParams): Promise;'], + }, + { + name: 'encodeWitnessHtlcRefundSingleSig', + swift: 'public func encodeWitnessHtlcRefundSingleSig(sighashType: SignatureHashType, privateKey: Data, inputOwnerDestination: String, transaction: Data, inputUtxos: [Data?], inputIndex: UInt32, additionalInfo: TxAdditionalInfo, currentBlockHeight: UInt64, network: Network)throws -> Data {', + ts: ['encodeWitnessHtlcRefundSingleSig(params: WitnessParams): Promise;'], + }, ]; /** The HTLC params record: the vendored facade takes a hex secret hash and @@ -95,9 +125,12 @@ const HTLC_PARAMS_TS_FIELDS = [ ]; /** Pinned sha256 over the joined normalized vendored signature lines, in - * the PINNED order. Recompute and update together with a vendored - * artifact upgrade only after re-reviewing every seam signature. */ -const PINNED_VENDOR_CHECKSUM = 'e0474caed1b25ae53f7f5e6c8bca888b07e400ebb4ccbbcb89ae95f1847d8e52'; + * the PINNED order: the transaction assembly seam, the order output, and + * every witness carrier including the privateKey/secret-carrying HTLC + * spend and refund encoders. Recompute and update together with a + * vendored artifact upgrade only after re-reviewing every seam + * signature. */ +const PINNED_VENDOR_CHECKSUM = '7d7f2c82e8bd0a95adda1f643cb8faecab8eaf39ff161a3df2db7f85136a6067'; function normalize(line: string): string { return line.replace(/\s+/g, ' ').trim(); From 797aab6def65308fbfb251cf40c3f9de80151e87 Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 08:23:09 +0100 Subject: [PATCH 16/20] fix(m4): guard 0-decimal ask legs and pair-filter my orders --- src/screens/DexScreen.tsx | 77 ++++++++++++++++++++++++++++++--------- 1 file changed, 60 insertions(+), 17 deletions(-) diff --git a/src/screens/DexScreen.tsx b/src/screens/DexScreen.tsx index 0894f1a..cc75a63 100644 --- a/src/screens/DexScreen.tsx +++ b/src/screens/DexScreen.tsx @@ -81,17 +81,31 @@ export function DexScreen() { }; }, [price, tf]); - // My orders (spec: actions on orders flagged as mine). + // My orders (spec: actions on orders flagged as mine). myOrders spans + // every wallet pair; this screen trades ML/USDT, so rows are filtered to + // the displayed pair (either direction) instead of rendering foreign + // tickers with hardcoded decimals. An ambiguous USDT ticker (more than + // one token id) keeps the list unloaded: the ticket refuses placement on + // the same condition. const [myOrders, setMyOrders] = useState(null); const [ordersError, setOrdersError] = useState(null); + const usdtTokenId = askTokenIds !== null && askTokenIds.length === 1 ? askTokenIds[0] : null; const loadMyOrders = useCallback(async () => { + if (usdtTokenId === null) return; try { - setMyOrders(await orders.myOrders()); + const mine = await orders.myOrders(); + setMyOrders( + mine.filter( + (order) => + (order.giveTokenId === COIN_REF && order.askTokenId === usdtTokenId) || + (order.giveTokenId === usdtTokenId && order.askTokenId === COIN_REF), + ), + ); setOrdersError(null); } catch { setOrdersError(t('errors.orders.book')); } - }, [orders]); + }, [orders, usdtTokenId]); useEffect(() => { void loadMyOrders(); }, [loadMyOrders]); @@ -103,13 +117,24 @@ export function DexScreen() { const [lastDemoNote, setLastDemoNote] = useState(null); // Fill confirmation state: the payout preview (proportionalGivePayout on // the order legs) plus the effective price versus the book mid, before - // any fill transaction is built. - const [fillSheet, setFillSheet] = useState<{ order: OrderData; payout: string; effective: string; mid: string } | null>(null); + // any fill transaction is built. legs carries the direction-derived + // decimals and symbols (the fill pays the order's ask currency). + const [fillSheet, setFillSheet] = useState<{ + order: OrderData; + payout: string; + effective: string; + mid: string; + legs: { payDecimals: number; paySymbol: string; receiveDecimals: number; receiveSymbol: string }; + } | null>(null); const bookRows = liveBook; if (!timeframes || !fees || !candles || !assets || !askTokenIds || !askMeta || !bookRows) return ; const maxAsk = Math.max(...bookRows.asks.map((r) => Number(r.total || 0)), 1); const maxBid = Math.max(...bookRows.bids.map((r) => Number(r.total || 0)), 1); + // Quote-token decimals with the absent-meta fallback: 0 is a valid + // precision, so a falsy-decimals fallback would inflate a 0-decimal + // order leg by 1e11. + const askDecimals = Number.isInteger(askMeta.decimals) ? askMeta.decimals : ML_DECIMALS; const total = usd(amount, market?.price ?? 0); const bestAsk = Number(bookRows.asks[0]?.price ?? market?.price ?? 0); const bestBid = Number(bookRows.bids[0]?.price ?? market?.price ?? 0); @@ -159,9 +184,9 @@ export function DexScreen() { try { await orders.createOrder({ giveTokenId: buy ? askTokenIds[0] : COIN_REF, - giveAtoms: buy ? decimalsToAtoms(total, askMeta.decimals || ML_DECIMALS) : decimalsToAtoms(amount, ML_DECIMALS), + giveAtoms: buy ? decimalsToAtoms(total, askDecimals) : decimalsToAtoms(amount, ML_DECIMALS), askTokenId: buy ? COIN_REF : askTokenIds[0], - askAtoms: buy ? decimalsToAtoms(amount, ML_DECIMALS) : decimalsToAtoms(total, askMeta.decimals || ML_DECIMALS), + askAtoms: buy ? decimalsToAtoms(amount, ML_DECIMALS) : decimalsToAtoms(total, askDecimals), }); setConfirmOpen(false); setLastDemoNote(mode === 'mock' ? t('dex.order.demo') : null); @@ -176,14 +201,16 @@ export function DexScreen() { /** Fill preview: payout from the order legs (the same math the flow * applies) and the effective ask-per-give price, checked against the - * book mid before the fill executes; the flow re-checks the band. */ + * book mid before the fill executes; the flow re-checks the band. The + * legs follow the order's direction, not the ticket's. */ const openFill = (order: OrderData) => { + const legs = pairLegs(order, askDecimals); const mid = (bestAsk + bestBid) / 2; const payout = proportionalGivePayout(order.giveBalanceAtoms, order.askBalanceAtoms, order.askBalanceAtoms); - const fillDecimal = Number(atomsToDecimal(order.askBalanceAtoms, askMeta.decimals)); - const payoutDecimal = Number(atomsToDecimal(payout, ML_DECIMALS)); + const fillDecimal = Number(atomsToDecimal(order.askBalanceAtoms, legs.payDecimals)); + const payoutDecimal = Number(atomsToDecimal(payout, legs.receiveDecimals)); const effective = payoutDecimal > 0 ? fillDecimal / payoutDecimal : 0; - setFillSheet({ order, payout, effective: effective.toFixed(4), mid: mid.toFixed(4) }); + setFillSheet({ order, payout, effective: effective.toFixed(4), mid: mid.toFixed(4), legs }); }; const runFill = async () => { @@ -194,7 +221,7 @@ export function DexScreen() { orderId: fillSheet.order.orderId, fillAtoms: fillSheet.order.askBalanceAtoms, destination: fillSheet.order.concludeDestination, - priceBand: { midDecimal: fillSheet.mid, maxSlippagePct: MAX_SLIPPAGE_PCT, askDecimals: askMeta.decimals, giveDecimals: ML_DECIMALS }, + priceBand: { midDecimal: fillSheet.mid, maxSlippagePct: MAX_SLIPPAGE_PCT, askDecimals: fillSheet.legs.payDecimals, giveDecimals: fillSheet.legs.receiveDecimals }, }); setFillSheet(null); void loadMyOrders(); @@ -406,6 +433,7 @@ export function DexScreen() { void loadMyOrders()} onError={setTicketError} onFill={openFill} @@ -439,9 +467,9 @@ export function DexScreen() { {fillSheet && ( <> - - - + + + {Number(fillSheet.effective) > 0 && Number(fillSheet.mid) > 0 && (Math.abs(Number(fillSheet.effective) - Number(fillSheet.mid)) / Number(fillSheet.mid)) * 100 > MAX_SLIPPAGE_PCT && ( @@ -475,10 +503,11 @@ function orderErrorCopy(e: unknown): string { return t('dex.book.error'); } -function MyOrderRow({ order, onDone, onError, onFill }: { order: OrderData; onDone: () => void; onError: (message: string) => void; onFill: (order: OrderData) => void }) { +function MyOrderRow({ order, usdtDecimals, onDone, onError, onFill }: { order: OrderData; usdtDecimals: number; onDone: () => void; onError: (message: string) => void; onFill: (order: OrderData) => void }) { const { orders } = useProviders(); const phase = orderPhase(order); const [busy, setBusy] = useState(false); + const legs = pairLegs(order, usdtDecimals); const run = async (action: () => Promise) => { setBusy(true); try { @@ -501,7 +530,7 @@ function MyOrderRow({ order, onDone, onError, onFill }: { order: OrderData; onDo - {`give ${atomsToDecimal(order.giveBalanceAtoms, ML_DECIMALS)} ML · ask ${atomsToDecimal(order.askBalanceAtoms, ML_DECIMALS)} USDT`} + {`give ${atomsToDecimal(order.giveBalanceAtoms, legs.receiveDecimals)} ${legs.receiveSymbol} · ask ${atomsToDecimal(order.askBalanceAtoms, legs.payDecimals)} ${legs.paySymbol}`} {phase !== 'concluded' && ( @@ -525,6 +554,20 @@ function MyOrderRow({ order, onDone, onError, onFill }: { order: OrderData; onDo ); } +/** Direction legs for a displayed-pair order (the myOrders load filter + * guarantees ML/USDT on both legs, either direction): the fill pays the + * order's ask currency and receives the give currency, each at its own + * decimals. */ +function pairLegs(order: OrderData, usdtDecimals: number): { payDecimals: number; paySymbol: string; receiveDecimals: number; receiveSymbol: string } { + const giveIsMl = order.giveTokenId === COIN_REF; + return { + payDecimals: giveIsMl ? usdtDecimals : ML_DECIMALS, + paySymbol: giveIsMl ? 'USDT' : 'ML', + receiveDecimals: giveIsMl ? ML_DECIMALS : usdtDecimals, + receiveSymbol: giveIsMl ? 'ML' : 'USDT', + }; +} + /** Order-book line with a depth bar filling from the right. */ function BookRow({ row, max, tone, delay }: { row: { price: string; size: string; total: string }; max: number; tone: string; delay: number }) { From 31c8e8d080387ca3dbdd27c52fdc5f2164d8a1eb Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 08:23:33 +0100 Subject: [PATCH 17/20] fix(m4): honest dex rejection and busy copy --- src/i18n/strings/en.ts | 2 ++ src/screens/DexScreen.tsx | 10 ++++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/i18n/strings/en.ts b/src/i18n/strings/en.ts index 57b7030..78fc469 100644 --- a/src/i18n/strings/en.ts +++ b/src/i18n/strings/en.ts @@ -209,6 +209,8 @@ export const en = { 'dex.order.ambiguousTicker': 'Several tokens share this ticker. Pick the exact token id to trade.', 'dex.order.typeUnsupported': 'Only limit orders are supported right now. Switch back to Limit to place an order.', 'dex.order.busy': 'The previous order action is still running. Wait for it to finish.', + 'dex.order.rejected': 'The order action was refused before anything was sent. Check the amount and the order state, then retry.', + 'dex.order.working': 'Working', 'dex.orders.empty': 'No orders of yours yet. Placed orders show up here.', 'dex.dev.demoBanner': 'Demo DEX: this order is simulated in this build, not a chain order.', 'dex.fill.cta': 'Fill order', diff --git a/src/screens/DexScreen.tsx b/src/screens/DexScreen.tsx index cc75a63..3addd84 100644 --- a/src/screens/DexScreen.tsx +++ b/src/screens/DexScreen.tsx @@ -457,7 +457,7 @@ export function DexScreen() { )} void placeOrder()}> - {placing ? t('swap.state.pending') : t('dex.order.place')} + {placing ? t('dex.order.working') : t('dex.order.place')} @@ -478,7 +478,7 @@ export function DexScreen() { )} void runFill()}> - {placing ? t('swap.state.pending') : t('dex.fill.cta')} + {placing ? t('dex.order.working') : t('dex.fill.cta')} )} @@ -488,7 +488,9 @@ export function DexScreen() { } /** Order flow failures to screen copy (device-pending and config-pending - * stay explicit: nothing reads as sent when it was not). */ + * stay explicit: nothing reads as sent when it was not). Generic order + * rejections (malformed fill amounts, non-computable legs, zero payout) + * get their own copy: the book-unreachable line misstates the failure. */ function orderErrorCopy(e: unknown): string { if (isBindingsUnavailable(e)) return t('dex.order.signingPending'); const record = e as { reason?: string } | null; @@ -500,7 +502,7 @@ function orderErrorCopy(e: unknown): string { if (record.reason === 'slippage') return t('errors.orders.slippage'); if (record.reason === 'busy') return t('dex.order.busy'); } - return t('dex.book.error'); + return t('dex.order.rejected'); } function MyOrderRow({ order, usdtDecimals, onDone, onError, onFill }: { order: OrderData; usdtDecimals: number; onDone: () => void; onError: (message: string) => void; onFill: (order: OrderData) => void }) { From 2dc2f07db1746b645e877f6a2019120f4dd3b057 Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 08:23:55 +0100 Subject: [PATCH 18/20] test(m4): refuse lying broadcast answers in the order gate --- src/trade/orders.test.ts | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/src/trade/orders.test.ts b/src/trade/orders.test.ts index 3c72e4f..7a95d79 100644 --- a/src/trade/orders.test.ts +++ b/src/trade/orders.test.ts @@ -169,7 +169,7 @@ function orderRow(overrides: Partial): OrderRow { }; } -function harness(opts?: { orders?: OrderRow[]; detail?: OrderRow; utxos?: MlUtxo[]; broadcastFails?: 'disabled' | null }) { +function harness(opts?: { orders?: OrderRow[]; detail?: OrderRow; utxos?: MlUtxo[]; broadcastFails?: 'disabled' | null; lyingBroadcast?: string }) { const bindings = fakeBindings(); const changeCounter = { n: 0 }; const broadcastHexes: string[] = []; @@ -222,7 +222,9 @@ function harness(opts?: { orders?: OrderRow[]; detail?: OrderRow; utxos?: MlUtxo if (opts?.broadcastFails === 'disabled') { throw new BroadcastError('ml', 'disabled', undefined, 'no ML submission endpoint is configured'); } - return { txId: localIdOf(signedTxHex) }; + // lyingBroadcast: the dishonest-backend case for the finishTx id + // equality contract (fill and conclude), like the htlc harness. + return { txId: opts?.lyingBroadcast ?? localIdOf(signedTxHex) }; }, async broadcastBtc() { return { txId: 'f'.repeat(64) }; @@ -435,6 +437,29 @@ async function main() { ); } + // 6b. A lying broadcast endpoint is refused on the finishTx path too: + // fill and conclude verify the answered id against the locally + // signed transaction (M3 contract; the HTLC side covers the lock). + { + const fillDetail = orderRow({}); + const h = harness({ + detail: fillDetail, + utxos: [coinUtxo('aa'.repeat(32), 0, VECTOR_ADDRESS, atoms(500n)), tokenUtxo('cc'.repeat(32), 0, VECTOR_ADDRESS, atoms(4n))], + lyingBroadcast: 'bb'.repeat(32), + }); + const destination = await mlAddressAt(account.xpub, 0, 1, 'mainnet'); + await assert.rejects( + () => h.flows.fillOrder({ orderId: ORDER_ID, fillAtoms: atoms(3n), destination, priceBand: FILL_BAND }), + (e: unknown) => e instanceof OrderFlowError && e.reason === 'rejected', + ); + const concludeDetail = orderRow({ concludeDestination: VECTOR_ADDRESS, giveBalance: { atoms: atoms(4n) }, askBalance: { atoms: atoms(1n) } }); + const h2 = harness({ detail: concludeDetail, lyingBroadcast: 'bb'.repeat(32) }); + await assert.rejects( + () => h2.flows.concludeOrder({ orderId: ORDER_ID }), + (e: unknown) => e instanceof OrderFlowError && e.reason === 'rejected', + ); + } + // 7. Serialization: an overlapping order transaction refuses typed. { const h = harness(); From 9379c56d9a2023d0dc856badf3ffa523cd79cf02 Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 08:24:10 +0100 Subject: [PATCH 19/20] fix(m4): scan send modules for console logging --- scripts/no-console.ts | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/scripts/no-console.ts b/scripts/no-console.ts index 69c1b48..7d6b458 100644 --- a/scripts/no-console.ts +++ b/scripts/no-console.ts @@ -1,14 +1,16 @@ // Secret-logging guard: no console.* anywhere in the native module facade -// or the secret-handling modules (keys, storage, onboarding: the phrase and -// the PIN cross all three). Binding calls carry key blobs, and the security -// note is "never log": the check fails the build instead of trusting review -// to catch a stray debug line. Test sources are exempt: they run in the Node -// gate and their stdout is the harness output. +// or the secret-handling modules (keys, send, storage, data, onboarding, +// trade, screens: the phrase and the PIN cross several of them, and the +// send and trade modules sign with in-session raw keys). Binding calls +// carry key blobs, and the security note is "never log": the check fails +// the build instead of trusting review to catch a stray debug line. Test +// sources are exempt: they run in the Node gate and their stdout is the +// harness output. // tsx scripts/no-console.ts import { readdirSync, readFileSync, statSync } from 'node:fs'; import { join } from 'node:path'; -const SCAN_ROOTS = ['modules/mojito-core', 'src/keys', 'src/storage', 'src/data', 'src/onboarding', 'src/trade', 'src/screens']; +const SCAN_ROOTS = ['modules/mojito-core', 'src/keys', 'src/send', 'src/storage', 'src/data', 'src/onboarding', 'src/trade', 'src/screens']; const failures: string[] = []; From 1cbe59c485b72ccb0e224c95a27028c598605d2c Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Wed, 18 Nov 2026 08:24:46 +0100 Subject: [PATCH 20/20] docs(m4): correct the check gate list and timelock claim --- README.md | 55 ++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 38 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 6f5343e..9b51cfd 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Real in M4: - **Order book**: Dex depth rows come from GET /order/pair/{base}_{quote}/book with keyset cursor pagination and an invalid-cursor page-1 restart; stale and error states are explicit, never fixture rows in real mode. - **Orders**: place (confirm sheet with the exact amounts and a slippage guard against the book mid), fill and conclude run the bindings order encoders with the F11 witness mix (no-signature on the order input, signed payer inputs); the order id derives through the bindings from the create tx inputs, and fill and conclude inputs carry the account nonce and block height per the vendored wallet-bindings v0.1.0 signatures (pinned by src/trade/bindingsParity.test.ts). -- **Atomic swap**: the ML-side HTLC flow (lock, claim, refund, secret extraction) per the docs guide; sessions persist across restarts with the secret hash only (the preimage never persists and never logs; the keep-open warning explains what is at stake). The BTC counterparty leg is the scripted demo (see scripts/e2e-testnet.mjs) with the shorter-timelock rule enforced by UI guards. +- **Atomic swap**: the ML-side HTLC flow (lock, claim, refund, secret extraction) per the docs guide; sessions persist across restarts with the secret hash only (the preimage never persists and never logs; the keep-open warning explains what is at stake), and the lock bytes are stored before the broadcast so a crash cannot strand the refund. The BTC counterparty leg is the scripted demo (see scripts/e2e-testnet.mjs); the timelock guard returns with real offers (plans/mojito-neo/decisions.md). - **Bridge**: quotes and status ride the bridge_v2 api-server per R5 (per-token fees per direction, the Mintlayer treasury deposit address, m2e deposit confirmations); E2M stays disabled with explanatory copy (no EVM signer, scoped decision open). M2E initiation is honestly gated until the deposit intent encoder and the ML submission route exist. The EVM demo fixtures (Arbitrum, Polygon, BNB) are removed from the bridge chains and pickers in this milestone. M3 (still accurate): BTC sends are end-to-end real on scure against the configured btc-api base; ML sends prepare and sign over the bindings interface but honestly refuse to broadcast (R3, action item A1); the send lifecycle tracks pending to confirmed with fresh-address rotation. @@ -241,7 +241,7 @@ npm run lint # eslint only npx tsx src/theme.test.ts ``` -`npm run check` runs thirty-six things: +`npm run check` runs thirty-seven things: 1. **`src/theme.test.ts`**: asserts the oklch→sRGB conversion against the known sRGB primaries. Every colour in the app flows through it, so it's the one piece of non-trivial logic with a @@ -275,33 +275,54 @@ npx tsx src/theme.test.ts the real-mode construction seams. 16. **`src/data/providers/broadcast.test.ts`**: the gap-3 broadcast provider: mock deterministic ids, 403-to-disabled and transport-to-network mappings, BTC POST tx shape, status reads. -17. **`src/keys/bip39.test.ts`**: published BIP39 seed vectors, checksum/word/length rejection, +17. **`src/data/providers/bridge.test.ts`**: the bridge_v2 api provider: quote and fee parsing + per direction, the treasury deposit address, status mapping and the E2M and initiation + typed gates, all over a scripted transport. +18. **`src/trade/orderBookService.test.ts`**: the live depth aggregation: cursor-paginated + pages, the num/denom price rational, the invalid-cursor page-1 restart and the honest + null last-fill. +19. **`src/trade/orders.test.ts`**: order create/fill/conclude over the bindings double: the + witness mix, order id extraction, nonce and height inputs, the fill guards (frozen, + concluded, overbid, off-band price) and the lying-broadcast refusals. +20. **`src/trade/htlc.test.ts`**: the HTLC flows: lock output parameters, the build/broadcast + split (nothing broadcasts until the prepared lock is confirmed), the claim witness with + the secret, the refund timelock refusal, lying-broadcast refusals and the secret + extraction round-trip. +21. **`src/trade/swapSession.test.ts`**: the swap session machine: transitions (including the + offered -> locked broadcast step), persistence round-trip, corrupt-row dropping, + legacy-column stripping and the no-preimage guarantee. +22. **`src/trade/priceGuards.test.ts`**: the slippage band, minimum fill floor, amount sanity + and the swap timelock rule margin, with typed NaN results. +23. **`src/trade/bindingsParity.test.ts`**: the vendored-signature parity pin: every seam + function (including the privateKey and secret carriers) line-pinned against the vendored + Swift plus the checksum that fails on any vendor upgrade. +24. **`src/keys/bip39.test.ts`**: published BIP39 seed vectors, checksum/word/length rejection, NFKD normalization, wordlist integrity, supplied-entropy generation. -18. **`src/keys/mlAccounts.test.ts`**: the bindings parity vectors (both networks) for account +25. **`src/keys/mlAccounts.test.ts`**: the bindings parity vectors (both networks) for account blobs, receiving blobs and addresses, plus the custom-path scan. -19. **`src/keys/BtcKeyring.test.ts`**: BIP84 zpub and address vectors, branch separation, custom +26. **`src/keys/BtcKeyring.test.ts`**: BIP84 zpub and address vectors, branch separation, custom account paths. -20. **`src/send/validation.test.ts`**: send address validation (mtc1/tmt1/bc1/tb1, wrong-network +27. **`src/send/validation.test.ts`**: send address validation (mtc1/tmt1/bc1/tb1, wrong-network detection, non-standard HRP rejection) and exact amount parsing against published vectors. -21. **`src/send/mlTxBuilder.test.ts`**: the ML planner and assembler: selection determinism, the +28. **`src/send/mlTxBuilder.test.ts`**: the ML planner and assembler: selection determinism, the implicit-fee invariant, token-remainder sizing on the real output list, signer loopback. -22. **`src/send/btcTxBuilder.test.ts`**: the BTC builder: plan-fee equals signed-fee on the BIP84 +29. **`src/send/btcTxBuilder.test.ts`**: the BTC builder: plan-fee equals signed-fee on the BIP84 vectors, multi-origin signing, confirmed-input policy, typed dust and insufficient funds. -23. **`src/send/TxTracker.test.ts`**: the pending-to-confirmed lifecycle with injected timers: +30. **`src/send/TxTracker.test.ts`**: the pending-to-confirmed lifecycle with injected timers: poll cadence, attempt caps, terminal stop, flaky-read tolerance. -24. **`src/data/real/realSend.test.ts`**: the real send service over an in-memory manager: +31. **`src/data/real/realSend.test.ts`**: the real send service over an in-memory manager: funding across every managed address with fresh branch 1 change, typed busy refusal, broadcast-answer verification, fee pinning, quote purity, post-broadcast warning, the origin walk over long change histories and the failed-send change release. -25. **`src/data/mock/mockSend.test.ts`**: the R3 demo send path: fixture fee tiers, the same +32. **`src/data/mock/mockSend.test.ts`**: the R3 demo send path: fixture fee tiers, the same address and amount validation rejections and deterministic demo-labelled ids. -26. **`src/keys/session.test.ts`**: KeySession closure isolation, zeroize of the seed buffer, +33. **`src/keys/session.test.ts`**: KeySession closure isolation, zeroize of the seed buffer, release semantics, xpub parity. -27. **`scripts/no-console.ts`**: no `console.*` in the native facade or the secret-handling - modules (keys, storage, data, onboarding). -28. **`scripts/no-em-dash.ts`**: no em or en dashes anywhere in code, specs or docs. -29. **`tsc --noEmit`**: strict TypeScript. -30. **`eslint .`**: `eslint-config-expo`, including the `react-hooks` rules. +34. **`scripts/no-console.ts`**: no `console.*` in the native facade or the secret-handling + modules (keys, send, storage, data, onboarding, trade, screens). +35. **`scripts/no-em-dash.ts`**: no em or en dashes anywhere in code, specs or docs. +36. **`tsc --noEmit`**: strict TypeScript. +37. **`eslint .`**: `eslint-config-expo`, including the `react-hooks` rules. **There is no UI/component test suite yet.** Adding one (React Native Testing Library + `jest-expo`) is a welcome contribution: start with the onboarding flow, which holds the most