@inversealtruism/cairnx-core 0.2.7 → 0.2.9

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
@@ -101,7 +101,7 @@ stateDiagram-v2
101
101
  Active --> Grace: lease term ends (~1 year)
102
102
  Grace --> Active: nrenew · OWNER ONLY, ~30-day window
103
103
  Grace --> Lapsed: grace ends un-renewed
104
- Lapsed --> Active: recapture · anyone re-claims at a DECAYING premium (20x to 1x over ~30 days), fresh lease
104
+ Lapsed --> Active: recapture · anyone re-claims at a DECAYING premium (19x stepping down to 1x over about 28 days), fresh lease
105
105
  Active --> [*]
106
106
  ```
107
107
 
@@ -115,7 +115,7 @@ stateDiagram-v2
115
115
  (`nprofile`), transfer it (`nxfer`), renew it (`nrenew`), or list it for sale.
116
116
  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.
117
117
  4. **Lapsed → decaying-premium recapture.** If grace passes un-renewed, anyone may re-claim, but at a
118
- **premium that decays 20× → 1×** over ~30 days (a Dutch auction back to the floor price). This prices
118
+ **premium of 19× stepping down to 1×** over about 28 days (CONVENTION section 17; a Dutch auction back to the floor price). This prices
119
119
  in genuine demand without a permanent squatting tax, and a recaptured name gets a fresh ownership basis
120
120
  so a stale pre-lapse commit can't steal it.
121
121
 
@@ -137,7 +137,7 @@ stateDiagram-v2
137
137
  |---|---|---|
138
138
  | Lease term | ~1 year (`NAME_TERM_EPOCHS = 8760`) | 1 epoch ≈ 1 h (30 blocks) |
139
139
  | Grace window | ~30 days (`NAME_GRACE_EPOCHS = 720`) | owner-only renewal |
140
- | Recapture premium | **20× → 1×** over ~30 days | decaying Dutch auction on lapsed names |
140
+ | Recapture premium | **19× stepping down to 1×** over about 28 days (CONVENTION section 17) | decaying Dutch auction on lapsed names |
141
141
  | Reveal window | ~16 min (`REG_COMMIT_MAX_BLOCKS = 8`, v2.5+; was 240 blocks below v2.5) | commit-reveal deadline; doubles as the displacement freeze |
142
142
  | Registration fee | **15 / 10 / 5 / 3 CSD** by length (≤3 / 4 / 5-9 / ≥10 chars, v2.4) | length-graded (was flat 6.7 / 3 CSD under v1.8); paid to the treasury at finalize (v2.5+) |
143
143
 
@@ -175,6 +175,11 @@ sequenceDiagram
175
175
  a name that does not resolve or whose lease lapsed, and at signing it re-checks and refuses an address change
176
176
  or a drop from verified to not verified. The wallet's `SECURITY.md` ("What happens when the sources
177
177
  disagree") is the full list.
178
+ - **The rule a resolved name follows** is `resolveNameIn(state.names, name)` (CONVENTION §35.4): the `nset` address,
179
+ else the owner; a pending reservation and an absent name resolve to nothing; a lapsed lease resolves with
180
+ `lapsed: true`, which a sender refuses. `nameView` gives what a reader shows: the class (held, pending, lapsed, free,
181
+ reserved), the owner, and a held name's address and profile. The reference service's `/cairnx/resolve/:name` answers
182
+ with the first, and `test/vectors/forward.json` pins both.
178
183
  - **Reverse resolution (`address → primary name`, a display label) is server-trusted.** It is never a send
179
184
  target, an identity badge only, so it is cheaper and clearly bounded as "unverified label."
180
185
  - **Ownership has an unambiguous total order:** lowest `(effectiveHeight, position, ordinal-id)` wins, with
@@ -285,7 +290,8 @@ from a block to events, CONVENTION §33) · `src/hashes.ts` (the state and event
285
290
  height-gated client selectors) · `src/client.ts` (the claim-burial depth a payer waits for, sized against a minority miner) · `src/preflight.ts`
286
291
  (build-side helpers every host must compute identically: `requiredFillOutputs`, `previewFill`/`fillIsSafe`,
287
292
  `buildFeeHeight` + `NAME_FEE_GATES`, `finalizeWinnerCheck`) · `src/primary.ts` (`pickPrimaryName` /
288
- `primaryRankBefore`, the one primary-name selection every host must agree on) · `src/mm/` (the
293
+ `primaryRankBefore`, the one primary-name selection every host must agree on) · `src/forward.ts` (`resolveNameIn` / `nameView`, forward
294
+ resolution, §35.4) · `src/mm/` (the
289
295
  `@inversealtruism/cairnx-core/mm` subpath: the market maker's bid sizer, fill notional, Sunrise spot curve and
290
296
  order pricing, and the RFQ all-in sum; not consensus and not part of the root export) · `CONVENTION.md`
291
297
  (normative spec, §1–§39) · `test/vectors/` (portable conformance corpus).
@@ -312,6 +318,10 @@ const state = resolve(events, tipHeight);
312
318
  console.log(state.names, state.tokens.CAIRN, state.balances.CAIRN);
313
319
  ```
314
320
 
321
+ For inputs made of plain values (what JSON carries), a release that changes no rule (`CONSENSUS_CHANGES.md`) returns
322
+ what the previous core returned and throws where it threw, and only event heights and a tip that are safe integers,
323
+ as a chain produces them, are consensus, so check both before the call (`CONVENTION.md` section 5).
324
+
315
325
  ### What a resolver result proves
316
326
 
317
327
  - Display: an answer read from someone's API. It is worth the trust you place in that API.
@@ -329,16 +339,24 @@ Why a record was applied or refused: each entry of `resolve(...).events` carries
329
339
  `REASON_CODES`), and `explainRecord(uri, payloadHash)` names the rule a record breaks before it reaches the resolver.
