@inversealtruism/cairnx-core 0.2.4 → 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.js CHANGED
@@ -115,17 +115,26 @@ var isTokenWant = (w) => typeof w.ticker === "string";
115
115
 
116
116
  // src/records.ts
117
117
  import { canonicalJson, payloadHash, isWellFormedUtf16 } from "@inversealtruism/csd-codec";
118
- function parseAmount(s, opts = {}) {
119
- if (typeof s !== "string" || !AMOUNT_RE.test(s)) return null;
118
+ function amountOrCode(s, allowZero) {
119
+ if (typeof s !== "string" || !AMOUNT_RE.test(s)) return "RECORD_BAD_AMOUNT";
120
120
  const v = BigInt(s);
121
- if (v > MAX_AMOUNT) return null;
122
- if (v === 0n && !opts.allowZero) return null;
121
+ if (v > MAX_AMOUNT) return "RECORD_AMOUNT_TOO_LARGE";
122
+ if (v === 0n && !allowZero) return "RECORD_AMOUNT_ZERO";
123
123
  return v;
124
124
  }
125
+ function parseAmount(s, opts = {}) {
126
+ const v = amountOrCode(s, Boolean(opts.allowZero));
127
+ return typeof v === "bigint" ? v : null;
128
+ }
129
+ var amountFault = (s, allowZero = false) => {
130
+ const v = amountOrCode(s, allowZero);
131
+ return typeof v === "bigint" ? null : v;
132
+ };
125
133
  var isAddr = (a) => typeof a === "string" && ADDR_RE.test(a);
126
134
  var isTicker = (t) => typeof t === "string" && TICKER_RE.test(t);
127
135
  var isHash = (h) => typeof h === "string" && HASH_RE.test(h);
128
- var isName = (n) => typeof n === "string" && NAME_RE.test(n) && !RESERVED_NAMES.has(n);
136
+ var nameFault = (n) => typeof n !== "string" || !NAME_RE.test(n) ? "RECORD_BAD_NAME" : RESERVED_NAMES.has(n) ? "RECORD_NAME_RESERVED" : null;
137
+ var isName = (n) => nameFault(n) === null;
129
138
  function nameCommit(name, salt, owner) {
130
139
  return payloadHash({ t: "cairnx:name:commit:v1", name, salt, owner: owner.toLowerCase() });
131
140
  }
@@ -151,172 +160,201 @@ var NFINALIZE_KEYS = /* @__PURE__ */ new Set(["v", "t", "name", "salt"]);
151
160
  var NPROFILE_KEYS = /* @__PURE__ */ new Set(["v", "t", "name", "p"]);
152
161
  var FCLAIM_KEYS = /* @__PURE__ */ new Set(["v", "t", "offer"]);
153
162
  function parseRecord(uri, payloadHashHex) {
154
- if (new TextEncoder().encode(uri).length > MAX_RECORD_BYTES) return null;
163
+ const r = recordOrCode(uri, payloadHashHex);
164
+ return typeof r === "string" ? null : r;
165
+ }
166
+ function explainRecord(uri, payloadHashHex) {
167
+ const r = recordOrCode(uri, payloadHashHex);
168
+ return typeof r === "string" ? { ok: false, code: r } : { ok: true, record: r };
169
+ }
170
+ function recordOrCode(uri, payloadHashHex) {
171
+ if (new TextEncoder().encode(uri).length > MAX_RECORD_BYTES) return "RECORD_TOO_LARGE";
155
172
  let obj;
156
173
  try {
157
174
  obj = JSON.parse(uri);
158
175
  } catch {
159
- return null;
176
+ return "RECORD_NOT_OBJECT";
160
177
  }
161
- if (typeof obj !== "object" || obj === null || Array.isArray(obj)) return null;
178
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) return "RECORD_NOT_OBJECT";
162
179
  try {
163
- if (canonicalJson(obj) !== uri) return null;
164
- if (payloadHash(obj).toLowerCase() !== payloadHashHex.toLowerCase()) return null;
180
+ if (canonicalJson(obj) !== uri) return "RECORD_NOT_CANONICAL";
165
181
  } catch {
166
- return null;
182
+ return "RECORD_NOT_CANONICAL";
167
183
  }
168
- if (!isWellFormedDeep(obj)) return null;
184
+ try {
185
+ if (payloadHash(obj).toLowerCase() !== payloadHashHex.toLowerCase()) return "RECORD_HASH_MISMATCH";
186
+ } catch {
187
+ return "RECORD_HASH_MISMATCH";
188
+ }
189
+ if (!isWellFormedDeep(obj)) return "RECORD_LONE_SURROGATE";
169
190
  const r = obj;
170
- if (r.v !== 1 || typeof r.t !== "string") return null;
191
+ if (r.v !== 1 || typeof r.t !== "string") return "RECORD_NOT_V1";
192
+ let fault;
171
193
  switch (r.t) {
172
194
  case "deploy": {
173
- if (!onlyKeys(r, DEPLOY_KEYS)) return null;
174
- if (!isTicker(r.ticker)) return null;
175
- if (r.name !== void 0 && (typeof r.name !== "string" || r.name.length > 32)) return null;
176
- if (typeof r.decimals !== "number" || !Number.isInteger(r.decimals) || r.decimals < 0 || r.decimals > MAX_TOKEN_DECIMALS) return null;
177
- if (parseAmount(r.supply) === null) return null;
178
- if (r.mint !== "open" && r.mint !== "issuer") return null;
179
- if (r.mint === "open" && parseAmount(r.mintLimit) === null) return null;
180
- if (r.mint === "issuer" && r.mintLimit !== void 0) return null;
195
+ if (!onlyKeys(r, DEPLOY_KEYS)) return "RECORD_EXTRA_KEY";
196
+ if (!isTicker(r.ticker)) return "RECORD_BAD_TICKER";
197
+ if (r.name !== void 0 && (typeof r.name !== "string" || r.name.length > 32)) return "RECORD_BAD_TEXT";
198
+ if (typeof r.decimals !== "number" || !Number.isInteger(r.decimals) || r.decimals < 0 || r.decimals > MAX_TOKEN_DECIMALS) return "RECORD_BAD_DECIMALS";
199
+ if (fault = amountFault(r.supply)) return fault;
200
+ if (r.mint !== "open" && r.mint !== "issuer") return "RECORD_BAD_MINT_MODE";
201
+ if (r.mint === "open" && (fault = amountFault(r.mintLimit))) return fault;
202
+ if (r.mint === "issuer" && r.mintLimit !== void 0) return "RECORD_BAD_SHAPE";
181
203
  return r;
182
204
  }
183
205
  case "mint": {
184
- if (!onlyKeys(r, MINT_KEYS)) return null;
185
- if (!isTicker(r.ticker)) return null;
186
- if (r.amount !== void 0 && parseAmount(r.amount) === null) return null;
206
+ if (!onlyKeys(r, MINT_KEYS)) return "RECORD_EXTRA_KEY";
207
+ if (!isTicker(r.ticker)) return "RECORD_BAD_TICKER";
208
+ if (r.amount !== void 0 && (fault = amountFault(r.amount))) return fault;
187
209
  return r;
188
210
  }
189
211
  case "transfer": {
190
- if (!onlyKeys(r, TRANSFER_KEYS)) return null;
191
- if (!isTicker(r.ticker) || !isAddr(r.to) || parseAmount(r.amount) === null) return null;
192
- if (r.memo !== void 0 && (typeof r.memo !== "string" || r.memo.length > 64)) return null;
193
- if (r.ts !== void 0 && (typeof r.ts !== "number" || !Number.isSafeInteger(r.ts))) return null;
212
+ if (!onlyKeys(r, TRANSFER_KEYS)) return "RECORD_EXTRA_KEY";
213
+ if (!isTicker(r.ticker)) return "RECORD_BAD_TICKER";
214
+ if (!isAddr(r.to)) return "RECORD_BAD_ADDRESS";
215
+ if (fault = amountFault(r.amount)) return fault;
216
+ if (r.memo !== void 0 && (typeof r.memo !== "string" || r.memo.length > 64)) return "RECORD_BAD_TEXT";
217
+ if (r.ts !== void 0 && (typeof r.ts !== "number" || !Number.isSafeInteger(r.ts))) return "RECORD_BAD_TS";
194
218
  return r;
195
219
  }
196
220
  case "offer": {
197
- if (!onlyKeys(r, OFFER_KEYS)) return null;
221
+ if (!onlyKeys(r, OFFER_KEYS)) return "RECORD_EXTRA_KEY";
198
222
  const g = r.give;
199
223
  const w = r.want;
200
- if (!g || !w || typeof g !== "object" || Array.isArray(g) || typeof w !== "object" || Array.isArray(w)) return null;
224
+ if (!g || !w || typeof g !== "object" || Array.isArray(g) || typeof w !== "object" || Array.isArray(w)) return "RECORD_BAD_SHAPE";
201
225
  const gKeys = Object.keys(g).sort().join(",");
202
226
  if (gKeys === "amount,ticker") {
203
- if (!isTicker(g.ticker) || parseAmount(g.amount) === null) return null;
227
+ if (!isTicker(g.ticker)) return "RECORD_BAD_TICKER";
228
+ if (fault = amountFault(g.amount)) return fault;
204
229
  } else if (gKeys === "name") {
205
- if (!isName(g.name)) return null;
206
- } else return null;
230
+ if (fault = nameFault(g.name)) return fault;
231
+ } else return "RECORD_BAD_SHAPE";
207
232
  const wKeys = Object.keys(w).filter((k) => k !== "payto").sort().join(",");
208
233
  if (wKeys === "value") {
209
- if (parseAmount(w.value, { allowZero: true }) === null) return null;
234
+ if (fault = amountFault(w.value, true)) return fault;
210
235
  } else if (wKeys === "amount,ticker") {
211
- if (!isTicker(w.ticker) || parseAmount(w.amount, { allowZero: true }) === null) return null;
212
- if (gKeys === "amount,ticker" && w.ticker === g.ticker) return null;
213
- if (r.min !== void 0) return null;
214
- } else return null;
215
- if (w.payto !== void 0 && !isAddr(w.payto)) return null;
236
+ if (!isTicker(w.ticker)) return "RECORD_BAD_TICKER";
237
+ if (fault = amountFault(w.amount, true)) return fault;
238
+ if (gKeys === "amount,ticker" && w.ticker === g.ticker) return "RECORD_SAME_TOKEN";
239
+ if (r.min !== void 0) return "RECORD_BAD_SHAPE";
240
+ } else return "RECORD_BAD_SHAPE";
241
+ if (w.payto !== void 0 && !isAddr(w.payto)) return "RECORD_BAD_ADDRESS";
216
242
  if (r.min !== void 0) {
217
- if (gKeys !== "amount,ticker" || wKeys !== "value") return null;
218
- const mn = parseAmount(r.min);
219
- if (mn === null || mn > parseAmount(w.value, { allowZero: true })) return null;
243
+ if (gKeys !== "amount,ticker" || wKeys !== "value") return "RECORD_BAD_SHAPE";
244
+ if (fault = amountFault(r.min)) return fault;
245
+ if (parseAmount(r.min) > parseAmount(w.value, { allowZero: true })) return "RECORD_MIN_ABOVE_WANT";
220
246
  }
221
- if (r.bid !== void 0 && !isHash(r.bid)) return null;
222
- if (r.taker !== void 0 && !isAddr(r.taker)) return null;
223
- if (r.memo !== void 0 && (typeof r.memo !== "string" || r.memo.length > 64)) return null;
224
- if (r.ts !== void 0 && (typeof r.ts !== "number" || !Number.isSafeInteger(r.ts))) return null;
247
+ if (r.bid !== void 0 && !isHash(r.bid)) return "RECORD_BAD_HASH";
248
+ if (r.taker !== void 0 && !isAddr(r.taker)) return "RECORD_BAD_ADDRESS";
249
+ if (r.memo !== void 0 && (typeof r.memo !== "string" || r.memo.length > 64)) return "RECORD_BAD_TEXT";
250
+ if (r.ts !== void 0 && (typeof r.ts !== "number" || !Number.isSafeInteger(r.ts))) return "RECORD_BAD_TS";
225
251
  return r;
226
252
  }
227
253
  case "ocancel": {
228
- if (r.ticker !== void 0 && r.name !== void 0) return null;
229
- if (r.ticker !== void 0 && !isTicker(r.ticker)) return null;
230
- if (r.name !== void 0 && !isName(r.name)) return null;
254
+ if (r.ticker !== void 0 && r.name !== void 0) return "RECORD_BAD_SHAPE";
255
+ if (r.ticker !== void 0 && !isTicker(r.ticker)) return "RECORD_BAD_TICKER";
256
+ if (r.name !== void 0 && (fault = nameFault(r.name))) return fault;
231
257
  const n = Object.keys(r).length;
232
- if (n !== 2 + (r.ticker !== void 0 ? 1 : 0) + (r.name !== void 0 ? 1 : 0)) return null;
258
+ if (n !== 2 + (r.ticker !== void 0 ? 1 : 0) + (r.name !== void 0 ? 1 : 0)) return "RECORD_EXTRA_KEY";
233
259
  return r;
234
260
  }
235
261
  case "bid": {
236
- if (!onlyKeys(r, BID_KEYS)) return null;
262
+ if (!onlyKeys(r, BID_KEYS)) return "RECORD_EXTRA_KEY";
237
263
  const w = r.want;
238
264
  const g = r.give;
239
- if (!w || !g || typeof w !== "object" || Array.isArray(w) || typeof g !== "object" || Array.isArray(g)) return null;
265
+ if (!w || !g || typeof w !== "object" || Array.isArray(w) || typeof g !== "object" || Array.isArray(g)) return "RECORD_BAD_SHAPE";
240
266
  const wKeys = Object.keys(w).sort().join(",");
241
267
  if (wKeys === "amount,ticker") {
242
- if (!isTicker(w.ticker) || parseAmount(w.amount) === null) return null;
268
+ if (!isTicker(w.ticker)) return "RECORD_BAD_TICKER";
269
+ if (fault = amountFault(w.amount)) return fault;
243
270
  } else if (wKeys === "name") {
244
- if (!isName(w.name)) return null;
245
- } else return null;
246
- if (Object.keys(g).sort().join(",") !== "value" || parseAmount(g.value) === null) return null;
247
- if (r.memo !== void 0 && (typeof r.memo !== "string" || r.memo.length > 64)) return null;
248
- if (r.ts !== void 0 && (typeof r.ts !== "number" || !Number.isSafeInteger(r.ts))) return null;
271
+ if (fault = nameFault(w.name)) return fault;
272
+ } else return "RECORD_BAD_SHAPE";
273
+ if (Object.keys(g).sort().join(",") !== "value") return "RECORD_BAD_SHAPE";
274
+ if (fault = amountFault(g.value)) return fault;
275
+ if (r.memo !== void 0 && (typeof r.memo !== "string" || r.memo.length > 64)) return "RECORD_BAD_TEXT";
276
+ if (r.ts !== void 0 && (typeof r.ts !== "number" || !Number.isSafeInteger(r.ts))) return "RECORD_BAD_TS";
249
277
  return r;
250
278
  }
251
279
  // ── names (v1.1) ──
252
280
  case "ncommit": {
253
- if (!isHash(r.commit)) return null;
254
- if (Object.keys(r).length !== 3) return null;
281
+ if (!isHash(r.commit)) return "RECORD_BAD_HASH";
282
+ if (Object.keys(r).length !== 3) return "RECORD_EXTRA_KEY";
255
283
  return r;
256
284
  }
257
285
  case "name": {
258
- if (!onlyKeys(r, NAME_KEYS)) return null;
259
- if (!isName(r.name)) return null;
260
- if (r.salt !== void 0 && (typeof r.salt !== "string" || !SALT_RE.test(r.salt))) return null;
286
+ if (!onlyKeys(r, NAME_KEYS)) return "RECORD_EXTRA_KEY";
287
+ if (fault = nameFault(r.name)) return fault;
288
+ if (r.salt !== void 0 && (typeof r.salt !== "string" || !SALT_RE.test(r.salt))) return "RECORD_BAD_SALT";
261
289
  return r;
262
290
  }
263
291
  case "nfinalize": {
264
- if (!onlyKeys(r, NFINALIZE_KEYS)) return null;
265
- if (!isName(r.name)) return null;
266
- if (typeof r.salt !== "string" || !SALT_RE.test(r.salt)) return null;
292
+ if (!onlyKeys(r, NFINALIZE_KEYS)) return "RECORD_EXTRA_KEY";
293
+ if (fault = nameFault(r.name)) return fault;
294
+ if (typeof r.salt !== "string" || !SALT_RE.test(r.salt)) return "RECORD_BAD_SALT";
267
295
  return r;
268
296
  }
269
297
  case "nxfer": {
270
- if (!isName(r.name) || !isAddr(r.to)) return null;
271
- if (Object.keys(r).length !== 4) return null;
298
+ if (fault = nameFault(r.name)) return fault;
299
+ if (!isAddr(r.to)) return "RECORD_BAD_ADDRESS";
300
+ if (Object.keys(r).length !== 4) return "RECORD_EXTRA_KEY";
272
301
  return r;
273
302
  }
