@inversealtruism/cairnx-core 0.2.0 → 0.2.1

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