330
340
  Match the code, never the `note` text, which may change; a code your release does not know reads by the entry's `ok`.
331
341
 
342
+ Who received which tokens in which record: an applied entry that moved tokens carries `moves` (`CONVENTION.md` §41,
343
+ `TokenMove`), each `{ leg, ticker, from, to, amount }` with the leg `mint`, `xfer`, `sale`, `fee` or `fill`, written
344
+ where the resolver moves the balance. A deposit credit is a move whose `to` is the receiving address; read the amount
345
+ from the move, not from the record, since a mint is capped and a partial fill delivers by its floor. A server that
346
+ credits a listed token by ticker also pins `tokens[ticker].deployId`, since a replay of another chain can bind the
347
+ ticker to another deploy. Moves are outside canonical state, so they change no hash.
348
+
332
349
  ### Write a conformant resolver in another language
333
350
 
334
351
  1. Implement `CONVENTION.md` §1–§34 (the events of a block, apply order, every record type, the `V*_HEIGHT`
335
352
  activations (using the re-pinned v2.4–v2.7 heights), the canonical-state format, ordinal key ordering, data
336
353
  surface only).
337
- 2. Reproduce `test/vectors/events.json` (§33.7). Replay `test/vectors/cases.json`, `cases-v29.json` and
338
- `cases-rules.json`: your canonical state must equal `expectedState` **byte-for-byte**.
354
+ 2. Reproduce `test/vectors/events.json` (§33.7). Replay `test/vectors/cases.json`, `cases-v29.json`,
355
+ `cases-rules.json` and `cases-convention.json`: your canonical state must equal `expectedState` **byte-for-byte**.
339
356
  3. Replay the live chain and compare the state hash (§34.1) against `test/vectors/replay-hashes.json`, and reproduce
340
357
  `test/vectors/hashes.json` (§34.4).
341
358
  4. Only if you publish reason codes (§40): reproduce `test/vectors/codes.json`.
359
+ 5. Only if you publish token moves (§41): reproduce `test/vectors/moves.json`.
342
360
 
343
361
  ---
344
362
 