274
303
  case "nset": {
275
- if (!isName(r.name) || !isAddr(r.addr)) return null;
276
- if (Object.keys(r).length !== 4) return null;
304
+ if (fault = nameFault(r.name)) return fault;
305
+ if (!isAddr(r.addr)) return "RECORD_BAD_ADDRESS";
306
+ if (Object.keys(r).length !== 4) return "RECORD_EXTRA_KEY";
277
307
  return r;
278
308
  }
279
309
  // ── v1.5 ──
280
310
  case "nrenew": {
281
- if (!isName(r.name)) return null;
282
- if (Object.keys(r).length !== 3) return null;
311
+ if (fault = nameFault(r.name)) return fault;
312
+ if (Object.keys(r).length !== 3) return "RECORD_EXTRA_KEY";
283
313
  return r;
284
314
  }
285
315
  case "nprofile": {
286
- if (!onlyKeys(r, NPROFILE_KEYS)) return null;
287
- if (!isName(r.name)) return null;
316
+ if (!onlyKeys(r, NPROFILE_KEYS)) return "RECORD_EXTRA_KEY";
317
+ if (fault = nameFault(r.name)) return fault;
288
318
  const p = r.p;
289
- if (!p || typeof p !== "object" || Array.isArray(p)) return null;
319
+ if (!p || typeof p !== "object" || Array.isArray(p)) return "RECORD_BAD_SHAPE";
290
320
  const keys = Object.keys(p);
291
- if (keys.length > PROFILE_MAX_KEYS) return null;
321
+ if (keys.length > PROFILE_MAX_KEYS) return "RECORD_PROFILE_TOO_MANY_KEYS";
292
322
  for (const k of keys) {
293
- if (!PKEY.test(k)) return null;
323
+ if (!PKEY.test(k)) return "RECORD_PROFILE_BAD_KEY";
294
324
  const val = p[k];
295
- if (typeof val !== "string") return null;
296
- if (new TextEncoder().encode(val).length > PROFILE_MAX_VALUE_BYTES) return null;
325
+ if (typeof val !== "string") return "RECORD_PROFILE_BAD_VALUE";
326
+ if (new TextEncoder().encode(val).length > PROFILE_MAX_VALUE_BYTES) return "RECORD_PROFILE_VALUE_TOO_LONG";
297
327
  }
298
328
  return r;
299
329
  }
300
330
  case "tmeta": {
301
- if (!isTicker(r.ticker)) return null;
302
- if (typeof r.hash !== "string" || !HASH_RE.test(r.hash)) return null;
303
- if (Object.keys(r).length !== 4) return null;
331
+ if (!isTicker(r.ticker)) return "RECORD_BAD_TICKER";
332
+ if (typeof r.hash !== "string" || !HASH_RE.test(r.hash)) return "RECORD_BAD_HASH";
333
+ if (Object.keys(r).length !== 4) return "RECORD_EXTRA_KEY";
304
334
  return r;
305
335
  }
306
336
  case "fclaim": {
307
- if (!onlyKeys(r, FCLAIM_KEYS)) return null;
308
- if (!isHash(r.offer)) return null;
337
+ if (!onlyKeys(r, FCLAIM_KEYS)) return "RECORD_EXTRA_KEY";
338
+ if (!isHash(r.offer)) return "RECORD_BAD_HASH";
309
339
  return r;
310
340
  }
311
341
  default:
312
- return null;
342
+ return "RECORD_UNKNOWN_TYPE";
313
343
  }
314
344
  }
345
+ var RecordError = class extends Error {
346
+ code;
347
+ constructor(code) {
348
+ super(`record does not validate against CONVENTION.md (${code})`);
349
+ this.name = "RecordError";
350
+ this.code = code;
351
+ }
352
+ };
315
353
  function buildRecord(record) {
316
354
  const uri = canonicalJson(record);
317
355
  const ph = payloadHash(record);
318
- const back = parseRecord(uri, ph);
319
- if (back === null) throw new Error("record does not validate against CONVENTION.md");
356
+ const back = explainRecord(uri, ph);
357
+ if (!back.ok) throw new RecordError(back.code);
320
358
  return { record, uri, payloadHash: ph };
321
359
  }
322
360
  var deploy = (r) => buildRecord({ v: 1, t: "deploy", ...r });
