@inversealtruism/cairnx-core 0.1.43 → 0.1.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CONVENTION.md CHANGED
@@ -1098,6 +1098,17 @@ mutates that offer object, so an inside-closure read sees the hold; a value snap
1098
1098
  apply-time target scan would not.) The freeze is scoped to `claimTxid !== undefined`, so pre-V28 legacy holds
1099
1099
  keep §16 behavior byte-for-byte.
1100
1100
 
1101
+ *Griefing note (Correction 2).* The freeze lets a buyer who holds a claim block the seller's cancel, and
1102
+ nothing in this version bounds how many holds follow one another. The claim cooldown binds only the address
1103
+ that held last (`claimedBy` is last-write-wins), so two addresses can alternate: each grant buys a hold of 61 to
1104
+ 90 blocks for one Propose fee (0.25 CSD), and a grant that lands in the block where the previous hold lapses
1105
+ also freezes a cancel in that block. Sustained, that costs about 2 to 3 CSD a day at the 120-second block
1106
+ target. While the chain of holds lasts the seller cannot withdraw the offer, and the holder can fill it at its
1107
+ posted terms whenever they become favourable: a free option on a stale price, not a loss of funds already
1108
+ paid. The exposure ends at the offer's expiry, because a hold can never outlive it. A seller who may need to
1109
+ pull an offer should keep its expiry short or quote taker-bound (Lane B, below), which cannot be claimed.
1110
+ `packages/cairnx/test/fclaim-v28.test.ts` case 12 pins both halves (two holders freeze the cancel; one cannot).
1111
+
1101
1112
  **Lane B (taker-bound offers become uncancellable at V28).** A taker-bound (RFQ) answer is a firm quote: at
1102
1113
  `h >= V28`, both cancel paths reject a cancel when `o.taker !== undefined` and the offer was anchored at V28+.
1103
1114
  The maker exits by letting the answer expire (one epoch, about an hour). This eliminates the cancel-reorder half
package/MAKERS.md CHANGED
@@ -1,147 +1,429 @@
1
1
  # Run a CairnX market maker
2
2
 
