@inversealtruism/cairnx-core 0.2.3 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -109,22 +109,32 @@ var offerExpiryHeightOf = (expiresEpoch, anchorHeight) => {
109
109
  const capped = (epochOf(anchorHeight) + MAX_OFFER_EPOCHS + 1) * EPOCH_LEN;
110
110
  return Math.min(raw, Math.max(V21_HEIGHT, capped));
111
111
  };
112
+ var offerFillTooLate = (expiresAt, tip) => expiresAt - 1 < tip + FILL_TIP_MARGIN;
112
113
  var isNameGive = (g) => typeof g.name === "string";
113
114
  var isTokenWant = (w) => typeof w.ticker === "string";
114
115
 
115
116
  // src/records.ts
116
117
  import { canonicalJson, payloadHash, isWellFormedUtf16 } from "@inversealtruism/csd-codec";
117
- function parseAmount(s, opts = {}) {
118
- 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";
119
120
  const v = BigInt(s);
120
- if (v > MAX_AMOUNT) return null;
121
- 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";
122
123
  return v;
123
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
+ };
124
133
  var isAddr = (a) => typeof a === "string" && ADDR_RE.test(a);
125
134
  var isTicker = (t) => typeof t === "string" && TICKER_RE.test(t);
126
135
  var isHash = (h) => typeof h === "string" && HASH_RE.test(h);
127
- 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;
128
138
  function nameCommit(name, salt, owner) {
129
139
  return payloadHash({ t: "cairnx:name:commit:v1", name, salt, owner: owner.toLowerCase() });
130
140
  }
@@ -150,172 +160,201 @@ var NFINALIZE_KEYS = /* @__PURE__ */ new Set(["v", "t", "name", "salt"]);
150
160
  var NPROFILE_KEYS = /* @__PURE__ */ new Set(["v", "t", "name", "p"]);
151
161
  var FCLAIM_KEYS = /* @__PURE__ */ new Set(["v", "t", "offer"]);
152
162
  function parseRecord(uri, payloadHashHex) {
153
- 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";
154
172
  let obj;
155
173
  try {
156
174
  obj = JSON.parse(uri);
157
175
  } catch {
158
- return null;
176
+ return "RECORD_NOT_OBJECT";
159
177
  }
160
- 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";
161
179
  try {
162
- if (canonicalJson(obj) !== uri) return null;
163
- if (payloadHash(obj).toLowerCase() !== payloadHashHex.toLowerCase()) return null;
180
+ if (canonicalJson(obj) !== uri) return "RECORD_NOT_CANONICAL";
164
181
  } catch {
165
- return null;
182
+ return "RECORD_NOT_CANONICAL";
166
183
  }
167
- 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";
168
190
  const r = obj;
169
- 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;
170
193
  switch (r.t) {
171
194
  case "deploy": {
172
- if (!onlyKeys(r, DEPLOY_KEYS)) return null;
173
- if (!isTicker(r.ticker)) return null;
174
- if (r.name !== void 0 && (typeof r.name !== "string" || r.name.length > 32)) return null;
175
- if (typeof r.decimals !== "number" || !Number.isInteger(r.decimals) || r.decimals < 0 || r.decimals > MAX_TOKEN_DECIMALS) return null;
176
- if (parseAmount(r.supply) === null) return null;
177
- if (r.mint !== "open" && r.mint !== "issuer") return null;
178
- if (r.mint === "open" && parseAmount(r.mintLimit) === null) return null;
179
- 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";
180
203
  return r;
181
204
  }
182
205
  case "mint": {
183
- if (!onlyKeys(r, MINT_KEYS)) return null;
184
- if (!isTicker(r.ticker)) return null;
185
- 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;
186
209
  return r;
187
210
  }
188
211
  case "transfer": {
189
- if (!onlyKeys(r, TRANSFER_KEYS)) return null;
190
- if (!isTicker(r.ticker) || !isAddr(r.to) || parseAmount(r.amount) === null) return null;
191
- if (r.memo !== void 0 && (typeof r.memo !== "string" || r.memo.length > 64)) return null;
192
- 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";
193
218
  return r;
194
219
  }
195
220
  case "offer": {
196
- if (!onlyKeys(r, OFFER_KEYS)) return null;
221
+ if (!onlyKeys(r, OFFER_KEYS)) return "RECORD_EXTRA_KEY";
197
222
  const g = r.give;
198
223
  const w = r.want;
199
- 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";
200
225
  const gKeys = Object.keys(g).sort().join(",");
201
226
  if (gKeys === "amount,ticker") {
202
- 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;
203
229
  } else if (gKeys === "name") {
204
- if (!isName(g.name)) return null;
205
- } else return null;
230
+ if (fault = nameFault(g.name)) return fault;
231
+ } else return "RECORD_BAD_SHAPE";
206
232
  const wKeys = Object.keys(w).filter((k) => k !== "payto").sort().join(",");
207
233
  if (wKeys === "value") {
208
- if (parseAmount(w.value, { allowZero: true }) === null) return null;
234
+ if (fault = amountFault(w.value, true)) return fault;
209
235
  } else if (wKeys === "amount,ticker") {
210
- if (!isTicker(w.ticker) || parseAmount(w.amount, { allowZero: true }) === null) return null;
211
- if (gKeys === "amount,ticker" && w.ticker === g.ticker) return null;
212
- if (r.min !== void 0) return null;
213
- } else return null;
214
- 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";
215
242
  if (r.min !== void 0) {
216
- if (gKeys !== "amount,ticker" || wKeys !== "value") return null;
217
- const mn = parseAmount(r.min);
218
- 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";
219
246
  }
220
- if (r.bid !== void 0 && !isHash(r.bid)) return null;
221
- if (r.taker !== void 0 && !isAddr(r.taker)) return null;
222
- if (r.memo !== void 0 && (typeof r.memo !== "string" || r.memo.length > 64)) return null;
223
- 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";
224
251
  return r;
225
252
  }
226
253
  case "ocancel": {
227
- if (r.ticker !== void 0 && r.name !== void 0) return null;
228
- if (r.ticker !== void 0 && !isTicker(r.ticker)) return null;
229
- 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;
230
257
  const n = Object.keys(r).length;
231
- 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";
232
259
  return r;
233
260
  }
234
261
  case "bid": {
235
- if (!onlyKeys(r, BID_KEYS)) return null;
262
+ if (!onlyKeys(r, BID_KEYS)) return "RECORD_EXTRA_KEY";
236
263
  const w = r.want;
237
264
  const g = r.give;
238
- 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";
239
266
  const wKeys = Object.keys(w).sort().join(",");
240
267
  if (wKeys === "amount,ticker") {
241
- 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;
242
270
  } else if (wKeys === "name") {
243
- if (!isName(w.name)) return null;
244
- } else return null;
245
- if (Object.keys(g).sort().join(",") !== "value" || parseAmount(g.value) === null) return null;
246
- if (r.memo !== void 0 && (typeof r.memo !== "string" || r.memo.length > 64)) return null;
247
- 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";
248
277
  return r;
249
278
  }
250
279
  // ── names (v1.1) ──
251
280
  case "ncommit": {
252
- if (!isHash(r.commit)) return null;
253
- 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";
254
283
  return r;
255
284
  }
256
285
  case "name": {
257
- if (!onlyKeys(r, NAME_KEYS)) return null;
258
- if (!isName(r.name)) return null;
259
- 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";
260
289
  return r;
261
290
  }
262
291
  case "nfinalize": {
263
- if (!onlyKeys(r, NFINALIZE_KEYS)) return null;
264
- if (!isName(r.name)) return null;
265
- 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";
266
295
  return r;
267
296
  }
268
297
  case "nxfer": {
269
- if (!isName(r.name) || !isAddr(r.to)) return null;
270
- 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";
271
301
  return r;
272
302
  }
273
303
  case "nset": {
274
- if (!isName(r.name) || !isAddr(r.addr)) return null;
275
- 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";
276
307
  return r;
277
308
  }
278
309
  // ── v1.5 ──
279
310
  case "nrenew": {
280
- if (!isName(r.name)) return null;
281
- 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";
282
313
  return r;
283
314
  }
284
315
  case "nprofile": {
285
- if (!onlyKeys(r, NPROFILE_KEYS)) return null;
286
- if (!isName(r.name)) return null;
316
+ if (!onlyKeys(r, NPROFILE_KEYS)) return "RECORD_EXTRA_KEY";
317
+ if (fault = nameFault(r.name)) return fault;
287
318
  const p = r.p;
288
- if (!p || typeof p !== "object" || Array.isArray(p)) return null;
319
+ if (!p || typeof p !== "object" || Array.isArray(p)) return "RECORD_BAD_SHAPE";
289
320
  const keys = Object.keys(p);
290
- if (keys.length > PROFILE_MAX_KEYS) return null;
321
+ if (keys.length > PROFILE_MAX_KEYS) return "RECORD_PROFILE_TOO_MANY_KEYS";
291
322
  for (const k of keys) {
292
- if (!PKEY.test(k)) return null;
323
+ if (!PKEY.test(k)) return "RECORD_PROFILE_BAD_KEY";
293
324
  const val = p[k];
294
- if (typeof val !== "string") return null;
295
- 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";
296
327
  }
297
328
  return r;
298
329
  }
299
330
  case "tmeta": {
300
- if (!isTicker(r.ticker)) return null;
301
- if (typeof r.hash !== "string" || !HASH_RE.test(r.hash)) return null;
302
- 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";
303
334
  return r;
304
335
  }
305
336
  case "fclaim": {
306
- if (!onlyKeys(r, FCLAIM_KEYS)) return null;
307
- 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";
308
339
  return r;
309
340
  }
310
341
  default:
311
- return null;
342
+ return "RECORD_UNKNOWN_TYPE";
312
343
  }
