@inversealtruism/cairnx-core 0.2.3 → 0.2.7

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