package/dist/index.cjs CHANGED
@@ -24,6 +24,7 @@ __export(index_exports, {
24
24
  ADDR_RE: () => ADDR_RE,
25
25
  AMOUNT_RE: () => AMOUNT_RE,
26
26
  BID_KEYS: () => BID_KEYS,
27
+ CAIRNX_CORE_VERSION: () => CAIRNX_CORE_VERSION,
27
28
  CAIRNX_EVENT_RULE: () => CAIRNX_EVENT_RULE,
28
29
  CAP_CODES: () => CAP_CODES,
29
30
  CLAIM_ATTACKER_Q: () => CLAIM_ATTACKER_Q,
@@ -51,6 +52,7 @@ __export(index_exports, {
51
52
  FINALIZE_TIP_MARGIN: () => FINALIZE_TIP_MARGIN,
52
53
  FINAL_DEPTH: () => FINAL_DEPTH,
53
54
  GAP_NEEDED: () => GAP_NEEDED,
55
+ GATE_HEIGHTS: () => GATE_HEIGHTS,
54
56
  HALVING_INTERVAL: () => import_csd_codec7.HALVING_INTERVAL,
55
57
  HASH_RE: () => HASH_RE,
56
58
  INITIAL_REWARD: () => import_csd_codec7.INITIAL_REWARD,
@@ -169,6 +171,7 @@ __export(index_exports, {
169
171
  nameRegFee: () => nameRegFee,
170
172
  nameRenew: () => nameRenew,
171
173
  nameSet: () => nameSet,
174
+ nameView: () => nameView,
172
175
  nameXfer: () => nameXfer,
173
176
  offer: () => offer,
174
177
  offerCancelAll: () => offerCancelAll,
@@ -188,6 +191,7 @@ __export(index_exports, {
188
191
  requiredClaimDepth: () => requiredClaimDepth,
189
192
  requiredFillOutputs: () => requiredFillOutputs,
190
193
  resolve: () => resolve,
194
+ resolveNameIn: () => resolveNameIn,
191
195
  stateHash: () => stateHash,
192
196
  tokenMeta: () => tokenMeta,
193
197
  tradeFee: () => tradeFee,
@@ -576,6 +580,7 @@ var fclaim = (r) => buildRecord({ v: 1, t: "fclaim", ...r });
576
580
  function ptAmt(v) {
577
581
  return typeof v === "string" && AMOUNT_RE.test(v) ? BigInt(v) : 0n;
578
582
  }
583
+ var tokenMove = (leg, ticker, from, to, amount) => ({ leg, ticker, from, to, amount: amount.toString() });
579
584
  var effExpiry = (e, height) => e.height >= V22_HEIGHT ? e.expiresEpoch : height >= V21_HEIGHT ? Math.min(e.expiresEpoch, (0, import_csd_codec.epochOf)(e.height) + MAX_OFFER_EPOCHS) : e.expiresEpoch;
580
585
  var claimGrace = (o) => o.claimUntilHeight !== void 0 ? claimGraceOf(o.claimUntilHeight, o.claimTxid) : 0;
581
586
  var claimHeld = (o, height) => o.claimedBy !== void 0 && o.claimUntilHeight !== void 0 && height < o.claimUntilHeight + claimGrace(o);
@@ -628,9 +633,13 @@ function createContext(store) {
628
633
  bal(t, o.seller).locked -= amt;
629
634
  bal(t, who).available += amt;
630
635
  offerLock.delete(o.id);
636
+ return tokenMove("fill", t, o.seller, who, amt);
631
637
  };
632
- const entry = (e, id, kind, ok, code, why) => log.push({ height: e.height, pos: e.pos, id, kind, ok, code, ...why ? { note: why } : {} });
633
- const applied = (e, id, kind, code, why) => entry(e, id, kind, true, code, why);
638
+ const entry = (e, id, kind, ok, code, why, moves) => {
639
+ const written = moves?.filter((m) => m.amount !== "0") ?? [];
640
+ log.push({ height: e.height, pos: e.pos, id, kind, ok, code, ...why ? { note: why } : {}, ...written.length ? { moves: written } : {} });
641
+ };
642
+ const applied = (e, id, kind, code, why, moves) => entry(e, id, kind, true, code, why, moves);
634
643
  const refused = (e, id, kind, code, why) => entry(e, id, kind, false, code, why);
635
644
  return {
636
645
  tokens,
@@ -793,13 +802,17 @@ function applyTokenFill(c, ev, o, who) {
793
802
  }
794
803
  buyer.available -= amt + fee;
795
804
  bal(o.want.ticker, o.want.payto).available += amt;
796
- if (fee > 0n) bal(o.want.ticker, TREASURY_ADDR).available += fee;
805
+ const moves = [tokenMove("sale", o.want.ticker, who, o.want.payto, amt)];
806
+ if (fee > 0n) {
807
+ bal(o.want.ticker, TREASURY_ADDR).available += fee;
808
+ moves.push(tokenMove("fee", o.want.ticker, who, TREASURY_ADDR, fee));
809
+ }
797
810
  if (isNameGive(o.give)) deliverNameToBuyer(c, o.give.name, giveName, who, ev);
798
- else releaseGiveLock(o, who, giveLock);
811
+ else moves.push(releaseGiveLock(o, who, giveLock));
799
812
  setOfferStatus(o, "filled");
800
813
  o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: amt.toString(), fee: fee.toString() };
801
814
  markBidDone(o, who);
802
- applied(ev, ev.txid, "fill", "FILL_APPLIED");
815
+ applied(ev, ev.txid, "fill", "FILL_APPLIED", void 0, moves);
803
816
  }
804
817
  function applyPartialFill(c, ev, o, who) {
805
818
  const { offerLock, bal, applied, refused, setOfferStatus, markBidDone } = c;
@@ -849,6 +862,7 @@ function applyPartialFill(c, ev, o, who) {
849
862
  }
850
863
  bal(o.give.ticker, o.seller).locked -= out;
851
864
  bal(o.give.ticker, who).available += out;
865
+ const moves = [tokenMove("fill", o.give.ticker, o.seller, who, out)];
852
866
  offerLock.set(o.id, lock - out);
853
867
  o.paid = newPaid.toString();
854
868
  o.delivered = newDelivered.toString();
@@ -861,7 +875,7 @@ function applyPartialFill(c, ev, o, who) {
861
875
  offerLock.delete(o.id);
862
876
  markBidDone(o, who);
863
877
  }
864
- applied(ev, ev.txid, "fill", "FILL_PARTIAL", `partial ${x}/${want}`);
878
+ applied(ev, ev.txid, "fill", "FILL_PARTIAL", `partial ${x}/${want}`, moves);
865
879
  }
866
880
  function applyFill(c, ev, o, who) {
867
881
  const { names, offerLock, applied, refused, setOfferStatus, markBidDone, releaseGiveLock } = c;
@@ -898,6 +912,7 @@ function applyFill(c, ev, o, who) {
898
912
  return;
899
913
  }
900
914
  const paid = ptAmt(pt[o.want.payto]);
915
+ const moves = [];
901
916
  if (isNameGive(o.give)) {
902
917
  const n = names.get(o.give.name);
903
918
  if (!n) {
@@ -911,13 +926,13 @@ function applyFill(c, ev, o, who) {
911
926
  refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "offer lock missing");
912
927
  return;
913
928
  }
914
- releaseGiveLock(o, who, amt);
929
+ moves.push(releaseGiveLock(o, who, amt));
915
930
  }
916
931
  c.feesPaid += fee;
917
932
  setOfferStatus(o, "filled");
918
933
  o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: paid.toString(), fee: fee.toString() };
919
934
  markBidDone(o, who);
920
- applied(ev, ev.txid, "fill", "FILL_APPLIED");
935
+ applied(ev, ev.txid, "fill", "FILL_APPLIED", void 0, moves);
921
936
  }
922
937
  function applyLegacyClaim(c, ev, o, who) {
923
938
  const { applied, refused, store } = c;
@@ -962,6 +977,10 @@ var MinQueue = class {
962
977
  get size() {
963
978
  return this.ids.length;
964
979
  }
980
+ /** The smallest stored key, or undefined when the queue is empty. */
981
+ peekKey() {
982
+ return this.keys[0];
983
+ }
965
984
  /** Adds an entry. A NaN key is not stored: no comparison with NaN is true, so such an item is never due. */
966
985
  push(key, id) {
967
986
  if (key !== key) return;
@@ -1047,6 +1066,7 @@ function createStore(opts = {}) {
1047
1066
  s.add(v);
1048
1067
  };
1049
1068
  const regimeHeight = () => maxSweep >= V21_HEIGHT ? V21_HEIGHT : V21_HEIGHT - 1;
1069
+ let splitSweep = true;
1050
1070
  const addOffer = (o) => {
1051
1071
  if (!offers.has(o.id)) offerAt.set(o.id, ++stamp);
1052
1072
  offers.set(o.id, o);
@@ -1187,11 +1207,27 @@ function createStore(opts = {}) {
1187
1207
  stats.visits += popped.length;
1188
1208
  return [...new Set(popped)].filter(isDue).sort((a, b) => at.get(a) - at.get(b));
1189
1209
  };
1210
+ const nextDue = () => {
1211
+ let d = maxSweep >= V21_HEIGHT ? Infinity : V21_HEIGHT;
1212
+ const ko = offerQ.peekKey(), kb = bidQ.peekKey(), kn = nameQ.peekKey(), kr = recaptureQ.peekKey();
1213
+ if (ko !== void 0) d = Math.min(d, (ko + 1) * import_csd_codec.EPOCH_LEN);
1214
+ if (kb !== void 0) d = Math.min(d, (kb + 1) * import_csd_codec.EPOCH_LEN);
1215
+ if (kn !== void 0) d = Math.min(d, kn + 1);
1216
+ if (kr !== void 0) d = Math.min(d, kr + 1);
1217
+ return d;
1218
+ };
1190
1219
  const sweep = (height, expireOffer) => {
1191
1220
  if (!(height >= maxSweep)) {
1192
1221
  walkSweep(height, expireOffer);
1193
1222
  return;
1194
1223
  }
1224
+ if (splitSweep) for (let d = nextDue(); d < height; d = nextDue()) {
1225
+ if (!(d > maxSweep)) break;
1226
+ sweepAt(d, expireOffer);
1227
+ }
1228
+ sweepAt(height, expireOffer);
1229
+ };
1230
+ const sweepAt = (height, expireOffer) => {
1195
1231
  if (!(maxSweep >= V21_HEIGHT) && height >= V21_HEIGHT) {
1196
1232
  stats.visits += openOffers.size + openBids.size;
1197
1233
  for (const id of openOffers) {
@@ -1218,6 +1254,13 @@ function createStore(opts = {}) {
1218
1254
  same(`expired bids at ${height}`, dueBids, want.bids);
1219
1255
  same(`expired reservations at ${height}`, dueNames, want.names);
1220
1256
  same(`expired recaptures at ${height}`, dueRecaptures, want.recaptures);
1257
+ const early = !splitSweep ? [] : [
1258
+ ...dueOffers.filter((id) => offerDue(offers.get(id), height - 1)),
1259
+ ...dueBids.filter((id) => bidDue(bids.get(id), height - 1)),
1260
+ ...dueNames.filter((nm) => nameDue(names.get(nm), height - 1)),
1261
+ ...dueRecaptures.filter((nm) => height - 1 > recaptures.get(nm).finalizeBy)
1262
+ ];
1263
+ if (early.length) throw new Error(`replay index check: expired at ${height}, due before it: ${early.join(", ")}`);
1221
1264
  }
1222
1265
  for (const id of dueOffers) {
1223
1266
  const o = offers.get(id);
@@ -1367,6 +1410,9 @@ function createStore(opts = {}) {
1367
1410
  putRecapture,
1368
1411
  deleteRecapture,
1369
1412
  sweep,
1413
+ endSplit: () => {
1414
+ splitSweep = false;
1415
+ },
1370
1416
  pendingCount,
1371
1417
  recaptureCount,
1372
1418
  liveHoldCount,
@@ -1927,7 +1973,7 @@ function applyMint(c, ev, rec, who) {
1927
1973
  }
1928
1974
  tok.minted += credit;
1929
1975
  bal(rec.ticker, who).available += credit;
1930
- applied(ev, ev.id, "mint", "TOKEN_MINTED", credit.toString());
1976
+ applied(ev, ev.id, "mint", "TOKEN_MINTED", credit.toString(), [tokenMove("mint", rec.ticker, null, who, credit)]);
1931
1977
  }
1932
1978
  function applyTransfer(c, ev, rec, who) {
1933
1979
  const { tokens, bal, applied, refused } = c;
@@ -1941,9 +1987,10 @@ function applyTransfer(c, ev, rec, who) {
1941
1987
  refused(ev, ev.id, "transfer", "TOKEN_BALANCE_LOW", "insufficient available balance");
1942
1988
  return;
1943
1989
  }
1990
+ const to = rec.to.toLowerCase();
1944
1991
  from.available -= amt;
1945
- bal(rec.ticker, rec.to.toLowerCase()).available += amt;
1946
- applied(ev, ev.id, "transfer", "TOKEN_TRANSFERRED");
1992
+ bal(rec.ticker, to).available += amt;
1993
+ applied(ev, ev.id, "transfer", "TOKEN_TRANSFERRED", void 0, [tokenMove("xfer", rec.ticker, who, to, amt)]);
1947
1994
  }
1948
1995
  function applyTmeta(c, ev, rec, who) {
1949
1996
  const { tokens, applied, refused } = c;
@@ -1977,27 +2024,31 @@ function resolve(events, tipHeight) {
1977
2024
  return replay(events, tipHeight);
1978
2025
  }
1979
2026
  function replay(events, tipHeight, opts = {}) {
1980
- const ordered = [...events].sort(applyOrder);
2027
+ const fold = createFold(opts);
2028
+ for (const e of [...events].sort(applyOrder)) fold.apply(e);
2029
+ return fold.finish(tipHeight);
2030
+ }
2031
+ function createFold(opts) {
1981
2032
  const seenIds = /* @__PURE__ */ new Set();
1982
- const applied = [];
1983
- for (const e of ordered) {
1984
- if (e.height >= V29_HEIGHT) {
1985
- const k = eventId(e);
1986
- if (seenIds.has(k)) continue;
1987
- seenIds.add(k);
1988
- }
1989
- applied.push(e);
1990
- }
1991
2033
  const store = createStore(opts);
1992
2034
  const c = createContext(store);
1993
- const { tokens, balances, names, recaptures, offers, bids, fclaims, log, refused, sweepExpired } = c;
2035
+ const { refused, sweepExpired } = c;
1994
2036
  let pendingBlock = -1;
1995
2037
  const applyPendingCancels = () => {
1996
2038
  for (const f of c.pendingCancels) f();
1997
2039
  c.pendingCancels = [];
1998
2040
  };
1999
- for (const ev of applied) {
2000
- if (beforeActivation(ev.height)) continue;
2041
+ const inDomain = (height) => {
2042
+ if (!Number.isSafeInteger(height)) store.endSplit();
2043
+ };
2044
+ const apply = (ev) => {
2045
+ inDomain(ev.height);
2046
+ if (ev.height >= V29_HEIGHT) {
2047
+ const k = eventId(ev);
2048
+ if (seenIds.has(k)) return;
2049
+ seenIds.add(k);
2050
+ }
2051
+ if (beforeActivation(ev.height)) return;
2001
2052
  if (ev.height !== pendingBlock) {
2002
2053
  applyPendingCancels();
2003
2054
  pendingBlock = ev.height;
@@ -2009,7 +2060,7 @@ function replay(events, tipHeight, opts = {}) {
2009
2060
  const parsed = explainRecord(ev.uri, ev.payloadHash);
2010
2061
  if (!parsed.ok) {
2011
2062
  refused(ev, ev.id, "invalid", parsed.code, "unparseable/non-canonical record");
2012
- continue;
2063
+ return;
2013
2064
  }
2014
2065
  const rec = parsed.record;
2015
2066
  const who = ev.proposer.toLowerCase();
@@ -2063,10 +2114,18 @@ function replay(events, tipHeight, opts = {}) {
2063
2114
  } else {
2064
2115
  applyAttest(c, ev);
2065
2116
  }
2066
- }
2067
- applyPendingCancels();
2068
- sweepExpired(tipHeight + 1);
2069
- store.verify(tipHeight + 1, true);
2117
+ };
2118
+ const finish = (tipHeight) => {
2119
+ applyPendingCancels();
2120
+ inDomain(tipHeight);
2121
+ sweepExpired(tipHeight + 1);
2122
+ store.verify(tipHeight + 1, true);
2123
+ return materialize(c, tipHeight);
2124
+ };
2125
+ return { apply, finish };
2126
+ }
2127
+ function materialize(c, tipHeight) {
2128
+ const { tokens, balances, names, recaptures, offers, bids, fclaims, log } = c;
2070
2129
  const tokensOut = {};
2071
2130
  for (const [t, tok] of [...tokens.entries()].sort(([a], [b]) => ord(a, b))) tokensOut[t] = { ...tok.meta, minted: tok.minted.toString() };
2072
2131
  const balancesOut = {};
@@ -2292,6 +2351,54 @@ function pickPrimaryName(names, a) {
2292
2351
  return best ? best.name : null;
2293
2352
  }
2294
2353
 
2354
+ // src/forward.ts
2355
+ function resolveNameIn(names, name) {
2356
+ if (!Object.hasOwn(names, name)) return null;
2357
+ const n = names[name];
2358
+ if (!n) return null;
2359
+ if (n.pending) return null;
2360
+ return { name, addr: n.addr ?? n.owner, via: n.addr ? "nset" : "owner", lapsed: n.expired === true, owner: n.owner };
2361
+ }
2362
+ function nameView(names, name) {
2363
+ if (typeof name !== "string" || !NAME_RE.test(name)) return null;
2364
+ const none = { owner: null, addr: null, profile: {}, paidThroughEpoch: null };
2365
+ if (RESERVED_NAMES.has(name)) return { name, state: "reserved", ...none };
2366
+ const n = Object.hasOwn(names, name) ? names[name] : void 0;
2367
+ if (!n) return { name, state: "free", ...none };
2368
+ const r = resolveNameIn(names, name);
2369
+ if (r === null) return { name, state: "pending", ...none, owner: n.owner };
2370
+ const paidThroughEpoch = n.paidThroughEpoch ?? null;
2371
+ if (r.lapsed) return { name, state: "lapsed", ...none, owner: n.owner, paidThroughEpoch };
2372
+ return { name, state: "held", owner: n.owner, addr: r.addr, profile: { ...n.profile }, paidThroughEpoch };
2373
+ }
2374
+
2375
+ // src/version.ts
2376
+ var CAIRNX_CORE_VERSION = "0.2.9";
2377
+
2378
+ // src/gates.ts
2379
+ var GATE_HEIGHTS = Object.freeze({
2380
+ ACTIVATION_HEIGHT,
2381
+ V11_HEIGHT,
2382
+ V12_HEIGHT,
2383
+ V13_HEIGHT,
2384
+ V14_HEIGHT,
2385
+ V15_HEIGHT,
2386
+ V16_HEIGHT,
2387
+ V17_HEIGHT,
2388
+ V18_HEIGHT,
2389
+ V19_HEIGHT,
2390
+ V20_HEIGHT,
2391
+ V21_HEIGHT,
2392
+ V22_HEIGHT,
2393
+ V23_HEIGHT,
2394
+ V24_HEIGHT,
2395
+ V25_HEIGHT,
2396
+ V26_HEIGHT,
2397
+ V27_HEIGHT,
2398
+ V28_HEIGHT,
2399
+ V29_HEIGHT
2400
+ });
2401
+
2295
2402
  // src/verifyfill.ts
2296
2403
  var import_csd_codec4 = require("@inversealtruism/csd-codec");
2297
2404
  var FCLAIM_MAX_HOLD_SPAN = import_csd_codec.EPOCH_LEN * (FCLAIM_MAX_EPOCH_AHEAD + 1) - 1;
@@ -2838,6 +2945,7 @@ var import_csd_codec7 = require("@inversealtruism/csd-codec");
2838
2945
  ADDR_RE,
2839
2946
  AMOUNT_RE,
2840
2947
  BID_KEYS,
2948
+ CAIRNX_CORE_VERSION,
2841
2949
  CAIRNX_EVENT_RULE,
2842
2950
  CAP_CODES,
2843
2951
  CLAIM_ATTACKER_Q,
@@ -2865,6 +2973,7 @@ var import_csd_codec7 = require("@inversealtruism/csd-codec");
2865
2973
  FINALIZE_TIP_MARGIN,
2866
2974
  FINAL_DEPTH,
2867
2975
  GAP_NEEDED,
2976
+ GATE_HEIGHTS,
2868
2977
  HALVING_INTERVAL,
2869
2978
  HASH_RE,
2870
2979
  INITIAL_REWARD,
@@ -2983,6 +3092,7 @@ var import_csd_codec7 = require("@inversealtruism/csd-codec");
2983
3092
  nameRegFee,
2984
3093
  nameRenew,
2985
3094
  nameSet,
3095
+ nameView,
2986
3096
  nameXfer,
2987
3097
  offer,
2988
3098
  offerCancelAll,
@@ -3002,6 +3112,7 @@ var import_csd_codec7 = require("@inversealtruism/csd-codec");
3002
3112
  requiredClaimDepth,
3003
3113
  requiredFillOutputs,
3004
3114
  resolve,
3115
+ resolveNameIn,
3005
3116
  stateHash,
3006
3117
  tokenMeta,
3007
3118
  tradeFee,
package/dist/index.d.cts CHANGED
@@ -473,6 +473,15 @@ interface BidState {
473
473
  /** offers anchored in response (tagged with this bid's id), in apply order */
474
474
  offers: string[];
475
475
  }
476
+ /** One token movement of an applied record (CONVENTION §41): `amount` base units of `ticker` from `from` (null for a mint)
477
+ * to `to`, written by the line that applies it. `amount` is a positive decimal string, the form of the state's balances. */
478
+ interface TokenMove {
479
+ leg: "xfer" | "mint" | "fill" | "sale" | "fee";
480
+ ticker: string;
481
+ from: string | null;
482
+ to: string;
483
+ amount: string;
484
+ }
476
485
  interface AppliedEvent {
477
486
  height: number;
478
487
  pos: number;
@@ -483,6 +492,9 @@ interface AppliedEvent {
483
492
  * a log built by hand or by a core before 0.2.6 has none. */
484
493
  code?: ReasonCode;
485
494
  note?: string;
495
+ /** The token moves of an applied record that moved tokens, in the order applied (CONVENTION §41); absent on every other
496
+ * entry and in a log from a core before 0.2.8. Outside canonical state, like the rest of the log. */
497
+ moves?: TokenMove[];
486
498
  }
487
499
  interface CairnXState {
488
500
  tipHeight: number;
@@ -592,9 +604,9 @@ declare function eventId(e: ChainEvent): string;
592
604
  * Outside that domain the result is unspecified: a NaN key compares as equal. */
593
605
  declare function applyOrder(a: ChainEvent, b: ChainEvent): number;
594
606
  declare function resolve(events: ChainEvent[], tipHeight: number): CairnXState;
595
- /** Canonical serialization of state (FORMAT 2) — byte-identical across honest resolvers.
607
+ /** Canonical serialization of state (FORMAT 2): byte-identical across honest resolvers.
596
608
  * The canonical surface is the DATA ONLY: {tipHeight, tokens, balances, names, offers, bids,
597
- * feesPaid}. The applied-event log is deliberately EXCLUDED — its free-text reason strings are
609
+ * feesPaid}. The applied-event log is deliberately EXCLUDED: its free-text reason strings are
598
610
  * implementation diagnostics, and making them normative would force every third-party resolver
599
611
  * to reproduce English prose byte-for-byte. (Format 1, pre-2026-06-12, included the log and
600
612
  * sorted with localeCompare; pinned format-1 hashes live in test/vectors/replay-hashes.json
@@ -818,6 +830,68 @@ declare const primaryRankBefore: (a: NameState, b: NameState) => boolean;
818
830
  /** The primary .csd name for address `a`, or null. Pure; no I/O. `a` may be any case. */
819
831
  declare function pickPrimaryName(names: Iterable<NameState>, a: string): string | null;
820
832
 
833
+ /** Where a payment to `name` goes: its `nset` address, else its owner. `lapsed` is the name's `expired` (§17): the
834
+ * address is the record's, and a sender refuses it. */
835
+ interface ResolvedName {
836
+ name: string;
837
+ addr: string;
838
+ via: "nset" | "owner";
839
+ lapsed: boolean;
840
+ owner: string;
841
+ }
842
+ /** The address `name` receives at in `names`, or null when `names` holds no such own key or holds a pending reservation
843
+ * (§28), which confers no address. The key is looked up as given: a caller normalizes its input first. */
844
+ declare function resolveNameIn(names: Record<string, NameState>, name: string): ResolvedName | null;
845
+ /** The classes of `nameView`: `free` is a name absent from `names`; `reserved` one in RESERVED_NAMES, whose record does
846
+ * not parse (§9), so it is never in `names`. */
847
+ type NameViewState = "held" | "pending" | "lapsed" | "free" | "reserved";
848
+ /** A name as a reader shows it. `addr` and `profile` are a held name's only: a pending or lapsed name gives no address,
849
+ * and its profile is not the word of a current owner (§35.3). `owner` is the reserver of a pending name and the last
850
+ * owner of a lapsed one. `paidThroughEpoch` is null where the state carries none (a pending name, a tip below V15). */
851
+ interface NameView {
852
+ name: string;
853
+ state: NameViewState;
854
+ owner: string | null;
855
+ addr: string | null;
856
+ profile: Record<string, string>;
857
+ paidThroughEpoch: number | null;
858
+ }
859
+ /** The view of `name` in `names`, or null when `name` does not match NAME_RE. Built on resolveNameIn: a held name's
860
+ * `addr` is its address. */
861
+ declare function nameView(names: Record<string, NameState>, name: string): NameView | null;
862
+
863
+ /** This package's version, for a host that names the core it loaded (cairnx-api's `rev`, a replica's report). Equal to
864
+ * package.json's version (test/version.test.ts). */
865
+ declare const CAIRNX_CORE_VERSION = "0.2.9";
866
+
867
+ /** Gate name to height: `ACTIVATION_HEIGHT` and each `V<n>_HEIGHT`, frozen. test/gates.test.ts keeps it equal to the
868
+ * individual exports and complete. It leaves out the one other exported height, `LEGACY_HOLD_SUNSET_HEIGHT`, which is
869
+ * derived from `V28_HEIGHT` and the claim window and grace, and which no replay rule reads. Two equal tables show
870
+ * equal gate heights, not equal rules: no fee, window or reserved-name constant is in the table. */
871
+ declare const GATE_HEIGHTS: Readonly<{
872
+ ACTIVATION_HEIGHT: 29860;
873
+ V11_HEIGHT: 29960;
874
+ V12_HEIGHT: 30300;
875
+ V13_HEIGHT: 31100;
876
+ V14_HEIGHT: 31400;
877
+ V15_HEIGHT: 32000;
878
+ V16_HEIGHT: 33600;
879
+ V17_HEIGHT: 34000;
880
+ V18_HEIGHT: 40000;
881
+ V19_HEIGHT: 36700;
882
+ V20_HEIGHT: 38400;
883
+ V21_HEIGHT: 40100;
884
+ V22_HEIGHT: 41300;
885
+ V23_HEIGHT: 52000;
886
+ V24_HEIGHT: 46400;
887
+ V25_HEIGHT: 46440;
888
+ V26_HEIGHT: 46480;
889
+ V27_HEIGHT: 46520;
890
+ V28_HEIGHT: 60000;
891
+ V29_HEIGHT: 88000;
892
+ }>;
893
+ type GateName = keyof typeof GATE_HEIGHTS;
894
+
821
895
  declare const FCLAIM_MAX_HOLD_SPAN: number;
822
896
  declare const GAP_NEEDED: number;
823
897
  declare const SCAN_MARGIN = 30;
@@ -1118,4 +1192,4 @@ interface ProvenOfferTx {
1118
1192
  * rules; the resolver writes no note below activation), or null when it passes. */
1119
1193
  declare function provenOfferRefusal(rec: OfferRecord, tx: ProvenOfferTx): string | null;
1120
1194
 
1121
- export { ACTIVATION_HEIGHT, ADDR_RE, AMOUNT_RE, type AppliedCode, type AppliedEvent, type AttestEvent, BID_KEYS, type BalanceState, type BidRecord, type BidState, type BidStatus, type BindTermsOpts, type BuiltRecord, CAIRNX_EVENT_RULE, CAP_CODES, 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, EVENTS_HASH_START, type EventMember, type EventRule, type EventRuleTx, type EventsSoFar, FCLAIM_KEYS, FCLAIM_MAX_EPOCH_AHEAD, FCLAIM_MAX_HOLD_SPAN, FCLAIM_WINDOW_MIN, FEE_BPS, FEE_BPS_V16, FEE_GATE_MARGIN_BLOCKS, FILL_TIP_MARGIN, FINALIZE_TIP_MARGIN, FINAL_DEPTH, type FclaimRecord, type FillEndorsement, type FillEntry, type FillOutputPlan, type FillPreview, type FillSafety, type FillSpvIo, type FillVerdict, GAP_NEEDED, type Give, HASH_RE, type HashedEvent, type HoldCandidate, type HoldCount, type HoldReplay, type HoldTarget, LEGACY_HOLD_SUNSET_HEIGHT, type LegacyBindOpts, MAX_ACTIVE_CLAIMS, MAX_AMOUNT, MAX_OFFER_EPOCHS, MAX_PENDING_REG, MAX_RECORD_BYTES, MAX_SCAN, MAX_TOKEN_DECIMALS, MINT_KEYS, type MintRecord, type MintedProvenOfferTerms, NAME_FEE_LEN3_V24, NAME_FEE_LEN4_V24, NAME_FEE_LONG_V24, NAME_FEE_MID_V24, NAME_FEE_SHORT_V18, NAME_FEE_V18, NAME_GRACE_EPOCHS, NAME_KEYS, NAME_PREMIUM_DECAY_EPOCHS, NAME_PREMIUM_START, NAME_RE, NAME_TERM_EPOCHS, NFINALIZE_KEYS, NPROFILE_KEYS, type NameCommitRecord, type NameFinalizeRecord, 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, type ProvenAttest, type ProvenEvent, type ProvenOfferTerms, type ProvenOfferTx, type ProvenPropose, REASON_CODES, REASON_CODE_OUTCOME, REBATE_BPS, REBATE_FLAT, REG_COMMIT_MAX_BLOCKS, REG_FINALIZE_GRACE_BLOCKS, RESERVED_NAMES, type ReasonCode, type RecordCode, RecordError, type RefusalCode, SALT_RE, SCAN_MARGIN, 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, V24_HEIGHT, V25_HEIGHT, V26_HEIGHT, V27_HEIGHT, V28_HEIGHT, V29_HEIGHT, type Want, ZERO_ADDR, applyOrder, beforeActivation, bid, bindOfferTerms, bindProvenOffer, blockEvents, blockMembers, buildFeeHeight, buildRecord, burnedPayment, canonicalState, claimGraceOf, claimWindowAt, claimWindowOf, countOtherHoldsAtGrant, deploy, eventId, eventOfTx, eventsHash, eventsHashStep, expiredClaimFee, explainRecord, fclaim, fclaimEpochFor, fclaimHoldEnd, feeBpsAt, fillEndorsement, fillIsSafe, fillOutputPlan, fillTargetId, finalizeWinnerCheck, hasLiveClaim, isName, isNameGive, isOpenClaimLane, isTokenWant, makerRebate, mint, myProvenFillClosedOffer, nameClaim, nameCommit, nameCommitRecord, nameFinalize, nameProfile, nameRegFee, nameRenew, nameSet, nameXfer, offer, offerCancelAll, offerExpiryHeightOf, offerFillTooLate, paidToFromOutputs, parseAmount, parseRecord, pickPrimaryName, previewFill, primaryRankBefore, provenOfferRefusal, provenOfferTerms, ptAmt, replayLiveHold, requiredClaimDepth, requiredFillOutputs, resolve, stateHash, tokenMeta, tradeFee, transfer, unsafeMintProvenOfferTerms, verifyFillSpv };
1195
+ export { ACTIVATION_HEIGHT, ADDR_RE, AMOUNT_RE, type AppliedCode, type AppliedEvent, type AttestEvent, BID_KEYS, type BalanceState, type BidRecord, type BidState, type BidStatus, type BindTermsOpts, type BuiltRecord, CAIRNX_CORE_VERSION, CAIRNX_EVENT_RULE, CAP_CODES, 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, EVENTS_HASH_START, type EventMember, type EventRule, type EventRuleTx, type EventsSoFar, FCLAIM_KEYS, FCLAIM_MAX_EPOCH_AHEAD, FCLAIM_MAX_HOLD_SPAN, FCLAIM_WINDOW_MIN, FEE_BPS, FEE_BPS_V16, FEE_GATE_MARGIN_BLOCKS, FILL_TIP_MARGIN, FINALIZE_TIP_MARGIN, FINAL_DEPTH, type FclaimRecord, type FillEndorsement, type FillEntry, type FillOutputPlan, type FillPreview, type FillSafety, type FillSpvIo, type FillVerdict, GAP_NEEDED, GATE_HEIGHTS, type GateName, type Give, HASH_RE, type HashedEvent, type HoldCandidate, type HoldCount, type HoldReplay, type HoldTarget, LEGACY_HOLD_SUNSET_HEIGHT, type LegacyBindOpts, MAX_ACTIVE_CLAIMS, MAX_AMOUNT, MAX_OFFER_EPOCHS, MAX_PENDING_REG, MAX_RECORD_BYTES, MAX_SCAN, MAX_TOKEN_DECIMALS, MINT_KEYS, type MintRecord, type MintedProvenOfferTerms, NAME_FEE_LEN3_V24, NAME_FEE_LEN4_V24, NAME_FEE_LONG_V24, NAME_FEE_MID_V24, NAME_FEE_SHORT_V18, NAME_FEE_V18, NAME_GRACE_EPOCHS, NAME_KEYS, NAME_PREMIUM_DECAY_EPOCHS, NAME_PREMIUM_START, NAME_RE, NAME_TERM_EPOCHS, NFINALIZE_KEYS, NPROFILE_KEYS, type NameCommitRecord, type NameFinalizeRecord, type NameProfileRecord, type NameRecord, type NameRenewRecord, type NameSetRecord, type NameState, type NameView, type NameViewState, type NameXferRecord, OFFER_KEYS, type OfferCancelAllRecord, type OfferRecord, type OfferState, type OfferStatus, PKEY, PROFILE_MAX_KEYS, PROFILE_MAX_VALUE_BYTES, type ProposeEvent, type ProvenAttest, type ProvenEvent, type ProvenOfferTerms, type ProvenOfferTx, type ProvenPropose, REASON_CODES, REASON_CODE_OUTCOME, REBATE_BPS, REBATE_FLAT, REG_COMMIT_MAX_BLOCKS, REG_FINALIZE_GRACE_BLOCKS, RESERVED_NAMES, type ReasonCode, type RecordCode, RecordError, type RefusalCode, type ResolvedName, SALT_RE, SCAN_MARGIN, SCORE_CANCEL, SCORE_CLAIM, SCORE_FILL, TICKER_RE, TRANSFER_KEYS, TREASURY_ADDR, type TokenMetaRecord, type TokenMove, 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, V24_HEIGHT, V25_HEIGHT, V26_HEIGHT, V27_HEIGHT, V28_HEIGHT, V29_HEIGHT, type Want, ZERO_ADDR, applyOrder, beforeActivation, bid, bindOfferTerms, bindProvenOffer, blockEvents, blockMembers, buildFeeHeight, buildRecord, burnedPayment, canonicalState, claimGraceOf, claimWindowAt, claimWindowOf, countOtherHoldsAtGrant, deploy, eventId, eventOfTx, eventsHash, eventsHashStep, expiredClaimFee, explainRecord, fclaim, fclaimEpochFor, fclaimHoldEnd, feeBpsAt, fillEndorsement, fillIsSafe, fillOutputPlan, fillTargetId, finalizeWinnerCheck, hasLiveClaim, isName, isNameGive, isOpenClaimLane, isTokenWant, makerRebate, mint, myProvenFillClosedOffer, nameClaim, nameCommit, nameCommitRecord, nameFinalize, nameProfile, nameRegFee, nameRenew, nameSet, nameView, nameXfer, offer, offerCancelAll, offerExpiryHeightOf, offerFillTooLate, paidToFromOutputs, parseAmount, parseRecord, pickPrimaryName, previewFill, primaryRankBefore, provenOfferRefusal, provenOfferTerms, ptAmt, replayLiveHold, requiredClaimDepth, requiredFillOutputs, resolve, resolveNameIn, stateHash, tokenMeta, tradeFee, transfer, unsafeMintProvenOfferTerms, verifyFillSpv };