@@ -342,33 +380,12 @@ function ptAmt(v) {
342
380
  var effExpiry = (e, height) => e.height >= V22_HEIGHT ? e.expiresEpoch : height >= V21_HEIGHT ? Math.min(e.expiresEpoch, epochOf(e.height) + MAX_OFFER_EPOCHS) : e.expiresEpoch;
343
381
  var claimGrace = (o) => o.claimUntilHeight !== void 0 ? claimGraceOf(o.claimUntilHeight, o.claimTxid) : 0;
344
382
  var claimHeld = (o, height) => o.claimedBy !== void 0 && o.claimUntilHeight !== void 0 && height < o.claimUntilHeight + claimGrace(o);
345
- function createContext() {
383
+ function createContext(store) {
346
384
  const tokens = /* @__PURE__ */ new Map();
347
385
  const balances = /* @__PURE__ */ new Map();
348
- const names = /* @__PURE__ */ new Map();
349
386
  const commits = /* @__PURE__ */ new Map();
350
- const recaptures = /* @__PURE__ */ new Map();
351
- const offers = /* @__PURE__ */ new Map();
352
387
  const offerLock = /* @__PURE__ */ new Map();
353
- const bids = /* @__PURE__ */ new Map();
354
- const openOffers = /* @__PURE__ */ new Set();
355
- const openBids = /* @__PURE__ */ new Set();
356
- const pendingNames = /* @__PURE__ */ new Set();
357
- const setOfferStatus = (o, status) => {
358
- o.status = status;
359
- if (status === "open") openOffers.add(o.id);
360
- else openOffers.delete(o.id);
361
- };
362
- const setBidStatus = (b, status) => {
363
- b.status = status;
364
- if (status === "open") openBids.add(b.id);
365
- else openBids.delete(b.id);
366
- };
367
- const putName = (nm, n) => {
368
- names.set(nm, n);
369
- if (n.pending) pendingNames.add(nm);
370
- else pendingNames.delete(nm);
371
- };
388
+ const { names, recaptures, offers, bids, setOfferStatus, setBidStatus, putName } = store;
372
389
  const fclaims = /* @__PURE__ */ new Map();
373
390
  const log = [];
374
391
  const bal = (ticker, addr) => {
@@ -384,7 +401,6 @@ function createContext() {
384
401
  }
385
402
  return b;
386
403
  };
387
- const note = (e, id, kind, ok, why) => log.push({ height: e.height, pos: e.pos, id, kind, ok, ...why ? { note: why } : {} });
388
404
  const releaseGive = (o) => {
389
405
  if (isNameGive(o.give)) {
390
406
  const n = names.get(o.give.name);
@@ -396,66 +412,27 @@ function createContext() {
396
412
  b.available += amt;
397
413
  }
398
414
  };
399
- const sweepExpired = (height) => {
400
- const ep = epochOf(height);
401
- for (const id of [...openOffers]) {
402
- const o = offers.get(id);
403
- if (!o || o.status !== "open") {
404
- openOffers.delete(id);
405
- continue;
406
- }
407
- if (ep > effExpiry(o, height)) {
408
- releaseGive(o);
409
- setOfferStatus(o, "expired");
410
- }
411
- }
412
- for (const id of [...openBids]) {
413
- const b = bids.get(id);
414
- if (!b || b.status !== "open") {
415
- openBids.delete(id);
416
- continue;
417
- }
418
- if (ep > effExpiry(b, height)) setBidStatus(b, "expired");
419
- }
420
- for (const nm of [...pendingNames]) {
421
- const n = names.get(nm);
422
- if (!n || !n.pending) {
423
- pendingNames.delete(nm);
424
- continue;
425
- }
426
- if (n.finalizeBy !== void 0 && height > n.finalizeBy) {
427
- names.delete(nm);
428
- pendingNames.delete(nm);
429
- }
430
- }
431
- for (const nm of [...recaptures.keys()]) {
432
- const r = recaptures.get(nm);
433
- if (height > r.finalizeBy) recaptures.delete(nm);
434
- }
435
- };
415
+ const sweepExpired = (height) => store.sweep(height, releaseGive);
436
416
  const markBidDone = (o, buyer) => {
437
417
  if (!o.bid) return;
438
418
  const b = bids.get(o.bid);
439
419
  if (b && b.status === "open" && b.bidder === buyer) setBidStatus(b, "done");
440
420
  };
441
421
  const voidOpenNameOffers = (name, height) => {
442
- for (const o of offers.values()) if (o.status === "open" && isNameGive(o.give) && o.give.name === name) {
443
- if (height >= V28_HEIGHT && o.claimTxid !== void 0 && claimHeld(o, height)) continue;
422
+ for (const o of store.voidTargets(name, height)) {
444
423
  releaseGive(o);
445
424
  setOfferStatus(o, "cancelled");
446
425
  }
447
426
  };
448
- const liveHoldCount = (who, height) => {
449
- let liveN = 0;
450
- for (const x of offers.values()) if (x.claimedBy === who && claimHeld(x, height) && (height < V29_HEIGHT || x.status === "open")) liveN++;
451
- return liveN;
452
- };
453
427
  const releaseGiveLock = (o, who, amt) => {
454
428
  const t = o.give.ticker;
455
429
  bal(t, o.seller).locked -= amt;
456
430
  bal(t, who).available += amt;
457
431
  offerLock.delete(o.id);
458
432
  };
433
+ const entry = (e, id, kind, ok, code, why) => log.push({ height: e.height, pos: e.pos, id, kind, ok, code, ...why ? { note: why } : {} });
434
+ const applied = (e, id, kind, code, why) => entry(e, id, kind, true, code, why);
435
+ const refused = (e, id, kind, code, why) => entry(e, id, kind, false, code, why);
459
436
  return {
460
437
  tokens,
461
438
  balances,
@@ -465,21 +442,19 @@ function createContext() {
465
442
  offers,
466
443
  offerLock,
467
444
  bids,
468
- openOffers,
469
- openBids,
470
- pendingNames,
471
445
  fclaims,
472
446
  log,
447
+ store,
473
448
  setOfferStatus,
474
449
  setBidStatus,
475
450
  putName,
476
451
  bal,
477
- note,
452
+ applied,
453
+ refused,
478
454
  releaseGive,
479
455
  sweepExpired,
480
456
  markBidDone,
481
457
  voidOpenNameOffers,
482
- liveHoldCount,
483
458
  releaseGiveLock,
484
459
  feesPaid: 0n,
485
460
  // v1.4 fill-before-cancel: at V14_HEIGHT+ a cancel/ocancel's EFFECT is deferred to the block
@@ -495,13 +470,13 @@ function createContext() {
495
470
  // src/resolve/attest.ts
496
471
  var openFillReject = (o, height, who, targetId) => {
497
472
  if (!(height >= V13_HEIGHT && !o.taker)) return void 0;
498
- if (height < V17_HEIGHT) return "v1.3: open CSD-quoted fills disabled (offer must be taker-bound)";
499
- if (height >= V28_HEIGHT && o.claimTxid !== void 0 && targetId === o.id) return "v2.8: fill the fclaim txid, not the offer";
500
- if (!(claimHeld(o, height) && who === o.claimedBy)) return "v1.7: open offer \u2014 claim it first (no live claim by you)";
473
+ if (height < V17_HEIGHT) return { code: "FILL_OPEN_LANE_CLOSED", note: "v1.3: open CSD-quoted fills disabled (offer must be taker-bound)" };
474
+ 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" };
475
+ 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)" };
501
476
  return void 0;
502
477
  };
503
- var deliverNameToBuyer = (n, who, ev) => {
504
- n.owner = who;
478
+ var deliverNameToBuyer = (c, name, n, who, ev) => {
479
+ c.store.setNameOwner(name, n, who);
505
480
  n.locked = false;
506
481
  n.addr = void 0;
507
482
  n.profile = void 0;
@@ -514,7 +489,7 @@ var deliverNameToBuyer = (n, who, ev) => {
514
489
  }
515
490
  };
516
491
  function applyAttest(c, ev) {
517
- const { offers, fclaims, bids, note, setBidStatus } = c;
492
+ const { offers, fclaims, bids, applied, refused, setBidStatus } = c;
518
493
  const who = ev.attester.toLowerCase();
519
494
  let o = offers.get(ev.proposalId);
520
495
  if (!o && ev.height >= V28_HEIGHT && ev.score === SCORE_FILL) {
@@ -526,21 +501,21 @@ function applyAttest(c, ev) {
526
501
  }
527
502
  if (!o) {
528
503
  if (ev.height >= V28_HEIGHT && ev.score === SCORE_FILL && fclaims.has(ev.proposalId)) {
529
- note(ev, ev.txid, "fill", false, "fclaim not current (denied or superseded): no delivery, denied-fclaim fill");
504
+ refused(ev, ev.txid, "fill", "FILL_FCLAIM_NOT_CURRENT", "fclaim not current (denied or superseded): no delivery, denied-fclaim fill");
530
505
  return;
531
506
  }
532
507
  const b = bids.get(ev.proposalId);
533
508
  if (b && ev.score === SCORE_CANCEL) {
534
509
  if (who !== b.bidder) {
535
- note(ev, ev.txid, "bidcancel", false, "only bidder may cancel");
510
+ refused(ev, ev.txid, "bidcancel", "BID_NOT_BIDDER", "only bidder may cancel");
536
511
  return;
537
512
  }
538
513
  if (b.status !== "open") {
539
- note(ev, ev.txid, "bidcancel", false, `bid ${b.status}`);
514
+ refused(ev, ev.txid, "bidcancel", "BID_NOT_OPEN", `bid ${b.status}`);
540
515
  return;
541
516
  }
542
517
  setBidStatus(b, "cancelled");
543
- note(ev, ev.txid, "bidcancel", true);
518
+ applied(ev, ev.txid, "bidcancel", "BID_CANCELLED");
544
519
  }
545
520
  return;
546
521
  }
@@ -551,95 +526,95 @@ function applyAttest(c, ev) {
551
526
  else if (ev.height >= V17_HEIGHT && ev.score === SCORE_CLAIM) applyLegacyClaim(c, ev, o, who);
552
527
  }
553
528
  function applyCancel(c, ev, o, who) {
554
- const { note, releaseGive, setOfferStatus } = c;
529
+ const { applied, refused, releaseGive, setOfferStatus } = c;
555
530
  if (who !== o.seller) {
556
- note(ev, ev.txid, "cancel", false, "only seller may cancel");
531
+ refused(ev, ev.txid, "cancel", "OFFER_NOT_SELLER", "only seller may cancel");
557
532
  return;
558
533
  }
559
534
  if (o.status !== "open") {
560
- note(ev, ev.txid, "cancel", false, `offer ${o.status}`);
535
+ refused(ev, ev.txid, "cancel", "OFFER_NOT_OPEN", `offer ${o.status}`);
561
536
  return;
562
537
  }
563
538
  if (o.taker !== void 0 && o.height >= V28_HEIGHT) {
564
- note(ev, ev.txid, "cancel", false, "v2.8: taker-bound offers are firm quotes (uncancellable)");
539
+ refused(ev, ev.txid, "cancel", "OFFER_FIRM_QUOTE", "v2.8: taker-bound offers are firm quotes (uncancellable)");
565
540
  return;
566
541
  }
567
542
  if (ev.height >= V14_HEIGHT) {
568
543
  c.pendingCancels.push(() => {
569
544
  if (ev.height >= V28_HEIGHT && o.claimTxid !== void 0 && claimHeld(o, ev.height)) {
570
- note(ev, ev.txid, "cancel", false, "v2.8: frozen (fclaim hold live)");
545
+ refused(ev, ev.txid, "cancel", "OFFER_CANCEL_HOLD_LIVE", "v2.8: frozen (fclaim hold live)");
571
546
  return;
572
547
  }
573
548
  if (o.status === "open") {
574
549
  releaseGive(o);
575
550
  setOfferStatus(o, "cancelled");
576
- note(ev, ev.txid, "cancel", true);
577
- } else note(ev, ev.txid, "cancel", false, "superseded by same-block fill (v1.4)");
551
+ applied(ev, ev.txid, "cancel", "OFFER_CANCELLED");
552
+ } else refused(ev, ev.txid, "cancel", "OFFER_CLOSED_BEFORE_CANCEL", "superseded by same-block fill (v1.4)");
578
553
  });
579
554
  } else {
580
555
  releaseGive(o);
581
556
  setOfferStatus(o, "cancelled");
582
- note(ev, ev.txid, "cancel", true);
557
+ applied(ev, ev.txid, "cancel", "OFFER_CANCELLED");
583
558
  }
584
559
  }
585
560
  function applyTokenFill(c, ev, o, who) {
586
- const { tokens, names, offerLock, bal, note, setOfferStatus, markBidDone, releaseGiveLock } = c;
561
+ const { tokens, names, offerLock, bal, applied, refused, setOfferStatus, markBidDone, releaseGiveLock } = c;
587
562
  if (o.status !== "open") {
588
- note(ev, ev.txid, "fill", false, `offer ${o.status}`);
563
+ refused(ev, ev.txid, "fill", "OFFER_NOT_OPEN", `offer ${o.status}`);
589
564
  return;
590
565
  }
591
566
  if (o.taker && who !== o.taker) {
592
- note(ev, ev.txid, "fill", false, "taker-bound offer");
567
+ refused(ev, ev.txid, "fill", "FILL_NOT_TAKER", "taker-bound offer");
593
568
  return;
594
569
  }
595
570
  if (ev.confidence !== CONF_TOKEN_FILL) {
596
- note(ev, ev.txid, "fill", false, "token fill requires confidence marker");
571
+ refused(ev, ev.txid, "fill", "FILL_NO_TOKEN_MARKER", "token fill requires confidence marker");
597
572
  return;
598
573
  }
599
574
  if (!tokens.has(o.want.ticker)) {
600
- note(ev, ev.txid, "fill", false, "want ticker does not exist");
575
+ refused(ev, ev.txid, "fill", "TOKEN_UNKNOWN", "want ticker does not exist");
601
576
  return;
602
577
  }
603
578
  const amt = BigInt(o.want.amount);
604
579
  const fee = o.feeBps ? tradeFee(amt, o.feeBps) : 0n;
605
580
  const buyer = bal(o.want.ticker, who);
606
581
  if (buyer.available < amt + fee) {
607
- note(ev, ev.txid, "fill", false, "insufficient want-token balance");
582
+ refused(ev, ev.txid, "fill", "TOKEN_BALANCE_LOW", "insufficient want-token balance");
608
583
  return;
609
584
  }
610
585
  const giveName = isNameGive(o.give) ? names.get(o.give.name) : void 0;
611
586
  if (isNameGive(o.give) && !giveName) {
612
- note(ev, ev.txid, "fill", false, "name vanished (consensus violation)");
587
+ refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "name vanished (consensus violation)");
613
588
  return;
614
589
  }
615
590
  const giveLock = isNameGive(o.give) ? void 0 : offerLock.get(o.id);
616
591
  if (!isNameGive(o.give) && giveLock === void 0) {
617
- note(ev, ev.txid, "fill", false, "offer lock missing");
592
+ refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "offer lock missing");
618
593
  return;
619
594
  }
620
595
  buyer.available -= amt + fee;
621
596
  bal(o.want.ticker, o.want.payto).available += amt;
622
597
  if (fee > 0n) bal(o.want.ticker, TREASURY_ADDR).available += fee;
623
- if (isNameGive(o.give)) deliverNameToBuyer(giveName, who, ev);
598
+ if (isNameGive(o.give)) deliverNameToBuyer(c, o.give.name, giveName, who, ev);
624
599
  else releaseGiveLock(o, who, giveLock);
625
600
  setOfferStatus(o, "filled");
626
601
  o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: amt.toString(), fee: fee.toString() };
627
602
  markBidDone(o, who);
628
- note(ev, ev.txid, "fill", true);
603
+ applied(ev, ev.txid, "fill", "FILL_APPLIED");
629
604
  }
630
605
  function applyPartialFill(c, ev, o, who) {
631
- const { offerLock, bal, note, setOfferStatus, markBidDone } = c;
606
+ const { offerLock, bal, applied, refused, setOfferStatus, markBidDone } = c;
632
607
  if (o.status !== "open") {
633
- note(ev, ev.txid, "fill", false, `offer ${o.status}`);
608
+ refused(ev, ev.txid, "fill", "OFFER_NOT_OPEN", `offer ${o.status}`);
634
609
  return;
635
610
  }
636
611
  if (o.taker && who !== o.taker) {
637
- note(ev, ev.txid, "fill", false, "taker-bound offer");
612
+ refused(ev, ev.txid, "fill", "FILL_NOT_TAKER", "taker-bound offer");
638
613
  return;
639
614
  }
640
615
  const blk = openFillReject(o, ev.height, who, ev.proposalId);
641
616
  if (blk) {
642
- note(ev, ev.txid, "fill", false, blk);
617
+ refused(ev, ev.txid, "fill", blk.code, blk.note);
643
618
  return;
644
619
  }
645
620
  const pt = ev.paidTo ?? {};
@@ -650,13 +625,13 @@ function applyPartialFill(c, ev, o, who) {
650
625
  const minV = BigInt(o.min);
651
626
  const effMin = remaining < minV ? remaining : minV;
652
627
  if (X < effMin) {
653
- note(ev, ev.txid, "fill", false, "payment below offer min");
628
+ refused(ev, ev.txid, "fill", "FILL_BELOW_MIN", "payment below offer min");
654
629
  return;
655
630
  }
656
631
  const x = X < remaining ? X : remaining;
657
632
  const fee = o.feeBps ? tradeFee(x, o.feeBps) : 0n;
658
633
  if (ptAmt(pt[TREASURY_ADDR]) < fee) {
659
- note(ev, ev.txid, "fill", false, "protocol fee unpaid");
634
+ refused(ev, ev.txid, "fill", "TREASURY_FEE_UNPAID", "protocol fee unpaid");
660
635
  return;
661
636
  }
662
637
  const giveTotal = BigInt(o.give.amount);
@@ -665,12 +640,12 @@ function applyPartialFill(c, ev, o, who) {
665
640
  const newDelivered = giveTotal * newPaid / want;
666
641
  const out = newDelivered - deliveredSoFar;
667
642
  if (out === 0n) {
668
- note(ev, ev.txid, "fill", false, "fill too small to deliver any tokens");
643
+ refused(ev, ev.txid, "fill", "FILL_ZERO_DELIVERY", "fill too small to deliver any tokens");
669
644
  return;
670
645
  }
671
646
  const lock = offerLock.get(o.id);
672
647
  if (lock === void 0) {
673
- note(ev, ev.txid, "fill", false, "offer lock missing");
648
+ refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "offer lock missing");
674
649
  return;
675
650
  }
676
651
  bal(o.give.ticker, o.seller).locked -= out;
@@ -687,21 +662,21 @@ function applyPartialFill(c, ev, o, who) {
687
662
  offerLock.delete(o.id);
688
663
  markBidDone(o, who);
689
664
  }
690
- note(ev, ev.txid, "fill", true, `partial ${x}/${want}`);
665
+ applied(ev, ev.txid, "fill", "FILL_PARTIAL", `partial ${x}/${want}`);
691
666
  }
692
667
  function applyFill(c, ev, o, who) {
693
- const { names, offerLock, note, setOfferStatus, markBidDone, releaseGiveLock } = c;
668
+ const { names, offerLock, applied, refused, setOfferStatus, markBidDone, releaseGiveLock } = c;
694
669
  if (o.status !== "open") {
695
- note(ev, ev.txid, "fill", false, `offer ${o.status}`);
670
+ refused(ev, ev.txid, "fill", "OFFER_NOT_OPEN", `offer ${o.status}`);
696
671
  return;
697
672
  }
698
673
  if (o.taker && who !== o.taker) {
699
- note(ev, ev.txid, "fill", false, "taker-bound offer");
674
+ refused(ev, ev.txid, "fill", "FILL_NOT_TAKER", "taker-bound offer");
700
675
  return;
701
676
  }
702
677
  const blk = openFillReject(o, ev.height, who, ev.proposalId);
703
678
  if (blk) {
704
- note(ev, ev.txid, "fill", false, blk);
679
+ refused(ev, ev.txid, "fill", blk.code, blk.note);
705
680
  return;
706
681
  }
707
682
  const pt = ev.paidTo ?? {};
@@ -716,25 +691,25 @@ function applyFill(c, ev, o, who) {
716
691
  if (rebate > 0n) addNeed(o.seller, rebate);
717
692
  let unpaid;
718
693
  for (const [addr, amt] of need) if (ptAmt(pt[addr]) < amt) {
719
- unpaid = addr === TREASURY_ADDR ? "protocol fee unpaid" : rebate > 0n && addr === o.seller ? "maker rebate unpaid (v1.6)" : "payment below want.value";
694
+ 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" };
720
695
  break;
721
696
  }
722
697
  if (unpaid) {
723
- note(ev, ev.txid, "fill", false, unpaid);
698
+ refused(ev, ev.txid, "fill", unpaid.code, unpaid.note);
724
699
  return;
725
700
  }
726
701
  const paid = ptAmt(pt[o.want.payto]);
727
702
  if (isNameGive(o.give)) {
728
703
  const n = names.get(o.give.name);
729
704
  if (!n) {
730
- note(ev, ev.txid, "fill", false, "name vanished (consensus violation)");
705
+ refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "name vanished (consensus violation)");
731
706
  return;
732
707
  }
733
- deliverNameToBuyer(n, who, ev);
708
+ deliverNameToBuyer(c, o.give.name, n, who, ev);
734
709
  } else {
735
710
  const amt = offerLock.get(o.id);
736
711
  if (amt === void 0) {
737
- note(ev, ev.txid, "fill", false, "offer lock missing");
712
+ refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "offer lock missing");
738
713
  return;
739
714
  }
740
715
  releaseGiveLock(o, who, amt);
@@ -743,41 +718,464 @@ function applyFill(c, ev, o, who) {
743
718
  setOfferStatus(o, "filled");
744
719
  o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: paid.toString(), fee: fee.toString() };
745
720
  markBidDone(o, who);
746
- note(ev, ev.txid, "fill", true);
721
+ applied(ev, ev.txid, "fill", "FILL_APPLIED");
747
722
  }
748
723
  function applyLegacyClaim(c, ev, o, who) {
749
- const { note, liveHoldCount } = c;
724
+ const { applied, refused, store } = c;
750
725
  if (ev.height >= V28_HEIGHT) {
751
- note(ev, ev.txid, "claim", false, "v2.8: claims are fclaim proposals now");
726
+ refused(ev, ev.txid, "claim", "CLAIM_LEGACY_SUNSET", "v2.8: claims are fclaim proposals now");
752
727
  return;
753
728
  }
754
729
  if (o.status !== "open") {
755
- note(ev, ev.txid, "claim", false, `offer ${o.status}`);
730
+ refused(ev, ev.txid, "claim", "OFFER_NOT_OPEN", `offer ${o.status}`);
756
731
  return;
757
732
  }
758
733
  if (o.taker) {
759
- note(ev, ev.txid, "claim", false, "taker-bound offer needs no claim");
734
+ refused(ev, ev.txid, "claim", "CLAIM_TAKER_BOUND", "taker-bound offer needs no claim");
760
735
  return;
761
736
  }
762
737
  if (isTokenWant(o.want)) {
763
- note(ev, ev.txid, "claim", false, "claims are for CSD-priced offers (token offers are no-op-safe)");
738
+ refused(ev, ev.txid, "claim", "CLAIM_TOKEN_PRICED", "claims are for CSD-priced offers (token offers are no-op-safe)");
764
739
  return;
765
740
  }
766
741
  if (claimHeld(o, ev.height)) {
767
- note(ev, ev.txid, "claim", false, "offer already claimed (hold live)");
742
+ refused(ev, ev.txid, "claim", "CLAIM_HOLD_LIVE", "offer already claimed (hold live)");
768
743
  return;
769
744
  }
770
745
  if (o.claimedBy === who && o.claimUntilHeight !== void 0 && ev.height < o.claimUntilHeight + claimGrace(o) + CLAIM_COOLDOWN_BLOCKS) {
771
- note(ev, ev.txid, "claim", false, "claim cooldown (you just held this offer)");
746
+ refused(ev, ev.txid, "claim", "CLAIM_COOLDOWN", "claim cooldown (you just held this offer)");
772
747
  return;
773
748
  }
774
- if (liveHoldCount(who, ev.height) >= MAX_ACTIVE_CLAIMS) {
775
- note(ev, ev.txid, "claim", false, `max ${MAX_ACTIVE_CLAIMS} live claims per address`);
749
+ if (store.liveHoldCount(who, ev.height) >= MAX_ACTIVE_CLAIMS) {
750
+ refused(ev, ev.txid, "claim", "CAP_LIVE_HOLDS", `max ${MAX_ACTIVE_CLAIMS} live claims per address`);
776
751
  return;
777
752
  }
778
- o.claimedBy = who;
779
- o.claimUntilHeight = ev.height + claimWindowAt(ev.height);
780
- note(ev, ev.txid, "claim", true);
753
+ store.setClaim(o, who, ev.height + claimWindowAt(ev.height));
754
+ applied(ev, ev.txid, "claim", "CLAIM_GRANTED");
755
+ }
756
+
757
+ // src/resolve/minqueue.ts
758
+ var MinQueue = class {
759
+ keys = [];
760
+ seqs = [];
761
+ ids = [];
762
+ pushed = 0;
763
+ get size() {
764
+ return this.ids.length;
765
+ }
766
+ /** Adds an entry. A NaN key is not stored: no comparison with NaN is true, so such an item is never due. */
767
+ push(key, id) {
768
+ if (key !== key) return;
769
+ let i = this.ids.length;
770
+ this.keys.push(key);
771
+ this.seqs.push(++this.pushed);
772
+ this.ids.push(id);
773
+ while (i > 0) {
774
+ const p = i - 1 >> 1;
775
+ if (!this.less(i, p)) break;
776
+ this.swap(i, p);
777
+ i = p;
778
+ }
779
+ }
780
+ /** Removes every entry whose key is below `limit` and appends its id to `out`, smallest key first. */
781
+ popBelow(limit, out) {
782
+ while (this.ids.length > 0 && this.keys[0] < limit) {
783
+ out.push(this.ids[0]);
784
+ this.swap(0, this.ids.length - 1);
785
+ this.keys.pop();
786
+ this.seqs.pop();
787
+ this.ids.pop();
788
+ let i = 0;
789
+ for (; ; ) {
790
+ const l = 2 * i + 1, r = l + 1;
791
+ let m = i;
792
+ if (l < this.ids.length && this.less(l, m)) m = l;
793
+ if (r < this.ids.length && this.less(r, m)) m = r;
794
+ if (m === i) break;
795
+ this.swap(i, m);
796
+ i = m;
797
+ }
798
+ }
799
+ }
800
+ /** Every stored (key, id), in no particular order: for the replay's check mode. */
801
+ *entries() {
802
+ for (let i = 0; i < this.ids.length; i++) yield [this.keys[i], this.ids[i]];
803
+ }
804
+ less(i, j) {
805
+ const a = this.keys[i], b = this.keys[j];
806
+ return a < b || a === b && this.seqs[i] < this.seqs[j];
807
+ }
808
+ swap(i, j) {
809
+ const k = this.keys[i], s = this.seqs[i], d = this.ids[i];
810
+ this.keys[i] = this.keys[j];
811
+ this.seqs[i] = this.seqs[j];
812
+ this.ids[i] = this.ids[j];
813
+ this.keys[j] = k;
814
+ this.seqs[j] = s;
815
+ this.ids[j] = d;
816
+ }
817
+ };
818
+
819
+ // src/resolve/store.ts
820
+ function createStore(opts = {}) {
821
+ const check = opts.check === true;
822
+ const checkEvery = Math.max(1, Math.floor(opts.checkEvery ?? 1));
823
+ const stats = opts.stats ?? { visits: 0 };
824
+ const offers = /* @__PURE__ */ new Map();
825
+ const bids = /* @__PURE__ */ new Map();
826
+ const names = /* @__PURE__ */ new Map();
827
+ const recaptures = /* @__PURE__ */ new Map();
828
+ const openOffers = /* @__PURE__ */ new Set();
829
+ const openBids = /* @__PURE__ */ new Set();
830
+ const pendingNames = /* @__PURE__ */ new Set();
831
+ let stamp = 0;
832
+ const openOfferAt = /* @__PURE__ */ new Map(), openBidAt = /* @__PURE__ */ new Map();
833
+ const pendingAt = /* @__PURE__ */ new Map(), recaptureAt = /* @__PURE__ */ new Map();
834
+ const offerAt = /* @__PURE__ */ new Map();
835
+ const offerQ = new MinQueue(), bidQ = new MinQueue(), nameQ = new MinQueue(), recaptureQ = new MinQueue();
836
+ let maxSweep = -Infinity;
837
+ const pendingBy = /* @__PURE__ */ new Map(), recaptureBy = /* @__PURE__ */ new Map();
838
+ const holdsBy = /* @__PURE__ */ new Map();
839
+ let maxHoldRead = -Infinity;
840
+ const bySeller = /* @__PURE__ */ new Map(), bySellerAsset = /* @__PURE__ */ new Map(), byName = /* @__PURE__ */ new Map();
841
+ const assetKey = (seller, g) => `${seller}\0${isNameGive(g) ? `n\0${g.name}` : `t\0${g.ticker}`}`;
842
+ const addTo = (m, k, v) => {
843
+ let s = m.get(k);
844
+ if (!s) {
845
+ s = /* @__PURE__ */ new Set();
846
+ m.set(k, s);
847
+ }
848
+ s.add(v);
849
+ };
850
+ const regimeHeight = () => maxSweep >= V21_HEIGHT ? V21_HEIGHT : V21_HEIGHT - 1;
851
+ const addOffer = (o) => {
852
+ if (!offers.has(o.id)) offerAt.set(o.id, ++stamp);
853
+ offers.set(o.id, o);
854
+ if (!openOffers.has(o.id)) {
855
+ openOffers.add(o.id);
856
+ openOfferAt.set(o.id, ++stamp);
857
+ }
858
+ offerQ.push(effExpiry(o, regimeHeight()), o.id);
859
+ if (!(o.taker !== void 0 && o.height >= V28_HEIGHT)) {
860
+ addTo(bySeller, o.seller, o.id);
861
+ addTo(bySellerAsset, assetKey(o.seller, o.give), o.id);
862
+ }
863
+ if (isNameGive(o.give)) addTo(byName, o.give.name, o.id);
864
+ };
865
+ const setClaim = (o, who, untilHeight, txid) => {
866
+ const m = o;
867
+ m.claimedBy = who;
868
+ m.claimUntilHeight = untilHeight;
869
+ if (txid !== void 0) m.claimTxid = txid;
870
+ addTo(holdsBy, who, o.id);
871
+ };
872
+ const setOfferStatus = (o, status) => {
873
+ o.status = status;
874
+ openOffers.delete(o.id);
875
+ };
876
+ const addBid = (b) => {
877
+ bids.set(b.id, b);
878
+ if (!openBids.has(b.id)) {
879
+ openBids.add(b.id);
880
+ openBidAt.set(b.id, ++stamp);
881
+ }
882
+ bidQ.push(effExpiry(b, regimeHeight()), b.id);
883
+ };
884
+ const setBidStatus = (b, status) => {
885
+ b.status = status;
886
+ openBids.delete(b.id);
887
+ };
888
+ const putName = (nm, n) => {
889
+ names.set(nm, n);
890
+ if (n.pending) {
891
+ if (!pendingNames.has(nm)) {
892
+ pendingNames.add(nm);
893
+ pendingAt.set(nm, ++stamp);
894
+ }
895
+ if (n.finalizeBy !== void 0) nameQ.push(n.finalizeBy, nm);
896
+ addTo(pendingBy, n.owner, nm);
897
+ } else pendingNames.delete(nm);
898
+ };
899
+ const setNameOwner = (nm, n, owner) => {
900
+ n.owner = owner;
901
+ if (n.pending) addTo(pendingBy, owner, nm);
902
+ };
903
+ const finalizeName = (nm, n) => {
904
+ delete n.pending;
905
+ delete n.finalizeBy;
906
+ pendingNames.delete(nm);
907
+ };
908
+ const putRecapture = (nm, r) => {
909
+ if (!recaptures.has(nm)) recaptureAt.set(nm, ++stamp);
910
+ recaptures.set(nm, r);
911
+ recaptureQ.push(r.finalizeBy, nm);
912
+ addTo(recaptureBy, r.owner, nm);
913
+ };
914
+ const deleteRecapture = (nm) => {
915
+ recaptures.delete(nm);
916
+ };
917
+ const walkSweep = (height, expireOffer) => {
918
+ const ep = epochOf(height);
919
+ stats.visits += openOffers.size + openBids.size + pendingNames.size + recaptures.size;
920
+ for (const id of [...openOffers]) {
921
+ const o = offers.get(id);
922
+ if (!o || o.status !== "open") {
923
+ openOffers.delete(id);
924
+ continue;
925
+ }
926
+ if (ep > effExpiry(o, height)) {
927
+ expireOffer(o);
928
+ setOfferStatus(o, "expired");
929
+ }
930
+ }
931
+ for (const id of [...openBids]) {
932
+ const b = bids.get(id);
933
+ if (!b || b.status !== "open") {
934
+ openBids.delete(id);
935
+ continue;
936
+ }
937
+ if (ep > effExpiry(b, height)) setBidStatus(b, "expired");
938
+ }
939
+ for (const nm of [...pendingNames]) {
940
+ const n = names.get(nm);
941
+ if (!n || !n.pending) {
942
+ pendingNames.delete(nm);
943
+ continue;
944
+ }
945
+ if (n.finalizeBy !== void 0 && height > n.finalizeBy) {
946
+ names.delete(nm);
947
+ pendingNames.delete(nm);
948
+ }
949
+ }
950
+ for (const nm of [...recaptures.keys()]) {
951
+ const r = recaptures.get(nm);
952
+ if (height > r.finalizeBy) recaptures.delete(nm);
953
+ }
954
+ };
955
+ const offerDue = (o, height) => !!o && o.status === "open" && epochOf(height) > effExpiry(o, height);
956
+ const bidDue = (b, height) => !!b && b.status === "open" && epochOf(height) > effExpiry(b, height);
957
+ const nameDue = (n, height) => !!n && !!n.pending && n.finalizeBy !== void 0 && height > n.finalizeBy;
958
+ const walkDue = (height) => ({
959
+ offers: [...openOffers].filter((id) => offerDue(offers.get(id), height)),
960
+ bids: [...openBids].filter((id) => bidDue(bids.get(id), height)),
961
+ names: [...pendingNames].filter((nm) => nameDue(names.get(nm), height)),
962
+ recaptures: [...recaptures].filter(([, r]) => height > r.finalizeBy).map(([nm]) => nm)
963
+ });
964
+ const walkPending = (who, except, height) => {
965
+ let k = 0;
966
+ for (const [nm, n] of names) if (n.pending && n.owner === who && nm !== except && n.finalizeBy !== void 0 && height <= n.finalizeBy) k++;
967
+ return k;
968
+ };
969
+ const walkRecaptures = (who, except, height) => {
970
+ let k = 0;
971
+ for (const [nm, r] of recaptures) if (r.owner === who && nm !== except && height <= r.finalizeBy) k++;
972
+ return k;
973
+ };
974
+ const holdLive = (x, who, height) => x.claimedBy === who && claimHeld(x, height) && (height < V29_HEIGHT || x.status === "open");
975
+ const walkHolds = (who, height) => {
976
+ let k = 0;
977
+ for (const x of offers.values()) if (holdLive(x, who, height)) k++;
978
+ return k;
979
+ };
980
+ 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));
981
+ 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));
982
+ const same = (what, index, walk) => {
983
+ if (JSON.stringify(index) !== JSON.stringify(walk)) throw new Error(`replay index check: ${what}: index ${JSON.stringify(index)}, walk ${JSON.stringify(walk)}`);
984
+ };
985
+ const popDue = (q, limit, at, isDue) => {
986
+ const popped = [];
987
+ q.popBelow(limit, popped);
988
+ stats.visits += popped.length;
989
+ return [...new Set(popped)].filter(isDue).sort((a, b) => at.get(a) - at.get(b));
990
+ };
991
+ const sweep = (height, expireOffer) => {
992
+ if (!(height >= maxSweep)) {
993
+ walkSweep(height, expireOffer);
994
+ return;
995
+ }
996
+ if (!(maxSweep >= V21_HEIGHT) && height >= V21_HEIGHT) {
997
+ stats.visits += openOffers.size + openBids.size;
998
+ for (const id of openOffers) {
999
+ const o = offers.get(id);
1000
+ if (o && o.status === "open" && !(o.height >= V22_HEIGHT)) offerQ.push(effExpiry(o, V21_HEIGHT), id);
1001
+ }
1002
+ for (const id of openBids) {
1003
+ const b = bids.get(id);
1004
+ if (b && b.status === "open" && !(b.height >= V22_HEIGHT)) bidQ.push(effExpiry(b, V21_HEIGHT), id);
1005
+ }
1006
+ }
1007
+ maxSweep = height;
1008
+ const ep = epochOf(height);
1009
+ const want = check ? walkDue(height) : void 0;
1010
+ const dueOffers = popDue(offerQ, ep, openOfferAt, (id) => openOffers.has(id) && offerDue(offers.get(id), height));
1011
+ const dueBids = popDue(bidQ, ep, openBidAt, (id) => openBids.has(id) && bidDue(bids.get(id), height));
1012
+ const dueNames = popDue(nameQ, height, pendingAt, (nm) => pendingNames.has(nm) && nameDue(names.get(nm), height));
1013
+ const dueRecaptures = popDue(recaptureQ, height, recaptureAt, (nm) => {
1014
+ const r = recaptures.get(nm);
1015
+ return !!r && height > r.finalizeBy;
1016
+ });
1017
+ if (want) {
1018
+ same(`expired offers at ${height}`, dueOffers, want.offers);
1019
+ same(`expired bids at ${height}`, dueBids, want.bids);
1020
+ same(`expired reservations at ${height}`, dueNames, want.names);
1021
+ same(`expired recaptures at ${height}`, dueRecaptures, want.recaptures);
1022
+ }
1023
+ for (const id of dueOffers) {
1024
+ const o = offers.get(id);
1025
+ expireOffer(o);
1026
+ setOfferStatus(o, "expired");
1027
+ }
1028
+ for (const id of dueBids) setBidStatus(bids.get(id), "expired");
1029
+ for (const nm of dueNames) {
1030
+ names.delete(nm);
1031
+ pendingNames.delete(nm);
1032
+ }
1033
+ for (const nm of dueRecaptures) recaptures.delete(nm);
1034
+ };
1035
+ const pendingCount = (who, except, height) => {
1036
+ let k = 0;
1037
+ const set = pendingBy.get(who);
1038
+ if (set) for (const nm of set) {
1039
+ stats.visits++;
1040
+ const n = names.get(nm);
1041
+ if (!n || !n.pending || n.owner !== who) {
1042
+ set.delete(nm);
1043
+ continue;
1044
+ }
1045
+ if (nm !== except && n.finalizeBy !== void 0 && height <= n.finalizeBy) k++;
1046
+ }
1047
+ if (check) same(`reservations of ${who} at ${height}`, k, walkPending(who, except, height));
1048
+ return k;
1049
+ };
1050
+ const recaptureCount = (who, except, height) => {
1051
+ let k = 0;
1052
+ const set = recaptureBy.get(who);
1053
+ if (set) for (const nm of set) {
1054
+ stats.visits++;
1055
+ const r = recaptures.get(nm);
1056
+ if (!r || r.owner !== who) {
1057
+ set.delete(nm);
1058
+ continue;
1059
+ }
1060
+ if (nm !== except && height <= r.finalizeBy) k++;
1061
+ }
1062
+ if (check) same(`recaptures of ${who} at ${height}`, k, walkRecaptures(who, except, height));
1063
+ return k;
1064
+ };
1065
+ const liveHoldCount = (who, height) => {
1066
+ if (!(height >= maxHoldRead)) {
1067
+ stats.visits += offers.size;
1068
+ return walkHolds(who, height);
1069
+ }
1070
+ maxHoldRead = height;
1071
+ let k = 0;
1072
+ const set = holdsBy.get(who);
1073
+ if (set) for (const id of set) {
1074
+ stats.visits++;
1075
+ const x = offers.get(id);
1076
+ if (x && holdLive(x, who, height)) k++;
1077
+ else set.delete(id);
1078
+ }
1079
+ if (check) same(`live holds of ${who} at ${height}`, k, walkHolds(who, height));
1080
+ return k;
1081
+ };
1082
+ const byInsertion = (a, b) => offerAt.get(a.id) - offerAt.get(b.id);
1083
+ const ocancelTargets = (who, ticker, name) => {
1084
+ const set = ticker !== void 0 ? bySellerAsset.get(`${who}\0t\0${ticker}`) : name !== void 0 ? bySellerAsset.get(`${who}\0n\0${name}`) : bySeller.get(who);
1085
+ const out = [];
1086
+ if (set) for (const id of set) {
1087
+ stats.visits++;
1088
+ const o = offers.get(id);
1089
+ if (!o || o.status !== "open" || o.seller !== who) {
1090
+ set.delete(id);
1091
+ continue;
1092
+ }
1093
+ if (ocancelMatch(o, who, ticker, name)) out.push(o);
1094
+ }
1095
+ out.sort(byInsertion);
1096
+ 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));
1097
+ return out;
1098
+ };
1099
+ const voidTargets = (name, height) => {
1100
+ const set = byName.get(name);
1101
+ const out = [];
1102
+ if (set) for (const id of set) {
1103
+ stats.visits++;
1104
+ const o = offers.get(id);
1105
+ if (!o || o.status !== "open" || !isNameGive(o.give) || o.give.name !== name) {
1106
+ set.delete(id);
1107
+ continue;
1108
+ }
1109
+ if (voidMatch(o, name, height)) out.push(o);
1110
+ }
1111
+ out.sort(byInsertion);
1112
+ 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));
1113
+ return out;
1114
+ };
1115
+ let checked = 0;
1116
+ const verify = (height, force = false) => {
1117
+ if (!check || !force && ++checked % checkEvery !== 0) return;
1118
+ const fail3 = (what) => {
1119
+ throw new Error(`replay index check: ${what}`);
1120
+ };
1121
+ const queued = (q) => new Set([...q.entries()].map(([k, id]) => `${k}\0${id}`));
1122
+ const oq = queued(offerQ), bq = queued(bidQ), nq = queued(nameQ), rq = queued(recaptureQ);
1123
+ for (const id of openOffers) {
1124
+ const o = offers.get(id);
1125
+ if (!o || o.status !== "open") fail3(`openOffers names ${id}, which is not open`);
1126
+ const k = effExpiry(o, regimeHeight());
1127
+ if (k === k && !oq.has(`${k}\0${id}`)) fail3(`open offer ${id} has no queue entry at ${k}`);
1128
+ }
1129
+ for (const id of openBids) {
1130
+ const b = bids.get(id);
1131
+ if (!b || b.status !== "open") fail3(`openBids names ${id}, which is not open`);
1132
+ const k = effExpiry(b, regimeHeight());
1133
+ if (k === k && !bq.has(`${k}\0${id}`)) fail3(`open bid ${id} has no queue entry at ${k}`);
1134
+ }
1135
+ for (const nm of pendingNames) {
1136
+ const n = names.get(nm);
1137
+ if (!n || !n.pending) fail3(`pendingNames names ${nm}, which is not pending`);
1138
+ }
1139
+ for (const [nm, n] of names) {
1140
+ if (!n.pending) continue;
1141
+ if (!pendingNames.has(nm)) fail3(`pending ${nm} is not in pendingNames`);
1142
+ if (!pendingBy.get(n.owner)?.has(nm)) fail3(`pending ${nm} is not a candidate of its owner ${n.owner}`);
1143
+ if (n.finalizeBy !== void 0 && !nq.has(`${n.finalizeBy}\0${nm}`)) fail3(`pending ${nm} has no queue entry at ${n.finalizeBy}`);
1144
+ }
1145
+ for (const [nm, r] of recaptures) {
1146
+ if (!recaptureBy.get(r.owner)?.has(nm)) fail3(`recapture ${nm} is not a candidate of its owner ${r.owner}`);
1147
+ if (!rq.has(`${r.finalizeBy}\0${nm}`)) fail3(`recapture ${nm} has no queue entry at ${r.finalizeBy}`);
1148
+ }
1149
+ for (const o of offers.values()) {
1150
+ 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`);
1151
+ 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}`);
1152
+ 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}`);
1153
+ }
1154
+ };
1155
+ return {
1156
+ offers,
1157
+ bids,
1158
+ names,
1159
+ recaptures,
1160
+ addOffer,
1161
+ setOfferStatus,
1162
+ setClaim,
1163
+ addBid,
1164
+ setBidStatus,
1165
+ putName,
1166
+ setNameOwner,
1167
+ finalizeName,
1168
+ putRecapture,
1169
+ deleteRecapture,
1170
+ sweep,
1171
+ pendingCount,
1172
+ recaptureCount,
1173
+ liveHoldCount,
1174
+ ocancelTargets,
1175
+ voidTargets,
1176
+ verify,
1177
+ stats
1178
+ };
781
1179
  }
782
1180
 
783
1181
  // src/resolve/names.ts
@@ -787,24 +1185,24 @@ var lapsed = (n, ep) => ep > paidThrough(n) + NAME_GRACE_EPOCHS;
787
1185
  var inGrace = (n, ep) => ep > paidThrough(n) && !lapsed(n, ep);
788
1186
  var earlierAnchor = (effHeight, pos, id, inc) => effHeight < inc.effHeight || effHeight === inc.effHeight && (pos < inc.pos || pos === inc.pos && id < inc.id);
789
1187
  function applyNcommit(c, ev, rec) {
790
- const { commits, note } = c;
1188
+ const { commits, applied, refused } = c;
791
1189
  const v11 = ev.height >= V11_HEIGHT;
792
1190
  if (!v11) {
793
- note(ev, ev.id, "ncommit", false, "before v1.1 activation");
1191
+ refused(ev, ev.id, "ncommit", "GATE_NOT_ACTIVE", "before v1.1 activation");
794
1192
  return;
795
1193
  }
796
1194
  const prev = commits.get(rec.commit);
797
1195
  if (prev === void 0 || ev.height < prev) commits.set(rec.commit, ev.height);
798
- note(ev, ev.id, "ncommit", true);
1196
+ applied(ev, ev.id, "ncommit", "NAME_COMMITTED");
799
1197
  }
800
1198
  function applyName(c, ev, rec, who, feeToTreasury) {
801
- const { commits, names, recaptures, note, putName, voidOpenNameOffers } = c;
1199
+ const { commits, names, recaptures, applied, refused, putName, voidOpenNameOffers, store } = c;
802
1200
  const v11 = ev.height >= V11_HEIGHT;
803
1201
  const v15 = ev.height >= V15_HEIGHT;
804
1202
  const v25 = ev.height >= V25_HEIGHT;
805
1203
  const v26 = ev.height >= V26_HEIGHT;
806
1204
  if (!v11) {
807
- note(ev, ev.id, "name", false, "before v1.1 activation");
1205
+ refused(ev, ev.id, "name", "GATE_NOT_ACTIVE", "before v1.1 activation");
808
1206
  return;
809
1207
  }
810
1208
  const regWindow = v25 || v26 ? REG_COMMIT_MAX_BLOCKS : COMMIT_MAX_BLOCKS;
@@ -813,7 +1211,7 @@ function applyName(c, ev, rec, who, feeToTreasury) {
813
1211
  const ch = nameCommit(rec.name, rec.salt, who);
814
1212
  const cH = commits.get(ch);
815
1213
  if (cH === void 0 || cH >= ev.height || ev.height - cH > regWindow) {
816
- note(ev, ev.id, "name", false, "no valid in-window commit for this reveal");
1214
+ refused(ev, ev.id, "name", "NAME_NO_COMMIT", "no valid in-window commit for this reveal");
817
1215
  return;
818
1216
  }
819
1217
  effHeight = cH;
@@ -824,62 +1222,61 @@ function applyName(c, ev, rec, who, feeToTreasury) {
824
1222
  if (curActive && !curActive.pending && v15 && lapsed(curActive, epClaim)) {
825
1223
  if (v26) {
826
1224
  if (rec.salt === void 0) {
827
- note(ev, ev.id, "name", false, "v2.6: recapture requires a commit-reveal (salt)");
1225
+ refused(ev, ev.id, "name", "NAME_SALT_REQUIRED", "v2.6: recapture requires a commit-reveal (salt)");
828
1226
  return;
829
1227
  }
830
1228
  const cr = recaptures.get(rec.name);
831
1229
  const crActive = cr && ev.height > cr.finalizeBy ? void 0 : cr;
832
1230
  const better2 = !crActive || earlierAnchor(effHeight, ev.pos, ev.id, crActive);
833
1231
  if (!better2) {
834
- note(ev, ev.id, "name", false, "recapture already reserved (earlier anchor wins)");
1232
+ refused(ev, ev.id, "name", "NAME_TAKEN_EARLIER", "recapture already reserved (earlier anchor wins)");
835
1233
  return;
836
1234
  }
837
- let myR = 0;
838
- for (const [nm, r] of recaptures) if (r.owner === who && nm !== rec.name && ev.height <= r.finalizeBy) myR++;
839
- if (myR >= MAX_PENDING_REG) {
840
- note(ev, ev.id, "name", false, "too many pending recaptures (max reached)");
1235
+ if (store.recaptureCount(who, rec.name, ev.height) >= MAX_PENDING_REG) {
1236
+ refused(ev, ev.id, "name", "CAP_PENDING_RECAPTURES", "too many pending recaptures (max reached)");
841
1237
  return;
842
1238
  }
843
- 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 });
844
- note(ev, ev.id, "name", true, crActive ? "recapture reserved (displaced prior reservation)" : "recapture reserved (pending finalize)");
1239
+ 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 });
1240
+ if (crActive) applied(ev, ev.id, "name", "NAME_RECAPTURE_RESERVED_DISPLACED", "recapture reserved (displaced prior reservation)");
1241
+ else applied(ev, ev.id, "name", "NAME_RECAPTURE_RESERVED", "recapture reserved (pending finalize)");
845
1242
  return;
846
1243
  }
847
1244
  const fee = expiredClaimFee(rec.name, epClaim - (paidThrough(curActive) + NAME_GRACE_EPOCHS), ev.height);
848
1245
  if (feeToTreasury < fee) {
849
- note(ev, ev.id, "name", false, "lapsed-name claim fee unpaid (decaying premium)");
1246
+ refused(ev, ev.id, "name", "TREASURY_FEE_UNPAID", "lapsed-name claim fee unpaid (decaying premium)");
850
1247
  return;
851
1248
  }
852
1249
  voidOpenNameOffers(rec.name, ev.height);
853
1250
  putName(rec.name, { owner: who, effHeight, pos: ev.pos, id: ev.id, height: ev.height, locked: false, viaFill: true, paidThroughEpoch: epClaim + NAME_TERM_EPOCHS });
854
1251
  c.feesPaid += fee;
855
- note(ev, ev.id, "name", true, "lapsed lease re-claimed (premium)");
1252
+ applied(ev, ev.id, "name", "NAME_RECLAIMED", "lapsed lease re-claimed (premium)");
856
1253
  return;
857
1254
  }
858
1255
  if (v25) {
859
1256
  if (rec.salt === void 0) {
860
- note(ev, ev.id, "name", false, "v2.5: registration requires a commit-reveal (salt)");
1257
+ refused(ev, ev.id, "name", "NAME_SALT_REQUIRED", "v2.5: registration requires a commit-reveal (salt)");
861
1258
  return;
862
1259
  }
863
1260
  const better2 = !curActive || !curActive.viaFill && earlierAnchor(effHeight, ev.pos, ev.id, curActive);
864
1261
  if (!better2) {
865
- note(ev, ev.id, "name", false, curActive?.viaFill ? "name taken (purchased \u2014 not displaceable)" : "name taken (earlier anchor wins)");
1262
+ if (curActive?.viaFill) refused(ev, ev.id, "name", "NAME_TAKEN_PURCHASED", "name taken (purchased \u2014 not displaceable)");
1263
+ else refused(ev, ev.id, "name", "NAME_TAKEN_EARLIER", "name taken (earlier anchor wins)");
866
1264
  return;
867
1265
  }
868
- let myPending = 0;
869
- for (const [nm, n] of names) if (n.pending && n.owner === who && nm !== rec.name && n.finalizeBy !== void 0 && ev.height <= n.finalizeBy) myPending++;
870
- if (myPending >= MAX_PENDING_REG) {
871
- note(ev, ev.id, "name", false, "too many pending reservations (max reached)");
1266
+ if (store.pendingCount(who, rec.name, ev.height) >= MAX_PENDING_REG) {
1267
+ refused(ev, ev.id, "name", "CAP_PENDING_RESERVATIONS", "too many pending reservations (max reached)");
872
1268
  return;
873
1269
  }
874
1270
  if (curActive) {
875
1271
  voidOpenNameOffers(rec.name, ev.height);
876
1272
  }
877
1273
  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 });
878
- note(ev, ev.id, "name", true, curActive ? "reserved (displaced prior reservation)" : "reserved (pending finalize)");
1274
+ if (curActive) applied(ev, ev.id, "name", "NAME_RESERVED_DISPLACED", "reserved (displaced prior reservation)");
1275
+ else applied(ev, ev.id, "name", "NAME_RESERVED", "reserved (pending finalize)");
879
1276
  return;
880
1277
  }
881
1278
  if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
882
- note(ev, ev.id, "name", false, "name registration fee unpaid");
1279
+ refused(ev, ev.id, "name", "TREASURY_FEE_UNPAID", "name registration fee unpaid");
883
1280
  return;
884
1281
  }
885
1282
  const cand = {
@@ -893,7 +1290,8 @@ function applyName(c, ev, rec, who, feeToTreasury) {
893
1290
  };
894
1291
  const better = !curActive || !curActive.viaFill && earlierAnchor(effHeight, ev.pos, ev.id, curActive);
895
1292
  if (!better) {
896
- note(ev, ev.id, "name", false, curActive?.viaFill ? "name taken (purchased \u2014 not displaceable)" : "name taken (earlier anchor wins)");
1293
+ if (curActive?.viaFill) refused(ev, ev.id, "name", "NAME_TAKEN_PURCHASED", "name taken (purchased \u2014 not displaceable)");
1294
+ else refused(ev, ev.id, "name", "NAME_TAKEN_EARLIER", "name taken (earlier anchor wins)");
897
1295
  return;
898
1296
  }
899
1297
  if (curActive) {
@@ -901,189 +1299,188 @@ function applyName(c, ev, rec, who, feeToTreasury) {
901
1299
  }
902
1300
  putName(rec.name, cand);
903
1301
  c.feesPaid += nameRegFee(rec.name, ev.height);
904
- note(ev, ev.id, "name", true, curActive ? "displaced prior holder" : void 0);
1302
+ if (curActive) applied(ev, ev.id, "name", "NAME_REGISTERED_DISPLACED", "displaced prior holder");
1303
+ else applied(ev, ev.id, "name", "NAME_REGISTERED");
905
1304
  }
906
1305
  function applyNfinalize(c, ev, rec, who, feeToTreasury) {
907
- const { commits, names, recaptures, pendingNames, note, putName, voidOpenNameOffers } = c;
1306
+ const { commits, names, recaptures, applied, refused, putName, voidOpenNameOffers, store } = c;
908
1307
  const v25 = ev.height >= V25_HEIGHT;
909
1308
  const v26 = ev.height >= V26_HEIGHT;
910
1309
  if (!v25) {
911
- note(ev, ev.id, "nfinalize", false, "before v2.5 activation");
1310
+ refused(ev, ev.id, "nfinalize", "GATE_NOT_ACTIVE", "before v2.5 activation");
912
1311
  return;
913
1312
  }
914
1313
  const n = names.get(rec.name);
915
1314
  if (n && n.pending && n.owner === who) {
916
1315
  const cH = commits.get(nameCommit(rec.name, rec.salt, who));
917
1316
  if (cH === void 0 || cH !== n.effHeight) {
918
- note(ev, ev.id, "nfinalize", false, "salt does not match the reservation commit");
1317
+ refused(ev, ev.id, "nfinalize", "NAME_SALT_MISMATCH", "salt does not match the reservation commit");
919
1318
  return;
920
1319
  }
921
1320
  if (!(ev.height > n.effHeight + REG_COMMIT_MAX_BLOCKS)) {
922
- note(ev, ev.id, "nfinalize", false, "too early \u2014 displacement contest not yet frozen");
1321
+ refused(ev, ev.id, "nfinalize", "NAME_FINALIZE_TOO_EARLY", "too early \u2014 displacement contest not yet frozen");
923
1322
  return;
924
1323
  }
925
1324
  if (n.finalizeBy !== void 0 && ev.height > n.finalizeBy) {
926
- note(ev, ev.id, "nfinalize", false, "reservation expired");
1325
+ refused(ev, ev.id, "nfinalize", "NAME_RESERVATION_EXPIRED", "reservation expired");
927
1326
  return;
928
1327
  }
929
1328
  if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
930
- note(ev, ev.id, "nfinalize", false, "name registration fee unpaid");
1329
+ refused(ev, ev.id, "nfinalize", "TREASURY_FEE_UNPAID", "name registration fee unpaid");
931
1330
  return;
932
1331
  }
933
- delete n.pending;
934
- delete n.finalizeBy;
935
- pendingNames.delete(rec.name);
1332
+ store.finalizeName(rec.name, n);
936
1333
  n.paidThroughEpoch = epochOf(ev.height) + NAME_TERM_EPOCHS;
937
1334
  c.feesPaid += nameRegFee(rec.name, ev.height);
938
- note(ev, ev.id, "nfinalize", true);
1335
+ applied(ev, ev.id, "nfinalize", "NAME_FINALIZED");
939
1336
  return;
940
1337
  }
941
1338
  const r = v26 ? recaptures.get(rec.name) : void 0;
942
1339
  if (r && r.owner === who) {
943
1340
  const cH = commits.get(nameCommit(rec.name, rec.salt, who));
944
1341
  if (cH === void 0 || cH !== r.effHeight) {
945
- note(ev, ev.id, "nfinalize", false, "salt does not match the recapture commit");
1342
+ refused(ev, ev.id, "nfinalize", "NAME_SALT_MISMATCH", "salt does not match the recapture commit");
946
1343
  return;
947
1344
  }
948
1345
  if (!(ev.height > r.effHeight + REG_COMMIT_MAX_BLOCKS)) {
949
- note(ev, ev.id, "nfinalize", false, "too early \u2014 recapture contest not yet frozen");
1346
+ refused(ev, ev.id, "nfinalize", "NAME_FINALIZE_TOO_EARLY", "too early \u2014 recapture contest not yet frozen");
950
1347
  return;
951
1348
  }
952
1349
  if (ev.height > r.finalizeBy) {
953
- note(ev, ev.id, "nfinalize", false, "recapture reservation expired");
1350
+ refused(ev, ev.id, "nfinalize", "NAME_RESERVATION_EXPIRED", "recapture reservation expired");
954
1351
  return;
955
1352
  }
956
1353
  const cur = names.get(rec.name);
957
1354
  const ep = epochOf(ev.height);
958
1355
  if (!cur || cur.pending || !lapsed(cur, ep)) {
959
- recaptures.delete(rec.name);
960
- note(ev, ev.id, "nfinalize", false, "name is no longer lapsed");
1356
+ store.deleteRecapture(rec.name);
1357
+ refused(ev, ev.id, "nfinalize", "NAME_NOT_LAPSED", "name is no longer lapsed");
961
1358
  return;
962
1359
  }
963
1360
  const fee = expiredClaimFee(rec.name, ep - (paidThrough(cur) + NAME_GRACE_EPOCHS), ev.height);
964
1361
  if (feeToTreasury < fee) {
965
- note(ev, ev.id, "nfinalize", false, "recapture premium unpaid (decaying)");
1362
+ refused(ev, ev.id, "nfinalize", "TREASURY_FEE_UNPAID", "recapture premium unpaid (decaying)");
966
1363
  return;
967
1364
  }
968
1365
  voidOpenNameOffers(rec.name, ev.height);
969
1366
  putName(rec.name, { owner: who, effHeight: r.effHeight, pos: r.pos, id: r.id, height: r.height, locked: false, paidThroughEpoch: ep + NAME_TERM_EPOCHS });
970
- recaptures.delete(rec.name);
1367
+ store.deleteRecapture(rec.name);
971
1368
  c.feesPaid += fee;
972
- note(ev, ev.id, "nfinalize", true, "recapture finalized (premium)");
1369
+ applied(ev, ev.id, "nfinalize", "NAME_RECAPTURE_FINALIZED", "recapture finalized (premium)");
973
1370
  return;
974
1371
  }
975
- note(ev, ev.id, "nfinalize", false, "no matching pending reservation you own");
1372
+ refused(ev, ev.id, "nfinalize", "NAME_NO_RESERVATION", "no matching pending reservation you own");
976
1373
  }
977
1374
  function applyNxfer(c, ev, rec, who) {
978
- const { names, note } = c;
1375
+ const { names, applied, refused, store } = c;
979
1376
  const v15 = ev.height >= V15_HEIGHT;
980
1377
  const n = names.get(rec.name);
981
1378
  if (!n || n.owner !== who) {
982
- note(ev, ev.id, "nxfer", false, "not the name owner");
1379
+ refused(ev, ev.id, "nxfer", "NAME_NOT_OWNER", "not the name owner");
983
1380
  return;
984
1381
  }
985
1382
  if (n.pending) {
986
- note(ev, ev.id, "nxfer", false, "name reservation not yet finalized");
1383
+ refused(ev, ev.id, "nxfer", "NAME_PENDING", "name reservation not yet finalized");
987
1384
  return;
988
1385
  }
989
1386
  if (v15 && lapsed(n, epochOf(ev.height))) {
990
- note(ev, ev.id, "nxfer", false, "lease lapsed \u2014 claim it instead");
1387
+ refused(ev, ev.id, "nxfer", "NAME_LAPSED", "lease lapsed \u2014 claim it instead");
991
1388
  return;
992
1389
  }
993
1390
  if (n.locked) {
994
- note(ev, ev.id, "nxfer", false, "name is locked by an open offer");
1391
+ refused(ev, ev.id, "nxfer", "NAME_LOCKED", "name is locked by an open offer");
995
1392
  return;
996
1393
  }
997
- n.owner = rec.to.toLowerCase();
1394
+ store.setNameOwner(rec.name, n, rec.to.toLowerCase());
998
1395
  n.addr = void 0;
999
1396
  n.profile = void 0;
1000
- note(ev, ev.id, "nxfer", true);
1397
+ applied(ev, ev.id, "nxfer", "NAME_TRANSFERRED");
1001
1398
  }
1002
1399
  function applyNset(c, ev, rec, who) {
1003
- const { names, note } = c;
1400
+ const { names, applied, refused } = c;
1004
1401
  const v15 = ev.height >= V15_HEIGHT;
1005
1402
  const v23 = ev.height >= V23_HEIGHT;
1006
1403
  const n = names.get(rec.name);
1007
1404
  if (!n || n.owner !== who) {
1008
- note(ev, ev.id, "nset", false, "not the name owner");
1405
+ refused(ev, ev.id, "nset", "NAME_NOT_OWNER", "not the name owner");
1009
1406
  return;
1010
1407
  }
1011
1408
  if (n.pending) {
1012
- note(ev, ev.id, "nset", false, "name reservation not yet finalized");
1409
+ refused(ev, ev.id, "nset", "NAME_PENDING", "name reservation not yet finalized");
1013
1410
  return;
1014
1411
  }
1015
1412
  if (v15 && lapsed(n, epochOf(ev.height))) {
1016
- note(ev, ev.id, "nset", false, "lease lapsed \u2014 claim it instead");
1413
+ refused(ev, ev.id, "nset", "NAME_LAPSED", "lease lapsed \u2014 claim it instead");
1017
1414
  return;
1018
1415
  }
1019
1416
  if (v23 && rec.addr.toLowerCase() === ZERO_ADDR) n.addr = void 0;
1020
1417
  else n.addr = rec.addr.toLowerCase();
1021
- note(ev, ev.id, "nset", true);
1418
+ applied(ev, ev.id, "nset", "NAME_ADDR_SET");
1022
1419
  }
1023
1420
  function applyNprofile(c, ev, rec, who) {
1024
- const { names, note } = c;
1421
+ const { names, applied, refused } = c;
1025
1422
  const v15 = ev.height >= V15_HEIGHT;
1026
1423
  const v19 = ev.height >= V19_HEIGHT;
1027
1424
  if (!v19) {
1028
- note(ev, ev.id, "nprofile", false, "before v1.9 activation");
1425
+ refused(ev, ev.id, "nprofile", "GATE_NOT_ACTIVE", "before v1.9 activation");
1029
1426
  return;
1030
1427
  }
1031
1428
  const n = names.get(rec.name);
1032
1429
  if (!n || n.owner !== who) {
1033
- note(ev, ev.id, "nprofile", false, "not the name owner");
1430
+ refused(ev, ev.id, "nprofile", "NAME_NOT_OWNER", "not the name owner");
1034
1431
  return;
1035
1432
  }
1036
1433
  if (n.pending) {
1037
- note(ev, ev.id, "nprofile", false, "name reservation not yet finalized");
1434
+ refused(ev, ev.id, "nprofile", "NAME_PENDING", "name reservation not yet finalized");
1038
1435
  return;
1039
1436
  }
1040
1437
  if (v15 && lapsed(n, epochOf(ev.height))) {
1041
- note(ev, ev.id, "nprofile", false, "lease lapsed \u2014 claim it instead");
1438
+ refused(ev, ev.id, "nprofile", "NAME_LAPSED", "lease lapsed \u2014 claim it instead");
1042
1439
  return;
1043
1440
  }
1044
1441
  n.profile = Object.keys(rec.p).length ? { ...rec.p } : void 0;
1045
- note(ev, ev.id, "nprofile", true);
1442
+ applied(ev, ev.id, "nprofile", "NAME_PROFILE_SET");
1046
1443
  }
1047
1444
  function applyNrenew(c, ev, rec, who, feeToTreasury) {
1048
- const { names, note } = c;
1445
+ const { names, applied, refused } = c;
1049
1446
  const v15 = ev.height >= V15_HEIGHT;
1050
1447
  if (!v15) {
1051
- note(ev, ev.id, "nrenew", false, "nrenew needs v1.5");
1448
+ refused(ev, ev.id, "nrenew", "GATE_NOT_ACTIVE", "nrenew needs v1.5");
1052
1449
  return;
1053
1450
  }
1054
1451
  const n = names.get(rec.name);
1055
1452
  const ep = epochOf(ev.height);
1056
1453
  if (n && n.pending) {
1057
- note(ev, ev.id, "nrenew", false, "name reservation not yet finalized");
1454
+ refused(ev, ev.id, "nrenew", "NAME_PENDING", "name reservation not yet finalized");
1058
1455
  return;
1059
1456
  }
1060
1457
  if (!n || lapsed(n, ep)) {
1061
- note(ev, ev.id, "nrenew", false, "no live lease (lapsed names are claimed, not renewed)");
1458
+ refused(ev, ev.id, "nrenew", "NAME_NO_LIVE_LEASE", "no live lease (lapsed names are claimed, not renewed)");
1062
1459
  return;
1063
1460
  }
1064
1461
  if (inGrace(n, ep) && who !== n.owner) {
1065
- note(ev, ev.id, "nrenew", false, "grace period: only the owner may renew");
1462
+ refused(ev, ev.id, "nrenew", "NAME_GRACE_OWNER_ONLY", "grace period: only the owner may renew");
1066
1463
  return;
1067
1464
  }
1068
1465
  if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
1069
- note(ev, ev.id, "nrenew", false, "renewal fee unpaid");
1466
+ refused(ev, ev.id, "nrenew", "TREASURY_FEE_UNPAID", "renewal fee unpaid");
1070
1467
  return;
1071
1468
  }
1072
1469
  n.paidThroughEpoch = paidThrough(n) + NAME_TERM_EPOCHS;
1073
1470
  c.feesPaid += nameRegFee(rec.name, ev.height);
1074
- note(ev, ev.id, "nrenew", true, `paid through epoch ${n.paidThroughEpoch}`);
1471
+ applied(ev, ev.id, "nrenew", "NAME_RENEWED", `paid through epoch ${n.paidThroughEpoch}`);
1075
1472
  }
1076
1473
 
1077
1474
  // src/resolve/market.ts
1078
1475
  function applyOffer(c, ev, rec, who) {
1079
- const { tokens, names, offers, offerLock, openOffers, bids, bal, note } = c;
1476
+ const { tokens, names, offerLock, bids, bal, applied, refused, store } = c;
1080
1477
  const v11 = ev.height >= V11_HEIGHT;
1081
1478
  const v15 = ev.height >= V15_HEIGHT;
1082
1479
  const v16 = ev.height >= V16_HEIGHT;
1083
1480
  const wantIsToken = isTokenWant(rec.want);
1084
1481
  const refusal = offerEnvelopeRefusal(rec, who, ev.height, ev.expiresEpoch);
1085
1482
  if (refusal !== null) {
1086
- note(ev, ev.id, "offer", false, refusal);
1483
+ refused(ev, ev.id, "offer", refusal.code, refusal.note);
1087
1484
  return;
1088
1485
  }
1089
1486
  const payto = (rec.want.payto ?? who).toLowerCase();
@@ -1091,36 +1488,36 @@ function applyOffer(c, ev, rec, who) {
1091
1488
  if (isNameGive(give)) {
1092
1489
  const n = names.get(give.name);
1093
1490
  if (!n || n.owner !== who) {
1094
- note(ev, ev.id, "offer", false, "you don't own this name");
1491
+ refused(ev, ev.id, "offer", "NAME_NOT_OWNER", "you don't own this name");
1095
1492
  return;
1096
1493
  }
1097
1494
  if (n.pending) {
1098
- note(ev, ev.id, "offer", false, "name reservation not yet finalized");
1495
+ refused(ev, ev.id, "offer", "NAME_PENDING", "name reservation not yet finalized");
1099
1496
  return;
1100
1497
  }
1101
1498
  if (n.locked) {
1102
- note(ev, ev.id, "offer", false, "name already locked by another offer");
1499
+ refused(ev, ev.id, "offer", "NAME_LOCKED", "name already locked by another offer");
1103
1500
  return;
1104
1501
  }
1105
1502
  const saleEmbargo = ev.height >= V27_HEIGHT ? REG_COMMIT_MAX_BLOCKS : COMMIT_MAX_BLOCKS;
1106
1503
  if (ev.height >= V13_HEIGHT && !n.viaFill && ev.height - n.effHeight <= saleEmbargo) {
1107
- note(ev, ev.id, "offer", false, "name too young to sell (must out-age the reveal window)");
1504
+ refused(ev, ev.id, "offer", "NAME_TOO_YOUNG", "name too young to sell (must out-age the reveal window)");
1108
1505
  return;
1109
1506
  }
1110
1507
  if (v15 && paidThrough(n) < ev.expiresEpoch) {
1111
- note(ev, ev.id, "offer", false, "v1.5: lease ends inside the offer window (renew first)");
1508
+ refused(ev, ev.id, "offer", "OFFER_LEASE_TOO_SHORT", "v1.5: lease ends inside the offer window (renew first)");
1112
1509
  return;
1113
1510
  }
1114
1511
  n.locked = true;
1115
1512
  } else {
1116
1513
  if (!tokens.has(give.ticker)) {
1117
- note(ev, ev.id, "offer", false, "unknown ticker");
1514
+ refused(ev, ev.id, "offer", "TOKEN_UNKNOWN", "unknown ticker");
1118
1515
  return;
1119
1516
  }
1120
1517
  const amt = parseAmount(give.amount);
1121
1518
  const s = bal(give.ticker, who);
1122
1519
  if (s.available < amt) {
1123
- note(ev, ev.id, "offer", false, "insufficient available balance");
1520
+ refused(ev, ev.id, "offer", "TOKEN_BALANCE_LOW", "insufficient available balance");
1124
1521
  return;
1125
1522
  }
1126
1523
  s.available -= amt;
@@ -1140,32 +1537,31 @@ function applyOffer(c, ev, rec, who) {
1140
1537
  height: ev.height,
1141
1538
  feeBps: v11 ? v16 ? FEE_BPS_V16 : FEE_BPS : 0
1142
1539
  };
1143
- offers.set(ev.id, o);
1144
- openOffers.add(ev.id);
1540
+ store.addOffer(o);
1145
1541
  const linked = rec.bid !== void 0 ? bids.get(rec.bid) : void 0;
1146
1542
  if (linked) linked.offers.push(ev.id);
1147
- note(ev, ev.id, "offer", true);
1543
+ applied(ev, ev.id, "offer", "OFFER_CREATED");
1148
1544
  }
1149
1545
  function applyBid(c, ev, rec, who) {
1150
- const { bids, openBids, note } = c;
1546
+ const { applied, refused, store } = c;
1151
1547
  const v12 = ev.height >= V12_HEIGHT;
1152
1548
  if (!v12) {
1153
- note(ev, ev.id, "bid", false, "bids need v1.2");
1549
+ refused(ev, ev.id, "bid", "GATE_NOT_ACTIVE", "bids need v1.2");
1154
1550
  return;
1155
1551
  }
1156
1552
  if (!Number.isSafeInteger(ev.expiresEpoch)) {
1157
- note(ev, ev.id, "bid", false, "expiresEpoch out of safe-integer range");
1553
+ refused(ev, ev.id, "bid", "EXPIRY_UNSAFE", "expiresEpoch out of safe-integer range");
1158
1554
  return;
1159
1555
  }
1160
1556
  if (epochOf(ev.height) > ev.expiresEpoch) {
1161
- note(ev, ev.id, "bid", false, "already expired at anchor");
1557
+ refused(ev, ev.id, "bid", "EXPIRY_PAST", "already expired at anchor");
1162
1558
  return;
1163
1559
  }
1164
1560
  if (ev.height >= V21_HEIGHT && ev.height < V22_HEIGHT && ev.expiresEpoch - epochOf(ev.height) > MAX_OFFER_EPOCHS) {
1165
- note(ev, ev.id, "bid", false, "v2.1: bid duration exceeds the max");
1561
+ refused(ev, ev.id, "bid", "EXPIRY_TOO_LONG", "v2.1: bid duration exceeds the max");
1166
1562
  return;
1167
1563
  }
1168
- bids.set(ev.id, {
1564
+ store.addBid({
1169
1565
  id: ev.id,
1170
1566
  bidder: who,
1171
1567
  want: rec.want,
@@ -1175,24 +1571,16 @@ function applyBid(c, ev, rec, who) {
1175
1571
  height: ev.height,
1176
1572
  offers: []
1177
1573
  });
1178
- openBids.add(ev.id);
1179
- note(ev, ev.id, "bid", true);
1574
+ applied(ev, ev.id, "bid", "BID_CREATED");
1180
1575
  }
1181
1576
  function applyOcancel(c, ev, rec, who) {
1182
- const { offers, note, releaseGive, setOfferStatus } = c;
1577
+ const { applied, refused, releaseGive, setOfferStatus, store } = c;
1183
1578
  const v12 = ev.height >= V12_HEIGHT;
1184
1579
  if (!v12) {
1185
- note(ev, ev.id, "ocancel", false, "ocancel needs v1.2");
1580
+ refused(ev, ev.id, "ocancel", "GATE_NOT_ACTIVE", "ocancel needs v1.2");
1186
1581
  return;
1187
1582
  }
1188
- const targets = [];
1189
- for (const o of offers.values()) {
1190
- if (o.status !== "open" || o.seller !== who) continue;
1191
- if (o.taker !== void 0 && o.height >= V28_HEIGHT) continue;
1192
- if (rec.ticker !== void 0 && !(!isNameGive(o.give) && o.give.ticker === rec.ticker)) continue;
1193
- if (rec.name !== void 0 && !(isNameGive(o.give) && o.give.name === rec.name)) continue;
1194
- targets.push(o);
1195
- }
1583
+ const targets = store.ocancelTargets(who, rec.ticker, rec.name);
1196
1584
  if (ev.height >= V14_HEIGHT) {
1197
1585
  c.pendingCancels.push(() => {
1198
1586
  let n = 0;
@@ -1204,100 +1592,98 @@ function applyOcancel(c, ev, rec, who) {
1204
1592
  n++;
1205
1593
  }
1206
1594
  }
1207
- note(ev, ev.id, "ocancel", true, `${n} cancelled (deferred past same-block fills)`);
1595
+ applied(ev, ev.id, "ocancel", "OFFER_BULK_CANCELLED", `${n} cancelled (deferred past same-block fills)`);
1208
1596
  });
1209
1597
  } else {
1210
1598
  for (const o of targets) {
1211
1599
  releaseGive(o);
1212
1600
  setOfferStatus(o, "cancelled");
1213
1601
  }
1214
- note(ev, ev.id, "ocancel", true, `${targets.length} cancelled`);
1602
+ applied(ev, ev.id, "ocancel", "OFFER_BULK_CANCELLED", `${targets.length} cancelled`);
1215
1603
  }
1216
1604
  }
1217
1605
  function applyFclaim(c, ev, rec, who) {
1218
- const { offers, fclaims, note, liveHoldCount } = c;
1606
+ const { offers, fclaims, applied, refused, store } = c;
1219
1607
  if (ev.height < V28_HEIGHT) {
1220
- note(ev, ev.id, "fclaim", false, "fclaim needs v2.8");
1608
+ refused(ev, ev.id, "fclaim", "GATE_NOT_ACTIVE", "fclaim needs v2.8");
1221
1609
  return;
1222
1610
  }
1223
1611
  const target = offers.get(rec.offer);
1224
1612
  const E = ev.expiresEpoch;
1225
- const deny = (why) => {
1613
+ const deny = (code, why) => {
1226
1614
  fclaims.set(ev.id, { offer: rec.offer, proposer: who, expiresEpoch: E, height: ev.height, granted: false });
1227
- note(ev, ev.id, "fclaim", false, why);
1615
+ refused(ev, ev.id, "fclaim", code, why);
1228
1616
  };
1229
1617
  if (!Number.isSafeInteger(E)) {
1230
- deny("expiresEpoch out of safe-integer range");
1618
+ deny("EXPIRY_UNSAFE", "expiresEpoch out of safe-integer range");
1231
1619
  return;
1232
1620
  }
1233
1621
  if (!target) {
1234
- deny("unknown offer");
1622
+ deny("OFFER_UNKNOWN", "unknown offer");
1235
1623
  return;
1236
1624
  }
1237
1625
  if (target.status !== "open") {
1238
- deny(`offer ${target.status}`);
1626
+ deny("OFFER_NOT_OPEN", `offer ${target.status}`);
1239
1627
  return;
1240
1628
  }
1241
1629
  if (target.taker) {
1242
- deny("taker-bound offer needs no claim");
1630
+ deny("CLAIM_TAKER_BOUND", "taker-bound offer needs no claim");
1243
1631
  return;
1244
1632
  }
1245
1633
  if (isTokenWant(target.want)) {
1246
- deny("claims are for CSD-priced offers");
1634
+ deny("CLAIM_TOKEN_PRICED", "claims are for CSD-priced offers");
1247
1635
  return;
1248
1636
  }
1249
1637
  if (E > effExpiry(target, ev.height)) {
1250
- deny("hold would outlive the offer expiry");
1638
+ deny("CLAIM_OUTLIVES_OFFER", "hold would outlive the offer expiry");
1251
1639
  return;
1252
1640
  }
1253
1641
  if (E > epochOf(ev.height) + FCLAIM_MAX_EPOCH_AHEAD) {
1254
- deny("hold too far ahead (anti-squat)");
1642
+ deny("CLAIM_TOO_FAR_AHEAD", "hold too far ahead (anti-squat)");
1255
1643
  return;
1256
1644
  }
1257
1645
  if (epochOf(ev.height) > E) {
1258
- deny("expiry already in the past");
1646
+ deny("EXPIRY_PAST", "expiry already in the past");
1259
1647
  return;
1260
1648
  }
1261
1649
  if (claimHeld(target, ev.height)) {
1262
- deny("offer already claimed (hold live)");
1650
+ deny("CLAIM_HOLD_LIVE", "offer already claimed (hold live)");
1263
1651
  return;
1264
1652
  }
1265
1653
  if (target.claimedBy === who && target.claimUntilHeight !== void 0 && ev.height < target.claimUntilHeight + claimGrace(target) + CLAIM_COOLDOWN_BLOCKS) {
1266
- deny("claim cooldown (you just held this offer)");
1654
+ deny("CLAIM_COOLDOWN", "claim cooldown (you just held this offer)");
1267
1655
  return;
1268
1656
  }
1269
- if (liveHoldCount(who, ev.height) >= MAX_ACTIVE_CLAIMS) {
1270
- deny(`max ${MAX_ACTIVE_CLAIMS} live claims per address`);
1657
+ if (store.liveHoldCount(who, ev.height) >= MAX_ACTIVE_CLAIMS) {
1658
+ deny("CAP_LIVE_HOLDS", `max ${MAX_ACTIVE_CLAIMS} live claims per address`);
1271
1659
  return;
1272
1660
  }
1273
- target.claimedBy = who;
1274
- target.claimUntilHeight = (E + 1) * EPOCH_LEN;
1275
- target.claimTxid = ev.id;
1661
+ store.setClaim(target, who, (E + 1) * EPOCH_LEN, ev.id);
1276
1662
  fclaims.set(ev.id, { offer: rec.offer, proposer: who, expiresEpoch: E, height: ev.height, granted: true });
1277
- note(ev, ev.id, "fclaim", true);
1663
+ applied(ev, ev.id, "fclaim", "CLAIM_GRANTED");
1278
1664
  }
1279
1665
  function offerEnvelopeRefusal(rec, who, height, expiresEpoch) {
1280
1666
  const wantIsToken = isTokenWant(rec.want);
1281
- if ((wantIsToken || rec.min !== void 0 || rec.bid !== void 0) && height < V12_HEIGHT) return "v1.2 offer shape before activation";
1282
- 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)";
1283
- if ((rec.want.payto ?? who).toLowerCase() === TREASURY_ADDR) return "payto cannot be the protocol treasury";
1284
- if (!Number.isSafeInteger(expiresEpoch)) return "expiresEpoch out of safe-integer range";
1285
- if (epochOf(height) > expiresEpoch) return "already expired at anchor";
1286
- if (height >= V21_HEIGHT && height < V22_HEIGHT && expiresEpoch - epochOf(height) > MAX_OFFER_EPOCHS) return "v2.1: offer duration exceeds the max";
1287
- if (isNameGive(rec.give) && height < V11_HEIGHT) return "name offers need v1.1";
1667
+ 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" };
1668
+ 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)" };
1669
+ if ((rec.want.payto ?? who).toLowerCase() === TREASURY_ADDR) return { code: "OFFER_PAYTO_TREASURY", note: "payto cannot be the protocol treasury" };
1670
+ if (!Number.isSafeInteger(expiresEpoch)) return { code: "EXPIRY_UNSAFE", note: "expiresEpoch out of safe-integer range" };
1671
+ if (epochOf(height) > expiresEpoch) return { code: "EXPIRY_PAST", note: "already expired at anchor" };
1672
+ if (height >= V21_HEIGHT && height < V22_HEIGHT && expiresEpoch - epochOf(height) > MAX_OFFER_EPOCHS) return { code: "EXPIRY_TOO_LONG", note: "v2.1: offer duration exceeds the max" };
1673
+ if (isNameGive(rec.give) && height < V11_HEIGHT) return { code: "GATE_NOT_ACTIVE", note: "name offers need v1.1" };
1288
1674
  return null;
1289
1675
  }
1290
1676
 
1291
1677
  // src/resolve/tokens.ts
1292
1678
  function applyDeploy(c, ev, rec, who, feeToTreasury) {
1293
- const { tokens, note } = c;
1679
+ const { tokens, applied, refused } = c;
1294
1680
  const v11 = ev.height >= V11_HEIGHT;
1295
1681
  if (tokens.has(rec.ticker)) {
1296
- note(ev, ev.id, "deploy", false, "ticker taken (first anchor wins)");
1682
+ refused(ev, ev.id, "deploy", "TOKEN_TICKER_TAKEN", "ticker taken (first anchor wins)");
1297
1683
  return;
1298
1684
  }
1299
1685
  if (v11 && feeToTreasury < BigInt(DEPLOY_FEE)) {
1300
- note(ev, ev.id, "deploy", false, "deploy fee unpaid");
1686
+ refused(ev, ev.id, "deploy", "TREASURY_FEE_UNPAID", "deploy fee unpaid");
1301
1687
  return;
1302
1688
  }
1303
1689
  const supply = parseAmount(rec.supply);
@@ -1309,29 +1695,29 @@ function applyDeploy(c, ev, rec, who, feeToTreasury) {
1309
1695
  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 }
1310
1696
  });
1311
1697
  if (v11) c.feesPaid += BigInt(DEPLOY_FEE);
1312
- note(ev, ev.id, "deploy", true);
1698
+ applied(ev, ev.id, "deploy", "TOKEN_DEPLOYED");
1313
1699
  }
1314
1700
  function applyMint(c, ev, rec, who) {
1315
- const { tokens, bal, note } = c;
1701
+ const { tokens, bal, applied, refused } = c;
1316
1702
  const tok = tokens.get(rec.ticker);
1317
1703
  if (!tok) {
1318
- note(ev, ev.id, "mint", false, "unknown ticker");
1704
+ refused(ev, ev.id, "mint", "TOKEN_UNKNOWN", "unknown ticker");
1319
1705
  return;
1320
1706
  }
1321
1707
  const remaining = tok.supply - tok.minted;
1322
1708
  if (remaining <= 0n) {
1323
- note(ev, ev.id, "mint", false, "supply exhausted");
1709
+ refused(ev, ev.id, "mint", "TOKEN_SUPPLY_EXHAUSTED", "supply exhausted");
1324
1710
  return;
1325
1711
  }
1326
1712
  let credit;
1327
1713
  if (tok.meta.mint === "issuer") {
1328
1714
  if (who !== tok.meta.deployer) {
1329
- note(ev, ev.id, "mint", false, "issuer-only mint");
1715
+ refused(ev, ev.id, "mint", "TOKEN_NOT_ISSUER", "issuer-only mint");
1330
1716
  return;
1331
1717
  }
1332
1718
  const req = rec.amount !== void 0 ? parseAmount(rec.amount) : null;
1333
1719
  if (req === null) {
1334
- note(ev, ev.id, "mint", false, "issuer mint requires amount");
1720
+ refused(ev, ev.id, "mint", "TOKEN_MINT_AMOUNT_REQUIRED", "issuer mint requires amount");
1335
1721
  return;
1336
1722
  }
1337
1723
  credit = req < remaining ? req : remaining;
@@ -1342,66 +1728,70 @@ function applyMint(c, ev, rec, who) {
1342
1728
  }
1343
1729
  tok.minted += credit;
1344
1730
  bal(rec.ticker, who).available += credit;
1345
- note(ev, ev.id, "mint", true, credit.toString());
1731
+ applied(ev, ev.id, "mint", "TOKEN_MINTED", credit.toString());
1346
1732
  }
1347
1733
  function applyTransfer(c, ev, rec, who) {
1348
- const { tokens, bal, note } = c;
1734
+ const { tokens, bal, applied, refused } = c;
1349
1735
  if (!tokens.has(rec.ticker)) {
1350
- note(ev, ev.id, "transfer", false, "unknown ticker");
1736
+ refused(ev, ev.id, "transfer", "TOKEN_UNKNOWN", "unknown ticker");
1351
1737
  return;
1352
1738
  }
1353
1739
  const amt = parseAmount(rec.amount);
1354
1740
  const from = bal(rec.ticker, who);
1355
1741
  if (from.available < amt) {
1356
- note(ev, ev.id, "transfer", false, "insufficient available balance");
1742
+ refused(ev, ev.id, "transfer", "TOKEN_BALANCE_LOW", "insufficient available balance");
1357
1743
  return;
1358
1744
  }
1359
1745
  from.available -= amt;
1360
1746
  bal(rec.ticker, rec.to.toLowerCase()).available += amt;
1361
- note(ev, ev.id, "transfer", true);
1747
+ applied(ev, ev.id, "transfer", "TOKEN_TRANSFERRED");
1362
1748
  }
1363
1749
  function applyTmeta(c, ev, rec, who) {
1364
- const { tokens, note } = c;
1750
+ const { tokens, applied, refused } = c;
1365
1751
  const v15 = ev.height >= V15_HEIGHT;
1366
1752
  if (!v15) {
1367
- note(ev, ev.id, "tmeta", false, "tmeta needs v1.5");
1753
+ refused(ev, ev.id, "tmeta", "GATE_NOT_ACTIVE", "tmeta needs v1.5");
1368
1754
  return;
1369
1755
  }
1370
1756
  const tok = tokens.get(rec.ticker);
1371
1757
  if (!tok) {
1372
- note(ev, ev.id, "tmeta", false, "unknown ticker");
1758
+ refused(ev, ev.id, "tmeta", "TOKEN_UNKNOWN", "unknown ticker");
1373
1759
  return;
1374
1760
  }
1375
1761
  if (who !== tok.meta.deployer) {
1376
- note(ev, ev.id, "tmeta", false, "issuer-only metadata");
1762
+ refused(ev, ev.id, "tmeta", "TOKEN_NOT_ISSUER", "issuer-only metadata");
1377
1763
  return;
1378
1764
  }
1379
1765
  tok.meta.tmeta = rec.hash;
1380
- note(ev, ev.id, "tmeta", true);
1766
+ applied(ev, ev.id, "tmeta", "TOKEN_META_SET");
1381
1767
  }
1382
1768
 
1383
1769
  // src/resolve.ts
1384
1770
  var ord = (a, b) => a < b ? -1 : a > b ? 1 : 0;
1771
+ function eventId(e) {
1772
+ return e.kind === "propose" ? e.id : e.txid;
1773
+ }
1774
+ function applyOrder(a, b) {
1775
+ return a.height - b.height || Number(a.kind === "attest") - Number(b.kind === "attest") || a.pos - b.pos || ord(eventId(a), eventId(b));
1776
+ }
1385
1777
  function resolve(events, tipHeight) {
1386
- const ordered = [...events].sort(
1387
- (a, b) => a.height - b.height || Number(a.kind === "attest") - Number(b.kind === "attest") || a.pos - b.pos || ord(
1388
- a.kind === "propose" ? a.id : a.txid,
1389
- b.kind === "propose" ? b.id : b.txid
1390
- )
1391
- );
1392
- const eid = (e) => e.kind === "propose" ? e.id : e.txid;
1778
+ return replay(events, tipHeight);
1779
+ }
1780
+ function replay(events, tipHeight, opts = {}) {
1781
+ const ordered = [...events].sort(applyOrder);
1393
1782
  const seenIds = /* @__PURE__ */ new Set();
1394
1783
  const applied = [];
1395
1784
  for (const e of ordered) {
1396
1785
  if (e.height >= V29_HEIGHT) {
1397
- const k = eid(e);
1786
+ const k = eventId(e);
1398
1787
  if (seenIds.has(k)) continue;
1399
1788
  seenIds.add(k);
1400
1789
  }
1401
1790
  applied.push(e);
1402
1791
  }
1403
- const c = createContext();
1404
- const { tokens, balances, names, recaptures, offers, bids, fclaims, log, note, sweepExpired } = c;
1792
+ const store = createStore(opts);
1793
+ const c = createContext(store);
1794
+ const { tokens, balances, names, recaptures, offers, bids, fclaims, log, refused, sweepExpired } = c;
1405
1795
  let pendingBlock = -1;
1406
1796
  const applyPendingCancels = () => {
1407
1797
  for (const f of c.pendingCancels) f();
@@ -1414,13 +1804,15 @@ function resolve(events, tipHeight) {
1414
1804
  pendingBlock = ev.height;
1415
1805
  }
1416
1806
  sweepExpired(ev.height);
1807
+ store.verify(ev.height);
1417
1808
  const feeToTreasury = ev.kind === "propose" ? ptAmt((ev.paidTo ?? {})[TREASURY_ADDR]) : 0n;
1418
1809
  if (ev.kind === "propose") {
1419
- const rec = parseRecord(ev.uri, ev.payloadHash);
1420
- if (!rec) {
1421
- note(ev, ev.id, "invalid", false, "unparseable/non-canonical record");
1810
+ const parsed = explainRecord(ev.uri, ev.payloadHash);
1811
+ if (!parsed.ok) {
1812
+ refused(ev, ev.id, "invalid", parsed.code, "unparseable/non-canonical record");
1422
1813
  continue;
1423
1814
  }
1815
+ const rec = parsed.record;
1424
1816
  const who = ev.proposer.toLowerCase();
1425
1817
  switch (rec.t) {
1426
1818
  case "deploy":
@@ -1475,6 +1867,7 @@ function resolve(events, tipHeight) {
1475
1867
  }
1476
1868
  applyPendingCancels();
1477
1869
  sweepExpired(tipHeight + 1);
1870
+ store.verify(tipHeight + 1, true);
1478
1871
  const tokensOut = {};
1479
1872
  for (const [t, tok] of [...tokens.entries()].sort(([a], [b]) => ord(a, b))) tokensOut[t] = { ...tok.meta, minted: tok.minted.toString() };
1480
1873
  const balancesOut = {};
@@ -1882,6 +2275,176 @@ function burnedPayment(paidTo, payer, offer2) {
1882
2275
  return { treasury: read(TREASURY_ADDR), counterparty };
1883
2276
  }
1884
2277
 
2278
+ // src/events.ts
2279
+ import { isWellFormedUtf16 as isWellFormedUtf162 } from "@inversealtruism/csd-codec";
2280
+ var CAIRNX_EVENT_RULE = Object.freeze({ domain: DOMAIN, activationHeight: ACTIVATION_HEIGHT });
2281
+ var fail = (what) => {
2282
+ throw new Error(`events rule: ${what}`);
2283
+ };
2284
+ var isIndex = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
2285
+ function hexOf(v, bytes, what) {
2286
+ const h = typeof v === "string" && v.startsWith("0x") ? v.slice(2) : v;
2287
+ if (typeof h !== "string" || h.length !== bytes * 2 || !/^[0-9a-fA-F]*$/.test(h)) return fail(`${what} is not ${bytes}-byte hex`);
2288
+ return "0x" + h.toLowerCase();
2289
+ }
2290
+ function u64Of(v, what) {
2291
+ if (typeof v === "bigint" && v >= 0n && v < 1n << 64n) return v;
2292
+ if (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 2 ** 53) return v;
2293
+ if (typeof v === "number" && Number.isInteger(v) && v > 2 ** 53) return fail(`${what} above 2^53 must be passed as a bigint`);
2294
+ return fail(`${what} is not a u64`);
2295
+ }
2296
+ function u32Of(v, what) {
2297
+ return typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 4294967295 ? v : fail(`${what} is not a u32`);
2298
+ }
2299
+ function checkRule(rule) {
2300
+ const d = rule?.domain;
2301
+ if (typeof d !== "string" || d === "" || !isWellFormedUtf162(d) || d.includes("\0") || d.includes(""))
2302
+ fail("the rule's domain must be non-empty, well-formed text without U+0000 or U+0001");
2303
+ if (!isIndex(rule.activationHeight)) fail("the rule's activation height must be a safe integer >= 0");
2304
+ }
2305
+ var kindOf = (app) => {
2306
+ const t = app?.type;
2307
+ return t === "None" ? "none" : t === "Propose" ? "propose" : t === "Attest" ? "attest" : fail(`unknown app type ${String(t)}`);
2308
+ };
2309
+ var domainOf = (app) => typeof app.domain === "string" ? app.domain : fail("a Propose domain is not text");
2310
+ function paidToOf(outputs) {
2311
+ if (!Array.isArray(outputs)) fail("outputs is not a list");
2312
+ const counted = [];
2313
+ for (const o of outputs) {
2314
+ const addr = hexOf(o?.scriptPubkey, 20, "script_pubkey"), value = u64Of(o?.value, "output value");
2315
+ if (value <= Number.MAX_SAFE_INTEGER) counted.push({ addr, value: Number(value) });
2316
+ }
2317
+ return paidToFromOutputs(counted);
2318
+ }
2319
+ function eventOfTx(t, height, author, rule = CAIRNX_EVENT_RULE) {
2320
+ checkRule(rule);
2321
+ if (!isIndex(height)) fail("height is not a safe integer >= 0");
2322
+ if (!isIndex(t?.pos)) fail("pos is not a safe integer >= 0");
2323
+ const txid = hexOf(t.txid, 32, "txid");
2324
+ const app = t.tx?.app;
2325
+ const kind = kindOf(app);
2326
+ if (kind === "none" || height < rule.activationHeight) return null;
2327
+ if (t.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2328
+ if (kind === "propose" && domainOf(app) !== rule.domain) return null;
2329
+ const paidTo = paidToOf(t.tx.outputs), who = hexOf(author, 20, "author");
2330
+ if (kind === "propose") {
2331
+ const p = app;
2332
+ const uri = p.uri;
2333
+ if (typeof uri !== "string" || !isWellFormedUtf162(uri)) return fail("uri is not well-formed text");
2334
+ const e = u64Of(p.expiresEpoch, "expiresEpoch");
2335
+ return {
2336
+ kind: "propose",
2337
+ id: txid,
2338
+ proposer: who,
2339
+ uri: uri.replaceAll("\0", ""),
2340
+ payloadHash: hexOf(p.payloadHash, 32, "payloadHash"),
2341
+ expiresEpoch: e <= Number.MAX_SAFE_INTEGER ? Number(e) : 2 ** 53,
2342
+ height,
2343
+ pos: t.pos,
2344
+ paidTo
2345
+ };
2346
+ }
2347
+ const a = app;
2348
+ return {
2349
+ kind: "attest",
2350
+ txid,
2351
+ proposalId: hexOf(a.proposalId, 32, "proposalId"),
2352
+ attester: who,
2353
+ score: u32Of(a.score, "score"),
2354
+ confidence: u32Of(a.confidence, "confidence"),
2355
+ height,
2356
+ pos: t.pos,
2357
+ paidTo
2358
+ };
2359
+ }
2360
+ function blockMembers(height, txs, sofar, rule = CAIRNX_EVENT_RULE) {
2361
+ checkRule(rule);
2362
+ if (!isIndex(height)) fail("height is not a safe integer >= 0");
2363
+ if (height < rule.activationHeight) return [];
2364
+ if (!Array.isArray(txs)) fail("txs is not a list");
2365
+ const ids = /* @__PURE__ */ new Set(), proposals = /* @__PURE__ */ new Set();
2366
+ const read = [];
2367
+ let last = -1;
2368
+ for (const item of txs) {
2369
+ if (!isIndex(item?.pos) || item.pos <= last) fail("positions are not safe integers >= 0 in strictly increasing order");
2370
+ last = item.pos;
2371
+ const id = hexOf(item.txid, 32, "txid");
2372
+ if (ids.has(id)) fail(`txid ${id} is repeated in the block`);
2373
+ ids.add(id);
2374
+ const kind = kindOf(item.tx?.app);
2375
+ if (kind === "none") continue;
2376
+ if (item.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2377
+ if (kind === "propose") {
2378
+ if (domainOf(item.tx.app) !== rule.domain || sofar.eventIds.has(id)) continue;
2379
+ proposals.add(id);
2380
+ read.push({ item, kind, id });
2381
+ } else read.push({ item, kind, id, proposal: hexOf(item.tx.app.proposalId, 32, "proposalId") });
2382
+ }
2383
+ 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 }));
2384
+ }
2385
+ function blockEvents(height, txs, sofar, authors, rule = CAIRNX_EVENT_RULE) {
2386
+ const members = blockMembers(height, txs, sofar, rule);
2387
+ if (!Array.isArray(authors) || authors.length !== members.length) fail(`the block has ${members.length} members, not ${authors?.length} authors`);
2388
+ const events = members.map((m, i) => eventOfTx(m.item, height, authors[i], rule) ?? fail("a member mapped to no event"));
2389
+ return [...events.filter((e) => e.kind === "propose"), ...events.filter((e) => e.kind === "attest")];
2390
+ }
2391
+
2392
+ // src/hashes.ts
2393
+ import { bytesToHex, concatBytes, hexToBytes, utf8ToBytes } from "@inversealtruism/csd-codec";
2394
+ import { sha256 } from "@noble/hashes/sha256";
2395
+ var EVENTS_HASH_START = "0x" + "00".repeat(32);
2396
+ var FINAL_DEPTH = 12;
2397
+ var fail2 = (what) => {
2398
+ throw new Error(`events hash: ${what}`);
2399
+ };
2400
+ var hex = (b) => "0x" + bytesToHex(b);
2401
+ function bytesOf(v, re, what) {
2402
+ return typeof v === "string" && re.test(v) ? hexToBytes(v.slice(2)) : fail2(`${what} is not 0x and lowercase hex of its length`);
2403
+ }
2404
+ function stateHash(state) {
2405
+ return hex(sha256(utf8ToBytes(canonicalState(state))));
2406
+ }
2407
+ function rowOf(e, height) {
2408
+ const kind = e?.kind;
2409
+ if (kind !== "propose" && kind !== "attest") return fail2("an event's kind is neither propose nor attest");
2410
+ if (e.height !== height) fail2(`an event at height ${String(e.height)} is in the block at ${height}`);
2411
+ 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]");
2412
+ const p = e, a = e;
2413
+ const id = bytesOf(kind === "propose" ? p.id : a.txid, HASH_RE, "an event's transaction id");
2414
+ const author = bytesOf(kind === "propose" ? p.proposer : a.attester, ADDR_RE, "an event's author");
2415
+ const row = new Uint8Array(56);
2416
+ new DataView(row.buffer).setUint32(0, e.pos);
2417
+ row.set(id, 4);
2418
+ row.set(author, 36);
2419
+ return { pos: e.pos, row };
2420
+ }
2421
+ function eventsHashStep(prev, height, events) {
2422
+ const e = bytesOf(prev, HASH_RE, "the previous value");
2423
+ if (!Number.isSafeInteger(height) || height < 0) fail2("height is not an integer in [0, 2^53 - 1]");
2424
+ if (!Array.isArray(events)) fail2("events is not a list");
2425
+ if (events.length === 0) return prev;
2426
+ const rows = events.map((x) => rowOf(x, height)).sort((x, y) => x.pos - y.pos);
2427
+ 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`);
2428
+ const head = new Uint8Array(8);
2429
+ new DataView(head.buffer).setBigUint64(0, BigInt(height));
2430
+ const b = sha256(concatBytes(head, ...rows.map((r) => r.row)));
2431
+ return hex(sha256(concatBytes(e, b)));
2432
+ }
2433
+ function eventsHash(events) {
2434
+ if (!Array.isArray(events)) fail2("events is not a list");
2435
+ let value = EVENTS_HASH_START, last = -1;
2436
+ for (let i = 0; i < events.length; ) {
2437
+ const height = events[i]?.height;
2438
+ let j = i + 1;
2439
+ while (j < events.length && events[j]?.height === height) j++;
2440
+ value = eventsHashStep(value, height, events.slice(i, j));
2441
+ if (height < last) fail2(`height ${height} follows height ${last}`);
2442
+ last = height;
2443
+ i = j;
2444
+ }
2445
+ return value;
2446
+ }
2447
+
1885
2448
  // src/fillclosed.ts
