@inversealtruism/cairnx-core 0.2.4 → 0.2.8

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