@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.cjs CHANGED
@@ -49,12 +49,14 @@ __export(index_exports, {
49
49
  HALVING_INTERVAL: () => import_csd_codec5.HALVING_INTERVAL,
50
50
  HASH_RE: () => HASH_RE,
51
51
  INITIAL_REWARD: () => import_csd_codec5.INITIAL_REWARD,
52
+ LEGACY_HOLD_SUNSET_HEIGHT: () => LEGACY_HOLD_SUNSET_HEIGHT,
52
53
  MAX_ACTIVE_CLAIMS: () => MAX_ACTIVE_CLAIMS,
53
54
  MAX_AMOUNT: () => MAX_AMOUNT,
54
55
  MAX_OFFER_EPOCHS: () => MAX_OFFER_EPOCHS,
55
56
  MAX_PENDING_REG: () => MAX_PENDING_REG,
56
57
  MAX_RECORD_BYTES: () => MAX_RECORD_BYTES,
57
58
  MAX_SCAN: () => MAX_SCAN,
59
+ MAX_TOKEN_DECIMALS: () => MAX_TOKEN_DECIMALS,
58
60
  MINT_KEYS: () => MINT_KEYS,
59
61
  MIN_FEE_ATTEST: () => import_csd_codec5.MIN_FEE_ATTEST,
60
62
  MIN_FEE_PROPOSE: () => import_csd_codec5.MIN_FEE_PROPOSE,
@@ -121,6 +123,7 @@ __export(index_exports, {
121
123
  claimGraceOf: () => claimGraceOf,
122
124
  claimWindowAt: () => claimWindowAt,
123
125
  claimWindowOf: () => claimWindowOf,
126
+ countOtherHoldsAtGrant: () => countOtherHoldsAtGrant,
124
127
  deploy: () => deploy,
125
128
  epochOf: () => import_csd_codec.epochOf,
126
129
  expiredClaimFee: () => expiredClaimFee,
@@ -160,6 +163,7 @@ __export(index_exports, {
160
163
  pickPrimaryName: () => pickPrimaryName,
161
164
  previewFill: () => previewFill,
162
165
  primaryRankBefore: () => primaryRankBefore,
166
+ provenOfferRefusal: () => provenOfferRefusal,
163
167
  provenOfferTerms: () => provenOfferTerms,
164
168
  ptAmt: () => ptAmt,
165
169
  replayLiveHold: () => replayLiveHold,
@@ -198,6 +202,7 @@ function expiredClaimFee(name, epochsPastGraceEnd, height) {
198
202
  }
199
203
  var MAX_RECORD_BYTES = import_csd_codec.MAX_URI_BYTES;
200
204
  var MAX_AMOUNT = (1n << 96n) - 1n;
205
+ var MAX_TOKEN_DECIMALS = 8;
201
206
  var SCORE_FILL = 100;
202
207
  var SCORE_CANCEL = 0;
203
208
  var SCORE_CLAIM = 50;
@@ -346,7 +351,7 @@ function parseRecord(uri, payloadHashHex) {
346
351
  if (!onlyKeys(r, DEPLOY_KEYS)) return null;
347
352
  if (!isTicker(r.ticker)) return null;
348
353
  if (r.name !== void 0 && (typeof r.name !== "string" || r.name.length > 32)) return null;
349
- if (typeof r.decimals !== "number" || !Number.isInteger(r.decimals) || r.decimals < 0 || r.decimals > 8) return null;
354
+ if (typeof r.decimals !== "number" || !Number.isInteger(r.decimals) || r.decimals < 0 || r.decimals > MAX_TOKEN_DECIMALS) return null;
350
355
  if (parseAmount(r.supply) === null) return null;
351
356
  if (r.mint !== "open" && r.mint !== "issuer") return null;
352
357
  if (r.mint === "open" && parseAmount(r.mintLimit) === null) return null;
@@ -508,29 +513,14 @@ var tokenMeta = (r) => buildRecord({ v: 1, t: "tmeta", ...r });
508
513
  var nameProfile = (r) => buildRecord({ v: 1, t: "nprofile", ...r });
509
514
  var fclaim = (r) => buildRecord({ v: 1, t: "fclaim", ...r });
510
515
 
511
- // src/resolve.ts
516
+ // src/resolve/context.ts
512
517
  function ptAmt(v) {
513
518
  return typeof v === "string" && AMOUNT_RE.test(v) ? BigInt(v) : 0n;
514
519
  }
515
- var ord = (a, b) => a < b ? -1 : a > b ? 1 : 0;
516
- function resolve(events, tipHeight) {
517
- const ordered = [...events].sort(
518
- (a, b) => a.height - b.height || Number(a.kind === "attest") - Number(b.kind === "attest") || a.pos - b.pos || ord(
519
- a.kind === "propose" ? a.id : a.txid,
520
- b.kind === "propose" ? b.id : b.txid
521
- )
522
- );
523
- const eid = (e) => e.kind === "propose" ? e.id : e.txid;
524
- const seenIds = /* @__PURE__ */ new Set();
525
- const applied = [];
526
- for (const e of ordered) {
527
- if (e.height >= V29_HEIGHT) {
528
- const k = eid(e);
529
- if (seenIds.has(k)) continue;
530
- seenIds.add(k);
531
- }
532
- applied.push(e);
533
- }
520
+ var effExpiry = (e, height) => e.height >= V22_HEIGHT ? e.expiresEpoch : height >= V21_HEIGHT ? Math.min(e.expiresEpoch, (0, import_csd_codec.epochOf)(e.height) + MAX_OFFER_EPOCHS) : e.expiresEpoch;
521
+ var claimGrace = (o) => o.claimUntilHeight !== void 0 ? claimGraceOf(o.claimUntilHeight, o.claimTxid) : 0;
522
+ var claimHeld = (o, height) => o.claimedBy !== void 0 && o.claimUntilHeight !== void 0 && height < o.claimUntilHeight + claimGrace(o);
523
+ function createContext() {
534
524
  const tokens = /* @__PURE__ */ new Map();
535
525
  const balances = /* @__PURE__ */ new Map();
536
526
  const names = /* @__PURE__ */ new Map();
@@ -559,13 +549,6 @@ function resolve(events, tipHeight) {
559
549
  };
560
550
  const fclaims = /* @__PURE__ */ new Map();
561
551
  const log = [];
562
- let feesPaid = 0n;
563
- let pendingCancels = [];
564
- let pendingBlock = -1;
565
- const applyPendingCancels = () => {
566
- for (const f of pendingCancels) f();
567
- pendingCancels = [];
568
- };
569
552
  const bal = (ticker, addr) => {
570
553
  let m = balances.get(ticker);
571
554
  if (!m) {
@@ -591,7 +574,6 @@ function resolve(events, tipHeight) {
591
574
  b.available += amt;
592
575
  }
593
576
  };
594
- const effExpiry = (e, height) => e.height >= V22_HEIGHT ? e.expiresEpoch : height >= V21_HEIGHT ? Math.min(e.expiresEpoch, (0, import_csd_codec.epochOf)(e.height) + MAX_OFFER_EPOCHS) : e.expiresEpoch;
595
577
  const sweepExpired = (height) => {
596
578
  const ep = (0, import_csd_codec.epochOf)(height);
597
579
  for (const id of [...openOffers]) {
@@ -629,10 +611,6 @@ function resolve(events, tipHeight) {
629
611
  if (height > r.finalizeBy) recaptures.delete(nm);
630
612
  }
631
613
  };
632
- const V15_EPOCH = (0, import_csd_codec.epochOf)(V15_HEIGHT);
633
- const paidThrough = (n) => n.paidThroughEpoch ?? V15_EPOCH + NAME_TERM_EPOCHS;
634
- const lapsed = (n, ep) => ep > paidThrough(n) + NAME_GRACE_EPOCHS;
635
- const inGrace = (n, ep) => ep > paidThrough(n) && !lapsed(n, ep);
636
614
  const markBidDone = (o, buyer) => {
637
615
  if (!o.bid) return;
638
616
  const b = bids.get(o.bid);
@@ -645,28 +623,10 @@ function resolve(events, tipHeight) {
645
623
  setOfferStatus(o, "cancelled");
646
624
  }
647
625
  };
648
- const earlierAnchor = (effHeight, pos, id, inc) => effHeight < inc.effHeight || effHeight === inc.effHeight && (pos < inc.pos || pos === inc.pos && id < inc.id);
649
- const claimGrace = (o) => o.claimUntilHeight !== void 0 ? claimGraceOf(o.claimUntilHeight, o.claimTxid) : 0;
650
- const claimHeld = (o, height) => o.claimedBy !== void 0 && o.claimUntilHeight !== void 0 && height < o.claimUntilHeight + claimGrace(o);
651
- const openFillReject = (o, height, who, targetId) => {
652
- if (!(height >= V13_HEIGHT && !o.taker)) return void 0;
653
- if (height < V17_HEIGHT) return "v1.3: open CSD-quoted fills disabled (offer must be taker-bound)";
654
- if (height >= V28_HEIGHT && o.claimTxid !== void 0 && targetId === o.id) return "v2.8: fill the fclaim txid, not the offer";
655
- if (!(claimHeld(o, height) && who === o.claimedBy)) return "v1.7: open offer \u2014 claim it first (no live claim by you)";
656
- return void 0;
657
- };
658
- const deliverNameToBuyer = (n, who, ev) => {
659
- n.owner = who;
660
- n.locked = false;
661
- n.addr = void 0;
662
- n.profile = void 0;
663
- if (ev.height >= V13_HEIGHT) {
664
- n.effHeight = ev.height;
665
- n.pos = ev.pos;
666
- n.id = ev.txid;
667
- n.height = ev.height;
668
- n.viaFill = true;
669
- }
626
+ const liveHoldCount = (who, height) => {
627
+ let liveN = 0;
628
+ for (const x of offers.values()) if (x.claimedBy === who && claimHeld(x, height) && (height < V29_HEIGHT || x.status === "open")) liveN++;
629
+ return liveN;
670
630
  };
671
631
  const releaseGiveLock = (o, who, amt) => {
672
632
  const t = o.give.ticker;
@@ -674,6 +634,960 @@ function resolve(events, tipHeight) {
674
634
  bal(t, who).available += amt;
675
635
  offerLock.delete(o.id);
676
636
  };
637
+ return {
638
+ tokens,
639
+ balances,
640
+ names,
641
+ commits,
642
+ recaptures,
643
+ offers,
644
+ offerLock,
645
+ bids,
646
+ openOffers,
647
+ openBids,
648
+ pendingNames,
649
+ fclaims,
650
+ log,
651
+ setOfferStatus,
652
+ setBidStatus,
653
+ putName,
654
+ bal,
655
+ note,
656
+ releaseGive,
657
+ sweepExpired,
658
+ markBidDone,
659
+ voidOpenNameOffers,
660
+ liveHoldCount,
661
+ releaseGiveLock,
662
+ feesPaid: 0n,
663
+ // v1.4 fill-before-cancel: at V14_HEIGHT+ a cancel/ocancel's EFFECT is deferred to the block
664
+ // boundary, so any same-block fill wins — a seller can no longer snipe a buyer's in-flight
665
+ // payment by front-running the fill with a cheap cancel (cancel applies first in consensus
666
+ // order: proposals before attests, and a paid-up cancel attest can out-pos the fill). A fill
667
+ // that lands = seller got paid = a completed sale; the late cancel then no-ops. Pre-v14 blocks
668
+ // never populate pendingCancels, so all historical replay stays byte-identical.
669
+ pendingCancels: []
670
+ };
671
+ }
672
+
673
+ // src/resolve/attest.ts
674
+ var openFillReject = (o, height, who, targetId) => {
675
+ if (!(height >= V13_HEIGHT && !o.taker)) return void 0;
676
+ if (height < V17_HEIGHT) return "v1.3: open CSD-quoted fills disabled (offer must be taker-bound)";
677
+ if (height >= V28_HEIGHT && o.claimTxid !== void 0 && targetId === o.id) return "v2.8: fill the fclaim txid, not the offer";
678
+ if (!(claimHeld(o, height) && who === o.claimedBy)) return "v1.7: open offer \u2014 claim it first (no live claim by you)";
679
+ return void 0;
680
+ };
681
+ var deliverNameToBuyer = (n, who, ev) => {
682
+ n.owner = who;
683
+ n.locked = false;
684
+ n.addr = void 0;
685
+ n.profile = void 0;
686
+ if (ev.height >= V13_HEIGHT) {
687
+ n.effHeight = ev.height;
688
+ n.pos = ev.pos;
689
+ n.id = ev.txid;
690
+ n.height = ev.height;
691
+ n.viaFill = true;
692
+ }
693
+ };
694
+ function applyAttest(c, ev) {
695
+ const { offers, fclaims, bids, note, setBidStatus } = c;
696
+ const who = ev.attester.toLowerCase();
697
+ let o = offers.get(ev.proposalId);
698
+ if (!o && ev.height >= V28_HEIGHT && ev.score === SCORE_FILL) {
699
+ const fc = fclaims.get(ev.proposalId);
700
+ if (fc && fc.granted) {
701
+ const linked = offers.get(fc.offer);
702
+ if (linked && linked.claimTxid === ev.proposalId) o = linked;
703
+ }
704
+ }
705
+ if (!o) {
706
+ if (ev.height >= V28_HEIGHT && ev.score === SCORE_FILL && fclaims.has(ev.proposalId)) {
707
+ note(ev, ev.txid, "fill", false, "fclaim not current (denied or superseded): no delivery, denied-fclaim fill");
708
+ return;
709
+ }
710
+ const b = bids.get(ev.proposalId);
711
+ if (b && ev.score === SCORE_CANCEL) {
712
+ if (who !== b.bidder) {
713
+ note(ev, ev.txid, "bidcancel", false, "only bidder may cancel");
714
+ return;
715
+ }
716
+ if (b.status !== "open") {
717
+ note(ev, ev.txid, "bidcancel", false, `bid ${b.status}`);
718
+ return;
719
+ }
720
+ setBidStatus(b, "cancelled");
721
+ note(ev, ev.txid, "bidcancel", true);
722
+ }
723
+ return;
724
+ }
725
+ if (ev.score === SCORE_CANCEL) applyCancel(c, ev, o, who);
726
+ else if (ev.score === SCORE_FILL && isTokenWant(o.want)) applyTokenFill(c, ev, o, who);
727
+ else if (ev.score === SCORE_FILL && o.min !== void 0 && !isNameGive(o.give)) applyPartialFill(c, ev, o, who);
728
+ else if (ev.score === SCORE_FILL) applyFill(c, ev, o, who);
729
+ else if (ev.height >= V17_HEIGHT && ev.score === SCORE_CLAIM) applyLegacyClaim(c, ev, o, who);
730
+ }
731
+ function applyCancel(c, ev, o, who) {
732
+ const { note, releaseGive, setOfferStatus } = c;
733
+ if (who !== o.seller) {
734
+ note(ev, ev.txid, "cancel", false, "only seller may cancel");
735
+ return;
736
+ }
737
+ if (o.status !== "open") {
738
+ note(ev, ev.txid, "cancel", false, `offer ${o.status}`);
739
+ return;
740
+ }
741
+ if (o.taker !== void 0 && o.height >= V28_HEIGHT) {
742
+ note(ev, ev.txid, "cancel", false, "v2.8: taker-bound offers are firm quotes (uncancellable)");
743
+ return;
744
+ }
745
+ if (ev.height >= V14_HEIGHT) {
746
+ c.pendingCancels.push(() => {
747
+ if (ev.height >= V28_HEIGHT && o.claimTxid !== void 0 && claimHeld(o, ev.height)) {
748
+ note(ev, ev.txid, "cancel", false, "v2.8: frozen (fclaim hold live)");
749
+ return;
750
+ }
751
+ if (o.status === "open") {
752
+ releaseGive(o);
753
+ setOfferStatus(o, "cancelled");
754
+ note(ev, ev.txid, "cancel", true);
755
+ } else note(ev, ev.txid, "cancel", false, "superseded by same-block fill (v1.4)");
756
+ });
757
+ } else {
758
+ releaseGive(o);
759
+ setOfferStatus(o, "cancelled");
760
+ note(ev, ev.txid, "cancel", true);
761
+ }
762
+ }
763
+ function applyTokenFill(c, ev, o, who) {
764
+ const { tokens, names, offerLock, bal, note, setOfferStatus, markBidDone, releaseGiveLock } = c;
765
+ if (o.status !== "open") {
766
+ note(ev, ev.txid, "fill", false, `offer ${o.status}`);
767
+ return;
768
+ }
769
+ if (o.taker && who !== o.taker) {
770
+ note(ev, ev.txid, "fill", false, "taker-bound offer");
771
+ return;
772
+ }
773
+ if (ev.confidence !== CONF_TOKEN_FILL) {
774
+ note(ev, ev.txid, "fill", false, "token fill requires confidence marker");
775
+ return;
776
+ }
777
+ if (!tokens.has(o.want.ticker)) {
778
+ note(ev, ev.txid, "fill", false, "want ticker does not exist");
779
+ return;
780
+ }
781
+ const amt = BigInt(o.want.amount);
782
+ const fee = o.feeBps ? tradeFee(amt, o.feeBps) : 0n;
783
+ const buyer = bal(o.want.ticker, who);
784
+ if (buyer.available < amt + fee) {
785
+ note(ev, ev.txid, "fill", false, "insufficient want-token balance");
786
+ return;
787
+ }
788
+ const giveName = isNameGive(o.give) ? names.get(o.give.name) : void 0;
789
+ if (isNameGive(o.give) && !giveName) {
790
+ note(ev, ev.txid, "fill", false, "name vanished (consensus violation)");
791
+ return;
792
+ }
793
+ const giveLock = isNameGive(o.give) ? void 0 : offerLock.get(o.id);
794
+ if (!isNameGive(o.give) && giveLock === void 0) {
795
+ note(ev, ev.txid, "fill", false, "offer lock missing");
796
+ return;
797
+ }
798
+ buyer.available -= amt + fee;
799
+ bal(o.want.ticker, o.want.payto).available += amt;
800
+ if (fee > 0n) bal(o.want.ticker, TREASURY_ADDR).available += fee;
801
+ if (isNameGive(o.give)) deliverNameToBuyer(giveName, who, ev);
802
+ else releaseGiveLock(o, who, giveLock);
803
+ setOfferStatus(o, "filled");
804
+ o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: amt.toString(), fee: fee.toString() };
805
+ markBidDone(o, who);
806
+ note(ev, ev.txid, "fill", true);
807
+ }
808
+ function applyPartialFill(c, ev, o, who) {
809
+ const { offerLock, bal, note, setOfferStatus, markBidDone } = c;
810
+ if (o.status !== "open") {
811
+ note(ev, ev.txid, "fill", false, `offer ${o.status}`);
812
+ return;
813
+ }
814
+ if (o.taker && who !== o.taker) {
815
+ note(ev, ev.txid, "fill", false, "taker-bound offer");
816
+ return;
817
+ }
818
+ const blk = openFillReject(o, ev.height, who, ev.proposalId);
819
+ if (blk) {
820
+ note(ev, ev.txid, "fill", false, blk);
821
+ return;
822
+ }
823
+ const pt = ev.paidTo ?? {};
824
+ const want = BigInt(o.want.value);
825
+ const paidSoFar = BigInt(o.paid ?? "0");
826
+ const remaining = want - paidSoFar;
827
+ const X = ptAmt(pt[o.want.payto]);
828
+ const minV = BigInt(o.min);
829
+ const effMin = remaining < minV ? remaining : minV;
830
+ if (X < effMin) {
831
+ note(ev, ev.txid, "fill", false, "payment below offer min");
832
+ return;
833
+ }
834
+ const x = X < remaining ? X : remaining;
835
+ const fee = o.feeBps ? tradeFee(x, o.feeBps) : 0n;
836
+ if (ptAmt(pt[TREASURY_ADDR]) < fee) {
837
+ note(ev, ev.txid, "fill", false, "protocol fee unpaid");
838
+ return;
839
+ }
840
+ const giveTotal = BigInt(o.give.amount);
841
+ const newPaid = paidSoFar + x;
842
+ const deliveredSoFar = BigInt(o.delivered ?? "0");
843
+ const newDelivered = giveTotal * newPaid / want;
844
+ const out = newDelivered - deliveredSoFar;
845
+ if (out === 0n) {
846
+ note(ev, ev.txid, "fill", false, "fill too small to deliver any tokens");
847
+ return;
848
+ }
849
+ const lock = offerLock.get(o.id);
850
+ if (lock === void 0) {
851
+ note(ev, ev.txid, "fill", false, "offer lock missing");
852
+ return;
853
+ }
854
+ bal(o.give.ticker, o.seller).locked -= out;
855
+ bal(o.give.ticker, who).available += out;
856
+ offerLock.set(o.id, lock - out);
857
+ o.paid = newPaid.toString();
858
+ o.delivered = newDelivered.toString();
859
+ const entry = { buyer: who, txid: ev.txid, height: ev.height, paid: x.toString(), fee: fee.toString(), got: out.toString() };
860
+ (o.fills ??= []).push(entry);
861
+ c.feesPaid += fee;
862
+ if (newPaid === want) {
863
+ setOfferStatus(o, "filled");
864
+ o.fill = entry;
865
+ offerLock.delete(o.id);
866
+ markBidDone(o, who);
867
+ }
868
+ note(ev, ev.txid, "fill", true, `partial ${x}/${want}`);
869
+ }
870
+ function applyFill(c, ev, o, who) {
871
+ const { names, offerLock, note, setOfferStatus, markBidDone, releaseGiveLock } = c;
872
+ if (o.status !== "open") {
873
+ note(ev, ev.txid, "fill", false, `offer ${o.status}`);
874
+ return;
875
+ }
876
+ if (o.taker && who !== o.taker) {
877
+ note(ev, ev.txid, "fill", false, "taker-bound offer");
878
+ return;
879
+ }
880
+ const blk = openFillReject(o, ev.height, who, ev.proposalId);
881
+ if (blk) {
882
+ note(ev, ev.txid, "fill", false, blk);
883
+ return;
884
+ }
885
+ const pt = ev.paidTo ?? {};
886
+ const want = BigInt(o.want.value);
887
+ const fee = o.feeBps ? tradeFee(want, o.feeBps) : 0n;
888
+ const restingLiquidity = o.taker !== void 0 && o.bid !== void 0 || o.height >= V17_HEIGHT && o.taker === void 0;
889
+ const rebate = o.height >= V16_HEIGHT && restingLiquidity ? makerRebate(want) : 0n;
890
+ const need = /* @__PURE__ */ new Map();
891
+ const addNeed = (a, v) => need.set(a, (need.get(a) ?? 0n) + v);
892
+ addNeed(o.want.payto, want);
893
+ addNeed(TREASURY_ADDR, fee);
894
+ if (rebate > 0n) addNeed(o.seller, rebate);
895
+ let unpaid;
896
+ for (const [addr, amt] of need) if (ptAmt(pt[addr]) < amt) {
897
+ unpaid = addr === TREASURY_ADDR ? "protocol fee unpaid" : rebate > 0n && addr === o.seller ? "maker rebate unpaid (v1.6)" : "payment below want.value";
898
+ break;
899
+ }
900
+ if (unpaid) {
901
+ note(ev, ev.txid, "fill", false, unpaid);
902
+ return;
903
+ }
904
+ const paid = ptAmt(pt[o.want.payto]);
905
+ if (isNameGive(o.give)) {
906
+ const n = names.get(o.give.name);
907
+ if (!n) {
908
+ note(ev, ev.txid, "fill", false, "name vanished (consensus violation)");
909
+ return;
910
+ }
911
+ deliverNameToBuyer(n, who, ev);
912
+ } else {
913
+ const amt = offerLock.get(o.id);
914
+ if (amt === void 0) {
915
+ note(ev, ev.txid, "fill", false, "offer lock missing");
916
+ return;
917
+ }
918
+ releaseGiveLock(o, who, amt);
919
+ }
920
+ c.feesPaid += fee;
921
+ setOfferStatus(o, "filled");
922
+ o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: paid.toString(), fee: fee.toString() };
923
+ markBidDone(o, who);
924
+ note(ev, ev.txid, "fill", true);
925
+ }
926
+ function applyLegacyClaim(c, ev, o, who) {
927
+ const { note, liveHoldCount } = c;
928
+ if (ev.height >= V28_HEIGHT) {
929
+ note(ev, ev.txid, "claim", false, "v2.8: claims are fclaim proposals now");
930
+ return;
931
+ }
932
+ if (o.status !== "open") {
933
+ note(ev, ev.txid, "claim", false, `offer ${o.status}`);
934
+ return;
935
+ }
936
+ if (o.taker) {
937
+ note(ev, ev.txid, "claim", false, "taker-bound offer needs no claim");
938
+ return;
939
+ }
940
+ if (isTokenWant(o.want)) {
941
+ note(ev, ev.txid, "claim", false, "claims are for CSD-priced offers (token offers are no-op-safe)");
942
+ return;
943
+ }
944
+ if (claimHeld(o, ev.height)) {
945
+ note(ev, ev.txid, "claim", false, "offer already claimed (hold live)");
946
+ return;
947
+ }
948
+ if (o.claimedBy === who && o.claimUntilHeight !== void 0 && ev.height < o.claimUntilHeight + claimGrace(o) + CLAIM_COOLDOWN_BLOCKS) {
949
+ note(ev, ev.txid, "claim", false, "claim cooldown (you just held this offer)");
950
+ return;
951
+ }
952
+ if (liveHoldCount(who, ev.height) >= MAX_ACTIVE_CLAIMS) {
953
+ note(ev, ev.txid, "claim", false, `max ${MAX_ACTIVE_CLAIMS} live claims per address`);
954
+ return;
955
+ }
956
+ o.claimedBy = who;
957
+ o.claimUntilHeight = ev.height + claimWindowAt(ev.height);
958
+ note(ev, ev.txid, "claim", true);
959
+ }
960
+
961
+ // src/resolve/names.ts
962
+ var V15_EPOCH = (0, import_csd_codec.epochOf)(V15_HEIGHT);
963
+ var paidThrough = (n) => n.paidThroughEpoch ?? V15_EPOCH + NAME_TERM_EPOCHS;
964
+ var lapsed = (n, ep) => ep > paidThrough(n) + NAME_GRACE_EPOCHS;
965
+ var inGrace = (n, ep) => ep > paidThrough(n) && !lapsed(n, ep);
966
+ var earlierAnchor = (effHeight, pos, id, inc) => effHeight < inc.effHeight || effHeight === inc.effHeight && (pos < inc.pos || pos === inc.pos && id < inc.id);
967
+ function applyNcommit(c, ev, rec) {
968
+ const { commits, note } = c;
969
+ const v11 = ev.height >= V11_HEIGHT;
970
+ if (!v11) {
971
+ note(ev, ev.id, "ncommit", false, "before v1.1 activation");
972
+ return;
973
+ }
974
+ const prev = commits.get(rec.commit);
975
+ if (prev === void 0 || ev.height < prev) commits.set(rec.commit, ev.height);
976
+ note(ev, ev.id, "ncommit", true);
977
+ }
978
+ function applyName(c, ev, rec, who, feeToTreasury) {
979
+ const { commits, names, recaptures, note, putName, voidOpenNameOffers } = c;
980
+ const v11 = ev.height >= V11_HEIGHT;
981
+ const v15 = ev.height >= V15_HEIGHT;
982
+ const v25 = ev.height >= V25_HEIGHT;
983
+ const v26 = ev.height >= V26_HEIGHT;
984
+ if (!v11) {
985
+ note(ev, ev.id, "name", false, "before v1.1 activation");
986
+ return;
987
+ }
988
+ const regWindow = v25 || v26 ? REG_COMMIT_MAX_BLOCKS : COMMIT_MAX_BLOCKS;
989
+ let effHeight = ev.height;
990
+ if (rec.salt !== void 0) {
991
+ const ch = nameCommit(rec.name, rec.salt, who);
992
+ const cH = commits.get(ch);
993
+ if (cH === void 0 || cH >= ev.height || ev.height - cH > regWindow) {
994
+ note(ev, ev.id, "name", false, "no valid in-window commit for this reveal");
995
+ return;
996
+ }
997
+ effHeight = cH;
998
+ }
999
+ const cur = names.get(rec.name);
1000
+ const epClaim = (0, import_csd_codec.epochOf)(ev.height);
1001
+ const curActive = cur && cur.pending && cur.finalizeBy !== void 0 && ev.height > cur.finalizeBy ? void 0 : cur;
1002
+ if (curActive && !curActive.pending && v15 && lapsed(curActive, epClaim)) {
1003
+ if (v26) {
1004
+ if (rec.salt === void 0) {
1005
+ note(ev, ev.id, "name", false, "v2.6: recapture requires a commit-reveal (salt)");
1006
+ return;
1007
+ }
1008
+ const cr = recaptures.get(rec.name);
1009
+ const crActive = cr && ev.height > cr.finalizeBy ? void 0 : cr;
1010
+ const better2 = !crActive || earlierAnchor(effHeight, ev.pos, ev.id, crActive);
1011
+ if (!better2) {
1012
+ note(ev, ev.id, "name", false, "recapture already reserved (earlier anchor wins)");
1013
+ return;
1014
+ }
1015
+ let myR = 0;
1016
+ for (const [nm, r] of recaptures) if (r.owner === who && nm !== rec.name && ev.height <= r.finalizeBy) myR++;
1017
+ if (myR >= MAX_PENDING_REG) {
1018
+ note(ev, ev.id, "name", false, "too many pending recaptures (max reached)");
1019
+ return;
1020
+ }
1021
+ 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 });
1022
+ note(ev, ev.id, "name", true, crActive ? "recapture reserved (displaced prior reservation)" : "recapture reserved (pending finalize)");
1023
+ return;
1024
+ }
1025
+ const fee = expiredClaimFee(rec.name, epClaim - (paidThrough(curActive) + NAME_GRACE_EPOCHS), ev.height);
1026
+ if (feeToTreasury < fee) {
1027
+ note(ev, ev.id, "name", false, "lapsed-name claim fee unpaid (decaying premium)");
1028
+ return;
1029
+ }
1030
+ voidOpenNameOffers(rec.name, ev.height);
1031
+ putName(rec.name, { owner: who, effHeight, pos: ev.pos, id: ev.id, height: ev.height, locked: false, viaFill: true, paidThroughEpoch: epClaim + NAME_TERM_EPOCHS });
1032
+ c.feesPaid += fee;
1033
+ note(ev, ev.id, "name", true, "lapsed lease re-claimed (premium)");
1034
+ return;
1035
+ }
1036
+ if (v25) {
1037
+ if (rec.salt === void 0) {
1038
+ note(ev, ev.id, "name", false, "v2.5: registration requires a commit-reveal (salt)");
1039
+ return;
1040
+ }
1041
+ const better2 = !curActive || !curActive.viaFill && earlierAnchor(effHeight, ev.pos, ev.id, curActive);
1042
+ if (!better2) {
1043
+ note(ev, ev.id, "name", false, curActive?.viaFill ? "name taken (purchased \u2014 not displaceable)" : "name taken (earlier anchor wins)");
1044
+ return;
1045
+ }
1046
+ let myPending = 0;
1047
+ for (const [nm, n] of names) if (n.pending && n.owner === who && nm !== rec.name && n.finalizeBy !== void 0 && ev.height <= n.finalizeBy) myPending++;
1048
+ if (myPending >= MAX_PENDING_REG) {
1049
+ note(ev, ev.id, "name", false, "too many pending reservations (max reached)");
1050
+ return;
1051
+ }
1052
+ if (curActive) {
1053
+ voidOpenNameOffers(rec.name, ev.height);
1054
+ }
1055
+ 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 });
1056
+ note(ev, ev.id, "name", true, curActive ? "reserved (displaced prior reservation)" : "reserved (pending finalize)");
1057
+ return;
1058
+ }
1059
+ if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
1060
+ note(ev, ev.id, "name", false, "name registration fee unpaid");
1061
+ return;
1062
+ }
1063
+ const cand = {
1064
+ owner: who,
1065
+ effHeight,
1066
+ pos: ev.pos,
1067
+ id: ev.id,
1068
+ height: ev.height,
1069
+ locked: false,
1070
+ ...v15 ? { paidThroughEpoch: epClaim + NAME_TERM_EPOCHS } : {}
1071
+ };
1072
+ const better = !curActive || !curActive.viaFill && earlierAnchor(effHeight, ev.pos, ev.id, curActive);
1073
+ if (!better) {
1074
+ note(ev, ev.id, "name", false, curActive?.viaFill ? "name taken (purchased \u2014 not displaceable)" : "name taken (earlier anchor wins)");
1075
+ return;
1076
+ }
1077
+ if (curActive) {
1078
+ voidOpenNameOffers(rec.name, ev.height);
1079
+ }
1080
+ putName(rec.name, cand);
1081
+ c.feesPaid += nameRegFee(rec.name, ev.height);
1082
+ note(ev, ev.id, "name", true, curActive ? "displaced prior holder" : void 0);
1083
+ }
1084
+ function applyNfinalize(c, ev, rec, who, feeToTreasury) {
1085
+ const { commits, names, recaptures, pendingNames, note, putName, voidOpenNameOffers } = c;
1086
+ const v25 = ev.height >= V25_HEIGHT;
1087
+ const v26 = ev.height >= V26_HEIGHT;
1088
+ if (!v25) {
1089
+ note(ev, ev.id, "nfinalize", false, "before v2.5 activation");
1090
+ return;
1091
+ }
1092
+ const n = names.get(rec.name);
1093
+ if (n && n.pending && n.owner === who) {
1094
+ const cH = commits.get(nameCommit(rec.name, rec.salt, who));
1095
+ if (cH === void 0 || cH !== n.effHeight) {
1096
+ note(ev, ev.id, "nfinalize", false, "salt does not match the reservation commit");
1097
+ return;
1098
+ }
1099
+ if (!(ev.height > n.effHeight + REG_COMMIT_MAX_BLOCKS)) {
1100
+ note(ev, ev.id, "nfinalize", false, "too early \u2014 displacement contest not yet frozen");
1101
+ return;
1102
+ }
1103
+ if (n.finalizeBy !== void 0 && ev.height > n.finalizeBy) {
1104
+ note(ev, ev.id, "nfinalize", false, "reservation expired");
1105
+ return;
1106
+ }
1107
+ if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
1108
+ note(ev, ev.id, "nfinalize", false, "name registration fee unpaid");
1109
+ return;
1110
+ }
1111
+ delete n.pending;
1112
+ delete n.finalizeBy;
1113
+ pendingNames.delete(rec.name);
1114
+ n.paidThroughEpoch = (0, import_csd_codec.epochOf)(ev.height) + NAME_TERM_EPOCHS;
1115
+ c.feesPaid += nameRegFee(rec.name, ev.height);
1116
+ note(ev, ev.id, "nfinalize", true);
1117
+ return;
1118
+ }
1119
+ const r = v26 ? recaptures.get(rec.name) : void 0;
1120
+ if (r && r.owner === who) {
1121
+ const cH = commits.get(nameCommit(rec.name, rec.salt, who));
1122
+ if (cH === void 0 || cH !== r.effHeight) {
1123
+ note(ev, ev.id, "nfinalize", false, "salt does not match the recapture commit");
1124
+ return;
1125
+ }
1126
+ if (!(ev.height > r.effHeight + REG_COMMIT_MAX_BLOCKS)) {
1127
+ note(ev, ev.id, "nfinalize", false, "too early \u2014 recapture contest not yet frozen");
1128
+ return;
1129
+ }
1130
+ if (ev.height > r.finalizeBy) {
1131
+ note(ev, ev.id, "nfinalize", false, "recapture reservation expired");
1132
+ return;
1133
+ }
1134
+ const cur = names.get(rec.name);
1135
+ const ep = (0, import_csd_codec.epochOf)(ev.height);
1136
+ if (!cur || cur.pending || !lapsed(cur, ep)) {
1137
+ recaptures.delete(rec.name);
1138
+ note(ev, ev.id, "nfinalize", false, "name is no longer lapsed");
1139
+ return;
1140
+ }
1141
+ const fee = expiredClaimFee(rec.name, ep - (paidThrough(cur) + NAME_GRACE_EPOCHS), ev.height);
1142
+ if (feeToTreasury < fee) {
1143
+ note(ev, ev.id, "nfinalize", false, "recapture premium unpaid (decaying)");
1144
+ return;
1145
+ }
1146
+ voidOpenNameOffers(rec.name, ev.height);
1147
+ putName(rec.name, { owner: who, effHeight: r.effHeight, pos: r.pos, id: r.id, height: r.height, locked: false, paidThroughEpoch: ep + NAME_TERM_EPOCHS });
1148
+ recaptures.delete(rec.name);
1149
+ c.feesPaid += fee;
1150
+ note(ev, ev.id, "nfinalize", true, "recapture finalized (premium)");
1151
+ return;
1152
+ }
1153
+ note(ev, ev.id, "nfinalize", false, "no matching pending reservation you own");
1154
+ }
1155
+ function applyNxfer(c, ev, rec, who) {
1156
+ const { names, note } = c;
1157
+ const v15 = ev.height >= V15_HEIGHT;
1158
+ const n = names.get(rec.name);
1159
+ if (!n || n.owner !== who) {
1160
+ note(ev, ev.id, "nxfer", false, "not the name owner");
1161
+ return;
1162
+ }
1163
+ if (n.pending) {
1164
+ note(ev, ev.id, "nxfer", false, "name reservation not yet finalized");
1165
+ return;
1166
+ }
1167
+ if (v15 && lapsed(n, (0, import_csd_codec.epochOf)(ev.height))) {
1168
+ note(ev, ev.id, "nxfer", false, "lease lapsed \u2014 claim it instead");
1169
+ return;
1170
+ }
1171
+ if (n.locked) {
1172
+ note(ev, ev.id, "nxfer", false, "name is locked by an open offer");
1173
+ return;
1174
+ }
1175
+ n.owner = rec.to.toLowerCase();
1176
+ n.addr = void 0;
1177
+ n.profile = void 0;
1178
+ note(ev, ev.id, "nxfer", true);
1179
+ }
1180
+ function applyNset(c, ev, rec, who) {
1181
+ const { names, note } = c;
1182
+ const v15 = ev.height >= V15_HEIGHT;
1183
+ const v23 = ev.height >= V23_HEIGHT;
1184
+ const n = names.get(rec.name);
1185
+ if (!n || n.owner !== who) {
1186
+ note(ev, ev.id, "nset", false, "not the name owner");
1187
+ return;
1188
+ }
1189
+ if (n.pending) {
1190
+ note(ev, ev.id, "nset", false, "name reservation not yet finalized");
1191
+ return;
1192
+ }
1193
+ if (v15 && lapsed(n, (0, import_csd_codec.epochOf)(ev.height))) {
1194
+ note(ev, ev.id, "nset", false, "lease lapsed \u2014 claim it instead");
1195
+ return;
1196
+ }
1197
+ if (v23 && rec.addr.toLowerCase() === ZERO_ADDR) n.addr = void 0;
1198
+ else n.addr = rec.addr.toLowerCase();
1199
+ note(ev, ev.id, "nset", true);
1200
+ }
1201
+ function applyNprofile(c, ev, rec, who) {
1202
+ const { names, note } = c;
1203
+ const v15 = ev.height >= V15_HEIGHT;
1204
+ const v19 = ev.height >= V19_HEIGHT;
1205
+ if (!v19) {
1206
+ note(ev, ev.id, "nprofile", false, "before v1.9 activation");
1207
+ return;
1208
+ }
1209
+ const n = names.get(rec.name);
1210
+ if (!n || n.owner !== who) {
1211
+ note(ev, ev.id, "nprofile", false, "not the name owner");
1212
+ return;
1213
+ }
1214
+ if (n.pending) {
1215
+ note(ev, ev.id, "nprofile", false, "name reservation not yet finalized");
1216
+ return;
1217
+ }
1218
+ if (v15 && lapsed(n, (0, import_csd_codec.epochOf)(ev.height))) {
1219
+ note(ev, ev.id, "nprofile", false, "lease lapsed \u2014 claim it instead");
1220
+ return;
1221
+ }
1222
+ n.profile = Object.keys(rec.p).length ? { ...rec.p } : void 0;
1223
+ note(ev, ev.id, "nprofile", true);
1224
+ }
1225
+ function applyNrenew(c, ev, rec, who, feeToTreasury) {
1226
+ const { names, note } = c;
1227
+ const v15 = ev.height >= V15_HEIGHT;
1228
+ if (!v15) {
1229
+ note(ev, ev.id, "nrenew", false, "nrenew needs v1.5");
1230
+ return;
1231
+ }
1232
+ const n = names.get(rec.name);
1233
+ const ep = (0, import_csd_codec.epochOf)(ev.height);
1234
+ if (n && n.pending) {
1235
+ note(ev, ev.id, "nrenew", false, "name reservation not yet finalized");
1236
+ return;
1237
+ }
1238
+ if (!n || lapsed(n, ep)) {
1239
+ note(ev, ev.id, "nrenew", false, "no live lease (lapsed names are claimed, not renewed)");
1240
+ return;
1241
+ }
1242
+ if (inGrace(n, ep) && who !== n.owner) {
1243
+ note(ev, ev.id, "nrenew", false, "grace period: only the owner may renew");
1244
+ return;
1245
+ }
1246
+ if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
1247
+ note(ev, ev.id, "nrenew", false, "renewal fee unpaid");
1248
+ return;
1249
+ }
1250
+ n.paidThroughEpoch = paidThrough(n) + NAME_TERM_EPOCHS;
1251
+ c.feesPaid += nameRegFee(rec.name, ev.height);
1252
+ note(ev, ev.id, "nrenew", true, `paid through epoch ${n.paidThroughEpoch}`);
1253
+ }
1254
+
1255
+ // src/resolve/market.ts
1256
+ function applyOffer(c, ev, rec, who) {
1257
+ const { tokens, names, offers, offerLock, openOffers, bids, bal, note } = c;
1258
+ const v11 = ev.height >= V11_HEIGHT;
1259
+ const v15 = ev.height >= V15_HEIGHT;
1260
+ const v16 = ev.height >= V16_HEIGHT;
1261
+ const wantIsToken = isTokenWant(rec.want);
1262
+ const refusal = offerEnvelopeRefusal(rec, who, ev.height, ev.expiresEpoch);
1263
+ if (refusal !== null) {
1264
+ note(ev, ev.id, "offer", false, refusal);
1265
+ return;
1266
+ }
1267
+ const payto = (rec.want.payto ?? who).toLowerCase();
1268
+ const give = rec.give;
1269
+ if (isNameGive(give)) {
1270
+ if (!v11) {
1271
+ note(ev, ev.id, "offer", false, "name offers need v1.1");
1272
+ return;
1273
+ }
1274
+ const n = names.get(give.name);
1275
+ if (!n || n.owner !== who) {
1276
+ note(ev, ev.id, "offer", false, "you don't own this name");
1277
+ return;
1278
+ }
1279
+ if (n.pending) {
1280
+ note(ev, ev.id, "offer", false, "name reservation not yet finalized");
1281
+ return;
1282
+ }
1283
+ if (n.locked) {
1284
+ note(ev, ev.id, "offer", false, "name already locked by another offer");
1285
+ return;
1286
+ }
1287
+ const saleEmbargo = ev.height >= V27_HEIGHT ? REG_COMMIT_MAX_BLOCKS : COMMIT_MAX_BLOCKS;
1288
+ if (ev.height >= V13_HEIGHT && !n.viaFill && ev.height - n.effHeight <= saleEmbargo) {
1289
+ note(ev, ev.id, "offer", false, "name too young to sell (must out-age the reveal window)");
1290
+ return;
1291
+ }
1292
+ if (v15 && paidThrough(n) < ev.expiresEpoch) {
1293
+ note(ev, ev.id, "offer", false, "v1.5: lease ends inside the offer window (renew first)");
1294
+ return;
1295
+ }
1296
+ n.locked = true;
1297
+ } else {
1298
+ if (!tokens.has(give.ticker)) {
1299
+ note(ev, ev.id, "offer", false, "unknown ticker");
1300
+ return;
1301
+ }
1302
+ const amt = parseAmount(give.amount);
1303
+ const s = bal(give.ticker, who);
1304
+ if (s.available < amt) {
1305
+ note(ev, ev.id, "offer", false, "insufficient available balance");
1306
+ return;
1307
+ }
1308
+ s.available -= amt;
1309
+ s.locked += amt;
1310
+ offerLock.set(ev.id, amt);
1311
+ }
1312
+ const o = {
1313
+ id: ev.id,
1314
+ seller: who,
1315
+ give,
1316
+ want: wantIsToken ? { ticker: rec.want.ticker, amount: rec.want.amount, payto } : { value: rec.want.value, payto },
1317
+ ...rec.taker ? { taker: rec.taker.toLowerCase() } : {},
1318
+ ...rec.min !== void 0 ? { min: rec.min, paid: "0", delivered: "0", fills: [] } : {},
1319
+ ...rec.bid !== void 0 ? { bid: rec.bid } : {},
1320
+ status: "open",
1321
+ expiresEpoch: ev.expiresEpoch,
1322
+ height: ev.height,
1323
+ feeBps: v11 ? v16 ? FEE_BPS_V16 : FEE_BPS : 0
1324
+ };
1325
+ offers.set(ev.id, o);
1326
+ openOffers.add(ev.id);
1327
+ const linked = rec.bid !== void 0 ? bids.get(rec.bid) : void 0;
1328
+ if (linked) linked.offers.push(ev.id);
1329
+ note(ev, ev.id, "offer", true);
1330
+ }
1331
+ function applyBid(c, ev, rec, who) {
1332
+ const { bids, openBids, note } = c;
1333
+ const v12 = ev.height >= V12_HEIGHT;
1334
+ if (!v12) {
1335
+ note(ev, ev.id, "bid", false, "bids need v1.2");
1336
+ return;
1337
+ }
1338
+ if (!Number.isSafeInteger(ev.expiresEpoch)) {
1339
+ note(ev, ev.id, "bid", false, "expiresEpoch out of safe-integer range");
1340
+ return;
1341
+ }
1342
+ if ((0, import_csd_codec.epochOf)(ev.height) > ev.expiresEpoch) {
1343
+ note(ev, ev.id, "bid", false, "already expired at anchor");
1344
+ return;
1345
+ }
1346
+ if (ev.height >= V21_HEIGHT && ev.height < V22_HEIGHT && ev.expiresEpoch - (0, import_csd_codec.epochOf)(ev.height) > MAX_OFFER_EPOCHS) {
1347
+ note(ev, ev.id, "bid", false, "v2.1: bid duration exceeds the max");
1348
+ return;
1349
+ }
1350
+ bids.set(ev.id, {
1351
+ id: ev.id,
1352
+ bidder: who,
1353
+ want: rec.want,
1354
+ give: rec.give,
1355
+ status: "open",
1356
+ expiresEpoch: ev.expiresEpoch,
1357
+ height: ev.height,
1358
+ offers: []
1359
+ });
1360
+ openBids.add(ev.id);
1361
+ note(ev, ev.id, "bid", true);
1362
+ }
1363
+ function applyOcancel(c, ev, rec, who) {
1364
+ const { offers, note, releaseGive, setOfferStatus } = c;
1365
+ const v12 = ev.height >= V12_HEIGHT;
1366
+ if (!v12) {
1367
+ note(ev, ev.id, "ocancel", false, "ocancel needs v1.2");
1368
+ return;
1369
+ }
1370
+ const targets = [];
1371
+ for (const o of offers.values()) {
1372
+ if (o.status !== "open" || o.seller !== who) continue;
1373
+ if (o.taker !== void 0 && o.height >= V28_HEIGHT) continue;
1374
+ if (rec.ticker !== void 0 && !(!isNameGive(o.give) && o.give.ticker === rec.ticker)) continue;
1375
+ if (rec.name !== void 0 && !(isNameGive(o.give) && o.give.name === rec.name)) continue;
1376
+ targets.push(o);
1377
+ }
1378
+ if (ev.height >= V14_HEIGHT) {
1379
+ c.pendingCancels.push(() => {
1380
+ let n = 0;
1381
+ for (const o of targets) {
1382
+ if (ev.height >= V28_HEIGHT && o.claimTxid !== void 0 && claimHeld(o, ev.height)) continue;
1383
+ if (o.status === "open") {
1384
+ releaseGive(o);
1385
+ setOfferStatus(o, "cancelled");
1386
+ n++;
1387
+ }
1388
+ }
1389
+ note(ev, ev.id, "ocancel", true, `${n} cancelled (deferred past same-block fills)`);
1390
+ });
1391
+ } else {
1392
+ for (const o of targets) {
1393
+ releaseGive(o);
1394
+ setOfferStatus(o, "cancelled");
1395
+ }
1396
+ note(ev, ev.id, "ocancel", true, `${targets.length} cancelled`);
1397
+ }
1398
+ }
1399
+ function applyFclaim(c, ev, rec, who) {
1400
+ const { offers, fclaims, note, liveHoldCount } = c;
1401
+ if (ev.height < V28_HEIGHT) {
1402
+ note(ev, ev.id, "fclaim", false, "fclaim needs v2.8");
1403
+ return;
1404
+ }
1405
+ const target = offers.get(rec.offer);
1406
+ const E = ev.expiresEpoch;
1407
+ const deny = (why) => {
1408
+ fclaims.set(ev.id, { offer: rec.offer, proposer: who, expiresEpoch: E, height: ev.height, granted: false });
1409
+ note(ev, ev.id, "fclaim", false, why);
1410
+ };
1411
+ if (!Number.isSafeInteger(E)) {
1412
+ deny("expiresEpoch out of safe-integer range");
1413
+ return;
1414
+ }
1415
+ if (!target) {
1416
+ deny("unknown offer");
1417
+ return;
1418
+ }
1419
+ if (target.status !== "open") {
1420
+ deny(`offer ${target.status}`);
1421
+ return;
1422
+ }
1423
+ if (target.taker) {
1424
+ deny("taker-bound offer needs no claim");
1425
+ return;
1426
+ }
1427
+ if (isTokenWant(target.want)) {
1428
+ deny("claims are for CSD-priced offers");
1429
+ return;
1430
+ }
1431
+ if (E > effExpiry(target, ev.height)) {
1432
+ deny("hold would outlive the offer expiry");
1433
+ return;
1434
+ }
1435
+ if (E > (0, import_csd_codec.epochOf)(ev.height) + FCLAIM_MAX_EPOCH_AHEAD) {
1436
+ deny("hold too far ahead (anti-squat)");
1437
+ return;
1438
+ }
1439
+ if ((0, import_csd_codec.epochOf)(ev.height) > E) {
1440
+ deny("expiry already in the past");
1441
+ return;
1442
+ }
1443
+ if (claimHeld(target, ev.height)) {
1444
+ deny("offer already claimed (hold live)");
1445
+ return;
1446
+ }
1447
+ if (target.claimedBy === who && target.claimUntilHeight !== void 0 && ev.height < target.claimUntilHeight + claimGrace(target) + CLAIM_COOLDOWN_BLOCKS) {
1448
+ deny("claim cooldown (you just held this offer)");
1449
+ return;
1450
+ }
1451
+ if (liveHoldCount(who, ev.height) >= MAX_ACTIVE_CLAIMS) {
1452
+ deny(`max ${MAX_ACTIVE_CLAIMS} live claims per address`);
1453
+ return;
1454
+ }
1455
+ target.claimedBy = who;
1456
+ target.claimUntilHeight = (E + 1) * import_csd_codec.EPOCH_LEN;
1457
+ target.claimTxid = ev.id;
1458
+ fclaims.set(ev.id, { offer: rec.offer, proposer: who, expiresEpoch: E, height: ev.height, granted: true });
1459
+ note(ev, ev.id, "fclaim", true);
1460
+ }
1461
+ function offerEnvelopeRefusal(rec, who, height, expiresEpoch) {
1462
+ const wantIsToken = isTokenWant(rec.want);
1463
+ if ((wantIsToken || rec.min !== void 0 || rec.bid !== void 0) && height < V12_HEIGHT) return "v1.2 offer shape before activation";
1464
+ 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)";
1465
+ if ((rec.want.payto ?? who).toLowerCase() === TREASURY_ADDR) return "payto cannot be the protocol treasury";
1466
+ if (!Number.isSafeInteger(expiresEpoch)) return "expiresEpoch out of safe-integer range";
1467
+ if ((0, import_csd_codec.epochOf)(height) > expiresEpoch) return "already expired at anchor";
1468
+ if (height >= V21_HEIGHT && height < V22_HEIGHT && expiresEpoch - (0, import_csd_codec.epochOf)(height) > MAX_OFFER_EPOCHS) return "v2.1: offer duration exceeds the max";
1469
+ return null;
1470
+ }
1471
+
1472
+ // src/resolve/tokens.ts
1473
+ function applyDeploy(c, ev, rec, who, feeToTreasury) {
1474
+ const { tokens, note } = c;
1475
+ const v11 = ev.height >= V11_HEIGHT;
1476
+ if (tokens.has(rec.ticker)) {
1477
+ note(ev, ev.id, "deploy", false, "ticker taken (first anchor wins)");
1478
+ return;
1479
+ }
1480
+ if (v11 && feeToTreasury < BigInt(DEPLOY_FEE)) {
1481
+ note(ev, ev.id, "deploy", false, "deploy fee unpaid");
1482
+ return;
1483
+ }
1484
+ const supply = parseAmount(rec.supply);
1485
+ const mintLimit = rec.mint === "open" ? parseAmount(rec.mintLimit) : null;
1486
+ tokens.set(rec.ticker, {
1487
+ minted: 0n,
1488
+ supply,
1489
+ mintLimit,
1490
+ 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 }
1491
+ });
1492
+ if (v11) c.feesPaid += BigInt(DEPLOY_FEE);
1493
+ note(ev, ev.id, "deploy", true);
1494
+ }
1495
+ function applyMint(c, ev, rec, who) {
1496
+ const { tokens, bal, note } = c;
1497
+ const tok = tokens.get(rec.ticker);
1498
+ if (!tok) {
1499
+ note(ev, ev.id, "mint", false, "unknown ticker");
1500
+ return;
1501
+ }
1502
+ const remaining = tok.supply - tok.minted;
1503
+ if (remaining <= 0n) {
1504
+ note(ev, ev.id, "mint", false, "supply exhausted");
1505
+ return;
1506
+ }
1507
+ let credit;
1508
+ if (tok.meta.mint === "issuer") {
1509
+ if (who !== tok.meta.deployer) {
1510
+ note(ev, ev.id, "mint", false, "issuer-only mint");
1511
+ return;
1512
+ }
1513
+ const req = rec.amount !== void 0 ? parseAmount(rec.amount) : null;
1514
+ if (req === null) {
1515
+ note(ev, ev.id, "mint", false, "issuer mint requires amount");
1516
+ return;
1517
+ }
1518
+ credit = req < remaining ? req : remaining;
1519
+ } else {
1520
+ const req = rec.amount !== void 0 ? parseAmount(rec.amount) : tok.mintLimit;
1521
+ const capped = req < tok.mintLimit ? req : tok.mintLimit;
1522
+ credit = capped < remaining ? capped : remaining;
1523
+ }
1524
+ tok.minted += credit;
1525
+ bal(rec.ticker, who).available += credit;
1526
+ note(ev, ev.id, "mint", true, credit.toString());
1527
+ }
1528
+ function applyTransfer(c, ev, rec, who) {
1529
+ const { tokens, bal, note } = c;
1530
+ if (!tokens.has(rec.ticker)) {
1531
+ note(ev, ev.id, "transfer", false, "unknown ticker");
1532
+ return;
1533
+ }
1534
+ const amt = parseAmount(rec.amount);
1535
+ const from = bal(rec.ticker, who);
1536
+ if (from.available < amt) {
1537
+ note(ev, ev.id, "transfer", false, "insufficient available balance");
1538
+ return;
1539
+ }
1540
+ from.available -= amt;
1541
+ bal(rec.ticker, rec.to.toLowerCase()).available += amt;
1542
+ note(ev, ev.id, "transfer", true);
1543
+ }
1544
+ function applyTmeta(c, ev, rec, who) {
1545
+ const { tokens, note } = c;
1546
+ const v15 = ev.height >= V15_HEIGHT;
1547
+ if (!v15) {
1548
+ note(ev, ev.id, "tmeta", false, "tmeta needs v1.5");
1549
+ return;
1550
+ }
1551
+ const tok = tokens.get(rec.ticker);
1552
+ if (!tok) {
1553
+ note(ev, ev.id, "tmeta", false, "unknown ticker");
1554
+ return;
1555
+ }
1556
+ if (who !== tok.meta.deployer) {
1557
+ note(ev, ev.id, "tmeta", false, "issuer-only metadata");
1558
+ return;
1559
+ }
1560
+ tok.meta.tmeta = rec.hash;
1561
+ note(ev, ev.id, "tmeta", true);
1562
+ }
1563
+
1564
+ // src/resolve.ts
1565
+ var ord = (a, b) => a < b ? -1 : a > b ? 1 : 0;
1566
+ function resolve(events, tipHeight) {
1567
+ const ordered = [...events].sort(
1568
+ (a, b) => a.height - b.height || Number(a.kind === "attest") - Number(b.kind === "attest") || a.pos - b.pos || ord(
1569
+ a.kind === "propose" ? a.id : a.txid,
1570
+ b.kind === "propose" ? b.id : b.txid
1571
+ )
1572
+ );
1573
+ const eid = (e) => e.kind === "propose" ? e.id : e.txid;
1574
+ const seenIds = /* @__PURE__ */ new Set();
1575
+ const applied = [];
1576
+ for (const e of ordered) {
1577
+ if (e.height >= V29_HEIGHT) {
1578
+ const k = eid(e);
1579
+ if (seenIds.has(k)) continue;
1580
+ seenIds.add(k);
1581
+ }
1582
+ applied.push(e);
1583
+ }
1584
+ const c = createContext();
1585
+ const { tokens, balances, names, recaptures, offers, bids, fclaims, log, note, sweepExpired } = c;
1586
+ let pendingBlock = -1;
1587
+ const applyPendingCancels = () => {
1588
+ for (const f of c.pendingCancels) f();
1589
+ c.pendingCancels = [];
1590
+ };
677
1591
  for (const ev of applied) {
678
1592
  if (ev.height < ACTIVATION_HEIGHT) continue;
679
1593
  if (ev.height !== pendingBlock) {
@@ -681,14 +1595,6 @@ function resolve(events, tipHeight) {
681
1595
  pendingBlock = ev.height;
682
1596
  }
683
1597
  sweepExpired(ev.height);
684
- const v11 = ev.height >= V11_HEIGHT;
685
- const v12 = ev.height >= V12_HEIGHT;
686
- const v15 = ev.height >= V15_HEIGHT;
687
- const v16 = ev.height >= V16_HEIGHT;
688
- const v19 = ev.height >= V19_HEIGHT;
689
- const v23 = ev.height >= V23_HEIGHT;
690
- const v25 = ev.height >= V25_HEIGHT;
691
- const v26 = ev.height >= V26_HEIGHT;
692
1598
  const feeToTreasury = ev.kind === "propose" ? ptAmt((ev.paidTo ?? {})[TREASURY_ADDR]) : 0n;
693
1599
  if (ev.kind === "propose") {
694
1600
  const rec = parseRecord(ev.uri, ev.payloadHash);
@@ -697,812 +1603,55 @@ function resolve(events, tipHeight) {
697
1603
  continue;
698
1604
  }
699
1605
  const who = ev.proposer.toLowerCase();
700
- if (rec.t === "deploy") {
701
- if (tokens.has(rec.ticker)) {
702
- note(ev, ev.id, "deploy", false, "ticker taken (first anchor wins)");
703
- continue;
704
- }
705
- if (v11 && feeToTreasury < BigInt(DEPLOY_FEE)) {
706
- note(ev, ev.id, "deploy", false, "deploy fee unpaid");
707
- continue;
708
- }
709
- const supply = parseAmount(rec.supply);
710
- const mintLimit = rec.mint === "open" ? parseAmount(rec.mintLimit) : null;
711
- tokens.set(rec.ticker, {
712
- minted: 0n,
713
- supply,
714
- mintLimit,
715
- 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 }
716
- });
717
- if (v11) feesPaid += BigInt(DEPLOY_FEE);
718
- note(ev, ev.id, "deploy", true);
719
- } else if (rec.t === "mint") {
720
- const tok = tokens.get(rec.ticker);
721
- if (!tok) {
722
- note(ev, ev.id, "mint", false, "unknown ticker");
723
- continue;
724
- }
725
- const remaining = tok.supply - tok.minted;
726
- if (remaining <= 0n) {
727
- note(ev, ev.id, "mint", false, "supply exhausted");
728
- continue;
729
- }
730
- let credit;
731
- if (tok.meta.mint === "issuer") {
732
- if (who !== tok.meta.deployer) {
733
- note(ev, ev.id, "mint", false, "issuer-only mint");
734
- continue;
735
- }
736
- const req = rec.amount !== void 0 ? parseAmount(rec.amount) : null;
737
- if (req === null) {
738
- note(ev, ev.id, "mint", false, "issuer mint requires amount");
739
- continue;
740
- }
741
- credit = req < remaining ? req : remaining;
742
- } else {
743
- const req = rec.amount !== void 0 ? parseAmount(rec.amount) : tok.mintLimit;
744
- const capped = req < tok.mintLimit ? req : tok.mintLimit;
745
- credit = capped < remaining ? capped : remaining;
746
- }
747
- tok.minted += credit;
748
- bal(rec.ticker, who).available += credit;
749
- note(ev, ev.id, "mint", true, credit.toString());
750
- } else if (rec.t === "transfer") {
751
- if (!tokens.has(rec.ticker)) {
752
- note(ev, ev.id, "transfer", false, "unknown ticker");
753
- continue;
754
- }
755
- const amt = parseAmount(rec.amount);
756
- const from = bal(rec.ticker, who);
757
- if (from.available < amt) {
758
- note(ev, ev.id, "transfer", false, "insufficient available balance");
759
- continue;
760
- }
761
- from.available -= amt;
762
- bal(rec.ticker, rec.to.toLowerCase()).available += amt;
763
- note(ev, ev.id, "transfer", true);
764
- } else if (rec.t === "ncommit") {
765
- if (!v11) {
766
- note(ev, ev.id, "ncommit", false, "before v1.1 activation");
767
- continue;
768
- }
769
- const prev = commits.get(rec.commit);
770
- if (prev === void 0 || ev.height < prev) commits.set(rec.commit, ev.height);
771
- note(ev, ev.id, "ncommit", true);
772
- } else if (rec.t === "name") {
773
- if (!v11) {
774
- note(ev, ev.id, "name", false, "before v1.1 activation");
775
- continue;
776
- }
777
- const regWindow = v25 || v26 ? REG_COMMIT_MAX_BLOCKS : COMMIT_MAX_BLOCKS;
778
- let effHeight = ev.height;
779
- if (rec.salt !== void 0) {
780
- const ch = nameCommit(rec.name, rec.salt, who);
781
- const cH = commits.get(ch);
782
- if (cH === void 0 || cH >= ev.height || ev.height - cH > regWindow) {
783
- note(ev, ev.id, "name", false, "no valid in-window commit for this reveal");
784
- continue;
785
- }
786
- effHeight = cH;
787
- }
788
- const cur = names.get(rec.name);
789
- const epClaim = (0, import_csd_codec.epochOf)(ev.height);
790
- const curActive = cur && cur.pending && cur.finalizeBy !== void 0 && ev.height > cur.finalizeBy ? void 0 : cur;
791
- if (curActive && !curActive.pending && v15 && lapsed(curActive, epClaim)) {
792
- if (v26) {
793
- if (rec.salt === void 0) {
794
- note(ev, ev.id, "name", false, "v2.6: recapture requires a commit-reveal (salt)");
795
- continue;
796
- }
797
- const cr = recaptures.get(rec.name);
798
- const crActive = cr && ev.height > cr.finalizeBy ? void 0 : cr;
799
- const better2 = !crActive || earlierAnchor(effHeight, ev.pos, ev.id, crActive);
800
- if (!better2) {
801
- note(ev, ev.id, "name", false, "recapture already reserved (earlier anchor wins)");
802
- continue;
803
- }
804
- let myR = 0;
805
- for (const [nm, r] of recaptures) if (r.owner === who && nm !== rec.name && ev.height <= r.finalizeBy) myR++;
806
- if (myR >= MAX_PENDING_REG) {
807
- note(ev, ev.id, "name", false, "too many pending recaptures (max reached)");
808
- continue;
809
- }
810
- 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 });
811
- note(ev, ev.id, "name", true, crActive ? "recapture reserved (displaced prior reservation)" : "recapture reserved (pending finalize)");
812
- continue;
813
- }
814
- const fee = expiredClaimFee(rec.name, epClaim - (paidThrough(curActive) + NAME_GRACE_EPOCHS), ev.height);
815
- if (feeToTreasury < fee) {
816
- note(ev, ev.id, "name", false, "lapsed-name claim fee unpaid (decaying premium)");
817
- continue;
818
- }
819
- voidOpenNameOffers(rec.name, ev.height);
820
- putName(rec.name, { owner: who, effHeight, pos: ev.pos, id: ev.id, height: ev.height, locked: false, viaFill: true, paidThroughEpoch: epClaim + NAME_TERM_EPOCHS });
821
- feesPaid += fee;
822
- note(ev, ev.id, "name", true, "lapsed lease re-claimed (premium)");
823
- continue;
824
- }
825
- if (v25) {
826
- if (rec.salt === void 0) {
827
- note(ev, ev.id, "name", false, "v2.5: registration requires a commit-reveal (salt)");
828
- continue;
829
- }
830
- const better2 = !curActive || !curActive.viaFill && earlierAnchor(effHeight, ev.pos, ev.id, curActive);
831
- if (!better2) {
832
- note(ev, ev.id, "name", false, curActive?.viaFill ? "name taken (purchased \u2014 not displaceable)" : "name taken (earlier anchor wins)");
833
- continue;
834
- }
835
- let myPending = 0;
836
- for (const [nm, n] of names) if (n.pending && n.owner === who && nm !== rec.name && n.finalizeBy !== void 0 && ev.height <= n.finalizeBy) myPending++;
837
- if (myPending >= MAX_PENDING_REG) {
838
- note(ev, ev.id, "name", false, "too many pending reservations (max reached)");
839
- continue;
840
- }
841
- if (curActive) {
842
- voidOpenNameOffers(rec.name, ev.height);
843
- }
844
- 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 });
845
- note(ev, ev.id, "name", true, curActive ? "reserved (displaced prior reservation)" : "reserved (pending finalize)");
846
- continue;
847
- }
848
- if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
849
- note(ev, ev.id, "name", false, "name registration fee unpaid");
850
- continue;
851
- }
852
- const cand = {
853
- owner: who,
854
- effHeight,
855
- pos: ev.pos,
856
- id: ev.id,
857
- height: ev.height,
858
- locked: false,
859
- ...v15 ? { paidThroughEpoch: epClaim + NAME_TERM_EPOCHS } : {}
860
- };
861
- const better = !curActive || !curActive.viaFill && earlierAnchor(effHeight, ev.pos, ev.id, curActive);
862
- if (!better) {
863
- note(ev, ev.id, "name", false, curActive?.viaFill ? "name taken (purchased \u2014 not displaceable)" : "name taken (earlier anchor wins)");
864
- continue;
865
- }
866
- if (curActive) {
867
- voidOpenNameOffers(rec.name, ev.height);
868
- }
869
- putName(rec.name, cand);
870
- feesPaid += nameRegFee(rec.name, ev.height);
871
- note(ev, ev.id, "name", true, curActive ? "displaced prior holder" : void 0);
872
- } else if (rec.t === "nfinalize") {
873
- if (!v25) {
874
- note(ev, ev.id, "nfinalize", false, "before v2.5 activation");
875
- continue;
876
- }
877
- const n = names.get(rec.name);
878
- if (n && n.pending && n.owner === who) {
879
- const cH = commits.get(nameCommit(rec.name, rec.salt, who));
880
- if (cH === void 0 || cH !== n.effHeight) {
881
- note(ev, ev.id, "nfinalize", false, "salt does not match the reservation commit");
882
- continue;
883
- }
884
- if (!(ev.height > n.effHeight + REG_COMMIT_MAX_BLOCKS)) {
885
- note(ev, ev.id, "nfinalize", false, "too early \u2014 displacement contest not yet frozen");
886
- continue;
887
- }
888
- if (n.finalizeBy !== void 0 && ev.height > n.finalizeBy) {
889
- note(ev, ev.id, "nfinalize", false, "reservation expired");
890
- continue;
891
- }
892
- if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
893
- note(ev, ev.id, "nfinalize", false, "name registration fee unpaid");
894
- continue;
895
- }
896
- delete n.pending;
897
- delete n.finalizeBy;
898
- pendingNames.delete(rec.name);
899
- n.paidThroughEpoch = (0, import_csd_codec.epochOf)(ev.height) + NAME_TERM_EPOCHS;
900
- feesPaid += nameRegFee(rec.name, ev.height);
901
- note(ev, ev.id, "nfinalize", true);
902
- continue;
903
- }
904
- const r = v26 ? recaptures.get(rec.name) : void 0;
905
- if (r && r.owner === who) {
906
- const cH = commits.get(nameCommit(rec.name, rec.salt, who));
907
- if (cH === void 0 || cH !== r.effHeight) {
908
- note(ev, ev.id, "nfinalize", false, "salt does not match the recapture commit");
909
- continue;
910
- }
911
- if (!(ev.height > r.effHeight + REG_COMMIT_MAX_BLOCKS)) {
912
- note(ev, ev.id, "nfinalize", false, "too early \u2014 recapture contest not yet frozen");
913
- continue;
914
- }
915
- if (ev.height > r.finalizeBy) {
916
- note(ev, ev.id, "nfinalize", false, "recapture reservation expired");
917
- continue;
918
- }
919
- const cur = names.get(rec.name);
920
- const ep = (0, import_csd_codec.epochOf)(ev.height);
921
- if (!cur || cur.pending || !lapsed(cur, ep)) {
922
- recaptures.delete(rec.name);
923
- note(ev, ev.id, "nfinalize", false, "name is no longer lapsed");
924
- continue;
925
- }
926
- const fee = expiredClaimFee(rec.name, ep - (paidThrough(cur) + NAME_GRACE_EPOCHS), ev.height);
927
- if (feeToTreasury < fee) {
928
- note(ev, ev.id, "nfinalize", false, "recapture premium unpaid (decaying)");
929
- continue;
930
- }
931
- voidOpenNameOffers(rec.name, ev.height);
932
- putName(rec.name, { owner: who, effHeight: r.effHeight, pos: r.pos, id: r.id, height: r.height, locked: false, paidThroughEpoch: ep + NAME_TERM_EPOCHS });
933
- recaptures.delete(rec.name);
934
- feesPaid += fee;
935
- note(ev, ev.id, "nfinalize", true, "recapture finalized (premium)");
936
- continue;
937
- }
938
- note(ev, ev.id, "nfinalize", false, "no matching pending reservation you own");
939
- } else if (rec.t === "nxfer") {
940
- const n = names.get(rec.name);
941
- if (!n || n.owner !== who) {
942
- note(ev, ev.id, "nxfer", false, "not the name owner");
943
- continue;
944
- }
945
- if (n.pending) {
946
- note(ev, ev.id, "nxfer", false, "name reservation not yet finalized");
947
- continue;
948
- }
949
- if (v15 && lapsed(n, (0, import_csd_codec.epochOf)(ev.height))) {
950
- note(ev, ev.id, "nxfer", false, "lease lapsed \u2014 claim it instead");
951
- continue;
952
- }
953
- if (n.locked) {
954
- note(ev, ev.id, "nxfer", false, "name is locked by an open offer");
955
- continue;
956
- }
957
- n.owner = rec.to.toLowerCase();
958
- n.addr = void 0;
959
- n.profile = void 0;
960
- note(ev, ev.id, "nxfer", true);
961
- } else if (rec.t === "nset") {
962
- const n = names.get(rec.name);
963
- if (!n || n.owner !== who) {
964
- note(ev, ev.id, "nset", false, "not the name owner");
965
- continue;
966
- }
967
- if (n.pending) {
968
- note(ev, ev.id, "nset", false, "name reservation not yet finalized");
969
- continue;
970
- }
971
- if (v15 && lapsed(n, (0, import_csd_codec.epochOf)(ev.height))) {
972
- note(ev, ev.id, "nset", false, "lease lapsed \u2014 claim it instead");
973
- continue;
974
- }
975
- if (v23 && rec.addr.toLowerCase() === ZERO_ADDR) n.addr = void 0;
976
- else n.addr = rec.addr.toLowerCase();
977
- note(ev, ev.id, "nset", true);
978
- } else if (rec.t === "nprofile") {
979
- if (!v19) {
980
- note(ev, ev.id, "nprofile", false, "before v1.9 activation");
981
- continue;
982
- }
983
- const n = names.get(rec.name);
984
- if (!n || n.owner !== who) {
985
- note(ev, ev.id, "nprofile", false, "not the name owner");
986
- continue;
987
- }
988
- if (n.pending) {
989
- note(ev, ev.id, "nprofile", false, "name reservation not yet finalized");
990
- continue;
991
- }
992
- if (v15 && lapsed(n, (0, import_csd_codec.epochOf)(ev.height))) {
993
- note(ev, ev.id, "nprofile", false, "lease lapsed \u2014 claim it instead");
994
- continue;
995
- }
996
- n.profile = Object.keys(rec.p).length ? { ...rec.p } : void 0;
997
- note(ev, ev.id, "nprofile", true);
998
- } else if (rec.t === "offer") {
999
- const wantIsToken = isTokenWant(rec.want);
1000
- if ((wantIsToken || rec.min !== void 0 || rec.bid !== void 0) && !v12) {
1001
- note(ev, ev.id, "offer", false, "v1.2 offer shape before activation");
1002
- continue;
1003
- }
1004
- if (ev.height >= V13_HEIGHT && ev.height < V17_HEIGHT && !wantIsToken && rec.taker === void 0) {
1005
- note(ev, ev.id, "offer", false, "v1.3: CSD-priced offers must be taker-bound (use bid/RFQ)");
1006
- continue;
1007
- }
1008
- const payto = (rec.want.payto ?? who).toLowerCase();
1009
- if (payto === TREASURY_ADDR) {
1010
- note(ev, ev.id, "offer", false, "payto cannot be the protocol treasury");
1011
- continue;
1012
- }
1013
- if (!Number.isSafeInteger(ev.expiresEpoch)) {
1014
- note(ev, ev.id, "offer", false, "expiresEpoch out of safe-integer range");
1015
- continue;
1016
- }
1017
- if ((0, import_csd_codec.epochOf)(ev.height) > ev.expiresEpoch) {
1018
- note(ev, ev.id, "offer", false, "already expired at anchor");
1019
- continue;
1020
- }
1021
- if (ev.height >= V21_HEIGHT && ev.height < V22_HEIGHT && ev.expiresEpoch - (0, import_csd_codec.epochOf)(ev.height) > MAX_OFFER_EPOCHS) {
1022
- note(ev, ev.id, "offer", false, "v2.1: offer duration exceeds the max");
1023
- continue;
1024
- }
1025
- const give = rec.give;
1026
- if (isNameGive(give)) {
1027
- if (!v11) {
1028
- note(ev, ev.id, "offer", false, "name offers need v1.1");
1029
- continue;
1030
- }
1031
- const n = names.get(give.name);
1032
- if (!n || n.owner !== who) {
1033
- note(ev, ev.id, "offer", false, "you don't own this name");
1034
- continue;
1035
- }
1036
- if (n.pending) {
1037
- note(ev, ev.id, "offer", false, "name reservation not yet finalized");
1038
- continue;
1039
- }
1040
- if (n.locked) {
1041
- note(ev, ev.id, "offer", false, "name already locked by another offer");
1042
- continue;
1043
- }
1044
- const saleEmbargo = ev.height >= V27_HEIGHT ? REG_COMMIT_MAX_BLOCKS : COMMIT_MAX_BLOCKS;
1045
- if (ev.height >= V13_HEIGHT && !n.viaFill && ev.height - n.effHeight <= saleEmbargo) {
1046
- note(ev, ev.id, "offer", false, "name too young to sell (must out-age the reveal window)");
1047
- continue;
1048
- }
1049
- if (v15 && paidThrough(n) < ev.expiresEpoch) {
1050
- note(ev, ev.id, "offer", false, "v1.5: lease ends inside the offer window (renew first)");
1051
- continue;
1052
- }
1053
- n.locked = true;
1054
- } else {
1055
- if (!tokens.has(give.ticker)) {
1056
- note(ev, ev.id, "offer", false, "unknown ticker");
1057
- continue;
1058
- }
1059
- const amt = parseAmount(give.amount);
1060
- const s = bal(give.ticker, who);
1061
- if (s.available < amt) {
1062
- note(ev, ev.id, "offer", false, "insufficient available balance");
1063
- continue;
1064
- }
1065
- s.available -= amt;
1066
- s.locked += amt;
1067
- offerLock.set(ev.id, amt);
1068
- }
1069
- const o = {
1070
- id: ev.id,
1071
- seller: who,
1072
- give,
1073
- want: wantIsToken ? { ticker: rec.want.ticker, amount: rec.want.amount, payto } : { value: rec.want.value, payto },
1074
- ...rec.taker ? { taker: rec.taker.toLowerCase() } : {},
1075
- ...rec.min !== void 0 ? { min: rec.min, paid: "0", delivered: "0", fills: [] } : {},
1076
- ...rec.bid !== void 0 ? { bid: rec.bid } : {},
1077
- status: "open",
1078
- expiresEpoch: ev.expiresEpoch,
1079
- height: ev.height,
1080
- feeBps: v11 ? v16 ? FEE_BPS_V16 : FEE_BPS : 0
1081
- };
1082
- offers.set(ev.id, o);
1083
- openOffers.add(ev.id);
1084
- const linked = rec.bid !== void 0 ? bids.get(rec.bid) : void 0;
1085
- if (linked) linked.offers.push(ev.id);
1086
- note(ev, ev.id, "offer", true);
1087
- } else if (rec.t === "bid") {
1088
- if (!v12) {
1089
- note(ev, ev.id, "bid", false, "bids need v1.2");
1090
- continue;
1091
- }
1092
- if (!Number.isSafeInteger(ev.expiresEpoch)) {
1093
- note(ev, ev.id, "bid", false, "expiresEpoch out of safe-integer range");
1094
- continue;
1095
- }
1096
- if ((0, import_csd_codec.epochOf)(ev.height) > ev.expiresEpoch) {
1097
- note(ev, ev.id, "bid", false, "already expired at anchor");
1098
- continue;
1099
- }
1100
- if (ev.height >= V21_HEIGHT && ev.height < V22_HEIGHT && ev.expiresEpoch - (0, import_csd_codec.epochOf)(ev.height) > MAX_OFFER_EPOCHS) {
1101
- note(ev, ev.id, "bid", false, "v2.1: bid duration exceeds the max");
1102
- continue;
1103
- }
1104
- bids.set(ev.id, {
1105
- id: ev.id,
1106
- bidder: who,
1107
- want: rec.want,
1108
- give: rec.give,
1109
- status: "open",
1110
- expiresEpoch: ev.expiresEpoch,
1111
- height: ev.height,
1112
- offers: []
1113
- });
1114
- openBids.add(ev.id);
1115
- note(ev, ev.id, "bid", true);
1116
- } else if (rec.t === "ocancel") {
1117
- if (!v12) {
1118
- note(ev, ev.id, "ocancel", false, "ocancel needs v1.2");
1119
- continue;
1120
- }
1121
- const targets = [];
1122
- for (const o of offers.values()) {
1123
- if (o.status !== "open" || o.seller !== who) continue;
1124
- if (o.taker !== void 0 && o.height >= V28_HEIGHT) continue;
1125
- if (rec.ticker !== void 0 && !(!isNameGive(o.give) && o.give.ticker === rec.ticker)) continue;
1126
- if (rec.name !== void 0 && !(isNameGive(o.give) && o.give.name === rec.name)) continue;
1127
- targets.push(o);
1128
- }
1129
- if (ev.height >= V14_HEIGHT) {
1130
- pendingCancels.push(() => {
1131
- let n = 0;
1132
- for (const o of targets) {
1133
- if (ev.height >= V28_HEIGHT && o.claimTxid !== void 0 && claimHeld(o, ev.height)) continue;
1134
- if (o.status === "open") {
1135
- releaseGive(o);
1136
- setOfferStatus(o, "cancelled");
1137
- n++;
1138
- }
1139
- }
1140
- note(ev, ev.id, "ocancel", true, `${n} cancelled (deferred past same-block fills)`);
1141
- });
1142
- } else {
1143
- for (const o of targets) {
1144
- releaseGive(o);
1145
- setOfferStatus(o, "cancelled");
1146
- }
1147
- note(ev, ev.id, "ocancel", true, `${targets.length} cancelled`);
1148
- }
1149
- } else if (rec.t === "nrenew") {
1150
- if (!v15) {
1151
- note(ev, ev.id, "nrenew", false, "nrenew needs v1.5");
1152
- continue;
1153
- }
1154
- const n = names.get(rec.name);
1155
- const ep = (0, import_csd_codec.epochOf)(ev.height);
1156
- if (n && n.pending) {
1157
- note(ev, ev.id, "nrenew", false, "name reservation not yet finalized");
1158
- continue;
1159
- }
1160
- if (!n || lapsed(n, ep)) {
1161
- note(ev, ev.id, "nrenew", false, "no live lease (lapsed names are claimed, not renewed)");
1162
- continue;
1163
- }
1164
- if (inGrace(n, ep) && who !== n.owner) {
1165
- note(ev, ev.id, "nrenew", false, "grace period: only the owner may renew");
1166
- continue;
1167
- }
1168
- if (feeToTreasury < nameRegFee(rec.name, ev.height)) {
1169
- note(ev, ev.id, "nrenew", false, "renewal fee unpaid");
1170
- continue;
1171
- }
1172
- n.paidThroughEpoch = paidThrough(n) + NAME_TERM_EPOCHS;
1173
- feesPaid += nameRegFee(rec.name, ev.height);
1174
- note(ev, ev.id, "nrenew", true, `paid through epoch ${n.paidThroughEpoch}`);
1175
- } else if (rec.t === "tmeta") {
1176
- if (!v15) {
1177
- note(ev, ev.id, "tmeta", false, "tmeta needs v1.5");
1178
- continue;
1179
- }
1180
- const tok = tokens.get(rec.ticker);
1181
- if (!tok) {
1182
- note(ev, ev.id, "tmeta", false, "unknown ticker");
1183
- continue;
1184
- }
1185
- if (who !== tok.meta.deployer) {
1186
- note(ev, ev.id, "tmeta", false, "issuer-only metadata");
1187
- continue;
1188
- }
1189
- tok.meta.tmeta = rec.hash;
1190
- note(ev, ev.id, "tmeta", true);
1191
- } else if (rec.t === "fclaim") {
1192
- if (ev.height < V28_HEIGHT) {
1193
- note(ev, ev.id, "fclaim", false, "fclaim needs v2.8");
1194
- continue;
1195
- }
1196
- const target = offers.get(rec.offer);
1197
- const E = ev.expiresEpoch;
1198
- const deny = (why) => {
1199
- fclaims.set(ev.id, { offer: rec.offer, proposer: who, expiresEpoch: E, height: ev.height, granted: false });
1200
- note(ev, ev.id, "fclaim", false, why);
1201
- };
1202
- if (!Number.isSafeInteger(E)) {
1203
- deny("expiresEpoch out of safe-integer range");
1204
- continue;
1205
- }
1206
- if (!target) {
1207
- deny("unknown offer");
1208
- continue;
1209
- }
1210
- if (target.status !== "open") {
1211
- deny(`offer ${target.status}`);
1212
- continue;
1213
- }
1214
- if (target.taker) {
1215
- deny("taker-bound offer needs no claim");
1216
- continue;
1217
- }
1218
- if (isTokenWant(target.want)) {
1219
- deny("claims are for CSD-priced offers");
1220
- continue;
1221
- }
1222
- if (E > effExpiry(target, ev.height)) {
1223
- deny("hold would outlive the offer expiry");
1224
- continue;
1225
- }
1226
- if (E > (0, import_csd_codec.epochOf)(ev.height) + FCLAIM_MAX_EPOCH_AHEAD) {
1227
- deny("hold too far ahead (anti-squat)");
1228
- continue;
1229
- }
1230
- if ((0, import_csd_codec.epochOf)(ev.height) > E) {
1231
- deny("expiry already in the past");
1232
- continue;
1233
- }
1234
- if (claimHeld(target, ev.height)) {
1235
- deny("offer already claimed (hold live)");
1236
- continue;
1237
- }
1238
- if (target.claimedBy === who && target.claimUntilHeight !== void 0 && ev.height < target.claimUntilHeight + claimGrace(target) + CLAIM_COOLDOWN_BLOCKS) {
1239
- deny("claim cooldown (you just held this offer)");
1240
- continue;
1241
- }
1242
- let liveN = 0;
1243
- for (const x of offers.values()) if (x.claimedBy === who && claimHeld(x, ev.height) && (ev.height < V29_HEIGHT || x.status === "open")) liveN++;
1244
- if (liveN >= MAX_ACTIVE_CLAIMS) {
1245
- deny(`max ${MAX_ACTIVE_CLAIMS} live claims per address`);
1246
- continue;
1247
- }
1248
- target.claimedBy = who;
1249
- target.claimUntilHeight = (E + 1) * import_csd_codec.EPOCH_LEN;
1250
- target.claimTxid = ev.id;
1251
- fclaims.set(ev.id, { offer: rec.offer, proposer: who, expiresEpoch: E, height: ev.height, granted: true });
1252
- note(ev, ev.id, "fclaim", true);
1253
- }
1254
- } else {
1255
- const who = ev.attester.toLowerCase();
1256
- let o = offers.get(ev.proposalId);
1257
- if (!o && ev.height >= V28_HEIGHT && ev.score === SCORE_FILL) {
1258
- const fc = fclaims.get(ev.proposalId);
1259
- if (fc && fc.granted) {
1260
- const linked = offers.get(fc.offer);
1261
- if (linked && linked.claimTxid === ev.proposalId) o = linked;
1262
- }
1263
- }
1264
- if (!o) {
1265
- if (ev.height >= V28_HEIGHT && ev.score === SCORE_FILL && fclaims.has(ev.proposalId)) {
1266
- note(ev, ev.txid, "fill", false, "fclaim not current (denied or superseded): no delivery, denied-fclaim fill");
1267
- continue;
1268
- }
1269
- const b = bids.get(ev.proposalId);
1270
- if (b && ev.score === SCORE_CANCEL) {
1271
- if (who !== b.bidder) {
1272
- note(ev, ev.txid, "bidcancel", false, "only bidder may cancel");
1273
- continue;
1274
- }
1275
- if (b.status !== "open") {
1276
- note(ev, ev.txid, "bidcancel", false, `bid ${b.status}`);
1277
- continue;
1278
- }
1279
- setBidStatus(b, "cancelled");
1280
- note(ev, ev.txid, "bidcancel", true);
1281
- }
1282
- continue;
1283
- }
1284
- if (ev.score === SCORE_CANCEL) {
1285
- if (who !== o.seller) {
1286
- note(ev, ev.txid, "cancel", false, "only seller may cancel");
1287
- continue;
1288
- }
1289
- if (o.status !== "open") {
1290
- note(ev, ev.txid, "cancel", false, `offer ${o.status}`);
1291
- continue;
1292
- }
1293
- if (o.taker !== void 0 && o.height >= V28_HEIGHT) {
1294
- note(ev, ev.txid, "cancel", false, "v2.8: taker-bound offers are firm quotes (uncancellable)");
1295
- continue;
1296
- }
1297
- if (ev.height >= V14_HEIGHT) {
1298
- pendingCancels.push(() => {
1299
- if (ev.height >= V28_HEIGHT && o.claimTxid !== void 0 && claimHeld(o, ev.height)) {
1300
- note(ev, ev.txid, "cancel", false, "v2.8: frozen (fclaim hold live)");
1301
- return;
1302
- }
1303
- if (o.status === "open") {
1304
- releaseGive(o);
1305
- setOfferStatus(o, "cancelled");
1306
- note(ev, ev.txid, "cancel", true);
1307
- } else note(ev, ev.txid, "cancel", false, "superseded by same-block fill (v1.4)");
1308
- });
1309
- } else {
1310
- releaseGive(o);
1311
- setOfferStatus(o, "cancelled");
1312
- note(ev, ev.txid, "cancel", true);
1313
- }
1314
- } else if (ev.score === SCORE_FILL && isTokenWant(o.want)) {
1315
- if (o.status !== "open") {
1316
- note(ev, ev.txid, "fill", false, `offer ${o.status}`);
1317
- continue;
1318
- }
1319
- if (o.taker && who !== o.taker) {
1320
- note(ev, ev.txid, "fill", false, "taker-bound offer");
1321
- continue;
1322
- }
1323
- if (ev.confidence !== CONF_TOKEN_FILL) {
1324
- note(ev, ev.txid, "fill", false, "token fill requires confidence marker");
1325
- continue;
1326
- }
1327
- if (!tokens.has(o.want.ticker)) {
1328
- note(ev, ev.txid, "fill", false, "want ticker does not exist");
1329
- continue;
1330
- }
1331
- const amt = BigInt(o.want.amount);
1332
- const fee = o.feeBps ? tradeFee(amt, o.feeBps) : 0n;
1333
- const buyer = bal(o.want.ticker, who);
1334
- if (buyer.available < amt + fee) {
1335
- note(ev, ev.txid, "fill", false, "insufficient want-token balance");
1336
- continue;
1337
- }
1338
- const giveName = isNameGive(o.give) ? names.get(o.give.name) : void 0;
1339
- if (isNameGive(o.give) && !giveName) {
1340
- note(ev, ev.txid, "fill", false, "name vanished (consensus violation)");
1341
- continue;
1342
- }
1343
- const giveLock = isNameGive(o.give) ? void 0 : offerLock.get(o.id);
1344
- if (!isNameGive(o.give) && giveLock === void 0) {
1345
- note(ev, ev.txid, "fill", false, "offer lock missing");
1346
- continue;
1347
- }
1348
- buyer.available -= amt + fee;
1349
- bal(o.want.ticker, o.want.payto).available += amt;
1350
- if (fee > 0n) bal(o.want.ticker, TREASURY_ADDR).available += fee;
1351
- if (isNameGive(o.give)) deliverNameToBuyer(giveName, who, ev);
1352
- else releaseGiveLock(o, who, giveLock);
1353
- setOfferStatus(o, "filled");
1354
- o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: amt.toString(), fee: fee.toString() };
1355
- markBidDone(o, who);
1356
- note(ev, ev.txid, "fill", true);
1357
- } else if (ev.score === SCORE_FILL && o.min !== void 0 && !isNameGive(o.give)) {
1358
- if (o.status !== "open") {
1359
- note(ev, ev.txid, "fill", false, `offer ${o.status}`);
1360
- continue;
1361
- }
1362
- if (o.taker && who !== o.taker) {
1363
- note(ev, ev.txid, "fill", false, "taker-bound offer");
1364
- continue;
1365
- }
1366
- const blk = openFillReject(o, ev.height, who, ev.proposalId);
1367
- if (blk) {
1368
- note(ev, ev.txid, "fill", false, blk);
1369
- continue;
1370
- }
1371
- const pt = ev.paidTo ?? {};
1372
- const want = BigInt(o.want.value);
1373
- const paidSoFar = BigInt(o.paid ?? "0");
1374
- const remaining = want - paidSoFar;
1375
- const X = ptAmt(pt[o.want.payto]);
1376
- const minV = BigInt(o.min);
1377
- const effMin = remaining < minV ? remaining : minV;
1378
- if (X < effMin) {
1379
- note(ev, ev.txid, "fill", false, "payment below offer min");
1380
- continue;
1381
- }
1382
- const x = X < remaining ? X : remaining;
1383
- const fee = o.feeBps ? tradeFee(x, o.feeBps) : 0n;
1384
- if (ptAmt(pt[TREASURY_ADDR]) < fee) {
1385
- note(ev, ev.txid, "fill", false, "protocol fee unpaid");
1386
- continue;
1387
- }
1388
- const giveTotal = BigInt(o.give.amount);
1389
- const newPaid = paidSoFar + x;
1390
- const deliveredSoFar = BigInt(o.delivered ?? "0");
1391
- const newDelivered = giveTotal * newPaid / want;
1392
- const out = newDelivered - deliveredSoFar;
1393
- if (out === 0n) {
1394
- note(ev, ev.txid, "fill", false, "fill too small to deliver any tokens");
1395
- continue;
1396
- }
1397
- const lock = offerLock.get(o.id);
1398
- if (lock === void 0) {
1399
- note(ev, ev.txid, "fill", false, "offer lock missing");
1400
- continue;
1401
- }
1402
- bal(o.give.ticker, o.seller).locked -= out;
1403
- bal(o.give.ticker, who).available += out;
1404
- offerLock.set(o.id, lock - out);
1405
- o.paid = newPaid.toString();
1406
- o.delivered = newDelivered.toString();
1407
- const entry = { buyer: who, txid: ev.txid, height: ev.height, paid: x.toString(), fee: fee.toString(), got: out.toString() };
1408
- (o.fills ??= []).push(entry);
1409
- feesPaid += fee;
1410
- if (newPaid === want) {
1411
- setOfferStatus(o, "filled");
1412
- o.fill = entry;
1413
- offerLock.delete(o.id);
1414
- markBidDone(o, who);
1415
- }
1416
- note(ev, ev.txid, "fill", true, `partial ${x}/${want}`);
1417
- } else if (ev.score === SCORE_FILL) {
1418
- if (o.status !== "open") {
1419
- note(ev, ev.txid, "fill", false, `offer ${o.status}`);
1420
- continue;
1421
- }
1422
- if (o.taker && who !== o.taker) {
1423
- note(ev, ev.txid, "fill", false, "taker-bound offer");
1424
- continue;
1425
- }
1426
- const blk = openFillReject(o, ev.height, who, ev.proposalId);
1427
- if (blk) {
1428
- note(ev, ev.txid, "fill", false, blk);
1429
- continue;
1430
- }
1431
- const pt = ev.paidTo ?? {};
1432
- const want = BigInt(o.want.value);
1433
- const fee = o.feeBps ? tradeFee(want, o.feeBps) : 0n;
1434
- const restingLiquidity = o.taker !== void 0 && o.bid !== void 0 || o.height >= V17_HEIGHT && o.taker === void 0;
1435
- const rebate = o.height >= V16_HEIGHT && restingLiquidity ? makerRebate(want) : 0n;
1436
- const need = /* @__PURE__ */ new Map();
1437
- const addNeed = (a, v) => need.set(a, (need.get(a) ?? 0n) + v);
1438
- addNeed(o.want.payto, want);
1439
- addNeed(TREASURY_ADDR, fee);
1440
- if (rebate > 0n) addNeed(o.seller, rebate);
1441
- let unpaid;
1442
- for (const [addr, amt] of need) if (ptAmt(pt[addr]) < amt) {
1443
- unpaid = addr === TREASURY_ADDR ? "protocol fee unpaid" : rebate > 0n && addr === o.seller ? "maker rebate unpaid (v1.6)" : "payment below want.value";
1606
+ switch (rec.t) {
1607
+ case "deploy":
1608
+ applyDeploy(c, ev, rec, who, feeToTreasury);
1609
+ break;
1610
+ case "mint":
1611
+ applyMint(c, ev, rec, who);
1612
+ break;
1613
+ case "transfer":
1614
+ applyTransfer(c, ev, rec, who);
1615
+ break;
1616
+ case "tmeta":
1617
+ applyTmeta(c, ev, rec, who);
1618
+ break;
1619
+ case "ncommit":
1620
+ applyNcommit(c, ev, rec);
1621
+ break;
1622
+ case "name":
1623
+ applyName(c, ev, rec, who, feeToTreasury);
1624
+ break;
1625
+ case "nfinalize":
1626
+ applyNfinalize(c, ev, rec, who, feeToTreasury);
1627
+ break;
1628
+ case "nxfer":
1629
+ applyNxfer(c, ev, rec, who);
1630
+ break;
1631
+ case "nset":
1632
+ applyNset(c, ev, rec, who);
1633
+ break;
1634
+ case "nprofile":
1635
+ applyNprofile(c, ev, rec, who);
1636
+ break;
1637
+ case "nrenew":
1638
+ applyNrenew(c, ev, rec, who, feeToTreasury);
1639
+ break;
1640
+ case "offer":
1641
+ applyOffer(c, ev, rec, who);
1642
+ break;
1643
+ case "bid":
1644
+ applyBid(c, ev, rec, who);
1645
+ break;
1646
+ case "ocancel":
1647
+ applyOcancel(c, ev, rec, who);
1648
+ break;
1649
+ case "fclaim":
1650
+ applyFclaim(c, ev, rec, who);
1444
1651
  break;
1445
- }
1446
- if (unpaid) {
1447
- note(ev, ev.txid, "fill", false, unpaid);
1448
- continue;
1449
- }
1450
- const paid = ptAmt(pt[o.want.payto]);
1451
- if (isNameGive(o.give)) {
1452
- const n = names.get(o.give.name);
1453
- if (!n) {
1454
- note(ev, ev.txid, "fill", false, "name vanished (consensus violation)");
1455
- continue;
1456
- }
1457
- deliverNameToBuyer(n, who, ev);
1458
- } else {
1459
- const amt = offerLock.get(o.id);
1460
- if (amt === void 0) {
1461
- note(ev, ev.txid, "fill", false, "offer lock missing");
1462
- continue;
1463
- }
1464
- releaseGiveLock(o, who, amt);
1465
- }
1466
- feesPaid += fee;
1467
- setOfferStatus(o, "filled");
1468
- o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: paid.toString(), fee: fee.toString() };
1469
- markBidDone(o, who);
1470
- note(ev, ev.txid, "fill", true);
1471
- } else if (ev.height >= V17_HEIGHT && ev.score === SCORE_CLAIM) {
1472
- if (ev.height >= V28_HEIGHT) {
1473
- note(ev, ev.txid, "claim", false, "v2.8: claims are fclaim proposals now");
1474
- continue;
1475
- }
1476
- if (o.status !== "open") {
1477
- note(ev, ev.txid, "claim", false, `offer ${o.status}`);
1478
- continue;
1479
- }
1480
- if (o.taker) {
1481
- note(ev, ev.txid, "claim", false, "taker-bound offer needs no claim");
1482
- continue;
1483
- }
1484
- if (isTokenWant(o.want)) {
1485
- note(ev, ev.txid, "claim", false, "claims are for CSD-priced offers (token offers are no-op-safe)");
1486
- continue;
1487
- }
1488
- if (claimHeld(o, ev.height)) {
1489
- note(ev, ev.txid, "claim", false, "offer already claimed (hold live)");
1490
- continue;
1491
- }
1492
- if (o.claimedBy === who && o.claimUntilHeight !== void 0 && ev.height < o.claimUntilHeight + claimGrace(o) + CLAIM_COOLDOWN_BLOCKS) {
1493
- note(ev, ev.txid, "claim", false, "claim cooldown (you just held this offer)");
1494
- continue;
1495
- }
1496
- let liveN = 0;
1497
- for (const x of offers.values()) if (x.claimedBy === who && claimHeld(x, ev.height) && (ev.height < V29_HEIGHT || x.status === "open")) liveN++;
1498
- if (liveN >= MAX_ACTIVE_CLAIMS) {
1499
- note(ev, ev.txid, "claim", false, `max ${MAX_ACTIVE_CLAIMS} live claims per address`);
1500
- continue;
1501
- }
1502
- o.claimedBy = who;
1503
- o.claimUntilHeight = ev.height + claimWindowAt(ev.height);
1504
- note(ev, ev.txid, "claim", true);
1505
1652
  }