1886
2449
  var lc = (v) => String(v).toLowerCase();
1887
2450
  function myProvenFillClosedOffer(fill, fclaim2, offerEv, me, grantHeight) {
@@ -1945,9 +2508,129 @@ function provenOfferRefusal(rec, tx) {
1945
2508
  if (tx.domain !== DOMAIN) return `not a ${DOMAIN} Propose (domain ${JSON.stringify(String(tx.domain))})`;
1946
2509
  if (beforeActivation(tx.height)) return `anchored before CairnX activation (block ${ACTIVATION_HEIGHT})`;
1947
2510
  const ee = typeof tx.expiresEpoch === "bigint" ? Number(tx.expiresEpoch) : tx.expiresEpoch;
1948
- return offerEnvelopeRefusal(rec, String(tx.seller).toLowerCase(), tx.height, ee);
2511
+ return offerEnvelopeRefusal(rec, String(tx.seller).toLowerCase(), tx.height, ee)?.note ?? null;
1949
2512
  }
1950
2513
 
2514
+ // src/codes.ts
2515
+ var TABLE = {
2516
+ TOKEN_DEPLOYED: "applied",
2517
+ TOKEN_MINTED: "applied",
2518
+ TOKEN_TRANSFERRED: "applied",
2519
+ TOKEN_META_SET: "applied",
2520
+ NAME_COMMITTED: "applied",
2521
+ NAME_REGISTERED: "applied",
2522
+ NAME_REGISTERED_DISPLACED: "applied",
2523
+ NAME_RESERVED: "applied",
2524
+ NAME_RESERVED_DISPLACED: "applied",
2525
+ NAME_RECAPTURE_RESERVED: "applied",
2526
+ NAME_RECAPTURE_RESERVED_DISPLACED: "applied",
2527
+ NAME_RECLAIMED: "applied",
2528
+ NAME_FINALIZED: "applied",
2529
+ NAME_RECAPTURE_FINALIZED: "applied",
2530
+ NAME_TRANSFERRED: "applied",
2531
+ NAME_ADDR_SET: "applied",
2532
+ NAME_PROFILE_SET: "applied",
2533
+ NAME_RENEWED: "applied",
2534
+ OFFER_CREATED: "applied",
2535
+ OFFER_BULK_CANCELLED: "applied",
2536
+ OFFER_CANCELLED: "applied",
2537
+ BID_CREATED: "applied",
2538
+ BID_CANCELLED: "applied",
2539
+ FILL_APPLIED: "applied",
2540
+ FILL_PARTIAL: "applied",
2541
+ CLAIM_GRANTED: "applied",
2542
+ GATE_NOT_ACTIVE: "refused",
2543
+ CLAIM_LEGACY_SUNSET: "refused",
2544
+ TOKEN_TICKER_TAKEN: "refused",
2545
+ TOKEN_UNKNOWN: "refused",
2546
+ TOKEN_NOT_ISSUER: "refused",
2547
+ TOKEN_SUPPLY_EXHAUSTED: "refused",
2548
+ TOKEN_MINT_AMOUNT_REQUIRED: "refused",
2549
+ TOKEN_BALANCE_LOW: "refused",
2550
+ TREASURY_FEE_UNPAID: "refused",
2551
+ NAME_NO_COMMIT: "refused",
2552
+ NAME_SALT_REQUIRED: "refused",
2553
+ NAME_TAKEN_EARLIER: "refused",
2554
+ NAME_TAKEN_PURCHASED: "refused",
2555
+ NAME_SALT_MISMATCH: "refused",
2556
+ NAME_FINALIZE_TOO_EARLY: "refused",
2557
+ NAME_RESERVATION_EXPIRED: "refused",
2558
+ NAME_NOT_LAPSED: "refused",
2559
+ NAME_NO_RESERVATION: "refused",
2560
+ NAME_NOT_OWNER: "refused",
2561
+ NAME_PENDING: "refused",
2562
+ NAME_LAPSED: "refused",
2563
+ NAME_NO_LIVE_LEASE: "refused",
2564
+ NAME_GRACE_OWNER_ONLY: "refused",
2565
+ NAME_LOCKED: "refused",
2566
+ NAME_TOO_YOUNG: "refused",
2567
+ OFFER_LEASE_TOO_SHORT: "refused",
2568
+ OFFER_TAKER_REQUIRED: "refused",
2569
+ OFFER_PAYTO_TREASURY: "refused",
2570
+ OFFER_UNKNOWN: "refused",
2571
+ OFFER_NOT_OPEN: "refused",
2572
+ OFFER_NOT_SELLER: "refused",
2573
+ OFFER_FIRM_QUOTE: "refused",
2574
+ OFFER_CANCEL_HOLD_LIVE: "refused",
2575
+ OFFER_CLOSED_BEFORE_CANCEL: "refused",
2576
+ BID_NOT_BIDDER: "refused",
2577
+ BID_NOT_OPEN: "refused",
2578
+ EXPIRY_UNSAFE: "refused",
2579
+ EXPIRY_PAST: "refused",
2580
+ EXPIRY_TOO_LONG: "refused",
2581
+ FILL_FCLAIM_NOT_CURRENT: "refused",
2582
+ FILL_NOT_TAKER: "refused",
2583
+ FILL_NO_TOKEN_MARKER: "refused",
2584
+ FILL_OPEN_LANE_CLOSED: "refused",
2585
+ FILL_WRONG_TARGET: "refused",
2586
+ FILL_NO_LIVE_CLAIM: "refused",
2587
+ FILL_BELOW_MIN: "refused",
2588
+ FILL_ZERO_DELIVERY: "refused",
2589
+ FILL_UNDERPAID: "refused",
2590
+ FILL_REBATE_UNPAID: "refused",
2591
+ CLAIM_TAKER_BOUND: "refused",
2592
+ CLAIM_TOKEN_PRICED: "refused",
2593
+ CLAIM_HOLD_LIVE: "refused",
2594
+ CLAIM_COOLDOWN: "refused",
2595
+ CLAIM_OUTLIVES_OFFER: "refused",
2596
+ CLAIM_TOO_FAR_AHEAD: "refused",
2597
+ CAP_PENDING_RESERVATIONS: "refused",
2598
+ CAP_PENDING_RECAPTURES: "refused",
2599
+ CAP_LIVE_HOLDS: "refused",
2600
+ INVARIANT_BROKEN: "refused",
2601
+ RECORD_TOO_LARGE: "refused",
2602
+ RECORD_NOT_OBJECT: "refused",
2603
+ RECORD_NOT_CANONICAL: "refused",
2604
+ RECORD_HASH_MISMATCH: "refused",
2605
+ RECORD_LONE_SURROGATE: "refused",
2606
+ RECORD_NOT_V1: "refused",
2607
+ RECORD_UNKNOWN_TYPE: "refused",
2608
+ RECORD_EXTRA_KEY: "refused",
2609
+ RECORD_BAD_SHAPE: "refused",
2610
+ RECORD_SAME_TOKEN: "refused",
2611
+ RECORD_BAD_TICKER: "refused",
2612
+ RECORD_BAD_NAME: "refused",
2613
+ RECORD_NAME_RESERVED: "refused",
2614
+ RECORD_BAD_ADDRESS: "refused",
2615
+ RECORD_BAD_AMOUNT: "refused",
2616
+ RECORD_AMOUNT_TOO_LARGE: "refused",
2617
+ RECORD_AMOUNT_ZERO: "refused",
2618
+ RECORD_MIN_ABOVE_WANT: "refused",
2619
+ RECORD_BAD_HASH: "refused",
2620
+ RECORD_BAD_SALT: "refused",
2621
+ RECORD_BAD_DECIMALS: "refused",
2622
+ RECORD_BAD_MINT_MODE: "refused",
2623
+ RECORD_BAD_TEXT: "refused",
2624
+ RECORD_BAD_TS: "refused",
2625
+ RECORD_PROFILE_TOO_MANY_KEYS: "refused",
2626
+ RECORD_PROFILE_BAD_KEY: "refused",
2627
+ RECORD_PROFILE_BAD_VALUE: "refused",
2628
+ RECORD_PROFILE_VALUE_TOO_LONG: "refused"
2629
+ };
2630
+ var REASON_CODES = Object.freeze(Object.keys(TABLE));
2631
+ var REASON_CODE_OUTCOME = Object.freeze({ ...TABLE });
2632
+ var CAP_CODES = Object.freeze(["CAP_PENDING_RESERVATIONS", "CAP_PENDING_RECAPTURES", "CAP_LIVE_HOLDS"]);
2633
+
1951
2634
  // src/index.ts
1952
2635
  import {
1953
2636
  canonicalJson as canonicalJson2,
@@ -1964,6 +2647,8 @@ export {
1964
2647
  ADDR_RE,
1965
2648
  AMOUNT_RE,
1966
2649
  BID_KEYS,
2650
+ CAIRNX_EVENT_RULE,
2651
+ CAP_CODES,
1967
2652
  CLAIM_ATTACKER_Q,
1968
2653
  CLAIM_COOLDOWN_BLOCKS,
1969
2654
  CLAIM_FILL_GRACE_BLOCKS,
@@ -1977,6 +2662,7 @@ export {
1977
2662
  DEPLOY_KEYS,
1978
2663
  DOMAIN,
1979
2664
  EPOCH_LEN2 as EPOCH_LEN,
2665
+ EVENTS_HASH_START,
1980
2666
  FCLAIM_KEYS,
1981
2667
  FCLAIM_MAX_EPOCH_AHEAD,
1982
2668
  FCLAIM_MAX_HOLD_SPAN,
@@ -1986,6 +2672,7 @@ export {
1986
2672
  FEE_GATE_MARGIN_BLOCKS,
1987
2673
  FILL_TIP_MARGIN,
1988
2674
  FINALIZE_TIP_MARGIN,
2675
+ FINAL_DEPTH,
1989
2676
  GAP_NEEDED,
1990
2677
  HALVING_INTERVAL,
1991
2678
  HASH_RE,
@@ -2019,11 +2706,14 @@ export {
2019
2706
  PKEY,
2020
2707
  PROFILE_MAX_KEYS,
2021
2708
  PROFILE_MAX_VALUE_BYTES,
2709
+ REASON_CODES,
2710
+ REASON_CODE_OUTCOME,
2022
2711
  REBATE_BPS,
2023
2712
  REBATE_FLAT,
2024
2713
  REG_COMMIT_MAX_BLOCKS,
2025
2714
  REG_FINALIZE_GRACE_BLOCKS,
2026
2715
  RESERVED_NAMES,
2716
+ RecordError,
2027
2717
  SALT_RE,
2028
2718
  SCAN_MARGIN,
2029
2719
  SCORE_CANCEL,
@@ -2052,10 +2742,13 @@ export {
2052
2742
  V28_HEIGHT,
2053
2743
  V29_HEIGHT,
2054
2744
  ZERO_ADDR,
2745
+ applyOrder,
2055
2746
  beforeActivation,
2056
2747
  bid,
2057
2748
  bindOfferTerms,
2058
2749
  bindProvenOffer,
2750
+ blockEvents,
2751
+ blockMembers,
2059
2752
  blockReward2 as blockReward,
2060
2753
  buildFeeHeight,
2061
2754
  buildRecord,
@@ -2068,7 +2761,12 @@ export {
2068
2761
  countOtherHoldsAtGrant,
2069
2762
  deploy,
2070
2763
  epochOf,
2764
+ eventId,
2765
+ eventOfTx,
2766
+ eventsHash,
2767
+ eventsHashStep,
2071
2768
  expiredClaimFee,
2769
+ explainRecord,
2072
2770
  fclaim,
2073
2771
  fclaimEpochFor,
2074
2772
  fclaimHoldEnd,
@@ -2113,6 +2811,7 @@ export {
2113
2811
  requiredClaimDepth,
2114
2812
  requiredFillOutputs,
2115
2813
  resolve,
2814
+ stateHash,
2116
2815
  tokenMeta,
2117
2816
  tradeFee,
2118
2817
  transfer,