@inversealtruism/cairnx-core 0.2.9 → 0.2.10

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/CHANGELOG.md CHANGED
@@ -1,6 +1,32 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.2.10
4
+
5
+ - A held replay context: `newReplayContext()` keeps `resolve()`'s fold between tips. `advance(toHeight, events)`
6
+ applies the whole blocks above the context's height, in apply order; `stateAt(t)`, at that height, answers in place.
7
+ It takes an event whose height is a safe integer (`isChainHeight`), whose position is a safe integer >= 0 and whose
8
+ id is a string, as CONVENTION section 33 builds them. For inputs made of plain values (what JSON carries), its answer
9
+ at t is what `resolve()` returns over the same events at t, and an answer handed out earlier does not change later.
10
+ Any other event, and a height or tip outside `isChainHeight`, is refused with a `ReplayContextRefusal` ("domain")
11
+ and the caller replays with `resolve()`. `advance` reads its events once and keeps a one-level copy of each, so a
12
+ write into an event after the call changes no later answer. The other refusals, each thrown before any write:
13
+ "order" (a target below the height, an event at or below it or above the target; a new context stands at -1, so it
14
+ refuses a negative height, which `resolve()` skips below activation), "tip" (an answer off the height), "broken"
15
+ (any call after the replay threw inside `advance` or `stateAt`, where `resolve()` throws too), "sloppy" (a build
16
+ that runs the module in sloppy mode, where a write to a frozen shared part would be dropped instead of throwing). The
17
+ context keeps no earlier state: a reorg that removes an applied block costs one full replay.
18
+ `isChainHeight`, the one domain rule (`Number.isSafeInteger`), is exported and read by `resolve()`'s fold and by the
19
+ context. `resolve()` is unchanged: the seal against 0.2.9 finds its whole result identical over each input of
20
+ 0.2.9's proof, and walks a held context through 26,303 of them, 1,270,287 answers each equal to `resolve()`
21
+ (`CONSENSUS_CHANGES.md`). `test/replay-context.test.ts` compares the context with `resolve()` at every height of the
22
+ sweep streams (D, over 284,000 blocks, at its dense tips; the malformed ones until refused), every event height of
23
+ the replay corpus and the growth streams at 500, with answers re-read after later advances and written over. On the
24
+ replay corpus (1,133 events in 774 blocks), advancing one block and answering at it, 774 times, took 2.81 percent of
25
+ the time of a `resolve()` per block (medians of five interleaved runs on a host at load 30 to 40; the build without
26
+ the copy and the position and id checks measured 4.41 percent in the same runs, and the runs' ranges overlap, so the
27
+ two figures do not rank the builds); those checks and the copy alone take 0.108 ms over the whole corpus.
28
+
29
+ ## 0.2.9
4
30
 
5
31
  - The replay runs as a fold (one step per event, an end at the tip that alone reads the tip) and its expiry sweep
6
32
  applies each expiry at the first height it is due, one batch per such height in ascending order, where 0.2.8 applied
package/CONVENTION.md CHANGED
@@ -252,6 +252,11 @@ times, is outside that statement. Outside the domain the result is not consensus
252
252
  differently (0.2.4 and 0.2.7 on a string height), so a caller checks that event heights and the tip are safe integers
253
253
  before the call.
254
254
 
255
+ A resolver may also hold its replay between tips and answer in place at the last height it applied, as cairnx-core's
256
+ held context does from 0.2.10: inside the domain its answer at t equals a full replay to t, because the answer's sweep
257
+ at `t + 1` is one more sweep height, and the next block's flush and sweep follow it as they would follow the block
258
+ before; outside the domain the heights at which sweeps run matter, so such a resolver replays in full.
259
+
255
260
  **Canonical state (format 2, normative):** the canonical surface is
256
261
  `{tipHeight, tokens, balances, names, offers, bids, feesPaid}`: the event log is excluded.
257
262
  Serialization is **canonical JSON** in the state form of §5.1: object keys sorted in ordinal (code-unit) order at every
package/README.md CHANGED
@@ -322,6 +322,20 @@ For inputs made of plain values (what JSON carries), a release that changes no r
322
322
  what the previous core returned and throws where it threw, and only event heights and a tip that are safe integers,
323
323
  as a chain produces them, are consensus, so check both before the call (`CONVENTION.md` section 5).
324
324
 
325
+ A replica or a server that answers at each new block can hold the replay instead of rebuilding it: `const ctx =
326
+ newReplayContext()`, then at each new height `h`, `ctx.advance(h, events)` with the events of the blocks above
327
+ `ctx.height` up to `h` (only those: an event at or below `ctx.height` is refused), and `ctx.stateAt(h)`. In the scope
328
+ above, its answer at a height is what `resolve()` returns over the same events there, for every event it takes: one
329
+ whose height is a safe integer (`isChainHeight`), whose position is a safe integer >= 0 and whose id is a string, as
330
+ the rule of `CONVENTION.md` section 33 builds them. It refuses any other event, and a height or tip that
331
+ `isChainHeight` rejects, with a `ReplayContextRefusal` before anything is written, and the caller replays with
332
+ `resolve()`. It keeps a copy of each event's own fields, so a later write into an event already given changes no
333
+ answer. A reorg that removes an applied block means a new context. A new context stands at height -1, below the
334
+ chain's first block, so it refuses a negative height ("order"), which `resolve()` skips below activation. It refuses
335
+ to start in a build that runs it in sloppy mode: it shares frozen parts with the answers it returns and relies on a
336
+ write to a frozen part throwing, so that a write the replay makes there breaks the context instead of being dropped
337
+ silently.
338
+
325
339
  ### What a resolver result proves
326
340
 
327
341
  - Display: an answer read from someone's API. It is worth the trust you place in that API.