1653
+ } else {
1654
+ applyAttest(c, ev);
1506
1655
  }
1507
1656
  }
1508
1657
  applyPendingCancels();
@@ -1552,7 +1701,7 @@ function resolve(events, tipHeight) {
1552
1701
  for (const [nm, r] of [...recaptures.entries()].sort(([a], [b]) => ord(a, b))) recapturesOut[nm] = { owner: r.owner, effectiveHeight: r.effHeight, finalizeBy: r.finalizeBy };
1553
1702
  const fclaimsOut = {};
1554
1703
  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 };
1555
- return { tipHeight, tokens: tokensOut, balances: balancesOut, names: namesOut, offers: offersOut, bids: bidsOut, recaptures: recapturesOut, fclaims: fclaimsOut, events: log, feesPaid: feesPaid.toString() };
1704
+ return { tipHeight, tokens: tokensOut, balances: balancesOut, names: namesOut, offers: offersOut, bids: bidsOut, recaptures: recapturesOut, fclaims: fclaimsOut, events: log, feesPaid: c.feesPaid.toString() };
1556
1705
  }
1557
1706
  function canonicalState(s) {
1558
1707
  const sortKeys = (v) => {
@@ -1705,8 +1854,9 @@ function finalizeWinnerCheck(nameState, me, commitHeight, tip) {
1705
1854
  if (nameState.pending !== true) return { safe: false, reason: "already registered to you \u2014 no second finalize fee is needed" };
1706
1855
  if (Number(nameState.effectiveHeight) !== Number(commitHeight))
1707
1856
  return { safe: false, reason: "your reservation was displaced (effective height changed) \u2014 a finalize now would burn the fee" };
1708
- if (tip !== void 0 && tip !== null && Number.isFinite(Number(tip))) {
1709
- const t = Number(tip);
1857
+ if (tip !== void 0 && tip !== null) {
1858
+ 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` };
1859
+ const t = tip;
1710
1860
  const eff = Number(nameState.effectiveHeight);
1711
1861
  const freezeEnd = eff + REG_COMMIT_MAX_BLOCKS;
1712
1862
  const closeAt = eff + REG_COMMIT_MAX_BLOCKS + REG_FINALIZE_GRACE_BLOCKS - FINALIZE_TIP_MARGIN;
@@ -1768,15 +1918,17 @@ async function verifyFillSpv(offerId, fclaimTxid, me, io, opts) {
1768
1918
  return no("could not enumerate the offer's events");
1769
1919
  }
1770
1920
  const want = /* @__PURE__ */ new Set([offerId.toLowerCase(), fclaimTxid.toLowerCase(), ...(hintIds ?? []).map((x) => String(x).toLowerCase())]);
1921
+ 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`);
1771
1922
  const proven = [];
1772
1923
  for (const wid of want) {
1773
1924
  let ev;
1774
1925
  try {
1775
1926
  ev = await io.provenEvent(wid);
1776
1927
  } catch {
1777
- ev = null;
1928
+ return unproven(wid);
1778
1929
  }
1779
- if (ev && (ev.kind === "propose" ? ev.id : ev.txid).toLowerCase() === wid) proven.push(ev);
1930
+ if (!ev || (ev.kind === "propose" ? ev.id : ev.txid).toLowerCase() !== wid) return unproven(wid);
1931
+ proven.push(ev);
1780
1932
  }
1781
1933
  const isProp = (e) => e.kind === "propose";
1782
1934
  const offerEv = proven.find((e) => isProp(e) && e.id.toLowerCase() === offerId.toLowerCase());
@@ -1855,7 +2007,9 @@ function provenOfferTerms(offerRec, provenHeight) {
1855
2007
  giveTicker: g.ticker !== void 0 ? String(g.ticker) : void 0,
1856
2008
  giveAmount: g.amount !== void 0 ? String(g.amount) : void 0,
1857
2009
  giveName: g.name !== void 0 ? String(g.name) : void 0,
1858
- wantType: isTokenWant(offerRec.want) ? "token" : "csd"
2010
+ wantType: isTokenWant(offerRec.want) ? "token" : "csd",
2011
+ wantTicker: isTokenWant(offerRec.want) ? String(w.ticker) : void 0,
2012
+ wantAmount: isTokenWant(offerRec.want) ? String(w.amount) : void 0
1859
2013
  };
1860
2014
  }
1861
2015
  function bindOfferTerms(servedOffer, t, opts) {
@@ -1870,7 +2024,8 @@ function bindOfferTerms(servedOffer, t, opts) {
1870
2024
  if ((om !== void 0 && om !== null) !== (t.min !== void 0)) return true;
1871
2025
  if (t.min !== void 0 && String(om) !== t.min) return true;
1872
2026
  if (opts?.wantType !== false) {
1873
- if (t.wantType === void 0 || typeof o?.want?.ticker === "string" !== (t.wantType === "token")) return true;
2027
+ if (t.wantType === void 0) return true;
2028
+ if (t.wantType === "token" ? String(o?.want?.ticker) !== t.wantTicker || String(o?.want?.amount) !== t.wantAmount : typeof o?.want?.ticker === "string") return true;
1874
2029
  }
1875
2030
  if (opts?.give !== false) {
1876
2031
  const g = o?.give;
@@ -1944,6 +2099,34 @@ function myProvenFillClosedOffer(fill, fclaim2, offerEv, me, grantHeight) {
1944
2099
  return need.every((leg) => ptAmt(fill.paidTo?.[lc(leg.to)]) >= leg.value);
1945
2100
  }
1946
2101
 
2102
+ // src/holdcount.ts
2103
+ var lastLegacyClaimEnd = V28_HEIGHT - 1 + claimWindowAt(V28_HEIGHT - 1);
2104
+ var LEGACY_HOLD_SUNSET_HEIGHT = lastLegacyClaimEnd + claimGraceOf(lastLegacyClaimEnd);
2105
+ function countOtherHoldsAtGrant(candidates, target, me, closed = /* @__PURE__ */ new Set()) {
2106
+ if (!(Number.isSafeInteger(target.height) && target.height >= LEGACY_HOLD_SUNSET_HEIGHT))
2107
+ 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` };
2108
+ const meL = String(me).toLowerCase(), tid = String(target.id).toLowerCase(), toffer = String(target.offer).toLowerCase();
2109
+ const offers = /* @__PURE__ */ new Set();
2110
+ for (const c of candidates) {
2111
+ const cid = String(c.id).toLowerCase();
2112
+ if (cid === tid || closed.has(cid) || String(c.proposer).toLowerCase() !== meL) continue;
2113
+ if (!(c.height < target.height || c.height === target.height && c.pos < target.pos)) continue;
2114
+ if (!(fclaimHoldEnd(Number(c.expiresEpoch)) >= target.height)) continue;
2115
+ const rec = parseRecord(String(c.uri), String(c.payloadHash));
2116
+ if (!rec || rec.t !== "fclaim") continue;
2117
+ const offer2 = String(rec.offer).toLowerCase();
2118
+ if (offer2 !== toffer) offers.add(offer2);
2119
+ }
2120
+ return { ok: true, count: offers.size };
2121
+ }
2122
+
2123
+ // src/admission.ts
2124
+ function provenOfferRefusal(rec, tx) {
2125
+ if (tx.domain !== DOMAIN) return `not a ${DOMAIN} Propose (domain ${JSON.stringify(String(tx.domain))})`;
2126
+ const ee = typeof tx.expiresEpoch === "bigint" ? Number(tx.expiresEpoch) : tx.expiresEpoch;
2127
+ return offerEnvelopeRefusal(rec, String(tx.seller).toLowerCase(), tx.height, ee);
2128
+ }
2129
+
1947
2130
  // src/index.ts
1948
2131
  var import_csd_codec5 = require("@inversealtruism/csd-codec");
1949
2132
  // Annotate the CommonJS export names for ESM import in node:
@@ -1977,12 +2160,14 @@ var import_csd_codec5 = require("@inversealtruism/csd-codec");
1977
2160
  HALVING_INTERVAL,
1978
2161
  HASH_RE,
1979
2162
  INITIAL_REWARD,
2163
+ LEGACY_HOLD_SUNSET_HEIGHT,
1980
2164
  MAX_ACTIVE_CLAIMS,
1981
2165
  MAX_AMOUNT,
1982
2166
  MAX_OFFER_EPOCHS,
1983
2167
  MAX_PENDING_REG,
1984
2168
  MAX_RECORD_BYTES,
1985
2169
  MAX_SCAN,
2170
+ MAX_TOKEN_DECIMALS,
1986
2171
  MINT_KEYS,
1987
2172
  MIN_FEE_ATTEST,
1988
2173
  MIN_FEE_PROPOSE,
@@ -2049,6 +2234,7 @@ var import_csd_codec5 = require("@inversealtruism/csd-codec");
2049
2234
  claimGraceOf,
2050
2235
  claimWindowAt,
2051
2236
  claimWindowOf,
2237
+ countOtherHoldsAtGrant,
2052
2238
  deploy,
2053
2239
  epochOf,
2054
2240
  expiredClaimFee,
@@ -2088,6 +2274,7 @@ var import_csd_codec5 = require("@inversealtruism/csd-codec");
2088
2274
  pickPrimaryName,
2089
2275
  previewFill,
2090
2276
  primaryRankBefore,
2277
+ provenOfferRefusal,
2091
2278
  provenOfferTerms,
2092
2279
  ptAmt,
2093
2280
  replayLiveHold,