3
- CairnX has **no AMM and no escrow**; native CSD can't be pooled (CONVENTION §6). Liquidity is whoever
4
- runs a *maker loop*. This guide is everything you need to join as a market maker, end to end. Anyone
5
- may run one, against any token, with their own key. It builds only on the public package
6
- [`@inversealtruism/cairnx-core`](https://www.npmjs.com/package/@inversealtruism/cairnx-core).
3
+ CairnX has no AMM and no escrow; native CSD cannot be pooled (CONVENTION section 6). Liquidity is whoever runs a
4
+ maker loop. This is the one maker guide for the project. Anyone may run a maker, against any token, with their own key.
7
5
 
8
- > Sibling doc: the `cairnx` app repo ships a repo-centric **Maker Kit** (`cairnx/MAKERS.md`) covering
9
- > the reference `mm-bot` implementation, its config, and ops runbook. The two are different documents
10
- > for different audiences by design, not drifted copies of one file.
6
+ What is public and what is not:
11
7
 
12
- ## How the market works (RFQ)
8
+ - Public: the packages [`@inversealtruism/cairnx-core`](https://www.npmjs.com/package/@inversealtruism/cairnx-core)
9
+ (record builders such as `offer`, `bid`, `fclaim`; the resolver; `fillOutputPlan`, `makerRebate`,
10
+ `fclaimEpochFor`; and the `/mm` subpath with the sizing and Sunrise pricing math), `@inversealtruism/csd-tx` and
11
+ `@inversealtruism/csd-client`. A maker loop can be written against these alone.
12
+ - Not public: the reference bot (the `src/mm/` directory of the private `cairnx` service repo). This guide
13
+ describes its behaviour and configuration because it is the normative statement of the safety rails, and so
14
+ that another maker can compare or mirror them. Deployment details of the project's own maker are kept in that
15
+ repo, not here.
13
16
 
14
- Post-v1.3 the CSD-priced market **is** an RFQ loop (CONVENTION §13/§15):
17
+ ## Required reading
15
18
 
16
- 1. A buyer anchors a **bid** — "I'll pay *N* CSD for *X*" (public, on-chain).
17
- 2. A **maker** (you) answers with a **taker-bound offer**: you give *X*, want *N* CSD, `taker` = the
18
- bidder, tagged `bid: <bidId>`. Only that bidder can fill it — so there is **no same-block fill race**
19
- and a losing buyer can never forfeit a payment.
20
- 3. The bidder **fills** it: one atomic transaction pays you and delivers *X*, or nothing happens.
19
+ Sections of [`CONVENTION.md`](https://github.com/InverseAltruism/csd-sdk/blob/master/packages/cairnx/CONVENTION.md):
21
20
 
22
- Open (non-taker-bound) CSD offers are rejected by consensus in `[v1.3, v1.7)` — that race-safety is *why*
23
- making is RFQ. **v1.7** (`V17_HEIGHT`) re-allows open CSD asks but makes them race-safe a second way —
24
- see *Claim-to-fill* below.
21
+ 1. Section 13: bids and the two-step RFQ fulfilment (what you are answering).
22
+ 2. Section 15: why CSD-priced offers must be taker-bound (the buyer-pays-twice race this removes). Your answers are
23
+ fillable only because they name the bidder as `taker`.
24
+ 3. Section 16: fill-before-cancel. A same-block fill beats your cancel; you cannot claw back an answer a bidder is
25
+ already filling.
26
+ 4. Sections 12 and 12b: partial fills (`min`) and `ocancel`, the maker's mass-cancel.
27
+ 5. Sections 6, 10, 14, 19: the honest limits and the fee tables. A maker pays anchor fees only (0.25 CSD per offer or
28
+ `ocancel` anchor, 0.05 CSD per per-offer cancel). The 1.5% protocol fee (`FEE_BPS_V16 = 150`, section 19) and the
29
+ maker rebate ride the fill transaction and are paid by the taker.
30
+ 6. Sections 20 and 31: the open-ask claim lane (see "Open asks and the claim lane" below).
25
31
 
26
- ## Why make a market (v1.6 maker rebate)
32
+ ## How the market works
27
33
 
28
- From **v1.6** (`V16_HEIGHT`), every **bid-answered whole fill** pays the maker a **rebate**, taker-funded,
29
- routed to you (`o.seller`):
34
+ Since v1.3 (`V13_HEIGHT = 31,100`) the CSD-priced market is an RFQ loop:
30
35
 
31
- ```
32
- maker rebate = 0.25 CSD + 0.5% of the trade value # flat reimburses your 0.25 CSD posting cost
33
- ```
34
-
35
- The taker also pays **1.5%** to the protocol treasury (separate). So on a 1 CSD fill you receive the
36
- 1 CSD price **+ 0.255 CSD rebate**. Net maker economics:
37
-
38
- ```
39
- net = Σ rebates earned − Σ anchor (propose) fees spent # 0.25 CSD per offer/cancel you post
40
- ```
41
-
42
- Each *filled* answer reimburses its own posting cost; the 0.5% margin covers answers that don't fill.
43
- Fund a key once and a healthy market funds itself — that's the whole point of v1.6. Live maker P&L for
44
- the reference bot is published at `/cairnx/mm-health` (and shown on the **Makers** tab at `/trade`).
36
+ 1. A buyer anchors a bid: "I will pay N CSD for X". It is public and non-binding.
37
+ 2. A maker answers with a taker-bound offer: `give` is X, `want` is N CSD, `taker` is the bidder, and the record
38
+ carries `bid: <bidId>`. Only that bidder can fill it, so there is no same-block fill race and a losing buyer can
39
+ never forfeit a payment.
40
+ 3. The bidder fills it. One atomic transaction pays the maker and delivers X, or nothing happens.
45
41
 
46
- ## Claim-to-fill (v1.7) — open CSD asks, race-safe
42
+ Open (non-taker-bound) CSD offers are rejected by consensus in `[v1.3, v1.7)`, which is why making is RFQ. From v1.7
43
+ (`V17_HEIGHT = 34,000`) open CSD asks are allowed again and are made race-safe a second way; see "Open asks and the
44
+ claim lane".
47
45
 
48
- From **v1.7** (`V17_HEIGHT`) a maker may post an **open** CSD ask (no `taker`) again. Anyone can buy it,
49
- but a fill is gated on a **claim** — a payment-free `SCORE_CLAIM` attest that reserves the offer for the
50
- first claimer (by consensus order) for a short window (`CLAIM_WINDOW_BLOCKS` ≈ 30 min). Only the live
51
- claimer may then fill, so two buyers never race a payment: a losing same-block claim is a no-op costing
52
- only the 0.05 CSD attest fee. The **maker rebate extends to open-ask fills** — an open ask filled at/after
53
- v1.7 pays you the same `0.25 CSD + 0.5%`, taker-funded.
46
+ ## Maker economics
54
47
 
55
- ⚠ **Buyer safety — claim before you fill.** A fill tx on an open offer you do **not** hold a live claim on
56
- is **rejected as a fill by consensus, but your payment outputs are still spent** (you paid for nothing).
57
- Always, in order:
48
+ From v1.6 (`V16_HEIGHT = 33,600`) a whole fill of resting liquidity pays the maker a rebate, funded by the taker and
49
+ routed to `offer.seller`:
58
50
 
59
- ```js
60
- import { buildClaimTx, buildFillTx, fillPayments } from "cairnx/txbuild"; // reference builders
61
-
62
- // 1. CLAIM — payment-free attest; reserves the open offer for you.
63
- const claim = buildClaimTx({ offerId, utxos, priv });
64
- // submit, then wait for confirmation and re-read state:
65
- // the offer must show claimedBy == yourAddr && tip < claimUntilHeight
66
- // 2. FILL — only once your claim is live. Pay price + treasury fee + the maker rebate to o.seller:
67
- const payments = fillPayments(offer.want.payto, offer.want.value,
68
- { feeBps: offer.feeBps, rebate: true, seller: offer.seller }); // seller REQUIRED when rebate:true
69
- const fill = buildFillTx({ offerId, utxos, priv, payments });
70
51
  ```
71
-
72
- `fillPayments({rebate:true})` throws if you omit `seller` — the rebate must route to `o.seller` or the
73
- resolver no-ops the unmatched output and the fill is lost. A claim is for **CSD-priced open offers only**;
74
- taker-bound offers (the RFQ path above) fill directly with no claim. Grief bounds: an address holds at most
75
- `MAX_ACTIVE_CLAIMS` live claims and cannot re-grab a just-lapsed offer for `CLAIM_COOLDOWN_BLOCKS`.
76
-
77
- ## Quickstart
78
-
79
- ```bash
80
- npm i @inversealtruism/cairnx-core @inversealtruism/csd-client
52
+ makerRebate(value) = 0.25 CSD + ceil(0.5% of value) # REBATE_FLAT + REBATE_BPS, cairnx-core
81
53
  ```
82
54
 
83
- **1. Create a dedicated maker key** (never reuse your main key):
55
+ Resting liquidity means a taker-bound answer to a bid, or an open ask anchored at or after v1.7. Partial fills and
56
+ token-priced fills earn no rebate. The taker also pays the 1.5% treasury fee, separately. On a 1 CSD fill the maker
57
+ receives the 1 CSD price plus 0.255 CSD of rebate. Net maker economics:
84
58
 
85
- ```bash
86
- # any CSD wallet/CLI; you need its 32-byte privkey + 20-byte addr20
59
+ ```
60
+ net = sum of rebates earned - sum of anchor (propose) fees spent
87
61
  ```
88
62
 
89
- **2. Fund it** with the token inventory you'll sell + a little CSD for anchor fees (0.25 CSD per
90
- quote). The reference bot halts loudly below a configurable CSD float so it never silently fails.
91
-
92
- **3. Answer bids.** Each pass: read open bids, compute a robust reference price, and for each bid that
93
- clears `ref + your margin`, anchor a taker-bound offer:
63
+ Each filled answer reimburses its own 0.25 CSD posting cost; the 0.5% covers answers that do not fill. The all-in a
64
+ buyer pays for a CSD value `n` is `rfqFillAllIn(n, feeBps)` (value, the treasury fee at the offer's `feeBps`, 1.5% when
65
+ omitted, rebate and the 0.05 CSD fill attest) and
66
+ `rfqBuyAllIn(n)` (that plus the 0.25 CSD propose that anchors the bid); both are exported from `cairnx-core/mm`.
67
+ A 2 CSD principal is 2.59 CSD all-in for the buyer.
68
+
69
+ ## The maker loop
70
+
71
+ Each pass the reference bot does the following:
72
+
73
+ 1. Reference price: compute a robust reference from trade history (see "Reference price hardening"). A suspicious
74
+ reference is clamped into a safe range and alerted on; it never grief-halts the market.
75
+ 2. Watch open bids: bids where `want.ticker` is your market and `status` is `open`, not yours, not already answered
76
+ (`bid.offers` is empty and there is no in-flight answer of yours), with notional above your dust floor.
77
+ 3. Answer: anchor a taker-bound offer with `give` equal to the bid's `want`, `want.value` at or under the bid's
78
+ `give.value` (at the bid's price, or under it to outcompete other makers), `taker` the bidder, and `bid` the bid
79
+ id so resolvers and UIs link them. Answer only bids whose unit price clears the reference plus your margin
80
+ (`MM_BID_MARGIN_BPS`).
81
+ 4. Short answer expiry: a few epochs (`MM_ANSWER_EXPIRY`, default 2; one epoch is 30 blocks, about an hour), capped by
82
+ the bid's own expiry. The anchor locks your inventory, and a bidder who walks away must release it quickly.
83
+ Expiry is consensus-enforced, so a dead maker degrades gracefully. Taker-bound answers cannot be cancelled once
84
+ anchored (V28); expiry is the only exit.
85
+ 5. Inventory lock accounting: every open answer locks its `give` until fill or expiry. Track outstanding answers (open
86
+ on chain plus in flight, unconfirmed) and cap them (`MM_MAX_BID_ANSWERS`, `MM_LOCK_FRAC`), or one wave of bids locks
87
+ the whole book.
88
+
89
+ A minimal answer, using only public packages:
94
90
 
95
91
  ```js
96
- import { offer } from "@inversealtruism/cairnx-core";
97
- import { CsdClient } from "@inversealtruism/csd-client";
98
-
99
- const client = new CsdClient({ baseUrl: "https://<node-or-proxy>/api/rpc" });
100
- const bids = await fetch("https://<host>/cairnx/bids?status=open").then(r => r.json());
101
-
102
- for (const b of bids) {
103
- if (!worthAnswering(b)) continue; // your pricing: only answer ≥ ref + margin
104
- const rec = offer({
105
- give: b.want, // the token/amount the bidder wants
106
- want: { value: b.give.value }, // the CSD they offered (or less, to compete)
107
- taker: b.bidder, // bind it to the bidder → race-free
108
- bid: b.id, // link it (resolvers/UIs + the rebate)
109
- });
110
- // anchor `rec.uri` / `rec.payloadHash` as a Propose tx (fee ≥ 0.25 CSD), then submit.
111
- // when the bidder fills, you receive: price + (0.25 + 0.5%) rebate; treasury gets 1.5%.
112
- }
92
+ import { offer, epochOf } from "@inversealtruism/cairnx-core";
93
+ import { buildPropose } from "@inversealtruism/csd-tx";
94
+ import { MIN_FEE_PROPOSE } from "@inversealtruism/csd-codec";
95
+
96
+ // bid: one entry of GET /trade/api/cairnx/bids?status=open on the site, or /cairnx/bids on a resolver
97
+ const { record, uri, payloadHash } = offer({
98
+ give: bid.want, // the token and amount the bidder wants
99
+ want: { value: bid.give.value }, // the CSD they offered (or less, to compete)
100
+ taker: bid.bidder, // bind it to the bidder: race-free
101
+ bid: bid.id, // link it; resolvers, UIs and the rebate use this
102
+ });
103
+ const tx = buildPropose({
104
+ domain: "cairnx:v1", payloadHash, uri,
105
+ expiresEpoch: Math.min(epochOf(tip) + 2, bid.expiresEpoch),
106
+ fee: MIN_FEE_PROPOSE, utxos, priv, // your maker key's confirmed UTXOs; submit with CsdClient
107
+ });
113
108
  ```
114
109
 
115
- `offer()` returns `{ record, uri, payloadHash }` — the canonical bytes to anchor. Build the Propose tx
116
- with your CSD tx tooling (e.g. `@inversealtruism/csd-tx` `buildPropose`, or the reference
117
- `buildAnchorTx`), sign with your maker key, and submit to the node `/tx/submit`.
118
-
119
- ## Safety rails the reference bot ships (and you should keep)
120
-
121
- - **Robust reference price** — a volume-weighted median over a trailing window, excluding self-fills /
122
- dust, with a per-pass move clamp and an optional absolute band. A poisoned print can't teleport your
123
- quotes; a suspicious reference *halts the pass loudly* instead of quoting a bad number.
124
- - **Per-UTC-day anchor budget** — a forced quote/cancel storm runs out of fuel, loudly.
125
- - **Min-float halt** — below a CSD threshold the maker stops and surfaces "underfunded" rather than
126
- silently failing submits.
127
- - **Short answer expiry + outstanding-answer cap** — a dead maker degrades gracefully; one wave of bids
128
- can't lock your whole book. Answers expire (consensus-enforced) and release their inventory lock.
129
- - **One anchor per pass, persisted in-flight state** — the substrate has no child-pays-for-parent, so
130
- never chain a second anchor off an unconfirmed change output; a restart can't double-post.
131
- - **Skip on a stale view** — never act when your indexer trails the node tip.
110
+ `offer()` returns the canonical bytes to anchor. `buildPropose` returns `{ ok: false, error }` when the balance cannot
111
+ cover the fee, so check `ok` before submitting.
112
+
113
+ ### One anchor per confirmation
114
+
115
+ The chain has no child-pays-for-parent: do not chain a second anchor off an unconfirmed change output. The reference
116
+ bot posts at most one anchor per pass and persists it (`mm-state.json`: txid, kind, tip) so a restart or a lagging
117
+ indexer cannot double-post. It skips the pass when the indexer and the node are more than `MM_STALE_BLOCKS` apart in
118
+ either direction, or when the indexer's block hash at its tip differs from the node's hash at that height. Never act
119
+ on a stale view of the chain.
120
+
121
+ ## Open asks and the claim lane
122
+
123
+ A maker may also keep open (non-taker) CSD asks on the book. Anyone can buy one, but a fill is gated on a prior claim
124
+ that reserves the offer for the first claimer, so two buyers never race a payment (CONVENTION sections 20 and 31).
125
+
126
+ - Before V28 (`V28_HEIGHT = 60,000`) a claim was a payment-free `Attest` with `score = SCORE_CLAIM (50)`. At or after
127
+ V28 that form is rejected.
128
+ - From V28 a claim is an `fclaim` record carried by a short-expiry `Propose` (0.25 CSD), and the fill is an `Attest`
129
+ (score 100) on the claim's txid, so L0's own expiry rules enforce the hold deadline. A client requests
130
+ `E = fclaimEpochFor(tip, offer.expiresEpoch)`, which gives a hold of 46 to 75 blocks (about 1.5 to 2.5 hours at
131
+ 2 minute blocks). The consensus bound on a hold is 89 blocks.
132
+ - An address holds at most `MAX_ACTIVE_CLAIMS` (3) live claims and cannot re-grab a just-lapsed offer for
133
+ `CLAIM_COOLDOWN_BLOCKS` (15).
134
+ - The maker rebate extends to open-ask fills, so an open ask filled in full pays the same `0.25 CSD + 0.5%`.
135
+
136
+ Buyer safety, which a maker should also understand: a fill on an open offer the buyer does not hold a live claim on is
137
+ rejected as a fill by consensus, but its payment outputs are still spent. Buyer software must claim, wait for the claim
138
+ to bury to a value-scaled depth (`requiredClaimDepth`), and only then fill. Size the fill outputs with
139
+ `fillOutputPlan(offer, pay)` and gate on `kind === "csd-outputs"` (`requiredFillOutputs` and `fillIsSafe` are
140
+ deprecated and behaviour-frozen). Taker-bound offers need no claim.
141
+
142
+ ### Optional: a thin resting ask ladder (`MM_LADDER_LEVELS`, default off)
143
+
144
+ The RFQ loop answers demand: a buyer must post a bid and wait. For a "there is always a price" book, a maker can keep a
145
+ thin set of standing open asks using the claim lane. The reference bot posts them as whole-fill offers (no `min`) so
146
+ each earns the rebate that reimburses its 0.25 CSD anchor. Configure with `MM_LADDER_LEVELS='[[spreadBps,size],...]'`
147
+ (for example `[[200,10],[800,25],[2000,50]]`); empty means pure RFQ. The bot keeps both lanes: the RFQ answer is the
148
+ cheaper path for a taker, and the ladder keeps the book from being empty. Keep it to single-digit levels
149
+ (`MM_LADDER_MAX_OPEN`, default 4): standing offers are what the resolver has to track, and a thin ladder is enough.
150
+
151
+ Two rules the reference bot enforces, and any ladder implementation must follow:
152
+
153
+ 1. Never cancel a claim-held rung. A cancel is beaten only by a same-block fill (section 16); a fill mining one block
154
+ after your cancel is rejected after the buyer's payment has settled to you, which is a buyer burn you must never
155
+ create. The bot refuses to cancel any rung a live hold covers (hold end plus grace plus a 2-block indexer-lag
156
+ margin) and waits it out. Rungs are refreshed with per-offer cancels (a 0.05 CSD attest), never a blanket 0.25 CSD
157
+ `ocancel`, which would also kill your live RFQ answers.
158
+ 2. Price the free option. A claim gives the buyer a free option of at least about 90 minutes to fill at the rung price. On a
159
+ volatile token a claimer can wait out the window and fill only if the market moves past your rung, which is
160
+ stale-quote pickoff. Set spreads at least about twice the token's typical 90-minute move and keep the tight rung
161
+ small. Treat repeated claim-then-lapse as a signal to widen. This is priced, not prevented.
162
+
163
+ A griefer can claim-lock a ladder cheaply (about 0.25 CSD per rung per hold, three claims per address, addresses are
164
+ free). The consequence is degraded discoverability only, with no fund loss, and taker-bound RFQ answers cannot be
165
+ claimed at all, so demand still clears.
166
+
167
+ ## How multiple makers compete
168
+
169
+ Taker-bound answers are race-free by construction: the resolver rejects any fill by a non-taker, so two makers
170
+ answering the same bid cannot burn a buyer. The bidder fills the best answer, and the losers' anchors expire and
171
+ release their locks. Competition is on price (answer under the bid) and latency (answer first within a poll). The only
172
+ money a losing maker spends is its own anchor fee, the cost of quoting. Do not re-answer a bid already answered at or
173
+ below the price you would quote (check `bid.offers`): it is a wasted anchor.
174
+
175
+ ## Reference price hardening
176
+
177
+ A "last trade print" reference is attacker-settable for one anchor fee: self-fill at an arbitrary unit price, then
178
+ harvest the mispriced quotes. The reference implementation (`robustRef` in `src/mm/lib.ts`) uses instead:
179
+
180
+ - A volume-weighted median over a trailing window (`MM_REF_WINDOW`, default 720 blocks, about a day). Weight is CSD
181
+ paid, so many dust prints do not move it.
182
+ - Exclusions: self-fills (buyer equals seller), sub-notional trades (`MM_MIN_TRADE`), and your own buys. Your asks
183
+ being lifted by others is genuine demand and counts.
184
+ - A per-buyer weight cap (`MM_MAX_BUYER_SHARE_BPS`, default 5000) so no single buyer's volume dominates.
185
+ - A buyer-diversity guard (`MM_MIN_REF_BUYERS`, default 3): the reference will not ratchet up unless at least this many
186
+ distinct buyers traded in the window. Two addresses meet a value of 2, so keep it at 3 or more. This is not Sybil
187
+ resistance: distinct addresses are not independent people.
188
+ - A move clamp (`MM_REF_CLAMP_BPS`, default 2000): one step when a new or changed qualifying print is admitted, at most
189
+ once per `MM_REF_CLAMP_BLOCKS` (default 30). Prints that only leave the window do not move the reference, and
190
+ repeating the same tape on a 30 second poll does not walk the price. A stored reference with no saved tape id adopts
191
+ the current tape as its baseline and does not move on adoption.
192
+ - An absolute band (`MM_BAND_LO`, `MM_BAND_HI`), strongly recommended: it is the only hard cap on manipulation. Without
193
+ it, a wash using at least `MM_MIN_REF_BUYERS` addresses can still move the quote by one clamp step each time the tape
194
+ changes and the block window has elapsed. The bot warns at startup when no band is set.
195
+ - Clamp and alert, never grief-halt: a median at or below the floor, a band breach or low buyer diversity clamps the
196
+ reference into a quotable range and logs an alert. Halting was itself griefable, since one at-floor wash could stop
197
+ the market.
198
+
199
+ Paired rails: a per-UTC-day budget for fees that bought nothing back (`MM_FEE_BUDGET`; a quote or cancel storm runs
200
+ out of fuel), a minimum CSD float (`MM_MIN_FLOAT`, `MM_MIN_FLOAT_HARD`) so the maker surfaces "underfunded" instead of
201
+ failing submits silently, and a drift debounce (`MM_DRIFT_BPS` for `MM_DRIFT_PASSES` consecutive passes) before the
202
+ ladder refreshes.
203
+
204
+ ## Key isolation
205
+
206
+ Run the maker on a dedicated key (`MM_KEY_FILE`), funded with the token inventory you are willing to sell plus CSD for
207
+ anchor fees. Never point it at an operator, treasury or personal key: the bot signs autonomously about every 30
208
+ seconds, so a bug, a poisoned reference or a compromised host is bounded to the maker key's balance. The state file is
209
+ written with mode 0600; the quotes and health files are public market data (0644) by design. The bot warns at startup
210
+ if `MM_KEY_FILE` is left at its default.
211
+
212
+ ## Running the reference bot
213
+
214
+ The reference bot reads its configuration from `MM_*` environment variables, or from a JSON file named by `MM_CONFIG`
215
+ with the same keys. Precedence is environment, then file, then default. `MM_DRY=1` builds every transaction and
216
+ submits and writes nothing. The resolver runs in process: the bot scans the indexer feed and replays it canonically, so
217
+ it trusts a remote indexer's raw events but never its prices. Merkle inclusion verification of the feed is off by
218
+ default.
219
+
220
+ ### Configuration reference
221
+
222
+ Amounts named "base" are base units (CSD has 8 decimals). Defaults are those of `loadConfig` in `src/mm/config.ts`.
223
+
224
+ | Variable | Default | Meaning |
225
+ |---|---|---|
226
+ | `CSD_RPC` | `http://127.0.0.1:8789` | Node RPC for UTXOs, tip and submit. Run your own node; the public proxy rate-limits. |
227
+ | `CSD_INDEXER` | `http://127.0.0.1:8793` | Indexer event feed. The public read feed is `https://cairn-substrate.com/explorer/api`. |
228
+ | `CSD_RPC_SECONDARY` | unset (off) | Opt-in dual-submit to a co-located miner mempool, for faster inclusion. |
229
+ | `MM_CONFIG` | unset | Path of a JSON file with the same `MM_*` keys. |
230
+ | `MM_KEY_FILE` | `~/.config/cairn/key.json` | The maker key. Always set a dedicated one. |
231
+ | `MM_STATE`, `MM_QUOTES`, `MM_HEALTH` | `~/.config/cairn/mm-state.json`, `mm-quotes.json`, `mm-health.json` | Persistent state, indicative-quote export, health export. `~` is expanded. Set `MM_STATE` yourself when one machine runs two makers. |
232
+ | `MM_TICKER` | `CAIRN` | The market. |
233
+ | `MM_FLOOR` | `1000000` | Base CSD per display unit; never quote below. |
234
+ | `MM_LEVELS` | `[[0,50],[2500,100],[6000,200]]` | `[spreadBps, size]` RFQ indicative tiers. In Sunrise only the sizes are read. |
235
+ | `MM_LEVELS_FRAC` | `[[0,100],[2500,1000],[6000,2000]]` | Inventory-fraction ask tiers in bps of remaining inventory (1%, 10%, 20%), so a large seed is not a toy book. `[]` falls back to `MM_LEVELS`. |
236
+ | `MM_LADDER_LEVELS` | `[]` (off) | The resting ask ladder. |
237
+ | `MM_LADDER_EXPIRY`, `MM_LADDER_MAX_OPEN` | `8`, `4` | Rung expiry in epochs (must exceed the hold) and cap on standing rungs. |
238
+ | `MM_MIN_FILL` | `5000000` | Partial-fill floor in base CSD (pre-v1.3 ladder offers). |
239
+ | `MM_EXPIRY`, `MM_ANSWER_EXPIRY` | `48`, `2` | Pre-v1.3 ladder and bid-answer expiry, in epochs. |
240
+ | `MM_POLL_MS` | `30000` | Pass interval; a bid should be answered in about 30 seconds. At least 1000. |
241
+ | `MM_REF_WINDOW`, `MM_MIN_TRADE` | `720`, `50000000` | Reference window in blocks and trade-notional floor in base CSD. |
242
+ | `MM_MIN_REF_BUYERS`, `MM_MAX_BUYER_SHARE_BPS` | `3`, `5000` | Distinct buyers required before an upward move; per-buyer weight cap. |
243
+ | `MM_REF_CLAMP_BPS`, `MM_REF_CLAMP_BLOCKS` | `2000`, `30` | One clamp step per admitted print, at most once per this many blocks. |
244
+ | `MM_BAND_LO`, `MM_BAND_HI` | unset | Absolute price band in base CSD per display unit. Set both. |
245
+ | `MM_DRIFT_BPS`, `MM_DRIFT_PASSES` | `1500`, `2` | Ladder-refresh drift threshold and debounce. |
246
+ | `MM_FEE_BUDGET` | `1000000000` | Base CSD per UTC day of fees that bought nothing back. Live and filled answers are not counted; answers that expired unfilled are. Past half of it, addresses with no prior fill on CairnX are answered only for bids of at least `MM_FRESH_MIN_CSD` (reason `budget-fresh-min`); past all of it the bot posts nothing of its own and answers returning buyers only (`budget-returning-only`). Answers to returning buyers are bounded by `MM_MAX_BID_ANSWERS` and `MM_MIN_FLOAT_HARD`, not by this budget. |
247
+ | `MM_FRESH_MIN_CSD`, `MM_FRESH_SLOTS` | `2000000000`, `16` | A bid below the minimum from an address with no prior fill is "fresh small" (in Sunrise the answer price is compared, not the bid). Such answers hold at most `MM_FRESH_SLOTS` of the `MM_MAX_BID_ANSWERS` slots (reason `fresh-slots`). |
248
+ | `MM_BID_MIN`, `MM_BID_MARGIN_BPS`, `MM_MAX_BID_ANSWERS` | `200000000`, `200`, `24` | Bid dust floor (2 CSD), accept margin over the reference, and outstanding-answer cap. |
249
+ | `MM_LOCK_FRAC` | `2500` | Token locked in open answers is at most this many bps of inventory. |
250
+ | `MM_DAY_SELL_CAIRN`, `MM_DAY_SELL_CSD` | `3000000000000`, `50000000000` | Daily sell caps in base units (30,000 CAIRN at 8 decimals, 500 CSD): today's fills plus live answers. In Sunrise an answer whose taker can no longer pay for it is not reserved against them; `MM_LOCK_FRAC`, inventory and `MM_SUNRISE_E` still count every live answer. |
251
+ | `MM_EXCLUDE_ADDRS` | the CairnX treasury address | Comma list; excluded from the reference, from answers and from fills. |
252
+ | `MM_BID_SPREAD_BPS`, `MM_BID_SIZE`, `MM_MAX_OPEN_BIDS` | `800`, `2000000000`, `2` | Thin bid side (Reservoir only). The bid reference is collared at the ask reference so the book cannot cross. `MM_MAX_OPEN_BIDS=0` stops new posts only, not fills of existing bids. |
253
+ | `MM_BID_LEVELS` | `[]` | `[[spreadBps, sizeCsd],...]`; empty means a single `MM_BID_SPREAD_BPS` bid. |
254
+ | `MM_FILL_BIDS` | `1` | `0` stops fills of answers to the maker's bids and new bid posts; cancels still run. The buy side runs only in the Reservoir: the Sunrise posts no bids. Must be 0 or 1. |
255
+ | `MM_DAY_BUY_CSD`, `MM_BID_EXPIRY` | `10000000000`, `24` | An absolute ceiling on the day's bid-side CSD (100 CSD); the buy-back guards below set the working limit. Bid life in epochs; bids are cancellable. |
256
+ | `MM_BUY_SALE_BPS` | `1000` | All-in buybacks over the trailing 7 days at most this share of the maker's 7-day sale proceeds. No recent sales, no buying. |
257
+ | `MM_BUY_LIFE_BPS` | `500` | Buybacks since the start tip at most this share of the sale proceeds since then. |
258
+ | `MM_BUY_SINCE_TIP` | `0` | Lifetime window start; a later Sunrise start recorded in state wins. Set it to the Sunrise start tip so a lost state file cannot widen the window. |
259
+ | `MM_BUY_SELLER_BPS` | `2000` | One seller at most this share of the trailing day's buy budget (the day's buybacks plus the room left, capped by `MM_DAY_BUY_CSD`). A bid only one seller can answer must fit it, so with `MM_DAY_BUY_CSD` 100 CSD a 20 CSD bid (20.70 CSD all-in) is never posted. |
260
+ | `MM_BUY_BID_CAP_BPS` | `8500` | A bid at most this share of the lower of the 7-day volume-weighted sale price and the graduated floor. |
261
+ | `MM_BUY_RESALE_BPS` | `11000` | The ask at least this share of the 7-day all-in average buy cost. Below 10000 is refused. |
262
+ | `MM_BUY_STOP_BPS` | `1000` | No buying past this share of the graduation inventory (the maker's available CAIRN at the graduation pass). |
263
+ | `MM_BUY_PAUSE_BPS` | `7000` | Pause line, as a share of the graduated floor (see below). |
264
+ | `MM_BUY_PAUSE_PARTIES`, `MM_BUY_PAUSE_MIN_CSD` | `3`, `2000000000` | The prints below the pause line must come from this many distinct addresses and sum to this much CSD. |
265
+ | `MM_VERIFY_INCLUSION` | `0` | 1 checks each indexer transaction against the maker's own node. Records younger than 12 blocks are deferred to a later pass, so the maker sees new records about 12 blocks late; `MM_INFLIGHT_TTL` grows by 12 blocks so a held-back post is not signed again, an answer holds its quota and capacity until its last epoch is final (one that expired unfilled frees it 12 blocks after expiry), and a buyer's bid is answered only once it is final with 2 epochs left; a record the node cannot prove fails the pass. It binds each record's outputs, position, height and own fields (proposer, uri, payload hash, expiry and domain; attester, score, confidence and target proposal) to the node's raw transaction, and an indexer row that disagrees fails the pass. The proposer or attester is the key whose signature in the first input verifies over the transaction's sighash, and a body without one fails the pass; this costs about 2.2 ms per record, cached until a reorg clears the cache (cold scan of 2,000 records on the test harness). The node supplies the headers, the tip and the bodies, and the maker checks no PoW and holds no UTXO set, so it cannot check that the signing key owns input 0's coin (a lying node could re-sign input 0 with its own key); the indexer can still withhold or delay records. A record with an expiry past 2^53 is parsed exactly and rejected per record, as with the flag off. Before turning it on in production, run one read-only flag-on scan against the live indexer and node and expect 0 field mismatches. |
266
+ | `MM_INV_LO` | `4000000000000` | Skip new sells when inventory is below this, in base units. Set it to 20% of `MM_SEED_INVENTORY` in base units (display units times 1e8 for an 8-decimal token): a 1M seed gives 200k, a 21M seed gives 4.2M. |
267
+ | `MM_BOOTSTRAP_BID` | off | Post a floor-bootstrap bid when the tape is empty. |
268
+ | `MM_STALE_BLOCKS`, `MM_INFLIGHT_TTL` | `2`, `24` | Indexer-lag skip threshold; blocks an unconfirmed post stays "covering". |
269
+ | `MM_SKEW_WINDOW`, `MM_SKEW_K_BPS`, `MM_SKEW_MAX_BPS`, `MM_SKEW_MAX_DN_BPS` | `720`, `200`, `10000`, `2000` | Flow skew of the ask: net tokens sold over the window (blocks) scaled by `k` against inventory, capped upward and, more tightly, downward so buying inventory back cannot sag the ask. |
270
+ | `MM_BUSY_PATTERNS` | unset (off) | Comma-separated `pgrep -f` patterns; while one matches, the bot skips its pass. For an operator sharing one key between the bot and manual scripts; leave off with a dedicated key. |
271
+ | `MM_DRY` | off | `1` builds everything, submits nothing, writes nothing, logs what would post. |
272
+ | `MM_MODE` | `reservoir` | `reservoir` or `sunrise`. |
273
+ | `MM_SEED_INVENTORY`, `MM_SEED_CSD`, `MM_REFILL_BELOW_BPS` | `197000`, `13700000000`, `2500` | Reservoir well denominator (display units); informational CSD buffer (base); raise `refillDue` when remaining inventory is below this many bps of seed. Refill coin, never CSD. |
274
+ | `MM_MIN_FLOAT`, `MM_MIN_FLOAT_HARD` | `2500000000`, `500000000` | Below `MM_MIN_FLOAT` (25 CSD) bids pause and answers continue; below the hard value (5 CSD) the bot halts. Do not top up CSD: sells replenish it. |
275
+ | `MM_SUNRISE_P0`, `MM_SUNRISE_RATE_BPS`, `MM_SUNRISE_K_SCALED`, `MM_SUNRISE_CAP_MULT` | `500000`, `2`, `1098612`, `8` | Sunrise curve: start price in base CSD per display unit, per-epoch time growth in bps, the curve steepness scaled by 1e6 (default `ln 3`), and the price cap as a multiple of P0. |
276
+ | `MM_SUNRISE_E`, `MM_SUNRISE_DAY_QUOTA`, `MM_SUNRISE_MAX_EPOCHS` | `100000`, `5000`, `2160` | Scheduled emission (display units), per-UTC-day quota with no accrual, and the epoch cap after which the schedule graduates. |
277
+ | `MM_SUNRISE_MAX_ORDER` | `60000` | Largest single Sunrise answer in display units; the day quota caps it too. Published as `sunrise.maxOrder` in base units. |
278
+ | `MM_SUNRISE_BID_BUFFER_BPS` | `200` | Buffer a Swap UI adds to a Sunrise bid above the rung; the answer asks the maker's price, so this is the buyer's tolerance. At most 2000. |
279
+ | `MM_SUNRISE_TARGET_DEPTH_BPS` | `500` | Part of the float target behind `sunrise.skimmable`: this many bps of the remaining Sunrise value. |
280
+ | `MM_ISSUER_ADDR`, `MM_SKIM_LEDGER` | empty, `~/.config/cairn/mm-skim.jsonl` | Skim destination and ledger. The bot never sends CSD itself; see "Skimming CSD". |
281
+
282
+ `MM_SUNRISE_PRICE_LOCK_BLOCKS` and `MM_SUNRISE_PRICE_LOCK_LOOKBACK` are not read any more.
283
+
284
+ ## Reservoir and Sunrise
285
+
286
+ The bot has two operating modes. Reservoir is the default: a fixed coin inventory plus a CSD float. The token page draws
287
+ a well (remaining over seed). When the well is thin, send the bot more coin, not CSD: sells already pay the ask plus the
288
+ maker rebate (buyer to seller, never protocol revenue). Bids pause first when the float is light so answering never
289
+ starves.
290
+
291
+ Sunrise is a published emission schedule for a fresh launch. The curve starts at `MM_SUNRISE_P0`, below the eventual
292
+ reservoir floor. None of it is chain consensus; it lives in local state and in the published quotes file.
293
+
294
+ The sale clock counts distinct chain epochs that contain a mined sale by this maker since `startTip`. The same sale list
295
+ gives the same count whether the maker watched each epoch or caught up later. Several fills in one epoch count once,
296
+ a sale in the launch epoch counts, quiet epochs and buybacks do not. `pricedEpochs` is a high-water of that count: a
297
+ reorg that drops a sale does not reduce a stored clock. `q`, the tokens sold, is high-water marked separately, and so is
298
+ the curve. The price the bot quotes and requires uses `q` plus the tokens in its live answers whose takers can still
299
+ pay, so answers to bids that race each other are priced one after another; the stored high-water is kept on the
300
+ sold-only price, so an answer that expires unfilled does not raise it. In Sunrise the quote reference is the curve; the
301
+ tape does not enter it. Empty windows hold the tape `lastRef` but not the executable ask, because Reservoir flow skew
302
+ expires on its own. A day quota does not accrue.
303
+
304
+ ### Buy-back guards
305
+
306
+ The buy side runs only once the quote mode is `reservoir`. Amounts are base units; shares are bps. The keys are in
307
+ the configuration reference above (`MM_BUY_*`, `MM_VERIFY_INCLUSION`).
308
+
309
+ `MM_DAY_BUY_CSD` stays as an absolute ceiling, and every window uses `MM_REF_WINDOW` (720 blocks) as its day.
310
+
311
+ The pause: new maker bids stop while the filtered tape (the reference's `qualifyTrades` prints over one `MM_REF_WINDOW`,
312
+ per-buyer capped median) is below 70% of the floor, and for one tape window after it last was. One burst of low prints
313
+ stays in the window for a day and the pause runs a day past that, so up to about 2 days. It stops only new maker bids:
314
+ bids already posted stay fillable and the sell side is untouched. Its floor is not sybil resistance: three addresses
315
+ washing 20 CSD between themselves in two prints trigger it for about 1.4 CSD (two bids, two answers, two fill attests,
316
+ and the 1.5% fee on 20 CSD).
317
+
318
+ Each pass publishes these limits under `reservoir.buyBack` in the quotes file, including `boughtBack` with
319
+ `retired: false` (bought-back CAIRN is held for resale).
320
+
321
+ ### Sunrise pricing
322
+
323
+ `sunrise.pricing` is `"integral-v1"`. An answer for `n` tokens asks `sunriseAnswerPrice` from
324
+ `@inversealtruism/cairnx-core/mm`: the integral of the curve from `q` to `q + n`, times `1 + MM_BID_MARGIN_BPS`, and
325
+ never less than that margin over the curve high-water (or `MM_SUNRISE_P0`) per token. The quotes file publishes the
326
+ inputs (`sunrise.qBase` in base units, `sunrise.pricedEpochs`, `sunrise.curveHighWater`), so anyone can recompute the
327
+ price. There are no size tiers: an order pays the curve's rise across its own size. `sunriseOrderCost`,
328
+ `sunriseCurve`, `sunriseTokensFor` and `expScaled` are exported from the same subpath.
329
+
330
+ The bid is a ceiling. The bot answers a bid when its CSD is at least the price, and the answer asks exactly the price
331
+ (`want.value`), so a bid that carries the Swap buffer pays less than it bid. A bid below the price is skipped as
332
+ `below-margin`. The solvency check (price plus the 1.5% fee, the maker fee and the fill attest) and the day-sell CSD
333
+ limits read the answer price. The fresh-address minimum (`MM_FRESH_MIN_CSD`) also reads the maker's price, not the bid;
334
+ otherwise a fresh address could declare 20 CSD, pay about 1 CSD and skip the fresh-slot limits. A signed answer not yet
335
+ on chain counts at the price it asks. One answer is at most `MM_SUNRISE_MAX_ORDER` tokens and at most the day quota; a
336
+ larger bid is `above-top-tier`. The cap bounds how far one answered but never filled bid lifts other buyers' prices while
337
+ it is live.
338
+
339
+ The tape reference does not enter the Sunrise price; it is published as `tapeRef` and still prices the Reservoir. A wider
340
+ `MM_BAND_LO`/`MM_BAND_HI` therefore cannot let wash prints lift the Sunrise ask. `levels` in the quotes file stays for
341
+ older clients: rung sizes come from `MM_LEVELS` cut at the order cap, `totalCsd` is the answer price of `size` tokens,
342
+ `pricePerUnit` is that per whole token rounded up, and `bps` is the rung's premium over `curvePrice`. The per-token price
343
+ rises with order size, so a bid sized on a rung with the Swap buffer clears the price of any smaller order. There is no
344
+ price lock; the bid buffer covers the sale clock moving between sizing and answer, and concurrent answers.
345
+
346
+ The Sunrise is sell-only. While `mode` in the quotes file is `sunrise` the bot posts no bids and fills no answers to its
347
+ own bids, whatever `MM_FILL_BIDS` says; existing own bids are still cancelled when they cross the ask or drift. The
348
+ quotes file then carries `bids: []`, `bidSpreadBps: null`, `bidReason: "sell-only"` and `availability.fillsEnabled:
349
+ false`. `feeRecovery.soldCairnLifetime` and `soldCsdLifetime` count every sale by this key since launch, not just the
350
+ Sunrise (`sunrise.emitted` is the Sunrise figure).
351
+
352
+ ### Launch outcomes
353
+
354
+ Graduation uses one latch. When completed sales `q` reach `MM_SUNRISE_E`, or the chain epoch reaches `startEpoch +
355
+ MM_SUNRISE_MAX_EPOCHS`, the bot stores `graduatedFloor` as the curve at that moment and then quotes with
356
+ `max(graduatedFloor, MM_FLOOR)`. Flipping `MM_MODE` does not roll a latched `graduatedFloor` back; set `MM_FLOOR` to it
357
+ if that is the floor you want. Graduation is not a claim that the market is liquid. Three outcomes:
358
+
359
+ - Sold out: `q` has reached `E`. The curve at that quantity is the latched floor, and `MM_FLOOR` still applies when it is
360
+ higher. `q` counts completed maker sales, while the daily quota counts commitments, and an unused quota unit does not
361
+ carry into the next UTC day. The defaults (`E` 100,000, quota 5,000) need at least 20 days in which every quota unit is
362
+ reserved and then sold. Treat `E` as a gross-sale budget for the launch, and as a lifetime issuance cap only if the
363
+ launch note says so. Compare `E` with the seed inventory and the coin the desk will keep (`MM_INV_LO` defaults to 20% of
364
+ the seed): a desk that holds exactly `E` and keeps that 20% can sell all of `E` only after more coin arrives. After
365
+ graduation Reservoir sells what remains under Reservoir rules; write down whether later sales sit inside the original
366
+ `E` or come from a later inventory decision.
367
+ - Timed out with sales: the epoch cap arrived, `q` is above zero and below `E`. The latched curve is the floor, raised to
368
+ `MM_FLOOR` when the curve is lower. Say the schedule ended; the floor is the issuer's minimum ask after it.
369
+ - Timed out without sales: the epoch cap arrived and `q` is zero. The curve stays at `MM_SUNRISE_P0`. With the defaults
370
+ that is 0.005 CSD per display unit while `MM_FLOOR` is 0.01, so the Reservoir floor steps from 0.005 to 0.01. That step
371
+ is the current rule; keeping the floor at 0.005 after a quiet timeout would be a separate product decision with its own
372
+ published migration. The bot does not clear `lastRef` or reinterpret a stored high-water.
373
+
374
+ ### Skimming CSD
375
+
376
+ Excess CSD is moved out with an operator script (`scripts/mm-skim.mjs` in the reference repo). `--dry` is the default and
377
+ `--live` submits. It refuses amounts above the quotes file's `sunrise.skimmable`: the float above a target of `MM_SUNRISE_TARGET_DEPTH_BPS` of the remaining Sunrise value plus 30 days of `MM_FEE_BUDGET`, never less than twice `MM_MIN_FLOAT`, and only when the float exceeds 1.5 times that target. The
378
+ ledger is `MM_SKIM_LEDGER` (mode 600).
132
379
 
133
380
  ## Honest limits
134
381
 
135
- - CSD has no liquid USD price; "value" math is in base units. CSD↔token is RFQ (2 signatures over a few
136
- blocks), never one-click — that's the no-escrow tradeoff, not a bug.
137
- - Competition is on price and latency: answer under the bid, answer first. The only money a *losing*
138
- maker spends is its own anchor fee — the cost of quoting.
139
- - Self-dealing the rebate is net-negative (you'd still owe the treasury fee + network fee), so it's not
140
- an exploit.
382
+ - CSD has no liquid USD price; value math is in base units. CSD to token is RFQ (two signatures over a few blocks), never
383
+ one click. That is the no-escrow tradeoff, not a bug.
384
+ - Competition is on price and latency: answer under the bid, answer first. The only money a losing maker spends is its own
385
+ anchor fee.
386
+ - Self-dealing the rebate is net-negative: you still owe the treasury fee and the network fee.
387
+ - Distinct buyer addresses are not independent people; the buyer-diversity guard only blocks an upward seed or ratchet.
388
+
389
+ ## Multi-maker quote discovery (design note, not implemented)
390
+
391
+ Today a resolver's `/cairnx/quotes` serves one maker's indicative file. With several makers, discovery would be: each
392
+ maker self-publishes, the chain advertises where, aggregators merge.
393
+
394
+ 1. Each maker publishes a signed indicative-quote JSON at an HTTPS URL it controls (the bot's `MM_QUOTES` export plus an
395
+ identity and a signature):
396
+
397
+ ```json
398
+ {
399
+ "v": 2, "ticker": "CAIRN", "maker": "0x<addr20>",
400
+ "updatedAt": 1765500000000, "pollMs": 30000,
401
+ "marginBps": 100, "minBidCsd": "50000000", "answerCap": 3,
402
+ "ref": "1000000", "decimals": 2,
403
+ "levels": [{ "bps": 0, "size": "50", "pricePerUnit": "1010000", "totalCsd": "50500000" }],
404
+ "inventory": "350", "halted": null,
405
+ "sig": "0x<65B recoverable secp256k1 over sha256(canonical JSON, keys sorted, sig omitted)>"
406
+ }
407
+ ```
408
+
409
+ `sig` recovers to `maker` (the same csd-crypto scheme as anchors), so quotes are self-certifying and the hosting URL is
410
+ not trusted. Quotes are indicative only; the binding act is the on-chain taker-bound answer, so a lying quote file costs
411
+ its maker reputation, never a counterparty's funds.
412
+ 2. The URL is advertised on chain, either through the L3 registry (a `cairnx:makers` list in the csd-registry convention
413
+ with entries `{ addr, url, ticker? }`; resolvers exist in `@inversealtruism/csd-registry`) or through a new cairnx record
414
+ `{"v":1,"t":"maker","url":"https://..."}`, which would need a convention revision.
415
+ 3. Aggregators fetch every advertised URL, verify `sig` against the advertised maker, drop stale quotes (older than about
416
+ three poll intervals) and halted makers, keep the latest per maker, and merge the book by best `pricePerUnit` per size
417
+ tier with attribution.
141
418
 
142
419
  ## Reference
143
420
 
144
- - **Protocol:** [`CONVENTION.md`](https://github.com/InverseAltruism/csd-sdk/blob/master/packages/cairnx/CONVENTION.md) — §13 RFQ, §15 taker-binding, §8/§10 fees, §6 no-escrow.
145
- - **Resolver + record builders:** [`@inversealtruism/cairnx-core`](https://github.com/InverseAltruism/csd-sdk/tree/master/packages/cairnx) (this package) — `offer`, `bid`, `deploy`, `mint`, `parseRecord`, `resolve`, `canonicalState`.
146
- - **Read endpoints:** `/cairnx/bids`, `/cairnx/offers`, `/cairnx/quotes` (indicative ladder), `/cairnx/mm-health` (live maker P&L), `/cairnx/state` (byte-canonical state).
147
- - **Determinism:** the resolver is byte-deterministic and cross-language co-signed (see `conformance/`); two honest resolvers converge — that's the trust model.
421
+ - Protocol: [`CONVENTION.md`](https://github.com/InverseAltruism/csd-sdk/blob/master/packages/cairnx/CONVENTION.md);
422
+ sections 13, 15, 16 (RFQ and taker binding), 19 (fee and rebate), 20 and 31 (claims), 6 (no escrow).
423
+ - Resolver and record builders: [`@inversealtruism/cairnx-core`](https://github.com/InverseAltruism/csd-sdk/tree/master/packages/cairnx):
424
+ `offer`, `bid`, `fclaim`, `deploy`, `mint`, `parseRecord`, `resolve`, `canonicalState`, and `cairnx-core/mm`.
425
+ - Read endpoints on a resolver (on the site under `/trade/api/cairnx/`): `/cairnx/bids`, `/cairnx/offers`,
426
+ `/cairnx/quotes` (the maker's indicative file), `/cairnx/mm-health` (live maker status) and `/cairnx/state`
427
+ (byte-canonical state).
428
+ - Determinism: the resolver is byte-deterministic and cross-language co-signed (see `conformance/`); two honest resolvers
429
+ converge, and that is the trust model.
package/README.md CHANGED
@@ -38,7 +38,7 @@ the operator's resolver does, and disagreement is detectable.
38
38
  ┌───────────────┴───────────────────────────────────────────────┴──────────────┐
39
39
  │ cairnX OVERLAY = resolve(events, tip) → state (THIS PACKAGE) │
40
40
  │ every replayer runs the SAME pure function and gets the SAME bytes: │
41
- │ wallet (SPV, in-browser) · Granus resolver svc · clarvis · cli │
41
+ │ wallet (SPV, in-browser) · reference resolver · clarvis · cli │
42
42
  └───────────────▲────────────────────────────────────────────────────────────────┘
43
43
  │ events (Propose/Attest) + block headers
44
44
  ┌───────────────┴────────────────────────────────────────────────────────────────┐
@@ -61,7 +61,7 @@ flowchart TD
61
61
  end
62
62
  CORE["cairnx-core<br/><b>resolve(events, tip) → state</b><br/>pure · deterministic · this package"]
63
63
  W["Cairn Wallet<br/>in-browser SPV replayer"]
64
- G["Granus resolver svc :8794"]
64
+ G["reference resolver svc :8794"]
65
65
  CL["clarvis · 2nd source"]
66
66
  CLI["cairn-cli"]
67
67
  UIN["CNS UI /names"]