@inversealtruism/cairnx-core 0.1.8

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 ADDED
@@ -0,0 +1,530 @@
1
+ # CairnX Convention v1
2
+
3
+ **Status:** DRAFT v1.0 (2026-06-10) · **Domain:** `cairnx:v1` · **Activation height:** 29 860
4
+
5
+ CairnX is a meta-asset and exchange convention on Compute Substrate (CSD). It defines fungible
6
+ tokens and atomic delivery-versus-payment trades using **only** the chain's existing `Propose`
7
+ and `Attest` transactions — no fork, no new transaction types, no custodian. Token semantics are
8
+ enforced by a **pure, deterministic resolver** that any party can run; independent resolvers
9
+ replaying the same chain converge on identical state.
10
+
11
+ This document is normative. The reference resolver (`src/resolve.ts`) and its conformance suite
12
+ implement exactly what is written here.
13
+
14
+ ---
15
+
16
+ ## 1. Consensus facts relied upon
17
+
18
+ Verified against the node source (`compute-substrate` @ v1.x, 2026-06-10):
19
+
20
+ - **C1.** Every input of a tx signs the same global sighash; tx validity requires all signatures.
21
+ - **C2.** A `Propose`/`Attest` tx's value outputs are unrestricted (only fee floors apply:
22
+ ≥ 0.25 CSD propose, ≥ 0.05 CSD attest). One tx can pay arbitrary addresses *and* carry an app payload.
23
+ - **C3.** `proposer` / `attester` = `hash160(input[0].pubkey)`, stored by consensus.
24
+ - **C4.** `Propose.uri` is a consensus-stored string ≤ **512 bytes** (non-empty); `payload_hash`
25
+ is a consensus-stored 32-byte value (non-zero).
26
+ - **C5.** An `Attest` referencing proposal `P` is **consensus-rejected** once
27
+ `epoch > P.expires_epoch` (epoch = ⌊height/30⌋). Same-block attest-after-propose is valid
28
+ (block apply phases: proposals, then attestations).
29
+ - **C6.** Duplicate `payload_hash` anchors are allowed; proposals are keyed by txid.
30
+ - **C7.** Mempool is first-seen; conflicting spends rejected; no RBF.
31
+
32
+ ## 2. Encoding: records live on-chain in `uri`
33
+
34
+ Every CairnX record is a **canonical JSON** object (UTF-8, recursively sorted keys, compact —
35
+ exactly `canonicalJson` from `@inversealtruism/csd-codec`) whose serialized form MUST be
36
+ ≤ 512 bytes. It is anchored by a `Propose` to domain **`cairnx:v1`** with:
37
+
38
+ - `uri` = the canonical JSON string itself (the record is **fully on-chain**, replicated by
39
+ every node, forever — there is no off-chain content-availability problem);
40
+ - `payload_hash` = `sha256(uri bytes)` (`payloadHash` of the record). Resolvers MUST verify
41
+ `sha256(uri) == payload_hash` and treat mismatching anchors as no-ops;
42
+ - `expires_epoch` — see per-record semantics (for offers it is the consensus-enforced fill window).
43
+
44
+ A record's **actor** is the anchoring tx's consensus `proposer` (C3). There are no off-chain
45
+ signatures in v1: anchoring *from your key* is the authorization.
46
+
47
+ ## 3. Common rules
48
+
49
+ - **Amounts** are strings of decimal integers in base units, `"1"` ≤ x < `2^96`. Resolvers use
50
+ arbitrary-precision integers. `decimals` (0–8) is display-only.
51
+ - **Tickers** match `^[A-Z][A-Z0-9]{2,11}$`.
52
+ - **Addresses** are `0x` + 40 lowercase hex.
53
+ - **Apply order:** events are replayed in consensus order — by block height; within a block,
54
+ all `cairnx:v1` proposals in tx order (`pos`), then all attestations on CairnX offers in tx
55
+ order. (Mirrors the node’s propose/attest phases, C5.) Remaining ties (same height, phase, pos —
56
+ possible only across indexer quirks, never on a real chain) break by **ordinal (code-unit)
57
+ comparison of the lowercase `0x`-hex txid**. Ordinal comparison is the ONLY string ordering
58
+ used anywhere in resolution and serialization — locale-aware collation (e.g. JavaScript's
59
+ `localeCompare`) is forbidden, since it is ICU-dependent and non-reproducible across runtimes.
60
+ - **Invalid = no-op.** A record that fails any check (schema, balance, state) has **no effect**.
61
+ Unknown `t` values and `v ≠ 1` are no-ops (forward compatibility). Invalidity never poisons
62
+ later records.
63
+ - **Activation:** anchors below height **29 860** are ignored. (Set just before the first
64
+ protocol traffic — the domain had no prior use; the live X2 e2e records ARE the genesis.)
65
+ - **Finality:** state derived from blocks < 6 confirmations is provisional (display threshold
66
+ 3, final 6 — matching Cairn's site conventions).
67
+
68
+ ## 4. Records
69
+
70
+ ### 4.1 `deploy` — create a token
71
+
72
+ ```json
73
+ {"v":1,"t":"deploy","ticker":"DUST","name":"Dust","decimals":2,
74
+ "supply":"100000000","mint":"open","mintLimit":"100000"}
75
+ ```
76
+
77
+ | field | rule |
78
+ |---|---|
79
+ | `ticker` | required; **first-anchored deploy of a ticker wins** (C6 + this convention); later deploys of the same ticker are no-ops |
80
+ | `name` | optional, ≤ 32 chars |
81
+ | `decimals` | integer 0–8 |
82
+ | `supply` | max total supply, amount-string |
83
+ | `mint` | `"open"` (anyone) or `"issuer"` (only the deployer) |
84
+ | `mintLimit` | required iff `mint:"open"` — max amount credited per mint record |
85
+
86
+ The deploy's `expires_epoch` SHOULD be far future (e.g. tip-epoch + 100 000); expiry has no
87
+ CairnX meaning for deploys. The **deployer** is the anchoring proposer.
88
+
89
+ ### 4.2 `mint` — issue supply
90
+
91
+ ```json
92
+ {"v":1,"t":"mint","ticker":"DUST","amount":"100000"}
93
+ ```
94
+
95
+ - Token must exist (deploy anchored strictly earlier in apply order; same-block-earlier-pos counts).
96
+ - `mint:"open"`: any proposer; credited `min(amount, mintLimit, remaining supply)`; if remaining
97
+ supply is 0 the mint is a no-op. `amount` defaults to `mintLimit` if omitted.
98
+ - `mint:"issuer"`: proposer MUST equal the deployer; credited `min(amount, remaining)`; `amount` required.
99
+ - Credited to the **proposer**.
100
+
101
+ ### 4.3 `transfer` — move tokens
102
+
103
+ ```json
104
+ {"v":1,"t":"transfer","ticker":"DUST","to":"0x…40","amount":"2500","memo":"…","ts":1781387000}
105
+ ```
106
+
107
+ - Sender = **proposer**. Valid iff sender's *unlocked* balance ≥ `amount` at apply time.
108
+ - `to` may be any address (including sender). `memo` ≤ 64 chars and `ts` are optional
109
+ free fields (also serve to differentiate otherwise-identical records; note two anchors of
110
+ byte-identical transfer content by the same sender are **two transfers** — each anchor is an
111
+ independent authorization by C3).
112
+
113
+ ### 4.4 `offer` — on-chain sell order (locks tokens)
114
+
115
+ ```json
116
+ {"v":1,"t":"offer","give":{"ticker":"DUST","amount":"1000"},
117
+ "want":{"value":"50000000","payto":"0x…40"},"taker":"0x…40","memo":"…"}
118
+ ```
119
+
120
+ - Seller = **proposer**. Valid iff seller's unlocked balance ≥ `give.amount`; on apply, that
121
+ amount is **locked** (cannot be transferred or re-offered).
122
+ - `want.value` — CSD price in base units (string; `"0"` allowed = giveaway). `want.payto`
123
+ defaults to the seller.
124
+ - `taker` (optional) — if present, only this address can fill. **Taker-bound offers are the
125
+ protected path** (see §6).
126
+ - The anchoring proposal's **`expires_epoch` is the offer's validity window** — after it, the
127
+ chain itself rejects fill attempts (C5), and the resolver releases the lock. Offers SHOULD
128
+ use short windows (e.g. tip-epoch + 24 ≈ 1 day).
129
+ - An offer is identified by its **proposal id (txid)**.
130
+
131
+ ### 4.5 `fill` — atomic delivery-versus-payment (an Attest, not a Propose)
132
+
133
+ A fill is an **`Attest` transaction** referencing the offer's proposal id with **`score = 100`**,
134
+ whose **own outputs** pay the seller:
135
+
136
+ - valid iff the offer is open (not filled, not cancelled, not expired) at apply time;
137
+ - if `taker` is set, `attester == taker`;
138
+ - `Σ(outputs of the attesting tx paying want.payto) ≥ want.value`;
139
+ - on apply: the locked `give.amount` moves to the **attester**, the offer closes.
140
+
141
+ Because payment outputs and the attestation are one transaction (C2), **delivery-versus-payment
142
+ is atomic at consensus level**: the buyer cannot pay without (the chain recording the basis for)
143
+ receiving, and the seller's tokens were already convention-locked. The fill costs only the
144
+ attest fee floor (0.05 CSD) plus the payment.
145
+
146
+ The **first valid fill in apply order wins**. `confidence` is ignored (set 100).
147
+
148
+ ### 4.6 `cancel` — close an offer (an Attest)
149
+
150
+ `Attest` on the offer with **`score = 0`**, valid only when `attester == seller`. Releases the
151
+ lock, closes the offer. (Cancel and fill race in apply order like everything else.)
152
+
153
+ Other `score` values on CairnX offers are reserved (no-ops); `score = 1` is reserved for a
154
+ future claim/exclusivity extension (v1.1).
155
+
156
+ ## 5. Resolver state (normative output)
157
+
158
+ ```
159
+ tokens: ticker → { deployId, deployer, name, decimals, supply, minted, mint, mintLimit, height }
160
+ balances: ticker → address → { available, locked }
161
+ offers: offerId → { seller, give, want, taker?, status: open|filled|cancelled|expired,
162
+ expiresEpoch, height, fill?: { buyer, txid, height, paid } }
163
+ events: ordered log of applied/no-op decisions (for explorers & audit — INFORMATIONAL,
164
+ excluded from the canonical surface; its reason strings are diagnostics, not protocol)
165
+ ```
166
+
167
+ **Canonical state (format 2, normative):** the canonical surface is
168
+ `{tipHeight, tokens, balances, names, offers, bids, feesPaid}` — the event log is excluded.
169
+ Serialization is **canonical JSON**: object keys sorted in ordinal (code-unit) order at every
170
+ depth, no insignificant whitespace, UTF-8, all amounts as decimal strings (no floats anywhere),
171
+ booleans/numbers in their shortest JS form. Two resolvers fed the same chain prefix MUST produce
172
+ byte-identical canonical state; `sha256(canonicalState)` at the activation heights is pinned in
173
+ `test/vectors/replay-hashes.json`, and `test/vectors/cases.json` carries language-neutral replay
174
+ vectors a third-party implementation must reproduce. (Format 1 — pre-2026-06-12 — included the
175
+ event log and used locale collation; it is retired.)
176
+
177
+ Determinism requirement: the conformance suite enforces byte-identity, including
178
+ shuffle-invariance of inputs that consensus ordering re-sorts.
179
+
180
+ ## 6. Honest limits & safety
181
+
182
+ - **Convention-enforced, not consensus-enforced.** The chain knows nothing about tokens; it
183
+ enforces (a) record immutability/ordering, (b) payment+attest atomicity in one tx, (c) the
184
+ offer fill window (C5). Everything else is this convention, enforced identically by every
185
+ honest resolver — the trust class of BRC-20/Runes, stated plainly.
186
+ - **Open-offer fill races:** if two buyers fill the same untaken offer, the first in apply
187
+ order wins; the loser's payment still reached the seller. Buyer software MUST default to
188
+ taker-bound (RFQ) flows or warn loudly on open-offer fills. Note the miner orders same-block
189
+ txs **by feerate DESC, then txid ASC** (verified in chain/mine.rs) — a same-block race is
190
+ therefore a fee auction, not arrival order; takers can bid up their fill's fee to win
191
+ deterministically. **v1.3 closes this structurally:** from height 31 100, CSD-priced offers
192
+ must be taker-bound (§15) — a warning cannot hold users back from a full-payment loss, and a
193
+ no-escrow chain has nothing to refund from, so the unsafe shape is removed rather than warned
194
+ about. (Claim windows, floated for v1.1, are impossible for the same reason.)
195
+ - **No unconfirmed chaining (no CPFP).** The mempool only accepts txs whose inputs exist in the
196
+ confirmed UTXO set — you cannot spend change that hasn't been mined. Sequential CairnX actions
197
+ from one key require one confirmation between them; client software must serialize and surface
198
+ this ("next action available after 1 conf").
199
+ - **No native-CSD pools.** CSD itself cannot be locked by convention (real UTXOs obey only
200
+ keys). CairnX trades CSD↔token atomically per-trade; it does not and cannot pool CSD.
201
+ - **Reorgs:** state is a pure function of the chain; resolvers recompute (or roll back) on
202
+ reorg. Treat sub-final fills accordingly.
203
+ - **Spam/squatting:** every record costs ≥ 0.25 CSD (anchor fee floor) — sybil-priced, like
204
+ everything on this chain. Ticker squatting is priced, not prevented; names are
205
+ first-anchored-wins, same as 04-registry's golden rule.
206
+
207
+ ## 7. Wire-level summary for implementers
208
+
209
+ | action | tx type | domain/ref | app fields | outputs |
210
+ |---|---|---|---|---|
211
+ | deploy/mint/transfer/offer | Propose | `cairnx:v1` | `uri` = record JSON, `payload_hash` = sha256(uri), `expires_epoch` per §4 | change only |
212
+ | fill | Attest | offer proposal id | `score=100, confidence=100` | payment to `want.payto` + change |
213
+ | cancel | Attest | offer proposal id | `score=0, confidence=100` | change only |
214
+
215
+ Fee floors: Propose ≥ 25 000 000, Attest ≥ 5 000 000 base units. 1 CSD = 100 000 000 base units.
216
+
217
+ ---
218
+
219
+ # CairnX Convention v1.1 (names + protocol fees)
220
+
221
+ **Activation height: 29 960** (non-retroactive — pre-29 960 token offers/deploys remain fee-free).
222
+
223
+ ## 9. Names — an on-chain-native namespace (ENS/BNS class)
224
+
225
+ CairnX names are a **tradeable, on-chain-native namespace**, distinct from `csd:identity` (which
226
+ binds a handle to a real-world identity via external proof and is NOT for sale). A name here is
227
+ owned purely on-chain — register, hold, point it at an address, transfer, or sell it.
228
+
229
+ - **Charset:** lowercase ASCII only — `^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$`, **1–32 chars**,
230
+ no leading/trailing hyphen (single- and double-character premium names are valid and priced at
231
+ the top of the fee curve). ASCII-only **eliminates the entire homograph/confusable attack
232
+ class** (no Unicode → no look-alikes) and is trivially deterministic for every indexer.
233
+ Reserved: `csd treasury admin official root www support` (`cairn`/`cairnx` are deliberately
234
+ NOT reserved — the operator registered them as ordinary, tradeable names).
235
+ - **`name` (claim):** `{v:1,t:"name",name,salt?}`. Owner = anchoring proposer. **Lowest
236
+ effective-anchor (height, pos, id) wins.** Requires the registration fee (§ below).
237
+ - **Direct claim** (no `salt`): effective height = claim height. Simple, instant; front-runnable.
238
+ - **Commit-reveal** (`salt` present): a prior `ncommit` of `sha256({t:"cairnx:name:commit:v1",
239
+ name,salt,owner})` must exist at a strictly lower height within `COMMIT_MAX_BLOCKS` (8 epochs).
240
+ The reveal **back-dates** its effective height to the commit height — so a committer beats any
241
+ direct-claim squatter who acts in between (the reveal **displaces** them). This is the
242
+ front-run defense (ENS/Namecoin/Runes pattern adapted to a fee-ordered chain).
243
+ - **`ncommit`:** `{v:1,t:"ncommit",commit}` — the commit hash (binds name+salt+owner, so it can't
244
+ be reused by another address). Cheap; the reg fee is paid at reveal.
245
+ - **`nxfer`:** `{v:1,t:"nxfer",name,to}` — owner gifts the name. Clears the resolver record. Fails
246
+ while the name is locked by an open offer.
247
+ - **`nset`:** `{v:1,t:"nset",name,addr}` — owner points the name at an address (the resolver
248
+ record). Reverse resolution (address → names owned) is computed by the resolver.
249
+ - **Selling a name:** an `offer` with `give:{name}` (instead of `{ticker,amount}`). Anchoring it
250
+ **locks** the name (can't transfer/re-offer); a `fill` transfers ownership to the buyer and pays
251
+ the seller (+ protocol fee), atomically, in one tx; cancel/expiry release the lock.
252
+ - **Honest limits (v1.1, superseded):** names were **perpetual** through v1.4 (the registration fee
253
+ was the only anti-squat measure). **Since v1.5 @ height 32 000 every name is a lease** — renewal,
254
+ grace period, and decaying-premium recapture are normative in **§17**. Displacement can unwind a transfer made by a wrongful holder within the commit window
255
+ (rare; deterministic).
256
+
257
+ ## 10. Protocol fees → the CairnX treasury
258
+
259
+ The chain can't enforce a fee in consensus, so — like everything here — fees are **convention-
260
+ enforced via same-tx outputs** (consensus F4: Propose/Attest outputs are unrestricted). A fee-
261
+ bearing action is a **no-op unless its own transaction pays the fee to the treasury address**
262
+ `0x6b09ce74e6070ebc982ab0fb793a211c4d24f016`. Fees accrue as ordinary UTXOs the operator controls.
263
+
264
+ | Action (height ≥ 29 960) | Fee to treasury | Carried by |
265
+ |---|---|---|
266
+ | **trade fill** (token or name) | **1%** of `want.value`, `ceil` | the fill's Attest tx, alongside the seller payment |
267
+ | **token deploy** | **1 CSD** | the deploy's Propose tx |
268
+ | **name registration** (claim/reveal) | **length curve**: ≤3→5, 4→2, 5→1, 6–9→0.5, 10+→0.1 CSD | the claim's Propose tx |
269
+
270
+ Mint, transfer, name-xfer, name-set, offer, commit and cancel pay only the chain's own anchor fee
271
+ (to miners), not a protocol fee. An offer's `want.payto` may not be the treasury (keeps the
272
+ payment and fee output buckets distinct). The resolver tracks `feesPaid` (total observed to the
273
+ treasury) — recomputable by anyone, like all CairnX state.
274
+
275
+ ---
276
+
277
+ # CairnX Convention v1.2 (token⇄token swaps + partial fills + bids)
278
+
279
+ **Activation height: 30 300** (non-retroactive — records using v1.2 shapes anchored below it are
280
+ no-ops; all v1/v1.1 records behave exactly as before at every height).
281
+
282
+ ## 11. Token-priced offers — token⇄token swaps
283
+
284
+ An offer's `want` may now be a **token amount** instead of a CSD value:
285
+
286
+ ```json
287
+ {"v":1,"t":"offer","give":{"ticker":"DUST","amount":"1000"},
288
+ "want":{"ticker":"CAIRN","amount":"50000000","payto":"0x…40"},"taker":"0x…40"}
289
+ ```
290
+
291
+ - `want.ticker` must exist at fill time (checked at apply, like every balance rule); a
292
+ token-priced offer over an unknown ticker simply can never fill until that ticker exists.
293
+ `give.ticker ≠ want.ticker`. `give` may also be a **name** (sell a name for tokens).
294
+ - Anchoring locks `give` exactly as in v1 (§4.4). `want.payto` (default seller) receives the
295
+ want-tokens; it may not be the treasury.
296
+ - **Fill** = an `Attest` with `score = 100` **and `confidence = 1 000 000`** whose attester's
297
+ *unlocked* `want.ticker` balance at apply time is ≥ `want.amount + fee`, where
298
+ `fee = ceil(1% × want.amount)` **in kind**. On apply, atomically: debit the attester
299
+ `amount + fee`; credit `payto` `amount`; credit the treasury `fee`; deliver `give` to the
300
+ attester; close the offer.
301
+ - **Why the `confidence = 1 000 000` marker:** attestation is this chain's native signaling
302
+ mechanism — people attest proposals to score them. A plain `score=100` attest on a
303
+ token-priced offer must NOT silently spend the attester's tokens. The magic confidence value
304
+ (impossible in normal signaling, which uses 0–100) makes a token-debiting fill an explicit,
305
+ signed opt-in. CSD-priced fills don't need it: their payment outputs already prove intent.
306
+ - Insufficient balance / missing marker / taker mismatch → **no-op, offer stays open**.
307
+ - Token-priced offers are **whole-fill only** in v1.2 (an Attest carries no amount channel;
308
+ partial fills below use the CSD payment itself as the amount signal).
309
+ - The buyer's tokens are **not pre-locked** — only the maker locks inventory. A fill that races
310
+ the buyer's own same-block transfer resolves deterministically by apply order (proposals
311
+ before attests, §3).
312
+
313
+ ## 12. Partial fills (CSD-priced token offers)
314
+
315
+ A CSD-priced **token** offer may opt into partial fills with `min`:
316
+
317
+ ```json
318
+ {"v":1,"t":"offer","give":{"ticker":"DUST","amount":"1000"},
319
+ "want":{"value":"50000000"},"min":"5000000"}
320
+ ```
321
+
322
+ - `min` (amount-string, `1 ≤ min ≤ want.value`) = the smallest payment a fill may make —
323
+ the maker's anti-dust/anti-grief floor. Presence of `min` ⇒ the offer is partially fillable.
324
+ `min` is invalid on name offers and on token-priced offers.
325
+ - A partial fill is a normal fill (Attest `score=100` + same-tx payment of `X` to `payto` +
326
+ fee) where `min ≤ X`. Let `x = min(X, wantRemaining)` (overpayment is capped — it buys no
327
+ more than what remains). Exception: when `wantRemaining < min`, `X ≥ wantRemaining` is
328
+ allowed (the tail is always buyable).
329
+ - **Delivery (cumulative pro-rata, no rounding loss):**
330
+ `deliveredCum' = floor(give.amount × paidCum' / want.value)` — each fill delivers
331
+ `deliveredCum' − deliveredCum`. The final fill (`paidCum' = want.value`) therefore delivers
332
+ exactly the undelivered remainder; rounding dust never strands in the lock.
333
+ - `fee = ceil(1% × x)` to the treasury in the same tx, per fill.
334
+ - The offer stays `open` until `paidCum = want.value` → `filled`. Cancel/expiry release the
335
+ undelivered remainder to the seller; completed partial fills stand.
336
+ - Each fill is appended to the offer's `fills[]` (buyer, txid, height, paid, got, fee).
337
+ - Open partially-fillable offers race like v1 open offers (fee auction, §6) — but losing a
338
+ race now only costs the loser the *overlap*: their payment still buys whatever remained.
339
+ Wallets must still warn on open-offer fills.
340
+
341
+ ## 12b. `ocancel` — mass-cancel (maker's kill switch)
342
+
343
+ ```json
344
+ {"v":1,"t":"ocancel","ticker":"DUST"}
345
+ ```
346
+
347
+ Cancels **all of the proposer's open offers anchored strictly earlier in apply order**, releasing
348
+ their locks — optionally filtered to one `give` asset (`ticker` or `name`, at most one). Without
349
+ cheap mass-cancel a market maker cannot keep a ladder of quotes honest (per-offer cancel = one tx
350
+ each — the 0x `minValidSalt` lesson). Anchor an `ocancel`, then re-post the fresh ladder — even in
351
+ the same block (proposals apply in tx order, so a later-pos ladder survives an earlier-pos cancel).
352
+
353
+ **Self-fills** (attester == seller) are **valid** and pay the protocol fee like any fill — wash
354
+ trading is self-punishing, and a no-op rule would just complicate determinism. **Fill races on
355
+ open offers** (§6) keep their v1 semantics; note that partial fills soften the loss — a racing
356
+ fill is clamped to whatever remainder exists, so its payment is only fully wasted when the
357
+ remainder is zero. Takers who need atomic certainty use whole-fill offers and taker-binding.
358
+
359
+ ## 13. Bids — non-binding buy-side intents
360
+
361
+ CSD cannot be locked by convention (§6), so a *binding* buy order is impossible — the buy side
362
+ of the book is instead built from **bids**, on-chain discovery records:
363
+
364
+ ```json
365
+ {"v":1,"t":"bid","want":{"ticker":"DUST","amount":"1000"},"give":{"value":"40000000"},"memo":"…"}
366
+ ```
367
+
368
+ - "I will pay `give.value` CSD (>0) for `want`" — `want` is a token amount or `{name}`.
369
+ The **bidder** = proposer. `expires_epoch` = the bid's validity window. Cancel = Attest
370
+ `score=0` by the bidder. **Non-binding**: nothing is locked; honoring it is reputational.
371
+ - **Fulfillment** is the two-step RFQ: the asset owner anchors a **taker-bound offer**
372
+ (`taker = bidder`, price ≤ bid) optionally tagged `"bid":"<bidId>"`; the bidder's client
373
+ detects the responding offer and fills it atomically. Two anchors + one fill — the
374
+ scriptless ceiling for buy-side flow.
375
+ - The resolver tracks `bids` (open/cancelled/expired) and links responding offers
376
+ (`offer.bid` → `bid.offers[]`). A bid whose linked offer is **filled by the bidder** is
377
+ marked `done` (purely informational).
378
+ - No protocol fee on bids (the anchor fee to miners is the spam price; the trade fee is paid
379
+ when the responding offer fills).
380
+
381
+ ## 14. v1.2 fee table (additions)
382
+
383
+ | Action (height ≥ 30 300) | Fee to treasury |
384
+ |---|---|
385
+ | token-priced fill | **1% in kind** (`ceil`, of `want.amount`, debited convention-side from the buyer) |
386
+ | partial fill | **1%** of each fill's effective payment `x`, `ceil`, same-tx CSD output |
387
+ | bid / bid-cancel | none (anchor fee only) |
388
+
389
+ In-kind fees accrue to the treasury **as token balances** (visible in `balances`); `feesPaid`
390
+ continues to count only CSD fees. The treasury spends its token balances like any holder
391
+ (transfer/offer records signed by the treasury key).
392
+
393
+ ---
394
+
395
+ # CairnX Convention v1.3 (mandatory taker-binding for CSD-priced offers)
396
+
397
+ **Activation height: 31 100** (non-retroactive — all records and fills below it behave exactly
398
+ as before at every height).
399
+
400
+ ## 15. CSD-priced offers must be taker-bound
401
+
402
+ The open (non-taker-bound) CSD-quoted fill was the **one structurally unsafe shape** in the
403
+ convention: a fill pays `want.value` as a real, irreversible CSD output to the seller in the
404
+ same tx that attests. If two buyers fill the same offer in one block, the apply-order winner
405
+ gets the asset and the **loser's full payment is already confirmed to the seller** — the seller
406
+ is paid twice and delivers once. The substrate has no escrow (§6), so no claim window, partial
407
+ fill, or warning can refund the loser. The only safe shapes are the two that already exist:
408
+ **taker-bound (RFQ) fills** — the resolver rejects non-takers, so a wallet never builds the
409
+ losing payment — and **token⇄token fills**, where both legs are convention-ledger debits and a
410
+ lost race is a guaranteed no-op.
411
+
412
+ From height **31 100**:
413
+
414
+ - **`offer` anchor rule:** a CSD-priced offer (`want.value`, token *or* name give) without a
415
+ `taker` field is a **no-op** (`v1.3: CSD-priced offers must be taker-bound`). Token-priced
416
+ (token⇄token) offers are unaffected and remain open to any filler.
417
+ - **`fill` rule:** a `SCORE_FILL` attest on **any** CSD-priced offer with no `taker` — including
418
+ offers anchored before activation — is a no-op. Pre-v1.3 open CSD offers therefore become
419
+ unfillable at activation (sellers cancel/`ocancel` or let them expire; locked give releases as
420
+ usual). This is deliberately strict: the loser-pays race is only dead if no open CSD fill can
421
+ ever succeed.
422
+ - **Buy-side flow for CSD pricing** is the v1.2 RFQ loop (§13): bid → seller answers with a
423
+ taker-bound offer (partial-fillable allowed; `min` works as in §12) → bidder fills race-free.
424
+ One extra anchor versus v1, in exchange for "a buyer can never lose more than the anchor fee."
425
+ - **Name sales are displacement-proof — two rules acting together:**
426
+ 1. **Age gate (offer anchor):** a name `offer` (CSD- *or* token-priced) is a no-op unless the
427
+ name's basis is a fill (`viaFill`, below) or its effective claim is **strictly older than
428
+ `COMMIT_MAX_BLOCKS`**. Every dangerous commit (one back-dating below the current claim) has
429
+ a reveal deadline of `commitHeight + COMMIT_MAX_BLOCKS < claimEffHeight + COMMIT_MAX_BLOCKS`,
430
+ so by the earliest legal offer — and therefore any fill — every lurking back-dated reveal
431
+ has either fired (displacing the *claimant*, which IS the §9 front-run defense, loss
432
+ bounded to the registration fee) or expired.
433
+ 2. **Fill immunity:** a name `fill` (CSD- or token-priced) marks the record **`viaFill`** and
434
+ re-stamps `claimId/height/effectiveHeight/pos` to the fill itself. Displacement arbitrates
435
+ **claim-vs-claim only** — a `viaFill` record can never be displaced by any reveal. (Without
436
+ the age gate, immunity alone would let a front-run squatter launder a name through a quick
437
+ flip; the gate makes that impossible, so the two rules are sound only together.)
438
+
439
+ Net effect: an innocent buyer of a completed sale can never lose the name to a back-dated
440
+ commit-reveal, and the §9 claim-time front-run defense is fully preserved. Residuals
441
+ (documented): a **claim-based** record younger than the commit window is still displaceable —
442
+ that is the defense working as designed; `nxfer` (a gift, no payment) does **not** re-stamp or
443
+ immunize — the recipient inherits the giver's basis; and `viaFill` records re-sell with no
444
+ aging delay (their basis cannot be back-dated under). Offers anchored *before* v1.3 that fill
445
+ after it are not age-gated (one-time activation edge; all current open offers are
446
+ operator-controlled).
447
+
448
+ ## 16. Fill-before-cancel — cancels defer to the block boundary
449
+
450
+ §15 killed the buyer-vs-buyer race, but the same apply-order semantics left one **malicious-
451
+ seller** variant: the **cancel snipe**. Within a block the resolver applies **all proposals
452
+ (pos asc), then all attests (pos asc)** (§1). A fill is an attest; an `ocancel` is a proposal
453
+ (always applies first); a plain `cancel` is an attest whose pos the seller can lower by paying
454
+ a higher fee (miners order feerate-DESC). So a seller who sees a buyer's fill in the mempool
455
+ could broadcast a cheap `ocancel` (or a higher-fee `cancel`) in the same block: the cancel
456
+ applied first, the offer was no longer `open`, the fill no-op'd — **but the fill tx's payment
457
+ is a real confirmed output to the seller.** Seller paid, delivers nothing, cost ≈ one anchor
458
+ fee. That breaks §15's guarantee ("a buyer can never lose more than the anchor fee") the moment
459
+ a non-operator seller answers an RFQ.
460
+
461
+ From height **31 400**:
462
+
463
+ - **Rule:** a `cancel` or `ocancel`'s **effect** (releasing the give, flipping the offer to
464
+ `cancelled`) is **deferred to the end of its block** — it applies only to offers still `open`
465
+ after every same-block fill has settled. A same-block fill therefore **always wins**: a fill
466
+ that lands means the seller got paid in that very tx, so it is a completed, fair sale; the
467
+ late cancel then no-ops on the now-filled offer (noted
468
+ `superseded by same-block fill (v1.4)`). An honest cancel — no competing same-block fill —
469
+ lands exactly as before, one block-boundary later in effect but in the same block.
470
+ - **Guards still fire at apply time:** only-the-seller and offer-must-be-open are checked when
471
+ the cancel is applied in order (a cancel on an already-filled/cancelled offer fails
472
+ immediately, as pre-v1.4). Only the *effect* of a passing cancel is deferred.
473
+ - **`ocancel` snapshot:** the target set (the proposer's open offers matching the filter) is
474
+ computed at apply time — correctly capturing only strictly-earlier offers, since higher-pos
475
+ same-block offers are not yet applied — and at the flush only the targets **still open** are
476
+ cancelled (partial fills in between deliver first; the flush releases the remainder).
477
+ - **Partial fills:** a same-block partial fill on a being-cancelled offer delivers its pro-rata
478
+ amount; the deferred cancel then releases only the unsold remainder. The buyer keeps what
479
+ they paid for; the seller keeps the rest.
480
+ - **Scope:** deferral is **intra-block only.** A fill in any later block than the cancel loses
481
+ normally (the cancel flushed at the block boundary). Expiry sweeps are unchanged and run
482
+ after the flush.
483
+ - **Why deferral, not reordering:** moving cancels after fills in the sort would break the
484
+ global ordered loop and the "offers settle before fills" invariant for every other record
485
+ type. Deferring only the effect keeps apply order intact. The one non-physical edge — a
486
+ same-key `ocancel`-then-relist in one block observing pre-flush lock state — **cannot occur
487
+ on-chain**: anchor inputs must be confirmed (no CPFP), so one key cannot chain two anchors
488
+ into a single block.
489
+ - **Determinism:** the deferred-cancel list is built and flushed in apply order, so the state
490
+ (and the event log) remains a pure function of the chain prefix. Non-retroactive: pre-v1.4
491
+ blocks never defer, so all historical replay is byte-identical.
492
+
493
+ With §15 + §16 together the invariant holds against **both** failure modes: a buyer can never
494
+ lose more than the anchor fee — not to another buyer (race), and not to the seller (snipe).
495
+
496
+ ## 17. Name leasing — names are paid-through, renewable, recapturable (v1.5)
497
+
498
+ §9's perpetual names were the registry's known economic gap: a 10+-char name costs 0.1 CSD
499
+ **once, forever** — squatting is free to carry, and lapsed projects strand names permanently.
500
+ From height **32 000** every name is a **lease**:
501
+
502
+ - **Term:** a claim (or premium re-claim) is paid through `claimEpoch + 8 760` epochs (≈ 1 year).
503
+ Names claimed before v1.5 are **grandfathered** one full term from activation
504
+ (`epochOf(32 000) + 8 760`) — computed lazily, no state rewrite at the boundary.
505
+ - **`nrenew` `{v:1,t:"nrenew",name}`:** extends the lease one term from its CURRENT end. Valid
506
+ from **anyone** while the lease is live (third-party gifting, ENS-style) iff the same tx pays
507
+ `nameRegFee(name)` to the treasury. A renewal never changes ownership.
508
+ - **Grace (720 epochs ≈ 30 days):** past `paidThroughEpoch`, only the **owner** may renew —
509
+ otherwise a squatter could extend a lapsing name they intend to take.
510
+ - **Lapse → decaying-premium recapture:** past grace the name is unowned again. Anyone may claim
511
+ it by paying `expiredClaimFee(name, epochsPastGraceEnd)`: `nameRegFee × 20` linearly decaying
512
+ to `× 1` over 720 epochs (pure integer function — deterministic everywhere). The re-claim is a
513
+ **fresh basis**: prior `viaFill` immunity is void (immunity protects a *paid* basis; an unpaid
514
+ lease is an abandoned one), and any still-open offer on the name is voided with its lock freed.
515
+ - **Guards:** `nxfer`/`nset` on a lapsed lease are no-ops. A name **offer** is a no-op unless the
516
+ lease covers the offer's ENTIRE fill window (`paidThroughEpoch ≥ expiresEpoch`) — so a fill can
517
+ never hit a mid-window lapse; the alternative (a no-op'd CSD fill whose payment already
518
+ confirmed to the seller) would be a fund-loss shape, so it is made unrepresentable. Offers
519
+ anchored before v1.5 are exempt (their windows all end long before any grandfathered lease).
520
+ - **State:** at v1.5+ tips `names[x]` carries `paidThroughEpoch` (and `expired: true` once
521
+ lapsed; the record is kept for history until re-claimed). Pre-v1.5 canonical hashes are
522
+ unchanged — the fields exist only at v1.5+ tips.
523
+
524
+ ## 18. `tmeta` — issuer token metadata via the content layer (v1.5)
525
+
526
+ `{v:1,t:"tmeta",ticker,hash}` — **issuer-only**, last write wins, no fee beyond the anchor.
527
+ `hash` is a csd-swarm Content Convention v1 hash (0x + 64 hex) pointing at the token's
528
+ `{logo, description, links}` document — self-certifying content, so the record stays tiny
529
+ (the 512-byte `uri` cap is untouched) and the metadata inherits the swarm's verify-on-read
530
+ property. State: `tokens[t].tmeta`. Records before v1.5 are no-ops.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 InverseAltruism
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # @inversealtruism/cairnx-core
2
+
3
+ **CairnX** — tokens, atomic delivery-versus-payment trades, and a leased `.csd` name registry on
4
+ [Compute Substrate](https://cairn-substrate.com/docs), implemented as a **pure deterministic
5
+ convention** over the chain's native `Propose`/`Attest` transactions. No fork, no smart
6
+ contracts, no custodian — the same trust class as Bitcoin Ordinals/Runes/BRC-20, stated plainly.
7
+
8
+ Live market: **https://cairn-substrate.com/trade** · Explorer: **/explorer**
9
+
10
+ ## The trust model, in one paragraph
11
+
12
+ CairnX state (token balances, name ownership, open offers) is computed by replaying the chain
13
+ through one pure function: `resolve(events, tipHeight) → state`. The chain enforces ordering,
14
+ the one-transaction atomicity of payment + fill, and offer expiry; this convention enforces
15
+ token/name semantics. **Determinism is the trust model**: every honest resolver fed the same
16
+ chain prefix MUST produce byte-identical canonical state. `CONVENTION.md` (shipped in this
17
+ package) is normative; `test/vectors/` is the conformance bar.
18
+
19
+ ## Use it
20
+
21
+ ```ts
22
+ import { resolve, canonicalState, offer, buildRecord, DOMAIN } from "@inversealtruism/cairnx-core";
23
+ import { buildPropose } from "@inversealtruism/csd-tx";
24
+
25
+ // 1. BUILD a record (a partially-fillable sell offer, reserved for one buyer — v1.3 RFQ)
26
+ const built = offer({ give: { ticker: "CAIRN", amount: "5000000000" },
27
+ want: { value: "100000000" }, min: "10000000", taker: buyerAddr });
28
+
29
+ // 2. ANCHOR it (the record IS the uri; same-tx outputs can pay fees/sellers — atomic DvP)
30
+ const tx = buildPropose({ domain: DOMAIN, uri: built.uri, payloadHash: built.payloadHash,
31
+ expiresEpoch, fee: 25_000_000, utxos, priv });
32
+
33
+ // 3. RESOLVE the chain (events come from any indexer; see the Scanner reference impl)
34
+ const state = resolve(events, tipHeight);
35
+ console.log(state.tokens.CAIRN, state.balances.CAIRN, state.names);
36
+ ```
37
+
38
+ ## Write a conformant resolver in another language
39
+
40
+ 1. Implement `CONVENTION.md` §1–§18 (apply order, every record type, the version activation
41
+ heights, canonical-state format 2 — ordinal key ordering, data surface only).
42
+ 2. Replay `test/vectors/cases.json`: for every case, your canonical state must equal
43
+ `expectedState` byte-for-byte (16 cases covering tokens, partials, swaps, RFQ, names,
44
+ leasing, and the v1.3/v1.4 safety semantics).
45
+ 3. Replay the live chain and compare `sha256(canonicalState)` against
46
+ `test/vectors/replay-hashes.json` at the pinned activation heights.
47
+
48
+ ## Versions (activation heights are consensus-grade — never reinterpret history)
49
+
50
+ | | height | what |
51
+ |---|---|---|
52
+ | v1.0/1.1 | 29 860 / 29 960 | tokens · names + protocol fees |
53
+ | v1.2 | 30 300 | token⇄token swaps · partial fills · bids (RFQ) · ocancel |
54
+ | v1.3 | 31 100 | CSD-priced offers must be taker-bound (open-fill race made unrepresentable) |
55
+ | v1.4 | 31 400 | fill-before-cancel (the cancel snipe is dead) |
56
+ | v1.5 | 32 000 | name **leasing** (renew/grace/decaying-premium recapture) · `tmeta` |
57
+
58
+ The invariant after v1.3+v1.4: **a buyer can never lose more than the anchor fee** — not to a
59
+ racing buyer, not to a malicious seller.