313
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
+ };
314
353
  function buildRecord(record) {
315
354
  const uri = canonicalJson(record);
316
355
  const ph = payloadHash(record);
317
- const back = parseRecord(uri, ph);
318
- 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);
319
358
  return { record, uri, payloadHash: ph };
320
359
  }
321
360
  var deploy = (r) => buildRecord({ v: 1, t: "deploy", ...r });
@@ -341,33 +380,12 @@ function ptAmt(v) {
341
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;
342
381
  var claimGrace = (o) => o.claimUntilHeight !== void 0 ? claimGraceOf(o.claimUntilHeight, o.claimTxid) : 0;
343
382
  var claimHeld = (o, height) => o.claimedBy !== void 0 && o.claimUntilHeight !== void 0 && height < o.claimUntilHeight + claimGrace(o);
344
- function createContext() {
383
+ function createContext(store) {
345
384
  const tokens = /* @__PURE__ */ new Map();
346
385
  const balances = /* @__PURE__ */ new Map();
347
- const names = /* @__PURE__ */ new Map();
348
386
  const commits = /* @__PURE__ */ new Map();
349
- const recaptures = /* @__PURE__ */ new Map();
350
- const offers = /* @__PURE__ */ new Map();
351
387
  const offerLock = /* @__PURE__ */ new Map();
352
- const bids = /* @__PURE__ */ new Map();
353
- const openOffers = /* @__PURE__ */ new Set();
354
- const openBids = /* @__PURE__ */ new Set();
355
- const pendingNames = /* @__PURE__ */ new Set();
356
- const setOfferStatus = (o, status) => {
357
- o.status = status;
358
- if (status === "open") openOffers.add(o.id);
359
- else openOffers.delete(o.id);
360
- };
361
- const setBidStatus = (b, status) => {
362
- b.status = status;
363
- if (status === "open") openBids.add(b.id);
364
- else openBids.delete(b.id);
365
- };
366
- const putName = (nm, n) => {
367
- names.set(nm, n);
368
- if (n.pending) pendingNames.add(nm);
369
- else pendingNames.delete(nm);
370
- };
388
+ const { names, recaptures, offers, bids, setOfferStatus, setBidStatus, putName } = store;
371
389
  const fclaims = /* @__PURE__ */ new Map();
372
390
  const log = [];
373
391
  const bal = (ticker, addr) => {
@@ -383,7 +401,6 @@ function createContext() {
383
401
  }
384
402
  return b;
385
403
  };
386
- const note = (e, id, kind, ok, why) => log.push({ height: e.height, pos: e.pos, id, kind, ok, ...why ? { note: why } : {} });
387
404
  const releaseGive = (o) => {
388
405
  if (isNameGive(o.give)) {
389
406
  const n = names.get(o.give.name);
@@ -395,66 +412,27 @@ function createContext() {
395
412
  b.available += amt;
396
413
  }
397
414
  };
398
- const sweepExpired = (height) => {
399
- const ep = epochOf(height);
400
- for (const id of [...openOffers]) {
401
- const o = offers.get(id);
402
- if (!o || o.status !== "open") {
403
- openOffers.delete(id);
404
- continue;
405
- }
406
- if (ep > effExpiry(o, height)) {
407
- releaseGive(o);
408
- setOfferStatus(o, "expired");
409
- }
410
- }
411
- for (const id of [...openBids]) {
412
- const b = bids.get(id);
413
- if (!b || b.status !== "open") {
414
- openBids.delete(id);
415
- continue;
416
- }
417
- if (ep > effExpiry(b, height)) setBidStatus(b, "expired");
418
- }
419
- for (const nm of [...pendingNames]) {
420
- const n = names.get(nm);
421
- if (!n || !n.pending) {
422
- pendingNames.delete(nm);
423
- continue;
424
- }
425
- if (n.finalizeBy !== void 0 && height > n.finalizeBy) {
426
- names.delete(nm);
427
- pendingNames.delete(nm);
428
- }
429
- }
430
- for (const nm of [...recaptures.keys()]) {
431
- const r = recaptures.get(nm);
432
- if (height > r.finalizeBy) recaptures.delete(nm);
433
- }
434
- };
415
+ const sweepExpired = (height) => store.sweep(height, releaseGive);
435
416
  const markBidDone = (o, buyer) => {
436
417
  if (!o.bid) return;
437
418
  const b = bids.get(o.bid);
438
419
  if (b && b.status === "open" && b.bidder === buyer) setBidStatus(b, "done");
439
420
  };
440
421
  const voidOpenNameOffers = (name, height) => {
441
- for (const o of offers.values()) if (o.status === "open" && isNameGive(o.give) && o.give.name === name) {
442
- if (height >= V28_HEIGHT && o.claimTxid !== void 0 && claimHeld(o, height)) continue;
422
+ for (const o of store.voidTargets(name, height)) {
443
423
  releaseGive(o);
444
424
  setOfferStatus(o, "cancelled");
445
425
  }
446
426
  };
447
- const liveHoldCount = (who, height) => {
448
- let liveN = 0;
449
- for (const x of offers.values()) if (x.claimedBy === who && claimHeld(x, height) && (height < V29_HEIGHT || x.status === "open")) liveN++;
450
- return liveN;
451
- };
452
427
  const releaseGiveLock = (o, who, amt) => {
453
428
  const t = o.give.ticker;
454
429
  bal(t, o.seller).locked -= amt;
455
430
  bal(t, who).available += amt;
456
431
  offerLock.delete(o.id);
457
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);
458
436
  return {
459
437
  tokens,
460
438
  balances,
@@ -464,21 +442,19 @@ function createContext() {
464
442
  offers,
465
443
  offerLock,
466
444
  bids,
467
- openOffers,
468
- openBids,
469
- pendingNames,
470
445
  fclaims,
471
446
  log,
447
+ store,
472
448
  setOfferStatus,
473
449
  setBidStatus,
474
450
  putName,
475
451
  bal,
476
- note,
452
+ applied,
453
+ refused,
477
454
  releaseGive,
478
455
  sweepExpired,
479
456
  markBidDone,
480
457
  voidOpenNameOffers,
481
- liveHoldCount,
482
458
  releaseGiveLock,
483
459
  feesPaid: 0n,
484
460
  // v1.4 fill-before-cancel: at V14_HEIGHT+ a cancel/ocancel's EFFECT is deferred to the block
@@ -494,13 +470,13 @@ function createContext() {
494
470
  // src/resolve/attest.ts
495
471
  var openFillReject = (o, height, who, targetId) => {
496
472
  if (!(height >= V13_HEIGHT && !o.taker)) return void 0;
497
- if (height < V17_HEIGHT) return "v1.3: open CSD-quoted fills disabled (offer must be taker-bound)";
498
- if (height >= V28_HEIGHT && o.claimTxid !== void 0 && targetId === o.id) return "v2.8: fill the fclaim txid, not the offer";
499
- 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)" };
500
476
  return void 0;
501
477
  };
502
- var deliverNameToBuyer = (n, who, ev) => {
503
- n.owner = who;
478
+ var deliverNameToBuyer = (c, name, n, who, ev) => {
479
+ c.store.setNameOwner(name, n, who);
504
480
  n.locked = false;
505
481
  n.addr = void 0;
506
482
  n.profile = void 0;
@@ -513,7 +489,7 @@ var deliverNameToBuyer = (n, who, ev) => {
513
489
  }
514
490
  };
515
491
  function applyAttest(c, ev) {
516
- const { offers, fclaims, bids, note, setBidStatus } = c;
492
+ const { offers, fclaims, bids, applied, refused, setBidStatus } = c;
517
493
  const who = ev.attester.toLowerCase();
518
494
  let o = offers.get(ev.proposalId);
519
495
  if (!o && ev.height >= V28_HEIGHT && ev.score === SCORE_FILL) {
@@ -525,21 +501,21 @@ function applyAttest(c, ev) {
525
501
  }
526
502
  if (!o) {
527
503
  if (ev.height >= V28_HEIGHT && ev.score === SCORE_FILL && fclaims.has(ev.proposalId)) {
528
- 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");
529
505
  return;
530
506
  }
531
507
  const b = bids.get(ev.proposalId);
532
508
  if (b && ev.score === SCORE_CANCEL) {
533
509
  if (who !== b.bidder) {
534
- note(ev, ev.txid, "bidcancel", false, "only bidder may cancel");
510
+ refused(ev, ev.txid, "bidcancel", "BID_NOT_BIDDER", "only bidder may cancel");
535
511
  return;
536
512
  }
537
513
  if (b.status !== "open") {
538
- note(ev, ev.txid, "bidcancel", false, `bid ${b.status}`);
514
+ refused(ev, ev.txid, "bidcancel", "BID_NOT_OPEN", `bid ${b.status}`);
539
515
  return;
540
516
  }
541
517
  setBidStatus(b, "cancelled");
542
- note(ev, ev.txid, "bidcancel", true);
518
+ applied(ev, ev.txid, "bidcancel", "BID_CANCELLED");
543
519
  }
544
520
  return;
545
521
  }
@@ -550,95 +526,95 @@ function applyAttest(c, ev) {
550
526
  else if (ev.height >= V17_HEIGHT && ev.score === SCORE_CLAIM) applyLegacyClaim(c, ev, o, who);
551
527
  }
552
528
  function applyCancel(c, ev, o, who) {
553
- const { note, releaseGive, setOfferStatus } = c;
529
+ const { applied, refused, releaseGive, setOfferStatus } = c;
554
530
  if (who !== o.seller) {
555
- note(ev, ev.txid, "cancel", false, "only seller may cancel");
531
+ refused(ev, ev.txid, "cancel", "OFFER_NOT_SELLER", "only seller may cancel");
556
532
  return;
557
533
  }
558
534
  if (o.status !== "open") {
559
- note(ev, ev.txid, "cancel", false, `offer ${o.status}`);
535
+ refused(ev, ev.txid, "cancel", "OFFER_NOT_OPEN", `offer ${o.status}`);
560
536
  return;
561
537
  }
562
538
  if (o.taker !== void 0 && o.height >= V28_HEIGHT) {
563
- 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)");
564
540
  return;
565
541
  }
566
542
  if (ev.height >= V14_HEIGHT) {
567
543
  c.pendingCancels.push(() => {
568
544
  if (ev.height >= V28_HEIGHT && o.claimTxid !== void 0 && claimHeld(o, ev.height)) {
569
- 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)");
570
546
  return;
571
547
  }
572
548
  if (o.status === "open") {
573
549
  releaseGive(o);
574
550
  setOfferStatus(o, "cancelled");
575
- note(ev, ev.txid, "cancel", true);
576
- } 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)");
577
553
  });
578
554
  } else {
579
555
  releaseGive(o);
580
556
  setOfferStatus(o, "cancelled");
581
- note(ev, ev.txid, "cancel", true);
557
+ applied(ev, ev.txid, "cancel", "OFFER_CANCELLED");
582
558
  }
583
559
  }
584
560
  function applyTokenFill(c, ev, o, who) {
585
- const { tokens, names, offerLock, bal, note, setOfferStatus, markBidDone, releaseGiveLock } = c;
561
+ const { tokens, names, offerLock, bal, applied, refused, setOfferStatus, markBidDone, releaseGiveLock } = c;
586
562
  if (o.status !== "open") {
587
- note(ev, ev.txid, "fill", false, `offer ${o.status}`);
563
+ refused(ev, ev.txid, "fill", "OFFER_NOT_OPEN", `offer ${o.status}`);
588
564
  return;
589
565
  }
590
566
  if (o.taker && who !== o.taker) {
591
- note(ev, ev.txid, "fill", false, "taker-bound offer");
567
+ refused(ev, ev.txid, "fill", "FILL_NOT_TAKER", "taker-bound offer");
592
568
  return;
593
569
  }
594
570
  if (ev.confidence !== CONF_TOKEN_FILL) {
595
- 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");
596
572
  return;
597
573
  }
598
574
  if (!tokens.has(o.want.ticker)) {
599
- note(ev, ev.txid, "fill", false, "want ticker does not exist");
575
+ refused(ev, ev.txid, "fill", "TOKEN_UNKNOWN", "want ticker does not exist");
600
576
  return;
601
577
  }
602
578
  const amt = BigInt(o.want.amount);
603
579
  const fee = o.feeBps ? tradeFee(amt, o.feeBps) : 0n;
604
580
  const buyer = bal(o.want.ticker, who);
605
581
  if (buyer.available < amt + fee) {
606
- note(ev, ev.txid, "fill", false, "insufficient want-token balance");
582
+ refused(ev, ev.txid, "fill", "TOKEN_BALANCE_LOW", "insufficient want-token balance");
607
583
  return;
608
584
  }
609
585
  const giveName = isNameGive(o.give) ? names.get(o.give.name) : void 0;
610
586
  if (isNameGive(o.give) && !giveName) {
611
- note(ev, ev.txid, "fill", false, "name vanished (consensus violation)");
587
+ refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "name vanished (consensus violation)");
612
588
  return;
613
589
  }
614
590
  const giveLock = isNameGive(o.give) ? void 0 : offerLock.get(o.id);
615
591
  if (!isNameGive(o.give) && giveLock === void 0) {
616
- note(ev, ev.txid, "fill", false, "offer lock missing");
592
+ refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "offer lock missing");
617
593
  return;
618
594
  }
619
595
  buyer.available -= amt + fee;
620
596
  bal(o.want.ticker, o.want.payto).available += amt;
621
597
  if (fee > 0n) bal(o.want.ticker, TREASURY_ADDR).available += fee;
622
- if (isNameGive(o.give)) deliverNameToBuyer(giveName, who, ev);
598
+ if (isNameGive(o.give)) deliverNameToBuyer(c, o.give.name, giveName, who, ev);
623
599
  else releaseGiveLock(o, who, giveLock);
624
600
  setOfferStatus(o, "filled");
625
601
  o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: amt.toString(), fee: fee.toString() };
626
602
  markBidDone(o, who);
627
- note(ev, ev.txid, "fill", true);
603
+ applied(ev, ev.txid, "fill", "FILL_APPLIED");
628
604
  }
629
605
  function applyPartialFill(c, ev, o, who) {
630
- const { offerLock, bal, note, setOfferStatus, markBidDone } = c;
606
+ const { offerLock, bal, applied, refused, setOfferStatus, markBidDone } = c;
631
607
  if (o.status !== "open") {
632
- note(ev, ev.txid, "fill", false, `offer ${o.status}`);
608
+ refused(ev, ev.txid, "fill", "OFFER_NOT_OPEN", `offer ${o.status}`);
633
609
  return;
634
610
  }
635
611
  if (o.taker && who !== o.taker) {
636
- note(ev, ev.txid, "fill", false, "taker-bound offer");
612
+ refused(ev, ev.txid, "fill", "FILL_NOT_TAKER", "taker-bound offer");
637
613
  return;
638
614
  }
639
615
  const blk = openFillReject(o, ev.height, who, ev.proposalId);
640
616
  if (blk) {
641
- note(ev, ev.txid, "fill", false, blk);
617
+ refused(ev, ev.txid, "fill", blk.code, blk.note);
642
618
  return;
643
619
  }
644
620
  const pt = ev.paidTo ?? {};
@@ -649,13 +625,13 @@ function applyPartialFill(c, ev, o, who) {
649
625
  const minV = BigInt(o.min);
650
626
  const effMin = remaining < minV ? remaining : minV;
651
627
  if (X < effMin) {
652
- note(ev, ev.txid, "fill", false, "payment below offer min");
628
+ refused(ev, ev.txid, "fill", "FILL_BELOW_MIN", "payment below offer min");
653
629
  return;
654
630
  }
655
631
  const x = X < remaining ? X : remaining;
656
632
  const fee = o.feeBps ? tradeFee(x, o.feeBps) : 0n;
657
633
  if (ptAmt(pt[TREASURY_ADDR]) < fee) {
658
- note(ev, ev.txid, "fill", false, "protocol fee unpaid");
634
+ refused(ev, ev.txid, "fill", "TREASURY_FEE_UNPAID", "protocol fee unpaid");
659
635
  return;
660
636
  }
661
637
  const giveTotal = BigInt(o.give.amount);
@@ -664,12 +640,12 @@ function applyPartialFill(c, ev, o, who) {
664
640
  const newDelivered = giveTotal * newPaid / want;
665
641
  const out = newDelivered - deliveredSoFar;
666
642
  if (out === 0n) {
667
- 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");
668
644
  return;
669
645
  }
670
646
  const lock = offerLock.get(o.id);
671
647
  if (lock === void 0) {
672
- note(ev, ev.txid, "fill", false, "offer lock missing");
648
+ refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "offer lock missing");
673
649
  return;
674
650
  }
675
651
  bal(o.give.ticker, o.seller).locked -= out;
@@ -686,21 +662,21 @@ function applyPartialFill(c, ev, o, who) {
686
662
  offerLock.delete(o.id);
687
663
  markBidDone(o, who);
688
664
  }
689
- note(ev, ev.txid, "fill", true, `partial ${x}/${want}`);
665
+ applied(ev, ev.txid, "fill", "FILL_PARTIAL", `partial ${x}/${want}`);
690
666
  }
691
667
  function applyFill(c, ev, o, who) {
692
- const { names, offerLock, note, setOfferStatus, markBidDone, releaseGiveLock } = c;
668
+ const { names, offerLock, applied, refused, setOfferStatus, markBidDone, releaseGiveLock } = c;
693
669
  if (o.status !== "open") {
694
- note(ev, ev.txid, "fill", false, `offer ${o.status}`);
670
+ refused(ev, ev.txid, "fill", "OFFER_NOT_OPEN", `offer ${o.status}`);
695
671
  return;
696
672
  }
697
673
  if (o.taker && who !== o.taker) {
698
- note(ev, ev.txid, "fill", false, "taker-bound offer");
674
+ refused(ev, ev.txid, "fill", "FILL_NOT_TAKER", "taker-bound offer");
699
675
  return;
700
676
  }
701
677
  const blk = openFillReject(o, ev.height, who, ev.proposalId);
702
678
  if (blk) {
703
- note(ev, ev.txid, "fill", false, blk);
679
+ refused(ev, ev.txid, "fill", blk.code, blk.note);
704
680
  return;
705
681
  }
706
682
  const pt = ev.paidTo ?? {};
@@ -715,25 +691,25 @@ function applyFill(c, ev, o, who) {
715
691
  if (rebate > 0n) addNeed(o.seller, rebate);
716
692
  let unpaid;
717
693
  for (const [addr, amt] of need) if (ptAmt(pt[addr]) < amt) {
718
- 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" };
719
695
  break;
720
696
  }
721
697
  if (unpaid) {
722
- note(ev, ev.txid, "fill", false, unpaid);
698
+ refused(ev, ev.txid, "fill", unpaid.code, unpaid.note);
723
699
  return;
724
700
  }
725
701
  const paid = ptAmt(pt[o.want.payto]);
726
702
  if (isNameGive(o.give)) {
727
703
  const n = names.get(o.give.name);
728
704
  if (!n) {
729
- note(ev, ev.txid, "fill", false, "name vanished (consensus violation)");
705
+ refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "name vanished (consensus violation)");
730
706
  return;
731
707
  }
732
- deliverNameToBuyer(n, who, ev);
708
+ deliverNameToBuyer(c, o.give.name, n, who, ev);
733
709
  } else {
734
710
  const amt = offerLock.get(o.id);
735
711
  if (amt === void 0) {
736
- note(ev, ev.txid, "fill", false, "offer lock missing");
712
+ refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "offer lock missing");
737
713
  return;
738
714
  }
739
715
  releaseGiveLock(o, who, amt);
@@ -742,41 +718,464 @@ function applyFill(c, ev, o, who) {
742
718
  setOfferStatus(o, "filled");
743
719
  o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: paid.toString(), fee: fee.toString() };
744
720
  markBidDone(o, who);
745
- note(ev, ev.txid, "fill", true);
721
+ applied(ev, ev.txid, "fill", "FILL_APPLIED");
746
722
  }
747
723
  function applyLegacyClaim(c, ev, o, who) {
748
- const { note, liveHoldCount } = c;
724
+ const { applied, refused, store } = c;
749
725
  if (ev.height >= V28_HEIGHT) {
750
- 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");
751
727
  return;
752
728
  }
753
729
  if (o.status !== "open") {
754
- note(ev, ev.txid, "claim", false, `offer ${o.status}`);
730
+ refused(ev, ev.txid, "claim", "OFFER_NOT_OPEN", `offer ${o.status}`);
755
731
  return;
756
732
  }
757
733
  if (o.taker) {
758
- 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");
759
735
  return;
760
736
  }
761
737
  if (isTokenWant(o.want)) {
762
- 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)");
763
739
  return;
764
740
  }
765
741
  if (claimHeld(o, ev.height)) {
766
- 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)");
767
743
  return;
768
744
  }
769
745
  if (o.claimedBy === who && o.claimUntilHeight !== void 0 && ev.height < o.claimUntilHeight + claimGrace(o) + CLAIM_COOLDOWN_BLOCKS) {
770
- 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)");
771
747
  return;
772
748
  }
773
- if (liveHoldCount(who, ev.height) >= MAX_ACTIVE_CLAIMS) {
774
- 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`);
775
751
  return;
776
752
  }
777
- o.claimedBy = who;
778
- o.claimUntilHeight = ev.height + claimWindowAt(ev.height);
779
- 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
+ };
780
1179
  }
781
1180
 
782
1181
  // src/resolve/names.ts
@@ -786,24 +1185,24 @@ var lapsed = (n, ep) => ep > paidThrough(n) + NAME_GRACE_EPOCHS;
786
1185
  var inGrace = (n, ep) => ep > paidThrough(n) && !lapsed(n, ep);
787
1186
  var earlierAnchor = (effHeight, pos, id, inc) => effHeight < inc.effHeight || effHeight === inc.effHeight && (pos < inc.pos || pos === inc.pos && id < inc.id);
788
1187
  function applyNcommit(c, ev, rec) {
789
- const { commits, note } = c;
1188
+ const { commits, applied, refused } = c;
790
1189
  const v11 = ev.height >= V11_HEIGHT;
791
1190
  if (!v11) {
792
- note(ev, ev.id, "ncommit", false, "before v1.1 activation");
1191
+ refused(ev, ev.id, "ncommit", "GATE_NOT_ACTIVE", "before v1.1 activation");
793
1192
  return;
794
1193
  }
795
1194
  const prev = commits.get(rec.commit);
796
1195
  if (prev === void 0 || ev.height < prev) commits.set(rec.commit, ev.height);
797
- note(ev, ev.id, "ncommit", true);
1196
+ applied(ev, ev.id, "ncommit", "NAME_COMMITTED");
798
1197
  }
799
1198
  function applyName(c, ev, rec, who, feeToTreasury) {
800
- const { commits, names, recaptures, note, putName, voidOpenNameOffers } = c;
1199
+ const { commits, names, recaptures, applied, refused, putName, voidOpenNameOffers, store } = c;
801
1200
  const v11 = ev.height >= V11_HEIGHT;
802
1201
  const v15 = ev.height >= V15_HEIGHT;
803
1202
  const v25 = ev.height >= V25_HEIGHT;
804
1203
  const v26 = ev.height >= V26_HEIGHT;
805
1204
  if (!v11) {
806
- note(ev, ev.id, "name", false, "before v1.1 activation");
1205
+ refused(ev, ev.id, "name", "GATE_NOT_ACTIVE", "before v1.1 activation");
807
1206
  return;
808
1207
  }
809
1208
  const regWindow = v25 || v26 ? REG_COMMIT_MAX_BLOCKS : COMMIT_MAX_BLOCKS;
@@ -812,7 +1211,7 @@ function applyName(c, ev, rec, who, feeToTreasury) {
812
1211
  const ch = nameCommit(rec.name, rec.salt, who);
813
1212
  const cH = commits.get(ch);
814
1213
  if (cH === void 0 || cH >= ev.height || ev.height - cH > regWindow) {
815
- 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");
816
1215
  return;
817
1216
  }
818
1217
  effHeight = cH;
@@ -823,62 +1222,61 @@ function applyName(c, ev, rec, who, feeToTreasury) {
823
1222
  if (curActive && !curActive.pending && v15 && lapsed(curActive, epClaim)) {
824
1223
  if (v26) {
825
1224
  if (rec.salt === void 0) {
826
- 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)");
827
1226
  return;
828
1227
  }
829
1228
  const cr = recaptures.get(rec.name);
830
1229
  const crActive = cr && ev.height > cr.finalizeBy ? void 0 : cr;
831
1230
  const better2 = !crActive || earlierAnchor(effHeight, ev.pos, ev.id, crActive);
832
1231
  if (!better2) {
833
- 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)");
834
1233
  return;
835
1234
  }
836
- let myR = 0;
837
- for (const [nm, r] of recaptures) if (r.owner === who && nm !== rec.name && ev.height <= r.finalizeBy) myR++;
838
- if (myR >= MAX_PENDING_REG) {
839
- 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)");
840
1237
  return;
841
1238
  }
842
- 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 });
843
- 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)");
844
1242
  return;
845
1243
  }
846
1244
  const fee = expiredClaimFee(rec.name, epClaim - (paidThrough(curActive) + NAME_GRACE_EPOCHS), ev.height);
847
1245
  if (feeToTreasury < fee) {
848
- 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)");
849
1247
  return;
850
1248
  }
851
1249
  voidOpenNameOffers(rec.name, ev.height);
852
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 });
853
1251
  c.feesPaid += fee;
854
- note(ev, ev.id, "name", true, "lapsed lease re-claimed (premium)");
1252
+ applied(ev, ev.id, "name", "NAME_RECLAIMED", "lapsed lease re-claimed (premium)");
855
1253
  return;
856
1254
  }
857
1255
  if (v25) {
858
1256
  if (rec.salt === void 0) {
859
- 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)");
860
1258
  return;
861
1259
  }
862
1260
  const better2 = !curActive || !curActive.viaFill && earlierAnchor(effHeight, ev.pos, ev.id, curActive);
863
1261
  if (!better2) {
864
- 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)");
865
1264
  return;
866
1265
  }
867
- let myPending = 0;
868
- for (const [nm, n] of names) if (n.pending && n.owner === who && nm !== rec.name && n.finalizeBy !== void 0 && ev.height <= n.finalizeBy) myPending++;
869
- if (myPending >= MAX_PENDING_REG) {
870
- 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)");
871
1268
  return;
872
1269
  }
873
1270
  if (curActive) {
874
1271
  voidOpenNameOffers(rec.name, ev.height);
875
1272
  }
876
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 });
877
- 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)");
878
1276
  return;
879
1277
  }
880
1278
  if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
881
- note(ev, ev.id, "name", false, "name registration fee unpaid");
1279
+ refused(ev, ev.id, "name", "TREASURY_FEE_UNPAID", "name registration fee unpaid");
882
1280
  return;
883
1281
  }
884
1282
  const cand = {
@@ -892,7 +1290,8 @@ function applyName(c, ev, rec, who, feeToTreasury) {
892
1290
  };
893
1291
  const better = !curActive || !curActive.viaFill && earlierAnchor(effHeight, ev.pos, ev.id, curActive);
894
1292
  if (!better) {
895
- 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)");
896
1295
  return;
897
1296
  }
898
1297
  if (curActive) {
@@ -900,189 +1299,188 @@ function applyName(c, ev, rec, who, feeToTreasury) {
900
1299
  }
901
1300
  putName(rec.name, cand);
902
1301
  c.feesPaid += nameRegFee(rec.name, ev.height);
903
- 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");
904
1304
  }
905
1305
  function applyNfinalize(c, ev, rec, who, feeToTreasury) {
906
- const { commits, names, recaptures, pendingNames, note, putName, voidOpenNameOffers } = c;
1306
+ const { commits, names, recaptures, applied, refused, putName, voidOpenNameOffers, store } = c;
907
1307
  const v25 = ev.height >= V25_HEIGHT;
908
1308
  const v26 = ev.height >= V26_HEIGHT;
909
1309
  if (!v25) {
910
- note(ev, ev.id, "nfinalize", false, "before v2.5 activation");
1310
+ refused(ev, ev.id, "nfinalize", "GATE_NOT_ACTIVE", "before v2.5 activation");
911
1311
  return;
912
1312
  }
913
1313
  const n = names.get(rec.name);
914
1314
  if (n && n.pending && n.owner === who) {
915
1315
  const cH = commits.get(nameCommit(rec.name, rec.salt, who));
916
1316
  if (cH === void 0 || cH !== n.effHeight) {
917
- 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");
918
1318
  return;
919
1319
  }
920
1320
  if (!(ev.height > n.effHeight + REG_COMMIT_MAX_BLOCKS)) {
921
- 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");
922
1322
  return;
923
1323
  }
924
1324
  if (n.finalizeBy !== void 0 && ev.height > n.finalizeBy) {
925
- note(ev, ev.id, "nfinalize", false, "reservation expired");
1325
+ refused(ev, ev.id, "nfinalize", "NAME_RESERVATION_EXPIRED", "reservation expired");
926
1326
  return;
927
1327
  }
928
1328
  if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
929
- note(ev, ev.id, "nfinalize", false, "name registration fee unpaid");
1329
+ refused(ev, ev.id, "nfinalize", "TREASURY_FEE_UNPAID", "name registration fee unpaid");
930
1330
  return;
931
1331
  }
932
- delete n.pending;
933
- delete n.finalizeBy;
934
- pendingNames.delete(rec.name);
1332
+ store.finalizeName(rec.name, n);
935
1333
  n.paidThroughEpoch = epochOf(ev.height) + NAME_TERM_EPOCHS;
936
1334
  c.feesPaid += nameRegFee(rec.name, ev.height);
937
- note(ev, ev.id, "nfinalize", true);
1335
+ applied(ev, ev.id, "nfinalize", "NAME_FINALIZED");
938
1336
  return;
939
1337
  }
940
1338
  const r = v26 ? recaptures.get(rec.name) : void 0;
941
1339
  if (r && r.owner === who) {
942
1340
  const cH = commits.get(nameCommit(rec.name, rec.salt, who));
943
1341
  if (cH === void 0 || cH !== r.effHeight) {
944
- 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");
945
1343
  return;
946
1344
  }
947
1345
  if (!(ev.height > r.effHeight + REG_COMMIT_MAX_BLOCKS)) {
948
- 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");
949
1347
  return;
950
1348
  }
951
1349
  if (ev.height > r.finalizeBy) {
952
- note(ev, ev.id, "nfinalize", false, "recapture reservation expired");
1350
+ refused(ev, ev.id, "nfinalize", "NAME_RESERVATION_EXPIRED", "recapture reservation expired");
953
1351
  return;
954
1352
  }
955
1353
  const cur = names.get(rec.name);
956
1354
  const ep = epochOf(ev.height);
957
1355
  if (!cur || cur.pending || !lapsed(cur, ep)) {
958
- recaptures.delete(rec.name);
959
- 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");
960
1358
  return;
961
1359
  }
962
1360
  const fee = expiredClaimFee(rec.name, ep - (paidThrough(cur) + NAME_GRACE_EPOCHS), ev.height);
963
1361
  if (feeToTreasury < fee) {
964
- note(ev, ev.id, "nfinalize", false, "recapture premium unpaid (decaying)");
1362
+ refused(ev, ev.id, "nfinalize", "TREASURY_FEE_UNPAID", "recapture premium unpaid (decaying)");
965
1363
  return;
966
1364
  }
967
1365
  voidOpenNameOffers(rec.name, ev.height);
968
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 });
969
- recaptures.delete(rec.name);
1367
+ store.deleteRecapture(rec.name);
970
1368
  c.feesPaid += fee;
971
- note(ev, ev.id, "nfinalize", true, "recapture finalized (premium)");
1369
+ applied(ev, ev.id, "nfinalize", "NAME_RECAPTURE_FINALIZED", "recapture finalized (premium)");
972
1370
  return;
973
1371
  }
974
- 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");
975
1373
  }
976
1374
  function applyNxfer(c, ev, rec, who) {
977
- const { names, note } = c;
1375
+ const { names, applied, refused, store } = c;
978
1376
  const v15 = ev.height >= V15_HEIGHT;
979
1377
  const n = names.get(rec.name);
980
1378
  if (!n || n.owner !== who) {
981
- note(ev, ev.id, "nxfer", false, "not the name owner");
1379
+ refused(ev, ev.id, "nxfer", "NAME_NOT_OWNER", "not the name owner");
982
1380
  return;
983
1381
  }
984
1382
  if (n.pending) {
985
- note(ev, ev.id, "nxfer", false, "name reservation not yet finalized");
1383
+ refused(ev, ev.id, "nxfer", "NAME_PENDING", "name reservation not yet finalized");
986
1384
  return;
987
1385
  }
988
1386
  if (v15 && lapsed(n, epochOf(ev.height))) {
989
- 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");
990
1388
  return;
991
1389
  }
992
1390
  if (n.locked) {
993
- 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");
994
1392
  return;
995
1393
  }
996
- n.owner = rec.to.toLowerCase();
1394
+ store.setNameOwner(rec.name, n, rec.to.toLowerCase());
997
1395
  n.addr = void 0;
998
1396
  n.profile = void 0;
999
- note(ev, ev.id, "nxfer", true);
1397
+ applied(ev, ev.id, "nxfer", "NAME_TRANSFERRED");
1000
1398
  }
1001
1399
  function applyNset(c, ev, rec, who) {
1002
- const { names, note } = c;
1400
+ const { names, applied, refused } = c;
1003
1401
  const v15 = ev.height >= V15_HEIGHT;
1004
1402
  const v23 = ev.height >= V23_HEIGHT;
1005
1403
  const n = names.get(rec.name);
1006
1404
  if (!n || n.owner !== who) {
1007
- note(ev, ev.id, "nset", false, "not the name owner");
1405
+ refused(ev, ev.id, "nset", "NAME_NOT_OWNER", "not the name owner");
1008
1406
  return;
1009
1407
  }
1010
1408
  if (n.pending) {
1011
- note(ev, ev.id, "nset", false, "name reservation not yet finalized");
1409
+ refused(ev, ev.id, "nset", "NAME_PENDING", "name reservation not yet finalized");
1012
1410
  return;
1013
1411
  }
1014
1412
  if (v15 && lapsed(n, epochOf(ev.height))) {
1015
- 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");
1016
1414
  return;
1017
1415
  }
1018
1416
  if (v23 && rec.addr.toLowerCase() === ZERO_ADDR) n.addr = void 0;
1019
1417
  else n.addr = rec.addr.toLowerCase();
1020
- note(ev, ev.id, "nset", true);
1418
+ applied(ev, ev.id, "nset", "NAME_ADDR_SET");
1021
1419
  }
1022
1420
  function applyNprofile(c, ev, rec, who) {
1023
- const { names, note } = c;
1421
+ const { names, applied, refused } = c;
1024
1422
  const v15 = ev.height >= V15_HEIGHT;
1025
1423
  const v19 = ev.height >= V19_HEIGHT;
1026
1424
  if (!v19) {
1027
- note(ev, ev.id, "nprofile", false, "before v1.9 activation");
1425
+ refused(ev, ev.id, "nprofile", "GATE_NOT_ACTIVE", "before v1.9 activation");
1028
1426
  return;
1029
1427
  }
1030
1428
  const n = names.get(rec.name);
1031
1429
  if (!n || n.owner !== who) {
1032
- note(ev, ev.id, "nprofile", false, "not the name owner");
1430
+ refused(ev, ev.id, "nprofile", "NAME_NOT_OWNER", "not the name owner");
1033
1431
  return;
1034
1432
  }
1035
1433
  if (n.pending) {
1036
- note(ev, ev.id, "nprofile", false, "name reservation not yet finalized");
1434
+ refused(ev, ev.id, "nprofile", "NAME_PENDING", "name reservation not yet finalized");
1037
1435
  return;
1038
1436
  }
1039
1437
  if (v15 && lapsed(n, epochOf(ev.height))) {
1040
- 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");
1041
1439
  return;
1042
1440
  }
1043
1441
  n.profile = Object.keys(rec.p).length ? { ...rec.p } : void 0;
1044
- note(ev, ev.id, "nprofile", true);
1442
+ applied(ev, ev.id, "nprofile", "NAME_PROFILE_SET");
1045
1443
  }
1046
1444
  function applyNrenew(c, ev, rec, who, feeToTreasury) {
1047
- const { names, note } = c;
1445
+ const { names, applied, refused } = c;
1048
1446
  const v15 = ev.height >= V15_HEIGHT;
1049
1447
  if (!v15) {
1050
- note(ev, ev.id, "nrenew", false, "nrenew needs v1.5");
1448
+ refused(ev, ev.id, "nrenew", "GATE_NOT_ACTIVE", "nrenew needs v1.5");
1051
1449
  return;
1052
1450
  }
1053
1451
  const n = names.get(rec.name);
1054
1452
  const ep = epochOf(ev.height);
1055
1453
  if (n && n.pending) {
1056
- note(ev, ev.id, "nrenew", false, "name reservation not yet finalized");
1454
+ refused(ev, ev.id, "nrenew", "NAME_PENDING", "name reservation not yet finalized");
1057
1455
  return;
1058
1456
  }
1059
1457
  if (!n || lapsed(n, ep)) {
1060
- 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)");
1061
1459
  return;
1062
1460
  }
1063
1461
  if (inGrace(n, ep) && who !== n.owner) {
1064
- 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");
1065
1463
  return;
1066
1464
  }
1067
1465
  if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
1068
- note(ev, ev.id, "nrenew", false, "renewal fee unpaid");
1466
+ refused(ev, ev.id, "nrenew", "TREASURY_FEE_UNPAID", "renewal fee unpaid");
1069
1467
  return;
1070
1468
  }
1071
1469
  n.paidThroughEpoch = paidThrough(n) + NAME_TERM_EPOCHS;
1072
1470
  c.feesPaid += nameRegFee(rec.name, ev.height);
1073
- note(ev, ev.id, "nrenew", true, `paid through epoch ${n.paidThroughEpoch}`);
1471
+ applied(ev, ev.id, "nrenew", "NAME_RENEWED", `paid through epoch ${n.paidThroughEpoch}`);
1074
1472
  }
1075
1473
 
1076
1474
  // src/resolve/market.ts
1077
1475
  function applyOffer(c, ev, rec, who) {
1078
- const { tokens, names, offers, offerLock, openOffers, bids, bal, note } = c;
1476
+ const { tokens, names, offerLock, bids, bal, applied, refused, store } = c;
1079
1477
  const v11 = ev.height >= V11_HEIGHT;
1080
1478
  const v15 = ev.height >= V15_HEIGHT;
1081
1479
  const v16 = ev.height >= V16_HEIGHT;
1082
1480
  const wantIsToken = isTokenWant(rec.want);
1083
1481
  const refusal = offerEnvelopeRefusal(rec, who, ev.height, ev.expiresEpoch);
1084
1482
  if (refusal !== null) {
1085
- note(ev, ev.id, "offer", false, refusal);
1483
+ refused(ev, ev.id, "offer", refusal.code, refusal.note);
1086
1484
  return;
1087
1485
  }
1088
1486
  const payto = (rec.want.payto ?? who).toLowerCase();
@@ -1090,36 +1488,36 @@ function applyOffer(c, ev, rec, who) {
1090
1488
  if (isNameGive(give)) {
1091
1489
  const n = names.get(give.name);
1092
1490
  if (!n || n.owner !== who) {
1093
- 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");
1094
1492
  return;
1095
1493
  }
1096
1494
  if (n.pending) {
1097
- note(ev, ev.id, "offer", false, "name reservation not yet finalized");
1495
+ refused(ev, ev.id, "offer", "NAME_PENDING", "name reservation not yet finalized");
1098
1496
  return;
1099
1497
  }
1100
1498
  if (n.locked) {
1101
- 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");
1102
1500
  return;
1103
1501
  }
1104
1502
  const saleEmbargo = ev.height >= V27_HEIGHT ? REG_COMMIT_MAX_BLOCKS : COMMIT_MAX_BLOCKS;
1105
1503
  if (ev.height >= V13_HEIGHT && !n.viaFill && ev.height - n.effHeight <= saleEmbargo) {
1106
- 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)");
1107
1505
  return;
1108
1506
  }
1109
1507
  if (v15 && paidThrough(n) < ev.expiresEpoch) {
1110
- 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)");
1111
1509
  return;
1112
1510
  }
1113
1511
  n.locked = true;
1114
1512
  } else {
1115
1513
  if (!tokens.has(give.ticker)) {
1116
- note(ev, ev.id, "offer", false, "unknown ticker");
1514
+ refused(ev, ev.id, "offer", "TOKEN_UNKNOWN", "unknown ticker");
1117
1515
  return;
1118
1516
  }
1119
1517
  const amt = parseAmount(give.amount);
1120
1518
  const s = bal(give.ticker, who);
1121
1519
  if (s.available < amt) {
1122
- note(ev, ev.id, "offer", false, "insufficient available balance");
1520
+ refused(ev, ev.id, "offer", "TOKEN_BALANCE_LOW", "insufficient available balance");
1123
1521
  return;
1124
1522
  }
1125
1523
  s.available -= amt;
@@ -1139,32 +1537,31 @@ function applyOffer(c, ev, rec, who) {
1139
1537
  height: ev.height,
1140
1538
  feeBps: v11 ? v16 ? FEE_BPS_V16 : FEE_BPS : 0
1141
1539
  };
1142
- offers.set(ev.id, o);
1143
- openOffers.add(ev.id);
1540
+ store.addOffer(o);
1144
1541
  const linked = rec.bid !== void 0 ? bids.get(rec.bid) : void 0;
1145
1542
  if (linked) linked.offers.push(ev.id);
1146
- note(ev, ev.id, "offer", true);
1543
+ applied(ev, ev.id, "offer", "OFFER_CREATED");
1147
1544
  }
1148
1545
  function applyBid(c, ev, rec, who) {
1149
- const { bids, openBids, note } = c;
1546
+ const { applied, refused, store } = c;
1150
1547
  const v12 = ev.height >= V12_HEIGHT;
1151
1548
  if (!v12) {
1152
- note(ev, ev.id, "bid", false, "bids need v1.2");
1549
+ refused(ev, ev.id, "bid", "GATE_NOT_ACTIVE", "bids need v1.2");
1153
1550
  return;
1154
1551
  }
1155
1552
  if (!Number.isSafeInteger(ev.expiresEpoch)) {
1156
- 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");
1157
1554
  return;
1158
1555
  }
1159
1556
  if (epochOf(ev.height) > ev.expiresEpoch) {
1160
- note(ev, ev.id, "bid", false, "already expired at anchor");
1557
+ refused(ev, ev.id, "bid", "EXPIRY_PAST", "already expired at anchor");
1161
1558
  return;
1162
1559
  }
1163
1560
  if (ev.height >= V21_HEIGHT && ev.height < V22_HEIGHT && ev.expiresEpoch - epochOf(ev.height) > MAX_OFFER_EPOCHS) {
1164
- 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");
1165
1562
  return;
1166
1563
  }
1167
- bids.set(ev.id, {
1564
+ store.addBid({
1168
1565
  id: ev.id,
1169
1566
  bidder: who,
1170
1567
  want: rec.want,
@@ -1174,24 +1571,16 @@ function applyBid(c, ev, rec, who) {
1174
1571
  height: ev.height,
1175
1572
  offers: []
1176
1573
  });
1177
- openBids.add(ev.id);
1178
- note(ev, ev.id, "bid", true);
1574
+ applied(ev, ev.id, "bid", "BID_CREATED");
1179
1575
  }
1180
1576
  function applyOcancel(c, ev, rec, who) {
1181
- const { offers, note, releaseGive, setOfferStatus } = c;
1577
+ const { applied, refused, releaseGive, setOfferStatus, store } = c;
1182
1578
  const v12 = ev.height >= V12_HEIGHT;
1183
1579
  if (!v12) {
1184
- note(ev, ev.id, "ocancel", false, "ocancel needs v1.2");
1580
+ refused(ev, ev.id, "ocancel", "GATE_NOT_ACTIVE", "ocancel needs v1.2");
1185
1581
  return;
1186
1582
  }
1187
- const targets = [];
1188
- for (const o of offers.values()) {
1189
- if (o.status !== "open" || o.seller !== who) continue;
1190
- if (o.taker !== void 0 && o.height >= V28_HEIGHT) continue;
1191
- if (rec.ticker !== void 0 && !(!isNameGive(o.give) && o.give.ticker === rec.ticker)) continue;
1192
- if (rec.name !== void 0 && !(isNameGive(o.give) && o.give.name === rec.name)) continue;
1193
- targets.push(o);
1194
- }
1583
+ const targets = store.ocancelTargets(who, rec.ticker, rec.name);
1195
1584
  if (ev.height >= V14_HEIGHT) {
1196
1585
  c.pendingCancels.push(() => {
1197
1586
  let n = 0;
@@ -1203,100 +1592,98 @@ function applyOcancel(c, ev, rec, who) {
1203
1592
  n++;
1204
1593
  }
1205
1594
  }
1206
- 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)`);
1207
1596
  });
1208
1597
  } else {
1209
1598
  for (const o of targets) {
1210
1599
  releaseGive(o);
1211
1600
  setOfferStatus(o, "cancelled");
1212
1601
  }
1213
- note(ev, ev.id, "ocancel", true, `${targets.length} cancelled`);
1602
+ applied(ev, ev.id, "ocancel", "OFFER_BULK_CANCELLED", `${targets.length} cancelled`);
1214
1603
  }
