@inversealtruism/cairnx-core 0.1.19 → 0.1.22

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,59 +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
279
+
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`.
39
284
 
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.
285
+ ---
47
286
 
48
- ## Versions (activation heights are consensus-grade — never reinterpret history)
287
+ ## 6 · ★ Single source of truth, change consensus without drift
49
288
 
50
- | | height | what |
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` |
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.
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) |
302
+
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).
308
+
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.
311
+
312
+ ---
313
+
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
@@ -83,6 +83,9 @@ __export(index_exports, {
83
83
  V19_HEIGHT: () => V19_HEIGHT,
84
84
  V20_HEIGHT: () => V20_HEIGHT,
85
85
  V21_HEIGHT: () => V21_HEIGHT,
86
+ V22_HEIGHT: () => V22_HEIGHT,
87
+ V23_HEIGHT: () => V23_HEIGHT,
88
+ ZERO_ADDR: () => ZERO_ADDR,
86
89
  bid: () => bid,
87
90
  blockReward: () => import_csd_codec4.blockReward,
88
91
  buildRecord: () => buildRecord,
@@ -167,6 +170,9 @@ var V19_HEIGHT = 36700;
167
170
  var V20_HEIGHT = 38400;
168
171
  var V21_HEIGHT = 40100;
169
172
  var MAX_OFFER_EPOCHS = 168;
173
+ var V22_HEIGHT = 41300;
174
+ var V23_HEIGHT = 52e3;
175
+ var ZERO_ADDR = "0x" + "00".repeat(20);
170
176
  var PKEY = /^[a-z0-9](?:[a-z0-9.-]{0,30}[a-z0-9])?$/;
171
177
  var PROFILE_MAX_KEYS = 16;
172
178
  var PROFILE_MAX_VALUE_BYTES = 256;
@@ -195,6 +201,7 @@ var claimWindowOf = (claimUntilHeight) => claimUntilHeight - CLAIM_WINDOW_BLOCKS
195
201
  var claimGraceOf = (claimUntilHeight) => claimUntilHeight - CLAIM_WINDOW_BLOCKS_V20 >= V20_HEIGHT ? CLAIM_FILL_GRACE_BLOCKS : 0;
196
202
  var offerExpiryHeightOf = (expiresEpoch, anchorHeight) => {
197
203
  const raw = (Number(expiresEpoch ?? 0) + 1) * import_csd_codec.EPOCH_LEN;
204
+ if (anchorHeight >= V22_HEIGHT) return raw;
198
205
  const capped = (epochOf(anchorHeight) + MAX_OFFER_EPOCHS + 1) * import_csd_codec.EPOCH_LEN;
199
206
  return Math.min(raw, Math.max(V21_HEIGHT, capped));
200
207
  };
@@ -424,6 +431,9 @@ var tokenMeta = (r) => buildRecord({ v: 1, t: "tmeta", ...r });
424
431
  var nameProfile = (r) => buildRecord({ v: 1, t: "nprofile", ...r });
425
432
 
426
433
  // src/resolve.ts
434
+ function ptAmt(v) {
435
+ return typeof v === "string" && AMOUNT_RE.test(v) ? BigInt(v) : 0n;
436
+ }
427
437
  var ord = (a, b) => a < b ? -1 : a > b ? 1 : 0;
428
438
  function resolve(events, tipHeight) {
429
439
  const ordered = [...events].sort(
@@ -472,7 +482,7 @@ function resolve(events, tipHeight) {
472
482
  b.available += amt;
473
483
  }
474
484
  };
475
- const effExpiry = (e, height) => height >= V21_HEIGHT ? Math.min(e.expiresEpoch, epochOf(e.height) + MAX_OFFER_EPOCHS) : e.expiresEpoch;
485
+ const effExpiry = (e, height) => e.height >= V22_HEIGHT ? e.expiresEpoch : height >= V21_HEIGHT ? Math.min(e.expiresEpoch, epochOf(e.height) + MAX_OFFER_EPOCHS) : e.expiresEpoch;
476
486
  const sweepExpired = (height) => {
477
487
  const ep = epochOf(height);
478
488
  for (const o of offers.values()) {
@@ -533,7 +543,8 @@ function resolve(events, tipHeight) {
533
543
  const v15 = ev.height >= V15_HEIGHT;
534
544
  const v16 = ev.height >= V16_HEIGHT;
535
545
  const v19 = ev.height >= V19_HEIGHT;
536
- 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;
537
548
  if (ev.kind === "propose") {
538
549
  const rec = parseRecord(ev.uri, ev.payloadHash);
539
550
  if (!rec) {
@@ -700,7 +711,8 @@ function resolve(events, tipHeight) {
700
711
  note(ev, ev.id, "nset", false, "lease lapsed \u2014 claim it instead");
701
712
  continue;
702
713
  }
703
- n.addr = rec.addr.toLowerCase();
714
+ if (v23 && rec.addr.toLowerCase() === ZERO_ADDR) n.addr = void 0;
715
+ else n.addr = rec.addr.toLowerCase();
704
716
  note(ev, ev.id, "nset", true);
705
717
  } else if (rec.t === "nprofile") {
706
718
  if (!v19) {
@@ -741,7 +753,7 @@ function resolve(events, tipHeight) {
741
753
  note(ev, ev.id, "offer", false, "already expired at anchor");
742
754
  continue;
743
755
  }
744
- if (ev.height >= V21_HEIGHT && ev.expiresEpoch - epochOf(ev.height) > MAX_OFFER_EPOCHS) {
756
+ if (ev.height >= V21_HEIGHT && ev.height < V22_HEIGHT && ev.expiresEpoch - epochOf(ev.height) > MAX_OFFER_EPOCHS) {
745
757
  note(ev, ev.id, "offer", false, "v2.1: offer duration exceeds the max");
746
758
  continue;
747
759
  }
@@ -814,7 +826,7 @@ function resolve(events, tipHeight) {
814
826
  note(ev, ev.id, "bid", false, "already expired at anchor");
815
827
  continue;
816
828
  }
817
- if (ev.height >= V21_HEIGHT && ev.expiresEpoch - epochOf(ev.height) > MAX_OFFER_EPOCHS) {
829
+ if (ev.height >= V21_HEIGHT && ev.height < V22_HEIGHT && ev.expiresEpoch - epochOf(ev.height) > MAX_OFFER_EPOCHS) {
818
830
  note(ev, ev.id, "bid", false, "v2.1: bid duration exceeds the max");
819
831
  continue;
820
832
  }
@@ -999,7 +1011,7 @@ function resolve(events, tipHeight) {
999
1011
  const want = BigInt(o.want.value);
1000
1012
  const paidSoFar = BigInt(o.paid ?? "0");
1001
1013
  const remaining = want - paidSoFar;
1002
- const X = BigInt(pt[o.want.payto] ?? "0");
1014
+ const X = ptAmt(pt[o.want.payto]);
1003
1015
  const minV = BigInt(o.min);
1004
1016
  const effMin = remaining < minV ? remaining : minV;
1005
1017
  if (X < effMin) {
@@ -1008,7 +1020,7 @@ function resolve(events, tipHeight) {
1008
1020
  }
1009
1021
  const x = X < remaining ? X : remaining;
1010
1022
  const fee = o.feeBps ? tradeFee(x, o.feeBps) : 0n;
1011
- if (BigInt(pt[TREASURY_ADDR] ?? "0") < fee) {
1023
+ if (ptAmt(pt[TREASURY_ADDR]) < fee) {
1012
1024
  note(ev, ev.txid, "fill", false, "protocol fee unpaid");
1013
1025
  continue;
1014
1026
  }
@@ -1066,7 +1078,7 @@ function resolve(events, tipHeight) {
1066
1078
  addNeed(TREASURY_ADDR, fee);
1067
1079
  if (rebate > 0n) addNeed(o.seller, rebate);
1068
1080
  let unpaid;
1069
- for (const [addr, amt] of need) if (BigInt(pt[addr] ?? "0") < amt) {
1081
+ for (const [addr, amt] of need) if (ptAmt(pt[addr]) < amt) {
1070
1082
  unpaid = addr === TREASURY_ADDR ? "protocol fee unpaid" : rebate > 0n && addr === o.seller ? "maker rebate unpaid (v1.6)" : "payment below want.value";
1071
1083
  break;
1072
1084
  }
@@ -1074,7 +1086,7 @@ function resolve(events, tipHeight) {
1074
1086
  note(ev, ev.txid, "fill", false, unpaid);
1075
1087
  continue;
1076
1088
  }
1077
- const paid = BigInt(pt[o.want.payto] ?? "0");
1089
+ const paid = ptAmt(pt[o.want.payto]);
1078
1090
  if (isNameGive(o.give)) {
1079
1091
  const n = names.get(o.give.name);
1080
1092
  if (!n) {
@@ -1263,6 +1275,9 @@ var import_csd_codec4 = require("@inversealtruism/csd-codec");
1263
1275
  V19_HEIGHT,
1264
1276
  V20_HEIGHT,
1265
1277
  V21_HEIGHT,
1278
+ V22_HEIGHT,
1279
+ V23_HEIGHT,
1280
+ ZERO_ADDR,
1266
1281
  bid,
1267
1282
  blockReward,
1268
1283
  buildRecord,
package/dist/index.d.cts CHANGED
@@ -41,6 +41,9 @@ declare const V19_HEIGHT = 36700;
41
41
  declare const V20_HEIGHT = 38400;
42
42
  declare const V21_HEIGHT = 40100;
43
43
  declare const MAX_OFFER_EPOCHS = 168;
44
+ declare const V22_HEIGHT = 41300;
45
+ declare const V23_HEIGHT = 52000;
46
+ declare const ZERO_ADDR: string;
44
47
  declare const PKEY: RegExp;
45
48
  declare const PROFILE_MAX_KEYS = 16;
46
49
  declare const PROFILE_MAX_VALUE_BYTES = 256;
@@ -394,4 +397,4 @@ declare function requiredClaimDepth(valueSats: number | bigint, height: number):
394
397
  capped: boolean;
395
398
  };
396
399
 
397
- 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, 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
@@ -41,6 +41,9 @@ declare const V19_HEIGHT = 36700;
41
41
  declare const V20_HEIGHT = 38400;
42
42
  declare const V21_HEIGHT = 40100;
43
43
  declare const MAX_OFFER_EPOCHS = 168;
44
+ declare const V22_HEIGHT = 41300;
45
+ declare const V23_HEIGHT = 52000;
46
+ declare const ZERO_ADDR: string;
44
47
  declare const PKEY: RegExp;
45
48
  declare const PROFILE_MAX_KEYS = 16;
46
49
  declare const PROFILE_MAX_VALUE_BYTES = 256;
@@ -394,4 +397,4 @@ declare function requiredClaimDepth(valueSats: number | bigint, height: number):
394
397
  capped: boolean;
395
398
  };
396
399
 
397
- 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, 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
@@ -44,6 +44,9 @@ var V19_HEIGHT = 36700;
44
44
  var V20_HEIGHT = 38400;
45
45
  var V21_HEIGHT = 40100;
46
46
  var MAX_OFFER_EPOCHS = 168;
47
+ var V22_HEIGHT = 41300;
48
+ var V23_HEIGHT = 52e3;
49
+ var ZERO_ADDR = "0x" + "00".repeat(20);
47
50
  var PKEY = /^[a-z0-9](?:[a-z0-9.-]{0,30}[a-z0-9])?$/;
48
51
  var PROFILE_MAX_KEYS = 16;
49
52
  var PROFILE_MAX_VALUE_BYTES = 256;
@@ -72,6 +75,7 @@ var claimWindowOf = (claimUntilHeight) => claimUntilHeight - CLAIM_WINDOW_BLOCKS
72
75
  var claimGraceOf = (claimUntilHeight) => claimUntilHeight - CLAIM_WINDOW_BLOCKS_V20 >= V20_HEIGHT ? CLAIM_FILL_GRACE_BLOCKS : 0;
73
76
  var offerExpiryHeightOf = (expiresEpoch, anchorHeight) => {
74
77
  const raw = (Number(expiresEpoch ?? 0) + 1) * EPOCH_LEN;
78
+ if (anchorHeight >= V22_HEIGHT) return raw;
75
79
  const capped = (epochOf(anchorHeight) + MAX_OFFER_EPOCHS + 1) * EPOCH_LEN;
76
80
  return Math.min(raw, Math.max(V21_HEIGHT, capped));
77
81
  };
@@ -301,6 +305,9 @@ var tokenMeta = (r) => buildRecord({ v: 1, t: "tmeta", ...r });
301
305
  var nameProfile = (r) => buildRecord({ v: 1, t: "nprofile", ...r });
302
306
 
303
307
  // src/resolve.ts
308
+ function ptAmt(v) {
309
+ return typeof v === "string" && AMOUNT_RE.test(v) ? BigInt(v) : 0n;
310
+ }
304
311
  var ord = (a, b) => a < b ? -1 : a > b ? 1 : 0;
305
312
  function resolve(events, tipHeight) {
306
313
  const ordered = [...events].sort(
@@ -349,7 +356,7 @@ function resolve(events, tipHeight) {
349
356
  b.available += amt;
350
357
  }
351
358
  };
352
- const effExpiry = (e, height) => height >= V21_HEIGHT ? Math.min(e.expiresEpoch, epochOf(e.height) + MAX_OFFER_EPOCHS) : e.expiresEpoch;
359
+ const effExpiry = (e, height) => e.height >= V22_HEIGHT ? e.expiresEpoch : height >= V21_HEIGHT ? Math.min(e.expiresEpoch, epochOf(e.height) + MAX_OFFER_EPOCHS) : e.expiresEpoch;
353
360
  const sweepExpired = (height) => {
354
361
  const ep = epochOf(height);
355
362
  for (const o of offers.values()) {
@@ -410,7 +417,8 @@ function resolve(events, tipHeight) {
410
417
  const v15 = ev.height >= V15_HEIGHT;
411
418
  const v16 = ev.height >= V16_HEIGHT;
412
419
  const v19 = ev.height >= V19_HEIGHT;
413
- 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;
414
422
  if (ev.kind === "propose") {
415
423
  const rec = parseRecord(ev.uri, ev.payloadHash);
416
424
  if (!rec) {
@@ -577,7 +585,8 @@ function resolve(events, tipHeight) {
577
585
  note(ev, ev.id, "nset", false, "lease lapsed \u2014 claim it instead");
578
586
  continue;
579
587
  }
580
- n.addr = rec.addr.toLowerCase();
588
+ if (v23 && rec.addr.toLowerCase() === ZERO_ADDR) n.addr = void 0;
589
+ else n.addr = rec.addr.toLowerCase();
581
590
  note(ev, ev.id, "nset", true);
582
591
  } else if (rec.t === "nprofile") {
583
592
  if (!v19) {
@@ -618,7 +627,7 @@ function resolve(events, tipHeight) {
618
627
  note(ev, ev.id, "offer", false, "already expired at anchor");
619
628
  continue;
620
629
  }
621
- if (ev.height >= V21_HEIGHT && ev.expiresEpoch - epochOf(ev.height) > MAX_OFFER_EPOCHS) {
630
+ if (ev.height >= V21_HEIGHT && ev.height < V22_HEIGHT && ev.expiresEpoch - epochOf(ev.height) > MAX_OFFER_EPOCHS) {
622
631
  note(ev, ev.id, "offer", false, "v2.1: offer duration exceeds the max");
623
632
  continue;
624
633
  }
@@ -691,7 +700,7 @@ function resolve(events, tipHeight) {
691
700
  note(ev, ev.id, "bid", false, "already expired at anchor");
692
701
  continue;
693
702
  }
694
- if (ev.height >= V21_HEIGHT && ev.expiresEpoch - epochOf(ev.height) > MAX_OFFER_EPOCHS) {
703
+ if (ev.height >= V21_HEIGHT && ev.height < V22_HEIGHT && ev.expiresEpoch - epochOf(ev.height) > MAX_OFFER_EPOCHS) {
695
704
  note(ev, ev.id, "bid", false, "v2.1: bid duration exceeds the max");
696
705
  continue;
697
706
  }
@@ -876,7 +885,7 @@ function resolve(events, tipHeight) {
876
885
  const want = BigInt(o.want.value);
877
886
  const paidSoFar = BigInt(o.paid ?? "0");
878
887
  const remaining = want - paidSoFar;
879
- const X = BigInt(pt[o.want.payto] ?? "0");
888
+ const X = ptAmt(pt[o.want.payto]);
880
889
  const minV = BigInt(o.min);
881
890
  const effMin = remaining < minV ? remaining : minV;
882
891
  if (X < effMin) {
@@ -885,7 +894,7 @@ function resolve(events, tipHeight) {
885
894
  }
886
895
  const x = X < remaining ? X : remaining;
887
896
  const fee = o.feeBps ? tradeFee(x, o.feeBps) : 0n;
888
- if (BigInt(pt[TREASURY_ADDR] ?? "0") < fee) {
897
+ if (ptAmt(pt[TREASURY_ADDR]) < fee) {
889
898
  note(ev, ev.txid, "fill", false, "protocol fee unpaid");
890
899
  continue;
891
900
  }
@@ -943,7 +952,7 @@ function resolve(events, tipHeight) {
943
952
  addNeed(TREASURY_ADDR, fee);
944
953
  if (rebate > 0n) addNeed(o.seller, rebate);
945
954
  let unpaid;
946
- for (const [addr, amt] of need) if (BigInt(pt[addr] ?? "0") < amt) {
955
+ for (const [addr, amt] of need) if (ptAmt(pt[addr]) < amt) {
947
956
  unpaid = addr === TREASURY_ADDR ? "protocol fee unpaid" : rebate > 0n && addr === o.seller ? "maker rebate unpaid (v1.6)" : "payment below want.value";
948
957
  break;
949
958
  }
@@ -951,7 +960,7 @@ function resolve(events, tipHeight) {
951
960
  note(ev, ev.txid, "fill", false, unpaid);
952
961
  continue;
953
962
  }
954
- const paid = BigInt(pt[o.want.payto] ?? "0");
963
+ const paid = ptAmt(pt[o.want.payto]);
955
964
  if (isNameGive(o.give)) {
956
965
  const n = names.get(o.give.name);
957
966
  if (!n) {
@@ -1148,6 +1157,9 @@ export {
1148
1157
  V19_HEIGHT,
1149
1158
  V20_HEIGHT,
1150
1159
  V21_HEIGHT,
1160
+ V22_HEIGHT,
1161
+ V23_HEIGHT,
1162
+ ZERO_ADDR,
1151
1163
  bid,
1152
1164
  blockReward2 as blockReward,
1153
1165
  buildRecord,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inversealtruism/cairnx-core",
3
- "version": "0.1.19",
3
+ "version": "0.1.22",
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",
@@ -21,8 +21,12 @@
21
21
  "MAKERS.md",
22
22
  "test/vectors"
23
23
  ],
24
+ "scripts": {
25
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
26
+ "test": "tsx test/vectors.test.ts && tsx test/name-decoy.test.ts && tsx test/client-helpers.test.ts"
27
+ },
24
28
  "dependencies": {
25
- "@inversealtruism/csd-codec": "0.1.14"
29
+ "@inversealtruism/csd-codec": "workspace:*"
26
30
  },
27
31
  "license": "MIT",
28
32
  "sideEffects": false,
@@ -34,9 +38,5 @@
34
38
  "url": "git+https://github.com/InverseAltruism/csd-sdk.git",
35
39
  "directory": "packages/cairnx"
36
40
  },
37
- "homepage": "https://cairn-substrate.com/trade",
38
- "scripts": {
39
- "build": "tsup src/index.ts --format esm,cjs --dts --clean",
40
- "test": "tsx test/vectors.test.ts && tsx test/name-decoy.test.ts && tsx test/client-helpers.test.ts"
41
- }
42
- }
41
+ "homepage": "https://cairn-substrate.com/trade"
42
+ }