@inversealtruism/cairnx-core 0.2.0 → 0.2.2

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
@@ -22,6 +22,7 @@ function expiredClaimFee(name, epochsPastGraceEnd, height) {
22
22
  }
23
23
  var MAX_RECORD_BYTES = MAX_URI_BYTES;
24
24
  var MAX_AMOUNT = (1n << 96n) - 1n;
25
+ var MAX_TOKEN_DECIMALS = 8;
25
26
  var SCORE_FILL = 100;
26
27
  var SCORE_CANCEL = 0;
27
28
  var SCORE_CLAIM = 50;
@@ -170,7 +171,7 @@ function parseRecord(uri, payloadHashHex) {
170
171
  if (!onlyKeys(r, DEPLOY_KEYS)) return null;
171
172
  if (!isTicker(r.ticker)) return null;
172
173
  if (r.name !== void 0 && (typeof r.name !== "string" || r.name.length > 32)) return null;
173
- if (typeof r.decimals !== "number" || !Number.isInteger(r.decimals) || r.decimals < 0 || r.decimals > 8) return null;
174
+ if (typeof r.decimals !== "number" || !Number.isInteger(r.decimals) || r.decimals < 0 || r.decimals > MAX_TOKEN_DECIMALS) return null;
174
175
  if (parseAmount(r.supply) === null) return null;
175
176
  if (r.mint !== "open" && r.mint !== "issuer") return null;
176
177
  if (r.mint === "open" && parseAmount(r.mintLimit) === null) return null;
@@ -332,29 +333,14 @@ var tokenMeta = (r) => buildRecord({ v: 1, t: "tmeta", ...r });
332
333
  var nameProfile = (r) => buildRecord({ v: 1, t: "nprofile", ...r });
333
334
  var fclaim = (r) => buildRecord({ v: 1, t: "fclaim", ...r });
334
335
 
335
- // src/resolve.ts
336
+ // src/resolve/context.ts
336
337
  function ptAmt(v) {
337
338
  return typeof v === "string" && AMOUNT_RE.test(v) ? BigInt(v) : 0n;
338
339
  }
339
- var ord = (a, b) => a < b ? -1 : a > b ? 1 : 0;
340
- function resolve(events, tipHeight) {
341
- const ordered = [...events].sort(
342
- (a, b) => a.height - b.height || Number(a.kind === "attest") - Number(b.kind === "attest") || a.pos - b.pos || ord(
343
- a.kind === "propose" ? a.id : a.txid,
344
- b.kind === "propose" ? b.id : b.txid
345
- )
346
- );
347
- const eid = (e) => e.kind === "propose" ? e.id : e.txid;
348
- const seenIds = /* @__PURE__ */ new Set();
349
- const applied = [];
350
- for (const e of ordered) {
351
- if (e.height >= V29_HEIGHT) {
352
- const k = eid(e);
353
- if (seenIds.has(k)) continue;
354
- seenIds.add(k);
355
- }
356
- applied.push(e);
357
- }
340
+ 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;
341
+ var claimGrace = (o) => o.claimUntilHeight !== void 0 ? claimGraceOf(o.claimUntilHeight, o.claimTxid) : 0;
342
+ var claimHeld = (o, height) => o.claimedBy !== void 0 && o.claimUntilHeight !== void 0 && height < o.claimUntilHeight + claimGrace(o);
343
+ function createContext() {
358
344
  const tokens = /* @__PURE__ */ new Map();
359
345
  const balances = /* @__PURE__ */ new Map();
360
346
  const names = /* @__PURE__ */ new Map();
@@ -383,13 +369,6 @@ function resolve(events, tipHeight) {
383
369
  };
384
370
  const fclaims = /* @__PURE__ */ new Map();
385
371
  const log = [];
386
- let feesPaid = 0n;
387
- let pendingCancels = [];
388
- let pendingBlock = -1;
389
- const applyPendingCancels = () => {
390
- for (const f of pendingCancels) f();
391
- pendingCancels = [];
392
- };
393
372
  const bal = (ticker, addr) => {
394
373
  let m = balances.get(ticker);
395
374
  if (!m) {
@@ -415,7 +394,6 @@ function resolve(events, tipHeight) {
415
394
  b.available += amt;
416
395
  }
417
396
  };
418
- const effExpiry = (e, height) => e.height >= V22_HEIGHT ? e.expiresEpoch : height >= V21_HEIGHT ? Math.min(e.expiresEpoch, epochOf(e.height) + MAX_OFFER_EPOCHS) : e.expiresEpoch;
419
397
  const sweepExpired = (height) => {
420
398
  const ep = epochOf(height);
421
399
  for (const id of [...openOffers]) {
@@ -453,10 +431,6 @@ function resolve(events, tipHeight) {
453
431
  if (height > r.finalizeBy) recaptures.delete(nm);
454
432
  }
455
433
  };
456
- const V15_EPOCH = epochOf(V15_HEIGHT);
457
- const paidThrough = (n) => n.paidThroughEpoch ?? V15_EPOCH + NAME_TERM_EPOCHS;
458
- const lapsed = (n, ep) => ep > paidThrough(n) + NAME_GRACE_EPOCHS;
459
- const inGrace = (n, ep) => ep > paidThrough(n) && !lapsed(n, ep);
460
434
  const markBidDone = (o, buyer) => {
461
435
  if (!o.bid) return;
462
436
  const b = bids.get(o.bid);
@@ -469,28 +443,10 @@ function resolve(events, tipHeight) {
469
443
  setOfferStatus(o, "cancelled");
470
444
  }
471
445
  };
472
- const earlierAnchor = (effHeight, pos, id, inc) => effHeight < inc.effHeight || effHeight === inc.effHeight && (pos < inc.pos || pos === inc.pos && id < inc.id);
473
- const claimGrace = (o) => o.claimUntilHeight !== void 0 ? claimGraceOf(o.claimUntilHeight, o.claimTxid) : 0;
474
- const claimHeld = (o, height) => o.claimedBy !== void 0 && o.claimUntilHeight !== void 0 && height < o.claimUntilHeight + claimGrace(o);
475
- const openFillReject = (o, height, who, targetId) => {
476
- if (!(height >= V13_HEIGHT && !o.taker)) return void 0;
477
- if (height < V17_HEIGHT) return "v1.3: open CSD-quoted fills disabled (offer must be taker-bound)";
478
- if (height >= V28_HEIGHT && o.claimTxid !== void 0 && targetId === o.id) return "v2.8: fill the fclaim txid, not the offer";
479
- if (!(claimHeld(o, height) && who === o.claimedBy)) return "v1.7: open offer \u2014 claim it first (no live claim by you)";
480
- return void 0;
481
- };
482
- const deliverNameToBuyer = (n, who, ev) => {
483
- n.owner = who;
484
- n.locked = false;
485
- n.addr = void 0;
486
- n.profile = void 0;
487
- if (ev.height >= V13_HEIGHT) {
488
- n.effHeight = ev.height;
489
- n.pos = ev.pos;
490
- n.id = ev.txid;
491
- n.height = ev.height;
492
- n.viaFill = true;
493
- }
446
+ const liveHoldCount = (who, height) => {
447
+ let liveN = 0;
448
+ for (const x of offers.values()) if (x.claimedBy === who && claimHeld(x, height) && (height < V29_HEIGHT || x.status === "open")) liveN++;
449
+ return liveN;
494
450
  };
495
451
  const releaseGiveLock = (o, who, amt) => {
496
452
  const t = o.give.ticker;
@@ -498,6 +454,960 @@ function resolve(events, tipHeight) {
498
454
  bal(t, who).available += amt;
499
455
  offerLock.delete(o.id);
500
456
  };
457
+ return {
458
+ tokens,
459
+ balances,
460
+ names,
461
+ commits,
462
+ recaptures,
463
+ offers,
464
+ offerLock,
465
+ bids,
466
+ openOffers,
467
+ openBids,
468
+ pendingNames,
469
+ fclaims,
470
+ log,
471
+ setOfferStatus,
472
+ setBidStatus,
473
+ putName,
474
+ bal,
475
+ note,
476
+ releaseGive,
477
+ sweepExpired,
478
+ markBidDone,
479
+ voidOpenNameOffers,
480
+ liveHoldCount,
481
+ releaseGiveLock,
482
+ feesPaid: 0n,
483
+ // v1.4 fill-before-cancel: at V14_HEIGHT+ a cancel/ocancel's EFFECT is deferred to the block
484
+ // boundary, so any same-block fill wins — a seller can no longer snipe a buyer's in-flight
485
+ // payment by front-running the fill with a cheap cancel (cancel applies first in consensus
486
+ // order: proposals before attests, and a paid-up cancel attest can out-pos the fill). A fill
487
+ // that lands = seller got paid = a completed sale; the late cancel then no-ops. Pre-v14 blocks
488
+ // never populate pendingCancels, so all historical replay stays byte-identical.
489
+ pendingCancels: []
490
+ };
491
+ }
492
+
493
+ // src/resolve/attest.ts
494
+ var openFillReject = (o, height, who, targetId) => {
495
+ if (!(height >= V13_HEIGHT && !o.taker)) return void 0;
496
+ if (height < V17_HEIGHT) return "v1.3: open CSD-quoted fills disabled (offer must be taker-bound)";
497
+ if (height >= V28_HEIGHT && o.claimTxid !== void 0 && targetId === o.id) return "v2.8: fill the fclaim txid, not the offer";
498
+ if (!(claimHeld(o, height) && who === o.claimedBy)) return "v1.7: open offer \u2014 claim it first (no live claim by you)";
499
+ return void 0;
500
+ };
501
+ var deliverNameToBuyer = (n, who, ev) => {
502
+ n.owner = who;
503
+ n.locked = false;
504
+ n.addr = void 0;
505
+ n.profile = void 0;
506
+ if (ev.height >= V13_HEIGHT) {
507
+ n.effHeight = ev.height;
508
+ n.pos = ev.pos;
509
+ n.id = ev.txid;
510
+ n.height = ev.height;
511
+ n.viaFill = true;
512
+ }
513
+ };
514
+ function applyAttest(c, ev) {
515
+ const { offers, fclaims, bids, note, setBidStatus } = c;
516
+ const who = ev.attester.toLowerCase();
517
+ let o = offers.get(ev.proposalId);
518
+ if (!o && ev.height >= V28_HEIGHT && ev.score === SCORE_FILL) {
519
+ const fc = fclaims.get(ev.proposalId);
520
+ if (fc && fc.granted) {
521
+ const linked = offers.get(fc.offer);
522
+ if (linked && linked.claimTxid === ev.proposalId) o = linked;
523
+ }
524
+ }
525
+ if (!o) {
526
+ if (ev.height >= V28_HEIGHT && ev.score === SCORE_FILL && fclaims.has(ev.proposalId)) {
527
+ note(ev, ev.txid, "fill", false, "fclaim not current (denied or superseded): no delivery, denied-fclaim fill");
528
+ return;
529
+ }
530
+ const b = bids.get(ev.proposalId);
531
+ if (b && ev.score === SCORE_CANCEL) {
532
+ if (who !== b.bidder) {
533
+ note(ev, ev.txid, "bidcancel", false, "only bidder may cancel");
534
+ return;
535
+ }
536
+ if (b.status !== "open") {
537
+ note(ev, ev.txid, "bidcancel", false, `bid ${b.status}`);
538
+ return;
539
+ }
540
+ setBidStatus(b, "cancelled");
541
+ note(ev, ev.txid, "bidcancel", true);
542
+ }
543
+ return;
544
+ }
545
+ if (ev.score === SCORE_CANCEL) applyCancel(c, ev, o, who);
546
+ else if (ev.score === SCORE_FILL && isTokenWant(o.want)) applyTokenFill(c, ev, o, who);
547
+ else if (ev.score === SCORE_FILL && o.min !== void 0 && !isNameGive(o.give)) applyPartialFill(c, ev, o, who);
548
+ else if (ev.score === SCORE_FILL) applyFill(c, ev, o, who);
549
+ else if (ev.height >= V17_HEIGHT && ev.score === SCORE_CLAIM) applyLegacyClaim(c, ev, o, who);
550
+ }
551
+ function applyCancel(c, ev, o, who) {
552
+ const { note, releaseGive, setOfferStatus } = c;
553
+ if (who !== o.seller) {
554
+ note(ev, ev.txid, "cancel", false, "only seller may cancel");
555
+ return;
556
+ }
557
+ if (o.status !== "open") {
558
+ note(ev, ev.txid, "cancel", false, `offer ${o.status}`);
559
+ return;
560
+ }
561
+ if (o.taker !== void 0 && o.height >= V28_HEIGHT) {
562
+ note(ev, ev.txid, "cancel", false, "v2.8: taker-bound offers are firm quotes (uncancellable)");
563
+ return;
564
+ }
565
+ if (ev.height >= V14_HEIGHT) {
566
+ c.pendingCancels.push(() => {
567
+ if (ev.height >= V28_HEIGHT && o.claimTxid !== void 0 && claimHeld(o, ev.height)) {
568
+ note(ev, ev.txid, "cancel", false, "v2.8: frozen (fclaim hold live)");
569
+ return;
570
+ }
571
+ if (o.status === "open") {
572
+ releaseGive(o);
573
+ setOfferStatus(o, "cancelled");
574
+ note(ev, ev.txid, "cancel", true);
575
+ } else note(ev, ev.txid, "cancel", false, "superseded by same-block fill (v1.4)");
576
+ });
577
+ } else {
578
+ releaseGive(o);
579
+ setOfferStatus(o, "cancelled");
580
+ note(ev, ev.txid, "cancel", true);
581
+ }
582
+ }
583
+ function applyTokenFill(c, ev, o, who) {
584
+ const { tokens, names, offerLock, bal, note, setOfferStatus, markBidDone, releaseGiveLock } = c;
585
+ if (o.status !== "open") {
586
+ note(ev, ev.txid, "fill", false, `offer ${o.status}`);
587
+ return;
588
+ }
589
+ if (o.taker && who !== o.taker) {
590
+ note(ev, ev.txid, "fill", false, "taker-bound offer");
591
+ return;
592
+ }
593
+ if (ev.confidence !== CONF_TOKEN_FILL) {
594
+ note(ev, ev.txid, "fill", false, "token fill requires confidence marker");
595
+ return;
596
+ }
597
+ if (!tokens.has(o.want.ticker)) {
598
+ note(ev, ev.txid, "fill", false, "want ticker does not exist");
599
+ return;
600
+ }
601
+ const amt = BigInt(o.want.amount);
602
+ const fee = o.feeBps ? tradeFee(amt, o.feeBps) : 0n;
603
+ const buyer = bal(o.want.ticker, who);
604
+ if (buyer.available < amt + fee) {
605
+ note(ev, ev.txid, "fill", false, "insufficient want-token balance");
606
+ return;
607
+ }
608
+ const giveName = isNameGive(o.give) ? names.get(o.give.name) : void 0;
609
+ if (isNameGive(o.give) && !giveName) {
610
+ note(ev, ev.txid, "fill", false, "name vanished (consensus violation)");
611
+ return;
612
+ }
613
+ const giveLock = isNameGive(o.give) ? void 0 : offerLock.get(o.id);
614
+ if (!isNameGive(o.give) && giveLock === void 0) {
615
+ note(ev, ev.txid, "fill", false, "offer lock missing");
616
+ return;
617
+ }
618
+ buyer.available -= amt + fee;
619
+ bal(o.want.ticker, o.want.payto).available += amt;
620
+ if (fee > 0n) bal(o.want.ticker, TREASURY_ADDR).available += fee;
621
+ if (isNameGive(o.give)) deliverNameToBuyer(giveName, who, ev);
622
+ else releaseGiveLock(o, who, giveLock);
623
+ setOfferStatus(o, "filled");
624
+ o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: amt.toString(), fee: fee.toString() };
625
+ markBidDone(o, who);
626
+ note(ev, ev.txid, "fill", true);
627
+ }
628
+ function applyPartialFill(c, ev, o, who) {
629
+ const { offerLock, bal, note, setOfferStatus, markBidDone } = c;
630
+ if (o.status !== "open") {
631
+ note(ev, ev.txid, "fill", false, `offer ${o.status}`);
632
+ return;
633
+ }
634
+ if (o.taker && who !== o.taker) {
635
+ note(ev, ev.txid, "fill", false, "taker-bound offer");
636
+ return;
637
+ }
638
+ const blk = openFillReject(o, ev.height, who, ev.proposalId);
639
+ if (blk) {
640
+ note(ev, ev.txid, "fill", false, blk);
641
+ return;
642
+ }
643
+ const pt = ev.paidTo ?? {};
644
+ const want = BigInt(o.want.value);
645
+ const paidSoFar = BigInt(o.paid ?? "0");
646
+ const remaining = want - paidSoFar;
647
+ const X = ptAmt(pt[o.want.payto]);
648
+ const minV = BigInt(o.min);
649
+ const effMin = remaining < minV ? remaining : minV;
650
+ if (X < effMin) {
651
+ note(ev, ev.txid, "fill", false, "payment below offer min");
652
+ return;
653
+ }
654
+ const x = X < remaining ? X : remaining;
655
+ const fee = o.feeBps ? tradeFee(x, o.feeBps) : 0n;
656
+ if (ptAmt(pt[TREASURY_ADDR]) < fee) {
657
+ note(ev, ev.txid, "fill", false, "protocol fee unpaid");
658
+ return;
659
+ }
660
+ const giveTotal = BigInt(o.give.amount);
661
+ const newPaid = paidSoFar + x;
662
+ const deliveredSoFar = BigInt(o.delivered ?? "0");
663
+ const newDelivered = giveTotal * newPaid / want;
664
+ const out = newDelivered - deliveredSoFar;
665
+ if (out === 0n) {
666
+ note(ev, ev.txid, "fill", false, "fill too small to deliver any tokens");
667
+ return;
668
+ }
669
+ const lock = offerLock.get(o.id);
670
+ if (lock === void 0) {
671
+ note(ev, ev.txid, "fill", false, "offer lock missing");
672
+ return;
673
+ }
674
+ bal(o.give.ticker, o.seller).locked -= out;
675
+ bal(o.give.ticker, who).available += out;
676
+ offerLock.set(o.id, lock - out);
677
+ o.paid = newPaid.toString();
678
+ o.delivered = newDelivered.toString();
679
+ const entry = { buyer: who, txid: ev.txid, height: ev.height, paid: x.toString(), fee: fee.toString(), got: out.toString() };
680
+ (o.fills ??= []).push(entry);
681
+ c.feesPaid += fee;
682
+ if (newPaid === want) {
683
+ setOfferStatus(o, "filled");
684
+ o.fill = entry;
685
+ offerLock.delete(o.id);
686
+ markBidDone(o, who);
687
+ }
688
+ note(ev, ev.txid, "fill", true, `partial ${x}/${want}`);
689
+ }
690
+ function applyFill(c, ev, o, who) {
691
+ const { names, offerLock, note, setOfferStatus, markBidDone, releaseGiveLock } = c;
692
+ if (o.status !== "open") {
693
+ note(ev, ev.txid, "fill", false, `offer ${o.status}`);
694
+ return;
695
+ }
696
+ if (o.taker && who !== o.taker) {
697
+ note(ev, ev.txid, "fill", false, "taker-bound offer");
698
+ return;
699
+ }
700
+ const blk = openFillReject(o, ev.height, who, ev.proposalId);
701
+ if (blk) {
702
+ note(ev, ev.txid, "fill", false, blk);
703
+ return;
704
+ }
705
+ const pt = ev.paidTo ?? {};
706
+ const want = BigInt(o.want.value);
707
+ const fee = o.feeBps ? tradeFee(want, o.feeBps) : 0n;
708
+ const restingLiquidity = o.taker !== void 0 && o.bid !== void 0 || o.height >= V17_HEIGHT && o.taker === void 0;
709
+ const rebate = o.height >= V16_HEIGHT && restingLiquidity ? makerRebate(want) : 0n;
710
+ const need = /* @__PURE__ */ new Map();
711
+ const addNeed = (a, v) => need.set(a, (need.get(a) ?? 0n) + v);
712
+ addNeed(o.want.payto, want);
713
+ addNeed(TREASURY_ADDR, fee);
714
+ if (rebate > 0n) addNeed(o.seller, rebate);
715
+ let unpaid;
716
+ for (const [addr, amt] of need) if (ptAmt(pt[addr]) < amt) {
717
+ unpaid = addr === TREASURY_ADDR ? "protocol fee unpaid" : rebate > 0n && addr === o.seller ? "maker rebate unpaid (v1.6)" : "payment below want.value";
718
+ break;
719
+ }
720
+ if (unpaid) {
721
+ note(ev, ev.txid, "fill", false, unpaid);
722
+ return;
723
+ }
724
+ const paid = ptAmt(pt[o.want.payto]);
725
+ if (isNameGive(o.give)) {
726
+ const n = names.get(o.give.name);
727
+ if (!n) {
728
+ note(ev, ev.txid, "fill", false, "name vanished (consensus violation)");
729
+ return;
730
+ }
731
+ deliverNameToBuyer(n, who, ev);
732
+ } else {
733
+ const amt = offerLock.get(o.id);
734
+ if (amt === void 0) {
735
+ note(ev, ev.txid, "fill", false, "offer lock missing");
736
+ return;
737
+ }
738
+ releaseGiveLock(o, who, amt);
739
+ }
740
+ c.feesPaid += fee;
741
+ setOfferStatus(o, "filled");
742
+ o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: paid.toString(), fee: fee.toString() };
743
+ markBidDone(o, who);
744
+ note(ev, ev.txid, "fill", true);
745
+ }
746
+ function applyLegacyClaim(c, ev, o, who) {
747
+ const { note, liveHoldCount } = c;
748
+ if (ev.height >= V28_HEIGHT) {
749
+ note(ev, ev.txid, "claim", false, "v2.8: claims are fclaim proposals now");
750
+ return;
751
+ }
752
+ if (o.status !== "open") {
753
+ note(ev, ev.txid, "claim", false, `offer ${o.status}`);
754
+ return;
755
+ }
756
+ if (o.taker) {
757
+ note(ev, ev.txid, "claim", false, "taker-bound offer needs no claim");
758
+ return;
759
+ }
760
+ if (isTokenWant(o.want)) {
761
+ note(ev, ev.txid, "claim", false, "claims are for CSD-priced offers (token offers are no-op-safe)");
762
+ return;
763
+ }
764
+ if (claimHeld(o, ev.height)) {
765
+ note(ev, ev.txid, "claim", false, "offer already claimed (hold live)");
766
+ return;
767
+ }
768
+ if (o.claimedBy === who && o.claimUntilHeight !== void 0 && ev.height < o.claimUntilHeight + claimGrace(o) + CLAIM_COOLDOWN_BLOCKS) {
769
+ note(ev, ev.txid, "claim", false, "claim cooldown (you just held this offer)");
770
+ return;
771
+ }
772
+ if (liveHoldCount(who, ev.height) >= MAX_ACTIVE_CLAIMS) {
773
+ note(ev, ev.txid, "claim", false, `max ${MAX_ACTIVE_CLAIMS} live claims per address`);
774
+ return;
775
+ }
776
+ o.claimedBy = who;
777
+ o.claimUntilHeight = ev.height + claimWindowAt(ev.height);
778
+ note(ev, ev.txid, "claim", true);
779
+ }
780
+
781
+ // src/resolve/names.ts
782
+ var V15_EPOCH = epochOf(V15_HEIGHT);
783
+ var paidThrough = (n) => n.paidThroughEpoch ?? V15_EPOCH + NAME_TERM_EPOCHS;
784
+ var lapsed = (n, ep) => ep > paidThrough(n) + NAME_GRACE_EPOCHS;
785
+ var inGrace = (n, ep) => ep > paidThrough(n) && !lapsed(n, ep);
786
+ var earlierAnchor = (effHeight, pos, id, inc) => effHeight < inc.effHeight || effHeight === inc.effHeight && (pos < inc.pos || pos === inc.pos && id < inc.id);
787
+ function applyNcommit(c, ev, rec) {
788
+ const { commits, note } = c;
789
+ const v11 = ev.height >= V11_HEIGHT;
790
+ if (!v11) {
791
+ note(ev, ev.id, "ncommit", false, "before v1.1 activation");
792
+ return;
793
+ }
794
+ const prev = commits.get(rec.commit);
795
+ if (prev === void 0 || ev.height < prev) commits.set(rec.commit, ev.height);
796
+ note(ev, ev.id, "ncommit", true);
797
+ }
798
+ function applyName(c, ev, rec, who, feeToTreasury) {
799
+ const { commits, names, recaptures, note, putName, voidOpenNameOffers } = c;
800
+ const v11 = ev.height >= V11_HEIGHT;
801
+ const v15 = ev.height >= V15_HEIGHT;
802
+ const v25 = ev.height >= V25_HEIGHT;
803
+ const v26 = ev.height >= V26_HEIGHT;
804
+ if (!v11) {
805
+ note(ev, ev.id, "name", false, "before v1.1 activation");
806
+ return;
807
+ }
808
+ const regWindow = v25 || v26 ? REG_COMMIT_MAX_BLOCKS : COMMIT_MAX_BLOCKS;
809
+ let effHeight = ev.height;
810
+ if (rec.salt !== void 0) {
811
+ const ch = nameCommit(rec.name, rec.salt, who);
812
+ const cH = commits.get(ch);
813
+ if (cH === void 0 || cH >= ev.height || ev.height - cH > regWindow) {
814
+ note(ev, ev.id, "name", false, "no valid in-window commit for this reveal");
815
+ return;
816
+ }
817
+ effHeight = cH;
818
+ }
819
+ const cur = names.get(rec.name);
820
+ const epClaim = epochOf(ev.height);
821
+ const curActive = cur && cur.pending && cur.finalizeBy !== void 0 && ev.height > cur.finalizeBy ? void 0 : cur;
822
+ if (curActive && !curActive.pending && v15 && lapsed(curActive, epClaim)) {
823
+ if (v26) {
824
+ if (rec.salt === void 0) {
825
+ note(ev, ev.id, "name", false, "v2.6: recapture requires a commit-reveal (salt)");
826
+ return;
827
+ }
828
+ const cr = recaptures.get(rec.name);
829
+ const crActive = cr && ev.height > cr.finalizeBy ? void 0 : cr;
830
+ const better2 = !crActive || earlierAnchor(effHeight, ev.pos, ev.id, crActive);
831
+ if (!better2) {
832
+ note(ev, ev.id, "name", false, "recapture already reserved (earlier anchor wins)");
833
+ return;
834
+ }
835
+ let myR = 0;
836
+ for (const [nm, r] of recaptures) if (r.owner === who && nm !== rec.name && ev.height <= r.finalizeBy) myR++;
837
+ if (myR >= MAX_PENDING_REG) {
838
+ note(ev, ev.id, "name", false, "too many pending recaptures (max reached)");
839
+ return;
840
+ }
841
+ 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 });
842
+ note(ev, ev.id, "name", true, crActive ? "recapture reserved (displaced prior reservation)" : "recapture reserved (pending finalize)");
843
+ return;
844
+ }
845
+ const fee = expiredClaimFee(rec.name, epClaim - (paidThrough(curActive) + NAME_GRACE_EPOCHS), ev.height);
846
+ if (feeToTreasury < fee) {
847
+ note(ev, ev.id, "name", false, "lapsed-name claim fee unpaid (decaying premium)");
848
+ return;
849
+ }
850
+ voidOpenNameOffers(rec.name, ev.height);
851
+ putName(rec.name, { owner: who, effHeight, pos: ev.pos, id: ev.id, height: ev.height, locked: false, viaFill: true, paidThroughEpoch: epClaim + NAME_TERM_EPOCHS });
852
+ c.feesPaid += fee;
853
+ note(ev, ev.id, "name", true, "lapsed lease re-claimed (premium)");
854
+ return;
855
+ }
856
+ if (v25) {
857
+ if (rec.salt === void 0) {
858
+ note(ev, ev.id, "name", false, "v2.5: registration requires a commit-reveal (salt)");
859
+ return;
860
+ }
861
+ const better2 = !curActive || !curActive.viaFill && earlierAnchor(effHeight, ev.pos, ev.id, curActive);
862
+ if (!better2) {
863
+ note(ev, ev.id, "name", false, curActive?.viaFill ? "name taken (purchased \u2014 not displaceable)" : "name taken (earlier anchor wins)");
864
+ return;
865
+ }
866
+ let myPending = 0;
867
+ for (const [nm, n] of names) if (n.pending && n.owner === who && nm !== rec.name && n.finalizeBy !== void 0 && ev.height <= n.finalizeBy) myPending++;
868
+ if (myPending >= MAX_PENDING_REG) {
869
+ note(ev, ev.id, "name", false, "too many pending reservations (max reached)");
870
+ return;
871
+ }
872
+ if (curActive) {
873
+ voidOpenNameOffers(rec.name, ev.height);
874
+ }
875
+ 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 });
876
+ note(ev, ev.id, "name", true, curActive ? "reserved (displaced prior reservation)" : "reserved (pending finalize)");
877
+ return;
878
+ }
879
+ if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
880
+ note(ev, ev.id, "name", false, "name registration fee unpaid");
881
+ return;
882
+ }
883
+ const cand = {
884
+ owner: who,
885
+ effHeight,
886
+ pos: ev.pos,
887
+ id: ev.id,
888
+ height: ev.height,
889
+ locked: false,
890
+ ...v15 ? { paidThroughEpoch: epClaim + NAME_TERM_EPOCHS } : {}
891
+ };
892
+ const better = !curActive || !curActive.viaFill && earlierAnchor(effHeight, ev.pos, ev.id, curActive);
893
+ if (!better) {
894
+ note(ev, ev.id, "name", false, curActive?.viaFill ? "name taken (purchased \u2014 not displaceable)" : "name taken (earlier anchor wins)");
895
+ return;
896
+ }
897
+ if (curActive) {
898
+ voidOpenNameOffers(rec.name, ev.height);
899
+ }
900
+ putName(rec.name, cand);
901
+ c.feesPaid += nameRegFee(rec.name, ev.height);
902
+ note(ev, ev.id, "name", true, curActive ? "displaced prior holder" : void 0);
903
+ }
904
+ function applyNfinalize(c, ev, rec, who, feeToTreasury) {
905
+ const { commits, names, recaptures, pendingNames, note, putName, voidOpenNameOffers } = c;
906
+ const v25 = ev.height >= V25_HEIGHT;
907
+ const v26 = ev.height >= V26_HEIGHT;
908
+ if (!v25) {
909
+ note(ev, ev.id, "nfinalize", false, "before v2.5 activation");
910
+ return;
911
+ }
912
+ const n = names.get(rec.name);
913
+ if (n && n.pending && n.owner === who) {
914
+ const cH = commits.get(nameCommit(rec.name, rec.salt, who));
915
+ if (cH === void 0 || cH !== n.effHeight) {
916
+ note(ev, ev.id, "nfinalize", false, "salt does not match the reservation commit");
917
+ return;
918
+ }
919
+ if (!(ev.height > n.effHeight + REG_COMMIT_MAX_BLOCKS)) {
920
+ note(ev, ev.id, "nfinalize", false, "too early \u2014 displacement contest not yet frozen");
921
+ return;
922
+ }
923
+ if (n.finalizeBy !== void 0 && ev.height > n.finalizeBy) {
924
+ note(ev, ev.id, "nfinalize", false, "reservation expired");
925
+ return;
926
+ }
927
+ if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
928
+ note(ev, ev.id, "nfinalize", false, "name registration fee unpaid");
929
+ return;
930
+ }
931
+ delete n.pending;
932
+ delete n.finalizeBy;
933
+ pendingNames.delete(rec.name);
934
+ n.paidThroughEpoch = epochOf(ev.height) + NAME_TERM_EPOCHS;
935
+ c.feesPaid += nameRegFee(rec.name, ev.height);
936
+ note(ev, ev.id, "nfinalize", true);
937
+ return;
938
+ }
939
+ const r = v26 ? recaptures.get(rec.name) : void 0;
940
+ if (r && r.owner === who) {
941
+ const cH = commits.get(nameCommit(rec.name, rec.salt, who));
942
+ if (cH === void 0 || cH !== r.effHeight) {
943
+ note(ev, ev.id, "nfinalize", false, "salt does not match the recapture commit");
944
+ return;
945
+ }
946
+ if (!(ev.height > r.effHeight + REG_COMMIT_MAX_BLOCKS)) {
947
+ note(ev, ev.id, "nfinalize", false, "too early \u2014 recapture contest not yet frozen");
948
+ return;
949
+ }
950
+ if (ev.height > r.finalizeBy) {
951
+ note(ev, ev.id, "nfinalize", false, "recapture reservation expired");
952
+ return;
953
+ }
954
+ const cur = names.get(rec.name);
955
+ const ep = epochOf(ev.height);
956
+ if (!cur || cur.pending || !lapsed(cur, ep)) {
957
+ recaptures.delete(rec.name);
958
+ note(ev, ev.id, "nfinalize", false, "name is no longer lapsed");
959
+ return;
960
+ }
961
+ const fee = expiredClaimFee(rec.name, ep - (paidThrough(cur) + NAME_GRACE_EPOCHS), ev.height);
962
+ if (feeToTreasury < fee) {
963
+ note(ev, ev.id, "nfinalize", false, "recapture premium unpaid (decaying)");
964
+ return;
965
+ }
966
+ voidOpenNameOffers(rec.name, ev.height);
967
+ putName(rec.name, { owner: who, effHeight: r.effHeight, pos: r.pos, id: r.id, height: r.height, locked: false, paidThroughEpoch: ep + NAME_TERM_EPOCHS });
968
+ recaptures.delete(rec.name);
969
+ c.feesPaid += fee;
970
+ note(ev, ev.id, "nfinalize", true, "recapture finalized (premium)");
971
+ return;
972
+ }
973
+ note(ev, ev.id, "nfinalize", false, "no matching pending reservation you own");
974
+ }
975
+ function applyNxfer(c, ev, rec, who) {
976
+ const { names, note } = c;
977
+ const v15 = ev.height >= V15_HEIGHT;
978
+ const n = names.get(rec.name);
979
+ if (!n || n.owner !== who) {
980
+ note(ev, ev.id, "nxfer", false, "not the name owner");
981
+ return;
982
+ }
983
+ if (n.pending) {
984
+ note(ev, ev.id, "nxfer", false, "name reservation not yet finalized");
985
+ return;
986
+ }
987
+ if (v15 && lapsed(n, epochOf(ev.height))) {
988
+ note(ev, ev.id, "nxfer", false, "lease lapsed \u2014 claim it instead");
989
+ return;
990
+ }
991
+ if (n.locked) {
992
+ note(ev, ev.id, "nxfer", false, "name is locked by an open offer");
993
+ return;
994
+ }
995
+ n.owner = rec.to.toLowerCase();
996
+ n.addr = void 0;
997
+ n.profile = void 0;
998
+ note(ev, ev.id, "nxfer", true);
999
+ }
1000
+ function applyNset(c, ev, rec, who) {
1001
+ const { names, note } = c;
1002
+ const v15 = ev.height >= V15_HEIGHT;
1003
+ const v23 = ev.height >= V23_HEIGHT;
1004
+ const n = names.get(rec.name);
1005
+ if (!n || n.owner !== who) {
1006
+ note(ev, ev.id, "nset", false, "not the name owner");
1007
+ return;
1008
+ }
1009
+ if (n.pending) {
1010
+ note(ev, ev.id, "nset", false, "name reservation not yet finalized");
1011
+ return;
1012
+ }
1013
+ if (v15 && lapsed(n, epochOf(ev.height))) {
1014
+ note(ev, ev.id, "nset", false, "lease lapsed \u2014 claim it instead");
1015
+ return;
1016
+ }
1017
+ if (v23 && rec.addr.toLowerCase() === ZERO_ADDR) n.addr = void 0;
1018
+ else n.addr = rec.addr.toLowerCase();
1019
+ note(ev, ev.id, "nset", true);
1020
+ }
1021
+ function applyNprofile(c, ev, rec, who) {
1022
+ const { names, note } = c;
1023
+ const v15 = ev.height >= V15_HEIGHT;
1024
+ const v19 = ev.height >= V19_HEIGHT;
1025
+ if (!v19) {
1026
+ note(ev, ev.id, "nprofile", false, "before v1.9 activation");
1027
+ return;
1028
+ }
1029
+ const n = names.get(rec.name);
1030
+ if (!n || n.owner !== who) {
1031
+ note(ev, ev.id, "nprofile", false, "not the name owner");
1032
+ return;
1033
+ }
1034
+ if (n.pending) {
1035
+ note(ev, ev.id, "nprofile", false, "name reservation not yet finalized");
1036
+ return;
1037
+ }
1038
+ if (v15 && lapsed(n, epochOf(ev.height))) {
1039
+ note(ev, ev.id, "nprofile", false, "lease lapsed \u2014 claim it instead");
1040
+ return;
1041
+ }
1042
+ n.profile = Object.keys(rec.p).length ? { ...rec.p } : void 0;
1043
+ note(ev, ev.id, "nprofile", true);
1044
+ }
1045
+ function applyNrenew(c, ev, rec, who, feeToTreasury) {
1046
+ const { names, note } = c;
1047
+ const v15 = ev.height >= V15_HEIGHT;
1048
+ if (!v15) {
1049
+ note(ev, ev.id, "nrenew", false, "nrenew needs v1.5");
1050
+ return;
1051
+ }
1052
+ const n = names.get(rec.name);
1053
+ const ep = epochOf(ev.height);
1054
+ if (n && n.pending) {
1055
+ note(ev, ev.id, "nrenew", false, "name reservation not yet finalized");
1056
+ return;
1057
+ }
1058
+ if (!n || lapsed(n, ep)) {
1059
+ note(ev, ev.id, "nrenew", false, "no live lease (lapsed names are claimed, not renewed)");
1060
+ return;
1061
+ }
1062
+ if (inGrace(n, ep) && who !== n.owner) {
1063
+ note(ev, ev.id, "nrenew", false, "grace period: only the owner may renew");
1064
+ return;
1065
+ }
1066
+ if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
1067
+ note(ev, ev.id, "nrenew", false, "renewal fee unpaid");
1068
+ return;
1069
+ }
1070
+ n.paidThroughEpoch = paidThrough(n) + NAME_TERM_EPOCHS;
1071
+ c.feesPaid += nameRegFee(rec.name, ev.height);
1072
+ note(ev, ev.id, "nrenew", true, `paid through epoch ${n.paidThroughEpoch}`);
1073
+ }
1074
+
1075
+ // src/resolve/market.ts
1076
+ function applyOffer(c, ev, rec, who) {
1077
+ const { tokens, names, offers, offerLock, openOffers, bids, bal, note } = c;
1078
+ const v11 = ev.height >= V11_HEIGHT;
1079
+ const v15 = ev.height >= V15_HEIGHT;
1080
+ const v16 = ev.height >= V16_HEIGHT;
1081
+ const wantIsToken = isTokenWant(rec.want);
1082
+ const refusal = offerEnvelopeRefusal(rec, who, ev.height, ev.expiresEpoch);
1083
+ if (refusal !== null) {
1084
+ note(ev, ev.id, "offer", false, refusal);
1085
+ return;
1086
+ }
1087
+ const payto = (rec.want.payto ?? who).toLowerCase();
1088
+ const give = rec.give;
1089
+ if (isNameGive(give)) {
1090
+ if (!v11) {
1091
+ note(ev, ev.id, "offer", false, "name offers need v1.1");
1092
+ return;
1093
+ }
1094
+ const n = names.get(give.name);
1095
+ if (!n || n.owner !== who) {
1096
+ note(ev, ev.id, "offer", false, "you don't own this name");
1097
+ return;
1098
+ }
1099
+ if (n.pending) {
1100
+ note(ev, ev.id, "offer", false, "name reservation not yet finalized");
1101
+ return;
1102
+ }
1103
+ if (n.locked) {
1104
+ note(ev, ev.id, "offer", false, "name already locked by another offer");
1105
+ return;
1106
+ }
1107
+ const saleEmbargo = ev.height >= V27_HEIGHT ? REG_COMMIT_MAX_BLOCKS : COMMIT_MAX_BLOCKS;
1108
+ if (ev.height >= V13_HEIGHT && !n.viaFill && ev.height - n.effHeight <= saleEmbargo) {
1109
+ note(ev, ev.id, "offer", false, "name too young to sell (must out-age the reveal window)");
1110
+ return;
1111
+ }
1112
+ if (v15 && paidThrough(n) < ev.expiresEpoch) {
1113
+ note(ev, ev.id, "offer", false, "v1.5: lease ends inside the offer window (renew first)");
1114
+ return;
1115
+ }
1116
+ n.locked = true;
1117
+ } else {
1118
+ if (!tokens.has(give.ticker)) {
1119
+ note(ev, ev.id, "offer", false, "unknown ticker");
1120
+ return;
1121
+ }
1122
+ const amt = parseAmount(give.amount);
1123
+ const s = bal(give.ticker, who);
1124
+ if (s.available < amt) {
1125
+ note(ev, ev.id, "offer", false, "insufficient available balance");
1126
+ return;
1127
+ }
1128
+ s.available -= amt;
1129
+ s.locked += amt;
1130
+ offerLock.set(ev.id, amt);
1131
+ }
1132
+ const o = {
1133
+ id: ev.id,
1134
+ seller: who,
1135
+ give,
1136
+ want: wantIsToken ? { ticker: rec.want.ticker, amount: rec.want.amount, payto } : { value: rec.want.value, payto },
1137
+ ...rec.taker ? { taker: rec.taker.toLowerCase() } : {},
1138
+ ...rec.min !== void 0 ? { min: rec.min, paid: "0", delivered: "0", fills: [] } : {},
1139
+ ...rec.bid !== void 0 ? { bid: rec.bid } : {},
1140
+ status: "open",
1141
+ expiresEpoch: ev.expiresEpoch,
1142
+ height: ev.height,
1143
+ feeBps: v11 ? v16 ? FEE_BPS_V16 : FEE_BPS : 0
1144
+ };
1145
+ offers.set(ev.id, o);
1146
+ openOffers.add(ev.id);
1147
+ const linked = rec.bid !== void 0 ? bids.get(rec.bid) : void 0;
1148
+ if (linked) linked.offers.push(ev.id);
1149
+ note(ev, ev.id, "offer", true);
1150
+ }
1151
+ function applyBid(c, ev, rec, who) {
1152
+ const { bids, openBids, note } = c;
1153
+ const v12 = ev.height >= V12_HEIGHT;
1154
+ if (!v12) {
1155
+ note(ev, ev.id, "bid", false, "bids need v1.2");
1156
+ return;
1157
+ }
1158
+ if (!Number.isSafeInteger(ev.expiresEpoch)) {
1159
+ note(ev, ev.id, "bid", false, "expiresEpoch out of safe-integer range");
1160
+ return;
1161
+ }
1162
+ if (epochOf(ev.height) > ev.expiresEpoch) {
1163
+ note(ev, ev.id, "bid", false, "already expired at anchor");
1164
+ return;
1165
+ }
1166
+ if (ev.height >= V21_HEIGHT && ev.height < V22_HEIGHT && ev.expiresEpoch - epochOf(ev.height) > MAX_OFFER_EPOCHS) {
1167
+ note(ev, ev.id, "bid", false, "v2.1: bid duration exceeds the max");
1168
+ return;
1169
+ }
1170
+ bids.set(ev.id, {
1171
+ id: ev.id,
1172
+ bidder: who,
1173
+ want: rec.want,
1174
+ give: rec.give,
1175
+ status: "open",
1176
+ expiresEpoch: ev.expiresEpoch,
1177
+ height: ev.height,
1178
+ offers: []
1179
+ });
1180
+ openBids.add(ev.id);
1181
+ note(ev, ev.id, "bid", true);
1182
+ }
1183
+ function applyOcancel(c, ev, rec, who) {
1184
+ const { offers, note, releaseGive, setOfferStatus } = c;
1185
+ const v12 = ev.height >= V12_HEIGHT;
1186
+ if (!v12) {
1187
+ note(ev, ev.id, "ocancel", false, "ocancel needs v1.2");
1188
+ return;
1189
+ }
1190
+ const targets = [];
1191
+ for (const o of offers.values()) {
1192
+ if (o.status !== "open" || o.seller !== who) continue;
1193
+ if (o.taker !== void 0 && o.height >= V28_HEIGHT) continue;
1194
+ if (rec.ticker !== void 0 && !(!isNameGive(o.give) && o.give.ticker === rec.ticker)) continue;
1195
+ if (rec.name !== void 0 && !(isNameGive(o.give) && o.give.name === rec.name)) continue;
1196
+ targets.push(o);
1197
+ }
1198
+ if (ev.height >= V14_HEIGHT) {
1199
+ c.pendingCancels.push(() => {
1200
+ let n = 0;
1201
+ for (const o of targets) {
1202
+ if (ev.height >= V28_HEIGHT && o.claimTxid !== void 0 && claimHeld(o, ev.height)) continue;
1203
+ if (o.status === "open") {
1204
+ releaseGive(o);
1205
+ setOfferStatus(o, "cancelled");
1206
+ n++;
1207
+ }
1208
+ }
1209
+ note(ev, ev.id, "ocancel", true, `${n} cancelled (deferred past same-block fills)`);
1210
+ });
1211
+ } else {
1212
+ for (const o of targets) {
1213
+ releaseGive(o);
1214
+ setOfferStatus(o, "cancelled");
1215
+ }
1216
+ note(ev, ev.id, "ocancel", true, `${targets.length} cancelled`);
1217
+ }
1218
+ }
1219
+ function applyFclaim(c, ev, rec, who) {
1220
+ const { offers, fclaims, note, liveHoldCount } = c;
1221
+ if (ev.height < V28_HEIGHT) {
1222
+ note(ev, ev.id, "fclaim", false, "fclaim needs v2.8");
1223
+ return;
1224
+ }
1225
+ const target = offers.get(rec.offer);
1226
+ const E = ev.expiresEpoch;
1227
+ const deny = (why) => {
1228
+ fclaims.set(ev.id, { offer: rec.offer, proposer: who, expiresEpoch: E, height: ev.height, granted: false });
1229
+ note(ev, ev.id, "fclaim", false, why);
1230
+ };
1231
+ if (!Number.isSafeInteger(E)) {
1232
+ deny("expiresEpoch out of safe-integer range");
1233
+ return;
1234
+ }
1235
+ if (!target) {
1236
+ deny("unknown offer");
1237
+ return;
1238
+ }
1239
+ if (target.status !== "open") {
1240
+ deny(`offer ${target.status}`);
1241
+ return;
1242
+ }
1243
+ if (target.taker) {
1244
+ deny("taker-bound offer needs no claim");
1245
+ return;
1246
+ }
1247
+ if (isTokenWant(target.want)) {
1248
+ deny("claims are for CSD-priced offers");
1249
+ return;
1250
+ }
1251
+ if (E > effExpiry(target, ev.height)) {
1252
+ deny("hold would outlive the offer expiry");
1253
+ return;
1254
+ }
1255
+ if (E > epochOf(ev.height) + FCLAIM_MAX_EPOCH_AHEAD) {
1256
+ deny("hold too far ahead (anti-squat)");
1257
+ return;
1258
+ }
1259
+ if (epochOf(ev.height) > E) {
1260
+ deny("expiry already in the past");
1261
+ return;
1262
+ }
1263
+ if (claimHeld(target, ev.height)) {
1264
+ deny("offer already claimed (hold live)");
1265
+ return;
1266
+ }
1267
+ if (target.claimedBy === who && target.claimUntilHeight !== void 0 && ev.height < target.claimUntilHeight + claimGrace(target) + CLAIM_COOLDOWN_BLOCKS) {
1268
+ deny("claim cooldown (you just held this offer)");
1269
+ return;
1270
+ }
1271
+ if (liveHoldCount(who, ev.height) >= MAX_ACTIVE_CLAIMS) {
1272
+ deny(`max ${MAX_ACTIVE_CLAIMS} live claims per address`);
1273
+ return;
1274
+ }
1275
+ target.claimedBy = who;
1276
+ target.claimUntilHeight = (E + 1) * EPOCH_LEN;
1277
+ target.claimTxid = ev.id;
1278
+ fclaims.set(ev.id, { offer: rec.offer, proposer: who, expiresEpoch: E, height: ev.height, granted: true });
1279
+ note(ev, ev.id, "fclaim", true);
1280
+ }
1281
+ function offerEnvelopeRefusal(rec, who, height, expiresEpoch) {
1282
+ const wantIsToken = isTokenWant(rec.want);
1283
+ if ((wantIsToken || rec.min !== void 0 || rec.bid !== void 0) && height < V12_HEIGHT) return "v1.2 offer shape before activation";
1284
+ 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)";
1285
+ if ((rec.want.payto ?? who).toLowerCase() === TREASURY_ADDR) return "payto cannot be the protocol treasury";
1286
+ if (!Number.isSafeInteger(expiresEpoch)) return "expiresEpoch out of safe-integer range";
1287
+ if (epochOf(height) > expiresEpoch) return "already expired at anchor";
1288
+ if (height >= V21_HEIGHT && height < V22_HEIGHT && expiresEpoch - epochOf(height) > MAX_OFFER_EPOCHS) return "v2.1: offer duration exceeds the max";
1289
+ return null;
1290
+ }
1291
+
1292
+ // src/resolve/tokens.ts
1293
+ function applyDeploy(c, ev, rec, who, feeToTreasury) {
1294
+ const { tokens, note } = c;
1295
+ const v11 = ev.height >= V11_HEIGHT;
1296
+ if (tokens.has(rec.ticker)) {
1297
+ note(ev, ev.id, "deploy", false, "ticker taken (first anchor wins)");
1298
+ return;
1299
+ }
1300
+ if (v11 && feeToTreasury < BigInt(DEPLOY_FEE)) {
1301
+ note(ev, ev.id, "deploy", false, "deploy fee unpaid");
1302
+ return;
1303
+ }
1304
+ const supply = parseAmount(rec.supply);
1305
+ const mintLimit = rec.mint === "open" ? parseAmount(rec.mintLimit) : null;
1306
+ tokens.set(rec.ticker, {
1307
+ minted: 0n,
1308
+ supply,
1309
+ mintLimit,
1310
+ 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 }
1311
+ });
1312
+ if (v11) c.feesPaid += BigInt(DEPLOY_FEE);
1313
+ note(ev, ev.id, "deploy", true);
1314
+ }
1315
+ function applyMint(c, ev, rec, who) {
1316
+ const { tokens, bal, note } = c;
1317
+ const tok = tokens.get(rec.ticker);
1318
+ if (!tok) {
1319
+ note(ev, ev.id, "mint", false, "unknown ticker");
1320
+ return;
1321
+ }
1322
+ const remaining = tok.supply - tok.minted;
1323
+ if (remaining <= 0n) {
1324
+ note(ev, ev.id, "mint", false, "supply exhausted");
1325
+ return;
1326
+ }
1327
+ let credit;
1328
+ if (tok.meta.mint === "issuer") {
1329
+ if (who !== tok.meta.deployer) {
1330
+ note(ev, ev.id, "mint", false, "issuer-only mint");
1331
+ return;
1332
+ }
1333
+ const req = rec.amount !== void 0 ? parseAmount(rec.amount) : null;
1334
+ if (req === null) {
1335
+ note(ev, ev.id, "mint", false, "issuer mint requires amount");
1336
+ return;
1337
+ }
1338
+ credit = req < remaining ? req : remaining;
1339
+ } else {
1340
+ const req = rec.amount !== void 0 ? parseAmount(rec.amount) : tok.mintLimit;
1341
+ const capped = req < tok.mintLimit ? req : tok.mintLimit;
1342
+ credit = capped < remaining ? capped : remaining;
1343
+ }
1344
+ tok.minted += credit;
1345
+ bal(rec.ticker, who).available += credit;
1346
+ note(ev, ev.id, "mint", true, credit.toString());
1347
+ }
1348
+ function applyTransfer(c, ev, rec, who) {
1349
+ const { tokens, bal, note } = c;
1350
+ if (!tokens.has(rec.ticker)) {
1351
+ note(ev, ev.id, "transfer", false, "unknown ticker");
1352
+ return;
1353
+ }
1354
+ const amt = parseAmount(rec.amount);
1355
+ const from = bal(rec.ticker, who);
1356
+ if (from.available < amt) {
1357
+ note(ev, ev.id, "transfer", false, "insufficient available balance");
1358
+ return;
1359
+ }
1360
+ from.available -= amt;
1361
+ bal(rec.ticker, rec.to.toLowerCase()).available += amt;
1362
+ note(ev, ev.id, "transfer", true);
1363
+ }
1364
+ function applyTmeta(c, ev, rec, who) {
1365
+ const { tokens, note } = c;
1366
+ const v15 = ev.height >= V15_HEIGHT;
1367
+ if (!v15) {
1368
+ note(ev, ev.id, "tmeta", false, "tmeta needs v1.5");
1369
+ return;
1370
+ }
1371
+ const tok = tokens.get(rec.ticker);
1372
+ if (!tok) {
1373
+ note(ev, ev.id, "tmeta", false, "unknown ticker");
1374
+ return;
1375
+ }
1376
+ if (who !== tok.meta.deployer) {
1377
+ note(ev, ev.id, "tmeta", false, "issuer-only metadata");
1378
+ return;
1379
+ }
1380
+ tok.meta.tmeta = rec.hash;
1381
+ note(ev, ev.id, "tmeta", true);
1382
+ }
1383
+
1384
+ // src/resolve.ts
1385
+ var ord = (a, b) => a < b ? -1 : a > b ? 1 : 0;
1386
+ function resolve(events, tipHeight) {
1387
+ const ordered = [...events].sort(
1388
+ (a, b) => a.height - b.height || Number(a.kind === "attest") - Number(b.kind === "attest") || a.pos - b.pos || ord(
1389
+ a.kind === "propose" ? a.id : a.txid,
1390
+ b.kind === "propose" ? b.id : b.txid
1391
+ )
1392
+ );
1393
+ const eid = (e) => e.kind === "propose" ? e.id : e.txid;
1394
+ const seenIds = /* @__PURE__ */ new Set();
1395
+ const applied = [];
1396
+ for (const e of ordered) {
1397
+ if (e.height >= V29_HEIGHT) {
1398
+ const k = eid(e);
1399
+ if (seenIds.has(k)) continue;
1400
+ seenIds.add(k);
1401
+ }
1402
+ applied.push(e);
1403
+ }
1404
+ const c = createContext();
1405
+ const { tokens, balances, names, recaptures, offers, bids, fclaims, log, note, sweepExpired } = c;
1406
+ let pendingBlock = -1;
1407
+ const applyPendingCancels = () => {
1408
+ for (const f of c.pendingCancels) f();
1409
+ c.pendingCancels = [];
1410
+ };
501
1411
  for (const ev of applied) {
502
1412
  if (ev.height < ACTIVATION_HEIGHT) continue;
503
1413
  if (ev.height !== pendingBlock) {
@@ -505,14 +1415,6 @@ function resolve(events, tipHeight) {
505
1415
  pendingBlock = ev.height;
506
1416
  }
507
1417
  sweepExpired(ev.height);
508
- const v11 = ev.height >= V11_HEIGHT;
509
- const v12 = ev.height >= V12_HEIGHT;
510
- const v15 = ev.height >= V15_HEIGHT;
511
- const v16 = ev.height >= V16_HEIGHT;
512
- const v19 = ev.height >= V19_HEIGHT;
513
- const v23 = ev.height >= V23_HEIGHT;
514
- const v25 = ev.height >= V25_HEIGHT;
515
- const v26 = ev.height >= V26_HEIGHT;
516
1418
  const feeToTreasury = ev.kind === "propose" ? ptAmt((ev.paidTo ?? {})[TREASURY_ADDR]) : 0n;
517
1419
  if (ev.kind === "propose") {
518
1420
  const rec = parseRecord(ev.uri, ev.payloadHash);
@@ -521,812 +1423,55 @@ function resolve(events, tipHeight) {
521
1423
  continue;
522
1424
  }
523
1425
  const who = ev.proposer.toLowerCase();
524
- if (rec.t === "deploy") {
525
- if (tokens.has(rec.ticker)) {
526
- note(ev, ev.id, "deploy", false, "ticker taken (first anchor wins)");
527
- continue;
528
- }
529
- if (v11 && feeToTreasury < BigInt(DEPLOY_FEE)) {
530
- note(ev, ev.id, "deploy", false, "deploy fee unpaid");
531
- continue;
532
- }
533
- const supply = parseAmount(rec.supply);
534
- const mintLimit = rec.mint === "open" ? parseAmount(rec.mintLimit) : null;
535
- tokens.set(rec.ticker, {
536
- minted: 0n,
537
- supply,
538
- mintLimit,
539
- 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 }
540
- });
541
- if (v11) feesPaid += BigInt(DEPLOY_FEE);
542
- note(ev, ev.id, "deploy", true);
543
- } else if (rec.t === "mint") {
544
- const tok = tokens.get(rec.ticker);
545
- if (!tok) {
546
- note(ev, ev.id, "mint", false, "unknown ticker");
547
- continue;
548
- }
549
- const remaining = tok.supply - tok.minted;
550
- if (remaining <= 0n) {
551
- note(ev, ev.id, "mint", false, "supply exhausted");
552
- continue;
553
- }
554
- let credit;
555
- if (tok.meta.mint === "issuer") {
556
- if (who !== tok.meta.deployer) {
557
- note(ev, ev.id, "mint", false, "issuer-only mint");
558
- continue;
559
- }
560
- const req = rec.amount !== void 0 ? parseAmount(rec.amount) : null;
561
- if (req === null) {
562
- note(ev, ev.id, "mint", false, "issuer mint requires amount");
563
- continue;
564
- }
565
- credit = req < remaining ? req : remaining;
566
- } else {
567
- const req = rec.amount !== void 0 ? parseAmount(rec.amount) : tok.mintLimit;
568
- const capped = req < tok.mintLimit ? req : tok.mintLimit;
569
- credit = capped < remaining ? capped : remaining;
570
- }
571
- tok.minted += credit;
572
- bal(rec.ticker, who).available += credit;
573
- note(ev, ev.id, "mint", true, credit.toString());
574
- } else if (rec.t === "transfer") {
575
- if (!tokens.has(rec.ticker)) {
576
- note(ev, ev.id, "transfer", false, "unknown ticker");
577
- continue;
578
- }
579
- const amt = parseAmount(rec.amount);
580
- const from = bal(rec.ticker, who);
581
- if (from.available < amt) {
582
- note(ev, ev.id, "transfer", false, "insufficient available balance");
583
- continue;
584
- }
585
- from.available -= amt;
586
- bal(rec.ticker, rec.to.toLowerCase()).available += amt;
587
- note(ev, ev.id, "transfer", true);
588
- } else if (rec.t === "ncommit") {
589
- if (!v11) {
590
- note(ev, ev.id, "ncommit", false, "before v1.1 activation");
591
- continue;
592
- }
593
- const prev = commits.get(rec.commit);
594
- if (prev === void 0 || ev.height < prev) commits.set(rec.commit, ev.height);
595
- note(ev, ev.id, "ncommit", true);
596
- } else if (rec.t === "name") {
597
- if (!v11) {
598
- note(ev, ev.id, "name", false, "before v1.1 activation");
599
- continue;
600
- }
601
- const regWindow = v25 || v26 ? REG_COMMIT_MAX_BLOCKS : COMMIT_MAX_BLOCKS;
602
- let effHeight = ev.height;
603
- if (rec.salt !== void 0) {
604
- const ch = nameCommit(rec.name, rec.salt, who);
605
- const cH = commits.get(ch);
606
- if (cH === void 0 || cH >= ev.height || ev.height - cH > regWindow) {
607
- note(ev, ev.id, "name", false, "no valid in-window commit for this reveal");
608
- continue;
609
- }
610
- effHeight = cH;
611
- }
612
- const cur = names.get(rec.name);
613
- const epClaim = epochOf(ev.height);
614
- const curActive = cur && cur.pending && cur.finalizeBy !== void 0 && ev.height > cur.finalizeBy ? void 0 : cur;
615
- if (curActive && !curActive.pending && v15 && lapsed(curActive, epClaim)) {
616
- if (v26) {
617
- if (rec.salt === void 0) {
618
- note(ev, ev.id, "name", false, "v2.6: recapture requires a commit-reveal (salt)");
619
- continue;
620
- }
621
- const cr = recaptures.get(rec.name);
622
- const crActive = cr && ev.height > cr.finalizeBy ? void 0 : cr;
623
- const better2 = !crActive || earlierAnchor(effHeight, ev.pos, ev.id, crActive);
624
- if (!better2) {
625
- note(ev, ev.id, "name", false, "recapture already reserved (earlier anchor wins)");
626
- continue;
627
- }
628
- let myR = 0;
629
- for (const [nm, r] of recaptures) if (r.owner === who && nm !== rec.name && ev.height <= r.finalizeBy) myR++;
630
- if (myR >= MAX_PENDING_REG) {
631
- note(ev, ev.id, "name", false, "too many pending recaptures (max reached)");
632
- continue;
633
- }
634
- 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 });
635
- note(ev, ev.id, "name", true, crActive ? "recapture reserved (displaced prior reservation)" : "recapture reserved (pending finalize)");
636
- continue;
637
- }
638
- const fee = expiredClaimFee(rec.name, epClaim - (paidThrough(curActive) + NAME_GRACE_EPOCHS), ev.height);
639
- if (feeToTreasury < fee) {
640
- note(ev, ev.id, "name", false, "lapsed-name claim fee unpaid (decaying premium)");
641
- continue;
642
- }
643
- voidOpenNameOffers(rec.name, ev.height);
644
- putName(rec.name, { owner: who, effHeight, pos: ev.pos, id: ev.id, height: ev.height, locked: false, viaFill: true, paidThroughEpoch: epClaim + NAME_TERM_EPOCHS });
645
- feesPaid += fee;
646
- note(ev, ev.id, "name", true, "lapsed lease re-claimed (premium)");
647
- continue;
648
- }
649
- if (v25) {
650
- if (rec.salt === void 0) {
651
- note(ev, ev.id, "name", false, "v2.5: registration requires a commit-reveal (salt)");
652
- continue;
653
- }
654
- const better2 = !curActive || !curActive.viaFill && earlierAnchor(effHeight, ev.pos, ev.id, curActive);
655
- if (!better2) {
656
- note(ev, ev.id, "name", false, curActive?.viaFill ? "name taken (purchased \u2014 not displaceable)" : "name taken (earlier anchor wins)");
657
- continue;
658
- }
659
- let myPending = 0;
660
- for (const [nm, n] of names) if (n.pending && n.owner === who && nm !== rec.name && n.finalizeBy !== void 0 && ev.height <= n.finalizeBy) myPending++;
661
- if (myPending >= MAX_PENDING_REG) {
662
- note(ev, ev.id, "name", false, "too many pending reservations (max reached)");
663
- continue;
664
- }
665
- if (curActive) {
666
- voidOpenNameOffers(rec.name, ev.height);
667
- }
668
- 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 });
669
- note(ev, ev.id, "name", true, curActive ? "reserved (displaced prior reservation)" : "reserved (pending finalize)");
670
- continue;
671
- }
672
- if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
673
- note(ev, ev.id, "name", false, "name registration fee unpaid");
674
- continue;
675
- }
676
- const cand = {
677
- owner: who,
678
- effHeight,
679
- pos: ev.pos,
680
- id: ev.id,
681
- height: ev.height,
682
- locked: false,
683
- ...v15 ? { paidThroughEpoch: epClaim + NAME_TERM_EPOCHS } : {}
684
- };
685
- const better = !curActive || !curActive.viaFill && earlierAnchor(effHeight, ev.pos, ev.id, curActive);
686
- if (!better) {
687
- note(ev, ev.id, "name", false, curActive?.viaFill ? "name taken (purchased \u2014 not displaceable)" : "name taken (earlier anchor wins)");
688
- continue;
689
- }
690
- if (curActive) {
691
- voidOpenNameOffers(rec.name, ev.height);
692
- }
693
- putName(rec.name, cand);
694
- feesPaid += nameRegFee(rec.name, ev.height);
695
- note(ev, ev.id, "name", true, curActive ? "displaced prior holder" : void 0);
696
- } else if (rec.t === "nfinalize") {
697
- if (!v25) {
698
- note(ev, ev.id, "nfinalize", false, "before v2.5 activation");
699
- continue;
700
- }
701
- const n = names.get(rec.name);
702
- if (n && n.pending && n.owner === who) {
703
- const cH = commits.get(nameCommit(rec.name, rec.salt, who));
704
- if (cH === void 0 || cH !== n.effHeight) {
705
- note(ev, ev.id, "nfinalize", false, "salt does not match the reservation commit");
706
- continue;
707
- }
708
- if (!(ev.height > n.effHeight + REG_COMMIT_MAX_BLOCKS)) {
709
- note(ev, ev.id, "nfinalize", false, "too early \u2014 displacement contest not yet frozen");
710
- continue;
711
- }
712
- if (n.finalizeBy !== void 0 && ev.height > n.finalizeBy) {
713
- note(ev, ev.id, "nfinalize", false, "reservation expired");
714
- continue;
715
- }
716
- if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
717
- note(ev, ev.id, "nfinalize", false, "name registration fee unpaid");
718
- continue;
719
- }
720
- delete n.pending;
721
- delete n.finalizeBy;
722
- pendingNames.delete(rec.name);
723
- n.paidThroughEpoch = epochOf(ev.height) + NAME_TERM_EPOCHS;
724
- feesPaid += nameRegFee(rec.name, ev.height);
725
- note(ev, ev.id, "nfinalize", true);
726
- continue;
727
- }
728
- const r = v26 ? recaptures.get(rec.name) : void 0;
729
- if (r && r.owner === who) {
730
- const cH = commits.get(nameCommit(rec.name, rec.salt, who));
731
- if (cH === void 0 || cH !== r.effHeight) {
732
- note(ev, ev.id, "nfinalize", false, "salt does not match the recapture commit");
733
- continue;
734
- }
735
- if (!(ev.height > r.effHeight + REG_COMMIT_MAX_BLOCKS)) {
736
- note(ev, ev.id, "nfinalize", false, "too early \u2014 recapture contest not yet frozen");
737
- continue;
738
- }
739
- if (ev.height > r.finalizeBy) {
740
- note(ev, ev.id, "nfinalize", false, "recapture reservation expired");
741
- continue;
742
- }
743
- const cur = names.get(rec.name);
744
- const ep = epochOf(ev.height);
745
- if (!cur || cur.pending || !lapsed(cur, ep)) {
746
- recaptures.delete(rec.name);
747
- note(ev, ev.id, "nfinalize", false, "name is no longer lapsed");
748
- continue;
749
- }
750
- const fee = expiredClaimFee(rec.name, ep - (paidThrough(cur) + NAME_GRACE_EPOCHS), ev.height);
751
- if (feeToTreasury < fee) {
752
- note(ev, ev.id, "nfinalize", false, "recapture premium unpaid (decaying)");
753
- continue;
754
- }
755
- voidOpenNameOffers(rec.name, ev.height);
756
- putName(rec.name, { owner: who, effHeight: r.effHeight, pos: r.pos, id: r.id, height: r.height, locked: false, paidThroughEpoch: ep + NAME_TERM_EPOCHS });
757
- recaptures.delete(rec.name);
758
- feesPaid += fee;
759
- note(ev, ev.id, "nfinalize", true, "recapture finalized (premium)");
760
- continue;
761
- }
762
- note(ev, ev.id, "nfinalize", false, "no matching pending reservation you own");
763
- } else if (rec.t === "nxfer") {
764
- const n = names.get(rec.name);
765
- if (!n || n.owner !== who) {
766
- note(ev, ev.id, "nxfer", false, "not the name owner");
767
- continue;
768
- }
769
- if (n.pending) {
770
- note(ev, ev.id, "nxfer", false, "name reservation not yet finalized");
771
- continue;
772
- }
773
- if (v15 && lapsed(n, epochOf(ev.height))) {
774
- note(ev, ev.id, "nxfer", false, "lease lapsed \u2014 claim it instead");
775
- continue;
776
- }
777
- if (n.locked) {
778
- note(ev, ev.id, "nxfer", false, "name is locked by an open offer");
779
- continue;
780
- }
781
- n.owner = rec.to.toLowerCase();
782
- n.addr = void 0;
783
- n.profile = void 0;
784
- note(ev, ev.id, "nxfer", true);
785
- } else if (rec.t === "nset") {
786
- const n = names.get(rec.name);
787
- if (!n || n.owner !== who) {
788
- note(ev, ev.id, "nset", false, "not the name owner");
789
- continue;
790
- }
791
- if (n.pending) {
792
- note(ev, ev.id, "nset", false, "name reservation not yet finalized");
793
- continue;
794
- }
795
- if (v15 && lapsed(n, epochOf(ev.height))) {
796
- note(ev, ev.id, "nset", false, "lease lapsed \u2014 claim it instead");
797
- continue;
798
- }
799
- if (v23 && rec.addr.toLowerCase() === ZERO_ADDR) n.addr = void 0;
800
- else n.addr = rec.addr.toLowerCase();
801
- note(ev, ev.id, "nset", true);
802
- } else if (rec.t === "nprofile") {
803
- if (!v19) {
804
- note(ev, ev.id, "nprofile", false, "before v1.9 activation");
805
- continue;
806
- }
807
- const n = names.get(rec.name);
808
- if (!n || n.owner !== who) {
809
- note(ev, ev.id, "nprofile", false, "not the name owner");
810
- continue;
811
- }
812
- if (n.pending) {
813
- note(ev, ev.id, "nprofile", false, "name reservation not yet finalized");
814
- continue;
815
- }
816
- if (v15 && lapsed(n, epochOf(ev.height))) {
817
- note(ev, ev.id, "nprofile", false, "lease lapsed \u2014 claim it instead");
818
- continue;
819
- }
820
- n.profile = Object.keys(rec.p).length ? { ...rec.p } : void 0;
821
- note(ev, ev.id, "nprofile", true);
822
- } else if (rec.t === "offer") {
823
- const wantIsToken = isTokenWant(rec.want);
824
- if ((wantIsToken || rec.min !== void 0 || rec.bid !== void 0) && !v12) {
825
- note(ev, ev.id, "offer", false, "v1.2 offer shape before activation");
826
- continue;
827
- }
828
- if (ev.height >= V13_HEIGHT && ev.height < V17_HEIGHT && !wantIsToken && rec.taker === void 0) {
829
- note(ev, ev.id, "offer", false, "v1.3: CSD-priced offers must be taker-bound (use bid/RFQ)");
830
- continue;
831
- }
832
- const payto = (rec.want.payto ?? who).toLowerCase();
833
- if (payto === TREASURY_ADDR) {
834
- note(ev, ev.id, "offer", false, "payto cannot be the protocol treasury");
835
- continue;
836
- }
837
- if (!Number.isSafeInteger(ev.expiresEpoch)) {
838
- note(ev, ev.id, "offer", false, "expiresEpoch out of safe-integer range");
839
- continue;
840
- }
841
- if (epochOf(ev.height) > ev.expiresEpoch) {
842
- note(ev, ev.id, "offer", false, "already expired at anchor");
843
- continue;
844
- }
845
- if (ev.height >= V21_HEIGHT && ev.height < V22_HEIGHT && ev.expiresEpoch - epochOf(ev.height) > MAX_OFFER_EPOCHS) {
846
- note(ev, ev.id, "offer", false, "v2.1: offer duration exceeds the max");
847
- continue;
848
- }
849
- const give = rec.give;
850
- if (isNameGive(give)) {
851
- if (!v11) {
852
- note(ev, ev.id, "offer", false, "name offers need v1.1");
853
- continue;
854
- }
855
- const n = names.get(give.name);
856
- if (!n || n.owner !== who) {
857
- note(ev, ev.id, "offer", false, "you don't own this name");
858
- continue;
859
- }
860
- if (n.pending) {
861
- note(ev, ev.id, "offer", false, "name reservation not yet finalized");
862
- continue;
863
- }
864
- if (n.locked) {
865
- note(ev, ev.id, "offer", false, "name already locked by another offer");
866
- continue;
867
- }
868
- const saleEmbargo = ev.height >= V27_HEIGHT ? REG_COMMIT_MAX_BLOCKS : COMMIT_MAX_BLOCKS;
869
- if (ev.height >= V13_HEIGHT && !n.viaFill && ev.height - n.effHeight <= saleEmbargo) {
870
- note(ev, ev.id, "offer", false, "name too young to sell (must out-age the reveal window)");
871
- continue;
872
- }
873
- if (v15 && paidThrough(n) < ev.expiresEpoch) {
874
- note(ev, ev.id, "offer", false, "v1.5: lease ends inside the offer window (renew first)");
875
- continue;
876
- }
877
- n.locked = true;
878
- } else {
879
- if (!tokens.has(give.ticker)) {
880
- note(ev, ev.id, "offer", false, "unknown ticker");
881
- continue;
882
- }
883
- const amt = parseAmount(give.amount);
884
- const s = bal(give.ticker, who);
885
- if (s.available < amt) {
886
- note(ev, ev.id, "offer", false, "insufficient available balance");
887
- continue;
888
- }
889
- s.available -= amt;
890
- s.locked += amt;
891
- offerLock.set(ev.id, amt);
892
- }
893
- const o = {
894
- id: ev.id,
895
- seller: who,
896
- give,
897
- want: wantIsToken ? { ticker: rec.want.ticker, amount: rec.want.amount, payto } : { value: rec.want.value, payto },
898
- ...rec.taker ? { taker: rec.taker.toLowerCase() } : {},
899
- ...rec.min !== void 0 ? { min: rec.min, paid: "0", delivered: "0", fills: [] } : {},
900
- ...rec.bid !== void 0 ? { bid: rec.bid } : {},
901
- status: "open",
902
- expiresEpoch: ev.expiresEpoch,
903
- height: ev.height,
904
- feeBps: v11 ? v16 ? FEE_BPS_V16 : FEE_BPS : 0
905
- };
906
- offers.set(ev.id, o);
907
- openOffers.add(ev.id);
908
- const linked = rec.bid !== void 0 ? bids.get(rec.bid) : void 0;
909
- if (linked) linked.offers.push(ev.id);
910
- note(ev, ev.id, "offer", true);
911
- } else if (rec.t === "bid") {
912
- if (!v12) {
913
- note(ev, ev.id, "bid", false, "bids need v1.2");
914
- continue;
915
- }
916
- if (!Number.isSafeInteger(ev.expiresEpoch)) {
917
- note(ev, ev.id, "bid", false, "expiresEpoch out of safe-integer range");
918
- continue;
919
- }
920
- if (epochOf(ev.height) > ev.expiresEpoch) {
921
- note(ev, ev.id, "bid", false, "already expired at anchor");
922
- continue;
923
- }
924
- if (ev.height >= V21_HEIGHT && ev.height < V22_HEIGHT && ev.expiresEpoch - epochOf(ev.height) > MAX_OFFER_EPOCHS) {
925
- note(ev, ev.id, "bid", false, "v2.1: bid duration exceeds the max");
926
- continue;
927
- }
928
- bids.set(ev.id, {
929
- id: ev.id,
930
- bidder: who,
931
- want: rec.want,
932
- give: rec.give,
933
- status: "open",
934
- expiresEpoch: ev.expiresEpoch,
935
- height: ev.height,
936
- offers: []
937
- });
938
- openBids.add(ev.id);
939
- note(ev, ev.id, "bid", true);
940
- } else if (rec.t === "ocancel") {
941
- if (!v12) {
942
- note(ev, ev.id, "ocancel", false, "ocancel needs v1.2");
943
- continue;
944
- }
945
- const targets = [];
946
- for (const o of offers.values()) {
947
- if (o.status !== "open" || o.seller !== who) continue;
948
- if (o.taker !== void 0 && o.height >= V28_HEIGHT) continue;
949
- if (rec.ticker !== void 0 && !(!isNameGive(o.give) && o.give.ticker === rec.ticker)) continue;
950
- if (rec.name !== void 0 && !(isNameGive(o.give) && o.give.name === rec.name)) continue;
951
- targets.push(o);
952
- }
953
- if (ev.height >= V14_HEIGHT) {
954
- pendingCancels.push(() => {
955
- let n = 0;
956
- for (const o of targets) {
957
- if (ev.height >= V28_HEIGHT && o.claimTxid !== void 0 && claimHeld(o, ev.height)) continue;
958
- if (o.status === "open") {
959
- releaseGive(o);
960
- setOfferStatus(o, "cancelled");
961
- n++;
962
- }
963
- }
964
- note(ev, ev.id, "ocancel", true, `${n} cancelled (deferred past same-block fills)`);
965
- });
966
- } else {
967
- for (const o of targets) {
968
- releaseGive(o);
969
- setOfferStatus(o, "cancelled");
970
- }
971
- note(ev, ev.id, "ocancel", true, `${targets.length} cancelled`);
972
- }
973
- } else if (rec.t === "nrenew") {
974
- if (!v15) {
975
- note(ev, ev.id, "nrenew", false, "nrenew needs v1.5");
976
- continue;
977
- }
978
- const n = names.get(rec.name);
979
- const ep = epochOf(ev.height);
980
- if (n && n.pending) {
981
- note(ev, ev.id, "nrenew", false, "name reservation not yet finalized");
982
- continue;
983
- }
984
- if (!n || lapsed(n, ep)) {
985
- note(ev, ev.id, "nrenew", false, "no live lease (lapsed names are claimed, not renewed)");
986
- continue;
987
- }
988
- if (inGrace(n, ep) && who !== n.owner) {
989
- note(ev, ev.id, "nrenew", false, "grace period: only the owner may renew");
990
- continue;
991
- }
992
- if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
993
- note(ev, ev.id, "nrenew", false, "renewal fee unpaid");
994
- continue;
995
- }
996
- n.paidThroughEpoch = paidThrough(n) + NAME_TERM_EPOCHS;
997
- feesPaid += nameRegFee(rec.name, ev.height);
998
- note(ev, ev.id, "nrenew", true, `paid through epoch ${n.paidThroughEpoch}`);
999
- } else if (rec.t === "tmeta") {
1000
- if (!v15) {
1001
- note(ev, ev.id, "tmeta", false, "tmeta needs v1.5");
1002
- continue;
1003
- }
1004
- const tok = tokens.get(rec.ticker);
1005
- if (!tok) {
1006
- note(ev, ev.id, "tmeta", false, "unknown ticker");
1007
- continue;
1008
- }
1009
- if (who !== tok.meta.deployer) {
1010
- note(ev, ev.id, "tmeta", false, "issuer-only metadata");
1011
- continue;
1012
- }
1013
- tok.meta.tmeta = rec.hash;
1014
- note(ev, ev.id, "tmeta", true);
1015
- } else if (rec.t === "fclaim") {
1016
- if (ev.height < V28_HEIGHT) {
1017
- note(ev, ev.id, "fclaim", false, "fclaim needs v2.8");
1018
- continue;
1019
- }
1020
- const target = offers.get(rec.offer);
1021
- const E = ev.expiresEpoch;
1022
- const deny = (why) => {
1023
- fclaims.set(ev.id, { offer: rec.offer, proposer: who, expiresEpoch: E, height: ev.height, granted: false });
1024
- note(ev, ev.id, "fclaim", false, why);
1025
- };
1026
- if (!Number.isSafeInteger(E)) {
1027
- deny("expiresEpoch out of safe-integer range");
1028
- continue;
1029
- }
1030
- if (!target) {
1031
- deny("unknown offer");
1032
- continue;
1033
- }
1034
- if (target.status !== "open") {
1035
- deny(`offer ${target.status}`);
1036
- continue;
1037
- }
1038
- if (target.taker) {
1039
- deny("taker-bound offer needs no claim");
1040
- continue;
1041
- }
1042
- if (isTokenWant(target.want)) {
1043
- deny("claims are for CSD-priced offers");
1044
- continue;
1045
- }
1046
- if (E > effExpiry(target, ev.height)) {
1047
- deny("hold would outlive the offer expiry");
1048
- continue;
1049
- }
1050
- if (E > epochOf(ev.height) + FCLAIM_MAX_EPOCH_AHEAD) {
1051
- deny("hold too far ahead (anti-squat)");
1052
- continue;
1053
- }
1054
- if (epochOf(ev.height) > E) {
1055
- deny("expiry already in the past");
1056
- continue;
1057
- }
1058
- if (claimHeld(target, ev.height)) {
1059
- deny("offer already claimed (hold live)");
1060
- continue;
1061
- }
1062
- if (target.claimedBy === who && target.claimUntilHeight !== void 0 && ev.height < target.claimUntilHeight + claimGrace(target) + CLAIM_COOLDOWN_BLOCKS) {
1063
- deny("claim cooldown (you just held this offer)");
1064
- continue;
1065
- }
1066
- let liveN = 0;
1067
- for (const x of offers.values()) if (x.claimedBy === who && claimHeld(x, ev.height) && (ev.height < V29_HEIGHT || x.status === "open")) liveN++;
1068
- if (liveN >= MAX_ACTIVE_CLAIMS) {
1069
- deny(`max ${MAX_ACTIVE_CLAIMS} live claims per address`);
1070
- continue;
1071
- }
1072
- target.claimedBy = who;
1073
- target.claimUntilHeight = (E + 1) * EPOCH_LEN;
1074
- target.claimTxid = ev.id;
1075
- fclaims.set(ev.id, { offer: rec.offer, proposer: who, expiresEpoch: E, height: ev.height, granted: true });
1076
- note(ev, ev.id, "fclaim", true);
1077
- }
1078
- } else {
1079
- const who = ev.attester.toLowerCase();
1080
- let o = offers.get(ev.proposalId);
1081
- if (!o && ev.height >= V28_HEIGHT && ev.score === SCORE_FILL) {
1082
- const fc = fclaims.get(ev.proposalId);
1083
- if (fc && fc.granted) {
1084
- const linked = offers.get(fc.offer);
1085
- if (linked && linked.claimTxid === ev.proposalId) o = linked;
1086
- }
1087
- }
1088
- if (!o) {
1089
- if (ev.height >= V28_HEIGHT && ev.score === SCORE_FILL && fclaims.has(ev.proposalId)) {
1090
- note(ev, ev.txid, "fill", false, "fclaim not current (denied or superseded): no delivery, denied-fclaim fill");
1091
- continue;
1092
- }
1093
- const b = bids.get(ev.proposalId);
1094
- if (b && ev.score === SCORE_CANCEL) {
1095
- if (who !== b.bidder) {
1096
- note(ev, ev.txid, "bidcancel", false, "only bidder may cancel");
1097
- continue;
1098
- }
1099
- if (b.status !== "open") {
1100
- note(ev, ev.txid, "bidcancel", false, `bid ${b.status}`);
1101
- continue;
1102
- }
1103
- setBidStatus(b, "cancelled");
1104
- note(ev, ev.txid, "bidcancel", true);
1105
- }
1106
- continue;
1107
- }
1108
- if (ev.score === SCORE_CANCEL) {
1109
- if (who !== o.seller) {
1110
- note(ev, ev.txid, "cancel", false, "only seller may cancel");
1111
- continue;
1112
- }
1113
- if (o.status !== "open") {
1114
- note(ev, ev.txid, "cancel", false, `offer ${o.status}`);
1115
- continue;
1116
- }
1117
- if (o.taker !== void 0 && o.height >= V28_HEIGHT) {
1118
- note(ev, ev.txid, "cancel", false, "v2.8: taker-bound offers are firm quotes (uncancellable)");
1119
- continue;
1120
- }
1121
- if (ev.height >= V14_HEIGHT) {
1122
- pendingCancels.push(() => {
1123
- if (ev.height >= V28_HEIGHT && o.claimTxid !== void 0 && claimHeld(o, ev.height)) {
1124
- note(ev, ev.txid, "cancel", false, "v2.8: frozen (fclaim hold live)");
1125
- return;
1126
- }
1127
- if (o.status === "open") {
1128
- releaseGive(o);
1129
- setOfferStatus(o, "cancelled");
1130
- note(ev, ev.txid, "cancel", true);
1131
- } else note(ev, ev.txid, "cancel", false, "superseded by same-block fill (v1.4)");
1132
- });
1133
- } else {
1134
- releaseGive(o);
1135
- setOfferStatus(o, "cancelled");
1136
- note(ev, ev.txid, "cancel", true);
1137
- }
1138
- } else if (ev.score === SCORE_FILL && isTokenWant(o.want)) {
1139
- if (o.status !== "open") {
1140
- note(ev, ev.txid, "fill", false, `offer ${o.status}`);
1141
- continue;
1142
- }
1143
- if (o.taker && who !== o.taker) {
1144
- note(ev, ev.txid, "fill", false, "taker-bound offer");
1145
- continue;
1146
- }
1147
- if (ev.confidence !== CONF_TOKEN_FILL) {
1148
- note(ev, ev.txid, "fill", false, "token fill requires confidence marker");
1149
- continue;
1150
- }
1151
- if (!tokens.has(o.want.ticker)) {
1152
- note(ev, ev.txid, "fill", false, "want ticker does not exist");
1153
- continue;
1154
- }
1155
- const amt = BigInt(o.want.amount);
1156
- const fee = o.feeBps ? tradeFee(amt, o.feeBps) : 0n;
1157
- const buyer = bal(o.want.ticker, who);
1158
- if (buyer.available < amt + fee) {
1159
- note(ev, ev.txid, "fill", false, "insufficient want-token balance");
1160
- continue;
1161
- }
1162
- const giveName = isNameGive(o.give) ? names.get(o.give.name) : void 0;
1163
- if (isNameGive(o.give) && !giveName) {
1164
- note(ev, ev.txid, "fill", false, "name vanished (consensus violation)");
1165
- continue;
1166
- }
1167
- const giveLock = isNameGive(o.give) ? void 0 : offerLock.get(o.id);
1168
- if (!isNameGive(o.give) && giveLock === void 0) {
1169
- note(ev, ev.txid, "fill", false, "offer lock missing");
1170
- continue;
1171
- }
1172
- buyer.available -= amt + fee;
1173
- bal(o.want.ticker, o.want.payto).available += amt;
1174
- if (fee > 0n) bal(o.want.ticker, TREASURY_ADDR).available += fee;
1175
- if (isNameGive(o.give)) deliverNameToBuyer(giveName, who, ev);
1176
- else releaseGiveLock(o, who, giveLock);
1177
- setOfferStatus(o, "filled");
1178
- o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: amt.toString(), fee: fee.toString() };
1179
- markBidDone(o, who);
1180
- note(ev, ev.txid, "fill", true);
1181
- } else if (ev.score === SCORE_FILL && o.min !== void 0 && !isNameGive(o.give)) {
1182
- if (o.status !== "open") {
1183
- note(ev, ev.txid, "fill", false, `offer ${o.status}`);
1184
- continue;
1185
- }
1186
- if (o.taker && who !== o.taker) {
1187
- note(ev, ev.txid, "fill", false, "taker-bound offer");
1188
- continue;
1189
- }
1190
- const blk = openFillReject(o, ev.height, who, ev.proposalId);
1191
- if (blk) {
1192
- note(ev, ev.txid, "fill", false, blk);
1193
- continue;
1194
- }
1195
- const pt = ev.paidTo ?? {};
1196
- const want = BigInt(o.want.value);
1197
- const paidSoFar = BigInt(o.paid ?? "0");
1198
- const remaining = want - paidSoFar;
1199
- const X = ptAmt(pt[o.want.payto]);
1200
- const minV = BigInt(o.min);
1201
- const effMin = remaining < minV ? remaining : minV;
1202
- if (X < effMin) {
1203
- note(ev, ev.txid, "fill", false, "payment below offer min");
1204
- continue;
1205
- }
1206
- const x = X < remaining ? X : remaining;
1207
- const fee = o.feeBps ? tradeFee(x, o.feeBps) : 0n;
1208
- if (ptAmt(pt[TREASURY_ADDR]) < fee) {
1209
- note(ev, ev.txid, "fill", false, "protocol fee unpaid");
1210
- continue;
1211
- }
1212
- const giveTotal = BigInt(o.give.amount);
1213
- const newPaid = paidSoFar + x;
1214
- const deliveredSoFar = BigInt(o.delivered ?? "0");
1215
- const newDelivered = giveTotal * newPaid / want;
1216
- const out = newDelivered - deliveredSoFar;
1217
- if (out === 0n) {
1218
- note(ev, ev.txid, "fill", false, "fill too small to deliver any tokens");
1219
- continue;
1220
- }
1221
- const lock = offerLock.get(o.id);
1222
- if (lock === void 0) {
1223
- note(ev, ev.txid, "fill", false, "offer lock missing");
1224
- continue;
1225
- }
1226
- bal(o.give.ticker, o.seller).locked -= out;
1227
- bal(o.give.ticker, who).available += out;
1228
- offerLock.set(o.id, lock - out);
1229
- o.paid = newPaid.toString();
1230
- o.delivered = newDelivered.toString();
1231
- const entry = { buyer: who, txid: ev.txid, height: ev.height, paid: x.toString(), fee: fee.toString(), got: out.toString() };
1232
- (o.fills ??= []).push(entry);
1233
- feesPaid += fee;
1234
- if (newPaid === want) {
1235
- setOfferStatus(o, "filled");
1236
- o.fill = entry;
1237
- offerLock.delete(o.id);
1238
- markBidDone(o, who);
1239
- }
1240
- note(ev, ev.txid, "fill", true, `partial ${x}/${want}`);
1241
- } else if (ev.score === SCORE_FILL) {
1242
- if (o.status !== "open") {
1243
- note(ev, ev.txid, "fill", false, `offer ${o.status}`);
1244
- continue;
1245
- }
1246
- if (o.taker && who !== o.taker) {
1247
- note(ev, ev.txid, "fill", false, "taker-bound offer");
1248
- continue;
1249
- }
1250
- const blk = openFillReject(o, ev.height, who, ev.proposalId);
1251
- if (blk) {
1252
- note(ev, ev.txid, "fill", false, blk);
1253
- continue;
1254
- }
1255
- const pt = ev.paidTo ?? {};
1256
- const want = BigInt(o.want.value);
1257
- const fee = o.feeBps ? tradeFee(want, o.feeBps) : 0n;
1258
- const restingLiquidity = o.taker !== void 0 && o.bid !== void 0 || o.height >= V17_HEIGHT && o.taker === void 0;
1259
- const rebate = o.height >= V16_HEIGHT && restingLiquidity ? makerRebate(want) : 0n;
1260
- const need = /* @__PURE__ */ new Map();
1261
- const addNeed = (a, v) => need.set(a, (need.get(a) ?? 0n) + v);
1262
- addNeed(o.want.payto, want);
1263
- addNeed(TREASURY_ADDR, fee);
1264
- if (rebate > 0n) addNeed(o.seller, rebate);
1265
- let unpaid;
1266
- for (const [addr, amt] of need) if (ptAmt(pt[addr]) < amt) {
1267
- unpaid = addr === TREASURY_ADDR ? "protocol fee unpaid" : rebate > 0n && addr === o.seller ? "maker rebate unpaid (v1.6)" : "payment below want.value";
1426
+ switch (rec.t) {
1427
+ case "deploy":
1428
+ applyDeploy(c, ev, rec, who, feeToTreasury);
1429
+ break;
1430
+ case "mint":
1431
+ applyMint(c, ev, rec, who);
1432
+ break;
1433
+ case "transfer":
1434
+ applyTransfer(c, ev, rec, who);
1435
+ break;
1436
+ case "tmeta":
1437
+ applyTmeta(c, ev, rec, who);
1438
+ break;
1439
+ case "ncommit":
1440
+ applyNcommit(c, ev, rec);
1441
+ break;
1442
+ case "name":
1443
+ applyName(c, ev, rec, who, feeToTreasury);
1444
+ break;
1445
+ case "nfinalize":
1446
+ applyNfinalize(c, ev, rec, who, feeToTreasury);
1447
+ break;
1448
+ case "nxfer":
1449
+ applyNxfer(c, ev, rec, who);
1450
+ break;
1451
+ case "nset":
1452
+ applyNset(c, ev, rec, who);
1453
+ break;
1454
+ case "nprofile":
1455
+ applyNprofile(c, ev, rec, who);
1456
+ break;
1457
+ case "nrenew":
1458
+ applyNrenew(c, ev, rec, who, feeToTreasury);
1459
+ break;
1460
+ case "offer":
1461
+ applyOffer(c, ev, rec, who);
1462
+ break;
1463
+ case "bid":
1464
+ applyBid(c, ev, rec, who);
1465
+ break;
1466
+ case "ocancel":
1467
+ applyOcancel(c, ev, rec, who);
1468
+ break;
1469
+ case "fclaim":
1470
+ applyFclaim(c, ev, rec, who);
1268
1471
  break;
1269
- }
1270
- if (unpaid) {
1271
- note(ev, ev.txid, "fill", false, unpaid);
1272
- continue;
1273
- }
1274
- const paid = ptAmt(pt[o.want.payto]);
1275
- if (isNameGive(o.give)) {
1276
- const n = names.get(o.give.name);
1277
- if (!n) {
1278
- note(ev, ev.txid, "fill", false, "name vanished (consensus violation)");
1279
- continue;
1280
- }
1281
- deliverNameToBuyer(n, who, ev);
1282
- } else {
1283
- const amt = offerLock.get(o.id);
1284
- if (amt === void 0) {
1285
- note(ev, ev.txid, "fill", false, "offer lock missing");
1286
- continue;
1287
- }
1288
- releaseGiveLock(o, who, amt);
1289
- }
1290
- feesPaid += fee;
1291
- setOfferStatus(o, "filled");
1292
- o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: paid.toString(), fee: fee.toString() };
1293
- markBidDone(o, who);
1294
- note(ev, ev.txid, "fill", true);
1295
- } else if (ev.height >= V17_HEIGHT && ev.score === SCORE_CLAIM) {
1296
- if (ev.height >= V28_HEIGHT) {
1297
- note(ev, ev.txid, "claim", false, "v2.8: claims are fclaim proposals now");
1298
- continue;
1299
- }
1300
- if (o.status !== "open") {
1301
- note(ev, ev.txid, "claim", false, `offer ${o.status}`);
1302
- continue;
1303
- }
1304
- if (o.taker) {
1305
- note(ev, ev.txid, "claim", false, "taker-bound offer needs no claim");
1306
- continue;
1307
- }
1308
- if (isTokenWant(o.want)) {
1309
- note(ev, ev.txid, "claim", false, "claims are for CSD-priced offers (token offers are no-op-safe)");
1310
- continue;
1311
- }
1312
- if (claimHeld(o, ev.height)) {
1313
- note(ev, ev.txid, "claim", false, "offer already claimed (hold live)");
1314
- continue;
1315
- }
1316
- if (o.claimedBy === who && o.claimUntilHeight !== void 0 && ev.height < o.claimUntilHeight + claimGrace(o) + CLAIM_COOLDOWN_BLOCKS) {
1317
- note(ev, ev.txid, "claim", false, "claim cooldown (you just held this offer)");
1318
- continue;
1319
- }
1320
- let liveN = 0;
1321
- for (const x of offers.values()) if (x.claimedBy === who && claimHeld(x, ev.height) && (ev.height < V29_HEIGHT || x.status === "open")) liveN++;
1322
- if (liveN >= MAX_ACTIVE_CLAIMS) {
1323
- note(ev, ev.txid, "claim", false, `max ${MAX_ACTIVE_CLAIMS} live claims per address`);
1324
- continue;
1325
- }
1326
- o.claimedBy = who;
1327
- o.claimUntilHeight = ev.height + claimWindowAt(ev.height);
1328
- note(ev, ev.txid, "claim", true);
1329
1472
  }
