@inversealtruism/cairnx-core 0.2.4 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -24,6 +24,9 @@ __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,
28
+ CAIRNX_EVENT_RULE: () => CAIRNX_EVENT_RULE,
29
+ CAP_CODES: () => CAP_CODES,
27
30
  CLAIM_ATTACKER_Q: () => CLAIM_ATTACKER_Q,
28
31
  CLAIM_COOLDOWN_BLOCKS: () => CLAIM_COOLDOWN_BLOCKS,
29
32
  CLAIM_FILL_GRACE_BLOCKS: () => CLAIM_FILL_GRACE_BLOCKS,
@@ -36,7 +39,8 @@ __export(index_exports, {
36
39
  DEPLOY_FEE: () => DEPLOY_FEE,
37
40
  DEPLOY_KEYS: () => DEPLOY_KEYS,
38
41
  DOMAIN: () => DOMAIN,
39
- EPOCH_LEN: () => import_csd_codec5.EPOCH_LEN,
42
+ EPOCH_LEN: () => import_csd_codec7.EPOCH_LEN,
43
+ EVENTS_HASH_START: () => EVENTS_HASH_START,
40
44
  FCLAIM_KEYS: () => FCLAIM_KEYS,
41
45
  FCLAIM_MAX_EPOCH_AHEAD: () => FCLAIM_MAX_EPOCH_AHEAD,
42
46
  FCLAIM_MAX_HOLD_SPAN: () => FCLAIM_MAX_HOLD_SPAN,
@@ -46,10 +50,12 @@ __export(index_exports, {
46
50
  FEE_GATE_MARGIN_BLOCKS: () => FEE_GATE_MARGIN_BLOCKS,
47
51
  FILL_TIP_MARGIN: () => FILL_TIP_MARGIN,
48
52
  FINALIZE_TIP_MARGIN: () => FINALIZE_TIP_MARGIN,
53
+ FINAL_DEPTH: () => FINAL_DEPTH,
49
54
  GAP_NEEDED: () => GAP_NEEDED,
50
- HALVING_INTERVAL: () => import_csd_codec5.HALVING_INTERVAL,
55
+ GATE_HEIGHTS: () => GATE_HEIGHTS,
56
+ HALVING_INTERVAL: () => import_csd_codec7.HALVING_INTERVAL,
51
57
  HASH_RE: () => HASH_RE,
52
- INITIAL_REWARD: () => import_csd_codec5.INITIAL_REWARD,
58
+ INITIAL_REWARD: () => import_csd_codec7.INITIAL_REWARD,
53
59
  LEGACY_HOLD_SUNSET_HEIGHT: () => LEGACY_HOLD_SUNSET_HEIGHT,
54
60
  MAX_ACTIVE_CLAIMS: () => MAX_ACTIVE_CLAIMS,
55
61
  MAX_AMOUNT: () => MAX_AMOUNT,
@@ -59,8 +65,8 @@ __export(index_exports, {
59
65
  MAX_SCAN: () => MAX_SCAN,
60
66
  MAX_TOKEN_DECIMALS: () => MAX_TOKEN_DECIMALS,
61
67
  MINT_KEYS: () => MINT_KEYS,
62
- MIN_FEE_ATTEST: () => import_csd_codec5.MIN_FEE_ATTEST,
63
- MIN_FEE_PROPOSE: () => import_csd_codec5.MIN_FEE_PROPOSE,
68
+ MIN_FEE_ATTEST: () => import_csd_codec7.MIN_FEE_ATTEST,
69
+ MIN_FEE_PROPOSE: () => import_csd_codec7.MIN_FEE_PROPOSE,
64
70
  NAME_FEE_LEN3_V24: () => NAME_FEE_LEN3_V24,
65
71
  NAME_FEE_LEN4_V24: () => NAME_FEE_LEN4_V24,
66
72
  NAME_FEE_LONG_V24: () => NAME_FEE_LONG_V24,
@@ -79,11 +85,14 @@ __export(index_exports, {
79
85
  PKEY: () => PKEY,
80
86
  PROFILE_MAX_KEYS: () => PROFILE_MAX_KEYS,
81
87
  PROFILE_MAX_VALUE_BYTES: () => PROFILE_MAX_VALUE_BYTES,
88
+ REASON_CODES: () => REASON_CODES,
89
+ REASON_CODE_OUTCOME: () => REASON_CODE_OUTCOME,
82
90
  REBATE_BPS: () => REBATE_BPS,
83
91
  REBATE_FLAT: () => REBATE_FLAT,
84
92
  REG_COMMIT_MAX_BLOCKS: () => REG_COMMIT_MAX_BLOCKS,
85
93
  REG_FINALIZE_GRACE_BLOCKS: () => REG_FINALIZE_GRACE_BLOCKS,
86
94
  RESERVED_NAMES: () => RESERVED_NAMES,
95
+ RecordError: () => RecordError,
87
96
  SALT_RE: () => SALT_RE,
88
97
  SCAN_MARGIN: () => SCAN_MARGIN,
89
98
  SCORE_CANCEL: () => SCORE_CANCEL,
@@ -112,15 +121,18 @@ __export(index_exports, {
112
121
  V28_HEIGHT: () => V28_HEIGHT,
113
122
  V29_HEIGHT: () => V29_HEIGHT,
114
123
  ZERO_ADDR: () => ZERO_ADDR,
124
+ applyOrder: () => applyOrder,
115
125
  beforeActivation: () => beforeActivation,
116
126
  bid: () => bid,
117
127
  bindOfferTerms: () => bindOfferTerms,
118
128
  bindProvenOffer: () => bindProvenOffer,
119
- blockReward: () => import_csd_codec5.blockReward,
129
+ blockEvents: () => blockEvents,
130
+ blockMembers: () => blockMembers,
131
+ blockReward: () => import_csd_codec7.blockReward,
120
132
  buildFeeHeight: () => buildFeeHeight,
121
133
  buildRecord: () => buildRecord,
122
134
  burnedPayment: () => burnedPayment,
123
- canonicalJson: () => import_csd_codec5.canonicalJson,
135
+ canonicalJson: () => import_csd_codec7.canonicalJson,
124
136
  canonicalState: () => canonicalState,
125
137
  claimGraceOf: () => claimGraceOf,
126
138
  claimWindowAt: () => claimWindowAt,
@@ -128,7 +140,12 @@ __export(index_exports, {
128
140
  countOtherHoldsAtGrant: () => countOtherHoldsAtGrant,
129
141
  deploy: () => deploy,
130
142
  epochOf: () => import_csd_codec.epochOf,
143
+ eventId: () => eventId,
144
+ eventOfTx: () => eventOfTx,
145
+ eventsHash: () => eventsHash,
146
+ eventsHashStep: () => eventsHashStep,
131
147
  expiredClaimFee: () => expiredClaimFee,
148
+ explainRecord: () => explainRecord,
132
149
  fclaim: () => fclaim,
133
150
  fclaimEpochFor: () => fclaimEpochFor,
134
151
  fclaimHoldEnd: () => fclaimHoldEnd,
@@ -154,6 +171,7 @@ __export(index_exports, {
154
171
  nameRegFee: () => nameRegFee,
155
172
  nameRenew: () => nameRenew,
156
173
  nameSet: () => nameSet,
174
+ nameView: () => nameView,
157
175
  nameXfer: () => nameXfer,
158
176
  offer: () => offer,
159
177
  offerCancelAll: () => offerCancelAll,
@@ -162,7 +180,7 @@ __export(index_exports, {
162
180
  paidToFromOutputs: () => paidToFromOutputs,
163
181
  parseAmount: () => parseAmount,
164
182
  parseRecord: () => parseRecord,
165
- payloadHash: () => import_csd_codec5.payloadHash,
183
+ payloadHash: () => import_csd_codec7.payloadHash,
166
184
  pickPrimaryName: () => pickPrimaryName,
167
185
  previewFill: () => previewFill,
168
186
  primaryRankBefore: () => primaryRankBefore,
@@ -173,6 +191,8 @@ __export(index_exports, {
173
191
  requiredClaimDepth: () => requiredClaimDepth,
174
192
  requiredFillOutputs: () => requiredFillOutputs,
175
193
  resolve: () => resolve,
194
+ resolveNameIn: () => resolveNameIn,
195
+ stateHash: () => stateHash,
176
196
  tokenMeta: () => tokenMeta,
177
197
  tradeFee: () => tradeFee,
178
198
  transfer: () => transfer,
@@ -298,17 +318,26 @@ var isTokenWant = (w) => typeof w.ticker === "string";
298
318
 
299
319
  // src/records.ts
300
320
  var import_csd_codec2 = require("@inversealtruism/csd-codec");
301
- function parseAmount(s, opts = {}) {
302
- if (typeof s !== "string" || !AMOUNT_RE.test(s)) return null;
321
+ function amountOrCode(s, allowZero) {
322
+ if (typeof s !== "string" || !AMOUNT_RE.test(s)) return "RECORD_BAD_AMOUNT";
303
323
  const v = BigInt(s);
304
- if (v > MAX_AMOUNT) return null;
305
- if (v === 0n && !opts.allowZero) return null;
324
+ if (v > MAX_AMOUNT) return "RECORD_AMOUNT_TOO_LARGE";
325
+ if (v === 0n && !allowZero) return "RECORD_AMOUNT_ZERO";
306
326
  return v;
307
327
  }
328
+ function parseAmount(s, opts = {}) {
329
+ const v = amountOrCode(s, Boolean(opts.allowZero));
330
+ return typeof v === "bigint" ? v : null;
331
+ }
332
+ var amountFault = (s, allowZero = false) => {
333
+ const v = amountOrCode(s, allowZero);
334
+ return typeof v === "bigint" ? null : v;
335
+ };
308
336
  var isAddr = (a) => typeof a === "string" && ADDR_RE.test(a);
309
337
  var isTicker = (t) => typeof t === "string" && TICKER_RE.test(t);
310
338
  var isHash = (h) => typeof h === "string" && HASH_RE.test(h);
311
- var isName = (n) => typeof n === "string" && NAME_RE.test(n) && !RESERVED_NAMES.has(n);
339
+ var nameFault = (n) => typeof n !== "string" || !NAME_RE.test(n) ? "RECORD_BAD_NAME" : RESERVED_NAMES.has(n) ? "RECORD_NAME_RESERVED" : null;
340
+ var isName = (n) => nameFault(n) === null;
312
341
  function nameCommit(name, salt, owner) {
313
342
  return (0, import_csd_codec2.payloadHash)({ t: "cairnx:name:commit:v1", name, salt, owner: owner.toLowerCase() });
314
343
  }
@@ -334,172 +363,201 @@ var NFINALIZE_KEYS = /* @__PURE__ */ new Set(["v", "t", "name", "salt"]);
334
363
  var NPROFILE_KEYS = /* @__PURE__ */ new Set(["v", "t", "name", "p"]);
335
364
  var FCLAIM_KEYS = /* @__PURE__ */ new Set(["v", "t", "offer"]);
336
365
  function parseRecord(uri, payloadHashHex) {
337
- if (new TextEncoder().encode(uri).length > MAX_RECORD_BYTES) return null;
366
+ const r = recordOrCode(uri, payloadHashHex);
367
+ return typeof r === "string" ? null : r;
368
+ }
369
+ function explainRecord(uri, payloadHashHex) {
370
+ const r = recordOrCode(uri, payloadHashHex);
371
+ return typeof r === "string" ? { ok: false, code: r } : { ok: true, record: r };
372
+ }
373
+ function recordOrCode(uri, payloadHashHex) {
374
+ if (new TextEncoder().encode(uri).length > MAX_RECORD_BYTES) return "RECORD_TOO_LARGE";
338
375
  let obj;
339
376
  try {
340
377
  obj = JSON.parse(uri);
341
378
  } catch {
342
- return null;
379
+ return "RECORD_NOT_OBJECT";
380
+ }
381
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) return "RECORD_NOT_OBJECT";
382
+ try {
383
+ if ((0, import_csd_codec2.canonicalJson)(obj) !== uri) return "RECORD_NOT_CANONICAL";
384
+ } catch {
385
+ return "RECORD_NOT_CANONICAL";
343
386
  }
344
- if (typeof obj !== "object" || obj === null || Array.isArray(obj)) return null;
345
387
  try {
346
- if ((0, import_csd_codec2.canonicalJson)(obj) !== uri) return null;
347
- if ((0, import_csd_codec2.payloadHash)(obj).toLowerCase() !== payloadHashHex.toLowerCase()) return null;
388
+ if ((0, import_csd_codec2.payloadHash)(obj).toLowerCase() !== payloadHashHex.toLowerCase()) return "RECORD_HASH_MISMATCH";
348
389
  } catch {
349
- return null;
390
+ return "RECORD_HASH_MISMATCH";
350
391
  }
351
- if (!isWellFormedDeep(obj)) return null;
392
+ if (!isWellFormedDeep(obj)) return "RECORD_LONE_SURROGATE";
352
393
  const r = obj;
353
- if (r.v !== 1 || typeof r.t !== "string") return null;
394
+ if (r.v !== 1 || typeof r.t !== "string") return "RECORD_NOT_V1";
395
+ let fault;
354
396
  switch (r.t) {
355
397
  case "deploy": {
356
- if (!onlyKeys(r, DEPLOY_KEYS)) return null;
357
- if (!isTicker(r.ticker)) return null;
358
- if (r.name !== void 0 && (typeof r.name !== "string" || r.name.length > 32)) return null;
359
- if (typeof r.decimals !== "number" || !Number.isInteger(r.decimals) || r.decimals < 0 || r.decimals > MAX_TOKEN_DECIMALS) return null;
360
- if (parseAmount(r.supply) === null) return null;
361
- if (r.mint !== "open" && r.mint !== "issuer") return null;
362
- if (r.mint === "open" && parseAmount(r.mintLimit) === null) return null;
363
- if (r.mint === "issuer" && r.mintLimit !== void 0) return null;
398
+ if (!onlyKeys(r, DEPLOY_KEYS)) return "RECORD_EXTRA_KEY";
399
+ if (!isTicker(r.ticker)) return "RECORD_BAD_TICKER";
400
+ if (r.name !== void 0 && (typeof r.name !== "string" || r.name.length > 32)) return "RECORD_BAD_TEXT";
401
+ if (typeof r.decimals !== "number" || !Number.isInteger(r.decimals) || r.decimals < 0 || r.decimals > MAX_TOKEN_DECIMALS) return "RECORD_BAD_DECIMALS";
402
+ if (fault = amountFault(r.supply)) return fault;
403
+ if (r.mint !== "open" && r.mint !== "issuer") return "RECORD_BAD_MINT_MODE";
404
+ if (r.mint === "open" && (fault = amountFault(r.mintLimit))) return fault;
405
+ if (r.mint === "issuer" && r.mintLimit !== void 0) return "RECORD_BAD_SHAPE";
364
406
  return r;
365
407
  }
366
408
  case "mint": {
367
- if (!onlyKeys(r, MINT_KEYS)) return null;
368
- if (!isTicker(r.ticker)) return null;
369
- if (r.amount !== void 0 && parseAmount(r.amount) === null) return null;
409
+ if (!onlyKeys(r, MINT_KEYS)) return "RECORD_EXTRA_KEY";
410
+ if (!isTicker(r.ticker)) return "RECORD_BAD_TICKER";
411
+ if (r.amount !== void 0 && (fault = amountFault(r.amount))) return fault;
370
412
  return r;
371
413
  }
372
414
  case "transfer": {
373
- if (!onlyKeys(r, TRANSFER_KEYS)) return null;
374
- if (!isTicker(r.ticker) || !isAddr(r.to) || parseAmount(r.amount) === null) return null;
375
- if (r.memo !== void 0 && (typeof r.memo !== "string" || r.memo.length > 64)) return null;
376
- if (r.ts !== void 0 && (typeof r.ts !== "number" || !Number.isSafeInteger(r.ts))) return null;
415
+ if (!onlyKeys(r, TRANSFER_KEYS)) return "RECORD_EXTRA_KEY";
416
+ if (!isTicker(r.ticker)) return "RECORD_BAD_TICKER";
417
+ if (!isAddr(r.to)) return "RECORD_BAD_ADDRESS";
418
+ if (fault = amountFault(r.amount)) return fault;
419
+ if (r.memo !== void 0 && (typeof r.memo !== "string" || r.memo.length > 64)) return "RECORD_BAD_TEXT";
420
+ if (r.ts !== void 0 && (typeof r.ts !== "number" || !Number.isSafeInteger(r.ts))) return "RECORD_BAD_TS";
377
421
  return r;
378
422
  }
379
423
  case "offer": {
380
- if (!onlyKeys(r, OFFER_KEYS)) return null;
424
+ if (!onlyKeys(r, OFFER_KEYS)) return "RECORD_EXTRA_KEY";
381
425
  const g = r.give;
382
426
  const w = r.want;
383
- if (!g || !w || typeof g !== "object" || Array.isArray(g) || typeof w !== "object" || Array.isArray(w)) return null;
427
+ if (!g || !w || typeof g !== "object" || Array.isArray(g) || typeof w !== "object" || Array.isArray(w)) return "RECORD_BAD_SHAPE";
384
428
  const gKeys = Object.keys(g).sort().join(",");
385
429
  if (gKeys === "amount,ticker") {
386
- if (!isTicker(g.ticker) || parseAmount(g.amount) === null) return null;
430
+ if (!isTicker(g.ticker)) return "RECORD_BAD_TICKER";
431
+ if (fault = amountFault(g.amount)) return fault;
387
432
  } else if (gKeys === "name") {
388
- if (!isName(g.name)) return null;
389
- } else return null;
433
+ if (fault = nameFault(g.name)) return fault;
434
+ } else return "RECORD_BAD_SHAPE";
390
435
  const wKeys = Object.keys(w).filter((k) => k !== "payto").sort().join(",");
391
436
  if (wKeys === "value") {
392
- if (parseAmount(w.value, { allowZero: true }) === null) return null;
437
+ if (fault = amountFault(w.value, true)) return fault;
393
438
  } else if (wKeys === "amount,ticker") {
394
- if (!isTicker(w.ticker) || parseAmount(w.amount, { allowZero: true }) === null) return null;
395
- if (gKeys === "amount,ticker" && w.ticker === g.ticker) return null;
396
- if (r.min !== void 0) return null;
397
- } else return null;
398
- if (w.payto !== void 0 && !isAddr(w.payto)) return null;
439
+ if (!isTicker(w.ticker)) return "RECORD_BAD_TICKER";
440
+ if (fault = amountFault(w.amount, true)) return fault;
441
+ if (gKeys === "amount,ticker" && w.ticker === g.ticker) return "RECORD_SAME_TOKEN";
442
+ if (r.min !== void 0) return "RECORD_BAD_SHAPE";
443
+ } else return "RECORD_BAD_SHAPE";
444
+ if (w.payto !== void 0 && !isAddr(w.payto)) return "RECORD_BAD_ADDRESS";
399
445
  if (r.min !== void 0) {
400
- if (gKeys !== "amount,ticker" || wKeys !== "value") return null;
401
- const mn = parseAmount(r.min);
402
- if (mn === null || mn > parseAmount(w.value, { allowZero: true })) return null;
446
+ if (gKeys !== "amount,ticker" || wKeys !== "value") return "RECORD_BAD_SHAPE";
447
+ if (fault = amountFault(r.min)) return fault;
448
+ if (parseAmount(r.min) > parseAmount(w.value, { allowZero: true })) return "RECORD_MIN_ABOVE_WANT";
403
449
  }
404
- if (r.bid !== void 0 && !isHash(r.bid)) return null;
405
- if (r.taker !== void 0 && !isAddr(r.taker)) return null;
406
- if (r.memo !== void 0 && (typeof r.memo !== "string" || r.memo.length > 64)) return null;
407
- if (r.ts !== void 0 && (typeof r.ts !== "number" || !Number.isSafeInteger(r.ts))) return null;
450
+ if (r.bid !== void 0 && !isHash(r.bid)) return "RECORD_BAD_HASH";
451
+ if (r.taker !== void 0 && !isAddr(r.taker)) return "RECORD_BAD_ADDRESS";
452
+ if (r.memo !== void 0 && (typeof r.memo !== "string" || r.memo.length > 64)) return "RECORD_BAD_TEXT";
453
+ if (r.ts !== void 0 && (typeof r.ts !== "number" || !Number.isSafeInteger(r.ts))) return "RECORD_BAD_TS";
408
454
  return r;
409
455
  }
410
456
  case "ocancel": {
411
- if (r.ticker !== void 0 && r.name !== void 0) return null;
412
- if (r.ticker !== void 0 && !isTicker(r.ticker)) return null;
413
- if (r.name !== void 0 && !isName(r.name)) return null;
457
+ if (r.ticker !== void 0 && r.name !== void 0) return "RECORD_BAD_SHAPE";
458
+ if (r.ticker !== void 0 && !isTicker(r.ticker)) return "RECORD_BAD_TICKER";
459
+ if (r.name !== void 0 && (fault = nameFault(r.name))) return fault;
414
460
  const n = Object.keys(r).length;
415
- if (n !== 2 + (r.ticker !== void 0 ? 1 : 0) + (r.name !== void 0 ? 1 : 0)) return null;
461
+ if (n !== 2 + (r.ticker !== void 0 ? 1 : 0) + (r.name !== void 0 ? 1 : 0)) return "RECORD_EXTRA_KEY";
416
462
  return r;
417
463
  }
418
464
  case "bid": {
419
- if (!onlyKeys(r, BID_KEYS)) return null;
465
+ if (!onlyKeys(r, BID_KEYS)) return "RECORD_EXTRA_KEY";
420
466
  const w = r.want;
421
467
  const g = r.give;
422
- if (!w || !g || typeof w !== "object" || Array.isArray(w) || typeof g !== "object" || Array.isArray(g)) return null;
468
+ if (!w || !g || typeof w !== "object" || Array.isArray(w) || typeof g !== "object" || Array.isArray(g)) return "RECORD_BAD_SHAPE";
423
469
  const wKeys = Object.keys(w).sort().join(",");
424
470
  if (wKeys === "amount,ticker") {
425
- if (!isTicker(w.ticker) || parseAmount(w.amount) === null) return null;
471
+ if (!isTicker(w.ticker)) return "RECORD_BAD_TICKER";
472
+ if (fault = amountFault(w.amount)) return fault;
426
473
  } else if (wKeys === "name") {
427
- if (!isName(w.name)) return null;
428
- } else return null;
429
- if (Object.keys(g).sort().join(",") !== "value" || parseAmount(g.value) === null) return null;
430
- if (r.memo !== void 0 && (typeof r.memo !== "string" || r.memo.length > 64)) return null;
431
- if (r.ts !== void 0 && (typeof r.ts !== "number" || !Number.isSafeInteger(r.ts))) return null;
474
+ if (fault = nameFault(w.name)) return fault;
475
+ } else return "RECORD_BAD_SHAPE";
476
+ if (Object.keys(g).sort().join(",") !== "value") return "RECORD_BAD_SHAPE";
477
+ if (fault = amountFault(g.value)) return fault;
478
+ if (r.memo !== void 0 && (typeof r.memo !== "string" || r.memo.length > 64)) return "RECORD_BAD_TEXT";
479
+ if (r.ts !== void 0 && (typeof r.ts !== "number" || !Number.isSafeInteger(r.ts))) return "RECORD_BAD_TS";
432
480
  return r;
433
481
  }
434
482
  // ── names (v1.1) ──
435
483
  case "ncommit": {
436
- if (!isHash(r.commit)) return null;
437
- if (Object.keys(r).length !== 3) return null;
484
+ if (!isHash(r.commit)) return "RECORD_BAD_HASH";
485
+ if (Object.keys(r).length !== 3) return "RECORD_EXTRA_KEY";
438
486
  return r;
439
487
  }
440
488
  case "name": {
441
- if (!onlyKeys(r, NAME_KEYS)) return null;
442
- if (!isName(r.name)) return null;
443
- if (r.salt !== void 0 && (typeof r.salt !== "string" || !SALT_RE.test(r.salt))) return null;
489
+ if (!onlyKeys(r, NAME_KEYS)) return "RECORD_EXTRA_KEY";
490
+ if (fault = nameFault(r.name)) return fault;
491
+ if (r.salt !== void 0 && (typeof r.salt !== "string" || !SALT_RE.test(r.salt))) return "RECORD_BAD_SALT";
444
492
  return r;
445
493
  }
446
494
  case "nfinalize": {
447
- if (!onlyKeys(r, NFINALIZE_KEYS)) return null;
448
- if (!isName(r.name)) return null;
449
- if (typeof r.salt !== "string" || !SALT_RE.test(r.salt)) return null;
495
+ if (!onlyKeys(r, NFINALIZE_KEYS)) return "RECORD_EXTRA_KEY";
496
+ if (fault = nameFault(r.name)) return fault;
497
+ if (typeof r.salt !== "string" || !SALT_RE.test(r.salt)) return "RECORD_BAD_SALT";
450
498
  return r;
451
499
  }
452
500
  case "nxfer": {
453
- if (!isName(r.name) || !isAddr(r.to)) return null;
454
- if (Object.keys(r).length !== 4) return null;
501
+ if (fault = nameFault(r.name)) return fault;
502
+ if (!isAddr(r.to)) return "RECORD_BAD_ADDRESS";
503
+ if (Object.keys(r).length !== 4) return "RECORD_EXTRA_KEY";
455
504
  return r;
456
505
  }
457
506
  case "nset": {
458
- if (!isName(r.name) || !isAddr(r.addr)) return null;
459
- if (Object.keys(r).length !== 4) return null;
507
+ if (fault = nameFault(r.name)) return fault;
508
+ if (!isAddr(r.addr)) return "RECORD_BAD_ADDRESS";
509
+ if (Object.keys(r).length !== 4) return "RECORD_EXTRA_KEY";
460
510
  return r;
461
511
  }
462
512
  // ── v1.5 ──
463
513
  case "nrenew": {
464
- if (!isName(r.name)) return null;
465
- if (Object.keys(r).length !== 3) return null;
514
+ if (fault = nameFault(r.name)) return fault;
515
+ if (Object.keys(r).length !== 3) return "RECORD_EXTRA_KEY";
466
516
  return r;
467
517
  }
468
518
  case "nprofile": {
469
- if (!onlyKeys(r, NPROFILE_KEYS)) return null;
470
- if (!isName(r.name)) return null;
519
+ if (!onlyKeys(r, NPROFILE_KEYS)) return "RECORD_EXTRA_KEY";
520
+ if (fault = nameFault(r.name)) return fault;
471
521
  const p = r.p;
472
- if (!p || typeof p !== "object" || Array.isArray(p)) return null;
522
+ if (!p || typeof p !== "object" || Array.isArray(p)) return "RECORD_BAD_SHAPE";
473
523
  const keys = Object.keys(p);
474
- if (keys.length > PROFILE_MAX_KEYS) return null;
524
+ if (keys.length > PROFILE_MAX_KEYS) return "RECORD_PROFILE_TOO_MANY_KEYS";
475
525
  for (const k of keys) {
476
- if (!PKEY.test(k)) return null;
526
+ if (!PKEY.test(k)) return "RECORD_PROFILE_BAD_KEY";
477
527
  const val = p[k];
478
- if (typeof val !== "string") return null;
479
- if (new TextEncoder().encode(val).length > PROFILE_MAX_VALUE_BYTES) return null;
528
+ if (typeof val !== "string") return "RECORD_PROFILE_BAD_VALUE";
529
+ if (new TextEncoder().encode(val).length > PROFILE_MAX_VALUE_BYTES) return "RECORD_PROFILE_VALUE_TOO_LONG";
480
530
  }
481
531
  return r;
482
532
  }
483
533
  case "tmeta": {
484
- if (!isTicker(r.ticker)) return null;
485
- if (typeof r.hash !== "string" || !HASH_RE.test(r.hash)) return null;
486
- if (Object.keys(r).length !== 4) return null;
534
+ if (!isTicker(r.ticker)) return "RECORD_BAD_TICKER";
535
+ if (typeof r.hash !== "string" || !HASH_RE.test(r.hash)) return "RECORD_BAD_HASH";
536
+ if (Object.keys(r).length !== 4) return "RECORD_EXTRA_KEY";
487
537
  return r;
488
538
  }
489
539
  case "fclaim": {
490
- if (!onlyKeys(r, FCLAIM_KEYS)) return null;
491
- if (!isHash(r.offer)) return null;
540
+ if (!onlyKeys(r, FCLAIM_KEYS)) return "RECORD_EXTRA_KEY";
541
+ if (!isHash(r.offer)) return "RECORD_BAD_HASH";
492
542
  return r;
493
543
  }
494
544
  default:
495
- return null;
545
+ return "RECORD_UNKNOWN_TYPE";
496
546
  }
497
547
  }
548
+ var RecordError = class extends Error {
549
+ code;
550
+ constructor(code) {
551
+ super(`record does not validate against CONVENTION.md (${code})`);
552
+ this.name = "RecordError";
553
+ this.code = code;
554
+ }
555
+ };
498
556
  function buildRecord(record) {
499
557
  const uri = (0, import_csd_codec2.canonicalJson)(record);
500
558
  const ph = (0, import_csd_codec2.payloadHash)(record);
501
- const back = parseRecord(uri, ph);
502
- if (back === null) throw new Error("record does not validate against CONVENTION.md");
559
+ const back = explainRecord(uri, ph);
560
+ if (!back.ok) throw new RecordError(back.code);
503
561
  return { record, uri, payloadHash: ph };
504
562
  }
505
563
  var deploy = (r) => buildRecord({ v: 1, t: "deploy", ...r });
@@ -522,36 +580,16 @@ var fclaim = (r) => buildRecord({ v: 1, t: "fclaim", ...r });
522
580
  function ptAmt(v) {
523
581
  return typeof v === "string" && AMOUNT_RE.test(v) ? BigInt(v) : 0n;
524
582
  }
583
+ var tokenMove = (leg, ticker, from, to, amount) => ({ leg, ticker, from, to, amount: amount.toString() });
525
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;
526
585
  var claimGrace = (o) => o.claimUntilHeight !== void 0 ? claimGraceOf(o.claimUntilHeight, o.claimTxid) : 0;
527
586
  var claimHeld = (o, height) => o.claimedBy !== void 0 && o.claimUntilHeight !== void 0 && height < o.claimUntilHeight + claimGrace(o);
528
- function createContext() {
587
+ function createContext(store) {
529
588
  const tokens = /* @__PURE__ */ new Map();
530
589
  const balances = /* @__PURE__ */ new Map();
531
- const names = /* @__PURE__ */ new Map();
532
590
  const commits = /* @__PURE__ */ new Map();
533
- const recaptures = /* @__PURE__ */ new Map();
534
- const offers = /* @__PURE__ */ new Map();
535
591
  const offerLock = /* @__PURE__ */ new Map();
536
- const bids = /* @__PURE__ */ new Map();
537
- const openOffers = /* @__PURE__ */ new Set();
538
- const openBids = /* @__PURE__ */ new Set();
539
- const pendingNames = /* @__PURE__ */ new Set();
540
- const setOfferStatus = (o, status) => {
541
- o.status = status;
542
- if (status === "open") openOffers.add(o.id);
543
- else openOffers.delete(o.id);
544
- };
545
- const setBidStatus = (b, status) => {
546
- b.status = status;
547
- if (status === "open") openBids.add(b.id);
548
- else openBids.delete(b.id);
549
- };
550
- const putName = (nm, n) => {
551
- names.set(nm, n);
552
- if (n.pending) pendingNames.add(nm);
553
- else pendingNames.delete(nm);
554
- };
592
+ const { names, recaptures, offers, bids, setOfferStatus, setBidStatus, putName } = store;
555
593
  const fclaims = /* @__PURE__ */ new Map();
556
594
  const log = [];
557
595
  const bal = (ticker, addr) => {
@@ -567,7 +605,6 @@ function createContext() {
567
605
  }
568
606
  return b;
569
607
  };
570
- const note = (e, id, kind, ok, why) => log.push({ height: e.height, pos: e.pos, id, kind, ok, ...why ? { note: why } : {} });
571
608
  const releaseGive = (o) => {
572
609
  if (isNameGive(o.give)) {
573
610
  const n = names.get(o.give.name);
@@ -579,66 +616,31 @@ function createContext() {
579
616
  b.available += amt;
580
617
  }
581
618
  };
582
- const sweepExpired = (height) => {
583
- const ep = (0, import_csd_codec.epochOf)(height);
584
- for (const id of [...openOffers]) {
585
- const o = offers.get(id);
586
- if (!o || o.status !== "open") {
587
- openOffers.delete(id);
588
- continue;
589
- }
590
- if (ep > effExpiry(o, height)) {
591
- releaseGive(o);
592
- setOfferStatus(o, "expired");
593
- }
594
- }
595
- for (const id of [...openBids]) {
596
- const b = bids.get(id);
597
- if (!b || b.status !== "open") {
598
- openBids.delete(id);
599
- continue;
600
- }
601
- if (ep > effExpiry(b, height)) setBidStatus(b, "expired");
602
- }
603
- for (const nm of [...pendingNames]) {
604
- const n = names.get(nm);
605
- if (!n || !n.pending) {
606
- pendingNames.delete(nm);
607
- continue;
608
- }
609
- if (n.finalizeBy !== void 0 && height > n.finalizeBy) {
610
- names.delete(nm);
611
- pendingNames.delete(nm);
612
- }
613
- }
614
- for (const nm of [...recaptures.keys()]) {
615
- const r = recaptures.get(nm);
616
- if (height > r.finalizeBy) recaptures.delete(nm);
617
- }
618
- };
619
+ const sweepExpired = (height) => store.sweep(height, releaseGive);
619
620
  const markBidDone = (o, buyer) => {
620
621
  if (!o.bid) return;
621
622
  const b = bids.get(o.bid);
622
623
  if (b && b.status === "open" && b.bidder === buyer) setBidStatus(b, "done");
623
624
  };
624
625
  const voidOpenNameOffers = (name, height) => {
625
- for (const o of offers.values()) if (o.status === "open" && isNameGive(o.give) && o.give.name === name) {
626
- if (height >= V28_HEIGHT && o.claimTxid !== void 0 && claimHeld(o, height)) continue;
626
+ for (const o of store.voidTargets(name, height)) {
627
627
  releaseGive(o);
628
628
  setOfferStatus(o, "cancelled");
629
629
  }
630
630
  };
631
- const liveHoldCount = (who, height) => {
632
- let liveN = 0;
633
- for (const x of offers.values()) if (x.claimedBy === who && claimHeld(x, height) && (height < V29_HEIGHT || x.status === "open")) liveN++;
634
- return liveN;
635
- };
636
631
  const releaseGiveLock = (o, who, amt) => {
637
632
  const t = o.give.ticker;
638
633
  bal(t, o.seller).locked -= amt;
639
634
  bal(t, who).available += amt;
640
635
  offerLock.delete(o.id);
636
+ return tokenMove("fill", t, o.seller, who, amt);
637
+ };
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
641
  };
642
+ const applied = (e, id, kind, code, why, moves) => entry(e, id, kind, true, code, why, moves);
643
+ const refused = (e, id, kind, code, why) => entry(e, id, kind, false, code, why);
642
644
  return {
643
645
  tokens,
644
646
  balances,
@@ -648,21 +650,19 @@ function createContext() {
648
650
  offers,
649
651
  offerLock,
650
652
  bids,
651
- openOffers,
652
- openBids,
653
- pendingNames,
654
653
  fclaims,
655
654
  log,
655
+ store,
656
656
  setOfferStatus,
657
657
  setBidStatus,
658
658
  putName,
659
659
  bal,
660
- note,
660
+ applied,
661
+ refused,
661
662
  releaseGive,
662
663
  sweepExpired,
663
664
  markBidDone,
664
665
  voidOpenNameOffers,
665
- liveHoldCount,
666
666
  releaseGiveLock,
667
667
  feesPaid: 0n,
668
668
  // v1.4 fill-before-cancel: at V14_HEIGHT+ a cancel/ocancel's EFFECT is deferred to the block
@@ -678,13 +678,13 @@ function createContext() {
678
678
  // src/resolve/attest.ts
679
679
  var openFillReject = (o, height, who, targetId) => {
680
680
  if (!(height >= V13_HEIGHT && !o.taker)) return void 0;
681
- if (height < V17_HEIGHT) return "v1.3: open CSD-quoted fills disabled (offer must be taker-bound)";
682
- if (height >= V28_HEIGHT && o.claimTxid !== void 0 && targetId === o.id) return "v2.8: fill the fclaim txid, not the offer";
683
- if (!(claimHeld(o, height) && who === o.claimedBy)) return "v1.7: open offer \u2014 claim it first (no live claim by you)";
681
+ if (height < V17_HEIGHT) return { code: "FILL_OPEN_LANE_CLOSED", note: "v1.3: open CSD-quoted fills disabled (offer must be taker-bound)" };
682
+ if (height >= V28_HEIGHT && o.claimTxid !== void 0 && targetId === o.id) return { code: "FILL_WRONG_TARGET", note: "v2.8: fill the fclaim txid, not the offer" };
683
+ if (!(claimHeld(o, height) && who === o.claimedBy)) return { code: "FILL_NO_LIVE_CLAIM", note: "v1.7: open offer \u2014 claim it first (no live claim by you)" };
684
684
  return void 0;
685
685
  };
686
- var deliverNameToBuyer = (n, who, ev) => {
687
- n.owner = who;
686
+ var deliverNameToBuyer = (c, name, n, who, ev) => {
687
+ c.store.setNameOwner(name, n, who);
688
688
  n.locked = false;
689
689
  n.addr = void 0;
690
690
  n.profile = void 0;
@@ -697,7 +697,7 @@ var deliverNameToBuyer = (n, who, ev) => {
697
697
  }
698
698
  };
699
699
  function applyAttest(c, ev) {
700
- const { offers, fclaims, bids, note, setBidStatus } = c;
700
+ const { offers, fclaims, bids, applied, refused, setBidStatus } = c;
701
701
  const who = ev.attester.toLowerCase();
702
702
  let o = offers.get(ev.proposalId);
703
703
  if (!o && ev.height >= V28_HEIGHT && ev.score === SCORE_FILL) {
@@ -709,21 +709,21 @@ function applyAttest(c, ev) {
709
709
  }
710
710
  if (!o) {
711
711
  if (ev.height >= V28_HEIGHT && ev.score === SCORE_FILL && fclaims.has(ev.proposalId)) {
712
- note(ev, ev.txid, "fill", false, "fclaim not current (denied or superseded): no delivery, denied-fclaim fill");
712
+ refused(ev, ev.txid, "fill", "FILL_FCLAIM_NOT_CURRENT", "fclaim not current (denied or superseded): no delivery, denied-fclaim fill");
713
713
  return;
714
714
  }
715
715
  const b = bids.get(ev.proposalId);
716
716
  if (b && ev.score === SCORE_CANCEL) {
717
717
  if (who !== b.bidder) {
718
- note(ev, ev.txid, "bidcancel", false, "only bidder may cancel");
718
+ refused(ev, ev.txid, "bidcancel", "BID_NOT_BIDDER", "only bidder may cancel");
719
719
  return;
720
720
  }
721
721
  if (b.status !== "open") {
722
- note(ev, ev.txid, "bidcancel", false, `bid ${b.status}`);
722
+ refused(ev, ev.txid, "bidcancel", "BID_NOT_OPEN", `bid ${b.status}`);
723
723
  return;
724
724
  }
725
725
  setBidStatus(b, "cancelled");
726
- note(ev, ev.txid, "bidcancel", true);
726
+ applied(ev, ev.txid, "bidcancel", "BID_CANCELLED");
727
727
  }
728
728
  return;
729
729
  }
@@ -734,95 +734,99 @@ function applyAttest(c, ev) {
734
734
  else if (ev.height >= V17_HEIGHT && ev.score === SCORE_CLAIM) applyLegacyClaim(c, ev, o, who);
735
735
  }
736
736
  function applyCancel(c, ev, o, who) {
737
- const { note, releaseGive, setOfferStatus } = c;
737
+ const { applied, refused, releaseGive, setOfferStatus } = c;
738
738
  if (who !== o.seller) {
739
- note(ev, ev.txid, "cancel", false, "only seller may cancel");
739
+ refused(ev, ev.txid, "cancel", "OFFER_NOT_SELLER", "only seller may cancel");
740
740
  return;
741
741
  }
742
742
  if (o.status !== "open") {
743
- note(ev, ev.txid, "cancel", false, `offer ${o.status}`);
743
+ refused(ev, ev.txid, "cancel", "OFFER_NOT_OPEN", `offer ${o.status}`);
744
744
  return;
745
745
  }
746
746
  if (o.taker !== void 0 && o.height >= V28_HEIGHT) {
747
- note(ev, ev.txid, "cancel", false, "v2.8: taker-bound offers are firm quotes (uncancellable)");
747
+ refused(ev, ev.txid, "cancel", "OFFER_FIRM_QUOTE", "v2.8: taker-bound offers are firm quotes (uncancellable)");
748
748
  return;
749
749
  }
750
750
  if (ev.height >= V14_HEIGHT) {
751
751
  c.pendingCancels.push(() => {
752
752
  if (ev.height >= V28_HEIGHT && o.claimTxid !== void 0 && claimHeld(o, ev.height)) {
753
- note(ev, ev.txid, "cancel", false, "v2.8: frozen (fclaim hold live)");
753
+ refused(ev, ev.txid, "cancel", "OFFER_CANCEL_HOLD_LIVE", "v2.8: frozen (fclaim hold live)");
754
754
  return;
755
755
  }
756
756
  if (o.status === "open") {
757
757
  releaseGive(o);
758
758
  setOfferStatus(o, "cancelled");
759
- note(ev, ev.txid, "cancel", true);
760
- } else note(ev, ev.txid, "cancel", false, "superseded by same-block fill (v1.4)");
759
+ applied(ev, ev.txid, "cancel", "OFFER_CANCELLED");
760
+ } else refused(ev, ev.txid, "cancel", "OFFER_CLOSED_BEFORE_CANCEL", "superseded by same-block fill (v1.4)");
761
761
  });
762
762
  } else {
763
763
  releaseGive(o);
764
764
  setOfferStatus(o, "cancelled");
765
- note(ev, ev.txid, "cancel", true);
765
+ applied(ev, ev.txid, "cancel", "OFFER_CANCELLED");
766
766
  }
767
767
  }
768
768
  function applyTokenFill(c, ev, o, who) {
769
- const { tokens, names, offerLock, bal, note, setOfferStatus, markBidDone, releaseGiveLock } = c;
769
+ const { tokens, names, offerLock, bal, applied, refused, setOfferStatus, markBidDone, releaseGiveLock } = c;
770
770
  if (o.status !== "open") {
771
- note(ev, ev.txid, "fill", false, `offer ${o.status}`);
771
+ refused(ev, ev.txid, "fill", "OFFER_NOT_OPEN", `offer ${o.status}`);
772
772
  return;
773
773
  }
774
774
  if (o.taker && who !== o.taker) {
775
- note(ev, ev.txid, "fill", false, "taker-bound offer");
775
+ refused(ev, ev.txid, "fill", "FILL_NOT_TAKER", "taker-bound offer");
776
776
  return;
777
777
  }
778
778
  if (ev.confidence !== CONF_TOKEN_FILL) {
779
- note(ev, ev.txid, "fill", false, "token fill requires confidence marker");
779
+ refused(ev, ev.txid, "fill", "FILL_NO_TOKEN_MARKER", "token fill requires confidence marker");
780
780
  return;
781
781
  }
782
782
  if (!tokens.has(o.want.ticker)) {
783
- note(ev, ev.txid, "fill", false, "want ticker does not exist");
783
+ refused(ev, ev.txid, "fill", "TOKEN_UNKNOWN", "want ticker does not exist");
784
784
  return;
785
785
  }
786
786
  const amt = BigInt(o.want.amount);
787
787
  const fee = o.feeBps ? tradeFee(amt, o.feeBps) : 0n;
788
788
  const buyer = bal(o.want.ticker, who);
789
789
  if (buyer.available < amt + fee) {
790
- note(ev, ev.txid, "fill", false, "insufficient want-token balance");
790
+ refused(ev, ev.txid, "fill", "TOKEN_BALANCE_LOW", "insufficient want-token balance");
791
791
  return;
792
792
  }
793
793
  const giveName = isNameGive(o.give) ? names.get(o.give.name) : void 0;
794
794
  if (isNameGive(o.give) && !giveName) {
795
- note(ev, ev.txid, "fill", false, "name vanished (consensus violation)");
795
+ refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "name vanished (consensus violation)");
796
796
  return;
797
797
  }
798
798
  const giveLock = isNameGive(o.give) ? void 0 : offerLock.get(o.id);
799
799
  if (!isNameGive(o.give) && giveLock === void 0) {
800
- note(ev, ev.txid, "fill", false, "offer lock missing");
800
+ refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "offer lock missing");
801
801
  return;
802
802
  }
803
803
  buyer.available -= amt + fee;
804
804
  bal(o.want.ticker, o.want.payto).available += amt;
805
- if (fee > 0n) bal(o.want.ticker, TREASURY_ADDR).available += fee;
806
- if (isNameGive(o.give)) deliverNameToBuyer(giveName, who, ev);
807
- else releaseGiveLock(o, who, giveLock);
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
+ }
810
+ if (isNameGive(o.give)) deliverNameToBuyer(c, o.give.name, giveName, who, ev);
811
+ else moves.push(releaseGiveLock(o, who, giveLock));
808
812
  setOfferStatus(o, "filled");
809
813
  o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: amt.toString(), fee: fee.toString() };
810
814
  markBidDone(o, who);
811
- note(ev, ev.txid, "fill", true);
815
+ applied(ev, ev.txid, "fill", "FILL_APPLIED", void 0, moves);
812
816
  }
813
817
  function applyPartialFill(c, ev, o, who) {
814
- const { offerLock, bal, note, setOfferStatus, markBidDone } = c;
818
+ const { offerLock, bal, applied, refused, setOfferStatus, markBidDone } = c;
815
819
  if (o.status !== "open") {
816
- note(ev, ev.txid, "fill", false, `offer ${o.status}`);
820
+ refused(ev, ev.txid, "fill", "OFFER_NOT_OPEN", `offer ${o.status}`);
817
821
  return;
818
822
  }
819
823
  if (o.taker && who !== o.taker) {
820
- note(ev, ev.txid, "fill", false, "taker-bound offer");
824
+ refused(ev, ev.txid, "fill", "FILL_NOT_TAKER", "taker-bound offer");
821
825
  return;
822
826
  }
823
827
  const blk = openFillReject(o, ev.height, who, ev.proposalId);
824
828
  if (blk) {
825
- note(ev, ev.txid, "fill", false, blk);
829
+ refused(ev, ev.txid, "fill", blk.code, blk.note);
826
830
  return;
827
831
  }
828
832
  const pt = ev.paidTo ?? {};
@@ -833,13 +837,13 @@ function applyPartialFill(c, ev, o, who) {
833
837
  const minV = BigInt(o.min);
834
838
  const effMin = remaining < minV ? remaining : minV;
835
839
  if (X < effMin) {
836
- note(ev, ev.txid, "fill", false, "payment below offer min");
840
+ refused(ev, ev.txid, "fill", "FILL_BELOW_MIN", "payment below offer min");
837
841
  return;
838
842
  }
839
843
  const x = X < remaining ? X : remaining;
840
844
  const fee = o.feeBps ? tradeFee(x, o.feeBps) : 0n;
841
845
  if (ptAmt(pt[TREASURY_ADDR]) < fee) {
842
- note(ev, ev.txid, "fill", false, "protocol fee unpaid");
846
+ refused(ev, ev.txid, "fill", "TREASURY_FEE_UNPAID", "protocol fee unpaid");
843
847
  return;
844
848
  }
845
849
  const giveTotal = BigInt(o.give.amount);
@@ -848,16 +852,17 @@ function applyPartialFill(c, ev, o, who) {
848
852
  const newDelivered = giveTotal * newPaid / want;
849
853
  const out = newDelivered - deliveredSoFar;
850
854
  if (out === 0n) {
851
- note(ev, ev.txid, "fill", false, "fill too small to deliver any tokens");
855
+ refused(ev, ev.txid, "fill", "FILL_ZERO_DELIVERY", "fill too small to deliver any tokens");
852
856
  return;
853
857
  }
854
858
  const lock = offerLock.get(o.id);
855
859
  if (lock === void 0) {
856
- note(ev, ev.txid, "fill", false, "offer lock missing");
860
+ refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "offer lock missing");
857
861
  return;
858
862
  }
859
863
  bal(o.give.ticker, o.seller).locked -= out;
860
864
  bal(o.give.ticker, who).available += out;
865
+ const moves = [tokenMove("fill", o.give.ticker, o.seller, who, out)];
861
866
  offerLock.set(o.id, lock - out);
862
867
  o.paid = newPaid.toString();
863
868
  o.delivered = newDelivered.toString();
@@ -870,21 +875,21 @@ function applyPartialFill(c, ev, o, who) {
870
875
  offerLock.delete(o.id);
871
876
  markBidDone(o, who);
872
877
  }
873
- note(ev, ev.txid, "fill", true, `partial ${x}/${want}`);
878
+ applied(ev, ev.txid, "fill", "FILL_PARTIAL", `partial ${x}/${want}`, moves);
874
879
  }
875
880
  function applyFill(c, ev, o, who) {
876
- const { names, offerLock, note, setOfferStatus, markBidDone, releaseGiveLock } = c;
881
+ const { names, offerLock, applied, refused, setOfferStatus, markBidDone, releaseGiveLock } = c;
877
882
  if (o.status !== "open") {
878
- note(ev, ev.txid, "fill", false, `offer ${o.status}`);
883
+ refused(ev, ev.txid, "fill", "OFFER_NOT_OPEN", `offer ${o.status}`);
879
884
  return;
880
885
  }
881
886
  if (o.taker && who !== o.taker) {
882
- note(ev, ev.txid, "fill", false, "taker-bound offer");
887
+ refused(ev, ev.txid, "fill", "FILL_NOT_TAKER", "taker-bound offer");
883
888
  return;
884
889
  }
885
890
  const blk = openFillReject(o, ev.height, who, ev.proposalId);
886
891
  if (blk) {
887
- note(ev, ev.txid, "fill", false, blk);
892
+ refused(ev, ev.txid, "fill", blk.code, blk.note);
888
893
  return;
889
894
  }
890
895
  const pt = ev.paidTo ?? {};
@@ -899,68 +904,492 @@ function applyFill(c, ev, o, who) {
899
904
  if (rebate > 0n) addNeed(o.seller, rebate);
900
905
  let unpaid;
901
906
  for (const [addr, amt] of need) if (ptAmt(pt[addr]) < amt) {
902
- unpaid = addr === TREASURY_ADDR ? "protocol fee unpaid" : rebate > 0n && addr === o.seller ? "maker rebate unpaid (v1.6)" : "payment below want.value";
907
+ unpaid = addr === TREASURY_ADDR ? { code: "TREASURY_FEE_UNPAID", note: "protocol fee unpaid" } : rebate > 0n && addr === o.seller ? { code: "FILL_REBATE_UNPAID", note: "maker rebate unpaid (v1.6)" } : { code: "FILL_UNDERPAID", note: "payment below want.value" };
903
908
  break;
904
909
  }
905
910
  if (unpaid) {
906
- note(ev, ev.txid, "fill", false, unpaid);
911
+ refused(ev, ev.txid, "fill", unpaid.code, unpaid.note);
907
912
  return;
908
913
  }
909
914
  const paid = ptAmt(pt[o.want.payto]);
915
+ const moves = [];
910
916
  if (isNameGive(o.give)) {
911
917
  const n = names.get(o.give.name);
912
918
  if (!n) {
913
- note(ev, ev.txid, "fill", false, "name vanished (consensus violation)");
919
+ refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "name vanished (consensus violation)");
914
920
  return;
915
921
  }
916
- deliverNameToBuyer(n, who, ev);
922
+ deliverNameToBuyer(c, o.give.name, n, who, ev);
917
923
  } else {
918
924
  const amt = offerLock.get(o.id);
919
925
  if (amt === void 0) {
920
- note(ev, ev.txid, "fill", false, "offer lock missing");
926
+ refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "offer lock missing");
921
927
  return;
922
928
  }
923
- releaseGiveLock(o, who, amt);
929
+ moves.push(releaseGiveLock(o, who, amt));
924
930
  }
925
931
  c.feesPaid += fee;
926
932
  setOfferStatus(o, "filled");
927
933
  o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: paid.toString(), fee: fee.toString() };
928
934
  markBidDone(o, who);
929
- note(ev, ev.txid, "fill", true);
935
+ applied(ev, ev.txid, "fill", "FILL_APPLIED", void 0, moves);
930
936
  }
931
937
  function applyLegacyClaim(c, ev, o, who) {
932
- const { note, liveHoldCount } = c;
938
+ const { applied, refused, store } = c;
933
939
  if (ev.height >= V28_HEIGHT) {
934
- note(ev, ev.txid, "claim", false, "v2.8: claims are fclaim proposals now");
940
+ refused(ev, ev.txid, "claim", "CLAIM_LEGACY_SUNSET", "v2.8: claims are fclaim proposals now");
935
941
  return;
936
942
  }
937
943
  if (o.status !== "open") {
938
- note(ev, ev.txid, "claim", false, `offer ${o.status}`);
944
+ refused(ev, ev.txid, "claim", "OFFER_NOT_OPEN", `offer ${o.status}`);
939
945
  return;
940
946
  }
941
947
  if (o.taker) {
942
- note(ev, ev.txid, "claim", false, "taker-bound offer needs no claim");
948
+ refused(ev, ev.txid, "claim", "CLAIM_TAKER_BOUND", "taker-bound offer needs no claim");
943
949
  return;
944
950
  }
945
951
  if (isTokenWant(o.want)) {
946
- note(ev, ev.txid, "claim", false, "claims are for CSD-priced offers (token offers are no-op-safe)");
952
+ refused(ev, ev.txid, "claim", "CLAIM_TOKEN_PRICED", "claims are for CSD-priced offers (token offers are no-op-safe)");
947
953
  return;
948
954
  }
949
955
  if (claimHeld(o, ev.height)) {
950
- note(ev, ev.txid, "claim", false, "offer already claimed (hold live)");
956
+ refused(ev, ev.txid, "claim", "CLAIM_HOLD_LIVE", "offer already claimed (hold live)");
951
957
  return;
952
958
  }
953
959
  if (o.claimedBy === who && o.claimUntilHeight !== void 0 && ev.height < o.claimUntilHeight + claimGrace(o) + CLAIM_COOLDOWN_BLOCKS) {
954
- note(ev, ev.txid, "claim", false, "claim cooldown (you just held this offer)");
960
+ refused(ev, ev.txid, "claim", "CLAIM_COOLDOWN", "claim cooldown (you just held this offer)");
955
961
  return;
956
962
  }
957
- if (liveHoldCount(who, ev.height) >= MAX_ACTIVE_CLAIMS) {
958
- note(ev, ev.txid, "claim", false, `max ${MAX_ACTIVE_CLAIMS} live claims per address`);
963
+ if (store.liveHoldCount(who, ev.height) >= MAX_ACTIVE_CLAIMS) {
964
+ refused(ev, ev.txid, "claim", "CAP_LIVE_HOLDS", `max ${MAX_ACTIVE_CLAIMS} live claims per address`);
959
965
  return;
960
966
  }
961
- o.claimedBy = who;
962
- o.claimUntilHeight = ev.height + claimWindowAt(ev.height);
963
- note(ev, ev.txid, "claim", true);
967
+ store.setClaim(o, who, ev.height + claimWindowAt(ev.height));
968
+ applied(ev, ev.txid, "claim", "CLAIM_GRANTED");
969
+ }
970
+
971
+ // src/resolve/minqueue.ts
972
+ var MinQueue = class {
973
+ keys = [];
974
+ seqs = [];
975
+ ids = [];
976
+ pushed = 0;
977
+ get size() {
978
+ return this.ids.length;
979
+ }
980
+ /** Adds an entry. A NaN key is not stored: no comparison with NaN is true, so such an item is never due. */
981
+ push(key, id) {
982
+ if (key !== key) return;
983
+ let i = this.ids.length;
984
+ this.keys.push(key);
985
+ this.seqs.push(++this.pushed);
986
+ this.ids.push(id);
987
+ while (i > 0) {
988
+ const p = i - 1 >> 1;
989
+ if (!this.less(i, p)) break;
990
+ this.swap(i, p);
991
+ i = p;
992
+ }
993
+ }
994
+ /** Removes every entry whose key is below `limit` and appends its id to `out`, smallest key first. */
995
+ popBelow(limit, out) {
996
+ while (this.ids.length > 0 && this.keys[0] < limit) {
997
+ out.push(this.ids[0]);
998
+ this.swap(0, this.ids.length - 1);
999
+ this.keys.pop();
1000
+ this.seqs.pop();
1001
+ this.ids.pop();
1002
+ let i = 0;
1003
+ for (; ; ) {
1004
+ const l = 2 * i + 1, r = l + 1;
1005
+ let m = i;
1006
+ if (l < this.ids.length && this.less(l, m)) m = l;
1007
+ if (r < this.ids.length && this.less(r, m)) m = r;
1008
+ if (m === i) break;
1009
+ this.swap(i, m);
1010
+ i = m;
1011
+ }
1012
+ }
1013
+ }
1014
+ /** Every stored (key, id), in no particular order: for the replay's check mode. */
1015
+ *entries() {
1016
+ for (let i = 0; i < this.ids.length; i++) yield [this.keys[i], this.ids[i]];
1017
+ }
1018
+ less(i, j) {
1019
+ const a = this.keys[i], b = this.keys[j];
1020
+ return a < b || a === b && this.seqs[i] < this.seqs[j];
1021
+ }
1022
+ swap(i, j) {
1023
+ const k = this.keys[i], s = this.seqs[i], d = this.ids[i];
1024
+ this.keys[i] = this.keys[j];
1025
+ this.seqs[i] = this.seqs[j];
1026
+ this.ids[i] = this.ids[j];
1027
+ this.keys[j] = k;
1028
+ this.seqs[j] = s;
1029
+ this.ids[j] = d;
1030
+ }
1031
+ };
1032
+
1033
+ // src/resolve/store.ts
1034
+ function createStore(opts = {}) {
1035
+ const check = opts.check === true;
1036
+ const checkEvery = Math.max(1, Math.floor(opts.checkEvery ?? 1));
1037
+ const stats = opts.stats ?? { visits: 0 };
1038
+ const offers = /* @__PURE__ */ new Map();
1039
+ const bids = /* @__PURE__ */ new Map();
1040
+ const names = /* @__PURE__ */ new Map();
1041
+ const recaptures = /* @__PURE__ */ new Map();
1042
+ const openOffers = /* @__PURE__ */ new Set();
1043
+ const openBids = /* @__PURE__ */ new Set();
1044
+ const pendingNames = /* @__PURE__ */ new Set();
1045
+ let stamp = 0;
1046
+ const openOfferAt = /* @__PURE__ */ new Map(), openBidAt = /* @__PURE__ */ new Map();
1047
+ const pendingAt = /* @__PURE__ */ new Map(), recaptureAt = /* @__PURE__ */ new Map();
1048
+ const offerAt = /* @__PURE__ */ new Map();
1049
+ const offerQ = new MinQueue(), bidQ = new MinQueue(), nameQ = new MinQueue(), recaptureQ = new MinQueue();
1050
+ let maxSweep = -Infinity;
1051
+ const pendingBy = /* @__PURE__ */ new Map(), recaptureBy = /* @__PURE__ */ new Map();
1052
+ const holdsBy = /* @__PURE__ */ new Map();
1053
+ let maxHoldRead = -Infinity;
1054
+ const bySeller = /* @__PURE__ */ new Map(), bySellerAsset = /* @__PURE__ */ new Map(), byName = /* @__PURE__ */ new Map();
1055
+ const assetKey = (seller, g) => `${seller}\0${isNameGive(g) ? `n\0${g.name}` : `t\0${g.ticker}`}`;
1056
+ const addTo = (m, k, v) => {
1057
+ let s = m.get(k);
1058
+ if (!s) {
1059
+ s = /* @__PURE__ */ new Set();
1060
+ m.set(k, s);
1061
+ }
1062
+ s.add(v);
1063
+ };
1064
+ const regimeHeight = () => maxSweep >= V21_HEIGHT ? V21_HEIGHT : V21_HEIGHT - 1;
1065
+ const addOffer = (o) => {
1066
+ if (!offers.has(o.id)) offerAt.set(o.id, ++stamp);
1067
+ offers.set(o.id, o);
1068
+ if (!openOffers.has(o.id)) {
1069
+ openOffers.add(o.id);
1070
+ openOfferAt.set(o.id, ++stamp);
1071
+ }
1072
+ offerQ.push(effExpiry(o, regimeHeight()), o.id);
1073
+ if (!(o.taker !== void 0 && o.height >= V28_HEIGHT)) {
1074
+ addTo(bySeller, o.seller, o.id);
1075
+ addTo(bySellerAsset, assetKey(o.seller, o.give), o.id);
1076
+ }
1077
+ if (isNameGive(o.give)) addTo(byName, o.give.name, o.id);
1078
+ };
1079
+ const setClaim = (o, who, untilHeight, txid) => {
1080
+ const m = o;
1081
+ m.claimedBy = who;
1082
+ m.claimUntilHeight = untilHeight;
1083
+ if (txid !== void 0) m.claimTxid = txid;
1084
+ addTo(holdsBy, who, o.id);
1085
+ };
1086
+ const setOfferStatus = (o, status) => {
1087
+ o.status = status;
1088
+ openOffers.delete(o.id);
1089
+ };
1090
+ const addBid = (b) => {
1091
+ bids.set(b.id, b);
1092
+ if (!openBids.has(b.id)) {
1093
+ openBids.add(b.id);
1094
+ openBidAt.set(b.id, ++stamp);
1095
+ }
1096
+ bidQ.push(effExpiry(b, regimeHeight()), b.id);
1097
+ };
1098
+ const setBidStatus = (b, status) => {
1099
+ b.status = status;
1100
+ openBids.delete(b.id);
1101
+ };
1102
+ const putName = (nm, n) => {
1103
+ names.set(nm, n);
1104
+ if (n.pending) {
1105
+ if (!pendingNames.has(nm)) {
1106
+ pendingNames.add(nm);
1107
+ pendingAt.set(nm, ++stamp);
1108
+ }
1109
+ if (n.finalizeBy !== void 0) nameQ.push(n.finalizeBy, nm);
1110
+ addTo(pendingBy, n.owner, nm);
1111
+ } else pendingNames.delete(nm);
1112
+ };
1113
+ const setNameOwner = (nm, n, owner) => {
1114
+ n.owner = owner;
1115
+ if (n.pending) addTo(pendingBy, owner, nm);
1116
+ };
1117
+ const finalizeName = (nm, n) => {
1118
+ delete n.pending;
1119
+ delete n.finalizeBy;
1120
+ pendingNames.delete(nm);
1121
+ };
1122
+ const putRecapture = (nm, r) => {
1123
+ if (!recaptures.has(nm)) recaptureAt.set(nm, ++stamp);
1124
+ recaptures.set(nm, r);
1125
+ recaptureQ.push(r.finalizeBy, nm);
1126
+ addTo(recaptureBy, r.owner, nm);
1127
+ };
1128
+ const deleteRecapture = (nm) => {
1129
+ recaptures.delete(nm);
1130
+ };
1131
+ const walkSweep = (height, expireOffer) => {
1132
+ const ep = (0, import_csd_codec.epochOf)(height);
1133
+ stats.visits += openOffers.size + openBids.size + pendingNames.size + recaptures.size;
1134
+ for (const id of [...openOffers]) {
1135
+ const o = offers.get(id);
1136
+ if (!o || o.status !== "open") {
1137
+ openOffers.delete(id);
1138
+ continue;
1139
+ }
1140
+ if (ep > effExpiry(o, height)) {
1141
+ expireOffer(o);
1142
+ setOfferStatus(o, "expired");
1143
+ }
1144
+ }
1145
+ for (const id of [...openBids]) {
1146
+ const b = bids.get(id);
1147
+ if (!b || b.status !== "open") {
1148
+ openBids.delete(id);
1149
+ continue;
1150
+ }
1151
+ if (ep > effExpiry(b, height)) setBidStatus(b, "expired");
1152
+ }
1153
+ for (const nm of [...pendingNames]) {
1154
+ const n = names.get(nm);
1155
+ if (!n || !n.pending) {
1156
+ pendingNames.delete(nm);
1157
+ continue;
1158
+ }
1159
+ if (n.finalizeBy !== void 0 && height > n.finalizeBy) {
1160
+ names.delete(nm);
1161
+ pendingNames.delete(nm);
1162
+ }
1163
+ }
1164
+ for (const nm of [...recaptures.keys()]) {
1165
+ const r = recaptures.get(nm);
1166
+ if (height > r.finalizeBy) recaptures.delete(nm);
1167
+ }
1168
+ };
1169
+ const offerDue = (o, height) => !!o && o.status === "open" && (0, import_csd_codec.epochOf)(height) > effExpiry(o, height);
1170
+ const bidDue = (b, height) => !!b && b.status === "open" && (0, import_csd_codec.epochOf)(height) > effExpiry(b, height);
1171
+ const nameDue = (n, height) => !!n && !!n.pending && n.finalizeBy !== void 0 && height > n.finalizeBy;
1172
+ const walkDue = (height) => ({
1173
+ offers: [...openOffers].filter((id) => offerDue(offers.get(id), height)),
1174
+ bids: [...openBids].filter((id) => bidDue(bids.get(id), height)),
1175
+ names: [...pendingNames].filter((nm) => nameDue(names.get(nm), height)),
1176
+ recaptures: [...recaptures].filter(([, r]) => height > r.finalizeBy).map(([nm]) => nm)
1177
+ });
1178
+ const walkPending = (who, except, height) => {
1179
+ let k = 0;
1180
+ for (const [nm, n] of names) if (n.pending && n.owner === who && nm !== except && n.finalizeBy !== void 0 && height <= n.finalizeBy) k++;
1181
+ return k;
1182
+ };
1183
+ const walkRecaptures = (who, except, height) => {
1184
+ let k = 0;
1185
+ for (const [nm, r] of recaptures) if (r.owner === who && nm !== except && height <= r.finalizeBy) k++;
1186
+ return k;
1187
+ };
1188
+ const holdLive = (x, who, height) => x.claimedBy === who && claimHeld(x, height) && (height < V29_HEIGHT || x.status === "open");
1189
+ const walkHolds = (who, height) => {
1190
+ let k = 0;
1191
+ for (const x of offers.values()) if (holdLive(x, who, height)) k++;
1192
+ return k;
1193
+ };
1194
+ const ocancelMatch = (o, who, ticker, name) => o.status === "open" && o.seller === who && !(o.taker !== void 0 && o.height >= V28_HEIGHT) && !(ticker !== void 0 && !(!isNameGive(o.give) && o.give.ticker === ticker)) && !(name !== void 0 && !(isNameGive(o.give) && o.give.name === name));
1195
+ const voidMatch = (o, name, height) => o.status === "open" && isNameGive(o.give) && o.give.name === name && !(height >= V28_HEIGHT && o.claimTxid !== void 0 && claimHeld(o, height));
1196
+ const same = (what, index, walk) => {
1197
+ if (JSON.stringify(index) !== JSON.stringify(walk)) throw new Error(`replay index check: ${what}: index ${JSON.stringify(index)}, walk ${JSON.stringify(walk)}`);
1198
+ };
1199
+ const popDue = (q, limit, at, isDue) => {
1200
+ const popped = [];
1201
+ q.popBelow(limit, popped);
1202
+ stats.visits += popped.length;
1203
+ return [...new Set(popped)].filter(isDue).sort((a, b) => at.get(a) - at.get(b));
1204
+ };
1205
+ const sweep = (height, expireOffer) => {
1206
+ if (!(height >= maxSweep)) {
1207
+ walkSweep(height, expireOffer);
1208
+ return;
1209
+ }
1210
+ if (!(maxSweep >= V21_HEIGHT) && height >= V21_HEIGHT) {
1211
+ stats.visits += openOffers.size + openBids.size;
1212
+ for (const id of openOffers) {
1213
+ const o = offers.get(id);
1214
+ if (o && o.status === "open" && !(o.height >= V22_HEIGHT)) offerQ.push(effExpiry(o, V21_HEIGHT), id);
1215
+ }
1216
+ for (const id of openBids) {
1217
+ const b = bids.get(id);
1218
+ if (b && b.status === "open" && !(b.height >= V22_HEIGHT)) bidQ.push(effExpiry(b, V21_HEIGHT), id);
1219
+ }
1220
+ }
1221
+ maxSweep = height;
1222
+ const ep = (0, import_csd_codec.epochOf)(height);
1223
+ const want = check ? walkDue(height) : void 0;
1224
+ const dueOffers = popDue(offerQ, ep, openOfferAt, (id) => openOffers.has(id) && offerDue(offers.get(id), height));
1225
+ const dueBids = popDue(bidQ, ep, openBidAt, (id) => openBids.has(id) && bidDue(bids.get(id), height));
1226
+ const dueNames = popDue(nameQ, height, pendingAt, (nm) => pendingNames.has(nm) && nameDue(names.get(nm), height));
1227
+ const dueRecaptures = popDue(recaptureQ, height, recaptureAt, (nm) => {
1228
+ const r = recaptures.get(nm);
1229
+ return !!r && height > r.finalizeBy;
1230
+ });
1231
+ if (want) {
1232
+ same(`expired offers at ${height}`, dueOffers, want.offers);
1233
+ same(`expired bids at ${height}`, dueBids, want.bids);
1234
+ same(`expired reservations at ${height}`, dueNames, want.names);
1235
+ same(`expired recaptures at ${height}`, dueRecaptures, want.recaptures);
1236
+ }
1237
+ for (const id of dueOffers) {
1238
+ const o = offers.get(id);
1239
+ expireOffer(o);
1240
+ setOfferStatus(o, "expired");
1241
+ }
1242
+ for (const id of dueBids) setBidStatus(bids.get(id), "expired");
1243
+ for (const nm of dueNames) {
1244
+ names.delete(nm);
1245
+ pendingNames.delete(nm);
1246
+ }
1247
+ for (const nm of dueRecaptures) recaptures.delete(nm);
1248
+ };
1249
+ const pendingCount = (who, except, height) => {
1250
+ let k = 0;
1251
+ const set = pendingBy.get(who);
1252
+ if (set) for (const nm of set) {
1253
+ stats.visits++;
1254
+ const n = names.get(nm);
1255
+ if (!n || !n.pending || n.owner !== who) {
1256
+ set.delete(nm);
1257
+ continue;
1258
+ }
1259
+ if (nm !== except && n.finalizeBy !== void 0 && height <= n.finalizeBy) k++;
1260
+ }
1261
+ if (check) same(`reservations of ${who} at ${height}`, k, walkPending(who, except, height));
1262
+ return k;
1263
+ };
1264
+ const recaptureCount = (who, except, height) => {
1265
+ let k = 0;
1266
+ const set = recaptureBy.get(who);
1267
+ if (set) for (const nm of set) {
1268
+ stats.visits++;
1269
+ const r = recaptures.get(nm);
1270
+ if (!r || r.owner !== who) {
1271
+ set.delete(nm);
1272
+ continue;
1273
+ }
1274
+ if (nm !== except && height <= r.finalizeBy) k++;
1275
+ }
1276
+ if (check) same(`recaptures of ${who} at ${height}`, k, walkRecaptures(who, except, height));
1277
+ return k;
1278
+ };
1279
+ const liveHoldCount = (who, height) => {
1280
+ if (!(height >= maxHoldRead)) {
1281
+ stats.visits += offers.size;
1282
+ return walkHolds(who, height);
1283
+ }
1284
+ maxHoldRead = height;
1285
+ let k = 0;
1286
+ const set = holdsBy.get(who);
1287
+ if (set) for (const id of set) {
1288
+ stats.visits++;
1289
+ const x = offers.get(id);
1290
+ if (x && holdLive(x, who, height)) k++;
1291
+ else set.delete(id);
1292
+ }
1293
+ if (check) same(`live holds of ${who} at ${height}`, k, walkHolds(who, height));
1294
+ return k;
1295
+ };
1296
+ const byInsertion = (a, b) => offerAt.get(a.id) - offerAt.get(b.id);
1297
+ const ocancelTargets = (who, ticker, name) => {
1298
+ const set = ticker !== void 0 ? bySellerAsset.get(`${who}\0t\0${ticker}`) : name !== void 0 ? bySellerAsset.get(`${who}\0n\0${name}`) : bySeller.get(who);
1299
+ const out = [];
1300
+ if (set) for (const id of set) {
1301
+ stats.visits++;
1302
+ const o = offers.get(id);
1303
+ if (!o || o.status !== "open" || o.seller !== who) {
1304
+ set.delete(id);
1305
+ continue;
1306
+ }
1307
+ if (ocancelMatch(o, who, ticker, name)) out.push(o);
1308
+ }
1309
+ out.sort(byInsertion);
1310
+ if (check) same(`bulk cancel by ${who}`, out.map((o) => o.id), [...offers.values()].filter((o) => ocancelMatch(o, who, ticker, name)).map((o) => o.id));
1311
+ return out;
1312
+ };
1313
+ const voidTargets = (name, height) => {
1314
+ const set = byName.get(name);
1315
+ const out = [];
1316
+ if (set) for (const id of set) {
1317
+ stats.visits++;
1318
+ const o = offers.get(id);
1319
+ if (!o || o.status !== "open" || !isNameGive(o.give) || o.give.name !== name) {
1320
+ set.delete(id);
1321
+ continue;
1322
+ }
1323
+ if (voidMatch(o, name, height)) out.push(o);
1324
+ }
1325
+ out.sort(byInsertion);
1326
+ if (check) same(`voids of ${name} at ${height}`, out.map((o) => o.id), [...offers.values()].filter((o) => voidMatch(o, name, height)).map((o) => o.id));
1327
+ return out;
1328
+ };
1329
+ let checked = 0;
1330
+ const verify = (height, force = false) => {
1331
+ if (!check || !force && ++checked % checkEvery !== 0) return;
1332
+ const fail3 = (what) => {
1333
+ throw new Error(`replay index check: ${what}`);
1334
+ };
1335
+ const queued = (q) => new Set([...q.entries()].map(([k, id]) => `${k}\0${id}`));
1336
+ const oq = queued(offerQ), bq = queued(bidQ), nq = queued(nameQ), rq = queued(recaptureQ);
1337
+ for (const id of openOffers) {
1338
+ const o = offers.get(id);
1339
+ if (!o || o.status !== "open") fail3(`openOffers names ${id}, which is not open`);
1340
+ const k = effExpiry(o, regimeHeight());
1341
+ if (k === k && !oq.has(`${k}\0${id}`)) fail3(`open offer ${id} has no queue entry at ${k}`);
1342
+ }
1343
+ for (const id of openBids) {
1344
+ const b = bids.get(id);
1345
+ if (!b || b.status !== "open") fail3(`openBids names ${id}, which is not open`);
1346
+ const k = effExpiry(b, regimeHeight());
1347
+ if (k === k && !bq.has(`${k}\0${id}`)) fail3(`open bid ${id} has no queue entry at ${k}`);
1348
+ }
1349
+ for (const nm of pendingNames) {
1350
+ const n = names.get(nm);
1351
+ if (!n || !n.pending) fail3(`pendingNames names ${nm}, which is not pending`);
1352
+ }
1353
+ for (const [nm, n] of names) {
1354
+ if (!n.pending) continue;
1355
+ if (!pendingNames.has(nm)) fail3(`pending ${nm} is not in pendingNames`);
1356
+ if (!pendingBy.get(n.owner)?.has(nm)) fail3(`pending ${nm} is not a candidate of its owner ${n.owner}`);
1357
+ if (n.finalizeBy !== void 0 && !nq.has(`${n.finalizeBy}\0${nm}`)) fail3(`pending ${nm} has no queue entry at ${n.finalizeBy}`);
1358
+ }
1359
+ for (const [nm, r] of recaptures) {
1360
+ if (!recaptureBy.get(r.owner)?.has(nm)) fail3(`recapture ${nm} is not a candidate of its owner ${r.owner}`);
1361
+ if (!rq.has(`${r.finalizeBy}\0${nm}`)) fail3(`recapture ${nm} has no queue entry at ${r.finalizeBy}`);
1362
+ }
1363
+ for (const o of offers.values()) {
1364
+ if (o.status === "open" && !(o.taker !== void 0 && o.height >= V28_HEIGHT) && !(bySeller.get(o.seller)?.has(o.id) && bySellerAsset.get(assetKey(o.seller, o.give))?.has(o.id))) fail3(`open offer ${o.id} is not a candidate of its seller`);
1365
+ if (o.status === "open" && isNameGive(o.give) && !byName.get(o.give.name)?.has(o.id)) fail3(`open name offer ${o.id} is not a candidate of ${o.give.name}`);
1366
+ if (height >= maxHoldRead && o.claimedBy !== void 0 && holdLive(o, o.claimedBy, height) && !holdsBy.get(o.claimedBy)?.has(o.id)) fail3(`live hold on ${o.id} is not a candidate of ${o.claimedBy}`);
1367
+ }
1368
+ };
1369
+ return {
1370
+ offers,
1371
+ bids,
1372
+ names,
1373
+ recaptures,
1374
+ addOffer,
1375
+ setOfferStatus,
1376
+ setClaim,
1377
+ addBid,
1378
+ setBidStatus,
1379
+ putName,
1380
+ setNameOwner,
1381
+ finalizeName,
1382
+ putRecapture,
1383
+ deleteRecapture,
1384
+ sweep,
1385
+ pendingCount,
1386
+ recaptureCount,
1387
+ liveHoldCount,
1388
+ ocancelTargets,
1389
+ voidTargets,
1390
+ verify,
1391
+ stats
1392
+ };
964
1393
  }
965
1394
 
966
1395
  // src/resolve/names.ts
@@ -970,24 +1399,24 @@ var lapsed = (n, ep) => ep > paidThrough(n) + NAME_GRACE_EPOCHS;
970
1399
  var inGrace = (n, ep) => ep > paidThrough(n) && !lapsed(n, ep);
971
1400
  var earlierAnchor = (effHeight, pos, id, inc) => effHeight < inc.effHeight || effHeight === inc.effHeight && (pos < inc.pos || pos === inc.pos && id < inc.id);
972
1401
  function applyNcommit(c, ev, rec) {
973
- const { commits, note } = c;
1402
+ const { commits, applied, refused } = c;
974
1403
  const v11 = ev.height >= V11_HEIGHT;
975
1404
  if (!v11) {
976
- note(ev, ev.id, "ncommit", false, "before v1.1 activation");
1405
+ refused(ev, ev.id, "ncommit", "GATE_NOT_ACTIVE", "before v1.1 activation");
977
1406
  return;
978
1407
  }
979
1408
  const prev = commits.get(rec.commit);
980
1409
  if (prev === void 0 || ev.height < prev) commits.set(rec.commit, ev.height);
981
- note(ev, ev.id, "ncommit", true);
1410
+ applied(ev, ev.id, "ncommit", "NAME_COMMITTED");
982
1411
  }
983
1412
  function applyName(c, ev, rec, who, feeToTreasury) {
984
- const { commits, names, recaptures, note, putName, voidOpenNameOffers } = c;
1413
+ const { commits, names, recaptures, applied, refused, putName, voidOpenNameOffers, store } = c;
985
1414
  const v11 = ev.height >= V11_HEIGHT;
986
1415
  const v15 = ev.height >= V15_HEIGHT;
987
1416
  const v25 = ev.height >= V25_HEIGHT;
988
1417
  const v26 = ev.height >= V26_HEIGHT;
989
1418
  if (!v11) {
990
- note(ev, ev.id, "name", false, "before v1.1 activation");
1419
+ refused(ev, ev.id, "name", "GATE_NOT_ACTIVE", "before v1.1 activation");
991
1420
  return;
992
1421
  }
993
1422
  const regWindow = v25 || v26 ? REG_COMMIT_MAX_BLOCKS : COMMIT_MAX_BLOCKS;
@@ -996,7 +1425,7 @@ function applyName(c, ev, rec, who, feeToTreasury) {
996
1425
  const ch = nameCommit(rec.name, rec.salt, who);
997
1426
  const cH = commits.get(ch);
998
1427
  if (cH === void 0 || cH >= ev.height || ev.height - cH > regWindow) {
999
- note(ev, ev.id, "name", false, "no valid in-window commit for this reveal");
1428
+ refused(ev, ev.id, "name", "NAME_NO_COMMIT", "no valid in-window commit for this reveal");
1000
1429
  return;
1001
1430
  }
1002
1431
  effHeight = cH;
@@ -1007,62 +1436,61 @@ function applyName(c, ev, rec, who, feeToTreasury) {
1007
1436
  if (curActive && !curActive.pending && v15 && lapsed(curActive, epClaim)) {
1008
1437
  if (v26) {
1009
1438
  if (rec.salt === void 0) {
1010
- note(ev, ev.id, "name", false, "v2.6: recapture requires a commit-reveal (salt)");
1439
+ refused(ev, ev.id, "name", "NAME_SALT_REQUIRED", "v2.6: recapture requires a commit-reveal (salt)");
1011
1440
  return;
1012
1441
  }
1013
1442
  const cr = recaptures.get(rec.name);
1014
1443
  const crActive = cr && ev.height > cr.finalizeBy ? void 0 : cr;
1015
1444
  const better2 = !crActive || earlierAnchor(effHeight, ev.pos, ev.id, crActive);
1016
1445
  if (!better2) {
1017
- note(ev, ev.id, "name", false, "recapture already reserved (earlier anchor wins)");
1446
+ refused(ev, ev.id, "name", "NAME_TAKEN_EARLIER", "recapture already reserved (earlier anchor wins)");
1018
1447
  return;
1019
1448
  }
1020
- let myR = 0;
1021
- for (const [nm, r] of recaptures) if (r.owner === who && nm !== rec.name && ev.height <= r.finalizeBy) myR++;
1022
- if (myR >= MAX_PENDING_REG) {
1023
- note(ev, ev.id, "name", false, "too many pending recaptures (max reached)");
1449
+ if (store.recaptureCount(who, rec.name, ev.height) >= MAX_PENDING_REG) {
1450
+ refused(ev, ev.id, "name", "CAP_PENDING_RECAPTURES", "too many pending recaptures (max reached)");
1024
1451
  return;
1025
1452
  }
1026
- recaptures.set(rec.name, { owner: who, effHeight, pos: ev.pos, id: ev.id, height: ev.height, finalizeBy: effHeight + REG_COMMIT_MAX_BLOCKS + REG_FINALIZE_GRACE_BLOCKS });
1027
- note(ev, ev.id, "name", true, crActive ? "recapture reserved (displaced prior reservation)" : "recapture reserved (pending finalize)");
1453
+ store.putRecapture(rec.name, { owner: who, effHeight, pos: ev.pos, id: ev.id, height: ev.height, finalizeBy: effHeight + REG_COMMIT_MAX_BLOCKS + REG_FINALIZE_GRACE_BLOCKS });
1454
+ if (crActive) applied(ev, ev.id, "name", "NAME_RECAPTURE_RESERVED_DISPLACED", "recapture reserved (displaced prior reservation)");
1455
+ else applied(ev, ev.id, "name", "NAME_RECAPTURE_RESERVED", "recapture reserved (pending finalize)");
1028
1456
  return;
1029
1457
  }
1030
1458
  const fee = expiredClaimFee(rec.name, epClaim - (paidThrough(curActive) + NAME_GRACE_EPOCHS), ev.height);
1031
1459
  if (feeToTreasury < fee) {
1032
- note(ev, ev.id, "name", false, "lapsed-name claim fee unpaid (decaying premium)");
1460
+ refused(ev, ev.id, "name", "TREASURY_FEE_UNPAID", "lapsed-name claim fee unpaid (decaying premium)");
1033
1461
  return;
1034
1462
  }
1035
1463
  voidOpenNameOffers(rec.name, ev.height);
1036
1464
  putName(rec.name, { owner: who, effHeight, pos: ev.pos, id: ev.id, height: ev.height, locked: false, viaFill: true, paidThroughEpoch: epClaim + NAME_TERM_EPOCHS });
1037
1465
  c.feesPaid += fee;
1038
- note(ev, ev.id, "name", true, "lapsed lease re-claimed (premium)");
1466
+ applied(ev, ev.id, "name", "NAME_RECLAIMED", "lapsed lease re-claimed (premium)");
1039
1467
  return;
1040
1468
  }
1041
1469
  if (v25) {
1042
1470
  if (rec.salt === void 0) {
1043
- note(ev, ev.id, "name", false, "v2.5: registration requires a commit-reveal (salt)");
1471
+ refused(ev, ev.id, "name", "NAME_SALT_REQUIRED", "v2.5: registration requires a commit-reveal (salt)");
1044
1472
  return;
1045
1473
  }
1046
1474
  const better2 = !curActive || !curActive.viaFill && earlierAnchor(effHeight, ev.pos, ev.id, curActive);
1047
1475
  if (!better2) {
1048
- note(ev, ev.id, "name", false, curActive?.viaFill ? "name taken (purchased \u2014 not displaceable)" : "name taken (earlier anchor wins)");
1476
+ if (curActive?.viaFill) refused(ev, ev.id, "name", "NAME_TAKEN_PURCHASED", "name taken (purchased \u2014 not displaceable)");
1477
+ else refused(ev, ev.id, "name", "NAME_TAKEN_EARLIER", "name taken (earlier anchor wins)");
1049
1478
  return;
1050
1479
  }
1051
- let myPending = 0;
1052
- for (const [nm, n] of names) if (n.pending && n.owner === who && nm !== rec.name && n.finalizeBy !== void 0 && ev.height <= n.finalizeBy) myPending++;
1053
- if (myPending >= MAX_PENDING_REG) {
1054
- note(ev, ev.id, "name", false, "too many pending reservations (max reached)");
1480
+ if (store.pendingCount(who, rec.name, ev.height) >= MAX_PENDING_REG) {
1481
+ refused(ev, ev.id, "name", "CAP_PENDING_RESERVATIONS", "too many pending reservations (max reached)");
1055
1482
  return;
1056
1483
  }
1057
1484
  if (curActive) {
1058
1485
  voidOpenNameOffers(rec.name, ev.height);
1059
1486
  }
1060
1487
  putName(rec.name, { owner: who, effHeight, pos: ev.pos, id: ev.id, height: ev.height, locked: false, pending: true, finalizeBy: effHeight + REG_COMMIT_MAX_BLOCKS + REG_FINALIZE_GRACE_BLOCKS });
1061
- note(ev, ev.id, "name", true, curActive ? "reserved (displaced prior reservation)" : "reserved (pending finalize)");
1488
+ if (curActive) applied(ev, ev.id, "name", "NAME_RESERVED_DISPLACED", "reserved (displaced prior reservation)");
1489
+ else applied(ev, ev.id, "name", "NAME_RESERVED", "reserved (pending finalize)");
1062
1490
  return;
1063
1491
  }
1064
1492
  if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
1065
- note(ev, ev.id, "name", false, "name registration fee unpaid");
1493
+ refused(ev, ev.id, "name", "TREASURY_FEE_UNPAID", "name registration fee unpaid");
1066
1494
  return;
1067
1495
  }
1068
1496
  const cand = {
@@ -1076,7 +1504,8 @@ function applyName(c, ev, rec, who, feeToTreasury) {
1076
1504
  };
1077
1505
  const better = !curActive || !curActive.viaFill && earlierAnchor(effHeight, ev.pos, ev.id, curActive);
1078
1506
  if (!better) {
1079
- note(ev, ev.id, "name", false, curActive?.viaFill ? "name taken (purchased \u2014 not displaceable)" : "name taken (earlier anchor wins)");
1507
+ if (curActive?.viaFill) refused(ev, ev.id, "name", "NAME_TAKEN_PURCHASED", "name taken (purchased \u2014 not displaceable)");
1508
+ else refused(ev, ev.id, "name", "NAME_TAKEN_EARLIER", "name taken (earlier anchor wins)");
1080
1509
  return;
1081
1510
  }
1082
1511
  if (curActive) {
@@ -1084,189 +1513,188 @@ function applyName(c, ev, rec, who, feeToTreasury) {
1084
1513
  }
1085
1514
  putName(rec.name, cand);
1086
1515
  c.feesPaid += nameRegFee(rec.name, ev.height);
1087
- note(ev, ev.id, "name", true, curActive ? "displaced prior holder" : void 0);
1516
+ if (curActive) applied(ev, ev.id, "name", "NAME_REGISTERED_DISPLACED", "displaced prior holder");
1517
+ else applied(ev, ev.id, "name", "NAME_REGISTERED");
1088
1518
  }
1089
1519
  function applyNfinalize(c, ev, rec, who, feeToTreasury) {
1090
- const { commits, names, recaptures, pendingNames, note, putName, voidOpenNameOffers } = c;
1520
+ const { commits, names, recaptures, applied, refused, putName, voidOpenNameOffers, store } = c;
1091
1521
  const v25 = ev.height >= V25_HEIGHT;
1092
1522
  const v26 = ev.height >= V26_HEIGHT;
1093
1523
  if (!v25) {
1094
- note(ev, ev.id, "nfinalize", false, "before v2.5 activation");
1524
+ refused(ev, ev.id, "nfinalize", "GATE_NOT_ACTIVE", "before v2.5 activation");
1095
1525
  return;
1096
1526
  }
1097
1527
  const n = names.get(rec.name);
1098
1528
  if (n && n.pending && n.owner === who) {
1099
1529
  const cH = commits.get(nameCommit(rec.name, rec.salt, who));
1100
1530
  if (cH === void 0 || cH !== n.effHeight) {
1101
- note(ev, ev.id, "nfinalize", false, "salt does not match the reservation commit");
1531
+ refused(ev, ev.id, "nfinalize", "NAME_SALT_MISMATCH", "salt does not match the reservation commit");
1102
1532
  return;
1103
1533
  }
1104
1534
  if (!(ev.height > n.effHeight + REG_COMMIT_MAX_BLOCKS)) {
1105
- note(ev, ev.id, "nfinalize", false, "too early \u2014 displacement contest not yet frozen");
1535
+ refused(ev, ev.id, "nfinalize", "NAME_FINALIZE_TOO_EARLY", "too early \u2014 displacement contest not yet frozen");
1106
1536
  return;
1107
1537
  }
1108
1538
  if (n.finalizeBy !== void 0 && ev.height > n.finalizeBy) {
1109
- note(ev, ev.id, "nfinalize", false, "reservation expired");
1539
+ refused(ev, ev.id, "nfinalize", "NAME_RESERVATION_EXPIRED", "reservation expired");
1110
1540
  return;
1111
1541
  }
1112
1542
  if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
1113
- note(ev, ev.id, "nfinalize", false, "name registration fee unpaid");
1543
+ refused(ev, ev.id, "nfinalize", "TREASURY_FEE_UNPAID", "name registration fee unpaid");
1114
1544
  return;
1115
1545
  }
1116
- delete n.pending;
1117
- delete n.finalizeBy;
1118
- pendingNames.delete(rec.name);
1546
+ store.finalizeName(rec.name, n);
1119
1547
  n.paidThroughEpoch = (0, import_csd_codec.epochOf)(ev.height) + NAME_TERM_EPOCHS;
1120
1548
  c.feesPaid += nameRegFee(rec.name, ev.height);
1121
- note(ev, ev.id, "nfinalize", true);
1549
+ applied(ev, ev.id, "nfinalize", "NAME_FINALIZED");
1122
1550
  return;
1123
1551
  }
1124
1552
  const r = v26 ? recaptures.get(rec.name) : void 0;
1125
1553
  if (r && r.owner === who) {
1126
1554
  const cH = commits.get(nameCommit(rec.name, rec.salt, who));
1127
1555
  if (cH === void 0 || cH !== r.effHeight) {
1128
- note(ev, ev.id, "nfinalize", false, "salt does not match the recapture commit");
1556
+ refused(ev, ev.id, "nfinalize", "NAME_SALT_MISMATCH", "salt does not match the recapture commit");
1129
1557
  return;
1130
1558
  }
1131
1559
  if (!(ev.height > r.effHeight + REG_COMMIT_MAX_BLOCKS)) {
1132
- note(ev, ev.id, "nfinalize", false, "too early \u2014 recapture contest not yet frozen");
1560
+ refused(ev, ev.id, "nfinalize", "NAME_FINALIZE_TOO_EARLY", "too early \u2014 recapture contest not yet frozen");
1133
1561
  return;
1134
1562
  }
1135
1563
  if (ev.height > r.finalizeBy) {
1136
- note(ev, ev.id, "nfinalize", false, "recapture reservation expired");
1564
+ refused(ev, ev.id, "nfinalize", "NAME_RESERVATION_EXPIRED", "recapture reservation expired");
1137
1565
  return;
1138
1566
  }
1139
1567
  const cur = names.get(rec.name);
1140
1568
  const ep = (0, import_csd_codec.epochOf)(ev.height);
1141
1569
  if (!cur || cur.pending || !lapsed(cur, ep)) {
1142
- recaptures.delete(rec.name);
1143
- note(ev, ev.id, "nfinalize", false, "name is no longer lapsed");
1570
+ store.deleteRecapture(rec.name);
1571
+ refused(ev, ev.id, "nfinalize", "NAME_NOT_LAPSED", "name is no longer lapsed");
1144
1572
  return;
1145
1573
  }
1146
1574
  const fee = expiredClaimFee(rec.name, ep - (paidThrough(cur) + NAME_GRACE_EPOCHS), ev.height);
1147
1575
  if (feeToTreasury < fee) {
1148
- note(ev, ev.id, "nfinalize", false, "recapture premium unpaid (decaying)");
1576
+ refused(ev, ev.id, "nfinalize", "TREASURY_FEE_UNPAID", "recapture premium unpaid (decaying)");
1149
1577
  return;
1150
1578
  }
1151
1579
  voidOpenNameOffers(rec.name, ev.height);
1152
1580
  putName(rec.name, { owner: who, effHeight: r.effHeight, pos: r.pos, id: r.id, height: r.height, locked: false, paidThroughEpoch: ep + NAME_TERM_EPOCHS });
1153
- recaptures.delete(rec.name);
1581
+ store.deleteRecapture(rec.name);
1154
1582
  c.feesPaid += fee;
1155
- note(ev, ev.id, "nfinalize", true, "recapture finalized (premium)");
1583
+ applied(ev, ev.id, "nfinalize", "NAME_RECAPTURE_FINALIZED", "recapture finalized (premium)");
1156
1584
  return;
1157
1585
  }
1158
- note(ev, ev.id, "nfinalize", false, "no matching pending reservation you own");
1586
+ refused(ev, ev.id, "nfinalize", "NAME_NO_RESERVATION", "no matching pending reservation you own");
1159
1587
  }
1160
1588
  function applyNxfer(c, ev, rec, who) {
1161
- const { names, note } = c;
1589
+ const { names, applied, refused, store } = c;
1162
1590
  const v15 = ev.height >= V15_HEIGHT;
1163
1591
  const n = names.get(rec.name);
1164
1592
  if (!n || n.owner !== who) {
1165
- note(ev, ev.id, "nxfer", false, "not the name owner");
1593
+ refused(ev, ev.id, "nxfer", "NAME_NOT_OWNER", "not the name owner");
1166
1594
  return;
1167
1595
  }
1168
1596
  if (n.pending) {
1169
- note(ev, ev.id, "nxfer", false, "name reservation not yet finalized");
1597
+ refused(ev, ev.id, "nxfer", "NAME_PENDING", "name reservation not yet finalized");
1170
1598
  return;
1171
1599
  }
1172
1600
  if (v15 && lapsed(n, (0, import_csd_codec.epochOf)(ev.height))) {
1173
- note(ev, ev.id, "nxfer", false, "lease lapsed \u2014 claim it instead");
1601
+ refused(ev, ev.id, "nxfer", "NAME_LAPSED", "lease lapsed \u2014 claim it instead");
1174
1602
  return;
1175
1603
  }
1176
1604
  if (n.locked) {
1177
- note(ev, ev.id, "nxfer", false, "name is locked by an open offer");
1605
+ refused(ev, ev.id, "nxfer", "NAME_LOCKED", "name is locked by an open offer");
1178
1606
  return;
1179
1607
  }
1180
- n.owner = rec.to.toLowerCase();
1608
+ store.setNameOwner(rec.name, n, rec.to.toLowerCase());
1181
1609
  n.addr = void 0;
1182
1610
  n.profile = void 0;
1183
- note(ev, ev.id, "nxfer", true);
1611
+ applied(ev, ev.id, "nxfer", "NAME_TRANSFERRED");
1184
1612
  }
1185
1613
  function applyNset(c, ev, rec, who) {
1186
- const { names, note } = c;
1614
+ const { names, applied, refused } = c;
1187
1615
  const v15 = ev.height >= V15_HEIGHT;
1188
1616
  const v23 = ev.height >= V23_HEIGHT;
1189
1617
  const n = names.get(rec.name);
1190
1618
  if (!n || n.owner !== who) {
1191
- note(ev, ev.id, "nset", false, "not the name owner");
1619
+ refused(ev, ev.id, "nset", "NAME_NOT_OWNER", "not the name owner");
1192
1620
  return;
1193
1621
  }
1194
1622
  if (n.pending) {
1195
- note(ev, ev.id, "nset", false, "name reservation not yet finalized");
1623
+ refused(ev, ev.id, "nset", "NAME_PENDING", "name reservation not yet finalized");
1196
1624
  return;
1197
1625
  }
1198
1626
  if (v15 && lapsed(n, (0, import_csd_codec.epochOf)(ev.height))) {
1199
- note(ev, ev.id, "nset", false, "lease lapsed \u2014 claim it instead");
1627
+ refused(ev, ev.id, "nset", "NAME_LAPSED", "lease lapsed \u2014 claim it instead");
1200
1628
  return;
1201
1629
  }
1202
1630
  if (v23 && rec.addr.toLowerCase() === ZERO_ADDR) n.addr = void 0;
1203
1631
  else n.addr = rec.addr.toLowerCase();
1204
- note(ev, ev.id, "nset", true);
1632
+ applied(ev, ev.id, "nset", "NAME_ADDR_SET");
1205
1633
  }
1206
1634
  function applyNprofile(c, ev, rec, who) {
1207
- const { names, note } = c;
1635
+ const { names, applied, refused } = c;
1208
1636
  const v15 = ev.height >= V15_HEIGHT;
1209
1637
  const v19 = ev.height >= V19_HEIGHT;
1210
1638
  if (!v19) {
1211
- note(ev, ev.id, "nprofile", false, "before v1.9 activation");
1639
+ refused(ev, ev.id, "nprofile", "GATE_NOT_ACTIVE", "before v1.9 activation");
1212
1640
  return;
1213
1641
  }
1214
1642
  const n = names.get(rec.name);
1215
1643
  if (!n || n.owner !== who) {
1216
- note(ev, ev.id, "nprofile", false, "not the name owner");
1644
+ refused(ev, ev.id, "nprofile", "NAME_NOT_OWNER", "not the name owner");
1217
1645
  return;
1218
1646
  }
1219
1647
  if (n.pending) {
1220
- note(ev, ev.id, "nprofile", false, "name reservation not yet finalized");
1648
+ refused(ev, ev.id, "nprofile", "NAME_PENDING", "name reservation not yet finalized");
1221
1649
  return;
1222
1650
  }
1223
1651
  if (v15 && lapsed(n, (0, import_csd_codec.epochOf)(ev.height))) {
1224
- note(ev, ev.id, "nprofile", false, "lease lapsed \u2014 claim it instead");
1652
+ refused(ev, ev.id, "nprofile", "NAME_LAPSED", "lease lapsed \u2014 claim it instead");
1225
1653
  return;
1226
1654
  }
1227
1655
  n.profile = Object.keys(rec.p).length ? { ...rec.p } : void 0;
1228
- note(ev, ev.id, "nprofile", true);
1656
+ applied(ev, ev.id, "nprofile", "NAME_PROFILE_SET");
1229
1657
  }
1230
1658
  function applyNrenew(c, ev, rec, who, feeToTreasury) {
1231
- const { names, note } = c;
1659
+ const { names, applied, refused } = c;
1232
1660
  const v15 = ev.height >= V15_HEIGHT;
1233
1661
  if (!v15) {
1234
- note(ev, ev.id, "nrenew", false, "nrenew needs v1.5");
1662
+ refused(ev, ev.id, "nrenew", "GATE_NOT_ACTIVE", "nrenew needs v1.5");
1235
1663
  return;
1236
1664
  }
1237
1665
  const n = names.get(rec.name);
1238
1666
  const ep = (0, import_csd_codec.epochOf)(ev.height);
1239
1667
  if (n && n.pending) {
1240
- note(ev, ev.id, "nrenew", false, "name reservation not yet finalized");
1668
+ refused(ev, ev.id, "nrenew", "NAME_PENDING", "name reservation not yet finalized");
1241
1669
  return;
1242
1670
  }
1243
1671
  if (!n || lapsed(n, ep)) {
1244
- note(ev, ev.id, "nrenew", false, "no live lease (lapsed names are claimed, not renewed)");
1672
+ refused(ev, ev.id, "nrenew", "NAME_NO_LIVE_LEASE", "no live lease (lapsed names are claimed, not renewed)");
1245
1673
  return;
1246
1674
  }
1247
1675
  if (inGrace(n, ep) && who !== n.owner) {
1248
- note(ev, ev.id, "nrenew", false, "grace period: only the owner may renew");
1676
+ refused(ev, ev.id, "nrenew", "NAME_GRACE_OWNER_ONLY", "grace period: only the owner may renew");
1249
1677
  return;
1250
1678
  }
1251
1679
  if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
1252
- note(ev, ev.id, "nrenew", false, "renewal fee unpaid");
1680
+ refused(ev, ev.id, "nrenew", "TREASURY_FEE_UNPAID", "renewal fee unpaid");
1253
1681
  return;
1254
1682
  }
1255
1683
  n.paidThroughEpoch = paidThrough(n) + NAME_TERM_EPOCHS;
1256
1684
  c.feesPaid += nameRegFee(rec.name, ev.height);
1257
- note(ev, ev.id, "nrenew", true, `paid through epoch ${n.paidThroughEpoch}`);
1685
+ applied(ev, ev.id, "nrenew", "NAME_RENEWED", `paid through epoch ${n.paidThroughEpoch}`);
1258
1686
  }
1259
1687
 
1260
1688
  // src/resolve/market.ts
1261
1689
  function applyOffer(c, ev, rec, who) {
1262
- const { tokens, names, offers, offerLock, openOffers, bids, bal, note } = c;
1690
+ const { tokens, names, offerLock, bids, bal, applied, refused, store } = c;
1263
1691
  const v11 = ev.height >= V11_HEIGHT;
1264
1692
  const v15 = ev.height >= V15_HEIGHT;
1265
1693
  const v16 = ev.height >= V16_HEIGHT;
1266
1694
  const wantIsToken = isTokenWant(rec.want);
1267
1695
  const refusal = offerEnvelopeRefusal(rec, who, ev.height, ev.expiresEpoch);
1268
1696
  if (refusal !== null) {
1269
- note(ev, ev.id, "offer", false, refusal);
1697
+ refused(ev, ev.id, "offer", refusal.code, refusal.note);
1270
1698
  return;
1271
1699
  }
1272
1700
  const payto = (rec.want.payto ?? who).toLowerCase();
@@ -1274,36 +1702,36 @@ function applyOffer(c, ev, rec, who) {
1274
1702
  if (isNameGive(give)) {
1275
1703
  const n = names.get(give.name);
1276
1704
  if (!n || n.owner !== who) {
1277
- note(ev, ev.id, "offer", false, "you don't own this name");
1705
+ refused(ev, ev.id, "offer", "NAME_NOT_OWNER", "you don't own this name");
1278
1706
  return;
1279
1707
  }
1280
1708
  if (n.pending) {
1281
- note(ev, ev.id, "offer", false, "name reservation not yet finalized");
1709
+ refused(ev, ev.id, "offer", "NAME_PENDING", "name reservation not yet finalized");
1282
1710
  return;
1283
1711
  }
1284
1712
  if (n.locked) {
1285
- note(ev, ev.id, "offer", false, "name already locked by another offer");
1713
+ refused(ev, ev.id, "offer", "NAME_LOCKED", "name already locked by another offer");
1286
1714
  return;
1287
1715
  }
1288
1716
  const saleEmbargo = ev.height >= V27_HEIGHT ? REG_COMMIT_MAX_BLOCKS : COMMIT_MAX_BLOCKS;
1289
1717
  if (ev.height >= V13_HEIGHT && !n.viaFill && ev.height - n.effHeight <= saleEmbargo) {
1290
- note(ev, ev.id, "offer", false, "name too young to sell (must out-age the reveal window)");
1718
+ refused(ev, ev.id, "offer", "NAME_TOO_YOUNG", "name too young to sell (must out-age the reveal window)");
1291
1719
  return;
1292
1720
  }
1293
1721
  if (v15 && paidThrough(n) < ev.expiresEpoch) {
1294
- note(ev, ev.id, "offer", false, "v1.5: lease ends inside the offer window (renew first)");
1722
+ refused(ev, ev.id, "offer", "OFFER_LEASE_TOO_SHORT", "v1.5: lease ends inside the offer window (renew first)");
1295
1723
  return;
1296
1724
  }
1297
1725
  n.locked = true;
1298
1726
  } else {
1299
1727
  if (!tokens.has(give.ticker)) {
1300
- note(ev, ev.id, "offer", false, "unknown ticker");
1728
+ refused(ev, ev.id, "offer", "TOKEN_UNKNOWN", "unknown ticker");
1301
1729
  return;
1302
1730
  }
1303
1731
  const amt = parseAmount(give.amount);
1304
1732
  const s = bal(give.ticker, who);
1305
1733
  if (s.available < amt) {
1306
- note(ev, ev.id, "offer", false, "insufficient available balance");
1734
+ refused(ev, ev.id, "offer", "TOKEN_BALANCE_LOW", "insufficient available balance");
1307
1735
  return;
1308
1736
  }
1309
1737
  s.available -= amt;
@@ -1323,32 +1751,31 @@ function applyOffer(c, ev, rec, who) {
1323
1751
  height: ev.height,
1324
1752
  feeBps: v11 ? v16 ? FEE_BPS_V16 : FEE_BPS : 0
1325
1753
  };
1326
- offers.set(ev.id, o);
1327
- openOffers.add(ev.id);
1754
+ store.addOffer(o);
1328
1755
  const linked = rec.bid !== void 0 ? bids.get(rec.bid) : void 0;
1329
1756
  if (linked) linked.offers.push(ev.id);
1330
- note(ev, ev.id, "offer", true);
1757
+ applied(ev, ev.id, "offer", "OFFER_CREATED");
1331
1758
  }
1332
1759
  function applyBid(c, ev, rec, who) {
1333
- const { bids, openBids, note } = c;
1760
+ const { applied, refused, store } = c;
1334
1761
  const v12 = ev.height >= V12_HEIGHT;
1335
1762
  if (!v12) {
1336
- note(ev, ev.id, "bid", false, "bids need v1.2");
1763
+ refused(ev, ev.id, "bid", "GATE_NOT_ACTIVE", "bids need v1.2");
1337
1764
  return;
1338
1765
  }
1339
1766
  if (!Number.isSafeInteger(ev.expiresEpoch)) {
1340
- note(ev, ev.id, "bid", false, "expiresEpoch out of safe-integer range");
1767
+ refused(ev, ev.id, "bid", "EXPIRY_UNSAFE", "expiresEpoch out of safe-integer range");
1341
1768
  return;
1342
1769
  }
1343
1770
  if ((0, import_csd_codec.epochOf)(ev.height) > ev.expiresEpoch) {
1344
- note(ev, ev.id, "bid", false, "already expired at anchor");
1771
+ refused(ev, ev.id, "bid", "EXPIRY_PAST", "already expired at anchor");
1345
1772
  return;
1346
1773
  }
1347
1774
  if (ev.height >= V21_HEIGHT && ev.height < V22_HEIGHT && ev.expiresEpoch - (0, import_csd_codec.epochOf)(ev.height) > MAX_OFFER_EPOCHS) {
1348
- note(ev, ev.id, "bid", false, "v2.1: bid duration exceeds the max");
1775
+ refused(ev, ev.id, "bid", "EXPIRY_TOO_LONG", "v2.1: bid duration exceeds the max");
1349
1776
  return;
1350
1777
  }
1351
- bids.set(ev.id, {
1778
+ store.addBid({
1352
1779
  id: ev.id,
1353
1780
  bidder: who,
1354
1781
  want: rec.want,
@@ -1358,24 +1785,16 @@ function applyBid(c, ev, rec, who) {
1358
1785
  height: ev.height,
1359
1786
  offers: []
1360
1787
  });
1361
- openBids.add(ev.id);
1362
- note(ev, ev.id, "bid", true);
1788
+ applied(ev, ev.id, "bid", "BID_CREATED");
1363
1789
  }
1364
1790
  function applyOcancel(c, ev, rec, who) {
1365
- const { offers, note, releaseGive, setOfferStatus } = c;
1791
+ const { applied, refused, releaseGive, setOfferStatus, store } = c;
1366
1792
  const v12 = ev.height >= V12_HEIGHT;
1367
1793
  if (!v12) {
1368
- note(ev, ev.id, "ocancel", false, "ocancel needs v1.2");
1794
+ refused(ev, ev.id, "ocancel", "GATE_NOT_ACTIVE", "ocancel needs v1.2");
1369
1795
  return;
1370
1796
  }
1371
- const targets = [];
1372
- for (const o of offers.values()) {
1373
- if (o.status !== "open" || o.seller !== who) continue;
1374
- if (o.taker !== void 0 && o.height >= V28_HEIGHT) continue;
1375
- if (rec.ticker !== void 0 && !(!isNameGive(o.give) && o.give.ticker === rec.ticker)) continue;
1376
- if (rec.name !== void 0 && !(isNameGive(o.give) && o.give.name === rec.name)) continue;
1377
- targets.push(o);
1378
- }
1797
+ const targets = store.ocancelTargets(who, rec.ticker, rec.name);
1379
1798
  if (ev.height >= V14_HEIGHT) {
1380
1799
  c.pendingCancels.push(() => {
1381
1800
  let n = 0;
@@ -1387,100 +1806,98 @@ function applyOcancel(c, ev, rec, who) {
1387
1806
  n++;
1388
1807
  }
1389
1808
  }
1390
- note(ev, ev.id, "ocancel", true, `${n} cancelled (deferred past same-block fills)`);
1809
+ applied(ev, ev.id, "ocancel", "OFFER_BULK_CANCELLED", `${n} cancelled (deferred past same-block fills)`);
1391
1810
  });
1392
1811
  } else {
1393
1812
  for (const o of targets) {
1394
1813
  releaseGive(o);
1395
1814
  setOfferStatus(o, "cancelled");
1396
1815
  }
1397
- note(ev, ev.id, "ocancel", true, `${targets.length} cancelled`);
1816
+ applied(ev, ev.id, "ocancel", "OFFER_BULK_CANCELLED", `${targets.length} cancelled`);
1398
1817
  }
1399
1818
  }
1400
1819
  function applyFclaim(c, ev, rec, who) {
1401
- const { offers, fclaims, note, liveHoldCount } = c;
1820
+ const { offers, fclaims, applied, refused, store } = c;
1402
1821
  if (ev.height < V28_HEIGHT) {
1403
- note(ev, ev.id, "fclaim", false, "fclaim needs v2.8");
1822
+ refused(ev, ev.id, "fclaim", "GATE_NOT_ACTIVE", "fclaim needs v2.8");
1404
1823
  return;
1405
1824
  }
1406
1825
  const target = offers.get(rec.offer);
1407
1826
  const E = ev.expiresEpoch;
1408
- const deny = (why) => {
1827
+ const deny = (code, why) => {
1409
1828
  fclaims.set(ev.id, { offer: rec.offer, proposer: who, expiresEpoch: E, height: ev.height, granted: false });
1410
- note(ev, ev.id, "fclaim", false, why);
1829
+ refused(ev, ev.id, "fclaim", code, why);
1411
1830
  };
1412
1831
  if (!Number.isSafeInteger(E)) {
1413
- deny("expiresEpoch out of safe-integer range");
1832
+ deny("EXPIRY_UNSAFE", "expiresEpoch out of safe-integer range");
1414
1833
  return;
1415
1834
  }
1416
1835
  if (!target) {
1417
- deny("unknown offer");
1836
+ deny("OFFER_UNKNOWN", "unknown offer");
1418
1837
  return;
1419
1838
  }
1420
1839
  if (target.status !== "open") {
1421
- deny(`offer ${target.status}`);
1840
+ deny("OFFER_NOT_OPEN", `offer ${target.status}`);
1422
1841
  return;
1423
1842
  }
1424
1843
  if (target.taker) {
1425
- deny("taker-bound offer needs no claim");
1844
+ deny("CLAIM_TAKER_BOUND", "taker-bound offer needs no claim");
1426
1845
  return;
1427
1846
  }
1428
1847
  if (isTokenWant(target.want)) {
1429
- deny("claims are for CSD-priced offers");
1848
+ deny("CLAIM_TOKEN_PRICED", "claims are for CSD-priced offers");
1430
1849
  return;
1431
1850
  }
1432
1851
  if (E > effExpiry(target, ev.height)) {
1433
- deny("hold would outlive the offer expiry");
1852
+ deny("CLAIM_OUTLIVES_OFFER", "hold would outlive the offer expiry");
1434
1853
  return;
1435
1854
  }
1436
1855
  if (E > (0, import_csd_codec.epochOf)(ev.height) + FCLAIM_MAX_EPOCH_AHEAD) {
1437
- deny("hold too far ahead (anti-squat)");
1856
+ deny("CLAIM_TOO_FAR_AHEAD", "hold too far ahead (anti-squat)");
1438
1857
  return;
1439
1858
  }
1440
1859
  if ((0, import_csd_codec.epochOf)(ev.height) > E) {
1441
- deny("expiry already in the past");
1860
+ deny("EXPIRY_PAST", "expiry already in the past");
1442
1861
  return;
1443
1862
  }
1444
1863
  if (claimHeld(target, ev.height)) {
1445
- deny("offer already claimed (hold live)");
1864
+ deny("CLAIM_HOLD_LIVE", "offer already claimed (hold live)");
1446
1865
  return;
1447
1866
  }
1448
1867
  if (target.claimedBy === who && target.claimUntilHeight !== void 0 && ev.height < target.claimUntilHeight + claimGrace(target) + CLAIM_COOLDOWN_BLOCKS) {
1449
- deny("claim cooldown (you just held this offer)");
1868
+ deny("CLAIM_COOLDOWN", "claim cooldown (you just held this offer)");
1450
1869
  return;
1451
1870
  }
1452
- if (liveHoldCount(who, ev.height) >= MAX_ACTIVE_CLAIMS) {
1453
- deny(`max ${MAX_ACTIVE_CLAIMS} live claims per address`);
1871
+ if (store.liveHoldCount(who, ev.height) >= MAX_ACTIVE_CLAIMS) {
1872
+ deny("CAP_LIVE_HOLDS", `max ${MAX_ACTIVE_CLAIMS} live claims per address`);
1454
1873
  return;
1455
1874
  }
1456
- target.claimedBy = who;
1457
- target.claimUntilHeight = (E + 1) * import_csd_codec.EPOCH_LEN;
1458
- target.claimTxid = ev.id;
1875
+ store.setClaim(target, who, (E + 1) * import_csd_codec.EPOCH_LEN, ev.id);
1459
1876
  fclaims.set(ev.id, { offer: rec.offer, proposer: who, expiresEpoch: E, height: ev.height, granted: true });
1460
- note(ev, ev.id, "fclaim", true);
1877
+ applied(ev, ev.id, "fclaim", "CLAIM_GRANTED");
1461
1878
  }
1462
1879
  function offerEnvelopeRefusal(rec, who, height, expiresEpoch) {
1463
1880
  const wantIsToken = isTokenWant(rec.want);
1464
- if ((wantIsToken || rec.min !== void 0 || rec.bid !== void 0) && height < V12_HEIGHT) return "v1.2 offer shape before activation";
1465
- if (height >= V13_HEIGHT && height < V17_HEIGHT && !wantIsToken && rec.taker === void 0) return "v1.3: CSD-priced offers must be taker-bound (use bid/RFQ)";
1466
- if ((rec.want.payto ?? who).toLowerCase() === TREASURY_ADDR) return "payto cannot be the protocol treasury";
1467
- if (!Number.isSafeInteger(expiresEpoch)) return "expiresEpoch out of safe-integer range";
1468
- if ((0, import_csd_codec.epochOf)(height) > expiresEpoch) return "already expired at anchor";
1469
- if (height >= V21_HEIGHT && height < V22_HEIGHT && expiresEpoch - (0, import_csd_codec.epochOf)(height) > MAX_OFFER_EPOCHS) return "v2.1: offer duration exceeds the max";
1470
- if (isNameGive(rec.give) && height < V11_HEIGHT) return "name offers need v1.1";
1881
+ if ((wantIsToken || rec.min !== void 0 || rec.bid !== void 0) && height < V12_HEIGHT) return { code: "GATE_NOT_ACTIVE", note: "v1.2 offer shape before activation" };
1882
+ if (height >= V13_HEIGHT && height < V17_HEIGHT && !wantIsToken && rec.taker === void 0) return { code: "OFFER_TAKER_REQUIRED", note: "v1.3: CSD-priced offers must be taker-bound (use bid/RFQ)" };
1883
+ if ((rec.want.payto ?? who).toLowerCase() === TREASURY_ADDR) return { code: "OFFER_PAYTO_TREASURY", note: "payto cannot be the protocol treasury" };
1884
+ if (!Number.isSafeInteger(expiresEpoch)) return { code: "EXPIRY_UNSAFE", note: "expiresEpoch out of safe-integer range" };
1885
+ if ((0, import_csd_codec.epochOf)(height) > expiresEpoch) return { code: "EXPIRY_PAST", note: "already expired at anchor" };
1886
+ if (height >= V21_HEIGHT && height < V22_HEIGHT && expiresEpoch - (0, import_csd_codec.epochOf)(height) > MAX_OFFER_EPOCHS) return { code: "EXPIRY_TOO_LONG", note: "v2.1: offer duration exceeds the max" };
1887
+ if (isNameGive(rec.give) && height < V11_HEIGHT) return { code: "GATE_NOT_ACTIVE", note: "name offers need v1.1" };
1471
1888
  return null;
1472
1889
  }
1473
1890
 
1474
1891
  // src/resolve/tokens.ts
1475
1892
  function applyDeploy(c, ev, rec, who, feeToTreasury) {
1476
- const { tokens, note } = c;
1893
+ const { tokens, applied, refused } = c;
1477
1894
  const v11 = ev.height >= V11_HEIGHT;
1478
1895
  if (tokens.has(rec.ticker)) {
1479
- note(ev, ev.id, "deploy", false, "ticker taken (first anchor wins)");
1896
+ refused(ev, ev.id, "deploy", "TOKEN_TICKER_TAKEN", "ticker taken (first anchor wins)");
1480
1897
  return;
1481
1898
  }
1482
1899
  if (v11 && feeToTreasury < BigInt(DEPLOY_FEE)) {
1483
- note(ev, ev.id, "deploy", false, "deploy fee unpaid");
1900
+ refused(ev, ev.id, "deploy", "TREASURY_FEE_UNPAID", "deploy fee unpaid");
1484
1901
  return;
1485
1902
  }
1486
1903
  const supply = parseAmount(rec.supply);
@@ -1492,29 +1909,29 @@ function applyDeploy(c, ev, rec, who, feeToTreasury) {
1492
1909
  meta: { ticker: rec.ticker, deployId: ev.id, deployer: who, name: rec.name, decimals: rec.decimals, supply: rec.supply, minted: "0", mint: rec.mint, mintLimit: rec.mintLimit, height: ev.height }
1493
1910
  });
1494
1911
  if (v11) c.feesPaid += BigInt(DEPLOY_FEE);
1495
- note(ev, ev.id, "deploy", true);
1912
+ applied(ev, ev.id, "deploy", "TOKEN_DEPLOYED");
1496
1913
  }
1497
1914
  function applyMint(c, ev, rec, who) {
1498
- const { tokens, bal, note } = c;
1915
+ const { tokens, bal, applied, refused } = c;
1499
1916
  const tok = tokens.get(rec.ticker);
1500
1917
  if (!tok) {
1501
- note(ev, ev.id, "mint", false, "unknown ticker");
1918
+ refused(ev, ev.id, "mint", "TOKEN_UNKNOWN", "unknown ticker");
1502
1919
  return;
1503
1920
  }
1504
1921
  const remaining = tok.supply - tok.minted;
1505
1922
  if (remaining <= 0n) {
1506
- note(ev, ev.id, "mint", false, "supply exhausted");
1923
+ refused(ev, ev.id, "mint", "TOKEN_SUPPLY_EXHAUSTED", "supply exhausted");
1507
1924
  return;
1508
1925
  }
1509
1926
  let credit;
1510
1927
  if (tok.meta.mint === "issuer") {
1511
1928
  if (who !== tok.meta.deployer) {
1512
- note(ev, ev.id, "mint", false, "issuer-only mint");
1929
+ refused(ev, ev.id, "mint", "TOKEN_NOT_ISSUER", "issuer-only mint");
1513
1930
  return;
1514
1931
  }
1515
1932
  const req = rec.amount !== void 0 ? parseAmount(rec.amount) : null;
1516
1933
  if (req === null) {
1517
- note(ev, ev.id, "mint", false, "issuer mint requires amount");
1934
+ refused(ev, ev.id, "mint", "TOKEN_MINT_AMOUNT_REQUIRED", "issuer mint requires amount");
1518
1935
  return;
1519
1936
  }
1520
1937
  credit = req < remaining ? req : remaining;
@@ -1525,66 +1942,71 @@ function applyMint(c, ev, rec, who) {
1525
1942
  }
1526
1943
  tok.minted += credit;
1527
1944
  bal(rec.ticker, who).available += credit;
1528
- note(ev, ev.id, "mint", true, credit.toString());
1945
+ applied(ev, ev.id, "mint", "TOKEN_MINTED", credit.toString(), [tokenMove("mint", rec.ticker, null, who, credit)]);
1529
1946
  }
1530
1947
  function applyTransfer(c, ev, rec, who) {
1531
- const { tokens, bal, note } = c;
1948
+ const { tokens, bal, applied, refused } = c;
1532
1949
  if (!tokens.has(rec.ticker)) {
1533
- note(ev, ev.id, "transfer", false, "unknown ticker");
1950
+ refused(ev, ev.id, "transfer", "TOKEN_UNKNOWN", "unknown ticker");
1534
1951
  return;
1535
1952
  }
1536
1953
  const amt = parseAmount(rec.amount);
1537
1954
  const from = bal(rec.ticker, who);
1538
1955
  if (from.available < amt) {
1539
- note(ev, ev.id, "transfer", false, "insufficient available balance");
1956
+ refused(ev, ev.id, "transfer", "TOKEN_BALANCE_LOW", "insufficient available balance");
1540
1957
  return;
1541
1958
  }
1959
+ const to = rec.to.toLowerCase();
1542
1960
  from.available -= amt;
1543
- bal(rec.ticker, rec.to.toLowerCase()).available += amt;
1544
- note(ev, ev.id, "transfer", true);
1961
+ bal(rec.ticker, to).available += amt;
1962
+ applied(ev, ev.id, "transfer", "TOKEN_TRANSFERRED", void 0, [tokenMove("xfer", rec.ticker, who, to, amt)]);
1545
1963
  }
1546
1964
  function applyTmeta(c, ev, rec, who) {
1547
- const { tokens, note } = c;
1965
+ const { tokens, applied, refused } = c;
1548
1966
  const v15 = ev.height >= V15_HEIGHT;
1549
1967
  if (!v15) {
1550
- note(ev, ev.id, "tmeta", false, "tmeta needs v1.5");
1968
+ refused(ev, ev.id, "tmeta", "GATE_NOT_ACTIVE", "tmeta needs v1.5");
1551
1969
  return;
1552
1970
  }
1553
1971
  const tok = tokens.get(rec.ticker);
1554
1972
  if (!tok) {
1555
- note(ev, ev.id, "tmeta", false, "unknown ticker");
1973
+ refused(ev, ev.id, "tmeta", "TOKEN_UNKNOWN", "unknown ticker");
1556
1974
  return;
1557
1975
  }
1558
1976
  if (who !== tok.meta.deployer) {
1559
- note(ev, ev.id, "tmeta", false, "issuer-only metadata");
1977
+ refused(ev, ev.id, "tmeta", "TOKEN_NOT_ISSUER", "issuer-only metadata");
1560
1978
  return;
1561
1979
  }
1562
1980
  tok.meta.tmeta = rec.hash;
1563
- note(ev, ev.id, "tmeta", true);
1981
+ applied(ev, ev.id, "tmeta", "TOKEN_META_SET");
1564
1982
  }
1565
1983
 
1566
1984
  // src/resolve.ts
1567
1985
  var ord = (a, b) => a < b ? -1 : a > b ? 1 : 0;
1986
+ function eventId(e) {
1987
+ return e.kind === "propose" ? e.id : e.txid;
1988
+ }
1989
+ function applyOrder(a, b) {
1990
+ return a.height - b.height || Number(a.kind === "attest") - Number(b.kind === "attest") || a.pos - b.pos || ord(eventId(a), eventId(b));
1991
+ }
1568
1992
  function resolve(events, tipHeight) {
1569
- const ordered = [...events].sort(
1570
- (a, b) => a.height - b.height || Number(a.kind === "attest") - Number(b.kind === "attest") || a.pos - b.pos || ord(
1571
- a.kind === "propose" ? a.id : a.txid,
1572
- b.kind === "propose" ? b.id : b.txid
1573
- )
1574
- );
1575
- const eid = (e) => e.kind === "propose" ? e.id : e.txid;
1993
+ return replay(events, tipHeight);
1994
+ }
1995
+ function replay(events, tipHeight, opts = {}) {
1996
+ const ordered = [...events].sort(applyOrder);
1576
1997
  const seenIds = /* @__PURE__ */ new Set();
1577
1998
  const applied = [];
1578
1999
  for (const e of ordered) {
1579
2000
  if (e.height >= V29_HEIGHT) {
1580
- const k = eid(e);
2001
+ const k = eventId(e);
1581
2002
  if (seenIds.has(k)) continue;
1582
2003
  seenIds.add(k);
1583
2004
  }
1584
2005
  applied.push(e);
1585
2006
  }
1586
- const c = createContext();
1587
- const { tokens, balances, names, recaptures, offers, bids, fclaims, log, note, sweepExpired } = c;
2007
+ const store = createStore(opts);
2008
+ const c = createContext(store);
2009
+ const { tokens, balances, names, recaptures, offers, bids, fclaims, log, refused, sweepExpired } = c;
1588
2010
  let pendingBlock = -1;
1589
2011
  const applyPendingCancels = () => {
1590
2012
  for (const f of c.pendingCancels) f();
@@ -1597,13 +2019,15 @@ function resolve(events, tipHeight) {
1597
2019
  pendingBlock = ev.height;
1598
2020
  }
1599
2021
  sweepExpired(ev.height);
2022
+ store.verify(ev.height);
1600
2023
  const feeToTreasury = ev.kind === "propose" ? ptAmt((ev.paidTo ?? {})[TREASURY_ADDR]) : 0n;
1601
2024
  if (ev.kind === "propose") {
1602
- const rec = parseRecord(ev.uri, ev.payloadHash);
1603
- if (!rec) {
1604
- note(ev, ev.id, "invalid", false, "unparseable/non-canonical record");
2025
+ const parsed = explainRecord(ev.uri, ev.payloadHash);
2026
+ if (!parsed.ok) {
2027
+ refused(ev, ev.id, "invalid", parsed.code, "unparseable/non-canonical record");
1605
2028
  continue;
1606
2029
  }
2030
+ const rec = parsed.record;
1607
2031
  const who = ev.proposer.toLowerCase();
1608
2032
  switch (rec.t) {
1609
2033
  case "deploy":
@@ -1658,6 +2082,7 @@ function resolve(events, tipHeight) {
1658
2082
  }
1659
2083
  applyPendingCancels();
1660
2084
  sweepExpired(tipHeight + 1);
2085
+ store.verify(tipHeight + 1, true);
1661
2086
  const tokensOut = {};
1662
2087
  for (const [t, tok] of [...tokens.entries()].sort(([a], [b]) => ord(a, b))) tokensOut[t] = { ...tok.meta, minted: tok.minted.toString() };
1663
2088
  const balancesOut = {};
@@ -1883,6 +2308,54 @@ function pickPrimaryName(names, a) {
1883
2308
  return best ? best.name : null;
1884
2309
  }
1885
2310
 
2311
+ // src/forward.ts
2312
+ function resolveNameIn(names, name) {
2313
+ if (!Object.hasOwn(names, name)) return null;
2314
+ const n = names[name];
2315
+ if (!n) return null;
2316
+ if (n.pending) return null;
2317
+ return { name, addr: n.addr ?? n.owner, via: n.addr ? "nset" : "owner", lapsed: n.expired === true, owner: n.owner };
2318
+ }
2319
+ function nameView(names, name) {
2320
+ if (typeof name !== "string" || !NAME_RE.test(name)) return null;
2321
+ const none = { owner: null, addr: null, profile: {}, paidThroughEpoch: null };
2322
+ if (RESERVED_NAMES.has(name)) return { name, state: "reserved", ...none };
2323
+ const n = Object.hasOwn(names, name) ? names[name] : void 0;
2324
+ if (!n) return { name, state: "free", ...none };
2325
+ const r = resolveNameIn(names, name);
2326
+ if (r === null) return { name, state: "pending", ...none, owner: n.owner };
2327
+ const paidThroughEpoch = n.paidThroughEpoch ?? null;
2328
+ if (r.lapsed) return { name, state: "lapsed", ...none, owner: n.owner, paidThroughEpoch };
2329
+ return { name, state: "held", owner: n.owner, addr: r.addr, profile: { ...n.profile }, paidThroughEpoch };
2330
+ }
2331
+
2332
+ // src/version.ts
2333
+ var CAIRNX_CORE_VERSION = "0.2.8";
2334
+
2335
+ // src/gates.ts
2336
+ var GATE_HEIGHTS = Object.freeze({
2337
+ ACTIVATION_HEIGHT,
2338
+ V11_HEIGHT,
2339
+ V12_HEIGHT,
2340
+ V13_HEIGHT,
2341
+ V14_HEIGHT,
2342
+ V15_HEIGHT,
2343
+ V16_HEIGHT,
2344
+ V17_HEIGHT,
2345
+ V18_HEIGHT,
2346
+ V19_HEIGHT,
2347
+ V20_HEIGHT,
2348
+ V21_HEIGHT,
2349
+ V22_HEIGHT,
2350
+ V23_HEIGHT,
2351
+ V24_HEIGHT,
2352
+ V25_HEIGHT,
2353
+ V26_HEIGHT,
2354
+ V27_HEIGHT,
2355
+ V28_HEIGHT,
2356
+ V29_HEIGHT
2357
+ });
2358
+
1886
2359
  // src/verifyfill.ts
1887
2360
  var import_csd_codec4 = require("@inversealtruism/csd-codec");
1888
2361
  var FCLAIM_MAX_HOLD_SPAN = import_csd_codec.EPOCH_LEN * (FCLAIM_MAX_EPOCH_AHEAD + 1) - 1;
@@ -2065,6 +2538,176 @@ function burnedPayment(paidTo, payer, offer2) {
2065
2538
  return { treasury: read(TREASURY_ADDR), counterparty };
2066
2539
  }
2067
2540
 
2541
+ // src/events.ts
2542
+ var import_csd_codec5 = require("@inversealtruism/csd-codec");
2543
+ var CAIRNX_EVENT_RULE = Object.freeze({ domain: DOMAIN, activationHeight: ACTIVATION_HEIGHT });
2544
+ var fail = (what) => {
2545
+ throw new Error(`events rule: ${what}`);
2546
+ };
2547
+ var isIndex = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
2548
+ function hexOf(v, bytes, what) {
2549
+ const h = typeof v === "string" && v.startsWith("0x") ? v.slice(2) : v;
2550
+ if (typeof h !== "string" || h.length !== bytes * 2 || !/^[0-9a-fA-F]*$/.test(h)) return fail(`${what} is not ${bytes}-byte hex`);
2551
+ return "0x" + h.toLowerCase();
2552
+ }
2553
+ function u64Of(v, what) {
2554
+ if (typeof v === "bigint" && v >= 0n && v < 1n << 64n) return v;
2555
+ if (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 2 ** 53) return v;
2556
+ if (typeof v === "number" && Number.isInteger(v) && v > 2 ** 53) return fail(`${what} above 2^53 must be passed as a bigint`);
2557
+ return fail(`${what} is not a u64`);
2558
+ }
2559
+ function u32Of(v, what) {
2560
+ return typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 4294967295 ? v : fail(`${what} is not a u32`);
2561
+ }
2562
+ function checkRule(rule) {
2563
+ const d = rule?.domain;
2564
+ if (typeof d !== "string" || d === "" || !(0, import_csd_codec5.isWellFormedUtf16)(d) || d.includes("\0") || d.includes(""))
2565
+ fail("the rule's domain must be non-empty, well-formed text without U+0000 or U+0001");
2566
+ if (!isIndex(rule.activationHeight)) fail("the rule's activation height must be a safe integer >= 0");
2567
+ }
2568
+ var kindOf = (app) => {
2569
+ const t = app?.type;
2570
+ return t === "None" ? "none" : t === "Propose" ? "propose" : t === "Attest" ? "attest" : fail(`unknown app type ${String(t)}`);
2571
+ };
2572
+ var domainOf = (app) => typeof app.domain === "string" ? app.domain : fail("a Propose domain is not text");
2573
+ function paidToOf(outputs) {
2574
+ if (!Array.isArray(outputs)) fail("outputs is not a list");
2575
+ const counted = [];
2576
+ for (const o of outputs) {
2577
+ const addr = hexOf(o?.scriptPubkey, 20, "script_pubkey"), value = u64Of(o?.value, "output value");
2578
+ if (value <= Number.MAX_SAFE_INTEGER) counted.push({ addr, value: Number(value) });
2579
+ }
2580
+ return paidToFromOutputs(counted);
2581
+ }
2582
+ function eventOfTx(t, height, author, rule = CAIRNX_EVENT_RULE) {
2583
+ checkRule(rule);
2584
+ if (!isIndex(height)) fail("height is not a safe integer >= 0");
2585
+ if (!isIndex(t?.pos)) fail("pos is not a safe integer >= 0");
2586
+ const txid = hexOf(t.txid, 32, "txid");
2587
+ const app = t.tx?.app;
2588
+ const kind = kindOf(app);
2589
+ if (kind === "none" || height < rule.activationHeight) return null;
2590
+ if (t.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2591
+ if (kind === "propose" && domainOf(app) !== rule.domain) return null;
2592
+ const paidTo = paidToOf(t.tx.outputs), who = hexOf(author, 20, "author");
2593
+ if (kind === "propose") {
2594
+ const p = app;
2595
+ const uri = p.uri;
2596
+ if (typeof uri !== "string" || !(0, import_csd_codec5.isWellFormedUtf16)(uri)) return fail("uri is not well-formed text");
2597
+ const e = u64Of(p.expiresEpoch, "expiresEpoch");
2598
+ return {
2599
+ kind: "propose",
2600
+ id: txid,
2601
+ proposer: who,
2602
+ uri: uri.replaceAll("\0", ""),
2603
+ payloadHash: hexOf(p.payloadHash, 32, "payloadHash"),
2604
+ expiresEpoch: e <= Number.MAX_SAFE_INTEGER ? Number(e) : 2 ** 53,
2605
+ height,
2606
+ pos: t.pos,
2607
+ paidTo
2608
+ };
2609
+ }
2610
+ const a = app;
2611
+ return {
2612
+ kind: "attest",
2613
+ txid,
2614
+ proposalId: hexOf(a.proposalId, 32, "proposalId"),
2615
+ attester: who,
2616
+ score: u32Of(a.score, "score"),
2617
+ confidence: u32Of(a.confidence, "confidence"),
2618
+ height,
2619
+ pos: t.pos,
2620
+ paidTo
2621
+ };
2622
+ }
2623
+ function blockMembers(height, txs, sofar, rule = CAIRNX_EVENT_RULE) {
2624
+ checkRule(rule);
2625
+ if (!isIndex(height)) fail("height is not a safe integer >= 0");
2626
+ if (height < rule.activationHeight) return [];
2627
+ if (!Array.isArray(txs)) fail("txs is not a list");
2628
+ const ids = /* @__PURE__ */ new Set(), proposals = /* @__PURE__ */ new Set();
2629
+ const read = [];
2630
+ let last = -1;
2631
+ for (const item of txs) {
2632
+ if (!isIndex(item?.pos) || item.pos <= last) fail("positions are not safe integers >= 0 in strictly increasing order");
2633
+ last = item.pos;
2634
+ const id = hexOf(item.txid, 32, "txid");
2635
+ if (ids.has(id)) fail(`txid ${id} is repeated in the block`);
2636
+ ids.add(id);
2637
+ const kind = kindOf(item.tx?.app);
2638
+ if (kind === "none") continue;
2639
+ if (item.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2640
+ if (kind === "propose") {
2641
+ if (domainOf(item.tx.app) !== rule.domain || sofar.eventIds.has(id)) continue;
2642
+ proposals.add(id);
2643
+ read.push({ item, kind, id });
2644
+ } else read.push({ item, kind, id, proposal: hexOf(item.tx.app.proposalId, 32, "proposalId") });
2645
+ }
2646
+ 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 }));
2647
+ }
2648
+ function blockEvents(height, txs, sofar, authors, rule = CAIRNX_EVENT_RULE) {
2649
+ const members = blockMembers(height, txs, sofar, rule);
2650
+ if (!Array.isArray(authors) || authors.length !== members.length) fail(`the block has ${members.length} members, not ${authors?.length} authors`);
2651
+ const events = members.map((m, i) => eventOfTx(m.item, height, authors[i], rule) ?? fail("a member mapped to no event"));
2652
+ return [...events.filter((e) => e.kind === "propose"), ...events.filter((e) => e.kind === "attest")];
2653
+ }
2654
+
2655
+ // src/hashes.ts
2656
+ var import_csd_codec6 = require("@inversealtruism/csd-codec");
2657
+ var import_sha256 = require("@noble/hashes/sha256");
2658
+ var EVENTS_HASH_START = "0x" + "00".repeat(32);
2659
+ var FINAL_DEPTH = 12;
2660
+ var fail2 = (what) => {
2661
+ throw new Error(`events hash: ${what}`);
2662
+ };
2663
+ var hex = (b) => "0x" + (0, import_csd_codec6.bytesToHex)(b);
2664
+ function bytesOf(v, re, what) {
2665
+ return typeof v === "string" && re.test(v) ? (0, import_csd_codec6.hexToBytes)(v.slice(2)) : fail2(`${what} is not 0x and lowercase hex of its length`);
2666
+ }
2667
+ function stateHash(state) {
2668
+ return hex((0, import_sha256.sha256)((0, import_csd_codec6.utf8ToBytes)(canonicalState(state))));
2669
+ }
2670
+ function rowOf(e, height) {
2671
+ const kind = e?.kind;
2672
+ if (kind !== "propose" && kind !== "attest") return fail2("an event's kind is neither propose nor attest");
2673
+ if (e.height !== height) fail2(`an event at height ${String(e.height)} is in the block at ${height}`);
2674
+ if (!Number.isInteger(e.pos) || e.pos < 0 || e.pos > 4294967295) fail2("an event's position is not an integer in [0, 2^32 - 1]");
2675
+ const p = e, a = e;
2676
+ const id = bytesOf(kind === "propose" ? p.id : a.txid, HASH_RE, "an event's transaction id");
2677
+ const author = bytesOf(kind === "propose" ? p.proposer : a.attester, ADDR_RE, "an event's author");
2678
+ const row = new Uint8Array(56);
2679
+ new DataView(row.buffer).setUint32(0, e.pos);
2680
+ row.set(id, 4);
2681
+ row.set(author, 36);
2682
+ return { pos: e.pos, row };
2683
+ }
2684
+ function eventsHashStep(prev, height, events) {
2685
+ const e = bytesOf(prev, HASH_RE, "the previous value");
2686
+ if (!Number.isSafeInteger(height) || height < 0) fail2("height is not an integer in [0, 2^53 - 1]");
2687
+ if (!Array.isArray(events)) fail2("events is not a list");
2688
+ if (events.length === 0) return prev;
2689
+ const rows = events.map((x) => rowOf(x, height)).sort((x, y) => x.pos - y.pos);
2690
+ for (let i = 1; i < rows.length; i++) if (rows[i].pos === rows[i - 1].pos) fail2(`position ${rows[i].pos} is repeated in the block`);
2691
+ const head = new Uint8Array(8);
2692
+ new DataView(head.buffer).setBigUint64(0, BigInt(height));
2693
+ const b = (0, import_sha256.sha256)((0, import_csd_codec6.concatBytes)(head, ...rows.map((r) => r.row)));
2694
+ return hex((0, import_sha256.sha256)((0, import_csd_codec6.concatBytes)(e, b)));
2695
+ }
2696
+ function eventsHash(events) {
2697
+ if (!Array.isArray(events)) fail2("events is not a list");
2698
+ let value = EVENTS_HASH_START, last = -1;
2699
+ for (let i = 0; i < events.length; ) {
2700
+ const height = events[i]?.height;
2701
+ let j = i + 1;
2702
+ while (j < events.length && events[j]?.height === height) j++;
2703
+ value = eventsHashStep(value, height, events.slice(i, j));
2704
+ if (height < last) fail2(`height ${height} follows height ${last}`);
2705
+ last = height;
2706
+ i = j;
2707
+ }
2708
+ return value;
2709
+ }
2710
+
2068
2711
  // src/fillclosed.ts
2069
2712
  var lc = (v) => String(v).toLowerCase();
2070
2713
  function myProvenFillClosedOffer(fill, fclaim2, offerEv, me, grantHeight) {
@@ -2128,17 +2771,140 @@ function provenOfferRefusal(rec, tx) {
2128
2771
  if (tx.domain !== DOMAIN) return `not a ${DOMAIN} Propose (domain ${JSON.stringify(String(tx.domain))})`;
2129
2772
  if (beforeActivation(tx.height)) return `anchored before CairnX activation (block ${ACTIVATION_HEIGHT})`;
2130
2773
  const ee = typeof tx.expiresEpoch === "bigint" ? Number(tx.expiresEpoch) : tx.expiresEpoch;
2131
- return offerEnvelopeRefusal(rec, String(tx.seller).toLowerCase(), tx.height, ee);
2774
+ return offerEnvelopeRefusal(rec, String(tx.seller).toLowerCase(), tx.height, ee)?.note ?? null;
2132
2775
  }
2133
2776
 
2777
+ // src/codes.ts
2778
+ var TABLE = {
2779
+ TOKEN_DEPLOYED: "applied",
2780
+ TOKEN_MINTED: "applied",
2781
+ TOKEN_TRANSFERRED: "applied",
2782
+ TOKEN_META_SET: "applied",
2783
+ NAME_COMMITTED: "applied",
2784
+ NAME_REGISTERED: "applied",
2785
+ NAME_REGISTERED_DISPLACED: "applied",
2786
+ NAME_RESERVED: "applied",
2787
+ NAME_RESERVED_DISPLACED: "applied",
2788
+ NAME_RECAPTURE_RESERVED: "applied",
2789
+ NAME_RECAPTURE_RESERVED_DISPLACED: "applied",
2790
+ NAME_RECLAIMED: "applied",
2791
+ NAME_FINALIZED: "applied",
2792
+ NAME_RECAPTURE_FINALIZED: "applied",
2793
+ NAME_TRANSFERRED: "applied",
2794
+ NAME_ADDR_SET: "applied",
2795
+ NAME_PROFILE_SET: "applied",
2796
+ NAME_RENEWED: "applied",
2797
+ OFFER_CREATED: "applied",
2798
+ OFFER_BULK_CANCELLED: "applied",
2799
+ OFFER_CANCELLED: "applied",
2800
+ BID_CREATED: "applied",
2801
+ BID_CANCELLED: "applied",
2802
+ FILL_APPLIED: "applied",
2803
+ FILL_PARTIAL: "applied",
2804
+ CLAIM_GRANTED: "applied",
2805
+ GATE_NOT_ACTIVE: "refused",
2806
+ CLAIM_LEGACY_SUNSET: "refused",
2807
+ TOKEN_TICKER_TAKEN: "refused",
2808
+ TOKEN_UNKNOWN: "refused",
2809
+ TOKEN_NOT_ISSUER: "refused",
2810
+ TOKEN_SUPPLY_EXHAUSTED: "refused",
2811
+ TOKEN_MINT_AMOUNT_REQUIRED: "refused",
2812
+ TOKEN_BALANCE_LOW: "refused",
2813
+ TREASURY_FEE_UNPAID: "refused",
2814
+ NAME_NO_COMMIT: "refused",
2815
+ NAME_SALT_REQUIRED: "refused",
2816
+ NAME_TAKEN_EARLIER: "refused",
2817
+ NAME_TAKEN_PURCHASED: "refused",
2818
+ NAME_SALT_MISMATCH: "refused",
2819
+ NAME_FINALIZE_TOO_EARLY: "refused",
2820
+ NAME_RESERVATION_EXPIRED: "refused",
2821
+ NAME_NOT_LAPSED: "refused",
2822
+ NAME_NO_RESERVATION: "refused",
2823
+ NAME_NOT_OWNER: "refused",
2824
+ NAME_PENDING: "refused",
2825
+ NAME_LAPSED: "refused",
2826
+ NAME_NO_LIVE_LEASE: "refused",
2827
+ NAME_GRACE_OWNER_ONLY: "refused",
2828
+ NAME_LOCKED: "refused",
2829
+ NAME_TOO_YOUNG: "refused",
2830
+ OFFER_LEASE_TOO_SHORT: "refused",
2831
+ OFFER_TAKER_REQUIRED: "refused",
2832
+ OFFER_PAYTO_TREASURY: "refused",
2833
+ OFFER_UNKNOWN: "refused",
2834
+ OFFER_NOT_OPEN: "refused",
2835
+ OFFER_NOT_SELLER: "refused",
2836
+ OFFER_FIRM_QUOTE: "refused",
2837
+ OFFER_CANCEL_HOLD_LIVE: "refused",
2838
+ OFFER_CLOSED_BEFORE_CANCEL: "refused",
2839
+ BID_NOT_BIDDER: "refused",
2840
+ BID_NOT_OPEN: "refused",
2841
+ EXPIRY_UNSAFE: "refused",
2842
+ EXPIRY_PAST: "refused",
2843
+ EXPIRY_TOO_LONG: "refused",
2844
+ FILL_FCLAIM_NOT_CURRENT: "refused",
2845
+ FILL_NOT_TAKER: "refused",
2846
+ FILL_NO_TOKEN_MARKER: "refused",
2847
+ FILL_OPEN_LANE_CLOSED: "refused",
2848
+ FILL_WRONG_TARGET: "refused",
2849
+ FILL_NO_LIVE_CLAIM: "refused",
2850
+ FILL_BELOW_MIN: "refused",
2851
+ FILL_ZERO_DELIVERY: "refused",
2852
+ FILL_UNDERPAID: "refused",
2853
+ FILL_REBATE_UNPAID: "refused",
2854
+ CLAIM_TAKER_BOUND: "refused",
2855
+ CLAIM_TOKEN_PRICED: "refused",
2856
+ CLAIM_HOLD_LIVE: "refused",
2857
+ CLAIM_COOLDOWN: "refused",
2858
+ CLAIM_OUTLIVES_OFFER: "refused",
2859
+ CLAIM_TOO_FAR_AHEAD: "refused",
2860
+ CAP_PENDING_RESERVATIONS: "refused",
2861
+ CAP_PENDING_RECAPTURES: "refused",
2862
+ CAP_LIVE_HOLDS: "refused",
2863
+ INVARIANT_BROKEN: "refused",
2864
+ RECORD_TOO_LARGE: "refused",
2865
+ RECORD_NOT_OBJECT: "refused",
2866
+ RECORD_NOT_CANONICAL: "refused",
2867
+ RECORD_HASH_MISMATCH: "refused",
2868
+ RECORD_LONE_SURROGATE: "refused",
2869
+ RECORD_NOT_V1: "refused",
2870
+ RECORD_UNKNOWN_TYPE: "refused",
2871
+ RECORD_EXTRA_KEY: "refused",
2872
+ RECORD_BAD_SHAPE: "refused",
2873
+ RECORD_SAME_TOKEN: "refused",
2874
+ RECORD_BAD_TICKER: "refused",
2875
+ RECORD_BAD_NAME: "refused",
2876
+ RECORD_NAME_RESERVED: "refused",
2877
+ RECORD_BAD_ADDRESS: "refused",
2878
+ RECORD_BAD_AMOUNT: "refused",
2879
+ RECORD_AMOUNT_TOO_LARGE: "refused",
2880
+ RECORD_AMOUNT_ZERO: "refused",
2881
+ RECORD_MIN_ABOVE_WANT: "refused",
2882
+ RECORD_BAD_HASH: "refused",
2883
+ RECORD_BAD_SALT: "refused",
2884
+ RECORD_BAD_DECIMALS: "refused",
2885
+ RECORD_BAD_MINT_MODE: "refused",
2886
+ RECORD_BAD_TEXT: "refused",
2887
+ RECORD_BAD_TS: "refused",
2888
+ RECORD_PROFILE_TOO_MANY_KEYS: "refused",
2889
+ RECORD_PROFILE_BAD_KEY: "refused",
2890
+ RECORD_PROFILE_BAD_VALUE: "refused",
2891
+ RECORD_PROFILE_VALUE_TOO_LONG: "refused"
2892
+ };
2893
+ var REASON_CODES = Object.freeze(Object.keys(TABLE));
2894
+ var REASON_CODE_OUTCOME = Object.freeze({ ...TABLE });
2895
+ var CAP_CODES = Object.freeze(["CAP_PENDING_RESERVATIONS", "CAP_PENDING_RECAPTURES", "CAP_LIVE_HOLDS"]);
2896
+
2134
2897
  // src/index.ts
2135
- var import_csd_codec5 = require("@inversealtruism/csd-codec");
2898
+ var import_csd_codec7 = require("@inversealtruism/csd-codec");
2136
2899
  // Annotate the CommonJS export names for ESM import in node:
2137
2900
  0 && (module.exports = {
2138
2901
  ACTIVATION_HEIGHT,
2139
2902
  ADDR_RE,
2140
2903
  AMOUNT_RE,
2141
2904
  BID_KEYS,
2905
+ CAIRNX_CORE_VERSION,
2906
+ CAIRNX_EVENT_RULE,
2907
+ CAP_CODES,
2142
2908
  CLAIM_ATTACKER_Q,
2143
2909
  CLAIM_COOLDOWN_BLOCKS,
2144
2910
  CLAIM_FILL_GRACE_BLOCKS,
@@ -2152,6 +2918,7 @@ var import_csd_codec5 = require("@inversealtruism/csd-codec");
2152
2918
  DEPLOY_KEYS,
2153
2919
  DOMAIN,
2154
2920
  EPOCH_LEN,
2921
+ EVENTS_HASH_START,
2155
2922
  FCLAIM_KEYS,
2156
2923
  FCLAIM_MAX_EPOCH_AHEAD,
2157
2924
  FCLAIM_MAX_HOLD_SPAN,
@@ -2161,7 +2928,9 @@ var import_csd_codec5 = require("@inversealtruism/csd-codec");
2161
2928
  FEE_GATE_MARGIN_BLOCKS,
2162
2929
  FILL_TIP_MARGIN,
2163
2930
  FINALIZE_TIP_MARGIN,
2931
+ FINAL_DEPTH,
2164
2932
  GAP_NEEDED,
2933
+ GATE_HEIGHTS,
2165
2934
  HALVING_INTERVAL,
2166
2935
  HASH_RE,
2167
2936
  INITIAL_REWARD,
@@ -2194,11 +2963,14 @@ var import_csd_codec5 = require("@inversealtruism/csd-codec");
2194
2963
  PKEY,
2195
2964
  PROFILE_MAX_KEYS,
2196
2965
  PROFILE_MAX_VALUE_BYTES,
2966
+ REASON_CODES,
2967
+ REASON_CODE_OUTCOME,
2197
2968
  REBATE_BPS,
2198
2969
  REBATE_FLAT,
2199
2970
  REG_COMMIT_MAX_BLOCKS,
2200
2971
  REG_FINALIZE_GRACE_BLOCKS,
2201
2972
  RESERVED_NAMES,
2973
+ RecordError,
2202
2974
  SALT_RE,
2203
2975
  SCAN_MARGIN,
2204
2976
  SCORE_CANCEL,
@@ -2227,10 +2999,13 @@ var import_csd_codec5 = require("@inversealtruism/csd-codec");
2227
2999
  V28_HEIGHT,
2228
3000
  V29_HEIGHT,
2229
3001
  ZERO_ADDR,
3002
+ applyOrder,
2230
3003
  beforeActivation,
2231
3004
  bid,
2232
3005
  bindOfferTerms,
2233
3006
  bindProvenOffer,
3007
+ blockEvents,
3008
+ blockMembers,
2234
3009
  blockReward,
2235
3010
  buildFeeHeight,
2236
3011
  buildRecord,
@@ -2243,7 +3018,12 @@ var import_csd_codec5 = require("@inversealtruism/csd-codec");
2243
3018
  countOtherHoldsAtGrant,
2244
3019
  deploy,
2245
3020
  epochOf,
3021
+ eventId,
3022
+ eventOfTx,
3023
+ eventsHash,
3024
+ eventsHashStep,
2246
3025
  expiredClaimFee,
3026
+ explainRecord,
2247
3027
  fclaim,
2248
3028
  fclaimEpochFor,
2249
3029
  fclaimHoldEnd,
@@ -2269,6 +3049,7 @@ var import_csd_codec5 = require("@inversealtruism/csd-codec");
2269
3049
  nameRegFee,
2270
3050
  nameRenew,
2271
3051
  nameSet,
3052
+ nameView,
2272
3053
  nameXfer,
2273
3054
  offer,
2274
3055
  offerCancelAll,
@@ -2288,6 +3069,8 @@ var import_csd_codec5 = require("@inversealtruism/csd-codec");
2288
3069
  requiredClaimDepth,
2289
3070
  requiredFillOutputs,
2290
3071
  resolve,
3072
+ resolveNameIn,
3073
+ stateHash,
2291
3074
  tokenMeta,
2292
3075
  tradeFee,
2293
3076
  transfer,