@inversealtruism/cairnx-core 0.1.20 → 0.1.23

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/README.md CHANGED
@@ -1,110 +1,327 @@
1
1
  # @inversealtruism/cairnx-core
2
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.
3
+ **CairnX** is the application layer of [Compute Substrate](https://cairn-substrate.com/docs) (CSD): an
4
+ on-chain **name service (CNS / `.csd`)**, **tokens**, and **atomic delivery-versus-payment trades**, implemented as a **pure deterministic convention** over the chain's native `Propose`/`Attest`
5
+ transactions. No fork, no smart contracts, no custodian. The same trust class as Bitcoin
6
+ Ordinals/Runes/BRC-20, stated plainly, and engineered to be byte-for-byte reproducible.
7
7
 
8
- Live market: **https://cairn-substrate.com/trade** · Explorer: **/explorer**
8
+ > **First product shipping: CNS, the Cairn Name Service.** `alice.csd` is an on-chain-native, leased,
9
+ > tradeable identity. This README leads with how CNS works, then covers tokens and trades.
9
10
 
10
- ## The trust model, in one paragraph
11
+ Live: market **[/trade](https://cairn-substrate.com/trade)** · names **[/names](https://cairn-substrate.com/names)** · explorer **[/explorer](https://cairn-substrate.com/explorer)**
12
+ Normative spec: **[`CONVENTION.md`](./CONVENTION.md)** (shipped in this package) · Conformance bar: **[`test/vectors/`](./test/vectors)**
11
13
 
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.
14
+ > Diagrams below render on GitHub (Mermaid). The ASCII architecture map renders everywhere.
18
15
 
19
- ## Use it
16
+ ---
17
+
18
+ ## 1 · The one idea: a pure deterministic overlay
19
+
20
+ Compute Substrate is a proof-of-work chain that does one thing: it **records** signed `Propose` /
21
+ `Attest` transactions and orders them. It does **not** know what a "token" or a "name" is. CairnX gives
22
+ those records *meaning* by replaying them through a single pure function:
23
+
24
+ ```
25
+ resolve(events, tipHeight) → canonical state (tokens · names · offers · bids · balances)
26
+ ```
27
+
28
+ **Determinism is the trust model.** Every honest party that replays the same chain prefix MUST produce
29
+ **byte-identical** canonical state. There is no privileged server, your wallet computes the same answer
30
+ the operator's resolver does, and disagreement is detectable.
31
+
32
+ ```
33
+ ┌──────────────────────────────────────────────────────────────────────────────┐
34
+ │ APP SURFACES CNS UI (/names) · Market (/trade) · Cairn Wallet │
35
+ │ Explorer · cairn-cli · 3rd-party dApps│
36
+ └───────────────▲───────────────────────────────────────────────▲──────────────┘
37
+ │ read derived state │ build + sign records
38
+ ┌───────────────┴───────────────────────────────────────────────┴──────────────┐
39
+ │ cairnX OVERLAY = resolve(events, tip) → state (THIS PACKAGE) │
40
+ │ every replayer runs the SAME pure function and gets the SAME bytes: │
41
+ │ wallet (SPV, in-browser) · Granus resolver svc · clarvis · cli │
42
+ └───────────────▲────────────────────────────────────────────────────────────────┘
43
+ │ events (Propose/Attest) + block headers
44
+ ┌───────────────┴────────────────────────────────────────────────────────────────┐
45
+ │ COMPUTE SUBSTRATE (base chain) PoW · records & orders txs · enforces same-tx │
46
+ │ payment atomicity & expiry - decides NOTHING │
47
+ └──────────────────────────────────────────────────────────────────────────────────┘
48
+ ```
49
+
50
+ **The safety consequence of "overlay":** CairnX names and tokens have **no native-CSD backing**. A bug,
51
+ an over-mint, or even a fully-lying indexer can only fork the *overlay view* of whoever trusts it, it
52
+ **cannot move CSD**. CSD moves *only* via real same-transaction payment outputs, which the chain makes
53
+ atomic with the fill and which a buyer's wallet verifies against the offer's terms before paying. This
54
+ single decision bounds the blast radius of every overlay bug and is why the names/tokens alpha is
55
+ funds-safe.
56
+
57
+ ```mermaid
58
+ flowchart TD
59
+ subgraph BASE["Compute Substrate · PoW base chain"]
60
+ TX["Propose / Attest txs<br/>(records live in the uri)"]
61
+ end
62
+ CORE["cairnx-core<br/><b>resolve(events, tip) → state</b><br/>pure · deterministic · this package"]
63
+ W["Cairn Wallet<br/>in-browser SPV replayer"]
64
+ G["Granus resolver svc :8794"]
65
+ CL["clarvis · 2nd source"]
66
+ CLI["cairn-cli"]
67
+ UIN["CNS UI /names"]
68
+ UIT["Market /trade"]
69
+ TX --> CORE
70
+ CORE --> W & G & CL & CLI
71
+ G --> UIN & UIT
72
+ W -. "self-verifies, never trusts a server" .-> UIN
73
+ ```
74
+
75
+ ---
76
+
77
+ ## 2 · CNS, the Cairn Name Service (`.csd`)
78
+
79
+ CNS is an **ENS-class** namespace native to Compute Substrate. A name like `alice.csd` is owned by an
80
+ address, **leased** (not sold forever), points to an address, and carries an optional profile, all as
81
+ plain on-chain records, all resolvable by replay.
82
+
83
+ - **Names are lowercase-ASCII only** (`^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$`, 1–32 chars). This kills
84
+ the homograph/confusable phishing class outright, there is no unicode look-alike attack surface.
85
+ - **The `.csd` suffix is presentation, not consensus.** The on-chain record stores the *bare* name
86
+ (`alice`); the UI renders `alice.csd`. The CNS rebrand and any display-suffix change are **UI-only**, they do not touch the resolver or chain history.
87
+ - **Reserved names** (`csd`, `treasury`, `admin`, `official`, `root`, `www`, `support`) can never be
88
+ registered, anti-impersonation, enforced in consensus.
89
+
90
+ ### 2.1 · Lifecycle
91
+
92
+ ```mermaid
93
+ stateDiagram-v2
94
+ [*] --> Committed: ncommit · hash(name+salt+owner)
95
+ Committed --> Active: name (reveal within ~8h) · pays the fee, starts a 1-year lease
96
+ Active --> Active: nrenew · nset (point to addr) · nprofile (identity) · nxfer (transfer) · sell (offer/fill)
97
+ Active --> Grace: lease term ends (~1 year)
98
+ Grace --> Active: nrenew · OWNER ONLY, ~30-day window
99
+ Grace --> Lapsed: grace ends un-renewed
100
+ Lapsed --> Active: recapture · anyone re-claims at a DECAYING premium (20x to 1x over ~30 days), fresh lease
101
+ Active --> [*]
102
+ ```
103
+
104
+ 1. **Commit → Reveal (registration).** You first publish `ncommit`, a hash of `{name, salt, owner}`.
105
+ Then within ~8 hours you publish the `name` record revealing the name. The resolver **back-dates** the
106
+ registration to the commit height, so a front-runner who copies your reveal loses the ownership race.
107
+ Standard commit-reveal, enforced deterministically.
108
+ 2. **Active lease (~1 year).** You own the name: point it at an address (`nset`), set an identity profile
109
+ (`nprofile`), transfer it (`nxfer`), renew it (`nrenew`), or list it for sale.
110
+ 3. **Grace (~30 days).** When the term ends, **only the current owner** may renew during a grace window, your name is never sniped out from under you while you still hold it.
111
+ 4. **Lapsed → decaying-premium recapture.** If grace passes un-renewed, anyone may re-claim, but at a
112
+ **premium that decays 20× → 1×** over ~30 days (a Dutch auction back to the floor price). This prices
113
+ in genuine demand without a permanent squatting tax, and a recaptured name gets a fresh ownership basis
114
+ so a stale pre-lapse commit can't steal it.
115
+
116
+ ### 2.2 · The records
117
+
118
+ | Record | What it does |
119
+ |---|---|
120
+ | `ncommit` | Commit to a name (hash of name+salt+owner), opens the front-run-safe reveal window |
121
+ | `name` | Reveal + claim (registration), pays the fee, starts/refreshes the lease |
122
+ | `nrenew` | Extend the lease (owner-only in grace) |
123
+ | `nxfer` | Transfer ownership to another address |
124
+ | `nset` | Set the forward address record (`alice.csd → 0x…`) |
125
+ | `nprofile` | Owner-set identity metadata (ENSIP-5-style keys: avatar, url, com.twitter, …) |
126
+
127
+ ### 2.3 · Parameters
128
+
129
+ | Parameter | Value | Notes |
130
+ |---|---|---|
131
+ | Lease term | ~1 year (`NAME_TERM_EPOCHS = 8760`) | 1 epoch ≈ 1 h (30 blocks) |
132
+ | Grace window | ~30 days (`NAME_GRACE_EPOCHS = 720`) | owner-only renewal |
133
+ | Recapture premium | **20× → 1×** over ~30 days | decaying Dutch auction on lapsed names |
134
+ | Reveal window | ~8 h (`COMMIT_MAX_BLOCKS = 240`) | commit-reveal deadline |
135
+ | Registration fee | **6.7 CSD** (≤4 chars) · **3 CSD** (≥5 chars) | flat 2-tier (v1.8); paid to the treasury |
136
+
137
+ ### 2.4 · How a name resolves, and what's actually *verified*
138
+
139
+ This is what makes CNS trust-minimized rather than "ask a server." When the wallet resolves `alice.csd`
140
+ to choose a send recipient, it does **not** trust the resolver's answer, it independently SPV-verifies
141
+ every relevant record into the proof-of-work chain it built itself, replays them, and only trusts the
142
+ deterministically-recomputed winner.
143
+
144
+ ```mermaid
145
+ sequenceDiagram
146
+ participant U as User / dApp
147
+ participant Wallet
148
+ participant Sources as Name sources (resolver + 2nd source)
149
+ participant SPV as In-browser SPV (own PoW headers)
150
+ U->>Wallet: send to alice.csd
151
+ Wallet->>Sources: fetch alice's name-history (records + inclusion proofs)
152
+ Sources-->>Wallet: candidate records (UNTRUSTED)
153
+ Wallet->>SPV: merkle-verify each record into the PoW-verified headers
154
+ Note over Wallet,SPV: union of sources: a source can only ADD real,<br/>signer-authenticated, prevout-bound events (never fabricate)
155
+ Wallet->>Wallet: resolve() the verified events to a deterministic owner + addr
156
+ alt recomputed addr matches and fully provable
157
+ Wallet-->>U: verified, show address, allow send
158
+ else mismatch or unprovable
159
+ Wallet-->>U: fail closed, show caution, do not auto-trust
160
+ end
161
+ ```
162
+
163
+ - **Forward resolution (`name → address`, the funds path) is SPV-verified and fail-closed.** The wallet
164
+ treats the resolver as untrusted, merkle-binds each record to a PoW header, replays, and refuses the
165
+ send if its recomputed answer disagrees or can't be proven. It re-checks again at signing time and
166
+ refuses both an address change and a verification-status regression.
167
+ - **Reverse resolution (`address → primary name`, a display label) is server-trusted.** It is never a send
168
+ target, an identity badge only, so it is cheaper and clearly bounded as "unverified label."
169
+ - **Ownership has an unambiguous total order:** lowest `(effectiveHeight, position, ordinal-id)` wins, with
170
+ a paid market-fill (`viaFill`) immune to displacement. Exactly one owner per name at every height.
171
+
172
+ > **Note on bought names:** a name you *register* is fully SPV-verifiable today. A name acquired via a
173
+ > *market fill* is displacement-immune and correctly resolved, but its forward resolution currently shows
174
+ > a caution rather than a green check (the wallet fails *closed* on this class) pending a resolver change
175
+ > that makes name-fills name-local. Registration, the alpha's primary flow, is unaffected.
176
+
177
+ ---
178
+
179
+ ## 3 · Tokens
180
+
181
+ Fungible tokens, same overlay model. A `deploy` declares a ticker; `mint` issues supply (capped by the
182
+ declared supply and, for open mints, a per-tx limit); `transfer` moves balances; `tmeta` attaches issuer
183
+ metadata. Because tokens are an overlay, an over-mint can only inflate *that token's* overlay view, it
184
+ can never touch CSD.
185
+
186
+ | Record | What it does |
187
+ |---|---|
188
+ | `deploy` | Create a token: `ticker`, `decimals` (0–8), `supply`, `mint: "open" \| "issuer"`, optional `mintLimit` |
189
+ | `mint` | Issue supply (≤ declared supply; open mints bounded per-tx by `mintLimit`) |
190
+ | `transfer` | Move a balance to another address (optional memo) |
191
+ | `tmeta` | Issuer-set token metadata (via the content layer) |
192
+
193
+ ---
194
+
195
+ ## 4 · Atomic delivery-versus-payment (DvP) trades
196
+
197
+ Sell a token **or a name** for CSD or another token, atomically. The offer locks the give-side in the
198
+ resolver; the fill is an `Attest` whose **same transaction carries the payment outputs:** the chain makes
199
+ payment and delivery one indivisible step. No escrow, no custodian, no "the other side didn't pay."
200
+
201
+ ```mermaid
202
+ sequenceDiagram
203
+ participant Maker
204
+ participant Chain as Compute Substrate
205
+ participant Taker
206
+ Maker->>Chain: offer { give: alice.csd or token, want: 100 CSD, payto } (locks the give)
207
+ Note over Chain: open CSD offers use claim-to-fill (v1.7):<br/>the FIRST claimer is reserved before paying, no race
208
+ Taker->>Chain: fill (Attest) + SAME-TX outputs · 100 CSD to payto, fee to treasury, rebate to maker
209
+ Chain-->>Chain: resolve(): payment satisfies want? deliver give to taker, else NO-OP
210
+ Note over Maker,Taker: invariant (v1.3+v1.4) · a buyer can never lose more than the anchor fee
211
+ ```
212
+
213
+ Highlights: partial fills (pro-rata, maker-favoring), bids (RFQ buy-side intents), `ocancel` (maker's mass
214
+ kill-switch), a 1.5% taker fee + maker rebate on resting liquidity (v1.6), and the **claim-to-fill** open
215
+ lane (v1.7) that reserves an untaken CSD offer for the first claimer so two buyers can't race into a burned
216
+ payment. Listing duration is a **UI policy** (consensus places no cap as of v2.2), long-rester inventory
217
+ is bounded in the light client, not the chain.
218
+
219
+ ---
220
+
221
+ ## 5 · How it's built (and why you can trust the replay)
222
+
223
+ - **One pure fold.** `resolve()` rebuilds *all* state from the event log every call, reorg-safe by
224
+ construction. Integer-only math (BigInt, ceil-rounded fees), one ordinal string comparator, sorted
225
+ iteration at every materialization, **no `Date`/`Math.random`/float in any value path**.
226
+ - **A fail-closed parse gate.** `parseRecord` validates every record type with `onlyKeys` allow-lists, a
227
+ recursive well-formed-UTF-16 check, and `Number.isSafeInteger` guards, closing real cross-language
228
+ canonicalization fork classes (astral-decoy keys, lone surrogates, the 2⁵³/`1e21` JSON trap). Invalid
229
+ input is always a no-op, never a throw that poisons replay.
230
+ - **Non-retroactive height-gated eras.** Every change activates at a `V*_HEIGHT` and is **byte-identical
231
+ below that gate:** history is never reinterpreted. Relaxations key on the offer's *anchor* height so a
232
+ mixed-version fleet can't fork during a rollout.
233
+ - **The determinism contract is *enforced*, not asserted.** An independent Python reference
234
+ (`conformance/cairnx_ref.py`) runs the same corpus and a 1500-iteration JS↔Python differential fuzzer on
235
+ every CI run, plus 60 language-neutral vectors and pinned live-chain replay hashes.
236
+
237
+ ### Version history (activation heights are consensus-grade, never reinterpret history)
238
+
239
+ | Version | Height | What |
240
+ |---|---|---|
241
+ | v1.0 / 1.1 | 29 860 / 29 960 | tokens · **names (CNS)** + protocol fees |
242
+ | v1.2 | 30 300 | token⇄token swaps · partial fills · bids (RFQ) · `ocancel` |
243
+ | v1.3 / 1.4 | 31 100 / 31 400 | CSD-priced offers taker-bound · fill-before-cancel, *buyer can't lose more than the anchor fee* |
244
+ | v1.5 | 32 000 | **name leasing** (renew / grace / decaying-premium recapture) · `tmeta` |
245
+ | v1.6 | 33 600 | taker fee 1% → 1.5% + maker rebate on resting liquidity |
246
+ | v1.7 | 34 000 | claim-to-fill, race-safe open CSD offers |
247
+ | v1.9 | 36 700 | `nprofile`, ENS-class identity on a name |
248
+ | v2.0 | 38 400 | bounded claim grace (the late-fill fix) |
249
+ | v1.8 | 40 000 | flat two-tier name fee (6.7 / 3 CSD) |
250
+ | v2.1 | 40 100 | offer/bid duration cap (`MAX_OFFER_EPOCHS = 168`), *superseded by v2.2* |
251
+ | v2.2 | 41 300 | duration cap **removed from consensus** → UI policy; bound moves to the light client |
252
+
253
+ ### Package layout
254
+
255
+ `src/resolve.ts` (the ledger) · `src/records.ts` (the parse/validate gate) · `src/types.ts` (constants +
256
+ height-gated client selectors) · `src/client.ts` (reorg-safety helpers a payer applies) · `CONVENTION.md`
257
+ (normative spec, §1–§24) · `test/vectors/` (portable conformance corpus).
258
+
259
+ ### Use it
20
260
 
21
261
  ```ts
22
- import { resolve, canonicalState, offer, buildRecord, DOMAIN } from "@inversealtruism/cairnx-core";
262
+ import { resolve, canonicalState, offer, nameCommit, DOMAIN } from "@inversealtruism/cairnx-core";
23
263
  import { buildPropose } from "@inversealtruism/csd-tx";
24
264
 
25
- // 1. BUILD a record (a partially-fillable sell offer, reserved for one buyer — v1.3 RFQ)
265
+ // BUILD a record (e.g. a partially-fillable sell offer, reserved for one buyer, v1.3 RFQ)
26
266
  const built = offer({ give: { ticker: "CAIRN", amount: "5000000000" },
27
267
  want: { value: "100000000" }, min: "10000000", taker: buyerAddr });
28
268
 
29
- // 2. ANCHOR it (the record IS the uri; same-tx outputs can pay fees/sellers — atomic DvP)
269
+ // ANCHOR it (the record IS the uri; same-tx outputs can pay fees/sellers, atomic DvP)
30
270
  const tx = buildPropose({ domain: DOMAIN, uri: built.uri, payloadHash: built.payloadHash,
31
271
  expiresEpoch, fee: 25_000_000, utxos, priv });
32
272
 
33
- // 3. RESOLVE the chain (events come from any indexer; see the Scanner reference impl)
273
+ // RESOLVE the chain (events come from any indexer; see the Scanner reference impl)
34
274
  const state = resolve(events, tipHeight);
35
- console.log(state.tokens.CAIRN, state.balances.CAIRN, state.names);
275
+ console.log(state.names, state.tokens.CAIRN, state.balances.CAIRN);
36
276
  ```
37
277
 
38
- ## Write a conformant resolver in another language
278
+ ### Write a conformant resolver in another language
39
279
 
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.
280
+ 1. Implement `CONVENTION.md` §1–§24 (apply order, every record type, the `V*_HEIGHT` activations, the
281
+ canonical-state format, ordinal key ordering, data surface only).
282
+ 2. Replay `test/vectors/cases.json`: your canonical state must equal `expectedState` **byte-for-byte**.
283
+ 3. Replay the live chain and compare `sha256(canonicalState)` against `test/vectors/replay-hashes.json`.
47
284
 
48
- ## Versions (activation heights are consensus-grade — never reinterpret history)
285
+ ---
49
286
 
50
- | | height | what |
287
+ ## 6 · ★ Single source of truth, change consensus without drift
288
+
289
+ **This package is the ONE canonical implementation of the CairnX convention.** Every consumer **imports**
290
+ its constants / regexes / fee+claim+expiry math / `canonicalJson` / `parseRecord` from here (via npm, or a
291
+ *deterministic vendored esbuild* of this exact dist where a browser/MV3 constraint forbids a runtime dep
292
+ tree). **Nothing re-declares a consensus value by hand:** a hand-mirror that drifts across a version bump
293
+ is a silent chain fork, the exact bug class the shared-core de-dup (`cairn/docs/Plans/46`) deleted.
294
+
295
+ | Consumer | How it gets consensus | Guard |
51
296
  |---|---|---|
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` |
297
+ | **cairnx svc** (`cairnx/`, the live resolver `:8794`) | npm pin → re-export shim | svc replay-hash conformance |
298
+ | **cairn /trade + /names UI** (browser) | `public/vendor/cairnx-core.js` (esbuild of this dist) | `vendor-cairnx-parity.test.mjs` + `check-vendor-fresh.mjs` |
299
+ | **cairn-wallet** (MV3, fund custody) | `src/vendor/cairnx-spv.js` (esbuild, `export *`) | `test/cairnx.ts` + `check-vendor-fresh.mjs` + `PROVENANCE.json` |
300
+ | **cairn-cli** | npm pin → imports regexes/limits | `test/cairnx.mjs` |
301
+ | **the Python oracle** `conformance/cairnx_ref.py` | INDEPENDENT re-implementation (the differential, **KEEP**) | `test:crosslang` (JS⇄Python) |
57
302
 
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.
303
+ **To make a consensus change:** edit `src/` here **and** `conformance/cairnx_ref.py`; add a height-gated
304
+ `V*_HEIGHT` (never reinterpret history) + a vector; `pnpm build && pnpm test && pnpm test:crosslang &&
305
+ node scripts/check-lockstep.mjs` (all green); **bump the version**; `pnpm publish`; **rebuild + recommit
306
+ the two vendored bundles**; re-pin every consumer and deploy them **between** activation heights, not
307
+ across one (below the gate the output is byte-identical, so the rollout is fork-free).
60
308
 
61
- ## ★ Single source of truth — consumers & how to change consensus without drift
309
+ **KEEP-list (verification, not duplication, never collapse):** the Python oracle, the wallet/swapguard SPV
310
+ light-client + `namespv.ts`, the wallet `core/csdtx.ts` tx-codec twin, the portable vectors.
62
311
 
63
- **This package is the ONE canonical implementation of the CairnX convention.** Every consumer in the
64
- ecosystem **imports** its constants / regexes / fee+claim+expiry math / `canonicalJson` / `parseRecord`
65
- from here (directly via npm, or via a *deterministic vendored esbuild* of this exact dist where a
66
- browser/MV3 constraint forbids a runtime dep tree). **Nothing re-declares a consensus value by hand** — a
67
- hand-mirror that drifts across a version bump is a silent chain fork, which is exactly the bug class the
68
- 2026-06-24 shared-core de-duplication (`cairn/docs/Plans/46`) deleted. Do not re-introduce one.
312
+ ---
69
313
 
70
- | Consumer | How it gets consensus | Guard |
71
- |---|---|---|
72
- | **cairnx svc** (`cairnx/`, the live resolver `:8794`) | npm pin → `src/resolve.ts` re-export shim | svc replay-hash conformance |
73
- | **cairn /trade + /names UI** (browser) | `public/vendor/cairnx-core.js` — esbuild of this dist; `helpers.js` imports+re-exports it | `test/vendor-cairnx-parity.test.mjs` (consumer golden) + `scripts/check-vendor-fresh.mjs` (CI) |
74
- | **cairn-wallet** (MV3 extension, fund custody) | `src/vendor/cairnx-spv.js` — esbuild of this dist (`export *`); `core/cairnx.ts` imports it | `test/cairnx.ts` (fixtures vs this pkg) + `scripts/check-vendor-fresh.mjs` + `PROVENANCE.json` |
75
- | **cairn-cli** | npm pin → `src/lib/cairnx.ts` imports the regexes/limits | `test/cairnx.mjs` |
76
- | **cairn server** (`cairn/src`) | proxies reads to the cairnx svc; imports `csd-*` (codec/crypto/tx) via `file:` | — |
77
- | **the Python oracle** `conformance/cairnx_ref.py` | INDEPENDENT re-implementation (the differential — **KEEP**, never collapse) | `test:crosslang` (JS⇄Python) |
78
-
79
- ### Versioning (independent cadence)
80
-
81
- `cairnx-core` versions on its **own** consensus cadence (it bumps when the convention changes); the stable
82
- `csd-*` primitives version on theirs. They need **not** share a version — coherence comes from `workspace:*`
83
- inter-deps (pnpm freezes each to the exact published version at publish), enforced by `scripts/check-lockstep.mjs`.
84
- **Never publish two different builds under one version** (the M4 hazard): bump the version whenever the bytes change.
85
-
86
- ### To make a CONSENSUS change (the whole flow — edit ONE source, not 4–5 mirrors)
87
-
88
- 1. Edit `src/` here **and** the Python oracle `conformance/cairnx_ref.py` (the differential). Add a height-gated
89
- activation (`V*_HEIGHT`) — never reinterpret history; add/extend a vector in `test/vectors/cases.json`.
90
- 2. `pnpm --filter @inversealtruism/cairnx-core build` · `pnpm --filter @inversealtruism/cairnx-core test` ·
91
- `pnpm test:crosslang` (JS≡Python) · `node scripts/check-lockstep.mjs`. All green.
92
- 3. **Bump** `package.json` version. `pnpm publish` (converts `workspace:*` → the exact csd-* version).
93
- 4. **Rebuild + recommit the two vendored bundles** (they are generated artifacts, not hand-copies):
94
- `cd cairn && bash scripts/build-trade-vendor.sh` → commit `public/vendor/cairnx-core.js`; `node scripts/check-vendor-fresh.mjs`.
95
- `cd cairn-wallet && bash scripts/build-spv-vendor.sh` → `node scripts/check-vendor-fresh.mjs --write` (regen PROVENANCE) → commit the bundle + `PROVENANCE.json`.
96
- *(esbuild is version-pinned in each repo — same version → byte-reproducible bundle; the freshness gates fail loud on a stale bundle.)*
97
- 5. **Re-pin every consumer** to the new version (cairnx svc + cairn-cli `package.json`) and, for a height-gated
98
- change, **deploy all consumers BETWEEN activation heights, not across one** (below the gate the output is
99
- byte-identical to history, so the rollout is safe).
100
- 6. Restart the cairnx svc; run its replay-hash conformance; (wallet) run the release flow + CWS upload.
101
-
102
- ### For agents / contributors
103
-
104
- - **Never hand-declare a CairnX consensus constant/regex/formula in a consumer.** Import it from this package
105
- (or its vendored bundle). If you find a hand-mirror, collapse it — don't add a guard.
106
- - A new exported symbol must be added to the consumers' import+re-export lists (`helpers.js`, `core/cairnx.ts`)
107
- and to the wallet's `cairnx-spv.d.ts`; the build scripts' export-assertion lists catch a dropped one.
108
- - The KEEP-list (do **not** collapse — these are *verification*, not duplication): the Python oracle, the
109
- wallet/swapguard SPV light-client + `namespv.ts`, the wallet `core/csdtx.ts` tx-codec twin, the portable
110
- vectors. The cross-language differential is the trust model — keep it intact.
314
+ ### Honest limits (read these)
315
+
316
+ - **Trust-min is operator-shaped today.** Completeness/availability rests on a single indexer and a
317
+ 2-source name union whose two defaults share one apex, strong against *fabrication* (every event is
318
+ SPV/signer/prevout-bound), weaker against *withholding* until a genuinely independent second source runs.
319
+ The 2nd-indexer canonical-hash comparator is designed but parked until that exists.
320
+ - **The indexer ships on SQLite by default.** A Postgres backend is fully built (`csd-indexer/src/db.ts`)
321
+ and is a documented env-flip + from-genesis-replay cutover (`RUNBOOK-HOST.md §8.3`), the scale path, not
322
+ yet the running default.
323
+ - **`verifyInclusion` (merkle-binding the indexer's decoded outputs) is OFF by default** and is a hard
324
+ prerequisite before any lane treats received CSD as spendable. The overlay model is what keeps the
325
+ names/tokens alpha funds-safe regardless.
326
+
327
+ MIT · the same trust class as Ordinals/Runes, engineered for byte-for-byte reproducible replay.
package/dist/index.cjs CHANGED
@@ -84,6 +84,8 @@ __export(index_exports, {
84
84
  V20_HEIGHT: () => V20_HEIGHT,
85
85
  V21_HEIGHT: () => V21_HEIGHT,
86
86
  V22_HEIGHT: () => V22_HEIGHT,
87
+ V23_HEIGHT: () => V23_HEIGHT,
88
+ ZERO_ADDR: () => ZERO_ADDR,
87
89
  bid: () => bid,
88
90
  blockReward: () => import_csd_codec4.blockReward,
89
91
  buildRecord: () => buildRecord,
@@ -169,6 +171,8 @@ var V20_HEIGHT = 38400;
169
171
  var V21_HEIGHT = 40100;
170
172
  var MAX_OFFER_EPOCHS = 168;
171
173
  var V22_HEIGHT = 41300;
174
+ var V23_HEIGHT = 52e3;
175
+ var ZERO_ADDR = "0x" + "00".repeat(20);
172
176
  var PKEY = /^[a-z0-9](?:[a-z0-9.-]{0,30}[a-z0-9])?$/;
173
177
  var PROFILE_MAX_KEYS = 16;
174
178
  var PROFILE_MAX_VALUE_BYTES = 256;
@@ -427,6 +431,9 @@ var tokenMeta = (r) => buildRecord({ v: 1, t: "tmeta", ...r });
427
431
  var nameProfile = (r) => buildRecord({ v: 1, t: "nprofile", ...r });
428
432
 
429
433
  // src/resolve.ts
434
+ function ptAmt(v) {
435
+ return typeof v === "string" && AMOUNT_RE.test(v) ? BigInt(v) : 0n;
436
+ }
430
437
  var ord = (a, b) => a < b ? -1 : a > b ? 1 : 0;
431
438
  function resolve(events, tipHeight) {
432
439
  const ordered = [...events].sort(
@@ -536,7 +543,8 @@ function resolve(events, tipHeight) {
536
543
  const v15 = ev.height >= V15_HEIGHT;
537
544
  const v16 = ev.height >= V16_HEIGHT;
538
545
  const v19 = ev.height >= V19_HEIGHT;
539
- const feeToTreasury = ev.kind === "propose" ? BigInt((ev.paidTo ?? {})[TREASURY_ADDR] ?? "0") : 0n;
546
+ const v23 = ev.height >= V23_HEIGHT;
547
+ const feeToTreasury = ev.kind === "propose" ? ptAmt((ev.paidTo ?? {})[TREASURY_ADDR]) : 0n;
540
548
  if (ev.kind === "propose") {
541
549
  const rec = parseRecord(ev.uri, ev.payloadHash);
542
550
  if (!rec) {
@@ -703,7 +711,8 @@ function resolve(events, tipHeight) {
703
711
  note(ev, ev.id, "nset", false, "lease lapsed \u2014 claim it instead");
704
712
  continue;
705
713
  }
706
- n.addr = rec.addr.toLowerCase();
714
+ if (v23 && rec.addr.toLowerCase() === ZERO_ADDR) n.addr = void 0;
715
+ else n.addr = rec.addr.toLowerCase();
707
716
  note(ev, ev.id, "nset", true);
708
717
  } else if (rec.t === "nprofile") {
709
718
  if (!v19) {
@@ -1002,7 +1011,7 @@ function resolve(events, tipHeight) {
1002
1011
  const want = BigInt(o.want.value);
1003
1012
  const paidSoFar = BigInt(o.paid ?? "0");
1004
1013
  const remaining = want - paidSoFar;
1005
- const X = BigInt(pt[o.want.payto] ?? "0");
1014
+ const X = ptAmt(pt[o.want.payto]);
1006
1015
  const minV = BigInt(o.min);
1007
1016
  const effMin = remaining < minV ? remaining : minV;
1008
1017
  if (X < effMin) {
@@ -1011,7 +1020,7 @@ function resolve(events, tipHeight) {
1011
1020
  }
1012
1021
  const x = X < remaining ? X : remaining;
1013
1022
  const fee = o.feeBps ? tradeFee(x, o.feeBps) : 0n;
1014
- if (BigInt(pt[TREASURY_ADDR] ?? "0") < fee) {
1023
+ if (ptAmt(pt[TREASURY_ADDR]) < fee) {
1015
1024
  note(ev, ev.txid, "fill", false, "protocol fee unpaid");
1016
1025
  continue;
1017
1026
  }
@@ -1069,7 +1078,7 @@ function resolve(events, tipHeight) {
1069
1078
  addNeed(TREASURY_ADDR, fee);
1070
1079
  if (rebate > 0n) addNeed(o.seller, rebate);
1071
1080
  let unpaid;
1072
- for (const [addr, amt] of need) if (BigInt(pt[addr] ?? "0") < amt) {
1081
+ for (const [addr, amt] of need) if (ptAmt(pt[addr]) < amt) {
1073
1082
  unpaid = addr === TREASURY_ADDR ? "protocol fee unpaid" : rebate > 0n && addr === o.seller ? "maker rebate unpaid (v1.6)" : "payment below want.value";
1074
1083
  break;
1075
1084
  }
@@ -1077,7 +1086,7 @@ function resolve(events, tipHeight) {
1077
1086
  note(ev, ev.txid, "fill", false, unpaid);
1078
1087
  continue;
1079
1088
  }
1080
- const paid = BigInt(pt[o.want.payto] ?? "0");
1089
+ const paid = ptAmt(pt[o.want.payto]);
1081
1090
  if (isNameGive(o.give)) {
1082
1091
  const n = names.get(o.give.name);
1083
1092
  if (!n) {
@@ -1267,6 +1276,8 @@ var import_csd_codec4 = require("@inversealtruism/csd-codec");
1267
1276
  V20_HEIGHT,
1268
1277
  V21_HEIGHT,
1269
1278
  V22_HEIGHT,
1279
+ V23_HEIGHT,
1280
+ ZERO_ADDR,
1270
1281
  bid,
1271
1282
  blockReward,
1272
1283
  buildRecord,
package/dist/index.d.cts CHANGED
@@ -42,6 +42,8 @@ declare const V20_HEIGHT = 38400;
42
42
  declare const V21_HEIGHT = 40100;
43
43
  declare const MAX_OFFER_EPOCHS = 168;
44
44
  declare const V22_HEIGHT = 41300;
45
+ declare const V23_HEIGHT = 52000;
46
+ declare const ZERO_ADDR: string;
45
47
  declare const PKEY: RegExp;
46
48
  declare const PROFILE_MAX_KEYS = 16;
47
49
  declare const PROFILE_MAX_VALUE_BYTES = 256;
@@ -395,4 +397,4 @@ declare function requiredClaimDepth(valueSats: number | bigint, height: number):
395
397
  capped: boolean;
396
398
  };
397
399
 
398
- export { ACTIVATION_HEIGHT, ADDR_RE, AMOUNT_RE, type AppliedEvent, type AttestEvent, BID_KEYS, type BalanceState, type BidRecord, type BidState, type BidStatus, type BuiltRecord, CLAIM_ATTACKER_Q, CLAIM_COOLDOWN_BLOCKS, CLAIM_FILL_GRACE_BLOCKS, CLAIM_MIN_DEPTH, CLAIM_WINDOW_BLOCKS, CLAIM_WINDOW_BLOCKS_V20, COMMIT_MAX_BLOCKS, COMMIT_REVEAL_MIN_DEPTH, CONF_TOKEN_FILL, type CairnXRecord, type CairnXState, type ChainEvent, DEPLOY_FEE, DEPLOY_KEYS, DOMAIN, type DeployRecord, FEE_BPS, FEE_BPS_V16, type FillEntry, type Give, HASH_RE, MAX_ACTIVE_CLAIMS, MAX_AMOUNT, MAX_OFFER_EPOCHS, MAX_RECORD_BYTES, MINT_KEYS, type MintRecord, NAME_FEE_SHORT_V18, NAME_FEE_V18, NAME_GRACE_EPOCHS, NAME_KEYS, NAME_PREMIUM_DECAY_EPOCHS, NAME_PREMIUM_START, NAME_RE, NAME_TERM_EPOCHS, NPROFILE_KEYS, type NameCommitRecord, type NameProfileRecord, type NameRecord, type NameRenewRecord, type NameSetRecord, type NameState, type NameXferRecord, OFFER_KEYS, type OfferCancelAllRecord, type OfferRecord, type OfferState, type OfferStatus, PKEY, PROFILE_MAX_KEYS, PROFILE_MAX_VALUE_BYTES, type ProposeEvent, REBATE_BPS, REBATE_FLAT, RESERVED_NAMES, SALT_RE, SCORE_CANCEL, SCORE_CLAIM, SCORE_FILL, TICKER_RE, TRANSFER_KEYS, TREASURY_ADDR, type TokenMetaRecord, type TokenState, type TransferRecord, V11_HEIGHT, V12_HEIGHT, V13_HEIGHT, V14_HEIGHT, V15_HEIGHT, V16_HEIGHT, V17_HEIGHT, V18_HEIGHT, V19_HEIGHT, V20_HEIGHT, V21_HEIGHT, V22_HEIGHT, type Want, bid, buildRecord, canonicalState, claimGraceOf, claimWindowAt, claimWindowOf, deploy, epochOf, expiredClaimFee, isName, isNameGive, isTokenWant, makerRebate, mint, nameClaim, nameCommit, nameCommitRecord, nameProfile, nameRegFee, nameRenew, nameSet, nameXfer, offer, offerCancelAll, offerExpiryHeightOf, parseAmount, parseRecord, requiredClaimDepth, resolve, tokenMeta, tradeFee, transfer };
400
+ export { ACTIVATION_HEIGHT, ADDR_RE, AMOUNT_RE, type AppliedEvent, type AttestEvent, BID_KEYS, type BalanceState, type BidRecord, type BidState, type BidStatus, type BuiltRecord, CLAIM_ATTACKER_Q, CLAIM_COOLDOWN_BLOCKS, CLAIM_FILL_GRACE_BLOCKS, CLAIM_MIN_DEPTH, CLAIM_WINDOW_BLOCKS, CLAIM_WINDOW_BLOCKS_V20, COMMIT_MAX_BLOCKS, COMMIT_REVEAL_MIN_DEPTH, CONF_TOKEN_FILL, type CairnXRecord, type CairnXState, type ChainEvent, DEPLOY_FEE, DEPLOY_KEYS, DOMAIN, type DeployRecord, FEE_BPS, FEE_BPS_V16, type FillEntry, type Give, HASH_RE, MAX_ACTIVE_CLAIMS, MAX_AMOUNT, MAX_OFFER_EPOCHS, MAX_RECORD_BYTES, MINT_KEYS, type MintRecord, NAME_FEE_SHORT_V18, NAME_FEE_V18, NAME_GRACE_EPOCHS, NAME_KEYS, NAME_PREMIUM_DECAY_EPOCHS, NAME_PREMIUM_START, NAME_RE, NAME_TERM_EPOCHS, NPROFILE_KEYS, type NameCommitRecord, type NameProfileRecord, type NameRecord, type NameRenewRecord, type NameSetRecord, type NameState, type NameXferRecord, OFFER_KEYS, type OfferCancelAllRecord, type OfferRecord, type OfferState, type OfferStatus, PKEY, PROFILE_MAX_KEYS, PROFILE_MAX_VALUE_BYTES, type ProposeEvent, REBATE_BPS, REBATE_FLAT, RESERVED_NAMES, SALT_RE, SCORE_CANCEL, SCORE_CLAIM, SCORE_FILL, TICKER_RE, TRANSFER_KEYS, TREASURY_ADDR, type TokenMetaRecord, type TokenState, type TransferRecord, V11_HEIGHT, V12_HEIGHT, V13_HEIGHT, V14_HEIGHT, V15_HEIGHT, V16_HEIGHT, V17_HEIGHT, V18_HEIGHT, V19_HEIGHT, V20_HEIGHT, V21_HEIGHT, V22_HEIGHT, V23_HEIGHT, type Want, ZERO_ADDR, bid, buildRecord, canonicalState, claimGraceOf, claimWindowAt, claimWindowOf, deploy, epochOf, expiredClaimFee, isName, isNameGive, isTokenWant, makerRebate, mint, nameClaim, nameCommit, nameCommitRecord, nameProfile, nameRegFee, nameRenew, nameSet, nameXfer, offer, offerCancelAll, offerExpiryHeightOf, parseAmount, parseRecord, requiredClaimDepth, resolve, tokenMeta, tradeFee, transfer };
package/dist/index.d.ts CHANGED
@@ -42,6 +42,8 @@ declare const V20_HEIGHT = 38400;
42
42
  declare const V21_HEIGHT = 40100;
43
43
  declare const MAX_OFFER_EPOCHS = 168;
44
44
  declare const V22_HEIGHT = 41300;
45
+ declare const V23_HEIGHT = 52000;
46
+ declare const ZERO_ADDR: string;
45
47
  declare const PKEY: RegExp;
46
48
  declare const PROFILE_MAX_KEYS = 16;
47
49
  declare const PROFILE_MAX_VALUE_BYTES = 256;
@@ -395,4 +397,4 @@ declare function requiredClaimDepth(valueSats: number | bigint, height: number):
395
397
  capped: boolean;
396
398
  };
397
399
 
398
- export { ACTIVATION_HEIGHT, ADDR_RE, AMOUNT_RE, type AppliedEvent, type AttestEvent, BID_KEYS, type BalanceState, type BidRecord, type BidState, type BidStatus, type BuiltRecord, CLAIM_ATTACKER_Q, CLAIM_COOLDOWN_BLOCKS, CLAIM_FILL_GRACE_BLOCKS, CLAIM_MIN_DEPTH, CLAIM_WINDOW_BLOCKS, CLAIM_WINDOW_BLOCKS_V20, COMMIT_MAX_BLOCKS, COMMIT_REVEAL_MIN_DEPTH, CONF_TOKEN_FILL, type CairnXRecord, type CairnXState, type ChainEvent, DEPLOY_FEE, DEPLOY_KEYS, DOMAIN, type DeployRecord, FEE_BPS, FEE_BPS_V16, type FillEntry, type Give, HASH_RE, MAX_ACTIVE_CLAIMS, MAX_AMOUNT, MAX_OFFER_EPOCHS, MAX_RECORD_BYTES, MINT_KEYS, type MintRecord, NAME_FEE_SHORT_V18, NAME_FEE_V18, NAME_GRACE_EPOCHS, NAME_KEYS, NAME_PREMIUM_DECAY_EPOCHS, NAME_PREMIUM_START, NAME_RE, NAME_TERM_EPOCHS, NPROFILE_KEYS, type NameCommitRecord, type NameProfileRecord, type NameRecord, type NameRenewRecord, type NameSetRecord, type NameState, type NameXferRecord, OFFER_KEYS, type OfferCancelAllRecord, type OfferRecord, type OfferState, type OfferStatus, PKEY, PROFILE_MAX_KEYS, PROFILE_MAX_VALUE_BYTES, type ProposeEvent, REBATE_BPS, REBATE_FLAT, RESERVED_NAMES, SALT_RE, SCORE_CANCEL, SCORE_CLAIM, SCORE_FILL, TICKER_RE, TRANSFER_KEYS, TREASURY_ADDR, type TokenMetaRecord, type TokenState, type TransferRecord, V11_HEIGHT, V12_HEIGHT, V13_HEIGHT, V14_HEIGHT, V15_HEIGHT, V16_HEIGHT, V17_HEIGHT, V18_HEIGHT, V19_HEIGHT, V20_HEIGHT, V21_HEIGHT, V22_HEIGHT, type Want, bid, buildRecord, canonicalState, claimGraceOf, claimWindowAt, claimWindowOf, deploy, epochOf, expiredClaimFee, isName, isNameGive, isTokenWant, makerRebate, mint, nameClaim, nameCommit, nameCommitRecord, nameProfile, nameRegFee, nameRenew, nameSet, nameXfer, offer, offerCancelAll, offerExpiryHeightOf, parseAmount, parseRecord, requiredClaimDepth, resolve, tokenMeta, tradeFee, transfer };
400
+ export { ACTIVATION_HEIGHT, ADDR_RE, AMOUNT_RE, type AppliedEvent, type AttestEvent, BID_KEYS, type BalanceState, type BidRecord, type BidState, type BidStatus, type BuiltRecord, CLAIM_ATTACKER_Q, CLAIM_COOLDOWN_BLOCKS, CLAIM_FILL_GRACE_BLOCKS, CLAIM_MIN_DEPTH, CLAIM_WINDOW_BLOCKS, CLAIM_WINDOW_BLOCKS_V20, COMMIT_MAX_BLOCKS, COMMIT_REVEAL_MIN_DEPTH, CONF_TOKEN_FILL, type CairnXRecord, type CairnXState, type ChainEvent, DEPLOY_FEE, DEPLOY_KEYS, DOMAIN, type DeployRecord, FEE_BPS, FEE_BPS_V16, type FillEntry, type Give, HASH_RE, MAX_ACTIVE_CLAIMS, MAX_AMOUNT, MAX_OFFER_EPOCHS, MAX_RECORD_BYTES, MINT_KEYS, type MintRecord, NAME_FEE_SHORT_V18, NAME_FEE_V18, NAME_GRACE_EPOCHS, NAME_KEYS, NAME_PREMIUM_DECAY_EPOCHS, NAME_PREMIUM_START, NAME_RE, NAME_TERM_EPOCHS, NPROFILE_KEYS, type NameCommitRecord, type NameProfileRecord, type NameRecord, type NameRenewRecord, type NameSetRecord, type NameState, type NameXferRecord, OFFER_KEYS, type OfferCancelAllRecord, type OfferRecord, type OfferState, type OfferStatus, PKEY, PROFILE_MAX_KEYS, PROFILE_MAX_VALUE_BYTES, type ProposeEvent, REBATE_BPS, REBATE_FLAT, RESERVED_NAMES, SALT_RE, SCORE_CANCEL, SCORE_CLAIM, SCORE_FILL, TICKER_RE, TRANSFER_KEYS, TREASURY_ADDR, type TokenMetaRecord, type TokenState, type TransferRecord, V11_HEIGHT, V12_HEIGHT, V13_HEIGHT, V14_HEIGHT, V15_HEIGHT, V16_HEIGHT, V17_HEIGHT, V18_HEIGHT, V19_HEIGHT, V20_HEIGHT, V21_HEIGHT, V22_HEIGHT, V23_HEIGHT, type Want, ZERO_ADDR, bid, buildRecord, canonicalState, claimGraceOf, claimWindowAt, claimWindowOf, deploy, epochOf, expiredClaimFee, isName, isNameGive, isTokenWant, makerRebate, mint, nameClaim, nameCommit, nameCommitRecord, nameProfile, nameRegFee, nameRenew, nameSet, nameXfer, offer, offerCancelAll, offerExpiryHeightOf, parseAmount, parseRecord, requiredClaimDepth, resolve, tokenMeta, tradeFee, transfer };
package/dist/index.js CHANGED
@@ -45,6 +45,8 @@ var V20_HEIGHT = 38400;
45
45
  var V21_HEIGHT = 40100;
46
46
  var MAX_OFFER_EPOCHS = 168;
47
47
  var V22_HEIGHT = 41300;
48
+ var V23_HEIGHT = 52e3;
49
+ var ZERO_ADDR = "0x" + "00".repeat(20);
48
50
  var PKEY = /^[a-z0-9](?:[a-z0-9.-]{0,30}[a-z0-9])?$/;
49
51
  var PROFILE_MAX_KEYS = 16;
50
52
  var PROFILE_MAX_VALUE_BYTES = 256;
@@ -303,6 +305,9 @@ var tokenMeta = (r) => buildRecord({ v: 1, t: "tmeta", ...r });
303
305
  var nameProfile = (r) => buildRecord({ v: 1, t: "nprofile", ...r });
304
306
 
305
307
  // src/resolve.ts
308
+ function ptAmt(v) {
309
+ return typeof v === "string" && AMOUNT_RE.test(v) ? BigInt(v) : 0n;
310
+ }
306
311
  var ord = (a, b) => a < b ? -1 : a > b ? 1 : 0;
307
312
  function resolve(events, tipHeight) {
308
313
  const ordered = [...events].sort(
@@ -412,7 +417,8 @@ function resolve(events, tipHeight) {
412
417
  const v15 = ev.height >= V15_HEIGHT;
413
418
  const v16 = ev.height >= V16_HEIGHT;
414
419
  const v19 = ev.height >= V19_HEIGHT;
415
- const feeToTreasury = ev.kind === "propose" ? BigInt((ev.paidTo ?? {})[TREASURY_ADDR] ?? "0") : 0n;
420
+ const v23 = ev.height >= V23_HEIGHT;
421
+ const feeToTreasury = ev.kind === "propose" ? ptAmt((ev.paidTo ?? {})[TREASURY_ADDR]) : 0n;
416
422
  if (ev.kind === "propose") {
417
423
  const rec = parseRecord(ev.uri, ev.payloadHash);
418
424
  if (!rec) {
@@ -579,7 +585,8 @@ function resolve(events, tipHeight) {
579
585
  note(ev, ev.id, "nset", false, "lease lapsed \u2014 claim it instead");
580
586
  continue;
581
587
  }
582
- n.addr = rec.addr.toLowerCase();
588
+ if (v23 && rec.addr.toLowerCase() === ZERO_ADDR) n.addr = void 0;
589
+ else n.addr = rec.addr.toLowerCase();
583
590
  note(ev, ev.id, "nset", true);
584
591
  } else if (rec.t === "nprofile") {
585
592
  if (!v19) {
@@ -878,7 +885,7 @@ function resolve(events, tipHeight) {
878
885
  const want = BigInt(o.want.value);
879
886
  const paidSoFar = BigInt(o.paid ?? "0");
880
887
  const remaining = want - paidSoFar;
881
- const X = BigInt(pt[o.want.payto] ?? "0");
888
+ const X = ptAmt(pt[o.want.payto]);
882
889
  const minV = BigInt(o.min);
883
890
  const effMin = remaining < minV ? remaining : minV;
884
891
  if (X < effMin) {
@@ -887,7 +894,7 @@ function resolve(events, tipHeight) {
887
894
  }
888
895
  const x = X < remaining ? X : remaining;
889
896
  const fee = o.feeBps ? tradeFee(x, o.feeBps) : 0n;
890
- if (BigInt(pt[TREASURY_ADDR] ?? "0") < fee) {
897
+ if (ptAmt(pt[TREASURY_ADDR]) < fee) {
891
898
  note(ev, ev.txid, "fill", false, "protocol fee unpaid");
892
899
  continue;
893
900
  }
@@ -945,7 +952,7 @@ function resolve(events, tipHeight) {
945
952
  addNeed(TREASURY_ADDR, fee);
946
953
  if (rebate > 0n) addNeed(o.seller, rebate);
947
954
  let unpaid;
948
- for (const [addr, amt] of need) if (BigInt(pt[addr] ?? "0") < amt) {
955
+ for (const [addr, amt] of need) if (ptAmt(pt[addr]) < amt) {
949
956
  unpaid = addr === TREASURY_ADDR ? "protocol fee unpaid" : rebate > 0n && addr === o.seller ? "maker rebate unpaid (v1.6)" : "payment below want.value";
950
957
  break;
951
958
  }
@@ -953,7 +960,7 @@ function resolve(events, tipHeight) {
953
960
  note(ev, ev.txid, "fill", false, unpaid);
954
961
  continue;
955
962
  }
956
- const paid = BigInt(pt[o.want.payto] ?? "0");
963
+ const paid = ptAmt(pt[o.want.payto]);
957
964
  if (isNameGive(o.give)) {
958
965
  const n = names.get(o.give.name);
959
966
  if (!n) {
@@ -1151,6 +1158,8 @@ export {
1151
1158
  V20_HEIGHT,
1152
1159
  V21_HEIGHT,
1153
1160
  V22_HEIGHT,
1161
+ V23_HEIGHT,
1162
+ ZERO_ADDR,
1154
1163
  bid,
1155
1164
  blockReward2 as blockReward,
1156
1165
  buildRecord,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inversealtruism/cairnx-core",
3
- "version": "0.1.20",
3
+ "version": "0.1.23",
4
4
  "description": "CairnX — tokens, atomic DvP trades and leased .csd names on Compute Substrate, as a pure deterministic convention library (Ordinals/Runes class). Ships the normative CONVENTION.md and the conformance vectors.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",