1215
1604
  }
1216
1605
  function applyFclaim(c, ev, rec, who) {
1217
- const { offers, fclaims, note, liveHoldCount } = c;
1606
+ const { offers, fclaims, applied, refused, store } = c;
1218
1607
  if (ev.height < V28_HEIGHT) {
1219
- note(ev, ev.id, "fclaim", false, "fclaim needs v2.8");
1608
+ refused(ev, ev.id, "fclaim", "GATE_NOT_ACTIVE", "fclaim needs v2.8");
1220
1609
  return;
1221
1610
  }
1222
1611
  const target = offers.get(rec.offer);
1223
1612
  const E = ev.expiresEpoch;
1224
- const deny = (why) => {
1613
+ const deny = (code, why) => {
1225
1614
  fclaims.set(ev.id, { offer: rec.offer, proposer: who, expiresEpoch: E, height: ev.height, granted: false });
1226
- note(ev, ev.id, "fclaim", false, why);
1615
+ refused(ev, ev.id, "fclaim", code, why);
1227
1616
  };
1228
1617
  if (!Number.isSafeInteger(E)) {
1229
- deny("expiresEpoch out of safe-integer range");
1618
+ deny("EXPIRY_UNSAFE", "expiresEpoch out of safe-integer range");
1230
1619
  return;
1231
1620
  }
1232
1621
  if (!target) {
1233
- deny("unknown offer");
1622
+ deny("OFFER_UNKNOWN", "unknown offer");
1234
1623
  return;
1235
1624
  }
1236
1625
  if (target.status !== "open") {
1237
- deny(`offer ${target.status}`);
1626
+ deny("OFFER_NOT_OPEN", `offer ${target.status}`);
1238
1627
  return;
1239
1628
  }
1240
1629
  if (target.taker) {
1241
- deny("taker-bound offer needs no claim");
1630
+ deny("CLAIM_TAKER_BOUND", "taker-bound offer needs no claim");
1242
1631
  return;
1243
1632
  }
1244
1633
  if (isTokenWant(target.want)) {
1245
- deny("claims are for CSD-priced offers");
1634
+ deny("CLAIM_TOKEN_PRICED", "claims are for CSD-priced offers");
1246
1635
  return;
1247
1636
  }
1248
1637
  if (E > effExpiry(target, ev.height)) {
1249
- deny("hold would outlive the offer expiry");
1638
+ deny("CLAIM_OUTLIVES_OFFER", "hold would outlive the offer expiry");
1250
1639
  return;
1251
1640
  }
1252
1641
  if (E > epochOf(ev.height) + FCLAIM_MAX_EPOCH_AHEAD) {
1253
- deny("hold too far ahead (anti-squat)");
1642
+ deny("CLAIM_TOO_FAR_AHEAD", "hold too far ahead (anti-squat)");
1254
1643
  return;
1255
1644
  }
1256
1645
  if (epochOf(ev.height) > E) {
1257
- deny("expiry already in the past");
1646
+ deny("EXPIRY_PAST", "expiry already in the past");
1258
1647
  return;
1259
1648
  }
1260
1649
  if (claimHeld(target, ev.height)) {
1261
- deny("offer already claimed (hold live)");
1650
+ deny("CLAIM_HOLD_LIVE", "offer already claimed (hold live)");
1262
1651
  return;
1263
1652
  }
1264
1653
  if (target.claimedBy === who && target.claimUntilHeight !== void 0 && ev.height < target.claimUntilHeight + claimGrace(target) + CLAIM_COOLDOWN_BLOCKS) {
1265
- deny("claim cooldown (you just held this offer)");
1654
+ deny("CLAIM_COOLDOWN", "claim cooldown (you just held this offer)");
1266
1655
  return;
1267
1656
  }
1268
- if (liveHoldCount(who, ev.height) >= MAX_ACTIVE_CLAIMS) {
1269
- 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`);
1270
1659
  return;
1271
1660
  }
1272
- target.claimedBy = who;
1273
- target.claimUntilHeight = (E + 1) * EPOCH_LEN;
1274
- target.claimTxid = ev.id;
1661
+ store.setClaim(target, who, (E + 1) * EPOCH_LEN, ev.id);
1275
1662
  fclaims.set(ev.id, { offer: rec.offer, proposer: who, expiresEpoch: E, height: ev.height, granted: true });
1276
- note(ev, ev.id, "fclaim", true);
1663
+ applied(ev, ev.id, "fclaim", "CLAIM_GRANTED");
1277
1664
  }
1278
1665
  function offerEnvelopeRefusal(rec, who, height, expiresEpoch) {
1279
1666
  const wantIsToken = isTokenWant(rec.want);
1280
- if ((wantIsToken || rec.min !== void 0 || rec.bid !== void 0) && height < V12_HEIGHT) return "v1.2 offer shape before activation";
1281
- 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)";
1282
- if ((rec.want.payto ?? who).toLowerCase() === TREASURY_ADDR) return "payto cannot be the protocol treasury";
1283
- if (!Number.isSafeInteger(expiresEpoch)) return "expiresEpoch out of safe-integer range";
1284
- if (epochOf(height) > expiresEpoch) return "already expired at anchor";
1285
- if (height >= V21_HEIGHT && height < V22_HEIGHT && expiresEpoch - epochOf(height) > MAX_OFFER_EPOCHS) return "v2.1: offer duration exceeds the max";
1286
- 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" };
1287
1674
  return null;
1288
1675
  }
1289
1676
 
1290
1677
  // src/resolve/tokens.ts
1291
1678
  function applyDeploy(c, ev, rec, who, feeToTreasury) {
1292
- const { tokens, note } = c;
1679
+ const { tokens, applied, refused } = c;
1293
1680
  const v11 = ev.height >= V11_HEIGHT;
1294
1681
  if (tokens.has(rec.ticker)) {
1295
- 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)");
1296
1683
  return;
1297
1684
  }
1298
1685
  if (v11 && feeToTreasury < BigInt(DEPLOY_FEE)) {
1299
- note(ev, ev.id, "deploy", false, "deploy fee unpaid");
1686
+ refused(ev, ev.id, "deploy", "TREASURY_FEE_UNPAID", "deploy fee unpaid");
1300
1687
  return;
1301
1688
  }
1302
1689
  const supply = parseAmount(rec.supply);
@@ -1308,29 +1695,29 @@ function applyDeploy(c, ev, rec, who, feeToTreasury) {
1308
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 }
1309
1696
  });
1310
1697
  if (v11) c.feesPaid += BigInt(DEPLOY_FEE);
1311
- note(ev, ev.id, "deploy", true);
1698
+ applied(ev, ev.id, "deploy", "TOKEN_DEPLOYED");
1312
1699
  }
1313
1700
  function applyMint(c, ev, rec, who) {
1314
- const { tokens, bal, note } = c;
1701
+ const { tokens, bal, applied, refused } = c;
1315
1702
  const tok = tokens.get(rec.ticker);
1316
1703
  if (!tok) {
1317
- note(ev, ev.id, "mint", false, "unknown ticker");
1704
+ refused(ev, ev.id, "mint", "TOKEN_UNKNOWN", "unknown ticker");
1318
1705
  return;
1319
1706
  }
1320
1707
  const remaining = tok.supply - tok.minted;
1321
1708
  if (remaining <= 0n) {
1322
- note(ev, ev.id, "mint", false, "supply exhausted");
1709
+ refused(ev, ev.id, "mint", "TOKEN_SUPPLY_EXHAUSTED", "supply exhausted");
1323
1710
  return;
1324
1711
  }
1325
1712
  let credit;
1326
1713
  if (tok.meta.mint === "issuer") {
1327
1714
  if (who !== tok.meta.deployer) {
1328
- note(ev, ev.id, "mint", false, "issuer-only mint");
1715
+ refused(ev, ev.id, "mint", "TOKEN_NOT_ISSUER", "issuer-only mint");
1329
1716
  return;
1330
1717
  }
1331
1718
  const req = rec.amount !== void 0 ? parseAmount(rec.amount) : null;
1332
1719
  if (req === null) {
1333
- note(ev, ev.id, "mint", false, "issuer mint requires amount");
1720
+ refused(ev, ev.id, "mint", "TOKEN_MINT_AMOUNT_REQUIRED", "issuer mint requires amount");
1334
1721
  return;
1335
1722
  }
1336
1723
  credit = req < remaining ? req : remaining;
@@ -1341,66 +1728,70 @@ function applyMint(c, ev, rec, who) {
1341
1728
  }
1342
1729
  tok.minted += credit;
1343
1730
  bal(rec.ticker, who).available += credit;
1344
- note(ev, ev.id, "mint", true, credit.toString());
1731
+ applied(ev, ev.id, "mint", "TOKEN_MINTED", credit.toString());
1345
1732
  }
1346
1733
  function applyTransfer(c, ev, rec, who) {
1347
- const { tokens, bal, note } = c;
1734
+ const { tokens, bal, applied, refused } = c;
1348
1735
  if (!tokens.has(rec.ticker)) {
1349
- note(ev, ev.id, "transfer", false, "unknown ticker");
1736
+ refused(ev, ev.id, "transfer", "TOKEN_UNKNOWN", "unknown ticker");
1350
1737
  return;
1351
1738
  }
1352
1739
  const amt = parseAmount(rec.amount);
1353
1740
  const from = bal(rec.ticker, who);
1354
1741
  if (from.available < amt) {
1355
- note(ev, ev.id, "transfer", false, "insufficient available balance");
1742
+ refused(ev, ev.id, "transfer", "TOKEN_BALANCE_LOW", "insufficient available balance");
1356
1743
  return;
1357
1744
  }
1358
1745
  from.available -= amt;
1359
1746
  bal(rec.ticker, rec.to.toLowerCase()).available += amt;
1360
- note(ev, ev.id, "transfer", true);
1747
+ applied(ev, ev.id, "transfer", "TOKEN_TRANSFERRED");
1361
1748
  }
1362
1749
  function applyTmeta(c, ev, rec, who) {
1363
- const { tokens, note } = c;
1750
+ const { tokens, applied, refused } = c;
1364
1751
  const v15 = ev.height >= V15_HEIGHT;
1365
1752
  if (!v15) {
1366
- note(ev, ev.id, "tmeta", false, "tmeta needs v1.5");
1753
+ refused(ev, ev.id, "tmeta", "GATE_NOT_ACTIVE", "tmeta needs v1.5");
1367
1754
  return;
1368
1755
  }
1369
1756
  const tok = tokens.get(rec.ticker);
1370
1757
  if (!tok) {
1371
- note(ev, ev.id, "tmeta", false, "unknown ticker");
1758
+ refused(ev, ev.id, "tmeta", "TOKEN_UNKNOWN", "unknown ticker");
1372
1759
  return;
1373
1760
  }
1374
1761
  if (who !== tok.meta.deployer) {
1375
- note(ev, ev.id, "tmeta", false, "issuer-only metadata");
1762
+ refused(ev, ev.id, "tmeta", "TOKEN_NOT_ISSUER", "issuer-only metadata");
1376
1763
  return;
1377
1764
  }
1378
1765
  tok.meta.tmeta = rec.hash;
1379
- note(ev, ev.id, "tmeta", true);
1766
+ applied(ev, ev.id, "tmeta", "TOKEN_META_SET");
1380
1767
  }
1381
1768
 
1382
1769
  // src/resolve.ts
1383
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
+ }
1384
1777
  function resolve(events, tipHeight) {
1385
- const ordered = [...events].sort(
1386
- (a, b) => a.height - b.height || Number(a.kind === "attest") - Number(b.kind === "attest") || a.pos - b.pos || ord(
1387
- a.kind === "propose" ? a.id : a.txid,
1388
- b.kind === "propose" ? b.id : b.txid
1389
- )
1390
- );
1391
- 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);
1392
1782
  const seenIds = /* @__PURE__ */ new Set();
1393
1783
  const applied = [];
1394
1784
  for (const e of ordered) {
1395
1785
  if (e.height >= V29_HEIGHT) {
1396
- const k = eid(e);
1786
+ const k = eventId(e);
1397
1787
  if (seenIds.has(k)) continue;
1398
1788
  seenIds.add(k);
1399
1789
  }
1400
1790
  applied.push(e);
1401
1791
  }
1402
- const c = createContext();
1403
- 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;
1404
1795
  let pendingBlock = -1;
1405
1796
  const applyPendingCancels = () => {
1406
1797
  for (const f of c.pendingCancels) f();
@@ -1413,13 +1804,15 @@ function resolve(events, tipHeight) {
1413
1804
  pendingBlock = ev.height;
1414
1805
  }
1415
1806
  sweepExpired(ev.height);
1807
+ store.verify(ev.height);
1416
1808
  const feeToTreasury = ev.kind === "propose" ? ptAmt((ev.paidTo ?? {})[TREASURY_ADDR]) : 0n;
1417
1809
  if (ev.kind === "propose") {
1418
- const rec = parseRecord(ev.uri, ev.payloadHash);
1419
- if (!rec) {
1420
- 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");
1421
1813
  continue;
1422
1814
  }
1815
+ const rec = parsed.record;
1423
1816
  const who = ev.proposer.toLowerCase();
1424
1817
  switch (rec.t) {
1425
1818
  case "deploy":
@@ -1474,6 +1867,7 @@ function resolve(events, tipHeight) {
1474
1867
  }
1475
1868
  applyPendingCancels();
1476
1869
  sweepExpired(tipHeight + 1);
1870
+ store.verify(tipHeight + 1, true);
1477
1871
  const tokensOut = {};
1478
1872
  for (const [t, tok] of [...tokens.entries()].sort(([a], [b]) => ord(a, b))) tokensOut[t] = { ...tok.meta, minted: tok.minted.toString() };
1479
1873
  const balancesOut = {};
@@ -1701,7 +2095,8 @@ function pickPrimaryName(names, a) {
1701
2095
 
1702
2096
  // src/verifyfill.ts
1703
2097
  import { payloadHash as payloadHash2 } from "@inversealtruism/csd-codec";
1704
- var GAP_NEEDED = EPOCH_LEN * (FCLAIM_MAX_EPOCH_AHEAD + 1) - 1 + CLAIM_COOLDOWN_BLOCKS;
2098
+ var FCLAIM_MAX_HOLD_SPAN = EPOCH_LEN * (FCLAIM_MAX_EPOCH_AHEAD + 1) - 1;
2099
+ var GAP_NEEDED = FCLAIM_MAX_HOLD_SPAN + CLAIM_COOLDOWN_BLOCKS;
1705
2100
  var SCAN_MARGIN = EPOCH_LEN;
1706
2101
  var MAX_SCAN = GAP_NEEDED + SCAN_MARGIN;
1707
2102
  function bindRecord(ev) {
@@ -1880,6 +2275,176 @@ function burnedPayment(paidTo, payer, offer2) {
1880
2275
  return { treasury: read(TREASURY_ADDR), counterparty };
1881
2276
  }
1882
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
+
1883
2448
  // src/fillclosed.ts
1884
2449
  var lc = (v) => String(v).toLowerCase();
1885
2450
  function myProvenFillClosedOffer(fill, fclaim2, offerEv, me, grantHeight) {
@@ -1943,9 +2508,129 @@ function provenOfferRefusal(rec, tx) {
1943
2508
  if (tx.domain !== DOMAIN) return `not a ${DOMAIN} Propose (domain ${JSON.stringify(String(tx.domain))})`;
1944
2509
  if (beforeActivation(tx.height)) return `anchored before CairnX activation (block ${ACTIVATION_HEIGHT})`;
1945
2510
  const ee = typeof tx.expiresEpoch === "bigint" ? Number(tx.expiresEpoch) : tx.expiresEpoch;
1946
- return offerEnvelopeRefusal(rec, String(tx.seller).toLowerCase(), tx.height, ee);
2511
+ return offerEnvelopeRefusal(rec, String(tx.seller).toLowerCase(), tx.height, ee)?.note ?? null;
1947
2512
  }
1948
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
+
1949
2634
  // src/index.ts
1950
2635
  import {
1951
2636
  canonicalJson as canonicalJson2,
@@ -1962,6 +2647,8 @@ export {
1962
2647
  ADDR_RE,
1963
2648
  AMOUNT_RE,
1964
2649
  BID_KEYS,
2650
+ CAIRNX_EVENT_RULE,
2651
+ CAP_CODES,
1965
2652
  CLAIM_ATTACKER_Q,
1966
2653
  CLAIM_COOLDOWN_BLOCKS,
1967
2654
  CLAIM_FILL_GRACE_BLOCKS,
@@ -1975,14 +2662,17 @@ export {
1975
2662
  DEPLOY_KEYS,
1976
2663
  DOMAIN,
1977
2664
  EPOCH_LEN2 as EPOCH_LEN,
2665
+ EVENTS_HASH_START,
1978
2666
  FCLAIM_KEYS,
1979
2667
  FCLAIM_MAX_EPOCH_AHEAD,
2668
+ FCLAIM_MAX_HOLD_SPAN,
1980
2669
  FCLAIM_WINDOW_MIN,
1981
2670
  FEE_BPS,
1982
2671
  FEE_BPS_V16,
1983
2672
  FEE_GATE_MARGIN_BLOCKS,
1984
2673
  FILL_TIP_MARGIN,
1985
2674
  FINALIZE_TIP_MARGIN,
2675
+ FINAL_DEPTH,
1986
2676
  GAP_NEEDED,
1987
2677
  HALVING_INTERVAL,
1988
2678
  HASH_RE,
@@ -2016,11 +2706,14 @@ export {
2016
2706
  PKEY,
2017
2707
  PROFILE_MAX_KEYS,
2018
2708
  PROFILE_MAX_VALUE_BYTES,
2709
+ REASON_CODES,
2710
+ REASON_CODE_OUTCOME,
2019
2711
  REBATE_BPS,
2020
2712
  REBATE_FLAT,
2021
2713
  REG_COMMIT_MAX_BLOCKS,
2022
2714
  REG_FINALIZE_GRACE_BLOCKS,
2023
2715
  RESERVED_NAMES,
2716
+ RecordError,
2024
2717
  SALT_RE,
2025
2718
  SCAN_MARGIN,
2026
2719
  SCORE_CANCEL,
@@ -2049,10 +2742,13 @@ export {
2049
2742
  V28_HEIGHT,
2050
2743
  V29_HEIGHT,
2051
2744
  ZERO_ADDR,
2745
+ applyOrder,
2052
2746
  beforeActivation,
2053
2747
  bid,
2054
2748
  bindOfferTerms,
2055
2749
  bindProvenOffer,
2750
+ blockEvents,
2751
+ blockMembers,
2056
2752
  blockReward2 as blockReward,
2057
2753
  buildFeeHeight,
2058
2754
  buildRecord,
@@ -2065,7 +2761,12 @@ export {
2065
2761
  countOtherHoldsAtGrant,
2066
2762
  deploy,
2067
2763
  epochOf,
2764
+ eventId,
2765
+ eventOfTx,
2766
+ eventsHash,
2767
+ eventsHashStep,
2068
2768
  expiredClaimFee,
2769
+ explainRecord,
2069
2770
  fclaim,
2070
2771
  fclaimEpochFor,
2071
2772
  fclaimHoldEnd,
@@ -2095,6 +2796,7 @@ export {
2095
2796
  offer,
2096
2797
  offerCancelAll,
2097
2798
  offerExpiryHeightOf,
2799
+ offerFillTooLate,
2098
2800
  paidToFromOutputs,
2099
2801
  parseAmount,
2100
2802
  parseRecord,
@@ -2109,6 +2811,7 @@ export {
2109
2811
  requiredClaimDepth,
2110
2812
  requiredFillOutputs,
2111
2813
  resolve,
2814
+ stateHash,
2112
2815
  tokenMeta,
2113
2816
  tradeFee,
2114
2817
  transfer,