1473
+ } else {
1474
+ applyAttest(c, ev);
1330
1475
  }
1331
1476
  }
1332
1477
  applyPendingCancels();
@@ -1376,7 +1521,7 @@ function resolve(events, tipHeight) {
1376
1521
  for (const [nm, r] of [...recaptures.entries()].sort(([a], [b]) => ord(a, b))) recapturesOut[nm] = { owner: r.owner, effectiveHeight: r.effHeight, finalizeBy: r.finalizeBy };
1377
1522
  const fclaimsOut = {};
1378
1523
  for (const [txid, fc] of [...fclaims.entries()].sort(([a], [b]) => ord(a, b))) if (fc.granted) fclaimsOut[txid] = { offer: fc.offer, proposer: fc.proposer, expiresEpoch: fc.expiresEpoch, height: fc.height };
1379
- return { tipHeight, tokens: tokensOut, balances: balancesOut, names: namesOut, offers: offersOut, bids: bidsOut, recaptures: recapturesOut, fclaims: fclaimsOut, events: log, feesPaid: feesPaid.toString() };
1524
+ return { tipHeight, tokens: tokensOut, balances: balancesOut, names: namesOut, offers: offersOut, bids: bidsOut, recaptures: recapturesOut, fclaims: fclaimsOut, events: log, feesPaid: c.feesPaid.toString() };
1380
1525
  }