package/dist/index.cjs CHANGED
@@ -93,6 +93,7 @@ __export(index_exports, {
93
93
  REG_FINALIZE_GRACE_BLOCKS: () => REG_FINALIZE_GRACE_BLOCKS,
94
94
  RESERVED_NAMES: () => RESERVED_NAMES,
95
95
  RecordError: () => RecordError,
96
+ ReplayContextRefusal: () => ReplayContextRefusal,
96
97
  SALT_RE: () => SALT_RE,
97
98
  SCAN_MARGIN: () => SCAN_MARGIN,
98
99
  SCORE_CANCEL: () => SCORE_CANCEL,
@@ -156,6 +157,7 @@ __export(index_exports, {
156
157
  fillTargetId: () => fillTargetId,
157
158
  finalizeWinnerCheck: () => finalizeWinnerCheck,
158
159
  hasLiveClaim: () => hasLiveClaim,
160
+ isChainHeight: () => isChainHeight,
159
161
  isName: () => isName,
160
162
  isNameGive: () => isNameGive,
161
163
  isOpenClaimLane: () => isOpenClaimLane,
@@ -173,6 +175,7 @@ __export(index_exports, {
173
175
  nameSet: () => nameSet,
174
176
  nameView: () => nameView,
175
177
  nameXfer: () => nameXfer,
178
+ newReplayContext: () => newReplayContext,
176
179
  offer: () => offer,
177
180
  offerCancelAll: () => offerCancelAll,
178
181
  offerExpiryHeightOf: () => offerExpiryHeightOf,
@@ -206,6 +209,7 @@ var import_csd_codec = require("@inversealtruism/csd-codec");
206
209
  var DOMAIN = "cairnx:v1";
207
210
  var ACTIVATION_HEIGHT = 29860;
208
211
  var beforeActivation = (height) => height < ACTIVATION_HEIGHT;
212
+ var isChainHeight = (height) => Number.isSafeInteger(height);
209
213
  var V11_HEIGHT = 29960;
210
214
  var V12_HEIGHT = 30300;
211
215
  var V13_HEIGHT = 31100;
@@ -2028,7 +2032,7 @@ function replay(events, tipHeight, opts = {}) {
2028
2032
  for (const e of [...events].sort(applyOrder)) fold.apply(e);
2029
2033
  return fold.finish(tipHeight);
2030
2034
  }
2031
- function createFold(opts) {
2035
+ function createFold(opts = {}) {
2032
2036
  const seenIds = /* @__PURE__ */ new Set();
2033
2037
  const store = createStore(opts);
2034
2038
  const c = createContext(store);
@@ -2039,7 +2043,7 @@ function createFold(opts) {
2039
2043
  c.pendingCancels = [];
2040
2044
  };
2041
2045
  const inDomain = (height) => {
2042
- if (!Number.isSafeInteger(height)) store.endSplit();
2046
+ if (!isChainHeight(height)) store.endSplit();
2043
2047
  };
2044
2048
  const apply = (ev) => {
2045
2049
  inDomain(ev.height);
@@ -2185,15 +2189,242 @@ function canonicalState(s) {
2185
2189
  return JSON.stringify(sortKeys(data));
2186
2190
  }
2187
2191
 
2188
- // src/client.ts
2192
+ // src/events.ts
2189
2193
  var import_csd_codec3 = require("@inversealtruism/csd-codec");
2194
+
2195
+ // src/paidto.ts
2196
+ function paidToFromOutputs(outputs) {
2197
+ const m = /* @__PURE__ */ Object.create(null);
2198
+ for (const o of outputs) {
2199
+ if (typeof o.value !== "number" || !Number.isSafeInteger(o.value) || o.value < 0) continue;
2200
+ m[o.addr] = (BigInt(m[o.addr] ?? "0") + BigInt(o.value)).toString();
2201
+ }
2202
+ return m;
2203
+ }
2204
+ function burnedPayment(paidTo, payer, offer2) {
2205
+ const read = (addr) => addr === payer ? 0n : ptAmt(paidTo?.[addr]);
2206
+ let counterparty = 0n;
2207
+ if (offer2) {
2208
+ for (const addr of /* @__PURE__ */ new Set([offer2.seller, offer2.want.payto])) if (addr !== TREASURY_ADDR) counterparty += read(addr);
2209
+ }
2210
+ return { treasury: read(TREASURY_ADDR), counterparty };
2211
+ }
2212
+
2213
+ // src/events.ts
2214
+ var CAIRNX_EVENT_RULE = Object.freeze({ domain: DOMAIN, activationHeight: ACTIVATION_HEIGHT });
2215
+ var fail = (what) => {
2216
+ throw new Error(`events rule: ${what}`);
2217
+ };
2218
+ var isIndex = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
2219
+ function hexOf(v, bytes, what) {
2220
+ const h = typeof v === "string" && v.startsWith("0x") ? v.slice(2) : v;
2221
+ if (typeof h !== "string" || h.length !== bytes * 2 || !/^[0-9a-fA-F]*$/.test(h)) return fail(`${what} is not ${bytes}-byte hex`);
2222
+ return "0x" + h.toLowerCase();
2223
+ }
2224
+ function u64Of(v, what) {
2225
+ if (typeof v === "bigint" && v >= 0n && v < 1n << 64n) return v;
2226
+ if (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 2 ** 53) return v;
2227
+ if (typeof v === "number" && Number.isInteger(v) && v > 2 ** 53) return fail(`${what} above 2^53 must be passed as a bigint`);
2228
+ return fail(`${what} is not a u64`);
2229
+ }
2230
+ function u32Of(v, what) {
2231
+ return typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 4294967295 ? v : fail(`${what} is not a u32`);
2232
+ }
2233
+ function checkRule(rule) {
2234
+ const d = rule?.domain;
2235
+ if (typeof d !== "string" || d === "" || !(0, import_csd_codec3.isWellFormedUtf16)(d) || d.includes("\0") || d.includes(""))
2236
+ fail("the rule's domain must be non-empty, well-formed text without U+0000 or U+0001");
2237
+ if (!isIndex(rule.activationHeight)) fail("the rule's activation height must be a safe integer >= 0");
2238
+ }
2239
+ var kindOf = (app) => {
2240
+ const t = app?.type;
2241
+ return t === "None" ? "none" : t === "Propose" ? "propose" : t === "Attest" ? "attest" : fail(`unknown app type ${String(t)}`);
2242
+ };
2243
+ var domainOf = (app) => typeof app.domain === "string" ? app.domain : fail("a Propose domain is not text");
2244
+ function paidToOf(outputs) {
2245
+ if (!Array.isArray(outputs)) fail("outputs is not a list");
2246
+ const counted = [];
2247
+ for (const o of outputs) {
2248
+ const addr = hexOf(o?.scriptPubkey, 20, "script_pubkey"), value = u64Of(o?.value, "output value");
2249
+ if (value <= Number.MAX_SAFE_INTEGER) counted.push({ addr, value: Number(value) });
2250
+ }
2251
+ return paidToFromOutputs(counted);
2252
+ }
2253
+ function eventOfTx(t, height, author, rule = CAIRNX_EVENT_RULE) {
2254
+ checkRule(rule);
2255
+ if (!isIndex(height)) fail("height is not a safe integer >= 0");
2256
+ if (!isIndex(t?.pos)) fail("pos is not a safe integer >= 0");
2257
+ const txid = hexOf(t.txid, 32, "txid");
2258
+ const app = t.tx?.app;
2259
+ const kind = kindOf(app);
2260
+ if (kind === "none" || height < rule.activationHeight) return null;
2261
+ if (t.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2262
+ if (kind === "propose" && domainOf(app) !== rule.domain) return null;
2263
+ const paidTo = paidToOf(t.tx.outputs), who = hexOf(author, 20, "author");
2264
+ if (kind === "propose") {
2265
+ const p = app;
2266
+ const uri = p.uri;
2267
+ if (typeof uri !== "string" || !(0, import_csd_codec3.isWellFormedUtf16)(uri)) return fail("uri is not well-formed text");
2268
+ const e = u64Of(p.expiresEpoch, "expiresEpoch");
2269
+ return {
2270
+ kind: "propose",
2271
+ id: txid,
2272
+ proposer: who,
2273
+ uri: uri.replaceAll("\0", ""),
2274
+ payloadHash: hexOf(p.payloadHash, 32, "payloadHash"),
2275
+ expiresEpoch: e <= Number.MAX_SAFE_INTEGER ? Number(e) : 2 ** 53,
2276
+ height,
2277
+ pos: t.pos,
2278
+ paidTo
2279
+ };
2280
+ }
2281
+ const a = app;
2282
+ return {
2283
+ kind: "attest",
2284
+ txid,
2285
+ proposalId: hexOf(a.proposalId, 32, "proposalId"),
2286
+ attester: who,
2287
+ score: u32Of(a.score, "score"),
2288
+ confidence: u32Of(a.confidence, "confidence"),
2289
+ height,
2290
+ pos: t.pos,
2291
+ paidTo
2292
+ };
2293
+ }
2294
+ function blockMembers(height, txs, sofar, rule = CAIRNX_EVENT_RULE) {
2295
+ checkRule(rule);
2296
+ if (!isIndex(height)) fail("height is not a safe integer >= 0");
2297
+ if (height < rule.activationHeight) return [];
2298
+ if (!Array.isArray(txs)) fail("txs is not a list");
2299
+ const ids = /* @__PURE__ */ new Set(), proposals = /* @__PURE__ */ new Set();
2300
+ const read = [];
2301
+ let last = -1;
2302
+ for (const item of txs) {
2303
+ if (!isIndex(item?.pos) || item.pos <= last) fail("positions are not safe integers >= 0 in strictly increasing order");
2304
+ last = item.pos;
2305
+ const id = hexOf(item.txid, 32, "txid");
2306
+ if (ids.has(id)) fail(`txid ${id} is repeated in the block`);
2307
+ ids.add(id);
2308
+ const kind = kindOf(item.tx?.app);
2309
+ if (kind === "none") continue;
2310
+ if (item.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2311
+ if (kind === "propose") {
2312
+ if (domainOf(item.tx.app) !== rule.domain || sofar.eventIds.has(id)) continue;
2313
+ proposals.add(id);
2314
+ read.push({ item, kind, id });
2315
+ } else read.push({ item, kind, id, proposal: hexOf(item.tx.app.proposalId, 32, "proposalId") });
2316
+ }
2317
+ return read.filter((r) => r.kind === "propose" || !sofar.eventIds.has(r.id) && (sofar.proposeIds.has(r.proposal) || proposals.has(r.proposal))).map((r) => ({ kind: r.kind, item: r.item }));
2318
+ }
2319
+ function blockEvents(height, txs, sofar, authors, rule = CAIRNX_EVENT_RULE) {
2320
+ const members = blockMembers(height, txs, sofar, rule);
2321
+ if (!Array.isArray(authors) || authors.length !== members.length) fail(`the block has ${members.length} members, not ${authors?.length} authors`);
2322
+ const events = members.map((m, i) => eventOfTx(m.item, height, authors[i], rule) ?? fail("a member mapped to no event"));
2323
+ return [...events.filter((e) => e.kind === "propose"), ...events.filter((e) => e.kind === "attest")];
2324
+ }
2325
+
2326
+ // src/replay-context.ts
2327
+ var ReplayContextRefusal = class extends Error {
2328
+ code;
2329
+ constructor(code, message) {
2330
+ super(message);
2331
+ this.name = "ReplayContextRefusal";
2332
+ this.code = code;
2333
+ }
2334
+ };
2335
+ var strictCode = /* @__PURE__ */ (function() {
2336
+ return this === void 0;
2337
+ })();
2338
+ function newReplayContext() {
2339
+ if (!strictCode) throw new ReplayContextRefusal("sloppy", "this build runs cairnx-core in sloppy mode, where a write to a frozen object is ignored");
2340
+ const fold = createFold();
2341
+ let height = -1;
2342
+ let broken = false;
2343
+ const live = () => {
2344
+ if (broken) throw new ReplayContextRefusal("broken", "the replay threw inside advance or stateAt; replay with resolve()");
2345
+ };
2346
+ return {
2347
+ get height() {
2348
+ return height;
2349
+ },
2350
+ advance(toHeight, events) {
2351
+ live();
2352
+ if (!isChainHeight(toHeight)) throw new ReplayContextRefusal("domain", `target height ${String(toHeight)} is not a safe integer`);
2353
+ const batch = [...events].map((e) => ({ ...e }));
2354
+ for (const e of batch) {
2355
+ if (!isChainHeight(e.height)) throw new ReplayContextRefusal("domain", `event height ${String(e.height)} is not a safe integer`);
2356
+ if (!isIndex(e.pos)) throw new ReplayContextRefusal("domain", `event position ${String(e.pos)} is not a safe integer >= 0`);
2357
+ if (typeof eventId(e) !== "string") throw new ReplayContextRefusal("domain", `an event id of type ${typeof eventId(e)}`);
2358
+ }
2359
+ if (toHeight < height) throw new ReplayContextRefusal("order", `target ${toHeight} is below the context's height ${height}`);
2360
+ for (const e of batch) {
2361
+ if (e.height <= height || e.height > toHeight) throw new ReplayContextRefusal("order", `event height ${e.height} is outside (${height}, ${toHeight}]`);
2362
+ }
2363
+ batch.sort(applyOrder);
2364
+ try {
2365
+ for (const e of batch) fold.apply(e);
2366
+ } catch (err) {
2367
+ broken = true;
2368
+ throw err;
2369
+ }
2370
+ height = toHeight;
2371
+ },
2372
+ stateAt(tipHeight) {
2373
+ live();
2374
+ if (tipHeight !== height) throw new ReplayContextRefusal("tip", `an answer at ${String(tipHeight)} from a context at ${height}`);
2375
+ try {
2376
+ return detach(fold.finish(tipHeight));
2377
+ } catch (err) {
2378
+ broken = true;
2379
+ throw err;
2380
+ }
2381
+ }
2382
+ };
2383
+ }
2384
+ var freezeDeep = (v) => {
2385
+ if (v === null || typeof v !== "object" || Object.isFrozen(v)) return;
2386
+ Object.freeze(v);
2387
+ for (const x of Object.values(v)) freezeDeep(x);
2388
+ };
2389
+ var copyRecord = (r) => {
2390
+ const out = {};
2391
+ for (const [k, v] of Object.entries(r)) {
2392
+ if (Array.isArray(v)) {
2393
+ for (const x of v) freezeDeep(x);
2394
+ out[k] = [...v];
2395
+ } else {
2396
+ freezeDeep(v);
2397
+ out[k] = v;
2398
+ }
2399
+ }
2400
+ return out;
2401
+ };
2402
+ function detach(st) {
2403
+ const offers = {};
2404
+ for (const [id, o] of Object.entries(st.offers)) {
2405
+ if (o.status === "open") offers[id] = copyRecord(o);
2406
+ else {
2407
+ freezeDeep(o);
2408
+ offers[id] = o;
2409
+ }
2410
+ }
2411
+ const bids = {};
2412
+ for (const [id, b] of Object.entries(st.bids)) bids[id] = copyRecord(b);
2413
+ for (const n of Object.values(st.names)) freezeDeep(n.profile);
2414
+ const events = st.events.slice();
2415
+ for (const e of events) freezeDeep(e);
2416
+ return { ...st, offers, bids, events };
2417
+ }
2418
+
2419
+ // src/client.ts
2420
+ var import_csd_codec4 = require("@inversealtruism/csd-codec");
2190
2421
  var CLAIM_ATTACKER_Q = 0.2;
2191
2422
  var CLAIM_MIN_DEPTH = 3;
2192
2423
  var COMMIT_REVEAL_MIN_DEPTH = 3;
2193
2424
  function requiredClaimDepth(valueSats, height) {
2194
2425
  const r = CLAIM_ATTACKER_Q / (1 - CLAIM_ATTACKER_Q);
2195
2426
  const V = Number(valueSats);
2196
- const R = (0, import_csd_codec3.blockReward)(height) || import_csd_codec3.INITIAL_REWARD;
2427
+ const R = (0, import_csd_codec4.blockReward)(height) || import_csd_codec4.INITIAL_REWARD;
2197
2428
  const max = claimWindowAt(height) - 5;
2198
2429
  for (let D = CLAIM_MIN_DEPTH; D <= max; D++) {
2199
2430
  if (Math.pow(r, D) * V <= D * R) return { depth: D, reversalPct: Math.pow(r, D) * 100, capped: false };
@@ -2373,7 +2604,7 @@ function nameView(names, name) {
2373
2604
  }
2374
2605
 
2375
2606
  // src/version.ts
2376
- var CAIRNX_CORE_VERSION = "0.2.9";
2607
+ var CAIRNX_CORE_VERSION = "0.2.10";
2377
2608
 
2378
2609
  // src/gates.ts
2379
2610
  var GATE_HEIGHTS = Object.freeze({
@@ -2400,7 +2631,7 @@ var GATE_HEIGHTS = Object.freeze({
2400
2631
  });
2401
2632
 
2402
2633
  // src/verifyfill.ts
2403
- var import_csd_codec4 = require("@inversealtruism/csd-codec");
2634
+ var import_csd_codec5 = require("@inversealtruism/csd-codec");
2404
2635
  var FCLAIM_MAX_HOLD_SPAN = import_csd_codec.EPOCH_LEN * (FCLAIM_MAX_EPOCH_AHEAD + 1) - 1;
2405
2636
  var GAP_NEEDED = FCLAIM_MAX_HOLD_SPAN + CLAIM_COOLDOWN_BLOCKS;
2406
2637
  var SCAN_MARGIN = import_csd_codec.EPOCH_LEN;
@@ -2408,7 +2639,7 @@ var MAX_SCAN = GAP_NEEDED + SCAN_MARGIN;
2408
2639
  function bindRecord(ev) {
2409
2640
  const rec = parseRecord(ev.uri, ev.payloadHash);
2410
2641
  if (!rec) return null;
2411
- if ((0, import_csd_codec4.payloadHash)(rec).toLowerCase() !== String(ev.payloadHash).toLowerCase()) return null;
2642
+ if ((0, import_csd_codec5.payloadHash)(rec).toLowerCase() !== String(ev.payloadHash).toLowerCase()) return null;
2412
2643
  return rec;
2413
2644
  }
2414
2645
  function replayLiveHold(proven, offerId, fclaimTxid, me, evalHeight) {
@@ -2563,138 +2794,6 @@ function bindProvenOffer(offerEv) {
2563
2794
  return { payto, seller, terms: provenOfferTerms(rec, offerEv.height) };
2564
2795
  }
2565
2796
 
2566
- // src/paidto.ts
2567
- function paidToFromOutputs(outputs) {
2568
- const m = /* @__PURE__ */ Object.create(null);
2569
- for (const o of outputs) {
2570
- if (typeof o.value !== "number" || !Number.isSafeInteger(o.value) || o.value < 0) continue;
2571
- m[o.addr] = (BigInt(m[o.addr] ?? "0") + BigInt(o.value)).toString();
2572
- }
2573
- return m;
2574
- }
2575
- function burnedPayment(paidTo, payer, offer2) {
2576
- const read = (addr) => addr === payer ? 0n : ptAmt(paidTo?.[addr]);
2577
- let counterparty = 0n;
2578
- if (offer2) {
2579
- for (const addr of /* @__PURE__ */ new Set([offer2.seller, offer2.want.payto])) if (addr !== TREASURY_ADDR) counterparty += read(addr);
2580
- }
2581
- return { treasury: read(TREASURY_ADDR), counterparty };
2582
- }
2583
-
2584
- // src/events.ts
2585
- var import_csd_codec5 = require("@inversealtruism/csd-codec");
2586
- var CAIRNX_EVENT_RULE = Object.freeze({ domain: DOMAIN, activationHeight: ACTIVATION_HEIGHT });
2587
- var fail = (what) => {
2588
- throw new Error(`events rule: ${what}`);
2589
- };
2590
- var isIndex = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
2591
- function hexOf(v, bytes, what) {
2592
- const h = typeof v === "string" && v.startsWith("0x") ? v.slice(2) : v;
2593
- if (typeof h !== "string" || h.length !== bytes * 2 || !/^[0-9a-fA-F]*$/.test(h)) return fail(`${what} is not ${bytes}-byte hex`);
2594
- return "0x" + h.toLowerCase();
2595
- }
2596
- function u64Of(v, what) {
2597
- if (typeof v === "bigint" && v >= 0n && v < 1n << 64n) return v;
2598
- if (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 2 ** 53) return v;
2599
- if (typeof v === "number" && Number.isInteger(v) && v > 2 ** 53) return fail(`${what} above 2^53 must be passed as a bigint`);
2600
- return fail(`${what} is not a u64`);
2601
- }
2602
- function u32Of(v, what) {
2603
- return typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 4294967295 ? v : fail(`${what} is not a u32`);
2604
- }
2605
- function checkRule(rule) {
2606
- const d = rule?.domain;
2607
- if (typeof d !== "string" || d === "" || !(0, import_csd_codec5.isWellFormedUtf16)(d) || d.includes("\0") || d.includes(""))
2608
- fail("the rule's domain must be non-empty, well-formed text without U+0000 or U+0001");
2609
- if (!isIndex(rule.activationHeight)) fail("the rule's activation height must be a safe integer >= 0");
2610
- }
2611
- var kindOf = (app) => {
2612
- const t = app?.type;
2613
- return t === "None" ? "none" : t === "Propose" ? "propose" : t === "Attest" ? "attest" : fail(`unknown app type ${String(t)}`);
2614
- };
2615
- var domainOf = (app) => typeof app.domain === "string" ? app.domain : fail("a Propose domain is not text");
2616
- function paidToOf(outputs) {
2617
- if (!Array.isArray(outputs)) fail("outputs is not a list");
2618
- const counted = [];
2619
- for (const o of outputs) {
2620
- const addr = hexOf(o?.scriptPubkey, 20, "script_pubkey"), value = u64Of(o?.value, "output value");
2621
- if (value <= Number.MAX_SAFE_INTEGER) counted.push({ addr, value: Number(value) });
2622
- }
2623
- return paidToFromOutputs(counted);
2624
- }
2625
- function eventOfTx(t, height, author, rule = CAIRNX_EVENT_RULE) {
2626
- checkRule(rule);
2627
- if (!isIndex(height)) fail("height is not a safe integer >= 0");
2628
- if (!isIndex(t?.pos)) fail("pos is not a safe integer >= 0");
2629
- const txid = hexOf(t.txid, 32, "txid");
2630
- const app = t.tx?.app;
2631
- const kind = kindOf(app);
2632
- if (kind === "none" || height < rule.activationHeight) return null;
2633
- if (t.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2634
- if (kind === "propose" && domainOf(app) !== rule.domain) return null;
2635
- const paidTo = paidToOf(t.tx.outputs), who = hexOf(author, 20, "author");
2636
- if (kind === "propose") {
2637
- const p = app;
2638
- const uri = p.uri;
2639
- if (typeof uri !== "string" || !(0, import_csd_codec5.isWellFormedUtf16)(uri)) return fail("uri is not well-formed text");
2640
- const e = u64Of(p.expiresEpoch, "expiresEpoch");
2641
- return {
2642
- kind: "propose",
2643
- id: txid,
2644
- proposer: who,
2645
- uri: uri.replaceAll("\0", ""),
2646
- payloadHash: hexOf(p.payloadHash, 32, "payloadHash"),
2647
- expiresEpoch: e <= Number.MAX_SAFE_INTEGER ? Number(e) : 2 ** 53,
2648
- height,
2649
- pos: t.pos,
2650
- paidTo
2651
- };
2652
- }
2653
- const a = app;
2654
- return {
2655
- kind: "attest",
2656
- txid,
2657
- proposalId: hexOf(a.proposalId, 32, "proposalId"),
2658
- attester: who,
2659
- score: u32Of(a.score, "score"),
2660
- confidence: u32Of(a.confidence, "confidence"),
2661
- height,
2662
- pos: t.pos,
2663
- paidTo
2664
- };
2665
- }
2666
- function blockMembers(height, txs, sofar, rule = CAIRNX_EVENT_RULE) {
2667
- checkRule(rule);
2668
- if (!isIndex(height)) fail("height is not a safe integer >= 0");
2669
- if (height < rule.activationHeight) return [];
2670
- if (!Array.isArray(txs)) fail("txs is not a list");
2671
- const ids = /* @__PURE__ */ new Set(), proposals = /* @__PURE__ */ new Set();
2672
- const read = [];
2673
- let last = -1;
2674
- for (const item of txs) {
2675
- if (!isIndex(item?.pos) || item.pos <= last) fail("positions are not safe integers >= 0 in strictly increasing order");
2676
- last = item.pos;
2677
- const id = hexOf(item.txid, 32, "txid");
2678
- if (ids.has(id)) fail(`txid ${id} is repeated in the block`);
2679
- ids.add(id);
2680
- const kind = kindOf(item.tx?.app);
2681
- if (kind === "none") continue;
2682
- if (item.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2683
- if (kind === "propose") {
2684
- if (domainOf(item.tx.app) !== rule.domain || sofar.eventIds.has(id)) continue;
2685
- proposals.add(id);
2686
- read.push({ item, kind, id });
2687
- } else read.push({ item, kind, id, proposal: hexOf(item.tx.app.proposalId, 32, "proposalId") });
2688
- }
2689
- return read.filter((r) => r.kind === "propose" || !sofar.eventIds.has(r.id) && (sofar.proposeIds.has(r.proposal) || proposals.has(r.proposal))).map((r) => ({ kind: r.kind, item: r.item }));
2690
- }
2691
- function blockEvents(height, txs, sofar, authors, rule = CAIRNX_EVENT_RULE) {
2692
- const members = blockMembers(height, txs, sofar, rule);
2693
- if (!Array.isArray(authors) || authors.length !== members.length) fail(`the block has ${members.length} members, not ${authors?.length} authors`);
2694
- const events = members.map((m, i) => eventOfTx(m.item, height, authors[i], rule) ?? fail("a member mapped to no event"));
2695
- return [...events.filter((e) => e.kind === "propose"), ...events.filter((e) => e.kind === "attest")];
2696
- }
2697
-
2698
2797
  // src/hashes.ts
2699
2798
  var import_csd_codec6 = require("@inversealtruism/csd-codec");
2700
2799
  var import_sha256 = require("@noble/hashes/sha256");
@@ -3014,6 +3113,7 @@ var import_csd_codec7 = require("@inversealtruism/csd-codec");
3014
3113
  REG_FINALIZE_GRACE_BLOCKS,
3015
3114
  RESERVED_NAMES,
3016
3115
  RecordError,
3116
+ ReplayContextRefusal,
3017
3117
  SALT_RE,
3018
3118
  SCAN_MARGIN,
3019
3119
  SCORE_CANCEL,
@@ -3077,6 +3177,7 @@ var import_csd_codec7 = require("@inversealtruism/csd-codec");
3077
3177
  fillTargetId,
3078
3178
  finalizeWinnerCheck,
3079
3179
  hasLiveClaim,
3180
+ isChainHeight,
3080
3181
  isName,
3081
3182
  isNameGive,
3082
3183
  isOpenClaimLane,
@@ -3094,6 +3195,7 @@ var import_csd_codec7 = require("@inversealtruism/csd-codec");
3094
3195
  nameSet,
3095
3196
  nameView,
3096
3197
  nameXfer,
3198
+ newReplayContext,
3097
3199
  offer,
3098
3200
  offerCancelAll,
3099
3201
  offerExpiryHeightOf,
package/dist/index.d.cts CHANGED
@@ -137,6 +137,10 @@ declare const DOMAIN = "cairnx:v1";
137
137
  declare const ACTIVATION_HEIGHT = 29860;
138
138
  /** True below ACTIVATION_HEIGHT, where resolve() skips every event without a note. */
139
139
  declare const beforeActivation: (height: number) => boolean;
140
+ /** Whether an event height or a tip lies in the domain the replay's expiry batches are proven for (CONVENTION section
141
+ * 5): a safe integer. The chain produces non-negative ones; a negative one is skipped below activation. The fold's
142
+ * split and a held context's refusal both read this one rule. */
143
+ declare const isChainHeight: (height: unknown) => height is number;
140
144
  declare const V11_HEIGHT = 29960;
141
145
  declare const V12_HEIGHT = 30300;
142
146
  declare const V13_HEIGHT = 31100;
@@ -613,6 +617,30 @@ declare function resolve(events: ChainEvent[], tipHeight: number): CairnXState;
613
617
  * history.) Keys sort in ordinal (code-unit) order at every depth. */
614
618
  declare function canonicalState(s: CairnXState): string;
615
619
 
620
+ type ReplayContextRefusalCode = "domain" | "order" | "tip" | "broken" | "sloppy";
621
+ /** A call the context does not take, thrown before it writes anything. "domain": a target height or an event height
622
+ * outside isChainHeight, an event position that is not a safe integer >= 0, or an event id (a Propose's id, an
623
+ * Attest's txid) that is not a string; "order": a target below the context's height, or an event at or below it or
624
+ * above the target (a negative height, for a new context); "tip": an answer asked off the context's height;
625
+ * "broken": any call after the replay threw inside advance or stateAt; "sloppy": a context started where a write to a
626
+ * frozen object does not throw. */
627
+ declare class ReplayContextRefusal extends Error {
628
+ readonly code: ReplayContextRefusalCode;
629
+ constructor(code: ReplayContextRefusalCode, message: string);
630
+ }
631
+ interface ReplayContext {
632
+ /** Every event at or below this height has been given; -1, below the chain's first block, for a new context. */
633
+ readonly height: number;
634
+ /** Applies all events of the blocks in (height, toHeight], in apply order, and moves the height to toHeight. Reads
635
+ * `events` once and keeps a copy of each event's own fields, so a later write into a fed event changes no later
636
+ * answer. The copy is one level deep: `paidTo` stays the caller's object, read only during this call. */
637
+ advance(toHeight: number, events: readonly ChainEvent[]): void;
638
+ /** resolve() over the events given so far at tipHeight, which must equal the context's height. The result shares
639
+ * nothing a later advance writes; what it shares is frozen. */
640
+ stateAt(tipHeight: number): CairnXState;
641
+ }
642
+ declare function newReplayContext(): ReplayContext;
643
+
616
644
  declare const CLAIM_ATTACKER_Q = 0.2;
617
645
  declare const CLAIM_MIN_DEPTH = 3;
618
646
  declare const COMMIT_REVEAL_MIN_DEPTH = 3;
@@ -862,7 +890,7 @@ declare function nameView(names: Record<string, NameState>, name: string): NameV
862
890
 
863
891
  /** This package's version, for a host that names the core it loaded (cairnx-api's `rev`, a replica's report). Equal to
864
892
  * package.json's version (test/version.test.ts). */
865
- declare const CAIRNX_CORE_VERSION = "0.2.9";
893
+ declare const CAIRNX_CORE_VERSION = "0.2.10";
866
894
 
867
895
  /** Gate name to height: `ACTIVATION_HEIGHT` and each `V<n>_HEIGHT`, frozen. test/gates.test.ts keeps it equal to the
868
896
  * individual exports and complete. It leaves out the one other exported height, `LEGACY_HOLD_SUNSET_HEIGHT`, which is
@@ -1192,4 +1220,4 @@ interface ProvenOfferTx {
1192
1220
  * rules; the resolver writes no note below activation), or null when it passes. */
1193
1221
  declare function provenOfferRefusal(rec: OfferRecord, tx: ProvenOfferTx): string | null;
1194
1222
 
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 };
1223
+ 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 ReplayContext, ReplayContextRefusal, type ReplayContextRefusalCode, 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, isChainHeight, isName, isNameGive, isOpenClaimLane, isTokenWant, makerRebate, mint, myProvenFillClosedOffer, nameClaim, nameCommit, nameCommitRecord, nameFinalize, nameProfile, nameRegFee, nameRenew, nameSet, nameView, nameXfer, newReplayContext, offer, offerCancelAll, offerExpiryHeightOf, offerFillTooLate, paidToFromOutputs, parseAmount, parseRecord, pickPrimaryName, previewFill, primaryRankBefore, provenOfferRefusal, provenOfferTerms, ptAmt, replayLiveHold, requiredClaimDepth, requiredFillOutputs, resolve, resolveNameIn, stateHash, tokenMeta, tradeFee, transfer, unsafeMintProvenOfferTerms, verifyFillSpv };
package/dist/index.d.ts CHANGED
@@ -137,6 +137,10 @@ declare const DOMAIN = "cairnx:v1";
137
137
  declare const ACTIVATION_HEIGHT = 29860;
138
138
  /** True below ACTIVATION_HEIGHT, where resolve() skips every event without a note. */
139
139
  declare const beforeActivation: (height: number) => boolean;
140
+ /** Whether an event height or a tip lies in the domain the replay's expiry batches are proven for (CONVENTION section
141
+ * 5): a safe integer. The chain produces non-negative ones; a negative one is skipped below activation. The fold's
142
+ * split and a held context's refusal both read this one rule. */
143
+ declare const isChainHeight: (height: unknown) => height is number;
140
144
  declare const V11_HEIGHT = 29960;
141
145
  declare const V12_HEIGHT = 30300;
142
146
  declare const V13_HEIGHT = 31100;
@@ -613,6 +617,30 @@ declare function resolve(events: ChainEvent[], tipHeight: number): CairnXState;
613
617
  * history.) Keys sort in ordinal (code-unit) order at every depth. */
614
618
  declare function canonicalState(s: CairnXState): string;
615
619
 
620
+ type ReplayContextRefusalCode = "domain" | "order" | "tip" | "broken" | "sloppy";
621
+ /** A call the context does not take, thrown before it writes anything. "domain": a target height or an event height
622
+ * outside isChainHeight, an event position that is not a safe integer >= 0, or an event id (a Propose's id, an
623
+ * Attest's txid) that is not a string; "order": a target below the context's height, or an event at or below it or
624
+ * above the target (a negative height, for a new context); "tip": an answer asked off the context's height;
625
+ * "broken": any call after the replay threw inside advance or stateAt; "sloppy": a context started where a write to a
626
+ * frozen object does not throw. */
627
+ declare class ReplayContextRefusal extends Error {
628
+ readonly code: ReplayContextRefusalCode;
629
+ constructor(code: ReplayContextRefusalCode, message: string);
630
+ }
631
+ interface ReplayContext {
632
+ /** Every event at or below this height has been given; -1, below the chain's first block, for a new context. */
633
+ readonly height: number;
634
+ /** Applies all events of the blocks in (height, toHeight], in apply order, and moves the height to toHeight. Reads
635
+ * `events` once and keeps a copy of each event's own fields, so a later write into a fed event changes no later
636
+ * answer. The copy is one level deep: `paidTo` stays the caller's object, read only during this call. */
637
+ advance(toHeight: number, events: readonly ChainEvent[]): void;
638
+ /** resolve() over the events given so far at tipHeight, which must equal the context's height. The result shares
639
+ * nothing a later advance writes; what it shares is frozen. */
640
+ stateAt(tipHeight: number): CairnXState;
641
+ }
642
+ declare function newReplayContext(): ReplayContext;
643
+
616
644
  declare const CLAIM_ATTACKER_Q = 0.2;
617
645
  declare const CLAIM_MIN_DEPTH = 3;
618
646
  declare const COMMIT_REVEAL_MIN_DEPTH = 3;
@@ -862,7 +890,7 @@ declare function nameView(names: Record<string, NameState>, name: string): NameV
862
890
 
863
891
  /** This package's version, for a host that names the core it loaded (cairnx-api's `rev`, a replica's report). Equal to
864
892
  * package.json's version (test/version.test.ts). */
865
- declare const CAIRNX_CORE_VERSION = "0.2.9";
893
+ declare const CAIRNX_CORE_VERSION = "0.2.10";
866
894
 
867
895
  /** Gate name to height: `ACTIVATION_HEIGHT` and each `V<n>_HEIGHT`, frozen. test/gates.test.ts keeps it equal to the
868
896
  * individual exports and complete. It leaves out the one other exported height, `LEGACY_HOLD_SUNSET_HEIGHT`, which is
@@ -1192,4 +1220,4 @@ interface ProvenOfferTx {
1192
1220
  * rules; the resolver writes no note below activation), or null when it passes. */
1193
1221
  declare function provenOfferRefusal(rec: OfferRecord, tx: ProvenOfferTx): string | null;
1194
1222
 
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 };
1223
+ 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 ReplayContext, ReplayContextRefusal, type ReplayContextRefusalCode, 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, isChainHeight, isName, isNameGive, isOpenClaimLane, isTokenWant, makerRebate, mint, myProvenFillClosedOffer, nameClaim, nameCommit, nameCommitRecord, nameFinalize, nameProfile, nameRegFee, nameRenew, nameSet, nameView, nameXfer, newReplayContext, offer, offerCancelAll, offerExpiryHeightOf, offerFillTooLate, paidToFromOutputs, parseAmount, parseRecord, pickPrimaryName, previewFill, primaryRankBefore, provenOfferRefusal, provenOfferTerms, ptAmt, replayLiveHold, requiredClaimDepth, requiredFillOutputs, resolve, resolveNameIn, stateHash, tokenMeta, tradeFee, transfer, unsafeMintProvenOfferTerms, verifyFillSpv };
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ import { EPOCH_LEN, MAX_URI_BYTES, epochOf } from "@inversealtruism/csd-codec";
3
3
  var DOMAIN = "cairnx:v1";
4
4
  var ACTIVATION_HEIGHT = 29860;
5
5
  var beforeActivation = (height) => height < ACTIVATION_HEIGHT;
6
+ var isChainHeight = (height) => Number.isSafeInteger(height);
6
7
  var V11_HEIGHT = 29960;
7
8
  var V12_HEIGHT = 30300;
8
9
  var V13_HEIGHT = 31100;
@@ -1825,7 +1826,7 @@ function replay(events, tipHeight, opts = {}) {
1825
1826
  for (const e of [...events].sort(applyOrder)) fold.apply(e);
1826
1827
  return fold.finish(tipHeight);
1827
1828
  }
1828
- function createFold(opts) {
1829
+ function createFold(opts = {}) {
1829
1830
  const seenIds = /* @__PURE__ */ new Set();
1830
1831
  const store = createStore(opts);
1831
1832
  const c = createContext(store);
@@ -1836,7 +1837,7 @@ function createFold(opts) {
1836
1837
  c.pendingCancels = [];
1837
1838
  };
1838
1839
  const inDomain = (height) => {
1839
- if (!Number.isSafeInteger(height)) store.endSplit();
1840
+ if (!isChainHeight(height)) store.endSplit();
1840
1841
  };
1841
1842
  const apply = (ev) => {
1842
1843
  inDomain(ev.height);
@@ -1982,6 +1983,233 @@ function canonicalState(s) {
1982
1983
  return JSON.stringify(sortKeys(data));
1983
1984
  }
1984
1985
 
1986
+ // src/events.ts
1987
+ import { isWellFormedUtf16 as isWellFormedUtf162 } from "@inversealtruism/csd-codec";
1988
+
1989
+ // src/paidto.ts
1990
+ function paidToFromOutputs(outputs) {
1991
+ const m = /* @__PURE__ */ Object.create(null);
1992
+ for (const o of outputs) {
1993
+ if (typeof o.value !== "number" || !Number.isSafeInteger(o.value) || o.value < 0) continue;
1994
+ m[o.addr] = (BigInt(m[o.addr] ?? "0") + BigInt(o.value)).toString();
1995
+ }
1996
+ return m;
1997
+ }
1998
+ function burnedPayment(paidTo, payer, offer2) {
1999
+ const read = (addr) => addr === payer ? 0n : ptAmt(paidTo?.[addr]);
2000
+ let counterparty = 0n;
2001
+ if (offer2) {
2002
+ for (const addr of /* @__PURE__ */ new Set([offer2.seller, offer2.want.payto])) if (addr !== TREASURY_ADDR) counterparty += read(addr);
2003
+ }
2004
+ return { treasury: read(TREASURY_ADDR), counterparty };
2005
+ }
2006
+
2007
+ // src/events.ts
2008
+ var CAIRNX_EVENT_RULE = Object.freeze({ domain: DOMAIN, activationHeight: ACTIVATION_HEIGHT });
2009
+ var fail = (what) => {
2010
+ throw new Error(`events rule: ${what}`);
2011
+ };
2012
+ var isIndex = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
2013
+ function hexOf(v, bytes, what) {
2014
+ const h = typeof v === "string" && v.startsWith("0x") ? v.slice(2) : v;
2015
+ if (typeof h !== "string" || h.length !== bytes * 2 || !/^[0-9a-fA-F]*$/.test(h)) return fail(`${what} is not ${bytes}-byte hex`);
2016
+ return "0x" + h.toLowerCase();
2017
+ }
2018
+ function u64Of(v, what) {
2019
+ if (typeof v === "bigint" && v >= 0n && v < 1n << 64n) return v;
2020
+ if (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 2 ** 53) return v;
2021
+ if (typeof v === "number" && Number.isInteger(v) && v > 2 ** 53) return fail(`${what} above 2^53 must be passed as a bigint`);
2022
+ return fail(`${what} is not a u64`);
2023
+ }
2024
+ function u32Of(v, what) {
2025
+ return typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 4294967295 ? v : fail(`${what} is not a u32`);
2026
+ }
2027
+ function checkRule(rule) {
2028
+ const d = rule?.domain;
2029
+ if (typeof d !== "string" || d === "" || !isWellFormedUtf162(d) || d.includes("\0") || d.includes(""))
2030
+ fail("the rule's domain must be non-empty, well-formed text without U+0000 or U+0001");
2031
+ if (!isIndex(rule.activationHeight)) fail("the rule's activation height must be a safe integer >= 0");
2032
+ }
2033
+ var kindOf = (app) => {
2034
+ const t = app?.type;
2035
+ return t === "None" ? "none" : t === "Propose" ? "propose" : t === "Attest" ? "attest" : fail(`unknown app type ${String(t)}`);
2036
+ };
2037
+ var domainOf = (app) => typeof app.domain === "string" ? app.domain : fail("a Propose domain is not text");
2038
+ function paidToOf(outputs) {
2039
+ if (!Array.isArray(outputs)) fail("outputs is not a list");
2040
+ const counted = [];
2041
+ for (const o of outputs) {
2042
+ const addr = hexOf(o?.scriptPubkey, 20, "script_pubkey"), value = u64Of(o?.value, "output value");
2043
+ if (value <= Number.MAX_SAFE_INTEGER) counted.push({ addr, value: Number(value) });
2044
+ }
2045
+ return paidToFromOutputs(counted);
2046
+ }
2047
+ function eventOfTx(t, height, author, rule = CAIRNX_EVENT_RULE) {
2048
+ checkRule(rule);
2049
+ if (!isIndex(height)) fail("height is not a safe integer >= 0");
2050
+ if (!isIndex(t?.pos)) fail("pos is not a safe integer >= 0");
2051
+ const txid = hexOf(t.txid, 32, "txid");
2052
+ const app = t.tx?.app;
2053
+ const kind = kindOf(app);
2054
+ if (kind === "none" || height < rule.activationHeight) return null;
2055
+ if (t.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2056
+ if (kind === "propose" && domainOf(app) !== rule.domain) return null;
2057
+ const paidTo = paidToOf(t.tx.outputs), who = hexOf(author, 20, "author");
2058
+ if (kind === "propose") {
2059
+ const p = app;
2060
+ const uri = p.uri;
2061
+ if (typeof uri !== "string" || !isWellFormedUtf162(uri)) return fail("uri is not well-formed text");
2062
+ const e = u64Of(p.expiresEpoch, "expiresEpoch");
2063
+ return {
2064
+ kind: "propose",
2065
+ id: txid,
2066
+ proposer: who,
2067
+ uri: uri.replaceAll("\0", ""),
2068
+ payloadHash: hexOf(p.payloadHash, 32, "payloadHash"),
2069
+ expiresEpoch: e <= Number.MAX_SAFE_INTEGER ? Number(e) : 2 ** 53,
2070
+ height,
2071
+ pos: t.pos,
2072
+ paidTo
2073
+ };
2074
+ }
2075
+ const a = app;
2076
+ return {
2077
+ kind: "attest",
2078
+ txid,
2079
+ proposalId: hexOf(a.proposalId, 32, "proposalId"),
2080
+ attester: who,
2081
+ score: u32Of(a.score, "score"),
2082
+ confidence: u32Of(a.confidence, "confidence"),
2083
+ height,
2084
+ pos: t.pos,
2085
+ paidTo
2086
+ };
2087
+ }
2088
+ function blockMembers(height, txs, sofar, rule = CAIRNX_EVENT_RULE) {
2089
+ checkRule(rule);
2090
+ if (!isIndex(height)) fail("height is not a safe integer >= 0");
2091
+ if (height < rule.activationHeight) return [];
2092
+ if (!Array.isArray(txs)) fail("txs is not a list");
2093
+ const ids = /* @__PURE__ */ new Set(), proposals = /* @__PURE__ */ new Set();
2094
+ const read = [];
2095
+ let last = -1;
2096
+ for (const item of txs) {
2097
+ if (!isIndex(item?.pos) || item.pos <= last) fail("positions are not safe integers >= 0 in strictly increasing order");
2098
+ last = item.pos;
2099
+ const id = hexOf(item.txid, 32, "txid");
2100
+ if (ids.has(id)) fail(`txid ${id} is repeated in the block`);
2101
+ ids.add(id);
2102
+ const kind = kindOf(item.tx?.app);
2103
+ if (kind === "none") continue;
2104
+ if (item.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2105
+ if (kind === "propose") {
2106
+ if (domainOf(item.tx.app) !== rule.domain || sofar.eventIds.has(id)) continue;
2107
+ proposals.add(id);
2108
+ read.push({ item, kind, id });
2109
+ } else read.push({ item, kind, id, proposal: hexOf(item.tx.app.proposalId, 32, "proposalId") });
2110
+ }
2111
+ return read.filter((r) => r.kind === "propose" || !sofar.eventIds.has(r.id) && (sofar.proposeIds.has(r.proposal) || proposals.has(r.proposal))).map((r) => ({ kind: r.kind, item: r.item }));
2112
+ }
2113
+ function blockEvents(height, txs, sofar, authors, rule = CAIRNX_EVENT_RULE) {
2114
+ const members = blockMembers(height, txs, sofar, rule);
2115
+ if (!Array.isArray(authors) || authors.length !== members.length) fail(`the block has ${members.length} members, not ${authors?.length} authors`);
2116
+ const events = members.map((m, i) => eventOfTx(m.item, height, authors[i], rule) ?? fail("a member mapped to no event"));
2117
+ return [...events.filter((e) => e.kind === "propose"), ...events.filter((e) => e.kind === "attest")];
2118
+ }
2119
+
2120
+ // src/replay-context.ts
2121
+ var ReplayContextRefusal = class extends Error {
2122
+ code;
2123
+ constructor(code, message) {
2124
+ super(message);
2125
+ this.name = "ReplayContextRefusal";
2126
+ this.code = code;
2127
+ }
2128
+ };
2129
+ var strictCode = /* @__PURE__ */ (function() {
2130
+ return this === void 0;
2131
+ })();
2132
+ function newReplayContext() {
2133
+ if (!strictCode) throw new ReplayContextRefusal("sloppy", "this build runs cairnx-core in sloppy mode, where a write to a frozen object is ignored");
2134
+ const fold = createFold();
2135
+ let height = -1;
2136
+ let broken = false;
2137
+ const live = () => {
2138
+ if (broken) throw new ReplayContextRefusal("broken", "the replay threw inside advance or stateAt; replay with resolve()");
2139
+ };
2140
+ return {
2141
+ get height() {
2142
+ return height;
2143
+ },
2144
+ advance(toHeight, events) {
2145
+ live();
2146
+ if (!isChainHeight(toHeight)) throw new ReplayContextRefusal("domain", `target height ${String(toHeight)} is not a safe integer`);
2147
+ const batch = [...events].map((e) => ({ ...e }));
2148
+ for (const e of batch) {
2149
+ if (!isChainHeight(e.height)) throw new ReplayContextRefusal("domain", `event height ${String(e.height)} is not a safe integer`);
2150
+ if (!isIndex(e.pos)) throw new ReplayContextRefusal("domain", `event position ${String(e.pos)} is not a safe integer >= 0`);
2151
+ if (typeof eventId(e) !== "string") throw new ReplayContextRefusal("domain", `an event id of type ${typeof eventId(e)}`);
2152
+ }
2153
+ if (toHeight < height) throw new ReplayContextRefusal("order", `target ${toHeight} is below the context's height ${height}`);
2154
+ for (const e of batch) {
2155
+ if (e.height <= height || e.height > toHeight) throw new ReplayContextRefusal("order", `event height ${e.height} is outside (${height}, ${toHeight}]`);
2156
+ }
2157
+ batch.sort(applyOrder);
2158
+ try {
2159
+ for (const e of batch) fold.apply(e);
2160
+ } catch (err) {
2161
+ broken = true;
2162
+ throw err;
2163
+ }
2164
+ height = toHeight;
2165
+ },
2166
+ stateAt(tipHeight) {
2167
+ live();
2168
+ if (tipHeight !== height) throw new ReplayContextRefusal("tip", `an answer at ${String(tipHeight)} from a context at ${height}`);
2169
+ try {
2170
+ return detach(fold.finish(tipHeight));
2171
+ } catch (err) {
2172
+ broken = true;
2173
+ throw err;
2174
+ }
2175
+ }
2176
+ };
2177
+ }
2178
+ var freezeDeep = (v) => {
2179
+ if (v === null || typeof v !== "object" || Object.isFrozen(v)) return;
2180
+ Object.freeze(v);
2181
+ for (const x of Object.values(v)) freezeDeep(x);
2182
+ };
2183
+ var copyRecord = (r) => {
2184
+ const out = {};
2185
+ for (const [k, v] of Object.entries(r)) {
2186
+ if (Array.isArray(v)) {
2187
+ for (const x of v) freezeDeep(x);
2188
+ out[k] = [...v];
2189
+ } else {
2190
+ freezeDeep(v);
2191
+ out[k] = v;
2192
+ }
2193
+ }
2194
+ return out;
2195
+ };
2196
+ function detach(st) {
2197
+ const offers = {};
2198
+ for (const [id, o] of Object.entries(st.offers)) {
2199
+ if (o.status === "open") offers[id] = copyRecord(o);
2200
+ else {
2201
+ freezeDeep(o);
2202
+ offers[id] = o;
2203
+ }
2204
+ }
2205
+ const bids = {};
2206
+ for (const [id, b] of Object.entries(st.bids)) bids[id] = copyRecord(b);
2207
+ for (const n of Object.values(st.names)) freezeDeep(n.profile);
2208
+ const events = st.events.slice();
2209
+ for (const e of events) freezeDeep(e);
2210
+ return { ...st, offers, bids, events };
2211
+ }
2212
+
1985
2213
  // src/client.ts
1986
2214
  import { blockReward, INITIAL_REWARD } from "@inversealtruism/csd-codec";
1987
2215
  var CLAIM_ATTACKER_Q = 0.2;
@@ -2170,7 +2398,7 @@ function nameView(names, name) {
2170
2398
  }
2171
2399
 
2172
2400
  // src/version.ts
2173
- var CAIRNX_CORE_VERSION = "0.2.9";
2401
+ var CAIRNX_CORE_VERSION = "0.2.10";
2174
2402
 
2175
2403
  // src/gates.ts
2176
2404
  var GATE_HEIGHTS = Object.freeze({
@@ -2360,138 +2588,6 @@ function bindProvenOffer(offerEv) {
2360
2588
  return { payto, seller, terms: provenOfferTerms(rec, offerEv.height) };
2361
2589
  }
2362
2590
 
2363
- // src/paidto.ts
2364
- function paidToFromOutputs(outputs) {
2365
- const m = /* @__PURE__ */ Object.create(null);
2366
- for (const o of outputs) {
2367
- if (typeof o.value !== "number" || !Number.isSafeInteger(o.value) || o.value < 0) continue;
2368
- m[o.addr] = (BigInt(m[o.addr] ?? "0") + BigInt(o.value)).toString();
2369
- }
2370
- return m;
2371
- }
2372
- function burnedPayment(paidTo, payer, offer2) {
2373
- const read = (addr) => addr === payer ? 0n : ptAmt(paidTo?.[addr]);
2374
- let counterparty = 0n;
2375
- if (offer2) {
2376
- for (const addr of /* @__PURE__ */ new Set([offer2.seller, offer2.want.payto])) if (addr !== TREASURY_ADDR) counterparty += read(addr);
2377
- }
2378
- return { treasury: read(TREASURY_ADDR), counterparty };
2379
- }
2380
-
2381
- // src/events.ts
2382
- import { isWellFormedUtf16 as isWellFormedUtf162 } from "@inversealtruism/csd-codec";
2383
- var CAIRNX_EVENT_RULE = Object.freeze({ domain: DOMAIN, activationHeight: ACTIVATION_HEIGHT });
2384
- var fail = (what) => {
2385
- throw new Error(`events rule: ${what}`);
2386
- };
2387
- var isIndex = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
2388
- function hexOf(v, bytes, what) {
2389
- const h = typeof v === "string" && v.startsWith("0x") ? v.slice(2) : v;
2390
- if (typeof h !== "string" || h.length !== bytes * 2 || !/^[0-9a-fA-F]*$/.test(h)) return fail(`${what} is not ${bytes}-byte hex`);
2391
- return "0x" + h.toLowerCase();
2392
- }
2393
- function u64Of(v, what) {
2394
- if (typeof v === "bigint" && v >= 0n && v < 1n << 64n) return v;
2395
- if (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 2 ** 53) return v;
2396
- if (typeof v === "number" && Number.isInteger(v) && v > 2 ** 53) return fail(`${what} above 2^53 must be passed as a bigint`);
2397
- return fail(`${what} is not a u64`);
2398
- }
2399
- function u32Of(v, what) {
2400
- return typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 4294967295 ? v : fail(`${what} is not a u32`);
2401
- }
2402
- function checkRule(rule) {
2403
- const d = rule?.domain;
2404
- if (typeof d !== "string" || d === "" || !isWellFormedUtf162(d) || d.includes("\0") || d.includes(""))
2405
- fail("the rule's domain must be non-empty, well-formed text without U+0000 or U+0001");
2406
- if (!isIndex(rule.activationHeight)) fail("the rule's activation height must be a safe integer >= 0");
2407
- }
2408
- var kindOf = (app) => {
2409
- const t = app?.type;
2410
- return t === "None" ? "none" : t === "Propose" ? "propose" : t === "Attest" ? "attest" : fail(`unknown app type ${String(t)}`);
2411
- };
2412
- var domainOf = (app) => typeof app.domain === "string" ? app.domain : fail("a Propose domain is not text");
2413
- function paidToOf(outputs) {
2414
- if (!Array.isArray(outputs)) fail("outputs is not a list");
2415
- const counted = [];
2416
- for (const o of outputs) {
2417
- const addr = hexOf(o?.scriptPubkey, 20, "script_pubkey"), value = u64Of(o?.value, "output value");
2418
- if (value <= Number.MAX_SAFE_INTEGER) counted.push({ addr, value: Number(value) });
2419
- }
2420
- return paidToFromOutputs(counted);
2421
- }
2422
- function eventOfTx(t, height, author, rule = CAIRNX_EVENT_RULE) {
2423
- checkRule(rule);
2424
- if (!isIndex(height)) fail("height is not a safe integer >= 0");
2425
- if (!isIndex(t?.pos)) fail("pos is not a safe integer >= 0");
2426
- const txid = hexOf(t.txid, 32, "txid");
2427
- const app = t.tx?.app;
2428
- const kind = kindOf(app);
2429
- if (kind === "none" || height < rule.activationHeight) return null;
2430
- if (t.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2431
- if (kind === "propose" && domainOf(app) !== rule.domain) return null;
2432
- const paidTo = paidToOf(t.tx.outputs), who = hexOf(author, 20, "author");
2433
- if (kind === "propose") {
2434
- const p = app;
2435
- const uri = p.uri;
2436
- if (typeof uri !== "string" || !isWellFormedUtf162(uri)) return fail("uri is not well-formed text");
2437
- const e = u64Of(p.expiresEpoch, "expiresEpoch");
2438
- return {
2439
- kind: "propose",
2440
- id: txid,
2441
- proposer: who,
2442
- uri: uri.replaceAll("\0", ""),
2443
- payloadHash: hexOf(p.payloadHash, 32, "payloadHash"),
2444
- expiresEpoch: e <= Number.MAX_SAFE_INTEGER ? Number(e) : 2 ** 53,
2445
- height,
2446
- pos: t.pos,
2447
- paidTo
2448
- };
2449
- }
2450
- const a = app;
2451
- return {
2452
- kind: "attest",
2453
- txid,
2454
- proposalId: hexOf(a.proposalId, 32, "proposalId"),
2455
- attester: who,
2456
- score: u32Of(a.score, "score"),
2457
- confidence: u32Of(a.confidence, "confidence"),
2458
- height,
2459
- pos: t.pos,
2460
- paidTo
2461
- };
2462
- }
2463
- function blockMembers(height, txs, sofar, rule = CAIRNX_EVENT_RULE) {
2464
- checkRule(rule);
2465
- if (!isIndex(height)) fail("height is not a safe integer >= 0");
2466
- if (height < rule.activationHeight) return [];
2467
- if (!Array.isArray(txs)) fail("txs is not a list");
2468
- const ids = /* @__PURE__ */ new Set(), proposals = /* @__PURE__ */ new Set();
2469
- const read = [];
2470
- let last = -1;
2471
- for (const item of txs) {
2472
- if (!isIndex(item?.pos) || item.pos <= last) fail("positions are not safe integers >= 0 in strictly increasing order");
2473
- last = item.pos;
2474
- const id = hexOf(item.txid, 32, "txid");
2475
- if (ids.has(id)) fail(`txid ${id} is repeated in the block`);
2476
- ids.add(id);
2477
- const kind = kindOf(item.tx?.app);
2478
- if (kind === "none") continue;
2479
- if (item.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2480
- if (kind === "propose") {
2481
- if (domainOf(item.tx.app) !== rule.domain || sofar.eventIds.has(id)) continue;
2482
- proposals.add(id);
2483
- read.push({ item, kind, id });
2484
- } else read.push({ item, kind, id, proposal: hexOf(item.tx.app.proposalId, 32, "proposalId") });
2485
- }
2486
- return read.filter((r) => r.kind === "propose" || !sofar.eventIds.has(r.id) && (sofar.proposeIds.has(r.proposal) || proposals.has(r.proposal))).map((r) => ({ kind: r.kind, item: r.item }));
2487
- }
2488
- function blockEvents(height, txs, sofar, authors, rule = CAIRNX_EVENT_RULE) {
2489
- const members = blockMembers(height, txs, sofar, rule);
2490
- if (!Array.isArray(authors) || authors.length !== members.length) fail(`the block has ${members.length} members, not ${authors?.length} authors`);
2491
- const events = members.map((m, i) => eventOfTx(m.item, height, authors[i], rule) ?? fail("a member mapped to no event"));
2492
- return [...events.filter((e) => e.kind === "propose"), ...events.filter((e) => e.kind === "attest")];
2493
- }
2494
-
2495
2591
  // src/hashes.ts
2496
2592
  import { bytesToHex, concatBytes, hexToBytes, utf8ToBytes } from "@inversealtruism/csd-codec";
2497
2593
  import { sha256 } from "@noble/hashes/sha256";
@@ -2819,6 +2915,7 @@ export {
2819
2915
  REG_FINALIZE_GRACE_BLOCKS,
2820
2916
  RESERVED_NAMES,
2821
2917
  RecordError,
2918
+ ReplayContextRefusal,
2822
2919
  SALT_RE,
2823
2920
  SCAN_MARGIN,
2824
2921
  SCORE_CANCEL,
@@ -2882,6 +2979,7 @@ export {
2882
2979
  fillTargetId,
2883
2980
  finalizeWinnerCheck,
2884
2981
  hasLiveClaim,
2982
+ isChainHeight,
2885
2983
  isName,
2886
2984
  isNameGive,
2887
2985
  isOpenClaimLane,
@@ -2899,6 +2997,7 @@ export {
2899
2997
  nameSet,
2900
2998
  nameView,
2901
2999
  nameXfer,
3000
+ newReplayContext,
2902
3001
  offer,
2903
3002
  offerCancelAll,
2904
3003
  offerExpiryHeightOf,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inversealtruism/cairnx-core",
3
- "version": "0.2.9",
3
+ "version": "0.2.10",
4
4
  "engines": {
5
5
  "node": ">=18"
6
6
  },