# Fondaco developer docs Source: https://docs.fondaco.network/ Fondaco is a request-for-quote network on Midnight. A wallet or app asks for a price, solvers compete with signed, binding quotes, and the trade settles in one Midnight transaction by merging offers. The relay never holds funds: the solver settles from its own coins and the wallet signs its own side. Privacy is a property of each leg. The shielded side (USDM) is hidden: amount, coins and the link to the user. The NIGHT side is public: an unshielded leg shows its address and amount on any explorer, until a shielded NIGHT is listed. The [threat model](/security/threat-model/) says who sees what. ## Start here | You are | Start with | Then | |---|---|---| | A wallet or dApp team | [Wallet in 20 minutes](/quickstart/wallet/) | The [wallet SDK reference](/reference/wallet-sdk/readme/), the [relay API](/reference/api/) | | A solver: desk, bot or agent | [Solver in 20 minutes](/quickstart/solver/) | The [solver SDK reference](/reference/solver-sdk/readme/), the [RFQ envelope](/standards/rfq-envelope/) | | A site that wants the swap on a page | [Embed in 5 minutes](/quickstart/embed/) | — | | Anyone checking the claims | [What is mocked](/what-is-mocked/) and the [threat model](/security/threat-model/) | The [MIP draft](/standards/rfq-envelope/) | ## What exists today, and what does not These docs describe the network as it is. Some pieces the quickstarts are built around are still being written; their pages say so at the top, show what works meanwhile, and change when the piece ships. The flags below are the ones the public site uses (site/src/data/site.json). | Piece | Status | Meanwhile | |---|---|---| | Wallet SDK demo mode (`SwapClient({ mode: "demo" })`, `DemoWallet`) | Upcoming | Demo mode is the next wallet SDK release (docs/devex.md §2). Until it ships, the swap runs against the local devnet stack or, with a token from us, Preprod. | | Solver CLI and mock relay (`npx si-solver dev`, `MockRelay`) | Upcoming | The si-solver command and its mock relay are the next solver SDK release (docs/devex.md §3). Until they ship, a solver runs against the local devnet stack. | | Hosted Preprod relay with the public `demo` app key | Works today | — | | The privacy level in the relay, the SDK and the swap | Upcoming | The privacy level ships in the relay, the wallet SDK and the web swap before mainnet (docs/privacy-levels.md). Until then every fill is what the public level describes: the NIGHT leg is public, the shielded side hidden. | What runs today: the relay, both SDKs, the solvers and the matcher on the local devnet stack (`scripts/stack.sh up`), and the same code on Preprod with a token from us. ## Package names The packages will publish to npm as `@fondaco/wallet-sdk`, `@fondaco/solver-sdk`, `@fondaco/connector`, `@fondaco/protocol` and `@fondaco/ledger-kit`. **None is published yet.** In the repository they are `@si/*` workspaces, built with `npm ci && npm run build` at the root; the code on these pages that runs today imports them from there. See [Packages](/reference/packages/). ## For agents [`/llms.txt`](/llms.txt) lists every page with a one-line summary; [`/llms-full.txt`](/llms-full.txt) is the text of the guides, the threat model and the MIP draft in one file. --- # Wallet in 20 minutes Source: https://docs.fondaco.network/quickstart/wallet/ Status: upcoming — Demo mode is the next wallet SDK release. The devnet path below works today and takes longer than 20 minutes the first time. > **Not built yet.** This quickstart is built around demo mode: the wallet SDK with an in-process relay, so a swap runs after npm install with nothing else. Demo mode, DemoWallet and the examples/wallet-quickstart app do not exist yet. The code in the first section shows the API they will have; it does not run today. Demo mode is the next wallet SDK release (docs/devex.md §2). Until it ships, the swap runs against the local devnet stack or, with a token from us, Preprod. ## The 20-minute path (upcoming) When demo mode ships, this is the whole quickstart: ```ts import { SwapClient, DemoWallet } from '@fondaco/wallet-sdk'; const client = new SwapClient({ mode: 'demo' }); // no relay URL, no app id, no key const wallet = new DemoWallet({ USDM: 1_000_000_000n }); // or a real connector in demo mode const r = await client.swap(wallet, { give: 'USDM', want: 'NIGHT', amount: 25_000_000n, receiver: wallet.receiver(), }); console.log(r.status.state); // finalized ``` What it will do, from the plan in docs/devex.md §2: - The demo relay answers with one firm quote, signed by a demo solver key, and one indicative quote from a ladder, attests them with a fixed demo key, and the client runs its real checks against them. - The fill walks `reserved → made → submitted → finalized`, the state names the production relay uses, on a compressed clock; `realtime: true` paces it like Preprod so a UI's progress steps can be tested. - Every response carries a `DEMO` marker, also in `r.status`. - `scenario` reproduces the production relay's error shapes: `no_quote`, `paused`, `declined`, `fade`, `reserve_race`, `ws_refused`, `privacy_unavailable`. [What is mocked](/what-is-mocked/) lists what demo mode will fake and what it will not. ## What works today: the SDK against the local devnet The same SDK, against a real relay with real solvers, on the repository's devnet (a single-node chain running the ledger WASM). It needs the whole stack, so budget an afternoon for the first run. **Prerequisites.** Node ≥ 22.12, Elixir ≥ 1.18 with OTP ≥ 28, Rust 1.95, `nats-server` and Postgres, and a checkout of the repository. **1. Build and start the stack.** From the repository root: ```bash npm ci && npm run build ``` ```bash DATABASE_URL=ecto://user:pass@localhost/si_relay_dev scripts/stack.sh up ``` That starts NATS, the devnet on `:7300`, the relay on `http://localhost:4000`, our solvers and the matcher, and three devnet wallets behind the dApp connector API (`:7500` holds only USDM, so its fees are sponsored; `:7501` holds NIGHT and DUST; `:7502` is for resting offers). Solvers start in dry run: start the stack with `AUTO_ADMIT=true`, or admit them after a few requests with `node scripts/seed-programme.mjs --admit`. **2. Swap in the browser.** Open `http://localhost:4000`. The page loads the devnet wallet the way a browser extension would inject itself, so it is the integration a real wallet gets. `http://localhost:4000/regression` runs the integration end to end: a network check, a buy and a sell through to settlement, and a limit offer posted and cancelled, with pass or fail and timings for each step. **3. Swap from your own code.** `SwapClient` is the whole client. The relay registers a partner app on the devnet with the key `devnet-partner-key`: ```ts import { SwapClient } from '@si/wallet-sdk'; // @fondaco/wallet-sdk once published const client = new SwapClient({ relayUrl: 'http://localhost:4000', appId: 'partner-wallet', apiKey: 'devnet-partner-key', }); // `wallet` is a connected dApp connector API (connector 4.x): an extension in a browser, // or the devnet wallet's RPC in Node. const r = await client.swap(wallet, { give: 'USDM', want: 'NIGHT', amount: 25_000_000n, // 25 USDM, six decimals receiver: { unshielded: myNightAddressHex }, onProgress: (p) => console.log(p.stage), // quoted, accepted, …, status }); console.log(r.status.state, r.status.txId); // finalized | failed | expired ``` The repository's trade script does exactly this from Node, against a demo wallet's RPC, including the connector shim and a leg check from `@si/ledger-kit`. It was written for and run on Preprod (docs/PREPROD.md); it takes any relay and wallet URL, but we have not yet run it against the devnet stack as a quickstart, so treat this command as the starting point rather than a tested recipe: ```bash RELAY_URL=http://localhost:4000 WALLET_URL=http://127.0.0.1:7500 node scripts/preprod-wallet-trade.mjs USDM 25 NIGHT --sponsor ``` It prints one JSON line per step: the wallet and its balances, the quotes, the accept, and the fill's final state with the time of each stage. ### What the client checks before your wallet signs `quote()` refuses a response unless the relay's attestation is signed with the key the client holds (from its options or the relay's `/network`, never from the response), is for the network, app, pair and amount it asked for, and commits to exactly the quotes returned; each firm quote must carry its solver's valid signature. `execute()` checks the accept against the request and the quote before the wallet does anything. For a solver's leg (`solver_offer`) it needs a leg check from you (`checkLeg`); without one, the client asks for `user_offer` quotes only. The full list is in the wallet SDK README and §8 and §10 of the [MIP draft](/standards/rfq-envelope/). ### Errors to handle | Error | When | |---|---| | `RelayError` | A non-2xx answer from the relay (with its status), or a response that fails the client's checks (502) | | `SwapWalletError` | The wallet failed or refused; `failure` says which class | | `NoQuoteError` | No solver quoted | ### Tell your user what the chain shows On a USDM → NIGHT buy, the USDM the user pays is hidden; the NIGHT they receive arrives at a public address, with its amount. The swap page says this before the wallet signs; your app should too. The wording the public site uses is on [what is private](https://fondaco.network/privacy-levels). ## Next - **Preprod.** The same code against the hosted Preprod relay: `relayUrl: 'https://preprod-relay.fondaco.network'`, the public test app `demo` (its app id and its key), and `tsSIT`, Preprod's shielded test token, where the samples say USDM; see docs/PREPROD.md. - **Limit offers.** `postLimitOffer`, `cancelLimitOffer` and `book` in the [wallet SDK reference](/reference/wallet-sdk/readme/). - **Your own app id, app fee and revenue share.** The integration guide. --- # Solver in 20 minutes Source: https://docs.fondaco.network/quickstart/solver/ Status: upcoming — The si-solver CLI and MockRelay are the next solver SDK release. The devnet path below works today. > **Not built yet.** This quickstart is built around npx si-solver dev, which runs a solver against an in-process mock relay. The si-solver CLI, MockRelay and the examples/solver-quickstart project do not exist yet. The first section shows the commands and API they will have; they do not run today. The si-solver command and its mock relay are the next solver SDK release (docs/devex.md §3). Until they ship, a solver runs against the local devnet stack. ## The 20-minute path (upcoming) ```bash npx si-solver dev ``` `si-solver dev` will run an inventory solver against `MockRelay` with a stub pricer and print each request, quote and fill. `--webhook URL` prices through your own endpoint, in any language; `--devnet` points it at a running devnet stack instead. Two more commands: - `npx si-solver gate-check` replays a batch of requests and prints the admission checks of the solver programme in the programme's words. The 48-hour dry run is the one check it cannot simulate, and it will say so. - `npx si-solver keys` makes a quote-signing key and prints the registration payload. In code: ```ts import { serveRelay, MockRelay, webhookPricer } from '@fondaco/solver-sdk'; const relay = new MockRelay({ flow: 'steady' }); // in-process Relay 1.0 await serveRelay({ relay, pricer: webhookPricer('http://localhost:8080/price'), inventory: { NIGHT: 10_000n } }); ``` `MockRelay` will speak the solver WebSocket protocol in process, check every quote's signature and terms as the relay does, and report what the programme's gate would see: response times, signature failures, would-win rate and fades. It will use mock proofs and a mock chain; see [What is mocked](/what-is-mocked/). ## What works today: a solver on the local devnet Everything a third-party solver needs is in `@si/solver-sdk` today, and our own solver is built only on it (a test fails if it imports anything else). So the fastest real start is to run a copy of our solver under your own id, then replace its pricing. **1. Start the stack.** Follow steps 1 and 2 of the [wallet quickstart](/quickstart/wallet/#what-works-today-the-sdk-against-the-local-devnet): `npm ci && npm run build`, then `scripts/stack.sh up`. The relay listens on `http://localhost:4000` and the devnet on `:7300`. **2. Register your solver.** On the devnet the operator's admin API is open to the seed script. This registers `my-solver` under an existing devnet entity, with a devnet bond, in dry run: ```bash SOLVERS=my-solver:rfq:agent-co:20000 node scripts/seed-programme.mjs ``` Its quote key and bearer token are derived from public labels (`si:quote-key:my-solver`, `devnet-token-my-solver`), which the SDK allows only while the relay is on loopback. Off loopback, every secret must be given. **3. Run it.** ```bash SOLVER_ID=my-solver HTTP_PORT=7440 STATE_DIR=.stack/my-solver node apps/solver/dist/src/main.js ``` On loopback, without `RELAY_PUBLIC_KEY`, it pins the key in the relay's first `welcome` for the life of the process; off loopback the key is required and the relay URL must be `https://`. `GET http://127.0.0.1:7440/status` shows what it is doing; `/inventory` shows its NIGHT. Requests reach it once it is connected; admit it with `node scripts/seed-programme.mjs --admit` after its dry run, or start the stack with `AUTO_ADMIT=true`. **4. Price it your way.** The solver prices from the relay's reference mid with a spread and an inventory skew (`SPREAD_BPS`, `SKEW_MAX_BPS`; every setting is in the solver README). To price from your own system, give `serveRelay` a pricer. `webhookPricer` posts each request to your endpoint, in any language: ```ts import { serveRelay, webhookPricer, midBound } from '@si/solver-sdk'; // @fondaco/solver-sdk once published // The most the SDK will sign for, whatever the webhook answers: what the relay's reference // mid pays plus a tolerance, capped by what you hold. `refPrice` is a RefPrice reading the // relay's mid; USDM and NIGHT are the token ids the relay's /network lists. const bound = midBound(refPrice, { usdm: USDM, night: NIGHT }, { toleranceBps: 50, available: (token) => myInventory(token), }); serveRelay(solver, client, { price: webhookPricer('http://localhost:8080/price', { bound }) }); ``` Your endpoint receives `{ requestId, pair, giveAmount, minWantAmount, feeDecl, notional, settlements }` as JSON and answers `{ "wantAmount": "" }` to quote or `{ "decline": true }` to pass. It has 250 ms by default (`timeoutMs`); a slow or malformed answer is no quote. The minimal solver in the SDK README shows the rest of the wiring: `connectChain`, `MakerSolver` and `RelayClient`. ### What the SDK does for you, and what you bring The SDK signs quotes and ladders, checks every accept and job against the quote it signed and acts on each once, builds and proves your leg, merges, sponsors DUST within your cap, keeps a DUST-generating NIGHT reserve it never spends, and refuses a reference mid outside your band. You bring inventory, pricing and strategy. ### Your leg is public where it is NIGHT When you sell NIGHT, your NIGHT input is public on chain, as the user's NIGHT output is; the USDM side stays hidden. A winning solver learns the user's receiver address, because it pays out to it, and nothing about who asked. The [threat model](/security/threat-model/) has the full table. ## Next - **Preprod.** The same solver on Preprod needs proven legs, a funded wallet and a token from us: docs/PREPROD.md and the `INDEXER_*`, `NODE_URL` settings in the solver README. - **The rules.** Bond, quote limits, the dry run, fade penalties and the reputation record: the solver programme; on the public site, [for solvers](https://fondaco.network/solvers). - **The messages you sign.** Quotes, ladders and the fee declaration: the [RFQ envelope](/standards/rfq-envelope/). --- # Embed in 5 minutes Source: https://docs.fondaco.network/quickstart/embed/ Status: works today — The snippet works today against the local devnet relay. The hosted relay it points at below comes with M1 hosting. Nothing to build: the relay serves the swap page and a small script that frames it on your page. Your app id travels with every quote, so the flow is attributed to you and you receive the channel share, 30% of the protocol fee on the flow you bring (the integration guide has the terms). ## The snippet ```html
``` On mainnet the host is `app.fondaco.network`. - `data-app-id`: your app id, as the operator registered it. Letters, digits, `.`, `_` and `-`, up to 64 characters. Without a valid one the swap still works but quotes as the operator, and nothing is attributed to you. - `data-target`: a CSS selector for the element to fill. Without it, the frame goes right after the script tag. - `data-ref` (optional): a referring app id. The script inserts an iframe of the swap's compact layout, full width up to the card's width, and resizes it to the page's height as the swap reports it (by `postMessage`, accepted only from the relay's origin and from that frame). The user connects their own wallet inside the frame; your page never sees the wallet or the trade. Load it with a plain ` ``` The framed swap is the same page as `http://localhost:4000`, with the devnet wallet in it. ## What your users should know The swap tells the user what the chain will show before the wallet signs: the USDM side is hidden; the NIGHT side is public, address and amount. Your page does not need to repeat it, but should not contradict it. --- # What is mocked Source: https://docs.fondaco.network/what-is-mocked/ Status: upcoming — Demo mode and the mock relay are upcoming. The devnet's mocks below exist today. > **Not built yet.** Demo mode (wallet SDK) and MockRelay (solver SDK) are not built yet. This page lists what they will fake, so you can judge the quickstarts before they ship, and what the devnet you can run today fakes. Demo mode is the next wallet SDK release (docs/devex.md §2). Until it ships, the swap runs against the local devnet stack or, with a token from us, Preprod. The rule for every mock here: **what passes in demo must pass on Preprod.** The mocks fake proofs, the chain and time. They do not fake the envelope, the checks or the error shapes. ## Demo mode and the mock relay (upcoming) | Faked | How | |---|---| | The relay | An in-process relay inside the SDK (`DemoTransport` for wallets, `MockRelay` for solvers) instead of a server | | Solvers (wallet side) | One firm quote from a demo solver key and one indicative quote from a ladder, at the demo relay's reference mid less a spread | | Request flow (solver side) | Generated requests: `steady`, `burst`, `quiet`, or a recorded trace | | Proofs | Mock-proven transactions; nothing is proven | | The chain | No ledger: the fill walks its states without a block | | Time | Compressed; `realtime: true` paces a fill like Preprod | | The wallet | `DemoWallet`: the part of the dApp connector API the SDK calls (balances, addresses, `makeIntent`, `balanceSealedTransaction`, `submitTransaction`) over mock coins | | Keys | Fixed demo keys for the relay and the demo solver, published in the SDK | | Real, not faked | Why it matters | |---|---| | The RFQ envelope | Quotes, ladders, the attestation and the fee declaration are the [MIP draft](/standards/rfq-envelope/)'s objects, signed for real | | The client's and the solver's checks | The SDK runs the same checks it runs against production; a response that fails them fails in demo too | | State names | `reserved → made → submitted → finalized`, as the production relay reports them | | Error shapes | Each scenario (`no_quote`, `paused`, `declined`, `fade`, `reserve_race`, `ws_refused`, `privacy_unavailable`) answers with the production relay's error; the plan is a test comparing them byte for byte against the relay on the devnet | | Reservation | A second accept of the same quote is refused, as on the relay | Every demo response carries a `DEMO` marker, so a demo fill cannot be mistaken for a real one. ## The local devnet (works today) `scripts/stack.sh up` runs the real relay (Elixir), the real solvers, the matcher and the real SDKs against a devnet. What the devnet fakes: | Faked | How | Turn it off | |---|---|---| | The chain | A single node running the ledger WASM (ledger 9) with an indexer-style API, not Midnight's node; short block times | Run on Preprod | | Proofs | Proofs are erased (`PROVER=mock`, the default) | `PROVER=http` with a local proof server proves every leg | | Celestia | A mock of the `mn-swap-v1` namespace for MIP-0006 open orders | — | | KYB, bonds, admission | Seeded fixtures (`scripts/seed-programme.mjs`): devnet entities, bonds by reference, no documents checked | — | | Wallets | Devnet wallets behind the dApp connector API, standing in for a browser extension; seeds derived from public labels | A real wallet on Preprod | | Secrets | Solver keys and tokens derived from public labels, accepted only while the relay is on loopback | — | Nothing else is faked: the relay's checks, the solver programme's rules, fees and fee verification, reservations, the audit chain and the error shapes are the production code. ## Preprod Preprod is Midnight's public test network: real node, real indexer, real proofs and real DUST. Its NIGHT has no value, and our test tokens stand in for the rest: `tsSIT` (shielded) where mainnet has USDM, `tSIT` (unshielded) for a second unshielded token. Nothing is mocked there except the value of the tokens. docs/PREPROD.md records what ran on it. --- # Relay API Source: https://docs.fondaco.network/reference/api/ Status: missing — No apps/relay/priv/openapi.yaml in the repository yet. Routes below are read from apps/relay/lib/si_relay_web/router.ex, last changed 29 October 2026. > **The OpenAPI reference is missing.** The API reference is meant to be generated from an OpenAPI document for `/api/v2` kept in `apps/relay/priv/openapi.yaml` and tested against the router (docs/website.md §7). That file does not exist yet, so there are no request and response schemas here. Until it does: the routes below are read from the relay's router at build time, so they cannot drift from what the relay serves; the request and response shapes are in the integration guide, the [wallet SDK reference](/reference/wallet-sdk/readme/) (`src/types.ts` declares Relay 1.0's shapes as the relay sends them) and, for signed objects, the [RFQ envelope](/standards/rfq-envelope/). ## Hosts | Host | Serves | |---|---| | `api.fondaco.network`, `relay.fondaco.network` | Relay 1.0: `/api/v2` and `/relay/v1` (mainnet) | | `preprod-relay.fondaco.network` | The same on Preprod | | `app.fondaco.network` | The swap and the pages below | Hosted endpoints come with M1 hosting; until then the relay runs on the local devnet stack (`scripts/stack.sh up`, `http://localhost:4000`). See [the wallet quickstart](/quickstart/wallet/). ## Routes ### Wallets and apps — `/api/v2` CORS-enabled for wallets on other origins. Apps send their key as `x-si-app-key`; the client token from a quote goes back as `x-si-client-token` on the accept and on every call for the fill. | Method | Path | Handler | |---|---|---| | `POST` | `/api/v2/rfq` | `RfqController.create` | | `GET` | `/api/v2/rfq/:id` | `RfqController.show` | | `POST` | `/api/v2/rfq/:id/accept` | `RfqController.accept` | | `GET` | `/api/v2/fills/:id` | `FillController.show` | | `POST` | `/api/v2/fills/:id/offer` | `FillController.offer` | | `POST` | `/api/v2/fills/:id/sponsor` | `FillController.sponsor` | | `POST` | `/api/v2/fills/:id/events` | `FillController.event` | | `GET` | `/api/v2/offers` | `OfferController.index` | | `POST` | `/api/v2/offers` | `OfferController.create` | | `DELETE` | `/api/v2/offers/:id` | `OfferController.delete` | | `GET` | `/api/v2/solvers` | `SolverController.index` | | `GET` | `/api/v2/solvers/:id` | `SolverController.show` | | `GET` | `/api/v2/programme/rules` | `SolverController.rules` | | `GET` | `/api/v2/exit-policy` | `NetworkController.exit_policy` | | `GET` | `/api/v2/network` | `NetworkController.show` | ### Fill status stream WebSocket: `?fill=`. The wallet SDK falls back to polling `GET /api/v2/fills/:id`. | Method | Path | Handler | |---|---|---| | `GET` | `/relay/v1/client` | `WebSocketController.client` | ### Solvers Bearer token in the `Authorization` header. The WebSocket protocol (welcome, rfq.request, quotes and ladders, rfq.accept, job.dispatch) is what `RelayClient` in the solver SDK speaks. | Method | Path | Handler | |---|---|---| | `GET` | `/relay/v1/solver` | `WebSocketController.solver` | | `GET` | `/jobs/:id` | `JobController.show` | ### Pages served by the relay On the app host, not the API host. | Method | Path | Handler | |---|---|---| | `GET` | `/` | `PageController.swap` | | `GET` | `/regression` | `PageController.regression` | | `GET` | `/explain` | `PageController.explain` | | `GET` | `/terms` | `PageController.terms` | | `GET` | `/privacy` | `PageController.privacy` | The operator's admin API (23 routes under `/api/v2/admin`, behind the admin allowlist) is not listed: it is not for integrators. --- # Packages Source: https://docs.fondaco.network/reference/packages/ Status: upcoming — Not on npm yet. Published names are @fondaco/*; in the repository they are @si/* workspaces. The SDKs will publish to npm under the `@fondaco` scope. Until the first release they exist only as workspaces in the repository, named `@si/*`, version 0.1.0, marked private. When they publish, the `@si/*` names stay as deprecated aliases for one release (docs/naming.md). | Published as | In the repository | What it is | Reference | |---|---|---|---| | `@fondaco/wallet-sdk` | `@si/wallet-sdk`, `packages/wallet-sdk` | What a wallet or app uses to swap: quote → accept → balance or make an offer → track, with the client's checks of every response; limit offers. Browsers and Node, `fetch` and `WebSocket` only | [TypeDoc](/reference/wallet-sdk/readme/), README | | `@fondaco/solver-sdk` | `@si/solver-sdk`, `packages/solver-sdk` | What a solver installs: the relay client, signed quotes and ladders, the job runner, webhook pricing, maker legs, DUST sponsorship, inventory, the exit policy. Node | [TypeDoc](/reference/solver-sdk/readme/), README | | `@fondaco/connector` | `@si/connector`, `packages/connector` | A thin library over the Midnight dApp connector API 4.0.1: detection, connect, per-wallet profiles, error mapping | README | | `@fondaco/protocol` | `@si/protocol`, `packages/protocol` | Wire formats: MIP-0005 offer files, the MIP-0006 namespace client, the RFQ envelope and the relay messages that carry it, amounts | README | | `@fondaco/ledger-kit` | `@si/ledger-kit`, `packages/ledger-kit` | The ledger-9 WASM, offer inspection (including `checkSolverLeg`, the leg check a wallet passes as `checkLeg`), shielded and DUST wallets. Node | README | ## Using them before they publish From a checkout of the repository: ```bash npm ci && npm run build ``` Each package builds to `packages//dist/`. Code inside the repository imports them by their `@si/*` names (npm links the workspaces); code outside can import the built files by path, as the repository's own scripts do: ```js import { SwapClient } from '../packages/wallet-sdk/dist/src/index.js'; ``` ## Versioning The references on this site are generated from the packages' sources at build time, so they describe the code on the branch the site was built from. When the packages publish, the docs build will be pinned to each SDK release tag, with a version switcher (docs/website.md §7); until then there is one version. --- # MIP draft: RFQ Quote Envelope and Fee Declaration Source: https://docs.fondaco.network/standards/rfq-envelope/ Status: generated — Rendered from docs/mip-draft-rfq-envelope.md, last changed 10 November 2026. Draft, not submitted. The RFQ envelope is unbranded: it is a proposal to the Midnight Foundation's MIP process, not a Fondaco format. Fondaco's relay and SDKs implement it today. This page is the draft as it stands in the repository; the canonical text will be the one in the MIP repository once it is submitted. | Field | Value | |---|---| | MIP | Not yet assigned | | Title | RFQ Quote Envelope and Fee Declaration | | Authors | Not yet named (the draft is unsubmitted) | | Status | Draft | | Category | Standards | | Created | 2026-10-28 | | Requires | MIP-0005: Offer Files; MIP-0006: Peer-to-Peer Atomic Swaps; MIP-0031: Midnight Message Signing | | Replaces | none | | MPS | none | | License | Apache-2.0 | ## Abstract A wallet that wants to swap one Midnight token for another can ask several liquidity providers, called solvers, for a price through a relay, and settle with one of them by merging MIP-0005 offers. This MIP specifies the signed messages of that request-for-quote (RFQ) exchange, so that solvers, relays and wallets written by different people interoperate, and so that each party keeps evidence of what the others committed to. It specifies five things: 1. the **quote** a solver signs: the request it answers, both amounts, the settlement mode, the fees and an expiry; 2. the **ladder**, a signed price curve from which a relay derives indicative quotes; 3. the **attestation** a relay signs over a request, every quote it returned and the quote it ranked best; 4. the **fee declaration**: how a protocol fee and an application fee are computed, and how they are paid as shielded outputs that a verifier can check from their openings; 5. the checks each party makes in the two settlement modes. Signatures are MIP-0031 signatures, and settlement uses MIP-0005 offers unchanged. Transport, solver admission, bonds and penalties, and ranking policy beyond one rule are out of scope. Nothing here changes the ledger, the node or the DApp Connector API. ## Motivation MIP-0005 defines an offer: a proven, imbalanced transaction that anyone holding a complementary one can complete. MIP-0006 defines how a maker publishes an offer for anyone to take. Both start from an offer that already exists, at a price its maker chose alone. Many swaps start earlier, with a question: what will I receive for this amount? A wallet puts that question to several solvers and takes the best answer. Midnight has no standard for the question, for the answers or for the evidence they leave, and MIP-0006 places fee-splitting out of scope. Without one: - every relay defines its own quote format, and a solver must integrate each relay separately; - a quote that does not bind the request's size, fees, network and relay can be presented again where it was never meant to apply; - fees appear only in the settled transaction, when the user can no longer refuse them; - a wallet cannot show afterwards what it was offered, and a solver cannot show what it committed to. This MIP fixes the signed content of the exchange, the fee rules and the settlement checks. It leaves to each relay how the messages travel. ## Specification The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are to be interpreted as described in BCP 14 (RFC 2119 and RFC 8174) when, and only when, they appear in all capitals. ### 1. Roles and scope - The **client** is the user's side: a wallet, or an application working with the user's wallet through the DApp Connector API. - A **relay** receives the client's request, asks solvers, returns their quotes and attests to them. - A **solver** quotes a price and, when its quote is accepted, settles from its own inventory or by merging other offers. **The exchange covered.** This MIP covers an RFQ exchange of one shape: - it runs through a relay. A quote answers a request that a relay issued, and names that relay (§5). A solver that quotes a wallet directly, with no relay between them, is not covered; - the request fixes the amount the user gives, and each quote says what the user receives. A request that fixes the amount the user receives is not covered; - the user gives one token and receives another, at the request's whole size, in one transaction (§10). This MIP says nothing about an exchange of another shape, and does not exclude one. Such an exchange would have payloads and tags of its own (§12). It could use the value forms, the payload encoding and the signature rules of §2 to §4 as they are: only §4's rules on keys are particular to a relay. This MIP specifies the objects the three exchange and what each must check. It does not specify: - how the objects travel (transport, sessions, authentication of connections); - how a relay admits solvers, or what follows when a solver fails to settle; - how a client tells the relay which quote it accepts; - who pays the transaction's DUST fee; - ranking, except the one rule in §8. **What each role implements.** Every role implements the value forms, the payload encoding, the signature rules and the versioning rule (§2 to §4, and §12). The rest depends on the role: | Part | Client | Relay | Solver | |---|---|---|---| | Request terms (§5) | Checks them against what it asked for (§8) | Sets them, the same for every solver it asks and for the client | Copies them into its quotes | | Firm quotes (§6) | Verifies them (§8) | Makes the checks of §6 | Signs them | | Ladders and indicative quotes (§7) | Receives no ladder. An indicative quote reaches it as a quote with `firm: false` | Optional | Optional | | Attestation (§8) | Makes the five checks before it relies on a response | Signs one for every request it answers | Not needed | | Fee declaration (§9) | Checks the fee token and the rates (§8) | Sets the declaration, names the recipients, checks the openings | Computes the fees, pays them as outputs, discloses their openings | | Settlement (§10) | Its steps in each mode it lists in `settlements` | Its steps in each mode it supports | Its steps in each mode it quotes in | - A solver signs firm quotes, publishes ladders, or does both. A solver that only publishes ladders signs no quote and settles by `user_offer` alone. - A relay that takes no ladders forms no indicative quotes, and its clients receive firm quotes only. - A relay that charges no fee still sets a fee declaration: one token of the pair, and both rates zero. The table is a summary. The rules are those of the sections it names. ### 2. Value forms Objects are described as JSON. Every value has one form, and the same text is what enters a signed payload (§3). | Form | JSON type | Text | |---|---|---| | Identifier | string | 1 to 128 characters from `A`–`Z`, `a`–`z`, `0`–`9`, `.`, `_`, `:` and `-` | | Amount | string | The shortest decimal of an integer in `[0, 2^128)`: digits only, no sign, no leading zeros, `0` for zero. Amounts are in a token's base units | | Time | number | An integer in `[0, 2^53)`: milliseconds since the Unix epoch. In a payload, its shortest decimal | | Count | number | An integer in `[0, 2^53)`. In a payload, its shortest decimal | | Rate | number | An integer in `[0, 10000]`: basis points. In a payload, its shortest decimal | | Hex32 | string | Exactly 64 lowercase hexadecimal characters | | Key | string | A `verifyingKey` in the wire form of §4: 64 lowercase hexadecimal characters, or 66 that begin with `02` or `03` | | Network | string | The Midnight network identifier the ledger and the DApp Connector API use (`mainnet`, `preprod`, `preview`, `undeployed`): 1 to 32 characters from `a`–`z`, `0`–`9` and `-` | A JSON number MUST be written as an integer, with no fraction and no exponent. A receiver MUST reject a value that is not in its form, and MUST NOT repair one: it does not trim it, change its case or drop a leading zero. A **token** is a raw token type together with its kind, in the form MIP-0006 uses for a leg: ```ts type TokenKind = 'SHIELDED' | 'UNSHIELDED'; type Token = { token: string; type: TokenKind }; // token: Hex32, the raw token type ``` The kind is part of the token's identity. One raw token type can name both a shielded and an unshielded token, and they are different tokens. ### 3. Payload encoding A payload is a fixed list of fields. Its encoding is the concatenation, in the order listed, of each field as a 4-byte big-endian length followed by that many bytes of UTF-8 text: ``` enc(f1, …, fn) = len32(f1) ‖ utf8(f1) ‖ … ‖ len32(fn) ‖ utf8(fn) ``` Every form in §2 is ASCII. A token contributes two fields, `type` then `token`. The first field of every payload is a tag that names the payload and its version: | Tag | Payload | Signed by | |---|---|---| | `midnight:rfq:quote[v1]` | A firm quote (§6) | The solver | | `midnight:rfq:indicative[v1]` | An indicative quote (§7) | Nobody: it is only digested | | `midnight:rfq:ladder[v1]` | A ladder (§7) | The solver | | `midnight:rfq:attestation[v1]` | An attestation (§8) | The relay | ### 4. Signatures and keys A signature in this MIP is made over a payload `P` (§3) in the way MIP-0031 specifies. The rules taken from MIP-0031 are stated here in full. Beyond them an implementation needs only SHA-256, BIP-340 and ECDSA over secp256k1. **Message.** The signed message is the byte string ``` M = utf8("midnight_signed_message:") ‖ dec(L) ‖ utf8(":") ‖ P ``` - `midnight_signed_message:` is 24 bytes of ASCII, in hexadecimal `6d69646e696768745f7369676e65645f6d6573736167653a`; - `L` is the length of `P` in bytes, and `dec(L)` is its shortest decimal in ASCII digits, with no leading zero, no sign and no separator. **Digest.** `h = SHA-256(M)`: SHA-256 applied once to the whole of `M`, the prefix included. Both schemes sign `h` and nothing else: not `P` without the prefix, not `SHA-256(P)`, and not a further hash of `h`. **Schemes.** There are two, both over the curve secp256k1: - `schnorr_bip340`: signing and verification are those of BIP-340, with the 32 bytes of `h` as BIP-340's message; - `ecdsa_secp256k1_sha256`: ECDSA with `h` as the message digest, which is ECDSA with SHA-256 over `M`. A signer MUST produce `s ≤ (n-1)/2`, where `n` is the order of the secp256k1 group: when its signing routine gives a greater `s`, it replaces it with `n - s`. In hexadecimal, `(n-1)/2` is `7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0`. Neither scheme's nonce derivation is fixed. Two signatures over one payload may differ and both be valid, and a verifier MUST NOT require a particular derivation. **Wire form.** A signature travels as this object: ```ts type Signature = { scheme: 'schnorr_bip340' | 'ecdsa_secp256k1_sha256'; signature: string; // 128 hexadecimal characters verifyingKey: string; // Key: 64 characters (Schnorr) or 66 (ECDSA) }; ``` `signature` and `verifyingKey` are lowercase hexadecimal (`0`–`9` and `a`–`f`), with no `0x` prefix, no separators or whitespace, and no version or tag bytes: | | `schnorr_bip340` | `ecdsa_secp256k1_sha256` | |---|---|---| | `verifyingKey` | 64 characters: the 32-byte x-only public key of BIP-340 | 66 characters: the 33-byte compressed point of SEC 1, which begins with `02` or `03` | | `signature` | 128 characters: BIP-340's `bytes(R) ‖ bytes(s)` | 128 characters: `r ‖ s`, each 32 bytes, big-endian | This is MIP-0031's `Signature` without `data`. The payload is always rebuilt from the object that carries the signature, never taken from bytes sent with it. **Validity.** A signature is **valid** for an object when all of these hold: 1. `scheme` is exactly one of the two literals; 2. `signature` and `verifyingKey` are strings in the wire form for that scheme. No other form is accepted or repaired: not uppercase hexadecimal, not an uncompressed key, not a DER-encoded signature; 3. the scheme's verification succeeds with `h`, where `h` is computed from `M`, and `M` from the payload `P` that this MIP defines for the object's fields. An ECDSA signature with `s > (n-1)/2` is rejected. A verifier MUST support both schemes. The scheme follows from the signer's key and is not negotiated. When a signature is not valid, a verifier MUST NOT try another construction of the message. A valid signature shows that the holder of `verifyingKey` signed the payload, not who that holder is. A party MUST NOT attribute a quote to a solver, or an attestation to a relay, on a key it learned from the same message. - **Relay key.** A relay has one signing key. Its `verifyingKey` is the relay's identity in this MIP (the `relay` field of §5). A client and a solver MUST each obtain it before the exchange, from configuration or an earlier authenticated fetch, and MUST NOT take it from a message they are verifying. - **Solver keys.** A solver registers one or more keys with each relay it quotes through; how is out of scope. A relay MUST accept a solver's signature only under a key registered for that `solverId` when the signature arrives. A relay SHOULD publish the keys registered for each solver, so that others can attribute a quote. **Relation to MIP-0031.** The message, the digest, the schemes and the wire forms above are those of MIP-0031 (its §1, §3 and §5, and step 9 of its §7) as it stood on 10 November 2026, with the status Proposed (commit `3704324` of the MIP repository). This MIP does not use MIP-0031's `data` field or the payload encodings of `signData`, and it does not tie a key to a wallet's address: the rules on keys above take that place. The `[v1]` payloads are bound to the rules as this section states them. A later change to MIP-0031 does not change them, and following one takes new versions of the tags (§12). ### 5. Request terms The request terms are what a quote answers. The relay gives them to every solver it asks and to the client. ```ts type Settlement = 'solver_offer' | 'user_offer'; type FeeDeclaration = { token: Token; protocolBps: number; appBps: number }; // Rates type RequestTerms = { network: string; // Network relay: string; // Key: the relay's verifying key requestId: string; // Identifier, assigned by the relay appId: string; // Identifier of the application the request came through pair: { give: Token; want: Token }; giveAmount: string; // Amount, greater than zero feeDecl: FeeDeclaration; // §9 settlements: Settlement[]; // what the client accepts; not empty }; ``` - `pair.give` is the token the user gives and `pair.want` the token the user receives. They MUST differ in `type` or in `token`. - The relay assigns `requestId` and MUST NOT use one twice. - The relay MUST give the same request terms to every solver it asks and to the client. ### 6. Quote ```ts type Quote = { // copied unchanged from the request terms network: string; relay: string; requestId: string; appId: string; pair: { give: Token; want: Token }; giveAmount: string; feeDecl: FeeDeclaration; quoteId: string; // Identifier solverId: string; // Identifier wantAmount: string; // Amount, greater than zero: what the user receives, after fees settlement: Settlement; // one of the request's `settlements` expiresAt: number; // Time uses: string[]; // Hex32[]: MIP-0005 offer IDs; may be empty firm: boolean; solverSig?: Signature; // present exactly when `firm` is true }; ``` The quote payload `P_quote` has 20 fields: | # | Field | Note | |---|---|---| | 1 | Tag | `midnight:rfq:quote[v1]` when `firm` is true, `midnight:rfq:indicative[v1]` when it is false | | 2 | `network` | | | 3 | `relay` | | | 4 | `requestId` | | | 5 | `quoteId` | | | 6 | `solverId` | | | 7 | `appId` | | | 8 | `pair.give.type` | | | 9 | `pair.give.token` | | | 10 | `pair.want.type` | | | 11 | `pair.want.token` | | | 12 | `giveAmount` | The request's size: a quote cannot be used at another size | | 13 | `wantAmount` | | | 14 | `settlement` | | | 15 | `feeDecl.token.type` | | | 16 | `feeDecl.token.token` | | | 17 | `feeDecl.protocolBps` | | | 18 | `feeDecl.appBps` | | | 19 | `expiresAt` | | | 20 | `uses` | Sorted ascending and joined with `,`. An empty list is an empty field | The **quote digest** is `SHA-256(P_quote)`, written as Hex32. It is taken over `P_quote`, not over the signed message, and identifies the quote's terms and whether it is firm. **Firm quotes.** A solver signs `P_quote` with the tag `midnight:rfq:quote[v1]` and sends the quote with `firm: true`. A firm quote is the solver's undertaking to settle on exactly these terms if the relay records the client's acceptance no later than `expiresAt` by the relay's clock. After `expiresAt` the quote lapses. A solver: - MUST copy the request terms into the quote unchanged; - MUST choose a `quoteId` it has not used for that `requestId`; - MUST list in `uses`, without duplicates, the MIP-0005 offer ID of every offer the settlement will merge besides the user's and its own, and leave it empty when it fills from its own inventory; - MUST NOT sign a payload carrying the tag `midnight:rfq:indicative[v1]`. A relay MUST refuse a firm quote unless all of these hold: 1. `network`, `relay`, `requestId`, `appId`, `pair`, `giveAmount` and `feeDecl` equal the request terms; 2. `settlement` is one of the request's `settlements`; 3. `solverSig` is valid (§4) under a key registered for `solverId`; 4. `expiresAt` has not passed; 5. the request holds no other quote with the same `solverId` and `quoteId`. A quote is identified by `solverId` and `quoteId` together, or by its digest. ### 7. Ladder and indicative quotes A ladder is a solver's standing price curve for one pair at one relay. A relay may answer a request from it without asking the solver. ```ts type Ladder = { network: string; relay: string; solverId: string; pair: { give: Token; want: Token }; seq: number; // Count validUntil: number; // Time points: [string, string][]; // [input, output], both Amounts solverSig: Signature; }; ``` A point `[x, y]` says: for `x` of `pair.give` received, the solver pays out `y` of `pair.want`, before fees. A ladder has 1 to 64 points. Inputs MUST increase strictly and the first MUST be greater than zero. Outputs SHOULD NOT decrease. The ladder payload `P_ladder` has 11 fields: | # | Field | Note | |---|---|---| | 1 | Tag | `midnight:rfq:ladder[v1]` | | 2 | `network` | | | 3 | `relay` | | | 4 | `solverId` | | | 5 | `pair.give.type` | | | 6 | `pair.give.token` | | | 7 | `pair.want.type` | | | 8 | `pair.want.token` | | | 9 | `seq` | | | 10 | `validUntil` | | | 11 | `points` | Each point as `x:y`, joined with `,` in the ladder's order | A relay MUST refuse a ladder unless `solverSig` is valid under a key registered for `solverId`, `network` and `relay` are its own, the points are well formed, `validUntil` has not passed, and `seq` is greater than that of the ladder it holds for that solver and pair. A relay MUST NOT derive a quote from a ladder at or after its `validUntil`, and MAY limit how far ahead `validUntil` lies. **Output at an amount.** For points `(x1, y1) … (xn, yn)` and an input `a > 0`, with `÷` the integer division that truncates toward zero: - if `a ≤ x1`: `out(a) = (y1 × a) ÷ x1`; - if `x(k-1) < a ≤ xk`: `out(a) = y(k-1) + ((yk − y(k-1)) × (a − x(k-1))) ÷ (xk − x(k-1))`; - if `a > xn`: the ladder gives no output. **Indicative quotes.** For a request of size `G` with rates `p = protocolBps` and `a = appBps`, the relay computes what the user would receive, `W`: - when `feeDecl.token` is `pair.give`: `W = out(G − (G × p) ÷ 10000 − (G × a) ÷ 10000)`; - otherwise: `W = (out(G) × 10000) ÷ (10000 + p + a)`. If the ladder gives no output, or `W` is zero, there is no quote. Otherwise the relay forms a `Quote` with `firm: false` and no `solverSig`: the request terms, the ladder's `solverId`, a `quoteId` the relay assigns, `wantAmount = W`, `settlement: 'user_offer'`, an `expiresAt` the relay chooses, and an empty `uses`. A relay MUST NOT form one when the request's `settlements` lack `user_offer`. An indicative quote is the relay's statement of what the solver's ladder gave at that size. It commits the solver to nothing, and the solver MAY decline to settle it. A client cannot check the derivation, because the ladder is not disclosed to it. ### 8. Attestation The relay signs one attestation for each request it answers. It covers the request, every quote returned and the quote ranked best. ```ts type Attestation = { network: string; requestId: string; appId: string; pair: { give: Token; want: Token }; giveAmount: string; feeDecl: FeeDeclaration; quotesReceived: number; // Count quotesDigest: string; // Hex32 best: string | null; // Hex32: a quote digest; null when there are no quotes at: number; // Time: the relay's clock when it signed relaySig: Signature; }; ``` The attestation payload `P_attestation` has 17 fields: | # | Field | Note | |---|---|---| | 1 | Tag | `midnight:rfq:attestation[v1]` | | 2 | `network` | | | 3 | `requestId` | | | 4 | `appId` | | | 5 | `pair.give.type` | | | 6 | `pair.give.token` | | | 7 | `pair.want.type` | | | 8 | `pair.want.token` | | | 9 | `giveAmount` | | | 10 | `feeDecl.token.type` | | | 11 | `feeDecl.token.token` | | | 12 | `feeDecl.protocolBps` | | | 13 | `feeDecl.appBps` | | | 14 | `quotesReceived` | | | 15 | `quotesDigest` | | | 16 | `best` | An empty field when `best` is null | | 17 | `at` | | The relay: - MUST return, with the attestation, every quote it ranked for the request, firm and indicative. `quotesReceived` is their number; - MUST set `quotesDigest` to the SHA-256 of the quotes' 32-byte digests concatenated in ascending bytewise order. With no quotes that is the SHA-256 of the empty string; - MUST set `best` to the digest of the quote it ranks first, or to null when there are none. The quote it names MUST have the greatest `wantAmount` of the quotes returned. Among equal amounts the choice is the relay's; - MUST sign an attestation for every request it answers, including one with no quotes; - MUST NOT sign two different attestations for one `requestId`. A client that relies on a response MUST: 1. check that `relaySig` is valid (§4) under the relay key it already holds; 2. check that `network`, `pair`, `giveAmount` and `appId` are what it asked for, and that `feeDecl` satisfies §9; 3. for each quote returned, check that `relay` is the relay key it holds, that its other request terms equal the attestation's, and that `solverSig` is present and valid exactly when `firm` is true; 4. compute each quote's digest, and check their number against `quotesReceived` and their combination against `quotesDigest`; 5. check that `best` is one of those digests (or null when there are none) and that no quote returned has a greater `wantAmount`. A client that accepts a quote without these checks relies on the relay alone. ### 9. Fee declaration A request carries two fees: a protocol fee for the relay's operator and an application fee for the application named by `appId`. The relay sets `feeDecl`, every quote repeats it, and a solver's signature therefore commits it to the fees. **Fee token.** `feeDecl.token` MUST be `pair.give` or `pair.want`. If either rate is greater than zero it MUST be a `SHIELDED` token. A pair with no shielded token therefore carries no fees under this version. Which of two shielded tokens a relay chooses is its policy; a relay will usually prefer a stable-value token. **Rates.** `protocolBps` and `appBps` are Rates, and their sum MUST NOT exceed 10000. **Amounts.** The fee base `B` is the fee-token side of the fill: - when the fee token is `pair.give`, `B = giveAmount`. The solver receives `giveAmount` and pays both fees out of it; - when the fee token is `pair.want`, `B = wantAmount`. The solver pays the user `wantAmount` and pays both fees in addition. Each fee is `(B × rate) ÷ 10000`, rounded down. In both cases the user gives exactly `giveAmount` and receives exactly `wantAmount`. **Outputs.** Each fee greater than zero is one shielded output of the fee token in the settlement transaction, created for its recipient's coin public key and encrypted to its recipient's encryption public key. A fee of zero has no output. The two fees are separate outputs even when they have the same recipient. **Recipients.** The relay names each fee's recipient to the solver when the quote is accepted. Recipients are not part of the quote: a solver's signature commits it to the amounts, not to who receives them. **Openings.** The solver discloses the opening of each fee output to the relay: ```ts type CoinOpening = { label: 'protocol' | 'app' | 'receive'; type: string; // Hex32: the raw token type nonce: string; // Hex32 value: string; // Amount coinPublicKey: string; // Hex32 }; ``` A verifier computes the Zswap coin commitment of `(nonce, type, value)` for `coinPublicKey`, as the ledger's `coinCommitment` does, and checks that it is among the output commitments of the transaction. It MUST check that `type`, `value` and `coinPublicKey` are the fee token's raw type, the fee amount and the recipient's key, and that no two openings give the same commitment. A fee counts as paid when a transaction carrying its commitment is final on chain. Only a recipient can tell whether an output was encrypted to it. A relay SHOULD give each recipient the openings of its outputs. Openings MUST NOT be published (see Security Considerations). ### 10. Settlement A fill settles as one transaction that merges MIP-0005 offers. Two rules hold in both modes: - **Guaranteed section only.** An offer exchanged under this MIP MUST NOT contain fallible coins, a fallible unshielded offer or a contract call. A part that can fail after the guaranteed section has been applied could leave one side paid and the other not. - **Receivers validate.** MIP-0005 makes the party that receives an offer responsible for validating it, whatever a relay has filtered. A relay SHOULD make the same checks before it passes an offer on; that does not relieve the receiver. Below, the *gives* and *wants* of an offer are its net imbalances as MIP-0006 derives them (*Deriving gives / wants*), each with its token kind. #### `solver_offer` The solver builds a leg that already pays the user, and the user's wallet balances it. 1. When the quote is accepted, the relay gives the solver the user's receiving address and the fee recipients. 2. The solver builds the **leg**, a MIP-0005 offer in which: - the user is paid `wantAmount` of `pair.want`: for an `UNSHIELDED` token, by an unshielded output of exactly that value owned by the user's address; for a `SHIELDED` token, by a shielded output of exactly that value for the user's coin public key, encrypted to the user's encryption public key; - the fee outputs of §9 are present; - there are no gives and exactly one want: `giveAmount` of `pair.give`. The leg has no other imbalance; - an intent carries a TTL late enough for the client to balance and submit it. 3. The solver gives the relay the leg and the openings of the fee outputs. When `pair.want` is `SHIELDED` it also gives the opening of the user's output, labelled `receive`. 4. The relay gives the client the leg and the `receive` opening. 5. The client is the leg's receiver. Before its wallet balances the leg, it MUST: - validate the leg as MIP-0005 requires of a receiver; - check the guaranteed-section rule; - check that the leg pays the user as step 2 says, at the address the client asked for. For a `SHIELDED` token it checks the `receive` opening as §9 describes; - check that the leg's only imbalance is a want of exactly `giveAmount` of `pair.give`; - check that the leg's TTL has not passed. These checks MAY be made by the application or by the wallet. A client that cannot make them MUST NOT list `solver_offer` in a request's `settlements`. 6. The wallet balances the leg, which adds the user's `giveAmount`, and the transaction is submitted. With the DApp Connector API this is `balanceSealedTransaction`. #### `user_offer` The user's wallet makes an offer, and the solver completes it. 1. The client builds an offer with exactly one give, `giveAmount` of `pair.give`, and exactly one want, `wantAmount` of `pair.want`. The output that receives `pair.want` is the user's own and is inside the offer. The offer carries an intent TTL. The client MUST take both amounts, both tokens and its own receiving address from the quote it accepted and from its own request, not from anything the relay sends at acceptance. With the DApp Connector API this is `makeIntent`; the wallet SHOULD use `intentId: 'random'`, so that the offer's intent does not collide with the solver's when the two merge. 2. The relay passes the offer to the solver whose quote was accepted. 3. The solver is the offer's receiver. Before completing it, the solver MUST validate it as MIP-0005 requires, check the guaranteed-section rule, and check that its gives and wants are exactly those of a firm quote it signed for that request and that has been accepted, or are terms it is willing to fill from its ladder. 4. The solver completes the offer with its own inputs and outputs and the fee outputs of §9, and submits the transaction. 5. The solver gives the relay the transaction and the openings of the fee outputs. The relay checks that the transaction contains the user's offer and the fee outputs. The user's offer enforces itself: the user's inputs are spent only in a transaction that also creates the user's output. The client's protection in this mode is step 1. ### 11. Worked example (non-normative) The keys here are test keys: the solver's secret is 32 bytes of `0x1f`, the relay's 32 bytes of `0x2e`. A user gives 25,000,000 base units of a shielded token and wants NIGHT, through a relay on Preprod. Fees are in the give token, at 4 and 12 basis points. A solver answers with a firm quote: ```json { "network": "preprod", "relay": "03d98a7def67e8370118f636620d0be08ed63344df68082b4f2f1844e7ce601483", "requestId": "rq_home-1_0a1b2c3d4e5f", "appId": "example-app", "pair": { "give": { "token": "fecaec9f21656685e2c137e9c62058905c58774b848116eb4a1d158e86eaa219", "type": "SHIELDED" }, "want": { "token": "0000000000000000000000000000000000000000000000000000000000000000", "type": "UNSHIELDED" } }, "giveAmount": "25000000", "feeDecl": { "token": { "token": "fecaec9f21656685e2c137e9c62058905c58774b848116eb4a1d158e86eaa219", "type": "SHIELDED" }, "protocolBps": 4, "appBps": 12 }, "quoteId": "maker-1-0a1b2c3d4e-0", "solverId": "maker-1", "wantAmount": "498820000", "settlement": "solver_offer", "expiresAt": 1793275200000, "uses": [], "firm": true, "solverSig": { "scheme": "ecdsa_secp256k1_sha256", "signature": "8a459c0fb8f19da22087fdb71da93b25a7287ea6b92ac5c87dfe842119ab43bd29add11caf2a0ff38866afd36eb944821c287ec1680545b0d0d3ab17700d63c3", "verifyingKey": "02505f234a81fe3af88625ebda259dbaec44c72b181e2f64735f8b8ec8d7cf7377" } } ``` `P_quote` is 498 bytes: ``` 000000166d69646e696768743a7266713a71756f74655b76315d0000000770726570726f64000000423033643938613764656636376538333730313138663633363632306430626530386564363333343464663638303832623466326631383434653763653630313438330000001672715f686f6d652d315f306131623263336434653566000000146d616b65722d312d306131623263336434652d30000000076d616b65722d310000000b6578616d706c652d61707000000008534849454c44454400000040666563616563396632313635363638356532633133376539633632303538393035633538373734623834383131366562346131643135386538366561613231390000000a554e534849454c4445440000004030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030000000083235303030303030000000093439383832303030300000000c736f6c7665725f6f6666657200000008534849454c444544000000406665636165633966323136353636383565326331333765396336323035383930356335383737346238343831313665623461316431353865383665616132313900000001340000000231320000000d3137393332373532303030303000000000 ``` | Value | | |---|---| | Quote digest, `SHA-256(P_quote)` | `2938957bf995131eee085155c0203cdbdaa3bec26edf24ea9d9cf0566e440236` | | `M` | `midnight_signed_message:498:` followed by `P_quote` | | `h = SHA-256(M)` | `c5822dcf132514cadf82012fc52411a7cc4ae1116a3ce2a057fac9d556b5d306` | The ECDSA signature above uses the deterministic nonce of RFC 6979. Under `schnorr_bip340` the same secret has the verifying key `505f234a81fe3af88625ebda259dbaec44c72b181e2f64735f8b8ec8d7cf7377`, and with 32 zero bytes of auxiliary randomness the signature over the same `h` is `db9df20af8fc3ebe11114d4c9fd3c5da6e87b5aac532fdb6559b616c0b9f61f0e755ca892a3f16657acaa6ab95b71e89818b27d170d85680171ffe3cfdea36c4`. **Fees.** The fee token is the give token, so `B = 25000000`: the protocol fee is 10,000 and the application fee 30,000. The solver receives 25,000,000 and keeps 24,960,000. The user gives 25,000,000 and receives 498,820,000. **Indicative quote.** Another solver, `kernel-1`, has a ladder for the pair with the points `10000000:199000000`, `50000000:990000000` and `200000000:3900000000`. Fees come off the input first, so the relay evaluates the ladder at 24,960,000: ``` out = 199000000 + ((990000000 − 199000000) × (24960000 − 10000000)) ÷ (50000000 − 10000000) = 494834000 ``` The relay forms a quote with `firm: false`, `solverId: "kernel-1"`, `quoteId: "ld-kernel-1-7-5c9e21a0b3"`, `wantAmount: "494834000"`, `settlement: "user_offer"`, `expiresAt: 1793275160000` and the same request terms. Its payload is 506 bytes and its digest is `de2016b8de6d3fb279f785b45a5407a85386d800f3c7b9e05e7d26132f2a62bc`. Had the fee token been the want token, the relay would have evaluated the ladder at 25,000,000, giving 495,625,000, and the user would receive `(495625000 × 10000) ÷ 10016 = 494833266`, with fees of 197,933 and 593,799 paid by the solver in addition. **Attestation.** The relay returns both quotes. The firm quote's digest sorts first, so `quotesDigest` is the SHA-256 of the firm digest followed by the indicative one. The firm quote has the greater `wantAmount` and is `best`: ```json { "network": "preprod", "requestId": "rq_home-1_0a1b2c3d4e5f", "appId": "example-app", "pair": { "give": { "token": "fecaec9f…a219", "type": "SHIELDED" }, "want": { "token": "00000000…0000", "type": "UNSHIELDED" } }, "giveAmount": "25000000", "feeDecl": { "token": { "token": "fecaec9f…a219", "type": "SHIELDED" }, "protocolBps": 4, "appBps": 12 }, "quotesReceived": 2, "quotesDigest": "bf1aa0ef0b7e96663fbe4ae5fc82a655b6690d202718e5d1929afd82aeecacaa", "best": "2938957bf995131eee085155c0203cdbdaa3bec26edf24ea9d9cf0566e440236", "at": 1793275100000, "relaySig": { "scheme": "ecdsa_secp256k1_sha256", "signature": "0e788bed89c773028a04c8a95cdb8e41366d237412494d8ba958808a97f752ea0e2320ee173e66dba0680443bbd9126f0396fc8eb3c1691c9944e7168bbe17d5", "verifyingKey": "03d98a7def67e8370118f636620d0be08ed63344df68082b4f2f1844e7ce601483" } } ``` The token types are shortened here; they are the two of the quote. `P_attestation` is 507 bytes and `h` is `96ccf89715ad0d37b741b956d71b7118cc65a245d2a682ab38f43117ad2cafea`. With no quotes, `quotesReceived` is 0, `best` is null and `quotesDigest` is `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`. ### 12. Versioning Each payload's tag ends in its version, `[vN]`. A change to a payload's fields, their order, their forms or their meaning takes a new version of that tag, and the old and new payloads are then different objects. A change to the signature rules of §4 takes a new version of the tag of every signed payload, so that a tag also names the rules its payload is signed under. A party MUST reject a payload whose tag it does not implement. Adding a tag, or a version of one, takes a MIP that supplements or supersedes this one. How a relay and its solvers and clients agree on which versions they use belongs to the transport. ## Rationale **One shape of exchange.** §1 limits this MIP to the exchange its first implementation runs: through a relay, with the amount given fixed. An exchange between a solver and a wallet alone, and a request that fixes the amount received, are both reasonable, and this MIP excludes neither. It does not specify them because the authors have no implementation to test them against, and a signed payload is costly to change once it is in use. Naming the relay in every quote is also what stops a quote from being presented at another relay (see Security Considerations). **Ladders are optional.** A ladder passes between a solver and a relay and is never shown to a client, so a relay or a solver can do without ladders and nothing the other parties rely on is lost. The ladder is specified so that it has one form at every relay that takes ladders. **MIP-0031 signatures, not a new construction.** Midnight has one specified way to sign off-chain data. Using it means a quote can be checked by any MIP-0031 verifier, a signer can hold its key in anything that implements `signData` (it passes `P` with the `hex` encoding and leaves `data` out of what it sends), and the argument that a signed message cannot be a transaction is MIP-0031's rather than a second one. The alternative was ECDSA over the bare payload with DER signatures and uncompressed keys, which the first implementation of this envelope used. An OpenSSL signer produces a high `s` about half the time, and a verifier that enforces MIP-0003's bound rejects those signatures; the encodings also differ from the ones the ledger and the connector use. **MIP-0003 alone is not enough.** MIP-0003 specifies ECDSA for authorising transactions: the curve, the fixed-width encodings and the bound on `s` that §4 uses. It does not say which bytes a signature over a message covers. A specification built on it alone would have to define the signed message itself, which is the new construction this MIP avoids. **The rules are stated, not only cited.** MIP-0031 is Proposed, and its text may change before it is accepted. Had this MIP only cited it, a change there would change what a signature means here, with nothing in a quote to show which rules it was signed under. §4 therefore states the rules and binds the `[v1]` payloads to them. If MIP-0031 is accepted in another form, new versions of the tags follow it (§12), and the acceptance criteria ask that the two agree. **Length-prefixed fields, not canonical JSON, CBOR or Protobuf.** Midnight has no canonical JSON convention, and the serialization of Compact values is not yet stable or fully specified (MPS-0042). MIP-0031 also signs a plain concatenation rather than a serialization format, which keeps a parser out of every verifier. A fixed list of length-prefixed fields needs no parser and has one encoding. Because the signed bytes do not depend on how an object travels, a relay may carry these objects as JSON, as Protobuf or as anything else. **The quote repeats the request terms.** A quote could bind a hash of the request instead. A quote that carries the terms can be read and checked on its own, and rule 1 of §6 is a simple comparison. **Tags in the form of MIP-0021.** That MIP governs the tags of hash preimages in the ledger and in contracts, which these are not. Its form is followed so that Midnight has one way to name and version a tagged structure. **The network as a plain identifier.** MIP-0008 proposes CAIP-2 identifiers, but it is a draft and says its identifiers are not final. The plain identifier is what the ledger and the connector use today. A later version of the tags can move to CAIP-2. **Tokens as type and raw type.** A raw token type does not say whether a token is shielded, and the two kinds settle differently. MIP-0006 already tags a leg this way. **`wantAmount` after fees.** The user compares one number across quotes, and the number is what arrives. Because the fees are fixed by the request, the greatest `wantAmount` is the best quote, which is what makes the rule on `best` checkable. **Fees as outputs of the settlement transaction.** A fee paid in the same transaction is paid exactly when the swap settles, needs no contract call (MIP-0005 offers merge without one), and can be checked from an opening without revealing the rest of the transaction. MIP-0006 leaves fee-splitting out of scope; this is one way to do it that needs nothing new from the ledger. **A shielded fee token.** Fees in an unshielded token would need no openings, because anyone can read an unshielded output. For the same reason they would mark every fill on chain with the operator's and the application's addresses and with the fee amounts. This version therefore requires a shielded fee token. Pairs with no shielded token are an open question below. **Indicative quotes share the quote's shape.** One digest rule covers both kinds, the attestation commits to them in the same way, and the separate tag means a solver cannot be brought to sign one. **The attestation commits to every quote.** A count alone cannot be checked. A commitment costs one hash, lets a client confirm that what it was shown is what was attested, and gives a solver something to check its own quote against. **No bond reference.** An earlier form of the quote carried a reference to the solver's bond. Bonds are today arrangements between a solver and a relay, and a reference that no third party can resolve adds nothing to a signature. A later version can add one when bonds are on chain. ### Open questions 1. Should acceptance be a message the relay signs, so that a solver can show whether it was asked before `expiresAt`? 2. Should a later version allow fees in an unshielded token, for pairs with no shielded one? 3. Should a relay publish its attestations, or their digests, so that a solver can check that its quote was included? 4. Should there be a common format for the solver keys a relay publishes? ## Path to Active For a Standards MIP that changes nothing on chain, Active means that relays, solvers and clients operated by different parties use this envelope on Midnight mainnet. ### Acceptance Criteria - Test vectors are published with this MIP: valid and invalid cases for each payload, for both signature schemes, for the ladder arithmetic and for the client's checks of §8. - A verifier written by an implementer who is not an author of this MIP accepts every valid vector and rejects every invalid one. - A relay and at least two solvers, from at least two independent implementations, complete fills in both settlement modes on a public Midnight network. - A client implementation makes the checks of §8 and, for `solver_offer`, of §10. - MIP-0005 and MIP-0031 are Accepted, and the rules of §4 agree with MIP-0031 as accepted. ### Implementation Plan 1. Publish the reference implementation and its vectors (see Implementation and Testing). 2. Review the settlement checks with the authors of MIP-0005 and MIP-0006, and the signature profile with the author of MIP-0031. 3. Run a relay with solvers from at least two operators on Preprod, then on mainnet. 4. Have at least one wallet or wallet SDK other than the reference one implement the client checks. ## Backwards Compatibility Assessment This MIP needs no hard fork and no change to the ledger, the node or the DApp Connector API. - Offers are MIP-0005 offers, unchanged. Nothing is added to an offer, to a MIP-0006 blob or to the `mn-swap-v1` namespace, and open orders stay as MIP-0006 defines them. - A client that uses the DApp Connector API needs `balanceSealedTransaction` for `solver_offer` and `makeIntent` for `user_offer`. Both exist in version 4 of the API. - An earlier form of the envelope (tags `si:quote:v2`, `si:ladder:v1` and `si:relay:v1`, DER signatures) is not compatible with this specification, and there is no period in which both are accepted. The reference implementation used it and no longer does; no other deployment is known. ## Security Considerations **What a signature proves.** A valid signature proves that a key signed a payload. Whose key it is comes from elsewhere: the relay's key from the client's or solver's configuration, a solver's keys from the relay's registry. A client that takes the relay's key from the response it is checking has verified nothing. **Replay.** A quote binds the network, the relay, the request and its size, the fees and an expiry, so it cannot be used on another network, at another relay, for another request or at another size. A ladder binds the network, the relay and the pair, and can be presented again by anyone who can deliver it until `validUntil`; a relay SHOULD accept ladders only over the solver's authenticated connection and SHOULD keep `validUntil` short. An attestation binds one request. **Malleability.** ECDSA signatures are malleable without the low-`s` bound, which §4 requires of signers and verifiers. A signature MUST NOT be used as an identifier. Quotes are identified by their digests. **What the relay is still trusted for.** The relay decides which solvers see a request, reports the time of acceptance, registers solver keys, names the fee recipients and may leave a quote out before it ranks. The attestation limits what a relay can later deny: it fixes the request, the quotes it showed and the one it called best. It does not show that every solver was asked or that every quote received was ranked. **`solver_offer` and the user's funds.** Balancing a leg supplies whatever the leg is short of. A leg that wants more than `giveAmount`, or that does not pay the user, takes the user's funds if it is balanced unchecked. The client's checks in §10 are what protect the user. A relay's checks do not replace them: MIP-0005 requires each receiver to validate. **Fallible sections.** A transaction's fallible sections can fail after its guaranteed section has been applied. If a payment or a fee output sat in one, the other side could settle without it. This is why §10 forbids them. **`user_offer`.** The user's offer is safe to hand to anyone: it can only be completed on its own terms. The risk is in building it. A client that builds the offer from terms the relay supplies at acceptance, rather than from the quote it verified, signs whatever the relay asks. **Indicative quotes.** An indicative quote is not a commitment, and a relay ranks it with firm quotes. A client SHOULD show the user whether the quote it is about to accept is firm. **Rounding.** Fees round down, so a fill small enough pays none. The loss is under one base unit per fee per fill. **Privacy.** This exchange happens off chain, and what it adds to the chain is the fee outputs. Each party learns the following. - The relay learns the request (pair, size, application, the user's receiving address) and which transaction settled it. - Every solver asked learns the pair, the size, the application and the fees. It does not need the user's receiving address to quote: a relay SHOULD give that address only to the solver whose quote is accepted. - An opening reveals a fee's value, and with the rate the size of the fill to within `10000 ÷ rate` base units; its commitment ties that to one transaction on chain. Openings go to the relay and to the fee's recipient, and MUST NOT be published. - A fee recipient that receives an opening learns that a fill of about that size happened, and which transaction it was. - Quotes and attestations carry no address of the user. On chain the transaction shows what MIP-0005 and MIP-0006 already describe, plus one or two further output commitments. **Clocks.** `expiresAt` and `validUntil` are judged by the relay's clock. A solver SHOULD allow for the difference between its clock and the relay's when it sets them. ## Implementation No component of Midnight is modified. The parties that implement this MIP are relays, solvers and clients. Their dependencies are MIP-0005 for offers and, for a client that uses a wallet, the DApp Connector API. The signature rules are MIP-0031's, and §4 states them in full. A reference implementation exists in the authors' repository, which is not yet public: | Part | Where | What it implements | |---|---|---| | Envelope, TypeScript | `packages/protocol/src/envelope.ts` | §2 to §9 and the client's checks of §8. Runs in browsers and Node | | Envelope, Elixir | `apps/relay/lib/si_relay/wire.ex` | The same forms and payloads for the relay | | Signature verification, Rust | `crates/ledger-native` (`verify_signature`) | Both schemes, by the ledger's own code, for the relay | | Relay | `apps/relay` | Request terms, the checks of §6 and §7, indicative quotes, the attestation, the fee rules and the checks of legs, user offers and fee openings | | Solver SDK | `packages/solver-sdk` | Firm quotes and ladders, bound to the relay key and network the solver holds; the solver's checks of §10 | | Client | `packages/wallet-sdk`, `packages/ledger-kit` (`checkSolverLeg`) | The checks of §8 on every response; the checks of a `solver_offer` leg of §10 | Where it stops short of this specification: - The relay does not pass fee openings on to their recipients (a SHOULD of §9). - Whether a leg's inputs are still unspent is checked by the client only when the application gives `checkSolverLeg` a way to ask the chain. The relay checks it for every offer. - The wallet SDK cannot decode a transaction in a browser, so the application supplies the leg check. The authors' web page has none and settles by `user_offer` only, as §10 requires. - A JavaScript receiver cannot tell `4.0` from `4` once the JSON is parsed, so it accepts a number written that way; the relay refuses it. A solver registered with an uncompressed key under the envelope's earlier form keeps it: the relay reads such a key as its compressed form. ## Testing The vectors are in the reference implementation at `schemas/test-vectors/rfq-envelope.json`, with their generator, and will be published beside this MIP as `vectors.json`. They contain: - each payload (a quote, a quote with `uses`, a ladder, attestations over no, one and several quotes): the fields, the payload bytes, its digest, `M`, `h`, and a signature under each scheme; - an indicative quote with its payload and digest; - signatures that MUST be rejected: a high `s`, a DER-encoded signature, an uncompressed key, uppercase hexadecimal, a signature over the bare payload, a scheme declared wrongly; - quotes and ladders that are not in the forms of §2: a leading zero, a fraction in a number, a token without its kind, an unshielded fee token, rates above 10000 together; - the valid quote with one field changed, for every field, under the valid quote's signature; - the ladder: outputs below, at, between and above its points, and indicative amounts with the fee token on each side; - responses that fail each of the client's checks in §8; - numbers whose JSON text is not a plain integer, for parsers that keep the difference. The first quote, the indicative quote and the attestation over both are the worked example of §11. Three implementations check the vectors: TypeScript (`@noble/curves`), Rust (the ledger's `base-crypto`) and Elixir (the same Rust code, through a native function). The generator also verifies every valid signature with the Midnight ledger library (ledger 9, release 1.0.1), whose `signData` and `verifySignature`, given `M`, sign and verify as §4 requires under both schemes, and checks that the library rejects the invalid ones it can be asked about. The relay signs with OpenSSL and brings `s` into the lower half; its signatures verify under the ledger's code. The TypeScript implementation was also run in a browser against the vectors. The reference implementation was run end to end on a local network (ledger 9, with proofs erased): swaps settled under both settlement modes, and a response taken off the wire, the relay's attestation and the solvers' firm quotes, verified under the ledger library. It has not been run on a public network in this form. ## References - [MIP-0001: Midnight Improvement Proposal Process](https://github.com/midnightntwrk/midnight-improvement-proposals/blob/main/mips/mip-0001-mip-process.md) - [MIP-0003: ECDSA signature support](https://github.com/midnightntwrk/midnight-improvement-proposals/blob/main/mips/mip-0003-ecdsa-support.md) - [MIP-0005: Offer Files](https://github.com/midnightntwrk/midnight-improvement-proposals/blob/main/mips/mip-0005-offer-files.md) - [MIP-0006: Peer-to-Peer Atomic Swaps](https://github.com/midnightntwrk/midnight-improvement-proposals/blob/main/mips/mip-0006-p2p-atomic-swaps.md) - [MIP-0008: CAIP-2 Network Identifiers for Midnight](https://github.com/midnightntwrk/midnight-improvement-proposals/blob/main/mips/mip-0008-caip-2-network-identifiers.md) - [MIP-0021: Domain-Separation Convention](https://github.com/midnightntwrk/midnight-improvement-proposals/blob/main/mips/mip-0021-domain-separation.md) - [MIP-0031: Midnight Message Signing](https://github.com/midnightntwrk/midnight-improvement-proposals/blob/37043249d3dc47f419cd606dbe7c765befc7f364/mips/mip-0031-message-signing/mip-0031-message-signing.md), at the commit §4 was written from - [MPS-0042: Stable, Versioned and Well-Specified Serialization Format](https://github.com/midnightntwrk/midnight-improvement-proposals/blob/main/mps/mps-0042-serialization-format.md) - [DApp Connector API specification](https://github.com/midnightntwrk/midnight-dapp-connector-api/blob/main/SPECIFICATION.md) - [BIP-340](https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki): Schnorr signatures for secp256k1 - [RFC 6979](https://www.rfc-editor.org/rfc/rfc6979): deterministic ECDSA nonces - [SEC 1 v2.0](https://www.secg.org/sec1-v2.pdf): ECDSA and the compressed form of a point; [SEC 2 v2.0](https://www.secg.org/sec2-v2.pdf): secp256k1 and its order `n` - [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf): SHA-256 - [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) and [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174): requirement key words ## Acknowledgements {To be completed before submission.} ## Copyright Waiver All contributions (code and text) submitted in this MIP must be licensed under the Apache License, Version 2.0. Submission requires agreement to the Midnight Foundation Contributor License Agreement [Link to CLA], which includes the assignment of copyright for your contributions to the Foundation. --- # Threat model Source: https://docs.fondaco.network/security/threat-model/ Status: generated — Rendered from docs/threat-model.md, last changed 27 November 2026. Draft v0.1 — 11 November 2026 — for review before publication (security-hardening §3). Who sees what in a Fondaco swap, what each party can do with it, and what stops the things that should not happen. It describes the current version on Preprod; where mainnet will differ, it says so. ## Scope A swap involves a user's wallet (or an app built on the wallet SDK), the relay, the solvers that quote, the winning solver or the matcher, the Midnight chain, and the edge in front of the relay. The relay never holds funds: a solver settles from its own coins and the wallet signs its own side. Privacy on Midnight is a property of each leg: a shielded token's leg hides amount, coins and the link to the user; an unshielded token's leg (NIGHT) shows the address and the amount. The user's privacy level ([privacy-levels.md](https://fondaco.network/privacy-levels)) constrains the user's legs only; it does not change what the relay or a solver sees. ## Who sees what | Party | Sees | Does not see | |---|---|---| | Anyone reading the chain | Every unshielded output and input: for a NIGHT leg, the user's NIGHT address and amount, and the solver's NIGHT input. The DUST fee paid. That a transaction happened, its nullifiers and commitments. An MIP-0006 open order's imbalances (amounts and token types, not identities) | Shielded amounts, coins and change; the fee amounts and recipients; which shielded inputs belong to whom | | The relay (Fondaco) | The request: pair, size, privacy level, app key, the user's IP and country as the edge reports them. Every quote. For `user_offer`, the offer bytes; for `solver_offer`, the solver's leg. The user's receiver address. Fee-output openings (token, value, recipient). Fill status and the transaction id | The user's keys; the user's shielded balance; any link between the shielded inputs and a person beyond what the request itself carries; a `compliant` disclosure record (stored encrypted, unreadable to the relay) | | A solver that quotes | The pair and the size of each request it is sent, and the privacy level; whether its own quote won | Who asked; the user's IP; other solvers' quotes before the release; the user's address, unless it wins | | The winning solver | The accepted terms and the user's receiver address; the user's offer bytes (`user_offer`) or its own leg and the merged transaction (`solver_offer`) | The user's keys and other coins; the user's IP | | The matcher | The resting offers on the book and the requests it crosses against them | As a solver | | The wallet or app that brought the trade | Everything about its own user's trade, and its statement of fills and fees | Other apps' flow | | The edge provider | IP, country, request paths, and — where TLS terminates at the edge — request and response bodies | Anything the relay itself does not see | ## What each party can do, and what stops it | Party | Could try to | What stops it | |---|---|---| | A solver | Quote and then not deliver (a fade) | The quote is signed and binds until it expires. A fade costs 50 bps of the notional from the solver's bond (5–500 USDM); fulfilment under 95% over 7 days suspends (solver-programme.md) | | A solver | Deliver a leg that pays the user less, or drops the fee outputs | The wallet SDK checks the leg against the quote before the wallet signs; the relay verifies every leg and its fee openings before passing it on, and finds the fee commitments in the finalized transaction. A fee breach costs the penalty cap and suspends | | A solver | Alter the user's offer | An offer file is proven; any change invalidates it. The ledger settles both legs together or neither | | A user or anyone | Post the same coins in many offers | The book takes one offer per input; the second post is refused, on any relay node | | The relay | Tell a wallet a worse quote was the best, or dispatch a job the solver did not agree to | The attestation commits to every quote by digest and is signed with the relay key the SDKs pin; each firm quote carries its solver's signature; solvers check every accept and job against their own quotes | | The relay | Move user or solver funds | It holds none and signs no transaction that spends them | | The relay | Read shielded amounts or link shielded inputs to a person | Zswap's proofs: the relay sees the same public view as the chain, plus what the request itself states | | An attacker who steals the relay signing key | Forge attestations and job dispatches until the key is rotated | Rotation with an overlap window; the key-management decision moves it into a KMS (m1/key-management.md). It still cannot move funds | | An attacker who steals a solver's wallet seed | Spend that solver's inventory | Hot inventory is capped; the rest is held cold (m1/key-management.md). Users' funds are not exposed | | An attacker with the relay database | Read requests, fills, quote snapshots, receiver addresses of unshielded legs, fee records and statements; try to rewrite the record | No keys or seeds are stored there; solver bearer tokens are stored only as hashes; the audit log is hash-chained, so a rewrite shows. Database traffic is TLS-verified outside the devnet | | Someone forging a location | Reach the service from a declined country | The edge strips any incoming country header and sets its own; the relay trusts the header only from configured proxies, and with the location rule on, declines a request that has none | | A flood of requests | Exhaust the relay | Per-IP rate limits at the edge and in the relay, per-IP connection caps, a cap on quote frames per solver, and kill switches the on-call can reach in under a minute | | One region failing | Settle a fill twice or lose one | Only the home region writes money-moving state, under a lease; a home that loses the lease stops its fills; a fill is rebuilt from its record after a failover | ## What is not protected - **The NIGHT leg is public.** Until a shielded form of NIGHT is listed, a buy or sell of NIGHT shows the user's NIGHT address and amount on any explorer. The swap says so before the wallet signs. - **The relay sees the request.** Pair, size, the user's receiver and their IP reach the relay. It keeps request logs for 30 days and fills for as long as the law requires (legal-pages §1). - **A quote can go stale.** A user offer is all-or-nothing and binds until its expiry; it can be cancelled before then only by spending one of its inputs. - **The winning solver learns the counterparty's receiver.** It needs it to pay out. - **Bridged assets carry their bridge's assumptions.** No bridged asset is listed today. Before one is (Nightmode's vault assets, the Cardano rails' tokens), this document will state who holds the bridge's keys and what happens if they misbehave. ## Open items - The key-management option for the relay key (m1/key-management.md §5 recommends a KMS). - The edge provider and where TLS terminates, which decides whether the provider sees bodies. - Ledger viewing keys (Foundation roadmap, Q1 2027), which will move `compliant` disclosure on chain. - Counsel's review of the data list on the privacy page.