1381
1526
  function canonicalState(s) {
1382
1527
  const sortKeys = (v) => {
@@ -1529,8 +1674,9 @@ function finalizeWinnerCheck(nameState, me, commitHeight, tip) {
1529
1674
  if (nameState.pending !== true) return { safe: false, reason: "already registered to you \u2014 no second finalize fee is needed" };
1530
1675
  if (Number(nameState.effectiveHeight) !== Number(commitHeight))
1531
1676
  return { safe: false, reason: "your reservation was displaced (effective height changed) \u2014 a finalize now would burn the fee" };
1532
- if (tip !== void 0 && tip !== null && Number.isFinite(Number(tip))) {
1533
- const t = Number(tip);
1677
+ if (tip !== void 0 && tip !== null) {
1678
+ if (!Number.isSafeInteger(tip) || tip < 0) return { safe: false, reason: `the chain tip given (${String(tip)}) is not a block height, so the finalize window cannot be checked` };
1679
+ const t = tip;
1534
1680
  const eff = Number(nameState.effectiveHeight);
1535
1681
  const freezeEnd = eff + REG_COMMIT_MAX_BLOCKS;
1536
1682
  const closeAt = eff + REG_COMMIT_MAX_BLOCKS + REG_FINALIZE_GRACE_BLOCKS - FINALIZE_TIP_MARGIN;
@@ -1592,15 +1738,17 @@ async function verifyFillSpv(offerId, fclaimTxid, me, io, opts) {
1592
1738
  return no("could not enumerate the offer's events");
1593
1739
  }
1594
1740
  const want = /* @__PURE__ */ new Set([offerId.toLowerCase(), fclaimTxid.toLowerCase(), ...(hintIds ?? []).map((x) => String(x).toLowerCase())]);
1741
+ const unproven = (wid) => wid === offerId.toLowerCase() ? no("offer not merkle-proven (no PoW-verified offer Propose)") : wid === fclaimTxid.toLowerCase() ? no("fclaim not merkle-proven (no PoW-verified fclaim Propose)") : no(`an event on this offer could not be merkle-proven (${wid}) - refusing, the replay would miss it`);
1595
1742
  const proven = [];
1596
1743
  for (const wid of want) {
1597
1744
  let ev;
1598
1745
  try {
1599
1746
  ev = await io.provenEvent(wid);
1600
1747
  } catch {
1601
- ev = null;
1748
+ return unproven(wid);
1602
1749
  }
1603
- if (ev && (ev.kind === "propose" ? ev.id : ev.txid).toLowerCase() === wid) proven.push(ev);
1750
+ if (!ev || (ev.kind === "propose" ? ev.id : ev.txid).toLowerCase() !== wid) return unproven(wid);
1751
+ proven.push(ev);
1604
1752
  }
1605
1753
  const isProp = (e) => e.kind === "propose";
1606
1754
  const offerEv = proven.find((e) => isProp(e) && e.id.toLowerCase() === offerId.toLowerCase());
@@ -1679,7 +1827,9 @@ function provenOfferTerms(offerRec, provenHeight) {
1679
1827
  giveTicker: g.ticker !== void 0 ? String(g.ticker) : void 0,
1680
1828
  giveAmount: g.amount !== void 0 ? String(g.amount) : void 0,
1681
1829
  giveName: g.name !== void 0 ? String(g.name) : void 0,
1682
- wantType: isTokenWant(offerRec.want) ? "token" : "csd"
1830
+ wantType: isTokenWant(offerRec.want) ? "token" : "csd",
1831
+ wantTicker: isTokenWant(offerRec.want) ? String(w.ticker) : void 0,
1832
+ wantAmount: isTokenWant(offerRec.want) ? String(w.amount) : void 0
1683
1833
  };
1684
1834
  }
1685
1835
  function bindOfferTerms(servedOffer, t, opts) {
@@ -1694,7 +1844,8 @@ function bindOfferTerms(servedOffer, t, opts) {
1694
1844
  if ((om !== void 0 && om !== null) !== (t.min !== void 0)) return true;
1695
1845
  if (t.min !== void 0 && String(om) !== t.min) return true;
1696
1846
  if (opts?.wantType !== false) {
1697
- if (t.wantType === void 0 || typeof o?.want?.ticker === "string" !== (t.wantType === "token")) return true;
1847
+ if (t.wantType === void 0) return true;
1848
+ if (t.wantType === "token" ? String(o?.want?.ticker) !== t.wantTicker || String(o?.want?.amount) !== t.wantAmount : typeof o?.want?.ticker === "string") return true;
1698
1849
  }
1699
1850
  if (opts?.give !== false) {
1700
1851
  const g = o?.give;
@@ -1768,6 +1919,34 @@ function myProvenFillClosedOffer(fill, fclaim2, offerEv, me, grantHeight) {
1768
1919
  return need.every((leg) => ptAmt(fill.paidTo?.[lc(leg.to)]) >= leg.value);
1769
1920
  }
1770
1921
 
1922
+ // src/holdcount.ts
1923
+ var lastLegacyClaimEnd = V28_HEIGHT - 1 + claimWindowAt(V28_HEIGHT - 1);
1924
+ var LEGACY_HOLD_SUNSET_HEIGHT = lastLegacyClaimEnd + claimGraceOf(lastLegacyClaimEnd);
1925
+ function countOtherHoldsAtGrant(candidates, target, me, closed = /* @__PURE__ */ new Set()) {
1926
+ if (!(Number.isSafeInteger(target.height) && target.height >= LEGACY_HOLD_SUNSET_HEIGHT))
1927
+ return { ok: false, reason: `this reservation was granted at ${target.height}, before block ${LEGACY_HOLD_SUNSET_HEIGHT}, while claims made before V28 could still count against the cap; it cannot be checked here` };
1928
+ const meL = String(me).toLowerCase(), tid = String(target.id).toLowerCase(), toffer = String(target.offer).toLowerCase();
1929
+ const offers = /* @__PURE__ */ new Set();
1930
+ for (const c of candidates) {
1931
+ const cid = String(c.id).toLowerCase();
1932
+ if (cid === tid || closed.has(cid) || String(c.proposer).toLowerCase() !== meL) continue;
1933
+ if (!(c.height < target.height || c.height === target.height && c.pos < target.pos)) continue;
1934
+ if (!(fclaimHoldEnd(Number(c.expiresEpoch)) >= target.height)) continue;
1935
+ const rec = parseRecord(String(c.uri), String(c.payloadHash));
1936
+ if (!rec || rec.t !== "fclaim") continue;
1937
+ const offer2 = String(rec.offer).toLowerCase();
1938
+ if (offer2 !== toffer) offers.add(offer2);
1939
+ }
1940
+ return { ok: true, count: offers.size };
1941
+ }
1942
+
1943
+ // src/admission.ts
1944
+ function provenOfferRefusal(rec, tx) {
1945
+ if (tx.domain !== DOMAIN) return `not a ${DOMAIN} Propose (domain ${JSON.stringify(String(tx.domain))})`;
1946
+ const ee = typeof tx.expiresEpoch === "bigint" ? Number(tx.expiresEpoch) : tx.expiresEpoch;
1947
+ return offerEnvelopeRefusal(rec, String(tx.seller).toLowerCase(), tx.height, ee);
1948
+ }
1949
+
1771
1950
  // src/index.ts
1772
1951
  import {
1773
1952
  canonicalJson as canonicalJson2,
@@ -1809,12 +1988,14 @@ export {
1809
1988
  HALVING_INTERVAL,
1810
1989
  HASH_RE,
1811
1990
  INITIAL_REWARD2 as INITIAL_REWARD,
1991
+ LEGACY_HOLD_SUNSET_HEIGHT,
1812
1992
  MAX_ACTIVE_CLAIMS,
1813
1993
  MAX_AMOUNT,
1814
1994
  MAX_OFFER_EPOCHS,
1815
1995
  MAX_PENDING_REG,
1816
1996
  MAX_RECORD_BYTES,
1817
1997
  MAX_SCAN,
1998
+ MAX_TOKEN_DECIMALS,
1818
1999
  MINT_KEYS,
1819
2000
  MIN_FEE_ATTEST,
1820
2001
  MIN_FEE_PROPOSE,
@@ -1881,6 +2062,7 @@ export {
1881
2062
  claimGraceOf,
1882
2063
  claimWindowAt,
1883
2064
  claimWindowOf,
2065
+ countOtherHoldsAtGrant,
1884
2066
  deploy,
1885
2067
  epochOf,
1886
2068
  expiredClaimFee,
@@ -1920,6 +2102,7 @@ export {
1920
2102
  pickPrimaryName,
1921
2103
  previewFill,
1922
2104
  primaryRankBefore,
2105
+ provenOfferRefusal,
1923
2106
  provenOfferTerms,
1924
2107
  ptAmt,
1925
2108
  replayLiveHold,